summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore205
-rw-r--r--README17
-rw-r--r--dist/gdb/Makefile.linux8
-rw-r--r--dist/gdb/Makefile.mingw7
-rw-r--r--dist/gdb/Makefile.osx10
-rw-r--r--dist/gdb/patches/gdb-ipv6.patch128
-rw-r--r--doc/api/coding-style.qdoc5
-rw-r--r--doc/api/plugin-specifications.qdoc14
-rw-r--r--doc/src/debugger/creator-debugger.qdoc44
-rw-r--r--doc/src/editors/creator-coding-edit-mode.qdoc14
-rw-r--r--doc/src/editors/creator-editors.qdoc22
-rw-r--r--doc/src/howto/creator-cli.qdoc6
-rw-r--r--doc/src/howto/creator-vcs.qdoc1
-rw-r--r--doc/src/qtquick/qtquick-creating.qdoc2
-rw-r--r--doc/templates/style/offline.css5
-rw-r--r--lib/qtcreator/qtcomponents/qtcomponents.qbs82
-rw-r--r--qbs/defaults.js17
-rw-r--r--qbs/pluginspec/pluginspec.qbs15
-rw-r--r--qtcreator.pri5
-rw-r--r--qtcreator.qbs36
-rw-r--r--share/qtcreator/dumper/bridge.py109
-rw-r--r--share/qtcreator/dumper/dumper.cpp8
-rw-r--r--share/qtcreator/dumper/dumper.py223
-rw-r--r--share/qtcreator/dumper/qttypes.py223
-rw-r--r--share/qtcreator/qml/qmldump/main.cpp4
-rw-r--r--share/qtcreator/qml/qmlobserver/main.cpp37
-rw-r--r--share/qtcreator/qml/qmlobserver/qmlruntime.cpp22
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/commands.pri7
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.cpp74
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.h69
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.cpp48
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.h (renamed from src/plugins/qmldesigner/extrasplugin/extrasplugin.h)27
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.cpp76
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.h66
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/tokencommand.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/tokencommand.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.cpp87
-rw-r--r--share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.h5
-rw-r--r--share/qtcreator/qml/qmlpuppet/container/imagecontainer.cpp175
-rw-r--r--share/qtcreator/qml/qmlpuppet/container/imagecontainer.h8
-rw-r--r--share/qtcreator/qml/qmlpuppet/container/instancecontainer.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/container/reparentcontainer.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/container/reparentcontainer.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/instances/instances.pri30
-rw-r--r--share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.cpp26
-rw-r--r--share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.h6
-rw-r--r--share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceclientinterface.h3
-rw-r--r--share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.cpp13
-rw-r--r--share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.h2
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/anchorchangesnodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.h74
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.cpp92
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/behaviornodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/childrenchangeeventfilter.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/childrenchangeeventfilter.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/childrenchangeeventfilter.h (renamed from share/qtcreator/qml/qmlpuppet/instances/childrenchangeeventfilter.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.cpp93
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.h62
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummycontextobject.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/dummycontextobject.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummycontextobject.h (renamed from src/plugins/qmldesigner/customstyleplugin/customstyleplugin.h)30
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummynodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/dummynodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummynodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/dummynodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/instances.pri50
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.cpp359
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.h107
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.cpp1177
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.h230
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.cpp124
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.h (renamed from share/qtcreator/qml/qmlpuppet/instances/nodeinstancesignalspy.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.cpp1180
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.h209
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.cpp97
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.h67
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.cpp118
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.h75
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.cpp138
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.h75
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.cpp76
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.h62
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp16
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceclientproxy.cpp3
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.cpp56
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.h12
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.cpp27
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.cpp49
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.h2
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/quickitemnodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.cpp)310
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/quickitemnodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.h)32
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.cpp639
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.h216
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri34
-rw-r--r--share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pro37
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.cpp84
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/anchorchangesnodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/behaviornodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.h62
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.cpp58
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.h (renamed from src/plugins/qmldesigner/meegoplugin/meegoplugin.h)28
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/componentnodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/componentnodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/componentnodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/componentnodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummycontextobject.cpp (renamed from src/plugins/qmldesigner/customstyleplugin/customstyleplugin.cpp)26
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummycontextobject.h (renamed from share/qtcreator/qml/qmlpuppet/instances/dummycontextobject.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.cpp108
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.h72
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/instances.pri28
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancemetaobject.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/nodeinstancemetaobject.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancemetaobject.h (renamed from share/qtcreator/qml/qmlpuppet/instances/nodeinstancemetaobject.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstanceserver.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/nodeinstanceserver.cpp)13
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstanceserver.h (renamed from share/qtcreator/qml/qmlpuppet/instances/nodeinstanceserver.h)5
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/nodeinstancesignalspy.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.h66
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/objectnodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/objectnodeinstance.cpp)2
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/objectnodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/objectnodeinstance.h)2
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/positionernodeinstance.cpp2
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlpropertychangesnodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/qmlpropertychangesnodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlpropertychangesnodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/qmlpropertychangesnodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlstatenodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/qmlstatenodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlstatenodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/qmlstatenodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmltransitionnodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/qmltransitionnodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmltransitionnodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/qmltransitionnodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.cpp9
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.cpp11
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.cpp7
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.h1
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/servernodeinstance.cpp (renamed from share/qtcreator/qml/qmlpuppet/instances/servernodeinstance.cpp)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/servernodeinstance.h (renamed from share/qtcreator/qml/qmlpuppet/instances/servernodeinstance.h)0
-rw-r--r--share/qtcreator/qml/qmlpuppet/qmlpuppet/qmlpuppet.pri3
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AlignmentHorizontalButtons.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/AlignmentHorizontalButtons.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AlignmentVerticalButtons.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/AlignmentVerticalButtons.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AnchorBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/AnchorBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AnchorButtons.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/AnchorButtons.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/CheckBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/CheckBox.qml)2
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ColorGroupBox.qml)9
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLabel.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ColorLabel.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLineEdit.qml161
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorScheme.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ColorScheme.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorTypeButtons.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ColorTypeButtons.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ComboBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ComboBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/DoubleSpinBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/DoubleSpinBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/DoubleSpinBoxAlternate.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/DoubleSpinBoxAlternate.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExpressionEditor.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ExpressionEditor.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Extended.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Extended.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedFunctionButton.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedFunctionButton.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedPane.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedPane.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedSwitches.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedSwitches.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FlagedButton.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FlagedButton.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontComboBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FontComboBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FontGroupBox.qml)33
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontStyleButtons.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FontStyleButtons.qml)38
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Geometry.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Geometry.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/GroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/GroupBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/GroupBoxOption.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/GroupBoxOption.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/HorizontalLayout.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/HorizontalLayout.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/HorizontalWhiteLine.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/HorizontalWhiteLine.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/IntEditor.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/IntEditor.qml)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Label.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Label.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Layout.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Layout.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/LayoutPane.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/LayoutPane.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/LineEdit.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/LineEdit.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Modifiers.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Modifiers.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/PlaceHolder.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/PlaceHolder.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/PropertyFrame.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/PropertyFrame.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ScrollArea.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ScrollArea.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/SliderWidget.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/SliderWidget.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/SpinBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/SpinBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/StandardTextColorGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/StandardTextColorGroupBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/StandardTextGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/StandardTextGroupBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Switches.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Switches.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/TextEditor.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/TextEditor.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/TextInputGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/TextInputGroupBox.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Transformation.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Transformation.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Type.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Type.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/UrlEdit.qml57
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/VerticalLayout.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/VerticalLayout.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Visibility.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/Visibility.qml)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorbottom.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorbottom.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorbox.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorbox.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorfill.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorfill.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorhorizontal.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorhorizontal.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorleft.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorleft.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorright.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorright.css)6
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorspacer.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorspacer.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchortop.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchortop.css)10
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorvertical.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/anchorvertical.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/applybutton.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/applybutton.css)2
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/aspectlock.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/aspectlock.css)6
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/cancelbutton.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/cancelbutton.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/checkbox_tr.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/checkbox_tr.css)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentbottom-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentbottom-h-icon.png)bin207 -> 207 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentbottom-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentbottom-icon.png)bin207 -> 207 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentcenterh-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentcenterh-h-icon.png)bin337 -> 337 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentcenterh-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentcenterh-icon.png)bin295 -> 295 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentleft-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentleft-h-icon.png)bin217 -> 217 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentleft-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentleft-icon.png)bin216 -> 216 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentmiddle-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentmiddle-h-icon.png)bin206 -> 206 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentmiddle-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentmiddle-icon.png)bin207 -> 207 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentright-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentright-h-icon.png)bin338 -> 338 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentright-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentright-icon.png)bin313 -> 313 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmenttop-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmenttop-h-icon.png)bin221 -> 221 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmenttop-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmenttop-icon.png)bin221 -> 221 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/apply.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/apply.png)bin646 -> 646 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/behaivour.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/behaivour.png)bin425 -> 425 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/blended-image-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/blended-image-icon.png)bin340 -> 340 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/bold-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/bold-h-icon.png)bin447 -> 447 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/bold-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/bold-icon.png)bin434 -> 434 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/button.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/button.png)bin687 -> 687 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/cancel.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/cancel.png)bin749 -> 749 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/default-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/default-icon.png)bin341 -> 341 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/downArrow.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/downArrow.png)bin855 -> 855 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/expression.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/expression.png)bin517 -> 517 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/extended.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/extended.png)bin293 -> 293 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/grid-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/grid-icon.png)bin369 -> 369 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_gradient.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_gradient.png)bin157 -> 157 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_none.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_none.png)bin310 -> 310 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_solid.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_solid.png)bin135 -> 135 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/image-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/image-icon.png)bin292 -> 292 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/italic-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/italic-h-icon.png)bin382 -> 382 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/italic-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/italic-icon.png)bin368 -> 368 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/item-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/item-icon.png)bin293 -> 293 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/layout.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/layout.png)bin369 -> 369 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/leftArrow.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/leftArrow.png)bin885 -> 885 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/list-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/list-icon.png)bin424 -> 424 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/mouse-area-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/mouse-area-icon.png)bin511 -> 511 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/placeholder.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/placeholder.png)bin213 -> 213 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/rect-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/rect-icon.png)bin237 -> 237 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/reset-button.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/reset-button.png)bin741 -> 741 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/rightArrow.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/rightArrow.png)bin871 -> 871 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/standard.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/standard.png)bin340 -> 340 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/strikeout-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/strikeout-h-icon.png)bin514 -> 514 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/strikeout-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/strikeout-icon.png)bin494 -> 494 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/submenu.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/submenu.png)bin389 -> 389 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/text-edit-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/text-edit-icon.png)bin368 -> 368 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/text-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/text-icon.png)bin582 -> 582 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/underline-h-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/underline-h-icon.png)bin367 -> 367 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/underline-icon.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/underline-icon.png)bin359 -> 359 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/upArrow.png (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/images/upArrow.png)bin849 -> 849 bytes
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/layoutWidget.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/layoutWidget.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/propertyEditor.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/propertyEditor.css)42
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/qmldir48
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/specialCheckBox.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/specialCheckBox.css)3
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonleft.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonleft.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonmiddle.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonmiddle.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonright.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonright.css)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/switch.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/switch.css)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/typeLabel.css (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/typeLabel.css)0
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/BooleanEditorTemplate.template14
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/ColorEditorTemplate.template5
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/IntEditorTemplate.template6
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/RealEditorTemplate.template5
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/StringEditorTemplate.template12
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/TemplateTypes.qml29
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/UrlEditorTemplate.template12
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/BorderImageSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/BorderImageSpecifics.qml)3
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlickableGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FlickableGroupBox.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlickableSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FlickableSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlipableSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FlipableSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlowSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/FlowSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/GridSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/GridSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/GridViewSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/GridViewSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/ImageSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ImageSpecifics.qml)3
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/ItemPane.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ItemPane.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/ListViewSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/ListViewSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/MouseAreaSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/MouseAreaSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/PathViewSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/PathViewSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/RectangleColorGroupBox.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/RectangleColorGroupBox.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/RectangleSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/RectangleSpecifics.qml)4
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/RowSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/RowSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextEditSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/TextEditSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextInputSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/TextInputSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextSpecifics.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/TextSpecifics.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtQuick/emptyPane.qml (renamed from share/qtcreator/qmldesigner/propertyeditor/Qt/emptyPane.qml)1
-rw-r--r--share/qtcreator/qmldesigner/propertyeditor/QtWebKit/WebViewSpecifics.qml2
-rwxr-xr-xshare/qtcreator/scripts/openTerminal.command21
-rw-r--r--share/qtcreator/templates/qml/qtquick1_1/main.qml17
-rw-r--r--share/qtcreator/templates/qml/qtquick1_1/main.qmlproject21
-rw-r--r--share/qtcreator/templates/qml/qtquick1_1/template.pngbin0 -> 427 bytes
-rw-r--r--share/qtcreator/templates/qml/qtquick1_1/template.xml13
-rw-r--r--share/qtcreator/templates/qml/qtquick2/main.qml17
-rw-r--r--share/qtcreator/templates/qml/qtquick2/main.qmlproject21
-rw-r--r--share/qtcreator/templates/qml/qtquick2/template.pngbin0 -> 427 bytes
-rw-r--r--share/qtcreator/templates/qml/qtquick2/template.xml13
-rw-r--r--share/qtcreator/templates/qtquick2app/qtquick2applicationviewer/qtquick2applicationviewer.cpp6
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/assets/SecondPage.qml24
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/assets/main.qml37
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/bar-descriptor.xml17
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/icon.pngbin0 -> 1364 bytes
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/main.cpp13
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/project.cpp14
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/project.hpp16
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/project.pro18
-rw-r--r--share/qtcreator/templates/wizards/bb-cascades-app/wizard.xml49
-rw-r--r--share/qtcreator/templates/wizards/bb-qt5-guiapp/wizard.xml4
-rw-r--r--share/qtcreator/templates/wizards/bb-qt5-quick2app/wizard.xml2
-rw-r--r--share/qtcreator/templates/wizards/codesnippet/main.cpp1
-rw-r--r--share/qtcreator/templates/wizards/codesnippet/project.pro15
-rw-r--r--share/qtcreator/templates/wizards/codesnippet/wizard.xml76
-rw-r--r--share/qtcreator/translations/translations.qbs7
-rw-r--r--share/share.qbs1388
-rwxr-xr-xshare/update-share-qbs.py87
-rw-r--r--src/app/app.pro5
-rw-r--r--src/app/main.cpp13
-rw-r--r--src/libs/3rdparty/botan/botan.cpp41
-rw-r--r--src/libs/3rdparty/botan/botan.h20
-rw-r--r--src/libs/3rdparty/botan/botan.pri2
-rw-r--r--src/libs/3rdparty/cplusplus/AST.cpp180
-rw-r--r--src/libs/3rdparty/cplusplus/AST.h145
-rw-r--r--src/libs/3rdparty/cplusplus/ASTClone.cpp72
-rw-r--r--src/libs/3rdparty/cplusplus/ASTMatch0.cpp26
-rw-r--r--src/libs/3rdparty/cplusplus/ASTMatcher.cpp116
-rw-r--r--src/libs/3rdparty/cplusplus/ASTMatcher.h5
-rw-r--r--src/libs/3rdparty/cplusplus/ASTPatternBuilder.h134
-rw-r--r--src/libs/3rdparty/cplusplus/ASTVisit.cpp37
-rw-r--r--src/libs/3rdparty/cplusplus/ASTVisitor.h10
-rw-r--r--src/libs/3rdparty/cplusplus/ASTfwd.h5
-rw-r--r--src/libs/3rdparty/cplusplus/Bind.cpp82
-rw-r--r--src/libs/3rdparty/cplusplus/Bind.h7
-rw-r--r--src/libs/3rdparty/cplusplus/Control.cpp23
-rw-r--r--src/libs/3rdparty/cplusplus/Control.h1
-rw-r--r--src/libs/3rdparty/cplusplus/Keywords.cpp20
-rw-r--r--src/libs/3rdparty/cplusplus/Literals.cpp3
-rw-r--r--src/libs/3rdparty/cplusplus/Names.cpp21
-rw-r--r--src/libs/3rdparty/cplusplus/Names.h18
-rw-r--r--src/libs/3rdparty/cplusplus/Parser.cpp371
-rw-r--r--src/libs/3rdparty/cplusplus/Parser.h10
-rw-r--r--src/libs/3rdparty/cplusplus/Symbol.cpp2
-rw-r--r--src/libs/3rdparty/cplusplus/Symbols.cpp49
-rw-r--r--src/libs/3rdparty/cplusplus/Symbols.h10
-rw-r--r--src/libs/3rdparty/cplusplus/Templates.cpp11
-rw-r--r--src/libs/3rdparty/cplusplus/Templates.h2
-rw-r--r--src/libs/3rdparty/cplusplus/Token.cpp2
-rw-r--r--src/libs/3rdparty/cplusplus/Token.h4
-rw-r--r--src/libs/3rdparty/cplusplus/TranslationUnit.cpp36
-rw-r--r--src/libs/3rdparty/cplusplus/TranslationUnit.h5
-rw-r--r--src/libs/QtcLibrary.qbs28
-rw-r--r--src/libs/aggregation/aggregation.qbs11
-rw-r--r--src/libs/cplusplus/AlreadyConsideredClassContainer.h45
-rw-r--r--src/libs/cplusplus/CppDocument.cpp15
-rw-r--r--src/libs/cplusplus/CppDocument.h12
-rw-r--r--src/libs/cplusplus/CppRewriter.cpp25
-rw-r--r--src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp15
-rw-r--r--src/libs/cplusplus/Dumpers.cpp42
-rw-r--r--src/libs/cplusplus/ExpressionUnderCursor.cpp7
-rw-r--r--src/libs/cplusplus/FastPreprocessor.cpp12
-rw-r--r--src/libs/cplusplus/FastPreprocessor.h1
-rw-r--r--src/libs/cplusplus/FindUsages.cpp52
-rw-r--r--src/libs/cplusplus/FindUsages.h6
-rw-r--r--src/libs/cplusplus/Icons.cpp16
-rw-r--r--src/libs/cplusplus/LookupContext.cpp241
-rw-r--r--src/libs/cplusplus/LookupContext.h90
-rw-r--r--src/libs/cplusplus/NamePrettyPrinter.cpp4
-rw-r--r--src/libs/cplusplus/Overview.cpp100
-rw-r--r--src/libs/cplusplus/Overview.h100
-rw-r--r--src/libs/cplusplus/OverviewModel.cpp3
-rw-r--r--src/libs/cplusplus/PPToken.h2
-rw-r--r--src/libs/cplusplus/PreprocessorClient.h6
-rw-r--r--src/libs/cplusplus/ResolveExpression.cpp138
-rw-r--r--src/libs/cplusplus/ResolveExpression.h3
-rw-r--r--src/libs/cplusplus/SimpleLexer.cpp3
-rw-r--r--src/libs/cplusplus/TypeOfExpression.cpp2
-rw-r--r--src/libs/cplusplus/TypeOfExpression.h2
-rw-r--r--src/libs/cplusplus/TypePrettyPrinter.cpp179
-rw-r--r--src/libs/cplusplus/TypePrettyPrinter.h29
-rw-r--r--src/libs/cplusplus/cplusplus-lib.pri3
-rw-r--r--src/libs/cplusplus/cplusplus.qbs79
-rw-r--r--src/libs/cplusplus/pp-engine.cpp265
-rw-r--r--src/libs/cplusplus/pp-engine.h69
-rw-r--r--src/libs/extensionsystem/extensionsystem.qbs14
-rw-r--r--src/libs/extensionsystem/invoker.cpp10
-rw-r--r--src/libs/extensionsystem/invoker.h2
-rw-r--r--src/libs/extensionsystem/optionsparser.cpp29
-rw-r--r--src/libs/extensionsystem/pluginerroroverview.cpp41
-rw-r--r--src/libs/extensionsystem/pluginerroroverview.h15
-rw-r--r--src/libs/extensionsystem/pluginmanager.cpp97
-rw-r--r--src/libs/extensionsystem/pluginmanager_p.h19
-rw-r--r--src/libs/extensionsystem/pluginspec.cpp102
-rw-r--r--src/libs/extensionsystem/pluginspec_p.h1
-rw-r--r--src/libs/extensionsystem/pluginview.cpp4
-rw-r--r--src/libs/glsl/glsl.g4
-rw-r--r--src/libs/glsl/glsl.pro4
-rw-r--r--src/libs/glsl/glsl.qbs48
-rw-r--r--src/libs/glsl/glslparser.cpp4
-rw-r--r--src/libs/glsl/glslsemantic.cpp37
-rw-r--r--src/libs/glsl/glsltypes.cpp4
-rw-r--r--src/libs/languageutils/componentversion.cpp2
-rw-r--r--src/libs/languageutils/languageutils.qbs12
-rw-r--r--src/libs/qmldebug/declarativetoolsclient.cpp23
-rw-r--r--src/libs/qmldebug/qmldebug.qbs21
-rw-r--r--src/libs/qmldebug/qmldebugclient.cpp5
-rw-r--r--src/libs/qmldebug/qmlprofilertraceclient.cpp6
-rw-r--r--src/libs/qmldebug/qmltoolsclient.cpp12
-rw-r--r--src/libs/qmldebug/qpacketprotocol.cpp2
-rw-r--r--src/libs/qmldebug/qv8profilerclient.cpp8
-rw-r--r--src/libs/qmleditorwidgets/colorbox.cpp2
-rw-r--r--src/libs/qmleditorwidgets/colorbox.h2
-rw-r--r--src/libs/qmleditorwidgets/colorbutton.cpp8
-rw-r--r--src/libs/qmleditorwidgets/colorbutton.h15
-rw-r--r--src/libs/qmleditorwidgets/colorwidgets.h2
-rw-r--r--src/libs/qmleditorwidgets/contextpanetextwidget.cpp35
-rw-r--r--src/libs/qmleditorwidgets/contextpanetextwidget.h2
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidget.cpp74
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidget.h12
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetimage.cpp120
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetimage.h12
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp29
-rw-r--r--src/libs/qmleditorwidgets/contextpanewidgetrectangle.h2
-rw-r--r--src/libs/qmleditorwidgets/customcolordialog.cpp34
-rw-r--r--src/libs/qmleditorwidgets/customcolordialog.h2
-rw-r--r--src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp31
-rw-r--r--src/libs/qmleditorwidgets/easingpane/easinggraph.cpp26
-rw-r--r--src/libs/qmleditorwidgets/filewidget.cpp10
-rw-r--r--src/libs/qmleditorwidgets/filewidget.h2
-rw-r--r--src/libs/qmleditorwidgets/fontsizespinbox.cpp14
-rw-r--r--src/libs/qmleditorwidgets/fontsizespinbox.h2
-rw-r--r--src/libs/qmleditorwidgets/gradientline.cpp2
-rw-r--r--src/libs/qmleditorwidgets/gradientline.h2
-rw-r--r--src/libs/qmleditorwidgets/huecontrol.h2
-rw-r--r--src/libs/qmleditorwidgets/qmleditorwidgets.pro1
-rw-r--r--src/libs/qmleditorwidgets/qmleditorwidgets.qbs68
-rw-r--r--src/libs/qmljs/consoleitem.cpp152
-rw-r--r--src/libs/qmljs/consoleitem.h (renamed from src/plugins/remotelinux/deployablefile.h)75
-rw-r--r--src/libs/qmljs/consolemanagerinterface.cpp (renamed from src/plugins/qmldesigner/extrasplugin/extrasplugin.cpp)28
-rw-r--r--src/libs/qmljs/consolemanagerinterface.h64
-rw-r--r--src/libs/qmljs/iscriptevaluator.h (renamed from tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/QmlComponent02.qml)29
-rwxr-xr-xsrc/libs/qmljs/parser/gen-parser.sh12
-rw-r--r--src/libs/qmljs/parser/parser.patch277
-rw-r--r--src/libs/qmljs/parser/parser.pri3
-rw-r--r--src/libs/qmljs/parser/qmldirparser.cpp32
-rw-r--r--src/libs/qmljs/parser/qmldirparser_p.h2
-rw-r--r--src/libs/qmljs/parser/qmlerror.cpp39
-rw-r--r--src/libs/qmljs/parser/qmljs.g95
-rw-r--r--src/libs/qmljs/parser/qmljsgrammar.cpp1610
-rw-r--r--src/libs/qmljs/parser/qmljsgrammar_p.h41
-rw-r--r--src/libs/qmljs/parser/qmljskeywords_p.h76
-rw-r--r--src/libs/qmljs/parser/qmljslexer.cpp77
-rw-r--r--src/libs/qmljs/parser/qmljslexer_p.h5
-rw-r--r--src/libs/qmljs/parser/qmljsparser.cpp106
-rw-r--r--src/libs/qmljs/parser/qmljsparser_p.h9
-rw-r--r--src/libs/qmljs/persistenttrie.cpp631
-rw-r--r--src/libs/qmljs/persistenttrie.h127
-rw-r--r--src/libs/qmljs/qmljs-lib.pri13
-rw-r--r--src/libs/qmljs/qmljs.qbs25
-rw-r--r--src/libs/qmljs/qmljscheck.cpp184
-rw-r--r--src/libs/qmljs/qmljscheck.h1
-rw-r--r--src/libs/qmljs/qmljscodeformatter.cpp47
-rw-r--r--src/libs/qmljs/qmljscodeformatter.h1
-rw-r--r--src/libs/qmljs/qmljscompletioncontextfinder.cpp3
-rw-r--r--src/libs/qmljs/qmljsdelta.cpp33
-rw-r--r--src/libs/qmljs/qmljsdocument.cpp32
-rw-r--r--src/libs/qmljs/qmljsdocument.h15
-rw-r--r--src/libs/qmljs/qmljsevaluate.cpp12
-rw-r--r--src/libs/qmljs/qmljsicons.cpp6
-rw-r--r--src/libs/qmljs/qmljsindenter.cpp26
-rw-r--r--src/libs/qmljs/qmljsinterpreter.cpp72
-rw-r--r--src/libs/qmljs/qmljsinterpreter.h2
-rw-r--r--src/libs/qmljs/qmljslineinfo.cpp9
-rw-r--r--src/libs/qmljs/qmljslink.cpp17
-rw-r--r--src/libs/qmljs/qmljspropertyreader.cpp20
-rw-r--r--src/libs/qmljs/qmljsreformatter.cpp42
-rw-r--r--src/libs/qmljs/qmljsrewriter.cpp25
-rw-r--r--src/libs/qmljs/qmljsscopeastpath.cpp7
-rw-r--r--src/libs/qmljs/qmljsscopebuilder.cpp16
-rw-r--r--src/libs/qmljs/qmljssimplereader.cpp346
-rw-r--r--src/libs/qmljs/qmljssimplereader.h134
-rw-r--r--src/libs/qmljs/qmljsstaticanalysismessage.cpp17
-rw-r--r--src/libs/qmljs/qmljsstaticanalysismessage.h5
-rw-r--r--src/libs/qmljs/qmljstypedescriptionreader.cpp201
-rw-r--r--src/libs/qmljs/qmljsvalueowner.cpp570
-rw-r--r--src/libs/qtcomponents/styleitem/qdeclarativefolderlistmodel.cpp2
-rw-r--r--src/libs/qtcomponents/styleitem/qstyleitem.cpp178
-rw-r--r--src/libs/qtcomponents/styleitem/qstyleplugin.cpp6
-rw-r--r--src/libs/qtcomponents/styleitem/qwheelarea.cpp10
-rw-r--r--src/libs/qtcomponents/styleitem/styleitem.qbs13
-rw-r--r--src/libs/qtcreatorcdbext/containers.cpp15
-rw-r--r--src/libs/qtcreatorcdbext/extensioncontext.cpp28
-rw-r--r--src/libs/qtcreatorcdbext/extensioncontext.h16
-rw-r--r--src/libs/qtcreatorcdbext/gdbmihelpers.cpp27
-rw-r--r--src/libs/qtcreatorcdbext/gdbmihelpers.h2
-rw-r--r--src/libs/qtcreatorcdbext/knowntype.h3
-rw-r--r--src/libs/qtcreatorcdbext/qtcreatorcdbext.def1
-rw-r--r--src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp126
-rw-r--r--src/libs/qtcreatorcdbext/stringutils.cpp54
-rw-r--r--src/libs/qtcreatorcdbext/stringutils.h36
-rw-r--r--src/libs/qtcreatorcdbext/symbolgroup.cpp5
-rw-r--r--src/libs/qtcreatorcdbext/symbolgroupnode.cpp76
-rw-r--r--src/libs/qtcreatorcdbext/symbolgroupnode.h6
-rw-r--r--src/libs/qtcreatorcdbext/symbolgroupvalue.cpp273
-rw-r--r--src/libs/qtcreatorcdbext/symbolgroupvalue.h7
-rw-r--r--src/libs/ssh/sftpchannel_p.h11
-rw-r--r--src/libs/ssh/sftpoutgoingpacket.cpp2
-rw-r--r--src/libs/ssh/ssh.pro7
-rw-r--r--src/libs/ssh/ssh.qbs28
-rw-r--r--src/libs/ssh/sshcapabilities.cpp2
-rw-r--r--src/libs/ssh/sshchannel.cpp33
-rw-r--r--src/libs/ssh/sshchannel_p.h20
-rw-r--r--src/libs/ssh/sshchannelmanager.cpp11
-rw-r--r--src/libs/ssh/sshchannelmanager_p.h7
-rw-r--r--src/libs/ssh/sshconnection.cpp52
-rw-r--r--src/libs/ssh/sshconnection.h13
-rw-r--r--src/libs/ssh/sshconnection_p.h5
-rw-r--r--src/libs/ssh/sshcryptofacility.cpp15
-rw-r--r--src/libs/ssh/sshcryptofacility_p.h2
-rw-r--r--src/libs/ssh/sshdirecttcpiptunnel.cpp194
-rw-r--r--src/libs/ssh/sshdirecttcpiptunnel.h90
-rw-r--r--src/libs/ssh/sshdirecttcpiptunnel_p.h84
-rw-r--r--src/libs/ssh/sshkeycreationdialog.cpp5
-rw-r--r--src/libs/ssh/sshkeyexchange.cpp23
-rw-r--r--src/libs/ssh/sshkeyexchange_p.h3
-rw-r--r--src/libs/ssh/sshkeygenerator.cpp6
-rw-r--r--src/libs/ssh/sshoutgoingpacket.cpp11
-rw-r--r--src/libs/ssh/sshoutgoingpacket_p.h3
-rw-r--r--src/libs/ssh/sshremoteprocess.cpp3
-rw-r--r--src/libs/ssh/sshremoteprocess_p.h13
-rw-r--r--src/libs/ssh/sshsendfacility.cpp9
-rw-r--r--src/libs/ssh/sshsendfacility_p.h3
-rw-r--r--src/libs/utils/basetreeview.cpp34
-rw-r--r--src/libs/utils/basetreeview.h1
-rw-r--r--src/libs/utils/buildablehelperlibrary.cpp22
-rw-r--r--src/libs/utils/changeset.cpp2
-rw-r--r--src/libs/utils/classnamevalidatinglineedit.cpp37
-rw-r--r--src/libs/utils/classnamevalidatinglineedit.h5
-rw-r--r--src/libs/utils/consoleprocess.cpp21
-rw-r--r--src/libs/utils/consoleprocess.h14
-rw-r--r--src/libs/utils/consoleprocess_p.h8
-rw-r--r--src/libs/utils/consoleprocess_unix.cpp124
-rw-r--r--src/libs/utils/consoleprocess_win.cpp33
-rw-r--r--src/libs/utils/crumblepath.cpp22
-rw-r--r--src/libs/utils/detailsbutton.cpp16
-rw-r--r--src/libs/utils/detailswidget.cpp40
-rw-r--r--src/libs/utils/detailswidget.h2
-rw-r--r--src/libs/utils/elfreader.cpp2
-rw-r--r--src/libs/utils/elidinglabel.cpp (renamed from src/plugins/qmldesigner/components/integration/integrationcore.cpp)79
-rw-r--r--src/libs/utils/elidinglabel.h59
-rw-r--r--src/libs/utils/environment.cpp257
-rw-r--r--src/libs/utils/environment.h4
-rw-r--r--src/libs/utils/environmentmodel.cpp21
-rw-r--r--src/libs/utils/fancylineedit.cpp10
-rw-r--r--src/libs/utils/fancymainwindow.cpp9
-rw-r--r--src/libs/utils/filenamevalidatinglineedit.cpp13
-rw-r--r--src/libs/utils/filesearch.cpp71
-rw-r--r--src/libs/utils/filesearch.h1
-rw-r--r--src/libs/utils/filesystemwatcher.cpp6
-rw-r--r--src/libs/utils/fileutils.cpp110
-rw-r--r--src/libs/utils/fileutils.h91
-rw-r--r--src/libs/utils/filewizarddialog.cpp20
-rw-r--r--src/libs/utils/filewizardpage.ui2
-rw-r--r--src/libs/utils/flowlayout.cpp10
-rw-r--r--src/libs/utils/historycompleter.cpp13
-rw-r--r--src/libs/utils/hostosinfo.cpp (renamed from tests/auto/icheckbuild/ichecklib_global.h)38
-rw-r--r--src/libs/utils/hostosinfo.h111
-rw-r--r--src/libs/utils/json.cpp6
-rw-r--r--src/libs/utils/networkaccessmanager.cpp8
-rw-r--r--src/libs/utils/newclasswidget.cpp2
-rw-r--r--src/libs/utils/newclasswidget.h8
-rw-r--r--src/libs/utils/newclasswidget.ui7
-rw-r--r--src/libs/utils/parameteraction.cpp5
-rw-r--r--src/libs/utils/pathchooser.cpp25
-rw-r--r--src/libs/utils/pathchooser.h1
-rw-r--r--src/libs/utils/pathlisteditor.cpp24
-rw-r--r--src/libs/utils/pathlisteditor.h2
-rw-r--r--src/libs/utils/persistentsettings.cpp7
-rw-r--r--src/libs/utils/portlist.cpp2
-rw-r--r--src/libs/utils/process_stub_unix.c210
-rw-r--r--src/libs/utils/qtcprocess.cpp2
-rw-r--r--src/libs/utils/reloadpromptutils.cpp7
-rw-r--r--src/libs/utils/savefile.cpp42
-rw-r--r--src/libs/utils/savefile.h3
-rw-r--r--src/libs/utils/stringutils.cpp13
-rw-r--r--src/libs/utils/stylehelper.cpp8
-rw-r--r--src/libs/utils/synchronousprocess.cpp51
-rw-r--r--src/libs/utils/synchronousprocess.h1
-rw-r--r--src/libs/utils/tcpportsgatherer.cpp6
-rw-r--r--src/libs/utils/textfileformat.cpp12
-rw-r--r--src/libs/utils/tooltip/effects.h (renamed from src/plugins/texteditor/tooltip/effects.h)0
-rw-r--r--src/libs/utils/tooltip/reuse.h (renamed from src/plugins/texteditor/tooltip/reuse.h)4
-rw-r--r--src/libs/utils/tooltip/tipcontents.cpp (renamed from src/plugins/texteditor/tooltip/tipcontents.cpp)4
-rw-r--r--src/libs/utils/tooltip/tipcontents.h (renamed from src/plugins/texteditor/tooltip/tipcontents.h)14
-rw-r--r--src/libs/utils/tooltip/tips.cpp (renamed from src/plugins/texteditor/tooltip/tips.cpp)8
-rw-r--r--src/libs/utils/tooltip/tips.h (renamed from src/plugins/texteditor/tooltip/tips.h)14
-rw-r--r--src/libs/utils/tooltip/tooltip.cpp (renamed from src/plugins/texteditor/tooltip/tooltip.cpp)47
-rw-r--r--src/libs/utils/tooltip/tooltip.h (renamed from src/plugins/texteditor/tooltip/tooltip.h)15
-rw-r--r--src/libs/utils/uncommentselection.cpp2
-rw-r--r--src/libs/utils/utils-lib.pri31
-rw-r--r--src/libs/utils/utils.pro6
-rw-r--r--src/libs/utils/utils.qbs102
-rw-r--r--src/libs/utils/utils.qrc1
-rw-r--r--src/libs/utils/wizard.cpp3
-rw-r--r--src/libs/zeroconf/avahiLib.cpp5
-rw-r--r--src/libs/zeroconf/embed/dnssd_clientstub.c4
-rw-r--r--src/libs/zeroconf/embeddedLib.cpp8
-rw-r--r--src/libs/zeroconf/servicebrowser.cpp42
-rw-r--r--src/libs/zeroconf/zeroconf.qbs21
-rw-r--r--src/plugins/QtcPlugin.qbs20
-rw-r--r--src/plugins/analyzerbase/analyzerbase.pro2
-rw-r--r--src/plugins/analyzerbase/analyzerbase.qbs27
-rw-r--r--src/plugins/analyzerbase/analyzermanager.cpp8
-rw-r--r--src/plugins/analyzerbase/analyzeroptionspage.cpp2
-rw-r--r--src/plugins/analyzerbase/analyzerruncontrol.cpp2
-rw-r--r--src/plugins/analyzerbase/analyzerruncontrolfactory.cpp10
-rw-r--r--src/plugins/analyzerbase/analyzerruncontrolfactory.h1
-rw-r--r--src/plugins/analyzerbase/analyzersettings.cpp27
-rw-r--r--src/plugins/analyzerbase/analyzersettings.h9
-rw-r--r--src/plugins/analyzerbase/ianalyzertool.cpp10
-rw-r--r--src/plugins/android/Android.pluginspec.in4
-rw-r--r--src/plugins/android/android.pro1
-rw-r--r--src/plugins/android/android.qbs19
-rw-r--r--src/plugins/android/androidconfigurations.cpp62
-rw-r--r--src/plugins/android/androidconstants.h4
-rw-r--r--src/plugins/android/androiddebugsupport.cpp5
-rw-r--r--src/plugins/android/androiddeployconfiguration.cpp1
-rw-r--r--src/plugins/android/androiddeploystep.cpp210
-rw-r--r--src/plugins/android/androiddeploystep.h33
-rw-r--r--src/plugins/android/androiddeploystepwidget.cpp6
-rw-r--r--src/plugins/android/androiddeploystepwidget.h1
-rw-r--r--src/plugins/android/androiddeploystepwidget.ui9
-rw-r--r--src/plugins/android/androidmanager.cpp40
-rw-r--r--src/plugins/android/androidmanager.h6
-rw-r--r--src/plugins/android/androidpackagecreationstep.cpp38
-rw-r--r--src/plugins/android/androidpackagecreationstep.h4
-rw-r--r--src/plugins/android/androidpackagecreationwidget.cpp12
-rw-r--r--src/plugins/android/androidqtversion.cpp41
-rw-r--r--src/plugins/android/androidqtversion.h2
-rw-r--r--src/plugins/android/androidruncontrol.cpp2
-rw-r--r--src/plugins/android/androidrunner.cpp59
-rw-r--r--src/plugins/android/androidrunner.h4
-rw-r--r--src/plugins/android/androidsettingspage.cpp4
-rw-r--r--src/plugins/android/androidsettingswidget.cpp32
-rw-r--r--src/plugins/android/androidtoolchain.cpp58
-rw-r--r--src/plugins/android/androidtoolchain.h2
-rw-r--r--src/plugins/android/images/QtAndroid.pngbin2295 -> 8217 bytes
-rw-r--r--src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in18
-rw-r--r--src/plugins/autotoolsprojectmanager/autogenstep.cpp12
-rw-r--r--src/plugins/autotoolsprojectmanager/autogenstep.h2
-rw-r--r--src/plugins/autotoolsprojectmanager/autoreconfstep.cpp12
-rw-r--r--src/plugins/autotoolsprojectmanager/autoreconfstep.h2
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp14
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h3
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp14
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h9
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsproject.cpp20
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsproject.h1
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro1
-rw-r--r--src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.qbs11
-rw-r--r--src/plugins/autotoolsprojectmanager/configurestep.cpp12
-rw-r--r--src/plugins/autotoolsprojectmanager/configurestep.h2
-rw-r--r--src/plugins/autotoolsprojectmanager/makestep.cpp20
-rw-r--r--src/plugins/autotoolsprojectmanager/makestep.h2
-rw-r--r--src/plugins/bazaar/annotationhighlighter.h2
-rw-r--r--src/plugins/bazaar/bazaar.pro1
-rw-r--r--src/plugins/bazaar/bazaar.qbs39
-rw-r--r--src/plugins/bazaar/bazaarclient.cpp2
-rw-r--r--src/plugins/bazaar/bazaarcommitwidget.cpp4
-rw-r--r--src/plugins/bazaar/bazaarcommitwidget.h4
-rw-r--r--src/plugins/bazaar/bazaarcontrol.cpp2
-rw-r--r--src/plugins/bazaar/bazaarcontrol.h2
-rw-r--r--src/plugins/bazaar/bazaareditor.cpp24
-rw-r--r--src/plugins/bazaar/bazaareditor.h9
-rw-r--r--src/plugins/bazaar/bazaarplugin.cpp64
-rw-r--r--src/plugins/bazaar/bazaarplugin.h7
-rw-r--r--src/plugins/bazaar/commiteditor.cpp2
-rw-r--r--src/plugins/bazaar/optionspage.cpp2
-rw-r--r--src/plugins/bineditor/bineditor.cpp104
-rw-r--r--src/plugins/bineditor/bineditor.h3
-rw-r--r--src/plugins/bineditor/bineditor.pro2
-rw-r--r--src/plugins/bineditor/bineditor.qbs13
-rw-r--r--src/plugins/bineditor/bineditorplugin.cpp19
-rw-r--r--src/plugins/bookmarks/bookmark.cpp16
-rw-r--r--src/plugins/bookmarks/bookmark.h4
-rw-r--r--src/plugins/bookmarks/bookmarkmanager.cpp102
-rw-r--r--src/plugins/bookmarks/bookmarkmanager.h11
-rw-r--r--src/plugins/bookmarks/bookmarks.qbs15
-rw-r--r--src/plugins/bookmarks/bookmarks_global.h1
-rw-r--r--src/plugins/bookmarks/bookmarksplugin.cpp21
-rw-r--r--src/plugins/bookmarks/bookmarksplugin.h2
-rw-r--r--src/plugins/classview/classview.qbs37
-rw-r--r--src/plugins/classview/classviewmanager.cpp3
-rw-r--r--src/plugins/classview/classviewmanager.h8
-rw-r--r--src/plugins/classview/classviewnavigationwidget.h6
-rw-r--r--src/plugins/classview/classviewparser.cpp18
-rw-r--r--src/plugins/classview/classviewparsertreeitem.cpp14
-rw-r--r--src/plugins/classview/classviewsymbolinformation.h2
-rw-r--r--src/plugins/classview/classviewutils.cpp7
-rw-r--r--src/plugins/classview/classviewutils.h2
-rw-r--r--src/plugins/clearcase/ClearCase.pluginspec.in2
-rw-r--r--src/plugins/clearcase/annotationhighlighter.h2
-rw-r--r--src/plugins/clearcase/clearcase.pro2
-rw-r--r--src/plugins/clearcase/clearcase.qbs9
-rw-r--r--src/plugins/clearcase/clearcasecontrol.cpp7
-rw-r--r--src/plugins/clearcase/clearcasecontrol.h1
-rw-r--r--src/plugins/clearcase/clearcaseeditor.cpp42
-rw-r--r--src/plugins/clearcase/clearcaseeditor.h4
-rw-r--r--src/plugins/clearcase/clearcaseplugin.cpp140
-rw-r--r--src/plugins/clearcase/clearcaseplugin.h25
-rw-r--r--src/plugins/clearcase/clearcasesettings.cpp7
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditor.cpp4
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditor.h2
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditorwidget.cpp2
-rw-r--r--src/plugins/clearcase/clearcasesubmiteditorwidget.h4
-rw-r--r--src/plugins/clearcase/settingspage.cpp13
-rw-r--r--src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp60
-rw-r--r--src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h8
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditor.cpp22
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditor.h2
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp2
-rw-r--r--src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp (renamed from src/plugins/texteditor/tooltip/tipfactory.cpp)34
-rw-r--r--src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h56
-rw-r--r--src/plugins/cmakeprojectmanager/cmakehighlighter.cpp8
-rw-r--r--src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp7
-rw-r--r--src/plugins/cmakeprojectmanager/cmakelocatorfilter.h4
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp68
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h2
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeproject.cpp295
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeproject.h20
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp169
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.h27
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro8
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs19
-rw-r--r--src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp3
-rw-r--r--src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp6
-rw-r--r--src/plugins/cmakeprojectmanager/cmakerunconfiguration.h3
-rw-r--r--src/plugins/cmakeprojectmanager/cmakevalidator.cpp258
-rw-r--r--src/plugins/cmakeprojectmanager/cmakevalidator.h (renamed from src/plugins/madde/maemodeployconfigurationwidget.h)69
-rw-r--r--src/plugins/cmakeprojectmanager/makestep.cpp20
-rw-r--r--src/plugins/coreplugin/actionmanager/actioncontainer.cpp5
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager.cpp24
-rw-r--r--src/plugins/coreplugin/actionmanager/actionmanager.h2
-rw-r--r--src/plugins/coreplugin/actionmanager/command.cpp33
-rw-r--r--src/plugins/coreplugin/actionmanager/command_p.h2
-rw-r--r--src/plugins/coreplugin/actionmanager/commandmappings.cpp21
-rw-r--r--src/plugins/coreplugin/actionmanager/commandsfile.cpp2
-rw-r--r--src/plugins/coreplugin/basefilewizard.cpp24
-rw-r--r--src/plugins/coreplugin/coreconstants.h2
-rw-r--r--src/plugins/coreplugin/coreplugin.cpp7
-rw-r--r--src/plugins/coreplugin/coreplugin.pro1
-rw-r--r--src/plugins/coreplugin/coreplugin.qbs70
-rw-r--r--src/plugins/coreplugin/designmode.cpp11
-rw-r--r--src/plugins/coreplugin/dialogs/externaltoolconfig.cpp34
-rw-r--r--src/plugins/coreplugin/dialogs/externaltoolconfig.h1
-rw-r--r--src/plugins/coreplugin/dialogs/externaltoolconfig.ui51
-rw-r--r--src/plugins/coreplugin/dialogs/ioptionspage.h20
-rw-r--r--src/plugins/coreplugin/dialogs/newdialog.cpp13
-rw-r--r--src/plugins/coreplugin/dialogs/promptoverwritedialog.cpp5
-rw-r--r--src/plugins/coreplugin/dialogs/saveitemsdialog.cpp28
-rw-r--r--src/plugins/coreplugin/dialogs/settingsdialog.cpp89
-rw-r--r--src/plugins/coreplugin/dialogs/settingsdialog.h21
-rw-r--r--src/plugins/coreplugin/dialogs/shortcutsettings.cpp29
-rw-r--r--src/plugins/coreplugin/documentmanager.cpp82
-rw-r--r--src/plugins/coreplugin/documentmanager.h3
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager.cpp281
-rw-r--r--src/plugins/coreplugin/editormanager/editormanager.h10
-rw-r--r--src/plugins/coreplugin/editormanager/editorview.cpp28
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsmodel.cpp7
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.cpp87
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.h10
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorsview.ui31
-rw-r--r--src/plugins/coreplugin/editormanager/openeditorswindow.cpp14
-rw-r--r--src/plugins/coreplugin/editortoolbar.cpp15
-rw-r--r--src/plugins/coreplugin/externaltool.cpp39
-rw-r--r--src/plugins/coreplugin/fancyactionbar.cpp15
-rw-r--r--src/plugins/coreplugin/fancytabwidget.cpp20
-rw-r--r--src/plugins/coreplugin/featureprovider.h17
-rw-r--r--src/plugins/coreplugin/fileiconprovider.cpp15
-rw-r--r--src/plugins/coreplugin/fileutils.cpp155
-rw-r--r--src/plugins/coreplugin/generalsettings.cpp24
-rw-r--r--src/plugins/coreplugin/generalsettings.h1
-rw-r--r--src/plugins/coreplugin/generalsettings.ui168
-rw-r--r--src/plugins/coreplugin/icontext.cpp23
-rw-r--r--src/plugins/coreplugin/icontext.h24
-rw-r--r--src/plugins/coreplugin/icore.cpp11
-rw-r--r--src/plugins/coreplugin/icore.h10
-rw-r--r--src/plugins/coreplugin/id.cpp236
-rw-r--r--src/plugins/coreplugin/id.h22
-rw-r--r--src/plugins/coreplugin/idocument.cpp4
-rw-r--r--src/plugins/coreplugin/images/logo/logo.qbs17
-rw-r--r--src/plugins/coreplugin/inavigationwidgetfactory.h2
-rw-r--r--src/plugins/coreplugin/infobar.cpp86
-rw-r--r--src/plugins/coreplugin/infobar.h26
-rw-r--r--src/plugins/coreplugin/iversioncontrol.cpp5
-rw-r--r--src/plugins/coreplugin/iversioncontrol.h5
-rw-r--r--src/plugins/coreplugin/mainwindow.cpp132
-rw-r--r--src/plugins/coreplugin/mainwindow.h9
-rw-r--r--src/plugins/coreplugin/manhattanstyle.cpp18
-rw-r--r--src/plugins/coreplugin/mimedatabase.cpp51
-rw-r--r--src/plugins/coreplugin/mimetypesettings.cpp19
-rw-r--r--src/plugins/coreplugin/modemanager.cpp2
-rw-r--r--src/plugins/coreplugin/navigationsubwidget.cpp2
-rw-r--r--src/plugins/coreplugin/navigationwidget.cpp7
-rw-r--r--src/plugins/coreplugin/outputpane.cpp2
-rw-r--r--src/plugins/coreplugin/outputpanemanager.cpp22
-rw-r--r--src/plugins/coreplugin/outputwindow.cpp3
-rw-r--r--src/plugins/coreplugin/progressmanager/futureprogress.cpp13
-rw-r--r--src/plugins/coreplugin/progressmanager/progressbar.cpp2
-rw-r--r--src/plugins/coreplugin/progressmanager/progressmanager.cpp10
-rw-r--r--src/plugins/coreplugin/progressmanager/progressview.cpp5
-rw-r--r--src/plugins/coreplugin/rightpane.cpp8
-rw-r--r--src/plugins/coreplugin/scriptmanager/scriptmanager.cpp2
-rw-r--r--src/plugins/coreplugin/settingsdatabase.cpp3
-rw-r--r--src/plugins/coreplugin/sidebar.cpp17
-rw-r--r--src/plugins/coreplugin/sidebarwidget.cpp4
-rw-r--r--src/plugins/coreplugin/styleanimator.cpp6
-rw-r--r--src/plugins/coreplugin/textdocument.h1
-rw-r--r--src/plugins/coreplugin/toolsettings.cpp10
-rw-r--r--src/plugins/coreplugin/variablechooser.cpp33
-rw-r--r--src/plugins/coreplugin/variablechooser.h1
-rw-r--r--src/plugins/coreplugin/variablemanager.cpp9
-rw-r--r--src/plugins/coreplugin/variablemanager.h1
-rw-r--r--src/plugins/coreplugin/vcsmanager.cpp11
-rw-r--r--src/plugins/coreplugin/versiondialog.cpp2
-rw-r--r--src/plugins/cpaster/codepasterprotocol.cpp16
-rw-r--r--src/plugins/cpaster/codepastersettings.cpp4
-rw-r--r--src/plugins/cpaster/cpaster.pro1
-rw-r--r--src/plugins/cpaster/cpaster.qbs12
-rw-r--r--src/plugins/cpaster/cpasterconstants.h2
-rw-r--r--src/plugins/cpaster/cpasterplugin.cpp4
-rw-r--r--src/plugins/cpaster/fileshareprotocol.cpp12
-rw-r--r--src/plugins/cpaster/fileshareprotocolsettingspage.cpp4
-rw-r--r--src/plugins/cpaster/frontend/argumentscollector.cpp130
-rw-r--r--src/plugins/cpaster/frontend/argumentscollector.h64
-rw-r--r--src/plugins/cpaster/frontend/frontend.pro30
-rw-r--r--src/plugins/cpaster/frontend/frontend.qbs30
-rw-r--r--src/plugins/cpaster/frontend/main.cpp128
-rw-r--r--src/plugins/cpaster/kdepasteprotocol.cpp5
-rw-r--r--src/plugins/cpaster/pastebindotcaprotocol.cpp9
-rw-r--r--src/plugins/cpaster/pastebindotcaprotocol.h4
-rw-r--r--src/plugins/cpaster/pastebindotcomprotocol.cpp11
-rw-r--r--src/plugins/cpaster/pasteselectdialog.cpp8
-rw-r--r--src/plugins/cpaster/pasteview.cpp7
-rw-r--r--src/plugins/cpaster/protocol.cpp5
-rw-r--r--src/plugins/cpaster/settings.cpp8
-rw-r--r--src/plugins/cpaster/settingspage.cpp4
-rw-r--r--src/plugins/cpaster/urlopenprotocol.cpp5
-rw-r--r--src/plugins/cppeditor/cppclasswizard.cpp9
-rw-r--r--src/plugins/cppeditor/cppcompleteswitch.cpp45
-rw-r--r--src/plugins/cppeditor/cppcompleteswitch.h5
-rw-r--r--src/plugins/cppeditor/cppeditor.cpp140
-rw-r--r--src/plugins/cppeditor/cppeditor.pro5
-rw-r--r--src/plugins/cppeditor/cppeditor.qbs24
-rw-r--r--src/plugins/cppeditor/cppelementevaluator.cpp221
-rw-r--r--src/plugins/cppeditor/cppelementevaluator.h85
-rw-r--r--src/plugins/cppeditor/cppfunctiondecldeflink.cpp89
-rw-r--r--src/plugins/cppeditor/cppfunctiondecldeflink.h3
-rw-r--r--src/plugins/cppeditor/cpphighlighter.cpp38
-rw-r--r--src/plugins/cppeditor/cpphoverhandler.cpp8
-rw-r--r--src/plugins/cppeditor/cppinsertdecldef.cpp280
-rw-r--r--src/plugins/cppeditor/cppinsertdecldef.h15
-rw-r--r--src/plugins/cppeditor/cppinsertqtpropertymembers.cpp39
-rw-r--r--src/plugins/cppeditor/cppinsertqtpropertymembers.h6
-rw-r--r--src/plugins/cppeditor/cppoutline.cpp3
-rw-r--r--src/plugins/cppeditor/cppplugin.cpp25
-rw-r--r--src/plugins/cppeditor/cppplugin.h5
-rw-r--r--src/plugins/cppeditor/cppquickfix.cpp41
-rw-r--r--src/plugins/cppeditor/cppquickfix.h53
-rw-r--r--src/plugins/cppeditor/cppquickfix_test.cpp217
-rw-r--r--src/plugins/cppeditor/cppquickfixassistant.cpp1
-rw-r--r--src/plugins/cppeditor/cppquickfixes.cpp522
-rw-r--r--src/plugins/cppeditor/cpptypehierarchy.cpp24
-rw-r--r--src/plugins/cppeditor/cpptypehierarchy.h4
-rw-r--r--src/plugins/cpptools/ModelManagerInterface.cpp22
-rw-r--r--src/plugins/cpptools/ModelManagerInterface.h55
-rw-r--r--src/plugins/cpptools/builtinindexingsupport.cpp213
-rw-r--r--src/plugins/cpptools/builtinindexingsupport.h32
-rw-r--r--src/plugins/cpptools/completionsettingspage.cpp2
-rw-r--r--src/plugins/cpptools/cppchecksymbols.cpp49
-rw-r--r--src/plugins/cpptools/cppchecksymbols.h4
-rw-r--r--src/plugins/cpptools/cppclassesfilter.cpp6
-rw-r--r--src/plugins/cpptools/cppclassesfilter.h4
-rw-r--r--src/plugins/cpptools/cppcodeformatter.cpp37
-rw-r--r--src/plugins/cpptools/cppcodeformatter.h3
-rw-r--r--src/plugins/cpptools/cppcodegen_test.cpp20
-rw-r--r--src/plugins/cpptools/cppcodestylepreferences.cpp7
-rw-r--r--src/plugins/cpptools/cppcodestylepreferencesfactory.cpp4
-rw-r--r--src/plugins/cpptools/cppcodestylepreferencesfactory.h16
-rw-r--r--src/plugins/cpptools/cppcodestylesettings.cpp122
-rw-r--r--src/plugins/cpptools/cppcodestylesettings.h23
-rw-r--r--src/plugins/cpptools/cppcodestylesettingspage.cpp117
-rw-r--r--src/plugins/cpptools/cppcodestylesettingspage.ui82
-rw-r--r--src/plugins/cpptools/cppcompletion_test.cpp617
-rw-r--r--src/plugins/cpptools/cppcompletionassist.cpp142
-rw-r--r--src/plugins/cpptools/cppcompletionassist.h26
-rw-r--r--src/plugins/cpptools/cppcurrentdocumentfilter.cpp20
-rw-r--r--src/plugins/cpptools/cppcurrentdocumentfilter.h3
-rw-r--r--src/plugins/cpptools/cppdoxygen.cpp639
-rw-r--r--src/plugins/cpptools/cppfilesettingspage.cpp11
-rw-r--r--src/plugins/cpptools/cppfindreferences.cpp47
-rw-r--r--src/plugins/cpptools/cppfindreferences.h2
-rw-r--r--src/plugins/cpptools/cppfunctionsfilter.cpp4
-rw-r--r--src/plugins/cpptools/cppfunctionsfilter.h6
-rw-r--r--src/plugins/cpptools/cpphighlightingsupportinternal.cpp12
-rw-r--r--src/plugins/cpptools/cppindexingsupport.cpp47
-rw-r--r--src/plugins/cpptools/cppindexingsupport.h (renamed from src/plugins/remotelinux/deploymentsettingsassistant.h)72
-rw-r--r--src/plugins/cpptools/cpplocalsymbols.cpp5
-rw-r--r--src/plugins/cpptools/cpplocatorfilter.cpp14
-rw-r--r--src/plugins/cpptools/cpplocatorfilter.h4
-rw-r--r--src/plugins/cpptools/cppmodelmanager.cpp504
-rw-r--r--src/plugins/cpptools/cppmodelmanager.h111
-rw-r--r--src/plugins/cpptools/cppmodelmanager_test.cpp138
-rw-r--r--src/plugins/cpptools/cpppointerdeclarationformatter.cpp417
-rw-r--r--src/plugins/cpptools/cpppointerdeclarationformatter.h122
-rw-r--r--src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp577
-rw-r--r--src/plugins/cpptools/cpptools.pro22
-rw-r--r--src/plugins/cpptools/cpptools.qbs61
-rw-r--r--src/plugins/cpptools/cpptoolseditorsupport.cpp7
-rw-r--r--src/plugins/cpptools/cpptoolsplugin.cpp102
-rw-r--r--src/plugins/cpptools/cpptoolsplugin.h33
-rw-r--r--src/plugins/cpptools/cpptoolsreuse.h2
-rw-r--r--src/plugins/cpptools/cpptoolssettings.cpp8
-rw-r--r--src/plugins/cpptools/insertionpointlocator.cpp44
-rw-r--r--src/plugins/cpptools/modelmanagertesthelper.cpp99
-rw-r--r--src/plugins/cpptools/modelmanagertesthelper.h94
-rw-r--r--src/plugins/cpptools/searchsymbols.cpp25
-rw-r--r--src/plugins/cpptools/searchsymbols.h12
-rw-r--r--src/plugins/cpptools/symbolsfindfilter.cpp121
-rw-r--r--src/plugins/cpptools/symbolsfindfilter.h19
-rw-r--r--src/plugins/cpptools/uicodecompletionsupport.cpp62
-rw-r--r--src/plugins/cpptools/uicodecompletionsupport.h5
-rw-r--r--src/plugins/cvs/cvs.pro1
-rw-r--r--src/plugins/cvs/cvs.qbs37
-rw-r--r--src/plugins/cvs/cvscontrol.cpp2
-rw-r--r--src/plugins/cvs/cvseditor.cpp43
-rw-r--r--src/plugins/cvs/cvseditor.h2
-rw-r--r--src/plugins/cvs/cvsplugin.cpp75
-rw-r--r--src/plugins/cvs/cvsplugin.h11
-rw-r--r--src/plugins/cvs/cvssettings.cpp8
-rw-r--r--src/plugins/cvs/cvssubmiteditor.cpp6
-rw-r--r--src/plugins/cvs/cvsutils.cpp14
-rw-r--r--src/plugins/cvs/settingspage.cpp2
-rw-r--r--src/plugins/debugger/basewindow.h1
-rw-r--r--src/plugins/debugger/breakhandler.cpp45
-rw-r--r--src/plugins/debugger/breakhandler.h2
-rw-r--r--src/plugins/debugger/breakpointmarker.cpp10
-rw-r--r--src/plugins/debugger/breakpointmarker.h4
-rw-r--r--src/plugins/debugger/breakwindow.cpp19
-rw-r--r--src/plugins/debugger/cdb/cdbengine.cpp211
-rw-r--r--src/plugins/debugger/cdb/cdbengine.h5
-rw-r--r--src/plugins/debugger/cdb/cdboptions.cpp12
-rw-r--r--src/plugins/debugger/cdb/cdboptions.h2
-rw-r--r--src/plugins/debugger/cdb/cdboptionspage.cpp117
-rw-r--r--src/plugins/debugger/cdb/cdboptionspage.h36
-rw-r--r--src/plugins/debugger/cdb/cdboptionspagewidget.ui169
-rw-r--r--src/plugins/debugger/cdb/cdbparsehelpers.cpp61
-rw-r--r--src/plugins/debugger/cdb/cdbparsehelpers.h7
-rw-r--r--src/plugins/debugger/commonoptionspage.cpp170
-rw-r--r--src/plugins/debugger/commonoptionspage.h27
-rw-r--r--src/plugins/debugger/commonoptionspage.ui194
-rw-r--r--src/plugins/debugger/debugger.pro27
-rw-r--r--src/plugins/debugger/debugger.qbs127
-rw-r--r--src/plugins/debugger/debugger.qrc6
-rw-r--r--src/plugins/debugger/debuggeractions.cpp22
-rw-r--r--src/plugins/debugger/debuggeractions.h4
-rw-r--r--src/plugins/debugger/debuggerconstants.h14
-rw-r--r--src/plugins/debugger/debuggercore.h4
-rw-r--r--src/plugins/debugger/debuggerdialogs.cpp5
-rw-r--r--src/plugins/debugger/debuggerengine.cpp62
-rw-r--r--src/plugins/debugger/debuggerengine.h11
-rw-r--r--src/plugins/debugger/debuggerkitconfigwidget.cpp33
-rw-r--r--src/plugins/debugger/debuggerkitconfigwidget.h8
-rw-r--r--src/plugins/debugger/debuggerkitinformation.cpp7
-rw-r--r--src/plugins/debugger/debuggermainwindow.cpp7
-rw-r--r--src/plugins/debugger/debuggerplugin.cpp193
-rw-r--r--src/plugins/debugger/debuggerprotocol.cpp (renamed from src/plugins/debugger/gdb/gdbmi.cpp)157
-rw-r--r--src/plugins/debugger/debuggerprotocol.h (renamed from src/plugins/debugger/gdb/gdbmi.h)54
-rw-r--r--src/plugins/debugger/debuggerrunner.cpp15
-rw-r--r--src/plugins/debugger/debuggerstreamops.cpp4
-rw-r--r--src/plugins/debugger/debuggertooltipmanager.cpp39
-rw-r--r--src/plugins/debugger/disassembleragent.cpp2
-rw-r--r--src/plugins/debugger/gdb/abstractplaingdbadapter.cpp6
-rw-r--r--src/plugins/debugger/gdb/attachgdbadapter.cpp8
-rw-r--r--src/plugins/debugger/gdb/classicgdbengine.cpp24
-rw-r--r--src/plugins/debugger/gdb/coregdbadapter.cpp9
-rw-r--r--src/plugins/debugger/gdb/gdb.pri2
-rw-r--r--src/plugins/debugger/gdb/gdbengine.cpp279
-rw-r--r--src/plugins/debugger/gdb/gdbengine.h19
-rw-r--r--src/plugins/debugger/gdb/gdboptionspage.cpp55
-rw-r--r--src/plugins/debugger/gdb/localplaingdbadapter.cpp8
-rw-r--r--src/plugins/debugger/gdb/pythongdbengine.cpp3
-rw-r--r--src/plugins/debugger/gdb/remotegdbserveradapter.cpp38
-rw-r--r--src/plugins/debugger/gdb/termgdbadapter.cpp55
-rw-r--r--src/plugins/debugger/imageviewer.cpp170
-rw-r--r--src/plugins/debugger/imageviewer.h (renamed from src/plugins/qmldesigner/components/integration/integrationcore.h)44
-rw-r--r--src/plugins/debugger/lldb/guest/lldbengineguest.cpp15
-rw-r--r--src/plugins/debugger/lldb/ipcenginehost.cpp12
-rw-r--r--src/plugins/debugger/lldb/ipcenginehost.h2
-rw-r--r--src/plugins/debugger/lldb/lldbenginehost.cpp5
-rw-r--r--src/plugins/debugger/lldb/lldboptionspage.cpp2
-rw-r--r--src/plugins/debugger/localsandexpressionswindow.cpp11
-rw-r--r--src/plugins/debugger/localsandexpressionswindow.h1
-rw-r--r--src/plugins/debugger/logwindow.cpp18
-rw-r--r--src/plugins/debugger/memoryagent.cpp23
-rw-r--r--src/plugins/debugger/memoryagent.h2
-rw-r--r--src/plugins/debugger/moduleshandler.cpp6
-rw-r--r--src/plugins/debugger/moduleshandler.h18
-rw-r--r--src/plugins/debugger/moduleswindow.cpp17
-rw-r--r--src/plugins/debugger/namedemangler/namedemangler.cpp2
-rw-r--r--src/plugins/debugger/namedemangler/parsetreenodes.cpp11
-rw-r--r--src/plugins/debugger/namedemangler/parsetreenodes.h5
-rw-r--r--src/plugins/debugger/pdb/pdbengine.cpp10
-rw-r--r--src/plugins/debugger/pdb/pdbengine.h4
-rw-r--r--src/plugins/debugger/procinterrupt.cpp12
-rw-r--r--src/plugins/debugger/procinterrupt.h3
-rw-r--r--src/plugins/debugger/qml/baseqmldebuggerclient.cpp5
-rw-r--r--src/plugins/debugger/qml/qmladapter.cpp3
-rw-r--r--src/plugins/debugger/qml/qmlcppengine.cpp19
-rw-r--r--src/plugins/debugger/qml/qmlcppengine.h5
-rw-r--r--src/plugins/debugger/qml/qmlengine.cpp314
-rw-r--r--src/plugins/debugger/qml/qmlengine.h14
-rw-r--r--src/plugins/debugger/qml/qmlinspectoradapter.cpp136
-rw-r--r--src/plugins/debugger/qml/qmlinspectoradapter.h1
-rw-r--r--src/plugins/debugger/qml/qmlinspectoragent.cpp2
-rw-r--r--src/plugins/debugger/qml/qmllivetextpreview.cpp12
-rw-r--r--src/plugins/debugger/qml/qmlv8debuggerclient.cpp168
-rw-r--r--src/plugins/debugger/qml/qscriptdebuggerclient.cpp7
-rw-r--r--src/plugins/debugger/qtmessageloghandler.cpp405
-rw-r--r--src/plugins/debugger/qtmessagelogwindow.cpp253
-rw-r--r--src/plugins/debugger/registerhandler.cpp9
-rw-r--r--src/plugins/debugger/script/scriptengine.cpp12
-rw-r--r--src/plugins/debugger/script/scriptengine.h2
-rw-r--r--src/plugins/debugger/shared/hostutils.cpp19
-rw-r--r--src/plugins/debugger/shared/hostutils.h6
-rw-r--r--src/plugins/debugger/shared/peutils.cpp2
-rw-r--r--src/plugins/debugger/snapshothandler.cpp15
-rw-r--r--src/plugins/debugger/snapshothandler.h2
-rw-r--r--src/plugins/debugger/snapshotwindow.cpp2
-rw-r--r--src/plugins/debugger/sourcefileshandler.cpp6
-rw-r--r--src/plugins/debugger/sourcefileshandler.h1
-rw-r--r--src/plugins/debugger/sourceutils.cpp431
-rw-r--r--src/plugins/debugger/sourceutils.h60
-rw-r--r--src/plugins/debugger/stackhandler.cpp9
-rw-r--r--src/plugins/debugger/stackhandler.h2
-rw-r--r--src/plugins/debugger/threaddata.h48
-rw-r--r--src/plugins/debugger/threadshandler.cpp252
-rw-r--r--src/plugins/debugger/threadshandler.h27
-rw-r--r--src/plugins/debugger/threadswindow.cpp4
-rw-r--r--src/plugins/debugger/watchdata.cpp5
-rw-r--r--src/plugins/debugger/watchdelegatewidgets.cpp9
-rw-r--r--src/plugins/debugger/watchhandler.cpp146
-rw-r--r--src/plugins/debugger/watchhandler.h7
-rw-r--r--src/plugins/debugger/watchutils.cpp536
-rw-r--r--src/plugins/debugger/watchutils.h68
-rw-r--r--src/plugins/debugger/watchwindow.cpp65
-rw-r--r--src/plugins/debugger/watchwindow.h4
-rw-r--r--src/plugins/designer/cpp/cppsettingspage.cpp4
-rw-r--r--src/plugins/designer/cpp/formclasswizardpage.cpp3
-rw-r--r--src/plugins/designer/designer.pro7
-rw-r--r--src/plugins/designer/designer.qbs111
-rw-r--r--src/plugins/designer/formeditorfactory.cpp4
-rw-r--r--src/plugins/designer/formeditorstack.cpp8
-rw-r--r--src/plugins/designer/formeditorw.cpp2
-rw-r--r--src/plugins/designer/formwindoweditor.cpp6
-rw-r--r--src/plugins/designer/qt_private/formwindowbase_p.h2
-rw-r--r--src/plugins/designer/qtcreatorintegration.cpp3
-rw-r--r--src/plugins/designer/qtdesignerformclasscodegenerator.cpp3
-rw-r--r--src/plugins/designer/settingspage.cpp6
-rw-r--r--src/plugins/fakevim/fakevim.pro5
-rw-r--r--src/plugins/fakevim/fakevim.qbs20
-rw-r--r--src/plugins/fakevim/fakevim_test.cpp2816
-rw-r--r--src/plugins/fakevim/fakevimactions.cpp17
-rw-r--r--src/plugins/fakevim/fakevimactions.h5
-rw-r--r--src/plugins/fakevim/fakevimhandler.cpp6072
-rw-r--r--src/plugins/fakevim/fakevimhandler.h31
-rw-r--r--src/plugins/fakevim/fakevimoptions.ui222
-rw-r--r--src/plugins/fakevim/fakevimplugin.cpp491
-rw-r--r--src/plugins/fakevim/fakevimplugin.h100
-rw-r--r--src/plugins/find/basetextfind.cpp47
-rw-r--r--src/plugins/find/currentdocumentfind.cpp3
-rw-r--r--src/plugins/find/find.pro2
-rw-r--r--src/plugins/find/find.qbs18
-rw-r--r--src/plugins/find/find.qrc1
-rw-r--r--src/plugins/find/findplugin.cpp10
-rw-r--r--src/plugins/find/findplugin.h1
-rw-r--r--src/plugins/find/findtoolbar.cpp66
-rw-r--r--src/plugins/find/findtoolbar.h2
-rw-r--r--src/plugins/find/findtoolwindow.cpp9
-rw-r--r--src/plugins/find/ifindfilter.cpp8
-rw-r--r--src/plugins/find/images/preservecase.pngbin0 -> 196 bytes
-rw-r--r--src/plugins/find/searchresultcolor.h20
-rw-r--r--src/plugins/find/searchresulttreeitemdelegate.cpp75
-rw-r--r--src/plugins/find/searchresulttreeitemdelegate.h3
-rw-r--r--src/plugins/find/searchresulttreeitemroles.h2
-rw-r--r--src/plugins/find/searchresulttreeitems.cpp5
-rw-r--r--src/plugins/find/searchresulttreemodel.cpp33
-rw-r--r--src/plugins/find/searchresulttreemodel.h4
-rw-r--r--src/plugins/find/searchresulttreeview.cpp5
-rw-r--r--src/plugins/find/searchresulttreeview.h3
-rw-r--r--src/plugins/find/searchresultwidget.cpp99
-rw-r--r--src/plugins/find/searchresultwidget.h12
-rw-r--r--src/plugins/find/searchresultwindow.cpp28
-rw-r--r--src/plugins/find/searchresultwindow.h8
-rw-r--r--src/plugins/find/textfindconstants.h4
-rw-r--r--src/plugins/genericprojectmanager/filesselectionwizardpage.cpp6
-rw-r--r--src/plugins/genericprojectmanager/genericbuildconfiguration.cpp27
-rw-r--r--src/plugins/genericprojectmanager/genericbuildconfiguration.h13
-rw-r--r--src/plugins/genericprojectmanager/genericmakestep.cpp28
-rw-r--r--src/plugins/genericprojectmanager/genericmakestep.h3
-rw-r--r--src/plugins/genericprojectmanager/genericproject.cpp50
-rw-r--r--src/plugins/genericprojectmanager/genericproject.h4
-rw-r--r--src/plugins/genericprojectmanager/genericprojectfileseditor.cpp7
-rw-r--r--src/plugins/genericprojectmanager/genericprojectmanager.pro1
-rw-r--r--src/plugins/genericprojectmanager/genericprojectmanager.qbs42
-rw-r--r--src/plugins/genericprojectmanager/genericprojectnodes.cpp172
-rw-r--r--src/plugins/genericprojectmanager/genericprojectnodes.h8
-rw-r--r--src/plugins/genericprojectmanager/genericprojectplugin.cpp3
-rw-r--r--src/plugins/genericprojectmanager/selectablefilesmodel.cpp19
-rw-r--r--src/plugins/git/annotationhighlighter.h2
-rw-r--r--src/plugins/git/branchadddialog.cpp70
-rw-r--r--src/plugins/git/branchadddialog.h3
-rw-r--r--src/plugins/git/branchcheckoutdialog.cpp88
-rw-r--r--src/plugins/git/branchcheckoutdialog.h45
-rw-r--r--src/plugins/git/branchcheckoutdialog.ui133
-rw-r--r--src/plugins/git/branchdialog.cpp86
-rw-r--r--src/plugins/git/branchdialog.h2
-rw-r--r--src/plugins/git/branchdialog.ui133
-rw-r--r--src/plugins/git/branchmodel.cpp187
-rw-r--r--src/plugins/git/branchmodel.h5
-rw-r--r--src/plugins/git/changeselectiondialog.cpp60
-rw-r--r--src/plugins/git/changeselectiondialog.h12
-rw-r--r--src/plugins/git/changeselectiondialog.ui33
-rw-r--r--src/plugins/git/clonewizard.h12
-rw-r--r--src/plugins/git/clonewizardpage.cpp3
-rw-r--r--src/plugins/git/clonewizardpage.h6
-rw-r--r--src/plugins/git/commitdata.cpp95
-rw-r--r--src/plugins/git/commitdata.h62
-rw-r--r--src/plugins/git/gerrit/gerritdialog.cpp33
-rw-r--r--src/plugins/git/gerrit/gerritdialog.h6
-rw-r--r--src/plugins/git/gerrit/gerritmodel.cpp48
-rw-r--r--src/plugins/git/gerrit/gerritoptionspage.cpp7
-rw-r--r--src/plugins/git/gerrit/gerritoptionspage.h6
-rw-r--r--src/plugins/git/gerrit/gerritparameters.cpp19
-rw-r--r--src/plugins/git/gerrit/gerritplugin.cpp76
-rw-r--r--src/plugins/git/gerrit/gerritplugin.h8
-rw-r--r--src/plugins/git/git.pro12
-rw-r--r--src/plugins/git/git.qbs41
-rw-r--r--src/plugins/git/gitclient.cpp627
-rw-r--r--src/plugins/git/gitclient.h72
-rw-r--r--src/plugins/git/giteditor.cpp110
-rw-r--r--src/plugins/git/giteditor.h21
-rw-r--r--src/plugins/git/gitorious/gitorious.cpp60
-rw-r--r--src/plugins/git/gitorious/gitoriousclonewizard.cpp6
-rw-r--r--src/plugins/git/gitorious/gitoriousclonewizard.h12
-rw-r--r--src/plugins/git/gitorious/gitorioushostwidget.cpp5
-rw-r--r--src/plugins/git/gitorious/gitorioushostwizardpage.h4
-rw-r--r--src/plugins/git/gitorious/gitoriousprojectwidget.cpp10
-rw-r--r--src/plugins/git/gitorious/gitoriousprojectwidget.h2
-rw-r--r--src/plugins/git/gitorious/gitoriousprojectwizardpage.cpp2
-rw-r--r--src/plugins/git/gitorious/gitoriousprojectwizardpage.h4
-rw-r--r--src/plugins/git/gitorious/gitoriousrepositorywizardpage.cpp2
-rw-r--r--src/plugins/git/gitorious/gitoriousrepositorywizardpage.h4
-rw-r--r--src/plugins/git/gitplugin.cpp527
-rw-r--r--src/plugins/git/gitplugin.h25
-rw-r--r--src/plugins/git/gitsettings.cpp7
-rw-r--r--src/plugins/git/gitsubmiteditor.cpp110
-rw-r--r--src/plugins/git/gitsubmiteditor.h7
-rw-r--r--src/plugins/git/gitsubmiteditorwidget.cpp20
-rw-r--r--src/plugins/git/gitsubmiteditorwidget.h8
-rw-r--r--src/plugins/git/gitutils.cpp2
-rw-r--r--src/plugins/git/gitversioncontrol.cpp29
-rw-r--r--src/plugins/git/gitversioncontrol.h1
-rw-r--r--src/plugins/git/mergetool.cpp308
-rw-r--r--src/plugins/git/mergetool.h98
-rw-r--r--src/plugins/git/remotedialog.h2
-rw-r--r--src/plugins/git/remotemodel.cpp6
-rw-r--r--src/plugins/git/resetdialog.cpp22
-rw-r--r--src/plugins/git/resetdialog.h10
-rw-r--r--src/plugins/git/settingspage.cpp29
-rw-r--r--src/plugins/git/settingspage.h3
-rw-r--r--src/plugins/git/stashdialog.cpp17
-rw-r--r--src/plugins/glsleditor/glslcompletionassist.cpp18
-rw-r--r--src/plugins/glsleditor/glsleditor.cpp6
-rw-r--r--src/plugins/glsleditor/glsleditor.qbs41
-rw-r--r--src/plugins/glsleditor/glsleditorfactory.cpp2
-rw-r--r--src/plugins/glsleditor/glsleditorplugin.cpp74
-rw-r--r--src/plugins/glsleditor/glsleditorplugin.h36
-rw-r--r--src/plugins/glsleditor/glslhighlighter.cpp28
-rw-r--r--src/plugins/glsleditor/glslhoverhandler.cpp3
-rw-r--r--src/plugins/helloworld/helloworld.qbs11
-rw-r--r--src/plugins/help/centralwidget.cpp2
-rw-r--r--src/plugins/help/docsettingspage.cpp4
-rw-r--r--src/plugins/help/externalhelpwindow.cpp29
-rw-r--r--src/plugins/help/filtersettingspage.cpp4
-rw-r--r--src/plugins/help/generalsettingspage.cpp13
-rw-r--r--src/plugins/help/help.pro6
-rw-r--r--src/plugins/help/help.qbs82
-rw-r--r--src/plugins/help/helpindexfilter.cpp18
-rw-r--r--src/plugins/help/helpindexfilter.h3
-rw-r--r--src/plugins/help/helpplugin.cpp48
-rw-r--r--src/plugins/help/helpviewer.cpp12
-rw-r--r--src/plugins/help/helpviewer.h5
-rw-r--r--src/plugins/help/helpviewer_p.h4
-rw-r--r--src/plugins/help/helpviewer_qtb.cpp22
-rw-r--r--src/plugins/help/helpviewer_qwv.cpp26
-rw-r--r--src/plugins/help/localhelpmanager.cpp2
-rw-r--r--src/plugins/help/openpagesmanager.cpp5
-rw-r--r--src/plugins/help/openpagesswitcher.cpp14
-rw-r--r--src/plugins/help/remotehelpfilter.cpp29
-rw-r--r--src/plugins/help/remotehelpfilter.h4
-rw-r--r--src/plugins/help/searchwidget.cpp19
-rw-r--r--src/plugins/imageviewer/imageviewer.cpp12
-rw-r--r--src/plugins/imageviewer/imageviewer.qbs31
-rw-r--r--src/plugins/imageviewer/imagevieweractionhandler.cpp2
-rw-r--r--src/plugins/imageviewer/imagevieweractionhandler.h4
-rw-r--r--src/plugins/imageviewer/imageviewerfactory.cpp2
-rw-r--r--src/plugins/locator/basefilefilter.cpp6
-rw-r--r--src/plugins/locator/commandlocator.cpp34
-rw-r--r--src/plugins/locator/commandlocator.h32
-rw-r--r--src/plugins/locator/directoryfilter.cpp15
-rw-r--r--src/plugins/locator/directoryfilter.h3
-rw-r--r--src/plugins/locator/executefilter.cpp2
-rw-r--r--src/plugins/locator/executefilter.h3
-rw-r--r--src/plugins/locator/filesystemfilter.cpp18
-rw-r--r--src/plugins/locator/filesystemfilter.h7
-rw-r--r--src/plugins/locator/ilocatorfilter.cpp57
-rw-r--r--src/plugins/locator/ilocatorfilter.h47
-rw-r--r--src/plugins/locator/locator.qbs29
-rw-r--r--src/plugins/locator/locatorfiltersfilter.cpp24
-rw-r--r--src/plugins/locator/locatorfiltersfilter.h4
-rw-r--r--src/plugins/locator/locatorplugin.cpp6
-rw-r--r--src/plugins/locator/locatorplugin.h4
-rw-r--r--src/plugins/locator/locatorwidget.cpp81
-rw-r--r--src/plugins/locator/locatorwidget.h2
-rw-r--r--src/plugins/locator/opendocumentsfilter.cpp13
-rw-r--r--src/plugins/locator/opendocumentsfilter.h3
-rw-r--r--src/plugins/locator/settingspage.cpp2
-rw-r--r--src/plugins/locator/settingspage.ui3
-rw-r--r--src/plugins/macros/actionmacrohandler.cpp68
-rw-r--r--src/plugins/macros/actionmacrohandler.h9
-rw-r--r--src/plugins/macros/macro.cpp2
-rw-r--r--src/plugins/macros/macroevent.cpp21
-rw-r--r--src/plugins/macros/macroevent.h8
-rw-r--r--src/plugins/macros/macrolocatorfilter.cpp2
-rw-r--r--src/plugins/macros/macrolocatorfilter.h4
-rw-r--r--src/plugins/macros/macromanager.cpp20
-rw-r--r--src/plugins/macros/macrooptionspage.cpp4
-rw-r--r--src/plugins/macros/macrooptionswidget.cpp3
-rw-r--r--src/plugins/macros/macros.qbs18
-rw-r--r--src/plugins/macros/savedialog.cpp2
-rw-r--r--src/plugins/madde/Madde.pluginspec.in3
-rw-r--r--src/plugins/madde/debianmanager.cpp33
-rw-r--r--src/plugins/madde/madde.pro6
-rw-r--r--src/plugins/madde/madde.qbs27
-rw-r--r--src/plugins/madde/madde_dependencies.pri1
-rw-r--r--src/plugins/madde/maddedevicetester.cpp2
-rw-r--r--src/plugins/madde/maemoconstants.h6
-rw-r--r--src/plugins/madde/maemodeploybymountsteps.cpp69
-rw-r--r--src/plugins/madde/maemodeployconfigurationwidget.cpp218
-rw-r--r--src/plugins/madde/maemodeployconfigurationwidget.ui48
-rw-r--r--src/plugins/madde/maemodeploystepfactory.cpp4
-rw-r--r--src/plugins/madde/maemoglobal.cpp62
-rw-r--r--src/plugins/madde/maemoinstalltosysrootstep.cpp31
-rw-r--r--src/plugins/madde/maemoinstalltosysrootstep.h4
-rw-r--r--src/plugins/madde/maemopackagecreationstep.cpp25
-rw-r--r--src/plugins/madde/maemopackagecreationwidget.cpp2
-rw-r--r--src/plugins/madde/maemopublishedprojectmodel.cpp5
-rw-r--r--src/plugins/madde/maemopublisherfremantlefree.cpp81
-rw-r--r--src/plugins/madde/maemopublisherfremantlefree.h3
-rw-r--r--src/plugins/madde/maemoqemumanager.cpp4
-rw-r--r--src/plugins/madde/maemoqemuruntimeparser.cpp54
-rw-r--r--src/plugins/madde/maemoqtversion.cpp20
-rw-r--r--src/plugins/madde/maemoremotecopyfacility.cpp20
-rw-r--r--src/plugins/madde/maemoremotecopyfacility.h8
-rw-r--r--src/plugins/madde/maemorunconfiguration.h3
-rw-r--r--src/plugins/madde/maemorunfactories.cpp5
-rw-r--r--src/plugins/madde/maemosettingspages.cpp8
-rw-r--r--src/plugins/madde/maemosettingspages.h5
-rw-r--r--src/plugins/madde/qt4maemodeployconfiguration.cpp84
-rw-r--r--src/plugins/madde/qt4maemodeployconfiguration.h16
-rw-r--r--src/plugins/mercurial/annotationhighlighter.h2
-rw-r--r--src/plugins/mercurial/commiteditor.cpp4
-rw-r--r--src/plugins/mercurial/constants.h3
-rw-r--r--src/plugins/mercurial/mercurial.pro1
-rw-r--r--src/plugins/mercurial/mercurial.qbs54
-rw-r--r--src/plugins/mercurial/mercurialclient.cpp6
-rw-r--r--src/plugins/mercurial/mercurialclient.h8
-rw-r--r--src/plugins/mercurial/mercurialcommitwidget.cpp4
-rw-r--r--src/plugins/mercurial/mercurialcommitwidget.h4
-rw-r--r--src/plugins/mercurial/mercurialcontrol.cpp2
-rw-r--r--src/plugins/mercurial/mercurialcontrol.h2
-rw-r--r--src/plugins/mercurial/mercurialeditor.cpp26
-rw-r--r--src/plugins/mercurial/mercurialeditor.h13
-rw-r--r--src/plugins/mercurial/mercurialplugin.cpp63
-rw-r--r--src/plugins/mercurial/mercurialplugin.h11
-rw-r--r--src/plugins/mercurial/optionspage.cpp2
-rw-r--r--src/plugins/mercurial/optionspage.h2
-rw-r--r--src/plugins/perforce/annotationhighlighter.h2
-rw-r--r--src/plugins/perforce/perforce.pro2
-rw-r--r--src/plugins/perforce/perforce.qbs48
-rw-r--r--src/plugins/perforce/perforcechecker.h2
-rw-r--r--src/plugins/perforce/perforceeditor.cpp54
-rw-r--r--src/plugins/perforce/perforceeditor.h11
-rw-r--r--src/plugins/perforce/perforceplugin.cpp54
-rw-r--r--src/plugins/perforce/perforceplugin.h7
-rw-r--r--src/plugins/perforce/perforcesettings.cpp8
-rw-r--r--src/plugins/perforce/perforcesubmiteditor.cpp2
-rw-r--r--src/plugins/perforce/perforcesubmiteditorwidget.cpp2
-rw-r--r--src/plugins/perforce/perforcesubmiteditorwidget.h4
-rw-r--r--src/plugins/perforce/perforceversioncontrol.cpp2
-rw-r--r--src/plugins/perforce/settingspage.cpp2
-rw-r--r--src/plugins/plugins.pro4
-rw-r--r--src/plugins/projectexplorer/abi.cpp2
-rw-r--r--src/plugins/projectexplorer/abiwidget.cpp1
-rw-r--r--src/plugins/projectexplorer/abstractmsvctoolchain.cpp12
-rw-r--r--src/plugins/projectexplorer/abstractmsvctoolchain.h2
-rw-r--r--src/plugins/projectexplorer/abstractprocessstep.cpp2
-rw-r--r--src/plugins/projectexplorer/abstractprocessstep.h3
-rw-r--r--src/plugins/projectexplorer/allprojectsfilter.cpp8
-rw-r--r--src/plugins/projectexplorer/allprojectsfilter.h3
-rw-r--r--src/plugins/projectexplorer/applicationlauncher.cpp2
-rw-r--r--src/plugins/projectexplorer/appoutputpane.cpp5
-rw-r--r--src/plugins/projectexplorer/baseprojectwizarddialog.cpp3
-rw-r--r--src/plugins/projectexplorer/buildconfiguration.cpp48
-rw-r--r--src/plugins/projectexplorer/buildconfiguration.h20
-rw-r--r--src/plugins/projectexplorer/buildconfigurationmodel.cpp6
-rw-r--r--src/plugins/projectexplorer/buildenvironmentwidget.cpp19
-rw-r--r--src/plugins/projectexplorer/buildenvironmentwidget.h8
-rw-r--r--src/plugins/projectexplorer/buildmanager.cpp35
-rw-r--r--src/plugins/projectexplorer/buildsettingspropertiespage.cpp34
-rw-r--r--src/plugins/projectexplorer/buildsettingspropertiespage.h8
-rw-r--r--src/plugins/projectexplorer/buildstep.h18
-rw-r--r--src/plugins/projectexplorer/buildsteplist.cpp4
-rw-r--r--src/plugins/projectexplorer/buildstepspage.cpp57
-rw-r--r--src/plugins/projectexplorer/buildstepspage.h7
-rw-r--r--src/plugins/projectexplorer/buildtargetinfo.h27
-rw-r--r--src/plugins/projectexplorer/clangparser.cpp10
-rw-r--r--src/plugins/projectexplorer/codestylesettingspropertiespage.cpp6
-rw-r--r--src/plugins/projectexplorer/compileoutputwindow.cpp11
-rw-r--r--src/plugins/projectexplorer/copytaskhandler.cpp10
-rw-r--r--src/plugins/projectexplorer/copytaskhandler.h1
-rw-r--r--src/plugins/projectexplorer/currentprojectfilter.cpp8
-rw-r--r--src/plugins/projectexplorer/currentprojectfilter.h4
-rw-r--r--src/plugins/projectexplorer/customtoolchain.cpp506
-rw-r--r--src/plugins/projectexplorer/customtoolchain.h179
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizard.cpp18
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizardpage.cpp20
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizardparameters.cpp65
-rw-r--r--src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp20
-rw-r--r--src/plugins/projectexplorer/dependenciespanel.cpp6
-rw-r--r--src/plugins/projectexplorer/deployconfiguration.cpp44
-rw-r--r--src/plugins/projectexplorer/deployconfiguration.h27
-rw-r--r--src/plugins/projectexplorer/deployconfigurationmodel.cpp6
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanager.cpp9
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp4
-rw-r--r--src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp4
-rw-r--r--src/plugins/projectexplorer/devicesupport/idevice.cpp52
-rw-r--r--src/plugins/projectexplorer/devicesupport/idevice.h2
-rw-r--r--src/plugins/projectexplorer/doubletabwidget.cpp17
-rw-r--r--src/plugins/projectexplorer/editorconfiguration.cpp23
-rw-r--r--src/plugins/projectexplorer/editorconfiguration.h6
-rw-r--r--src/plugins/projectexplorer/environmentitemswidget.cpp6
-rw-r--r--src/plugins/projectexplorer/foldernavigationwidget.cpp78
-rw-r--r--src/plugins/projectexplorer/foldernavigationwidget.h9
-rw-r--r--src/plugins/projectexplorer/gccparser.cpp155
-rw-r--r--src/plugins/projectexplorer/gcctoolchain.cpp152
-rw-r--r--src/plugins/projectexplorer/gcctoolchain.h11
-rw-r--r--src/plugins/projectexplorer/gcctoolchainfactories.h1
-rw-r--r--src/plugins/projectexplorer/gnumakeparser.cpp12
-rw-r--r--src/plugins/projectexplorer/headerpath.h6
-rw-r--r--src/plugins/projectexplorer/images/targetchangebutton.pngbin0 -> 1605 bytes
-rw-r--r--src/plugins/projectexplorer/images/targetchangebutton2.pngbin0 -> 1578 bytes
-rw-r--r--src/plugins/projectexplorer/images/targetremovebutton.pngbin566 -> 0 bytes
-rw-r--r--src/plugins/projectexplorer/images/targetremovebuttondark.pngbin1533 -> 0 bytes
-rw-r--r--src/plugins/projectexplorer/itaskhandler.h3
-rw-r--r--src/plugins/projectexplorer/kit.cpp58
-rw-r--r--src/plugins/projectexplorer/kit.h10
-rw-r--r--src/plugins/projectexplorer/kitconfigwidget.h15
-rw-r--r--src/plugins/projectexplorer/kitinformation.cpp26
-rw-r--r--src/plugins/projectexplorer/kitinformation.h1
-rw-r--r--src/plugins/projectexplorer/kitinformationconfigwidget.cpp125
-rw-r--r--src/plugins/projectexplorer/kitinformationconfigwidget.h23
-rw-r--r--src/plugins/projectexplorer/kitmanager.cpp9
-rw-r--r--src/plugins/projectexplorer/kitmanager.h3
-rw-r--r--src/plugins/projectexplorer/kitmanagerconfigwidget.cpp95
-rw-r--r--src/plugins/projectexplorer/kitmanagerconfigwidget.h18
-rw-r--r--src/plugins/projectexplorer/kitmodel.cpp5
-rw-r--r--src/plugins/projectexplorer/kitoptionspage.cpp6
-rw-r--r--src/plugins/projectexplorer/kitoptionspage.h3
-rw-r--r--src/plugins/projectexplorer/linuxiccparser.cpp6
-rw-r--r--src/plugins/projectexplorer/localapplicationrunconfiguration.cpp (renamed from src/plugins/projectexplorer/applicationrunconfiguration.cpp)20
-rw-r--r--src/plugins/projectexplorer/localapplicationrunconfiguration.h (renamed from src/plugins/projectexplorer/applicationrunconfiguration.h)6
-rw-r--r--src/plugins/projectexplorer/localapplicationruncontrol.cpp6
-rw-r--r--src/plugins/projectexplorer/miniprojecttargetselector.cpp42
-rw-r--r--src/plugins/projectexplorer/msvcparser.cpp38
-rw-r--r--src/plugins/projectexplorer/msvctoolchain.cpp115
-rw-r--r--src/plugins/projectexplorer/msvctoolchain.h9
-rw-r--r--src/plugins/projectexplorer/nodesvisitor.cpp6
-rw-r--r--src/plugins/projectexplorer/outputparser_test.cpp2
-rw-r--r--src/plugins/projectexplorer/pluginfilefactory.cpp2
-rw-r--r--src/plugins/projectexplorer/pluginfilefactory.h1
-rw-r--r--src/plugins/projectexplorer/processparameters.cpp7
-rw-r--r--src/plugins/projectexplorer/processparameters.h1
-rw-r--r--src/plugins/projectexplorer/processstep.cpp13
-rw-r--r--src/plugins/projectexplorer/processstep.h4
-rw-r--r--src/plugins/projectexplorer/project.cpp15
-rw-r--r--src/plugins/projectexplorer/project.h9
-rw-r--r--src/plugins/projectexplorer/projectconfiguration.cpp7
-rw-r--r--src/plugins/projectexplorer/projectexplorer.cpp198
-rw-r--r--src/plugins/projectexplorer/projectexplorer.h1
-rw-r--r--src/plugins/projectexplorer/projectexplorer.pro14
-rw-r--r--src/plugins/projectexplorer/projectexplorer.qbs270
-rw-r--r--src/plugins/projectexplorer/projectexplorer.qrc4
-rw-r--r--src/plugins/projectexplorer/projectexplorerconstants.h16
-rw-r--r--src/plugins/projectexplorer/projectexplorersettingspage.cpp41
-rw-r--r--src/plugins/projectexplorer/projectexplorersettingspage.h5
-rw-r--r--src/plugins/projectexplorer/projectexplorersettingspage.ui64
-rw-r--r--src/plugins/projectexplorer/projectfilewizardextension.cpp20
-rw-r--r--src/plugins/projectexplorer/projectmacroexpander.cpp74
-rw-r--r--src/plugins/projectexplorer/projectmacroexpander.h (renamed from tests/auto/icheckbuild/ichecklib.h)33
-rw-r--r--src/plugins/projectexplorer/projectmodels.cpp43
-rw-r--r--src/plugins/projectexplorer/projectmodels.h2
-rw-r--r--src/plugins/projectexplorer/projectnodes.cpp34
-rw-r--r--src/plugins/projectexplorer/projectnodes.h16
-rw-r--r--src/plugins/projectexplorer/projecttreewidget.cpp56
-rw-r--r--src/plugins/projectexplorer/projectwelcomepage.cpp21
-rw-r--r--src/plugins/projectexplorer/projectwizardpage.cpp4
-rw-r--r--src/plugins/projectexplorer/removetaskhandler.cpp58
-rw-r--r--src/plugins/projectexplorer/removetaskhandler.h54
-rw-r--r--src/plugins/projectexplorer/runconfiguration.cpp50
-rw-r--r--src/plugins/projectexplorer/runconfiguration.h8
-rw-r--r--src/plugins/projectexplorer/runconfigurationmodel.cpp6
-rw-r--r--src/plugins/projectexplorer/runsettingspropertiespage.cpp6
-rw-r--r--src/plugins/projectexplorer/runsettingspropertiespage.h4
-rw-r--r--src/plugins/projectexplorer/session.cpp27
-rw-r--r--src/plugins/projectexplorer/sessiondialog.cpp5
-rw-r--r--src/plugins/projectexplorer/settingsaccessor.cpp172
-rw-r--r--src/plugins/projectexplorer/showineditortaskhandler.cpp4
-rw-r--r--src/plugins/projectexplorer/showoutputtaskhandler.cpp2
-rw-r--r--src/plugins/projectexplorer/target.cpp12
-rw-r--r--src/plugins/projectexplorer/target.h5
-rw-r--r--src/plugins/projectexplorer/targetselector.cpp133
-rw-r--r--src/plugins/projectexplorer/targetselector.h20
-rw-r--r--src/plugins/projectexplorer/targetsettingspanel.cpp299
-rw-r--r--src/plugins/projectexplorer/targetsettingspanel.h18
-rw-r--r--src/plugins/projectexplorer/targetsettingswidget.cpp9
-rw-r--r--src/plugins/projectexplorer/targetsettingswidget.h8
-rw-r--r--src/plugins/projectexplorer/taskhub.cpp4
-rw-r--r--src/plugins/projectexplorer/taskmodel.cpp19
-rw-r--r--src/plugins/projectexplorer/taskwindow.cpp145
-rw-r--r--src/plugins/projectexplorer/taskwindow.h7
-rw-r--r--src/plugins/projectexplorer/toolchain.cpp7
-rw-r--r--src/plugins/projectexplorer/toolchain.h4
-rw-r--r--src/plugins/projectexplorer/toolchainmanager.cpp13
-rw-r--r--src/plugins/projectexplorer/toolchainoptionspage.cpp17
-rw-r--r--src/plugins/projectexplorer/toolchainoptionspage.h9
-rw-r--r--src/plugins/projectexplorer/wincetoolchain.cpp2
-rw-r--r--src/plugins/qmldesigner/components/componentcore/abstractdesigneraction.h73
-rw-r--r--src/plugins/qmldesigner/components/componentcore/componentcore.pri15
-rw-r--r--src/plugins/qmldesigner/components/componentcore/componentcore_constants.h106
-rw-r--r--src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp444
-rw-r--r--src/plugins/qmldesigner/components/componentcore/designeractionmanager.h66
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp140
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h59
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp274
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h280
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp606
-rw-r--r--src/plugins/qmldesigner/components/componentcore/modelnodeoperations.h70
-rw-r--r--src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp (renamed from src/plugins/qmldesigner/meegoplugin/meegoplugin.cpp)35
-rw-r--r--src/plugins/qmldesigner/components/componentcore/selectioncontext.h99
-rw-r--r--src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp7
-rw-r--r--src/plugins/qmldesigner/components/formeditor/dragtool.cpp31
-rw-r--r--src/plugins/qmldesigner/components/formeditor/dragtool.h1
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditor.pri6
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp123
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h73
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorgraphicsview.cpp5
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp5
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorscene.cpp24
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorview.cpp35
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorview.h7
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp40
-rw-r--r--src/plugins/qmldesigner/components/formeditor/formeditorwidget.h4
-rw-r--r--src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp49
-rw-r--r--src/plugins/qmldesigner/components/formeditor/movetool.cpp10
-rw-r--r--src/plugins/qmldesigner/components/formeditor/onedimensionalcluster.cpp2
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp60
-rw-r--r--src/plugins/qmldesigner/components/formeditor/resizetool.cpp10
-rw-r--r--src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp2
-rw-r--r--src/plugins/qmldesigner/components/formeditor/selectiontool.cpp7
-rw-r--r--src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp4
-rw-r--r--src/plugins/qmldesigner/components/formeditor/snapper.cpp19
-rw-r--r--src/plugins/qmldesigner/components/formeditor/toolbox.cpp10
-rw-r--r--src/plugins/qmldesigner/components/formeditor/toolbox.h7
-rw-r--r--src/plugins/qmldesigner/components/formeditor/zoomaction.cpp7
-rw-r--r--src/plugins/qmldesigner/components/integration/componentaction.cpp21
-rw-r--r--src/plugins/qmldesigner/components/integration/componentaction.h7
-rw-r--r--src/plugins/qmldesigner/components/integration/componentview.cpp17
-rw-r--r--src/plugins/qmldesigner/components/integration/componentview.h6
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocument.cpp784
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocument.h (renamed from src/plugins/qmldesigner/components/integration/designdocumentcontroller.h)127
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocumentcontroller.cpp994
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocumentview.cpp (renamed from src/plugins/qmldesigner/components/integration/designdocumentcontrollerview.cpp)82
-rw-r--r--src/plugins/qmldesigner/components/integration/designdocumentview.h (renamed from src/plugins/qmldesigner/components/integration/designdocumentcontrollerview.h)14
-rw-r--r--src/plugins/qmldesigner/components/integration/integration.pri10
-rw-r--r--src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.cpp12
-rw-r--r--src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.h8
-rw-r--r--src/plugins/qmldesigner/components/integration/xuifiledialog.cpp30
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp4
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h2
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp7
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp15
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h4
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp289
-rw-r--r--src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h46
-rw-r--r--src/plugins/qmldesigner/components/logger/logger.cpp3
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigator.pri1
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp36
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatortreemodel.h2
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatorview.cpp7
-rw-r--r--src/plugins/qmldesigner/components/navigator/navigatorview.h2
-rw-r--r--src/plugins/qmldesigner/components/pluginmanager/pluginmanager.cpp79
-rw-r--r--src/plugins/qmldesigner/components/pluginmanager/pluginmanager.h12
-rw-r--r--src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp2
-rw-r--r--src/plugins/qmldesigner/components/pluginmanager/pluginpath.h6
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp19
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp3
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp94
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h16
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/filewidget.cpp41
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/filewidget.h1
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/genericpropertieswidget.cpp25
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp2
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/originwidget.cpp2
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp152
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h2
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h3
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp38
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h3
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp12
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp2
-rw-r--r--src/plugins/qmldesigner/components/propertyeditor/siblingcombobox.cpp2
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp10
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp36
-rw-r--r--src/plugins/qmldesigner/components/stateseditor/stateseditorview.h3
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/customstyle.metainfo93
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/customstyleplugin.json19
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pri13
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pro4
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/customstyleplugin.qrc41
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/busyindicator.pngbin4089 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/busyindicator16.pngbin3594 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/busyindicatora.pngbin3546 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/busyindicatora16.pngbin3385 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/button.pngbin3537 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/button16.pngbin3250 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn.pngbin3264 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn16.pngbin3166 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/buttonrow.pngbin3247 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/buttonrow16.pngbin3174 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/checkbox.pngbin3612 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/checkbox16.pngbin3334 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/choicelist.pngbin3870 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/choicelist16.pngbin3494 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/item-icon.pngbin396 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/item-icon16.pngbin312 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/progressbar.pngbin2971 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/progressbar16.pngbin3004 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/radiobutton.pngbin3849 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/radiobutton16.pngbin3439 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/slider.pngbin3576 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/slider16.pngbin3266 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/sliderh.pngbin3578 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/sliderh16.pngbin3285 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/switchbutton.pngbin3236 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/switchbutton16.pngbin534 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/tabbar.pngbin385 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/tabbar16.pngbin264 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/tabbutton.pngbin3270 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/tabbutton16.pngbin3108 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/textarea.pngbin3644 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/textarea16.pngbin3309 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/textfield.pngbin3617 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/textfield16.pngbin3265 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/toolbar.pngbin339 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/toolbar16.pngbin255 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/window.pngbin396 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/customstyleplugin/images/window16.pngbin312 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/designercore/designercore-lib.pri (renamed from src/plugins/qmldesigner/designercore/designercore.pri)12
-rw-r--r--src/plugins/qmldesigner/designercore/exceptions/invalididexception.cpp5
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp12
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp19
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/filemanager.pri9
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/firstdefinitionfinder.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/moveobjectbeforeobjectvisitor.cpp9
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/moveobjectvisitor.cpp11
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/qmlrefactoring.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/qmlrewriter.h2
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.cpp77
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.h41
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.ui112
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp9
-rw-r--r--src/plugins/qmldesigner/designercore/filemanager/removeuiobjectmembervisitor.cpp8
-rw-r--r--src/plugins/qmldesigner/designercore/include/abstractproperty.h30
-rw-r--r--src/plugins/qmldesigner/designercore/include/abstractview.h13
-rw-r--r--src/plugins/qmldesigner/designercore/include/basetexteditmodifier.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/bindingproperty.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/bytearraymodifier.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/exception.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/import.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidargumentexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalididexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidmetainfoexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidmodelnodeexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidmodelstateexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidpropertyexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidqmlsourceexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidreparentingexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/invalidslideindexexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h31
-rw-r--r--src/plugins/qmldesigner/designercore/include/metainfo.h10
-rw-r--r--src/plugins/qmldesigner/designercore/include/metainforeader.h125
-rw-r--r--src/plugins/qmldesigner/designercore/include/model.h17
-rw-r--r--src/plugins/qmldesigner/designercore/include/modelnode.h30
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h16
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodeinstanceview.h9
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodelistproperty.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodemetainfo.h12
-rw-r--r--src/plugins/qmldesigner/designercore/include/nodeproperty.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/notimplementedexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/plaintexteditmodifier.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/propertycontainer.h19
-rw-r--r--src/plugins/qmldesigner/designercore/include/propertynode.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlanchors.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlchangeset.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmldesignercorelib_global.h (renamed from src/plugins/qmldesigner/designercore/include/corelib_global.h)13
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlitemnode.h14
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlmodelview.h12
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlobjectnode.h10
-rw-r--r--src/plugins/qmldesigner/designercore/include/qmlstate.h6
-rw-r--r--src/plugins/qmldesigner/designercore/include/removebasestateexception.h2
-rw-r--r--src/plugins/qmldesigner/designercore/include/rewriterview.h15
-rw-r--r--src/plugins/qmldesigner/designercore/include/subcomponentmanager.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/textmodifier.h4
-rw-r--r--src/plugins/qmldesigner/designercore/include/variantproperty.h10
-rw-r--r--src/plugins/qmldesigner/designercore/include/viewmanager.h115
-rw-r--r--src/plugins/qmldesigner/designercore/include/widgetqueryview.h56
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp75
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp80
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h1
-rw-r--r--src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp128
-rw-r--r--src/plugins/qmldesigner/designercore/iwidgetplugin.pri1
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp73
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp25
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainfoparser.cpp245
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp335
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp331
-rw-r--r--src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp155
-rw-r--r--src/plugins/qmldesigner/designercore/model/abstractproperty.cpp1
-rw-r--r--src/plugins/qmldesigner/designercore/model/abstractview.cpp21
-rw-r--r--src/plugins/qmldesigner/designercore/model/anchorline.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/model/basetexteditmodifier.cpp5
-rw-r--r--src/plugins/qmldesigner/designercore/model/bindingproperty.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/model/internalnode.cpp8
-rw-r--r--src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/model/internalproperty.h4
-rw-r--r--src/plugins/qmldesigner/designercore/model/model.cpp168
-rw-r--r--src/plugins/qmldesigner/designercore/model/model_p.h11
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelmerger.cpp15
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelnode.cpp39
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.cpp951
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.h131
-rw-r--r--src/plugins/qmldesigner/designercore/model/modelrewriter.cpp15
-rw-r--r--src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp15
-rw-r--r--src/plugins/qmldesigner/designercore/model/modeltotextmerger.h4
-rw-r--r--src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/model/painteventfilter.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/model/paster.cpp12
-rw-r--r--src/plugins/qmldesigner/designercore/model/plaintexteditmodifier.cpp5
-rw-r--r--src/plugins/qmldesigner/designercore/model/propertycontainer.cpp19
-rw-r--r--src/plugins/qmldesigner/designercore/model/propertyparser.cpp6
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlanchors.cpp19
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp9
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp46
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp9
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmlstate.cpp18
-rw-r--r--src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp8
-rw-r--r--src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp14
-rw-r--r--src/plugins/qmldesigner/designercore/model/rewriterview.cpp76
-rw-r--r--src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp129
-rw-r--r--src/plugins/qmldesigner/designercore/model/texttomodelmerger.h4
-rw-r--r--src/plugins/qmldesigner/designercore/model/variantproperty.cpp3
-rw-r--r--src/plugins/qmldesigner/designercore/model/viewlogger.cpp49
-rw-r--r--src/plugins/qmldesigner/designercore/model/viewlogger.h4
-rw-r--r--src/plugins/qmldesigner/designercore/model/viewmanager.cpp201
-rw-r--r--src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.cpp26
-rw-r--r--src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.h9
-rw-r--r--src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp2
-rw-r--r--src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.h5
-rw-r--r--src/plugins/qmldesigner/designercore/preview/stylemanager.cpp2
-rw-r--r--src/plugins/qmldesigner/designersettings.cpp16
-rw-r--r--src/plugins/qmldesigner/designersettings.h4
-rw-r--r--src/plugins/qmldesigner/designmodewidget.cpp479
-rw-r--r--src/plugins/qmldesigner/designmodewidget.h92
-rw-r--r--src/plugins/qmldesigner/desktopplugin/desktop.metainfo522
-rw-r--r--src/plugins/qmldesigner/documentmanager.cpp80
-rw-r--r--src/plugins/qmldesigner/documentmanager.h65
-rw-r--r--src/plugins/qmldesigner/extrasplugin/extras.metainfo54
-rw-r--r--src/plugins/qmldesigner/extrasplugin/extrasplugin.json19
-rw-r--r--src/plugins/qmldesigner/extrasplugin/extrasplugin.pri13
-rw-r--r--src/plugins/qmldesigner/extrasplugin/extrasplugin.pro4
-rw-r--r--src/plugins/qmldesigner/extrasplugin/extrasplugin.qrc31
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/count-bubble-16.pngbin3427 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/count-bubble-24.pngbin985 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/date-picker-16.pngbin3512 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/date-picker-24.pngbin606 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/info-banner-16.pngbin3105 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/info-banner-24.pngbin323 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/list-button-16.pngbin3217 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/list-button-24.pngbin481 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/list-delegate-16.pngbin3281 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/list-delegate-24.pngbin425 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/more-indicator-16.pngbin3333 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/more-indicator-24.pngbin896 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/page-indicator-16.pngbin3168 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/page-indicator-24.pngbin579 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/rating-indicator-16.pngbin3422 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/rating-indicator-24.pngbin1144 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/time-picker-16.pngbin3438 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/time-picker-24.pngbin875 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-16.pngbin3467 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-24.pngbin836 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-button-16.pngbin3481 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-button-24.pngbin880 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-column-16.pngbin3493 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-column-24.pngbin991 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-16.pngbin3167 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-24.pngbin414 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/Untitled-2.pngbin3144 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/busyindicator.pngbin4089 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/busyindicator16.pngbin3594 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/busyindicatora.pngbin3546 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/busyindicatora16.pngbin3385 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/button.pngbin3537 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/button16.pngbin3250 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/buttoncolumn.pngbin3264 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/buttoncolumn16.pngbin3166 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/buttonrow.pngbin3247 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/buttonrow16.pngbin3174 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/checkbox.pngbin3612 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/checkbox16.pngbin3334 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/choicelist.pngbin3870 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/choicelist16.pngbin3494 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/item-icon.pngbin396 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/item-icon16.pngbin312 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/label.pngbin1134 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/label16.pngbin750 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/lineedit.pngbin430 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/lineedit16.pngbin358 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/progressbar.pngbin2971 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/progressbar16.pngbin3004 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/radiobutton.pngbin3849 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/radiobutton16.pngbin3439 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/slider.pngbin3576 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/slider16.pngbin3266 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/sliderh.pngbin3578 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/sliderh16.pngbin3285 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/switchbutton.pngbin3236 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/switchbutton16.pngbin534 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/tabbutton.pngbin3270 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/tabbutton16.pngbin3108 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/textarea.pngbin3644 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/textarea16.pngbin3309 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/textfield.pngbin3617 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/textfield16.pngbin3265 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/toolbar.pngbin339 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/toolbar16.pngbin255 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/window.pngbin396 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/images/window16.pngbin312 -> 0 bytes
-rw-r--r--src/plugins/qmldesigner/meegoplugin/meego.metainfo110
-rw-r--r--src/plugins/qmldesigner/meegoplugin/meegoplugin.json19
-rw-r--r--src/plugins/qmldesigner/meegoplugin/meegoplugin.pri13
-rw-r--r--src/plugins/qmldesigner/meegoplugin/meegoplugin.pro4
-rw-r--r--src/plugins/qmldesigner/meegoplugin/meegoplugin.qrc45
-rw-r--r--src/plugins/qmldesigner/meegoplugin/qtquickplugin.json19
-rw-r--r--src/plugins/qmldesigner/qmldesigner.pro2
-rw-r--r--src/plugins/qmldesigner/qmldesigner.qbs853
-rw-r--r--src/plugins/qmldesigner/qmldesignerconstants.h4
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.cpp486
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.h75
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.pri20
-rw-r--r--src/plugins/qmldesigner/qmldesignerplugin.pro21
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/qtquickplugin.qrc6
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/quick.metainfo596
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/source/gridviewv2.qml87
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/source/listviewv2.qml68
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/source/pathviewv2.qml78
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/source/texteditv2.qml37
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/source/textinputv2.qml37
-rw-r--r--src/plugins/qmldesigner/qtquickplugin/source/textv2.qml35
-rw-r--r--src/plugins/qmldesigner/settingspage.cpp13
-rw-r--r--src/plugins/qmldesigner/settingspage.ui45
-rw-r--r--src/plugins/qmldesigner/shortcutmanager.cpp326
-rw-r--r--src/plugins/qmldesigner/shortcutmanager.h72
-rw-r--r--src/plugins/qmljseditor/QmlJSEditor.mimetypes.xml18
-rw-r--r--src/plugins/qmljseditor/jsfilewizard.cpp3
-rw-r--r--src/plugins/qmljseditor/qmljscompletionassist.cpp9
-rw-r--r--src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp13
-rw-r--r--src/plugins/qmljseditor/qmljscomponentfromobjectdef.h3
-rw-r--r--src/plugins/qmljseditor/qmljseditor.cpp30
-rw-r--r--src/plugins/qmljseditor/qmljseditor.qbs17
-rw-r--r--src/plugins/qmljseditor/qmljseditoreditable.cpp2
-rw-r--r--src/plugins/qmljseditor/qmljseditorfactory.cpp5
-rw-r--r--src/plugins/qmljseditor/qmljseditorplugin.cpp4
-rw-r--r--src/plugins/qmljseditor/qmljsfindreferences.cpp20
-rw-r--r--src/plugins/qmljseditor/qmljsfindreferences.h2
-rw-r--r--src/plugins/qmljseditor/qmljshighlighter.cpp74
-rw-r--r--src/plugins/qmljseditor/qmljshoverhandler.cpp14
-rw-r--r--src/plugins/qmljseditor/qmljsoutline.cpp8
-rw-r--r--src/plugins/qmljseditor/qmljspreviewrunner.cpp5
-rw-r--r--src/plugins/qmljseditor/qmljsquickfix.cpp35
-rw-r--r--src/plugins/qmljseditor/qmljsquickfix.h37
-rw-r--r--src/plugins/qmljseditor/qmljsquickfixes.cpp22
-rw-r--r--src/plugins/qmljseditor/qmljssemantichighlighter.cpp12
-rw-r--r--src/plugins/qmljseditor/qmljswrapinloader.cpp30
-rw-r--r--src/plugins/qmljseditor/qmljswrapinloader.h4
-rw-r--r--src/plugins/qmljseditor/qmloutlinemodel.cpp69
-rw-r--r--src/plugins/qmljseditor/quicktoolbar.cpp53
-rw-r--r--src/plugins/qmljseditor/quicktoolbar.h4
-rw-r--r--src/plugins/qmljseditor/quicktoolbarsettingspage.cpp4
-rw-r--r--src/plugins/qmljstools/images/collapse.png (renamed from src/plugins/debugger/images/collapse.png)bin986 -> 986 bytes
-rw-r--r--src/plugins/qmljstools/images/error.png (renamed from src/plugins/debugger/images/error.png)bin1344 -> 1344 bytes
-rw-r--r--src/plugins/qmljstools/images/expand.png (renamed from src/plugins/debugger/images/expand.png)bin997 -> 997 bytes
-rw-r--r--src/plugins/qmljstools/images/log.png (renamed from src/plugins/debugger/images/log.png)bin1354 -> 1354 bytes
-rw-r--r--src/plugins/qmljstools/images/prompt.png (renamed from src/plugins/debugger/images/prompt.png)bin1049 -> 1049 bytes
-rw-r--r--src/plugins/qmljstools/images/warning.png (renamed from src/plugins/debugger/images/warning.png)bin1454 -> 1454 bytes
-rw-r--r--src/plugins/qmljstools/qmlconsoleedit.cpp (renamed from src/plugins/debugger/qtmessagelogeditor.cpp)84
-rw-r--r--src/plugins/qmljstools/qmlconsoleedit.h (renamed from src/plugins/debugger/qtmessagelogeditor.h)22
-rw-r--r--src/plugins/qmljstools/qmlconsoleitemdelegate.cpp (renamed from src/plugins/debugger/qtmessagelogitemdelegate.cpp)183
-rw-r--r--src/plugins/qmljstools/qmlconsoleitemdelegate.h (renamed from src/plugins/debugger/qtmessagelogitemdelegate.h)89
-rw-r--r--src/plugins/qmljstools/qmlconsoleitemmodel.cpp282
-rw-r--r--src/plugins/qmljstools/qmlconsoleitemmodel.h (renamed from src/plugins/debugger/qtmessageloghandler.h)93
-rw-r--r--src/plugins/qmljstools/qmlconsolemanager.cpp190
-rw-r--r--src/plugins/qmljstools/qmlconsolemanager.h74
-rw-r--r--src/plugins/qmljstools/qmlconsolemodel.h (renamed from src/plugins/texteditor/tooltip/tipfactory.h)27
-rw-r--r--src/plugins/qmljstools/qmlconsolepane.cpp244
-rw-r--r--src/plugins/qmljstools/qmlconsolepane.h100
-rw-r--r--src/plugins/qmljstools/qmlconsoleproxymodel.cpp (renamed from src/plugins/debugger/qtmessagelogproxymodel.cpp)42
-rw-r--r--src/plugins/qmljstools/qmlconsoleproxymodel.h (renamed from src/plugins/debugger/qtmessagelogproxymodel.h)20
-rw-r--r--src/plugins/qmljstools/qmlconsoleview.cpp (renamed from src/plugins/debugger/qtmessagelogview.cpp)151
-rw-r--r--src/plugins/qmljstools/qmlconsoleview.h (renamed from src/plugins/debugger/qtmessagelogview.h)16
-rw-r--r--src/plugins/qmljstools/qmljscodestylepreferencesfactory.cpp4
-rw-r--r--src/plugins/qmljstools/qmljscodestylepreferencesfactory.h14
-rw-r--r--src/plugins/qmljstools/qmljscodestylesettingspage.cpp12
-rw-r--r--src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp24
-rw-r--r--src/plugins/qmljstools/qmljsfunctionfilter.cpp4
-rw-r--r--src/plugins/qmljstools/qmljsfunctionfilter.h4
-rw-r--r--src/plugins/qmljstools/qmljsinterpreter.cpp87
-rw-r--r--src/plugins/qmljstools/qmljsinterpreter.h69
-rw-r--r--src/plugins/qmljstools/qmljslocatordata.cpp13
-rw-r--r--src/plugins/qmljstools/qmljsmodelmanager.cpp67
-rw-r--r--src/plugins/qmljstools/qmljsplugindumper.cpp6
-rw-r--r--src/plugins/qmljstools/qmljssemanticinfo.cpp16
-rw-r--r--src/plugins/qmljstools/qmljstools-lib.pri45
-rw-r--r--src/plugins/qmljstools/qmljstools.pri2
-rw-r--r--src/plugins/qmljstools/qmljstools.pro66
-rw-r--r--src/plugins/qmljstools/qmljstools.qbs46
-rw-r--r--src/plugins/qmljstools/qmljstools.qrc10
-rw-r--r--src/plugins/qmljstools/qmljstools_test.cpp44
-rw-r--r--src/plugins/qmljstools/qmljstoolsconstants.h5
-rw-r--r--src/plugins/qmljstools/qmljstoolsplugin.cpp11
-rw-r--r--src/plugins/qmljstools/qmljstoolsplugin.h2
-rw-r--r--src/plugins/qmljstools/qmljstoolssettings.cpp76
-rw-r--r--src/plugins/qmljstools/qmljstoolssettings.h22
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp3
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h2
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp3
-rw-r--r--src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp122
-rw-r--r--src/plugins/qmlprofiler/localqmlprofilerrunner.cpp8
-rw-r--r--src/plugins/qmlprofiler/qmlprofiler.qbs12
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp25
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp158
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp7
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerengine.cpp12
-rw-r--r--src/plugins/qmlprofiler/qmlprofilereventview.cpp34
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerstatemanager.cpp16
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp2
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertool.cpp21
-rw-r--r--src/plugins/qmlprofiler/qmlprofilertraceview.cpp146
-rw-r--r--src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp2
-rw-r--r--src/plugins/qmlprofiler/qv8profilerdatamodel.cpp82
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp23
-rw-r--r--src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp3
-rw-r--r--src/plugins/qmlprojectmanager/qmlapp.cpp439
-rw-r--r--src/plugins/qmlprojectmanager/qmlapp.h118
-rw-r--r--src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp175
-rw-r--r--src/plugins/qmlprojectmanager/qmlapplicationwizard.h (renamed from src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.h)59
-rw-r--r--src/plugins/qmlprojectmanager/qmlproject.cpp102
-rw-r--r--src/plugins/qmlprojectmanager/qmlproject.h9
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.cpp219
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectconstants.h4
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectfile.cpp2
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectmanager.cpp5
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectmanager.pro10
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectmanager.qbs57
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectnodes.cpp4
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectplugin.cpp11
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp14
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.h6
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfigurationfactory.cpp24
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp7
-rw-r--r--src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp16
-rw-r--r--src/plugins/qnx/bardescriptordocument.cpp260
-rw-r--r--src/plugins/qnx/bardescriptordocument.h92
-rw-r--r--src/plugins/qnx/bardescriptordocumentnodehandlers.cpp671
-rw-r--r--src/plugins/qnx/bardescriptordocumentnodehandlers.h287
-rw-r--r--src/plugins/qnx/bardescriptoreditor.cpp200
-rw-r--r--src/plugins/qnx/bardescriptoreditor.h104
-rw-r--r--src/plugins/qnx/bardescriptoreditorfactory.cpp74
-rw-r--r--src/plugins/qnx/bardescriptoreditorfactory.h62
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.cpp674
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.h187
-rw-r--r--src/plugins/qnx/bardescriptoreditorwidget.ui540
-rw-r--r--src/plugins/qnx/bardescriptormagicmatcher.cpp55
-rw-r--r--src/plugins/qnx/bardescriptormagicmatcher.h (renamed from src/plugins/qt4projectmanager/profilekeywords.h)33
-rw-r--r--src/plugins/qnx/bardescriptorpermissionsmodel.cpp170
-rw-r--r--src/plugins/qnx/bardescriptorpermissionsmodel.h94
-rw-r--r--src/plugins/qnx/blackberryapplicationrunner.cpp20
-rw-r--r--src/plugins/qnx/blackberryconfiguration.cpp338
-rw-r--r--src/plugins/qnx/blackberryconfiguration.h104
-rw-r--r--src/plugins/qnx/blackberryconnect.cpp17
-rw-r--r--src/plugins/qnx/blackberrydeployconfiguration.cpp102
-rw-r--r--src/plugins/qnx/blackberrydeployconfiguration.h10
-rw-r--r--src/plugins/qnx/blackberrydeployconfigurationwidget.cpp21
-rw-r--r--src/plugins/qnx/blackberrydeployconfigurationwidget.h6
-rw-r--r--src/plugins/qnx/blackberrydeploystep.cpp15
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp8
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp15
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h3
-rw-r--r--src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui37
-rw-r--r--src/plugins/qnx/blackberryndksettingspage.cpp69
-rw-r--r--src/plugins/qnx/blackberryndksettingspage.h58
-rw-r--r--src/plugins/qnx/blackberryndksettingswidget.cpp133
-rw-r--r--src/plugins/qnx/blackberryndksettingswidget.h74
-rw-r--r--src/plugins/qnx/blackberryndksettingswidget.ui57
-rw-r--r--src/plugins/qnx/blackberryqtversion.cpp124
-rw-r--r--src/plugins/qnx/blackberryqtversion.h6
-rw-r--r--src/plugins/qnx/blackberryrunconfiguration.cpp10
-rw-r--r--src/plugins/qnx/blackberryruncontrolfactory.cpp16
-rw-r--r--src/plugins/qnx/blackberryruncontrolfactory.h5
-rw-r--r--src/plugins/qnx/blackberrywizardextension.cpp1
-rw-r--r--src/plugins/qnx/qnx.pro28
-rw-r--r--src/plugins/qnx/qnx.qbs67
-rw-r--r--src/plugins/qnx/qnx_dependencies.pri1
-rw-r--r--src/plugins/qnx/qnxabstractqtversion.cpp63
-rw-r--r--src/plugins/qnx/qnxabstractqtversion.h5
-rw-r--r--src/plugins/qnx/qnxconstants.h13
-rw-r--r--src/plugins/qnx/qnxdeployconfiguration.cpp1
-rw-r--r--src/plugins/qnx/qnxdeviceconfigurationfactory.cpp3
-rw-r--r--src/plugins/qnx/qnxdeviceconfigurationwizard.cpp7
-rw-r--r--src/plugins/qnx/qnxplugin.cpp24
-rw-r--r--src/plugins/qnx/qnxqtversion.cpp35
-rw-r--r--src/plugins/qnx/qnxrunconfiguration.h3
-rw-r--r--src/plugins/qnx/qnxutils.cpp142
-rw-r--r--src/plugins/qnx/qnxutils.h10
-rw-r--r--src/plugins/qt4projectmanager/addlibrarywizard.cpp10
-rw-r--r--src/plugins/qt4projectmanager/customwidgetwizard/customwidgetpluginwizardpage.cpp5
-rw-r--r--src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizarddialog.cpp4
-rw-r--r--src/plugins/qt4projectmanager/images/qml.icobin99678 -> 0 bytes
-rw-r--r--src/plugins/qt4projectmanager/images/qml.pngbin0 -> 293 bytes
-rw-r--r--src/plugins/qt4projectmanager/librarydetailscontroller.cpp45
-rw-r--r--src/plugins/qt4projectmanager/makestep.cpp29
-rw-r--r--src/plugins/qt4projectmanager/profilecompletionassist.cpp411
-rw-r--r--src/plugins/qt4projectmanager/profilecompletionassist.h57
-rw-r--r--src/plugins/qt4projectmanager/profileeditor.cpp35
-rw-r--r--src/plugins/qt4projectmanager/profileeditor.h11
-rw-r--r--src/plugins/qt4projectmanager/profileeditorfactory.cpp2
-rw-r--r--src/plugins/qt4projectmanager/profilehighlighter.cpp15
-rw-r--r--src/plugins/qt4projectmanager/profilehighlighter.h13
-rw-r--r--src/plugins/qt4projectmanager/profilehoverhandler.cpp10
-rw-r--r--src/plugins/qt4projectmanager/profilehoverhandler.h2
-rw-r--r--src/plugins/qt4projectmanager/profilekeywords.cpp332
-rw-r--r--src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp25
-rw-r--r--src/plugins/qt4projectmanager/qmakekitconfigwidget.h14
-rw-r--r--src/plugins/qt4projectmanager/qmakeparser.cpp4
-rw-r--r--src/plugins/qt4projectmanager/qmakestep.cpp49
-rw-r--r--src/plugins/qt4projectmanager/qt-desktop/desktopqtversion.cpp4
-rw-r--r--src/plugins/qt4projectmanager/qt-desktop/desktopqtversionfactory.cpp2
-rw-r--r--src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.cpp40
-rw-r--r--src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h4
-rw-r--r--src/plugins/qt4projectmanager/qt-desktop/simulatorqtversion.cpp6
-rw-r--r--src/plugins/qt4projectmanager/qt4buildconfiguration.cpp261
-rw-r--r--src/plugins/qt4projectmanager/qt4buildconfiguration.h24
-rw-r--r--src/plugins/qt4projectmanager/qt4nodes.cpp397
-rw-r--r--src/plugins/qt4projectmanager/qt4nodes.h18
-rw-r--r--src/plugins/qt4projectmanager/qt4project.cpp166
-rw-r--r--src/plugins/qt4projectmanager/qt4project.h15
-rw-r--r--src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp69
-rw-r--r--src/plugins/qt4projectmanager/qt4projectconfigwidget.h9
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.cpp35
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.h1
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.pro8
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.qbs58
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanager.qrc2
-rw-r--r--src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp10
-rw-r--r--src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp10
-rw-r--r--src/plugins/qt4projectmanager/qtmodulesinfo.cpp4
-rw-r--r--src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp29
-rw-r--r--src/plugins/qt4projectmanager/unconfiguredprojectpanel.h2
-rw-r--r--src/plugins/qt4projectmanager/winceqtversion.cpp1
-rw-r--r--src/plugins/qt4projectmanager/wizards/abstractmobileapp.cpp6
-rw-r--r--src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp27
-rw-r--r--src/plugins/qt4projectmanager/wizards/consoleappwizarddialog.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/emptyprojectwizarddialog.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/guiappwizard.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/guiappwizarddialog.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/libraryparameters.cpp8
-rw-r--r--src/plugins/qt4projectmanager/wizards/librarywizard.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp11
-rw-r--r--src/plugins/qt4projectmanager/wizards/mobileappwizardpages.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtquickapp.cpp202
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtquickapp.h48
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp7
-rw-r--r--src/plugins/qt4projectmanager/wizards/qtwizard.cpp8
-rw-r--r--src/plugins/qt4projectmanager/wizards/subdirsprojectwizarddialog.cpp2
-rw-r--r--src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp10
-rw-r--r--src/plugins/qt4projectmanager/wizards/testwizard.cpp3
-rw-r--r--src/plugins/qt4projectmanager/wizards/testwizarddialog.cpp2
-rw-r--r--src/plugins/qtsupport/baseqtversion.cpp346
-rw-r--r--src/plugins/qtsupport/baseqtversion.h16
-rw-r--r--src/plugins/qtsupport/customexecutablerunconfiguration.cpp40
-rw-r--r--src/plugins/qtsupport/customexecutablerunconfiguration.h6
-rw-r--r--src/plugins/qtsupport/debugginghelper.cpp2
-rw-r--r--src/plugins/qtsupport/debugginghelperbuildtask.cpp6
-rw-r--r--src/plugins/qtsupport/exampleslistmodel.cpp122
-rw-r--r--src/plugins/qtsupport/exampleslistmodel.h73
-rw-r--r--src/plugins/qtsupport/gettingstartedwelcomepage.cpp24
-rw-r--r--src/plugins/qtsupport/gettingstartedwelcomepage.h1
-rw-r--r--src/plugins/qtsupport/profilereader.cpp6
-rw-r--r--src/plugins/qtsupport/profilereader.h2
-rw-r--r--src/plugins/qtsupport/qmldebugginglibrary.cpp8
-rw-r--r--src/plugins/qtsupport/qmldumptool.cpp16
-rw-r--r--src/plugins/qtsupport/qtkitconfigwidget.cpp41
-rw-r--r--src/plugins/qtsupport/qtkitconfigwidget.h15
-rw-r--r--src/plugins/qtsupport/qtkitinformation.cpp8
-rw-r--r--src/plugins/qtsupport/qtkitinformation.h10
-rw-r--r--src/plugins/qtsupport/qtoptionspage.cpp76
-rw-r--r--src/plugins/qtsupport/qtoptionspage.h3
-rw-r--r--src/plugins/qtsupport/qtoutputformatter.cpp5
-rw-r--r--src/plugins/qtsupport/qtoutputformatter.h4
-rw-r--r--src/plugins/qtsupport/qtparser.cpp13
-rw-r--r--src/plugins/qtsupport/qtsupport.pri1
-rw-r--r--src/plugins/qtsupport/qtsupport.pro5
-rw-r--r--src/plugins/qtsupport/qtsupport.qbs119
-rw-r--r--src/plugins/qtsupport/qtsupportplugin.cpp37
-rw-r--r--src/plugins/qtsupport/qtsupportplugin.h2
-rw-r--r--src/plugins/qtsupport/qtversionfactory.cpp12
-rw-r--r--src/plugins/qtsupport/qtversionfactory.h2
-rw-r--r--src/plugins/qtsupport/qtversionmanager.cpp24
-rw-r--r--src/plugins/qtsupport/qtversionmanager.h9
-rw-r--r--src/plugins/remotelinux/RemoteLinux.pluginspec.in2
-rw-r--r--src/plugins/remotelinux/abstractpackagingstep.cpp39
-rw-r--r--src/plugins/remotelinux/abstractpackagingstep.h11
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp36
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxdeployservice.h18
-rw-r--r--src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp2
-rw-r--r--src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp4
-rw-r--r--src/plugins/remotelinux/deployablefilesperprofile.cpp198
-rw-r--r--src/plugins/remotelinux/deployablefilesperprofile.h85
-rw-r--r--src/plugins/remotelinux/deploymentinfo.cpp204
-rw-r--r--src/plugins/remotelinux/deploymentsettingsassistant.cpp175
-rw-r--r--src/plugins/remotelinux/embeddedlinuxqtversion.cpp6
-rw-r--r--src/plugins/remotelinux/genericdirectuploadservice.cpp37
-rw-r--r--src/plugins/remotelinux/genericdirectuploadservice.h7
-rw-r--r--src/plugins/remotelinux/genericdirectuploadstep.cpp12
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp2
-rw-r--r--src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp1
-rw-r--r--src/plugins/remotelinux/linuxdevice.cpp2
-rw-r--r--src/plugins/remotelinux/profilesupdatedialog.cpp99
-rw-r--r--src/plugins/remotelinux/profilesupdatedialog.ui139
-rw-r--r--src/plugins/remotelinux/publickeydeploymentdialog.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinux.pro17
-rw-r--r--src/plugins/remotelinux/remotelinux.qbs74
-rw-r--r--src/plugins/remotelinux/remotelinux_dependencies.pri2
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp39
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfiguration.h13
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp4
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.cpp128
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.h19
-rw-r--r--src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.ui45
-rw-r--r--src/plugins/remotelinux/remotelinuxdeploymentdatamodel.cpp (renamed from src/plugins/remotelinux/deploymentinfo.h)76
-rw-r--r--src/plugins/remotelinux/remotelinuxdeploymentdatamodel.h (renamed from src/plugins/remotelinux/profilesupdatedialog.h)37
-rw-r--r--src/plugins/remotelinux/remotelinuxenvironmentreader.cpp2
-rw-r--r--src/plugins/remotelinux/remotelinuxpackageinstaller.cpp7
-rw-r--r--src/plugins/remotelinux/remotelinuxplugin.cpp4
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfiguration.cpp114
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfiguration.h14
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfigurationfactory.cpp46
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfigurationfactory.h10
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp16
-rw-r--r--src/plugins/remotelinux/remotelinuxrunconfigurationwidget.h2
-rw-r--r--src/plugins/remotelinux/remotelinuxruncontrol.cpp2
-rw-r--r--src/plugins/remotelinux/tarpackagecreationstep.cpp78
-rw-r--r--src/plugins/remotelinux/tarpackagecreationstep.h5
-rw-r--r--src/plugins/resourceeditor/qrceditor/qrceditor.cpp6
-rw-r--r--src/plugins/resourceeditor/qrceditor/resourcefile.cpp16
-rw-r--r--src/plugins/resourceeditor/qrceditor/resourceview.cpp3
-rw-r--r--src/plugins/resourceeditor/resourceeditor.pro2
-rw-r--r--src/plugins/resourceeditor/resourceeditor.qbs20
-rw-r--r--src/plugins/resourceeditor/resourceeditorfactory.cpp2
-rw-r--r--src/plugins/resourceeditor/resourceeditorw.h2
-rw-r--r--src/plugins/subversion/annotationhighlighter.h2
-rw-r--r--src/plugins/subversion/checkoutwizard.h12
-rw-r--r--src/plugins/subversion/checkoutwizardpage.h2
-rw-r--r--src/plugins/subversion/settingspage.cpp2
-rw-r--r--src/plugins/subversion/subversion.pro2
-rw-r--r--src/plugins/subversion/subversion.qbs35
-rw-r--r--src/plugins/subversion/subversioncontrol.cpp2
-rw-r--r--src/plugins/subversion/subversioneditor.cpp48
-rw-r--r--src/plugins/subversion/subversioneditor.h10
-rw-r--r--src/plugins/subversion/subversionplugin.cpp108
-rw-r--r--src/plugins/subversion/subversionplugin.h13
-rw-r--r--src/plugins/subversion/subversionsettings.cpp8
-rw-r--r--src/plugins/subversion/subversionsubmiteditor.cpp6
-rw-r--r--src/plugins/tasklist/taskfilefactory.cpp2
-rw-r--r--src/plugins/tasklist/tasklist.qbs24
-rw-r--r--src/plugins/tasklist/tasklistplugin.cpp20
-rw-r--r--src/plugins/texteditor/basefilefind.cpp29
-rw-r--r--src/plugins/texteditor/basefilefind.h6
-rw-r--r--src/plugins/texteditor/basehoverhandler.cpp10
-rw-r--r--src/plugins/texteditor/basetextdocument.cpp33
-rw-r--r--src/plugins/texteditor/basetextdocumentlayout.cpp94
-rw-r--r--src/plugins/texteditor/basetextdocumentlayout.h4
-rw-r--r--src/plugins/texteditor/basetexteditor.cpp467
-rw-r--r--src/plugins/texteditor/basetexteditor.h32
-rw-r--r--src/plugins/texteditor/basetexteditor_p.h80
-rw-r--r--src/plugins/texteditor/basetextmark.cpp3
-rw-r--r--src/plugins/texteditor/behaviorsettingspage.h2
-rw-r--r--src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp34
-rw-r--r--src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp23
-rw-r--r--src/plugins/texteditor/codeassist/genericproposalwidget.cpp47
-rw-r--r--src/plugins/texteditor/codeassist/keywordscompletionassist.cpp277
-rw-r--r--src/plugins/texteditor/codeassist/keywordscompletionassist.h113
-rw-r--r--src/plugins/texteditor/codeassist/quickfixassistprocessor.cpp4
-rw-r--r--src/plugins/texteditor/codestylepool.cpp8
-rw-r--r--src/plugins/texteditor/colorschemeedit.cpp3
-rw-r--r--src/plugins/texteditor/displaysettings.cpp17
-rw-r--r--src/plugins/texteditor/displaysettings.h3
-rw-r--r--src/plugins/texteditor/displaysettingspage.cpp19
-rw-r--r--src/plugins/texteditor/displaysettingspage.h5
-rw-r--r--src/plugins/texteditor/displaysettingspage.ui157
-rw-r--r--src/plugins/texteditor/fontsettings.cpp14
-rw-r--r--src/plugins/texteditor/fontsettings.h1
-rw-r--r--src/plugins/texteditor/fontsettingspage.cpp23
-rw-r--r--src/plugins/texteditor/fontsettingspage.h4
-rw-r--r--src/plugins/texteditor/generichighlighter/highlightdefinitionhandler.cpp59
-rw-r--r--src/plugins/texteditor/generichighlighter/highlighter.h4
-rw-r--r--src/plugins/texteditor/generichighlighter/highlightersettingspage.cpp8
-rw-r--r--src/plugins/texteditor/generichighlighter/highlightersettingspage.h4
-rw-r--r--src/plugins/texteditor/generichighlighter/keywordlist.cpp2
-rw-r--r--src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp2
-rw-r--r--src/plugins/texteditor/generichighlighter/rule.cpp2
-rw-r--r--src/plugins/texteditor/generichighlighter/specificrules.h2
-rw-r--r--src/plugins/texteditor/icodestylepreferences.cpp5
-rw-r--r--src/plugins/texteditor/icodestylepreferencesfactory.h4
-rw-r--r--src/plugins/texteditor/itexteditor.h1
-rw-r--r--src/plugins/texteditor/itextmark.cpp14
-rw-r--r--src/plugins/texteditor/itextmark.h8
-rw-r--r--src/plugins/texteditor/linenumberfilter.cpp3
-rw-r--r--src/plugins/texteditor/linenumberfilter.h3
-rw-r--r--src/plugins/texteditor/outlinefactory.cpp6
-rw-r--r--src/plugins/texteditor/plaintexteditor.cpp12
-rw-r--r--src/plugins/texteditor/plaintexteditorfactory.cpp4
-rw-r--r--src/plugins/texteditor/quickfix.h8
-rw-r--r--src/plugins/texteditor/refactoroverlay.cpp5
-rw-r--r--src/plugins/texteditor/snippets/snippeteditor.cpp2
-rw-r--r--src/plugins/texteditor/snippets/snippetssettingspage.cpp19
-rw-r--r--src/plugins/texteditor/snippets/snippetssettingspage.h4
-rw-r--r--src/plugins/texteditor/storagesettings.cpp10
-rw-r--r--src/plugins/texteditor/syntaxhighlighter.cpp36
-rw-r--r--src/plugins/texteditor/syntaxhighlighter.h2
-rw-r--r--src/plugins/texteditor/tabsettings.cpp5
-rw-r--r--src/plugins/texteditor/texteditor.pro26
-rw-r--r--src/plugins/texteditor/texteditor.qbs48
-rw-r--r--src/plugins/texteditor/texteditoractionhandler.cpp6
-rw-r--r--src/plugins/texteditor/texteditoroptionspage.cpp2
-rw-r--r--src/plugins/texteditor/texteditoroverlay.cpp7
-rw-r--r--src/plugins/texteditor/texteditorplugin.cpp9
-rw-r--r--src/plugins/texteditor/texteditorsettings.cpp36
-rw-r--r--src/plugins/texteditor/texteditorsettings.h20
-rw-r--r--src/plugins/todo/optionspage.cpp4
-rw-r--r--src/plugins/todo/todo.pro2
-rw-r--r--src/plugins/todo/todo.qbs12
-rw-r--r--src/plugins/updateinfo/updateinfo.qbs5
-rw-r--r--src/plugins/updateinfo/updateinfoplugin.cpp11
-rw-r--r--src/plugins/valgrind/callgrind/callgrindcallmodel.cpp3
-rw-r--r--src/plugins/valgrind/callgrind/callgrindcontroller.cpp30
-rw-r--r--src/plugins/valgrind/callgrind/callgrindcycledetection.cpp2
-rw-r--r--src/plugins/valgrind/callgrind/callgrinddatamodel.cpp66
-rw-r--r--src/plugins/valgrind/callgrind/callgrindfunction.cpp10
-rw-r--r--src/plugins/valgrind/callgrind/callgrindparsedata.cpp19
-rw-r--r--src/plugins/valgrind/callgrind/callgrindparser.cpp3
-rw-r--r--src/plugins/valgrind/callgrind/callgrindproxymodel.cpp6
-rw-r--r--src/plugins/valgrind/callgrind/callgrindrunner.cpp2
-rw-r--r--src/plugins/valgrind/callgrind/callgrindrunner.h2
-rw-r--r--src/plugins/valgrind/callgrindengine.cpp10
-rw-r--r--src/plugins/valgrind/callgrindhelper.cpp2
-rw-r--r--src/plugins/valgrind/callgrindtool.cpp20
-rw-r--r--src/plugins/valgrind/callgrindvisualisation.cpp7
-rw-r--r--src/plugins/valgrind/memcheck/memcheckrunner.cpp24
-rw-r--r--src/plugins/valgrind/memcheck/memcheckrunner.h2
-rw-r--r--src/plugins/valgrind/memcheckengine.cpp6
-rw-r--r--src/plugins/valgrind/memcheckerrorview.cpp21
-rw-r--r--src/plugins/valgrind/memchecktool.cpp52
-rw-r--r--src/plugins/valgrind/suppressiondialog.cpp2
-rw-r--r--src/plugins/valgrind/valgrind.qbs20
-rw-r--r--src/plugins/valgrind/valgrindconfigwidget.cpp13
-rw-r--r--src/plugins/valgrind/valgrindengine.cpp64
-rw-r--r--src/plugins/valgrind/valgrindengine.h12
-rw-r--r--src/plugins/valgrind/valgrindplugin.cpp8
-rw-r--r--src/plugins/valgrind/valgrindprocess.cpp22
-rw-r--r--src/plugins/valgrind/valgrindrunner.cpp12
-rw-r--r--src/plugins/valgrind/valgrindsettings.cpp46
-rw-r--r--src/plugins/valgrind/valgrindsettings.h4
-rw-r--r--src/plugins/valgrind/valgrindtool.cpp2
-rw-r--r--src/plugins/valgrind/xmlprotocol/error.cpp18
-rw-r--r--src/plugins/valgrind/xmlprotocol/modelhelpers.cpp10
-rw-r--r--src/plugins/valgrind/xmlprotocol/parser.cpp3
-rw-r--r--src/plugins/valgrind/xmlprotocol/stackmodel.cpp3
-rw-r--r--src/plugins/valgrind/xmlprotocol/suppression.cpp5
-rw-r--r--src/plugins/valgrind/xmlprotocol/threadedparser.cpp4
-rw-r--r--src/plugins/vcsbase/baseannotationhighlighter.cpp19
-rw-r--r--src/plugins/vcsbase/basevcseditorfactory.cpp2
-rw-r--r--src/plugins/vcsbase/basevcssubmiteditorfactory.cpp2
-rw-r--r--src/plugins/vcsbase/checkoutjobs.cpp9
-rw-r--r--src/plugins/vcsbase/checkoutwizarddialog.cpp2
-rw-r--r--src/plugins/vcsbase/cleandialog.cpp4
-rw-r--r--src/plugins/vcsbase/commonsettingspage.cpp2
-rw-r--r--src/plugins/vcsbase/commonvcssettings.cpp13
-rw-r--r--src/plugins/vcsbase/diffhighlighter.cpp12
-rw-r--r--src/plugins/vcsbase/diffhighlighter.h5
-rw-r--r--src/plugins/vcsbase/images/removesubmitfield.png (renamed from src/libs/utils/images/removesubmitfield.png)bin578 -> 578 bytes
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.cpp (renamed from src/libs/utils/submiteditorwidget.cpp)108
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.h (renamed from src/libs/utils/submiteditorwidget.h)30
-rw-r--r--src/plugins/vcsbase/submiteditorwidget.ui (renamed from src/libs/utils/submiteditorwidget.ui)6
-rw-r--r--src/plugins/vcsbase/submitfieldwidget.cpp (renamed from src/libs/utils/submitfieldwidget.cpp)17
-rw-r--r--src/plugins/vcsbase/submitfieldwidget.h (renamed from src/libs/utils/submitfieldwidget.h)8
-rw-r--r--src/plugins/vcsbase/submitfilemodel.cpp85
-rw-r--r--src/plugins/vcsbase/submitfilemodel.h21
-rw-r--r--src/plugins/vcsbase/vcsbase.pro13
-rw-r--r--src/plugins/vcsbase/vcsbase.qbs21
-rw-r--r--src/plugins/vcsbase/vcsbase.qrc1
-rw-r--r--src/plugins/vcsbase/vcsbaseclientsettings.cpp3
-rw-r--r--src/plugins/vcsbase/vcsbaseeditor.cpp288
-rw-r--r--src/plugins/vcsbase/vcsbaseeditor.h44
-rw-r--r--src/plugins/vcsbase/vcsbaseoptionspage.cpp2
-rw-r--r--src/plugins/vcsbase/vcsbaseplugin.cpp16
-rw-r--r--src/plugins/vcsbase/vcsbaseplugin.h1
-rw-r--r--src/plugins/vcsbase/vcsbasesubmiteditor.cpp81
-rw-r--r--src/plugins/vcsbase/vcsbasesubmiteditor.h22
-rw-r--r--src/plugins/vcsbase/vcsconfigurationpage.cpp4
-rw-r--r--src/plugins/welcome/welcome.qbs12
-rw-r--r--src/plugins/welcome/welcomeplugin.cpp34
-rw-r--r--src/share/share.qbs41
-rw-r--r--src/shared/cpaster/cgi.cpp16
-rw-r--r--src/shared/help/bookmarkmanager.cpp14
-rw-r--r--src/shared/help/indexwindow.cpp6
-rw-r--r--src/shared/proparser/ioutils.cpp6
-rw-r--r--src/shared/proparser/ioutils.h4
-rw-r--r--src/shared/proparser/profileevaluator.cpp26
-rw-r--r--src/shared/proparser/profileevaluator.h12
-rw-r--r--src/shared/proparser/proitems.cpp64
-rw-r--r--src/shared/proparser/proitems.h20
-rw-r--r--src/shared/proparser/qmake_global.h4
-rw-r--r--src/shared/proparser/qmakebuiltins.cpp127
-rw-r--r--src/shared/proparser/qmakeevaluator.cpp432
-rw-r--r--src/shared/proparser/qmakeevaluator.h71
-rw-r--r--src/shared/proparser/qmakeevaluator_p.h31
-rw-r--r--src/shared/proparser/qmakeglobals.cpp189
-rw-r--r--src/shared/proparser/qmakeglobals.h63
-rw-r--r--src/shared/proparser/qmakeparser.cpp90
-rw-r--r--src/shared/proparser/qmakeparser.h17
-rw-r--r--src/shared/qtlockedfile/qtlockedfile_win.cpp2
-rw-r--r--src/shared/qtsingleapplication/qtlocalpeer.cpp2
-rw-r--r--src/tools/QtcTool.qbs9
-rw-r--r--src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp33
-rw-r--r--src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro1
-rw-r--r--src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp22
-rw-r--r--src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri1
-rw-r--r--src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp60
-rw-r--r--src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro1
-rw-r--r--src/tools/examplesscanner/helpextractor.cpp8
-rw-r--r--src/tools/qml2puppet/qml2puppet.pro9
-rw-r--r--src/tools/qml2puppet/qml2puppet/qml2puppet.pro12
-rw-r--r--src/tools/qmlprofilertool/qmlprofilerapplication.cpp11
-rw-r--r--src/tools/qmlpuppet/qmlpuppet/qmlpuppet.pro2
-rw-r--r--src/tools/qtcdebugger/main.cpp2
-rw-r--r--src/tools/qtcdebugger/qtcdebugger.qbs2
-rw-r--r--src/tools/qtcreatorcrashhandler/backtracecollector.cpp128
-rw-r--r--src/tools/qtcreatorcrashhandler/backtracecollector.h64
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandler.cpp313
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandler.h69
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandlerdialog.cpp180
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandlerdialog.h71
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandlerdialog.ui147
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp134
-rw-r--r--src/tools/qtcreatorcrashhandler/crashhandlersetup.h36
-rw-r--r--src/tools/qtcreatorcrashhandler/main.cpp (renamed from src/plugins/qmldesigner/designercore/include/metainfoparser.h)61
-rw-r--r--src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.pro31
-rw-r--r--src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs33
-rw-r--r--src/tools/qtcreatorcrashhandler/utils.cpp (renamed from tests/auto/icheckbuild/tst_icheckbuild.cpp)26
-rw-r--r--src/tools/qtcreatorcrashhandler/utils.h (renamed from tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/QmlComponent01.qml)22
-rw-r--r--src/tools/qtcreatorwidgets/customwidgets.cpp5
-rw-r--r--src/tools/qtpromaker/main.cpp67
-rw-r--r--src/tools/sdktool/addkitoperation.cpp15
-rw-r--r--src/tools/sdktool/addqtoperation.cpp12
-rw-r--r--src/tools/sdktool/main.cpp2
-rw-r--r--src/tools/sdktool/rmkeysoperation.cpp4
-rw-r--r--src/tools/sdktool/rmkitoperation.cpp4
-rw-r--r--src/tools/sdktool/sdktool.pro2
-rw-r--r--src/tools/sdktool/sdktool.qbs14
-rw-r--r--src/tools/tools.pro9
-rw-r--r--src/tools/valgrindfake/valgrindfake.pro2
-rw-r--r--src/tools/win64interrupt/win64interrupt.c2
-rw-r--r--tests/auto/auto.pro1
-rw-r--r--tests/auto/cplusplus/ast/tst_ast.cpp154
-rw-r--r--tests/auto/cplusplus/checksymbols/checksymbols.pro4
-rw-r--r--tests/auto/cplusplus/checksymbols/tst_checksymbols.cpp452
-rw-r--r--tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp37
-rw-r--r--tests/auto/cplusplus/cplusplus.pro3
-rw-r--r--tests/auto/cplusplus/cxx11/data/aliasDecl.1.cpp4
-rw-r--r--tests/auto/cplusplus/cxx11/data/alignofAlignas.1.cpp2
-rw-r--r--tests/auto/cplusplus/cxx11/data/braceInitializers.1.cpp18
-rw-r--r--tests/auto/cplusplus/cxx11/data/braceInitializers.1.errors.txt0
-rw-r--r--tests/auto/cplusplus/cxx11/data/braceInitializers.2.cpp7
-rw-r--r--tests/auto/cplusplus/cxx11/data/braceInitializers.3.cpp6
-rw-r--r--tests/auto/cplusplus/cxx11/data/declType.1.cpp11
-rw-r--r--tests/auto/cplusplus/cxx11/data/defaultdeleteInitializer.1.cpp8
-rw-r--r--tests/auto/cplusplus/cxx11/data/enums.1.cpp11
-rw-r--r--tests/auto/cplusplus/cxx11/data/packExpansion.1.cpp4
-rw-r--r--tests/auto/cplusplus/cxx11/data/rangeFor.1.cpp5
-rw-r--r--tests/auto/cplusplus/cxx11/data/refQualifier.1.cpp21
-rw-r--r--tests/auto/cplusplus/cxx11/data/templateGreaterGreater.1.cpp10
-rw-r--r--tests/auto/cplusplus/cxx11/tst_cxx11.cpp82
-rw-r--r--tests/auto/cplusplus/findusages/tst_findusages.cpp159
-rw-r--r--tests/auto/cplusplus/preprocessor/tst_preprocessor.cpp114
-rw-r--r--tests/auto/cplusplus/semantic/tst_semantic.cpp4
-rw-r--r--tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter.cpp421
-rw-r--r--tests/auto/debugger/debugger.pro5
-rw-r--r--tests/auto/debugger/dumpers.pro30
-rw-r--r--tests/auto/debugger/gdb.pro2
-rw-r--r--tests/auto/debugger/namedemangler.pro3
-rw-r--r--tests/auto/debugger/olddumpers.pro23
-rw-r--r--tests/auto/debugger/tst_dumpers.cpp6234
-rw-r--r--tests/auto/debugger/tst_gdb.cpp18
-rw-r--r--tests/auto/debugger/tst_namedemangler.cpp5
-rw-r--r--tests/auto/debugger/tst_olddumpers.cpp2510
-rw-r--r--tests/auto/debugger/tst_version.cpp2
-rw-r--r--tests/auto/debugger/version.pro2
-rw-r--r--tests/auto/filesearch/tst_filesearch.cpp44
-rw-r--r--tests/auto/icheckbuild/icheckbuild.pro20
-rw-r--r--tests/auto/icheckbuild/ichecklib.cpp114
-rw-r--r--tests/auto/icheckbuild/parsemanager.cpp1528
-rw-r--r--tests/auto/icheckbuild/parsemanager.h304
-rw-r--r--tests/auto/ioutils/tst_ioutils.cpp2
-rw-r--r--tests/auto/profilewriter/tst_profilewriter.cpp4
-rw-r--r--tests/auto/qml/persistenttrie/completion.data10
-rw-r--r--tests/auto/qml/persistenttrie/intersect.data81
-rw-r--r--tests/auto/qml/persistenttrie/listAll.data26
-rw-r--r--tests/auto/qml/persistenttrie/merge.data81
-rw-r--r--tests/auto/qml/persistenttrie/persistenttrie.pro25
-rw-r--r--tests/auto/qml/persistenttrie/tst_testtrie.cpp374
-rw-r--r--tests/auto/qml/persistenttrie/tst_testtrie.h56
-rw-r--r--tests/auto/qml/qmldesigner/common/statichelpers.cpp13
-rw-r--r--tests/auto/qml/qmldesigner/coretests/coretests.pro36
-rw-r--r--tests/auto/qml/qmldesigner/coretests/setupPath.bat1
-rw-r--r--tests/auto/qml/qmldesigner/coretests/tst_testcore.cpp1592
-rw-r--r--tests/auto/qml/qmldesigner/coretests/tst_testcore.h8
-rw-r--r--tests/auto/qml/qmldesigner/testview.cpp7
-rw-r--r--tests/auto/qml/qmldesigner/testview.h3
-rw-r--r--tests/auto/qml/qmleditor/qmlcodeformatter/tst_qmlcodeformatter.cpp24
-rw-r--r--tests/auto/qml/qmljssimplereader/qmljssimplereader.pro12
-rw-r--r--tests/auto/qml/qmljssimplereader/tst_qmljssimplereader.cpp257
-rw-r--r--tests/auto/qml/qmlprojectmanager/fileformat/fileformat.pro1
-rw-r--r--tests/auto/qttest.pri1
l---------tests/cppmodelmanager/testdata/frameworks/My.framework/Frameworks1
l---------tests/cppmodelmanager/testdata/frameworks/My.framework/Headers1
l---------tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Headers1
-rw-r--r--tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/IncorrectVersion.h4
-rw-r--r--tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/Nested.h6
-rw-r--r--tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/CorrectVersion.h4
-rw-r--r--tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/Nested.h6
l---------tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/Current1
-rw-r--r--tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Headers/MyHeader.h6
l---------tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/Current1
-rw-r--r--tests/cppmodelmanager/testdata/include/header.h4
-rw-r--r--tests/cppmodelmanager/testdata/sources/test_modelmanager_framework_headers.cpp19
-rw-r--r--tests/manual/appwizards/main.cpp20
-rw-r--r--tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/apple.svg16
-rw-r--r--tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/qmldir1
-rw-r--r--tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/qmldir1
-rw-r--r--tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/tomato.svg16
-rw-r--r--tests/manual/cplusplus-frontend/cplusplus-frontend.cpp6
-rw-r--r--tests/manual/debugger/simple/deep/deep/simple_test_app.h2
-rw-r--r--tests/manual/debugger/simple/simple_test_app.cpp167
-rw-r--r--tests/manual/debugger/simple/simple_test_app.pro8
-rw-r--r--tests/manual/preprocessor/main.cpp11
-rw-r--r--tests/manual/preprocessor/preprocessor.pro4
-rw-r--r--tests/manual/proparser/main.cpp69
-rw-r--r--tests/manual/qml/testfiles/subcomponent.qml4
-rw-r--r--tests/manual/qml/testfiles_quick2/components/MyButton.qml36
-rw-r--r--tests/manual/qml/testfiles_quick2/empty.qml35
-rw-r--r--tests/manual/qml/testfiles_quick2/flipable.qml42
-rw-r--r--tests/manual/qml/testfiles_quick2/helloworld.qml40
-rw-r--r--tests/manual/qml/testfiles_quick2/helloworld_inverted.qml42
-rw-r--r--tests/manual/qml/testfiles_quick2/images.qml56
-rw-r--r--tests/manual/qml/testfiles_quick2/images/qtcreator.icobin0 -> 34108 bytes
-rw-r--r--tests/manual/qml/testfiles_quick2/images/qtcreator.jpgbin0 -> 10129 bytes
-rw-r--r--tests/manual/qml/testfiles_quick2/images/qtcreator.pngbin0 -> 15801 bytes
-rw-r--r--tests/manual/qml/testfiles_quick2/listmodel.qml39
-rw-r--r--tests/manual/qml/testfiles_quick2/listview.qml73
-rw-r--r--tests/manual/qml/testfiles_quick2/positioners.qml209
-rw-r--r--tests/manual/qml/testfiles_quick2/states.qml73
-rw-r--r--tests/manual/qml/testfiles_quick2/subcomponent.qml (renamed from tests/manual/appwizards/qmlimportscenario_02/subfolder1/myqmlapp.qml)23
-rw-r--r--tests/manual/qml/testfiles_quick2/testfiles_quick2.qmlproject (renamed from tests/manual/appwizards/qmlimportscenario_02/myqmlapp.qmlproject)9
-rw-r--r--tests/manual/qml/testfiles_quick2/usingbutton.qml40
-rw-r--r--tests/manual/qml/testfiles_quick2/views.qml198
-rw-r--r--tests/manual/ssh/remoteprocess/argumentscollector.cpp11
-rw-r--r--tests/manual/ssh/remoteprocess/argumentscollector.h4
-rw-r--r--tests/manual/ssh/remoteprocess/remoteprocesstest.h4
-rw-r--r--tests/manual/ssh/sftp/argumentscollector.cpp11
-rw-r--r--tests/manual/ssh/sftp/argumentscollector.h2
-rw-r--r--tests/manual/ssh/ssh.pro2
-rw-r--r--tests/manual/ssh/tunnel/argumentscollector.cpp175
-rw-r--r--tests/manual/ssh/tunnel/argumentscollector.h61
-rw-r--r--tests/manual/ssh/tunnel/main.cpp55
-rw-r--r--tests/manual/ssh/tunnel/tunnel.cpp165
-rw-r--r--tests/manual/ssh/tunnel/tunnel.h (renamed from src/plugins/debugger/qtmessagelogwindow.h)71
-rw-r--r--tests/manual/ssh/tunnel/tunnel.pro5
-rw-r--r--tests/manual/utils/tcpportsgatherer/tcpportsgatherer.pro2
-rw-r--r--tests/manual/utils/tcpportsgatherer/tcpportsgatherer.qbp2
-rw-r--r--tests/system/objects.map4
-rw-r--r--tests/system/shared/debugger.py17
-rw-r--r--tests/system/shared/editor_utils.py12
-rw-r--r--tests/system/shared/project_explorer.py2
-rw-r--r--tests/system/shared/utils.py6
-rwxr-xr-xtests/system/suite_CCOM/tst_CCOM02/test.py2
-rw-r--r--tests/system/suite_CSUP/tst_CSUP01/test.py7
-rw-r--r--tests/system/suite_CSUP/tst_CSUP02/test.py8
-rw-r--r--tests/system/suite_CSUP/tst_CSUP04/test.py10
-rw-r--r--tests/system/suite_CSUP/tst_CSUP05/test.py7
-rw-r--r--tests/system/suite_QMLS/shared/qmls.py7
-rw-r--r--tests/system/suite_QMLS/tst_QMLS03/test.py2
-rw-r--r--tests/system/suite_SCOM/tst_SCOM02/test.py2
-rw-r--r--tests/system/suite_SCOM/tst_SCOM04/test.py2
-rw-r--r--tests/system/suite_WELP/tst_WELP02/test.py4
-rw-r--r--tests/system/suite_debugger/tst_simple_debug/test.py2
-rw-r--r--tests/system/suite_editors/shared/testdata/main.c++11
-rw-r--r--tests/system/suite_editors/tst_qml_indent/test.py9
-rw-r--r--tests/system/suite_general/suite.conf2
-rw-r--r--tests/system/suite_general/tst_default_settings/test.py236
-rw-r--r--tests/system/suite_general/tst_default_settings/testdata/win_compiler_paths.tsv19
-rw-r--r--tests/system/suite_general/tst_openqt_creator/test.py6
-rw-r--r--tests/tools/cplusplus-ast2png/cplusplus-ast2png.cpp24
-rw-r--r--tests/tools/cplusplus-ast2png/cplusplus-ast2png.pro1
-rw-r--r--tests/tools/cplusplus-ast2png/dumpers.inc94
-rw-r--r--tests/tools/qml-ast2dot/main.cpp3
-rw-r--r--tests/valgrind/callgrind/callgrindparsertests.cpp90
-rw-r--r--tests/valgrind/callgrind/callgrindparsertests.pro1
-rw-r--r--tests/valgrind/memcheck/modeldemo.pro1
-rw-r--r--tests/valgrind/memcheck/parsertests.cpp13
-rw-r--r--tests/valgrind/memcheck/parsertests.pro1
-rw-r--r--tests/valgrind/memcheck/testrunner.cpp74
-rw-r--r--tests/valgrind/memcheck/testrunner.pro1
2469 files changed, 78326 insertions, 40500 deletions
diff --git a/.gitignore b/.gitignore
index caaca826c5..c919064366 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,7 @@
*.orig
*.rej
*.so
+*.so.*
*_pch.h.cpp
*_resource.rc
*.qm
@@ -28,15 +29,19 @@ moc_*.cpp
ui_*.h
qrc_*.cpp
Thumbs.db
+*.res
+*.rc
+*.embed.manifest
# qtcreator generated files
*.pro.user*
*.qmlproject.user*
*.pluginspec
-src/app/Info.plist
+*.json
+/src/app/Info.plist
app_version.h
-src/plugins/coreplugin/ide_version.h
-share/qtcreator/externaltools
+/src/plugins/coreplugin/ide_version.h
+/share/qtcreator/externaltools
phony.c
# xemacs temporary files
@@ -68,94 +73,128 @@ phony.c
*.pyc
# translation related:
-share/qtcreator/translations/*_tr.h
-share/qtcreator/translations/qtcreator_untranslated.ts
+/share/qtcreator/translations/*_tr.h
+/share/qtcreator/translations/qtcreator_untranslated.ts
# Directories to ignore
# ---------------------
-build
-debug
-lib/*
-lib64/*
-release
-doc/html/*
-doc/html-dev/*
-doc/api/html/*
-doc/pluginhowto/html/*
-dist/gdb/python
-.rcc
-.pch
-dist/gdb/qtcreator-*
-dist/gdb/source
-dist/gdb/staging
-ipch
-tmp
+debug/
+release/
+/lib/
+/lib64/
+/*-debug/
+/*-release/
+/doc/html/
+/doc/html-dev/
+/doc/api/html/
+/doc/pluginhowto/html/
+/dist/gdb/python/
+.moc/
+.obj/
+.pch/
+.rcc/
+.uic/
+/dist/gdb/qtcreator-*/
+/dist/gdb/source/
+/dist/gdb/staging/
+ipch/
+tmp/
# ignore both a directory as well as a symlink
-share/qtcreator/QtProject/
-share/qtcreator/QtProject
+/share/qtcreator/QtProject
# Binaries
# --------
-bin/*.dll
-bin/qtcreator
-bin/qtcreator_process_stub*
-bin/qtcreator_ctrlc_stub*
-bin/qtcreator.exe
-bin/qmlpuppet
-bin/qmlpuppet.exe
-bin/qml2puppet
-bin/qml2puppet.exe
-bin/qtpromaker
-bin/qtpromaker.exe
-share/doc/qtcreator/*.qch
-src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor
-src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.exe
-src/tools/cplusplus-update-frontend/cplusplus-update-frontend
-src/tools/cplusplus-update-frontend/cplusplus-update-frontend.exe
-src/tools/qml/qmldump/qmldump
-src/tools/examplesscanner/examplesscanner
-src/tools/valgrindfake/valgrind-fake
-bin/*.exe
+*.dll
+*.exe
+/bin/cpaster
+/bin/qmlpuppet
+/bin/qml2puppet
+/bin/qtcreator
+/bin/qtcreator_crash_handler
+/bin/qtcreator_ctrlc_stub
+/bin/qtcreator_process_stub
+/bin/qtpromaker
+/bin/sdktool
+/share/doc/qtcreator/*.qch
+/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor
+/src/tools/cplusplus-update-frontend/cplusplus-update-frontend
+/src/tools/qml/qmldump/qmldump
+/src/tools/examplesscanner/examplesscanner
+/src/tools/valgrindfake/valgrind-fake
# Tests
#------
-tests/manual/cplusplus-frontend/cplusplus-frontend
-tests/manual/cplusplus-frontend/cplusplus-frontend.exe
-tests/manual/qml-ast2dot/qml-ast2dot
-tests/manual/debugger/simple/libsimple_test_plugin.*dylib
-tests/manual/debugger/simple/simple_test_app
-tests/manual/plain-cplusplus/plain-c++
-tests/manual/preprocessor/pp
-tests/tools/cplusplus-ast2png/cplusplus-ast2png
-tests/tools/cplusplus-ast2png/cplusplus-ast2png.exe
-tests/auto/cplusplus/codegen/tst_codegen
-tests/auto/cplusplus/ast/tst_ast
-tests/auto/cplusplus/codeformatter/tst_codeformatter
-tests/auto/cplusplus/findusages/tst_findusages
-tests/auto/cplusplus/lookup/tst_lookup
-tests/auto/cplusplus/preprocessor/tst_preprocessor
-tests/auto/cplusplus/semantic/tst_semantic
-tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter
-tests/auto/qml/qmldesigner/bauhaustests/tst_bauhaus
-tests/auto/qml/qmldesigner/coretests/tst_qmldesigner_core
-tests/auto/qml/qmldesigner/propertyeditortests/tst_propertyeditor
-tests/auto/profilewriter/tst_profilewriter
-tests/auto/externaltool/tst_externaltool
-tests/valgrind/memcheck/modeldemo
-tests/valgrind/memcheck/parsertests
-tests/valgrind/memcheck/testapps/free1/free1
-tests/valgrind/memcheck/testapps/free2/free2
-tests/valgrind/memcheck/testapps/invalidjump/invalidjump
-tests/valgrind/memcheck/testapps/leak1/leak1
-tests/valgrind/memcheck/testapps/leak2/leak2
-tests/valgrind/memcheck/testapps/leak3/leak3
-tests/valgrind/memcheck/testapps/leak4/leak4
-tests/valgrind/memcheck/testapps/overlap/overlap
-tests/valgrind/memcheck/testapps/syscall/syscall
-tests/valgrind/memcheck/testapps/uninit1/uninit1
-tests/valgrind/memcheck/testapps/uninit2/uninit2
-tests/valgrind/memcheck/testapps/uninit3/uninit3
-tests/valgrind/memcheck/testrunner
-tests/valgrind/callgrind/callgrindparsertests
-tests/valgrind/callgrind/modeltest
+/tests/manual/cplusplus-frontend/cplusplus-frontend
+/tests/manual/qml-ast2dot/qml-ast2dot
+/tests/manual/debugger/simple/libsimple_test_plugin.*dylib
+/tests/manual/debugger/simple/simple_test_app
+/tests/manual/plain-cplusplus/plain-c++
+/tests/manual/preprocessor/pp
+/tests/tools/cplusplus-ast2png/cplusplus-ast2png
+/tests/auto/aggregation/tst_aggregation
+/tests/auto/changeset/tst_changeset
+/tests/auto/cplusplus/checksymbols/tst_checksymbols
+/tests/auto/cplusplus/codegen/tst_codegen
+/tests/auto/cplusplus/cxx11/tst_cxx11
+/tests/auto/cplusplus/misc/tst_misc
+/tests/auto/cplusplus/simplifytypes/tst_simplifytypes
+/tests/auto/cplusplus/ast/tst_ast
+/tests/auto/cplusplus/codeformatter/tst_codeformatter
+/tests/auto/cplusplus/findusages/tst_findusages
+/tests/auto/cplusplus/lookup/tst_lookup
+/tests/auto/cplusplus/preprocessor/tst_preprocessor
+/tests/auto/cplusplus/semantic/tst_semantic
+/tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter
+/tests/auto/debugger/tst_dumpers
+/tests/auto/debugger/tst_gdb
+/tests/auto/debugger/tst_namedemangler
+/tests/auto/debugger/tst_olddumpers
+/tests/auto/debugger/tst_version
+/tests/auto/environment/tst_environment
+/tests/auto/extensionsystem/pluginmanager/tst_pluginmanager
+/tests/auto/extensionsystem/pluginspec/tst_pluginspec
+/tests/auto/externaltool/tst_externaltool
+/tests/auto/fakevim/tst_fakevim
+/tests/auto/filesearch/tst_filesearch
+/tests/auto/generichighlighter/highlighterengine/tst_highlighterengine
+/tests/auto/generichighlighter/specificrules/tst_specificrules
+/tests/auto/ioutils/tst_ioutils
+/tests/auto/profilewriter/tst_profilewriter
+/tests/auto/qml/qmldesigner/bauhaustests/tst_bauhaus
+/tests/auto/qml/qmldesigner/coretests/tst_qmldesigner_core
+/tests/auto/qml/qmldesigner/propertyeditortests/tst_propertyeditor
+/tests/auto/qtcprocess/tst_qtcprocess
+/tests/auto/utils/fileutils/tst_fileutils
+/tests/auto/utils_stringutils/tst_utils_stringutils
+/tests/manual/debugger/gui/gui
+/tests/manual/debugger/helper/helper
+/tests/manual/fakevim/tst_fakevim
+/tests/manual/preprocessor/tst_pp
+/tests/manual/process/process
+/tests/manual/proparser/testreader
+/tests/manual/ssh/errorhandling/errorhandling
+/tests/manual/ssh/remoteprocess/remoteprocess
+/tests/manual/ssh/sftp/sftp
+/tests/manual/ssh/sftpfsmodel/sftpfsmodel
+/tests/manual/ssh/shell/shell
+/tests/manual/ssh/tunnel/tunnel
+/tests/manual/utils/tcpportsgatherer/tst_tcpportsgatherer
+/tests/tools/qml-ast2dot/qml-ast2dot
+/tests/valgrind/memcheck/modeldemo
+/tests/valgrind/memcheck/parsertests
+/tests/valgrind/memcheck/testapps/free1/free1
+/tests/valgrind/memcheck/testapps/free2/free2
+/tests/valgrind/memcheck/testapps/invalidjump/invalidjump
+/tests/valgrind/memcheck/testapps/leak1/leak1
+/tests/valgrind/memcheck/testapps/leak2/leak2
+/tests/valgrind/memcheck/testapps/leak3/leak3
+/tests/valgrind/memcheck/testapps/leak4/leak4
+/tests/valgrind/memcheck/testapps/overlap/overlap
+/tests/valgrind/memcheck/testapps/syscall/syscall
+/tests/valgrind/memcheck/testapps/uninit1/uninit1
+/tests/valgrind/memcheck/testapps/uninit2/uninit2
+/tests/valgrind/memcheck/testapps/uninit3/uninit3
+/tests/valgrind/memcheck/testrunner
+/tests/valgrind/callgrind/callgrindparsertests
+/tests/valgrind/callgrind/modeltest
diff --git a/README b/README
index a7f33a85ac..f93fe62fe3 100644
--- a/README
+++ b/README
@@ -24,13 +24,18 @@ Prerequisites:
* On Mac: XCode 2.5 or later, compiling on 10.4 requires setting the
environment variable QTC_TIGER_COMPAT before running qmake
-We recommend that you build Qt Creator not in the source directory, but in a
-separate directory. To do that, use the following commands:
+You can build Qt Creator with
-mkdir $BUILD_DIRECTORY
-cd $BUILD_DIRECTORY
-qmake $SOURCE_DIRECTORY/qtcreator.pro
-make (or mingw32-make or nmake or jom, depending on your platform)
+ cd $SOURCE_DIRECTORY
+ qmake -r
+ make (or mingw32-make or nmake or jom, depending on your platform)
+
+Note: If you get "make: *** No targets specified and no makefile found. Stop."
+ on Mac OS X, you need to additionally pass "-spec macx-g++" to qmake.
+
+Installation ("make install") is not needed. It is however possible, using
+
+ make install INSTALL_ROOT=$INSTALL_DIRECTORY
Compiling Qt Quick Designer
---------------------------
diff --git a/dist/gdb/Makefile.linux b/dist/gdb/Makefile.linux
index 1c7d6da33b..94bf99bca9 100644
--- a/dist/gdb/Makefile.linux
+++ b/dist/gdb/Makefile.linux
@@ -5,18 +5,13 @@ staging=${broot}/staging
pyversion=2.7
expatversion=2.0.1
arch=`uname -sm | sed 's/ /-/g' | tr A-Z a-z`
-version=7.4.1
+version=7.5
targetdir=${broot}/qtcreator-gdb-${version}
gdbtargets=$(addprefix ${targetdir}/gdb-, ${targets})
packagename=qtcreator-gdb-${version}-${arch}.tar.gz
all:package
-gdb-7.4: override version=7.4
-
-gdb-7.4: ${staging}/lib/libpython${pyversion}.a ${staging}/lib/libexpat.a
- ${MAKE} version=${version}
-
clean:
rm -rf ${broot}/qtcreator-gdb-* ${staging}/gdb-* qtcreator-gdb-*.tar.gz
@@ -73,7 +68,6 @@ ${staging}/gdb-${version}/configure: ${source}/gdb-${version}.tar.bz2 | makestag
cd gdb-${version} && \
touch configure && \
patch -p2 < ${broot}/patches/pythonhome-7.4.patch && \
- patch -p1 < ${broot}/patches/gdb-buildid-locate.patch && \
patch -p1 < ${broot}/patches/gdb-ipv6.patch && \
patch -p1 < ${broot}/patches/gdb-work-around-trk-single-step.patch
diff --git a/dist/gdb/Makefile.mingw b/dist/gdb/Makefile.mingw
index e8e0f80563..acc8a84173 100644
--- a/dist/gdb/Makefile.mingw
+++ b/dist/gdb/Makefile.mingw
@@ -6,7 +6,7 @@ pyversion=2.7
pydir=${broot}/python
expatversion=2.0.1
iconvversion=1.14
-version=7.4.1
+version=7.5
targetdir=${broot}/qtcreator-gdb-${version}
gdbtargets=$(addprefix ${targetdir}/gdb-, ${targets})
packageparts=${targetdir}/lib ${targetdir}/lib ${targetdir}/libiconv-2.dll ${targetdir}/python27.dll ${targetdir}/libexpat-1.dll
@@ -15,11 +15,6 @@ packagename=qtcreator-gdb-${version}-${arch}.tar.gz
all: package
-gdb-7.4: override version=7.4
-
-gdb-7.4:
- ${MAKE} version=${version}
-
clean:
rm -rf ${broot}/qtcreator-gdb-* ${staging}/gdb-*
diff --git a/dist/gdb/Makefile.osx b/dist/gdb/Makefile.osx
index 6b03bf6b29..20517d01ea 100644
--- a/dist/gdb/Makefile.osx
+++ b/dist/gdb/Makefile.osx
@@ -1,22 +1,17 @@
broot=${PWD}
source=${broot}/source
-targets=x86_64-unknown-linux-gnu i686-unknown-linux-gnu arm-none-linux-gnueabi
+targets=x86_64-unknown-linux-gnu i686-unknown-linux-gnu arm-none-linux-gnueabi x86_64-apple-darwin10
staging=${broot}/staging
pyversion=2.7
expatversion=2.0.1
arch=`uname -sm | sed 's/ /-/g' | tr A-Z a-z`
-version=7.4.1
+version=7.5
targetdir=${broot}/qtcreator-gdb-${version}
gdbtargets=$(addprefix ${targetdir}/gdb-, ${targets})
packagename=qtcreator-gdb-${version}-${arch}.tar.gz
all:package
-gdb-7.4: override version=7.4
-
-gdb-7.4: ${staging}/lib/libpython${pyversion}.a ${staging}/lib/libexpat.a
- ${MAKE} version=${version}
-
clean:
rm -rf ${broot}/qtcreator-gdb-* ${staging}/gdb-* qtcreator-gdb-*.tar.gz
@@ -71,7 +66,6 @@ ${staging}/gdb-${version}/configure: ${source}/gdb-${version}.tar.bz2 | makestag
tar xf ${source}/gdb-${version}.tar.bz2 && \
cd gdb-${version} && \
touch configure && \
- patch -p2 < ${broot}/patches/pythonhome-${version}.patch && \
patch -p1 < ${broot}/patches/gdb-ipv6.patch
${gdbtargets}: ${targetdir}/gdb-%: ${staging}/gdb-${version}/configure ${staging}/lib/libpython${pyversion}.a ${staging}/lib/libexpat.a | maketargetdir
diff --git a/dist/gdb/patches/gdb-ipv6.patch b/dist/gdb/patches/gdb-ipv6.patch
index f51d51f1d8..0e67e5cd10 100644
--- a/dist/gdb/patches/gdb-ipv6.patch
+++ b/dist/gdb/patches/gdb-ipv6.patch
@@ -59,7 +59,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
#include "server.h"
#include "terminal.h"
#include "target.h"
-@@ -62,6 +64,9 @@
+@@ -63,6 +65,9 @@
#if USE_WIN32API
#include <winsock2.h>
@@ -69,8 +69,8 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
#endif
#if __QNX__
-@@ -106,7 +111,7 @@ int remote_debug = 0;
- struct ui_file *gdb_stdlog;
+@@ -109,7 +114,7 @@ struct ui_file *gdb_stdlog;
+ static int remote_is_stdio = 0;
static gdb_fildes_t remote_desc = INVALID_DESCRIPTOR;
-static gdb_fildes_t listen_desc = INVALID_DESCRIPTOR;
@@ -78,7 +78,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
/* FIXME headerize? */
extern int using_threads;
-@@ -145,15 +150,17 @@ enable_async_notification (int fd)
+@@ -156,15 +161,17 @@ enable_async_notification (int fd)
static int
handle_accept_event (int err, gdb_client_data client_data)
{
@@ -100,7 +100,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
perror_with_name ("Accept failed");
/* Enable TCP keep alive process. */
-@@ -167,27 +174,55 @@ handle_accept_event (int err, gdb_client
+@@ -178,27 +185,55 @@ handle_accept_event (int err, gdb_client
setsockopt (remote_desc, IPPROTO_TCP, TCP_NODELAY,
(char *) &tmp, sizeof (tmp));
@@ -167,7 +167,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
enable_async_notification (remote_desc);
-@@ -213,12 +248,15 @@ remote_prepare (char *name)
+@@ -224,12 +259,15 @@ remote_prepare (char *name)
{
char *port_str;
#ifdef USE_WIN32API
@@ -186,9 +186,9 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
+ char *host_str = NULL;
+ char back_host[128], back_port[32];
- port_str = strchr (name, ':');
- if (port_str == NULL)
-@@ -227,8 +265,24 @@ remote_prepare (char *name)
+ remote_is_stdio = 0;
+ if (strcmp (name, STDIO_CONNECTION_NAME) == 0)
+@@ -249,8 +287,24 @@ remote_prepare (char *name)
return;
}
@@ -215,7 +215,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
fatal ("Bad port argument: %s", name);
#ifdef USE_WIN32API
-@@ -241,24 +295,181 @@ remote_prepare (char *name)
+@@ -263,24 +317,181 @@ remote_prepare (char *name)
}
#endif
@@ -241,14 +241,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
+ err = getaddrinfo(host_str, port_str, &hints, &ainfo0);
+ if (err)
+ fatal ("%s for %s", gai_strerror(err), name);
-
-- sockaddr.sin_family = PF_INET;
-- sockaddr.sin_port = htons (port);
-- sockaddr.sin_addr.s_addr = INADDR_ANY;
--
-- if (bind (listen_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
-- || listen (listen_desc, 1))
-- perror_with_name ("Can't bind address");
++
+ for (ainfo = ainfo0; ainfo; ainfo = ainfo->ai_next)
+ {
+ int current_port, tmp;
@@ -341,7 +334,14 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
+ s = -1;
+ continue;
+ }
-+
+
+- sockaddr.sin_family = PF_INET;
+- sockaddr.sin_port = htons (port);
+- sockaddr.sin_addr.s_addr = INADDR_ANY;
+-
+- if (bind (listen_desc, (struct sockaddr *) &sockaddr, sizeof (sockaddr))
+- || listen (listen_desc, 1))
+- perror_with_name ("Can't bind address");
+ {
+ struct sockaddr_storage address;
+ socklen_t alen = (socklen_t) sizeof (address);
@@ -380,7 +380,7 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
+ back_host, back_port);
+ }
+ }
-+
+
+ if (socktable_size < nsock + 3)
+ {
+ socktable = xrealloc (socktable,
@@ -399,11 +399,11 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
+ /* Bound socktable from both ends, so an inner pointer can still
+ find the whole array. */
+ socktable[++nsock] = INVALID_DESCRIPTOR;
-
- transport_is_reliable = 1;
++
++ transport_is_reliable = 1;
+ fprintf (stderr, "Listening on port %d\n", port);
+ fflush (stderr);
-+ transport_is_reliable = 1;
+ transport_is_reliable = 1;
+ if (listening_sockets)
+ fatal ("Multiple concurrent remote_open not supported.");
+
@@ -411,12 +411,13 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
}
/* Open a connection to a remote debugger.
-@@ -268,8 +479,25 @@ void
+@@ -290,8 +501,24 @@
remote_open (char *name)
{
char *port_str;
+ char *host_start, *host_end;
-+
+
+- port_str = strchr (name, ':');
+ host_start = name;
+ if (host_start[0] == '[')
+ {
@@ -433,78 +434,11 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
+ port_str = strchr (name, ':');
+ host_end = port_str;
+ }
-
-- port_str = strchr (name, ':');
- if (port_str == NULL)
- {
#ifdef USE_WIN32API
-@@ -278,21 +506,21 @@ remote_open (char *name)
- struct stat statbuf;
-
- if (stat (name, &statbuf) == 0
-- && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
-- remote_desc = open (name, O_RDWR);
-+ && (S_ISCHR (statbuf.st_mode) || S_ISFIFO (statbuf.st_mode)))
-+ remote_desc = open (name, O_RDWR);
- else
-- {
-- errno = EINVAL;
-- remote_desc = -1;
-- }
-+ {
-+ errno = EINVAL;
-+ remote_desc = -1;
-+ }
-
- if (remote_desc < 0)
-- perror_with_name ("Could not open remote device");
-+ perror_with_name ("Could not open remote device");
-
- #ifdef HAVE_TERMIOS
- {
-- struct termios termios;
-- tcgetattr (remote_desc, &termios);
-+ struct termios termios;
-+ tcgetattr (remote_desc, &termios);
-
- termios.c_iflag = 0;
- termios.c_oflag = 0;
-@@ -302,14 +530,14 @@ remote_open (char *name)
- termios.c_cc[VMIN] = 1;
- termios.c_cc[VTIME] = 0;
-
-- tcsetattr (remote_desc, TCSANOW, &termios);
-+ tcsetattr (remote_desc, TCSANOW, &termios);
- }
- #endif
-
- #ifdef HAVE_TERMIO
- {
-- struct termio termio;
-- ioctl (remote_desc, TCGETA, &termio);
-+ struct termio termio;
-+ ioctl (remote_desc, TCGETA, &termio);
-
- termio.c_iflag = 0;
- termio.c_oflag = 0;
-@@ -319,13 +547,13 @@ remote_open (char *name)
- termio.c_cc[VMIN] = 1;
- termio.c_cc[VTIME] = 0;
-
-- ioctl (remote_desc, TCSETA, &termio);
-+ ioctl (remote_desc, TCSETA, &termio);
- }
- #endif
-
- #ifdef HAVE_SGTTY
- {
-- struct sgttyb sg;
-+ struct sgttyb sg;
-
- ioctl (remote_desc, TIOCGETP, &sg);
- sg.sg_flags = RAW;
-@@ -343,22 +571,17 @@ remote_open (char *name)
- }
+ if (port_str == NULL)
+ error ("Only <host>:<port> is supported on this platform.");
+@@ -381,22 +608,17 @@ remote_open (char *name)
+ #endif /* USE_WIN32API */
else
{
- int port;
@@ -536,8 +470,6 @@ diff -rup gdb-7.4-clean/gdb/gdbserver/remote-utils.c gdb-7.4/gdb/gdbserver/remot
}
}
-Only in gdb-7.4/gdb/gdbserver: remote-utils.c.orig
-Only in gdb-7.4/gdb/gdbserver: remote-utils.c.rej
diff -rup gdb-7.4-clean/gdb/ser-tcp.c gdb-7.4/gdb/ser-tcp.c
--- gdb-7.4-clean/gdb/ser-tcp.c 2012-03-30 15:07:01.540553998 +0200
+++ gdb-7.4/gdb/ser-tcp.c 2012-03-30 15:08:39.484553844 +0200
diff --git a/doc/api/coding-style.qdoc b/doc/api/coding-style.qdoc
index 3abaec72f5..a8afd6a398 100644
--- a/doc/api/coding-style.qdoc
+++ b/doc/api/coding-style.qdoc
@@ -254,6 +254,11 @@
}
\endcode
+ \section3 Comments
+
+ In general, put one space after "//". To align text in multiline
+ comments, you can insert multiple spaces.
+
\section2 Braces
As a base rule, place the left curly brace on the same line as the
diff --git a/doc/api/plugin-specifications.qdoc b/doc/api/plugin-specifications.qdoc
index 653c9a4b72..129f36b44d 100644
--- a/doc/api/plugin-specifications.qdoc
+++ b/doc/api/plugin-specifications.qdoc
@@ -31,7 +31,8 @@
\section2 Main Tag
The root tag is \c plugin. It has the mandatory attributes \c name
- and \c version, and the optional attributes \c compatVersion and \c experimental.
+ and \c version, and the optional attributes \c compatVersion, \c experimental
+ and \c disabledByDefault.
\table
\header
\o Tag
@@ -68,9 +69,16 @@
(inclusive).
\row
\o experimental
- \o Optional. Can be \c yes or \c no, defaults to \c no.
+ \o Optional. Can be \c true or \c false, defaults to \c false.
Experimental plugins are not loaded by default but must be explicitly
- enabled by the user.
+ enabled by the user. This attribute should be enabled for new plugins which have the
+ potential to negatively affect the user experience.
+ \row
+ \o disabledByDefault
+ \o Optional. Can be \c true or \c false, defaults to \c false.
+ If set, the respective plugin is not loaded by default but must be explicitly
+ enabled by the user. This should be done for plugins which are not expected
+ to be used by so many people as to justify the additional resource consumption.
\endtable
\section2 Plugin-describing Tags
diff --git a/doc/src/debugger/creator-debugger.qdoc b/doc/src/debugger/creator-debugger.qdoc
index 046baa166a..134140135e 100644
--- a/doc/src/debugger/creator-debugger.qdoc
+++ b/doc/src/debugger/creator-debugger.qdoc
@@ -410,6 +410,8 @@
you are debugging C++ or QML. Frequently used views are shown by
default and rarely used ones are hidden. To change the default settings,
select \gui {Window > Views}, and then select views to display or hide.
+ Alternatively, you can enable or disable views from the context menu
+ of the title bar of any visible debugger view.
\image qtcreator-debugger-views.png "Debug mode views"
@@ -760,6 +762,20 @@
and \gui{Step Over}. By default, both \gui{Disassembler} and
\gui{Registers} view are hidden.
+ \section2 Creating Snapshots
+
+ A snapshot contains the complete state of the debugged program
+ at a time, including the full memory contents.
+
+ To create snapshots of a debugged program, select \gui Create in the
+ context menu in the \gui Snapshot view.
+
+ Double-click on entries in the snapshot view to switch between
+ snapshots. The debugger views are updated to reflect the
+ state of the program at time of taking the snapshot.
+
+ By default, the \gui{Snapshots} view is hidden.
+
*/
@@ -864,15 +880,17 @@
is also easier to extend as the script is less dependent on the
actual Qt version and does not need compilation.
- To extend the shipped Python based debugging helpers for custom types,
- define one Python function per user defined type in the
- GDB startup file. By default, the following startup file is used:
- \c{~/.gdbinit}. To use another file, select \gui {Tools > Options >
- Debugger > GDB}
- and specify a filename in the \gui {GDB startup script} field.
+ To extend the shipped Python based debugging helpers for custom
+ types, add debugging helper implementations to the GDB startup file
+ \c{~/.gdbinit}, or specify them directly in the \gui{Additional
+ Startup Commands} in \gui {Tools > Options > Debugger > GDB}.
- The function name has to be qdump__NS__Foo, where NS::Foo is the class
- or class template to be examined. Nested namespaces are possible.
+ The implementation of a debugging helper typically
+ consists of a single Python function, which needs to be named
+ \c{qdump__NS__Foo}, where \c{NS::Foo} is the class
+ or class template to be examined. Note that the \c{::} scope
+ resolution operator is replaced by double underscores \c{__}.
+ Nested namespaces are possible.
The debugger plugin calls this function whenever you want to
display an object of this type. The function is passed the following
@@ -899,9 +917,6 @@
alloc = d_ptr["alloc"]
size = d_ptr["size"]
- check(0 <= size and size <= alloc and alloc <= 1000 * 1000 * 1000)
- checkRef(d_ptr["ref"])
-
innerType = templateArgument(value.type, 0)
d.putItemCount(size)
d.putNumChild(size)
@@ -1052,7 +1067,12 @@
\o \gui{putCallItem(self, name, value, func, *args)} -
Uses GDB to call the function \c func on the value specified by
- \a {value} and output the resulting item.
+ \a {value} and output the resulting item. Use \c{putCallItem}
+ only if there is no other way to access the data.
+ Calls cannot be executed
+ when inspecting a core file, they are expensive to execute
+ and have the potential to change the state of the debugged
+ program.
\o \gui{putItem(self, value)} - The "master function", handling
basic types, references, pointers and enums directly, iterates
diff --git a/doc/src/editors/creator-coding-edit-mode.qdoc b/doc/src/editors/creator-coding-edit-mode.qdoc
index 928b44ec63..1b37d0ca17 100644
--- a/doc/src/editors/creator-coding-edit-mode.qdoc
+++ b/doc/src/editors/creator-coding-edit-mode.qdoc
@@ -118,7 +118,9 @@
\section1 Moving to Symbol Definition or Declaration
You can move directly to the definition or the declaration of a symbol by
- holding the \key Ctrl and clicking the symbol.
+ holding the \key Ctrl and clicking the symbol. If you have multiple splits
+ opened, link will be opened in next split. To open it in current split,
+ hold \key Ctrl and \key Alt while clicking on the symbol.
To enable this moving function, in \gui Tools > \gui{Options} >
\gui{Text Editor} > \gui Behavior, select \gui{Enable mouse navigation}.
@@ -126,11 +128,17 @@
You can also select the symbol and press \key F2, or right-click the symbol
and select \gui {Follow Symbol Under Cursor} to move to its definition or
declaration. This feature is supported for namespaces, classes, methods,
- variables, include statements, and macros.
+ variables, include statements, and macros. If you have multiple splits
+ opened, the result will be shown in another split.
To switch between the definition and declaration of a symbol, press
\key {Shift+F2} or right-click the symbol and select \gui {Switch Between
- Method Declaration/Definition}.
+ Method Declaration/Definition}. If you have multiple splits opened, the
+ result will be shown in another split.
+
+ Although links are opened in another split by default, this can be disabled
+ in \gui Tools > \gui{Options} > \gui{Text Editor} > \gui Display, by
+ unchecking \gui{Open Links in Next Split}.
\section1 Using Update Code Model
diff --git a/doc/src/editors/creator-editors.qdoc b/doc/src/editors/creator-editors.qdoc
index add0d6b183..60527ccb0e 100644
--- a/doc/src/editors/creator-editors.qdoc
+++ b/doc/src/editors/creator-editors.qdoc
@@ -1172,6 +1172,28 @@
\endlist
+ The \gui{Preserve Case when Replacing} option can be selected to preserve
+ the case of the original text when replacing. This option is not compatible
+ with the \gui {Regular Expressions} search option, and will thus be
+ disabled when regular expressions are used. When the option is used, the
+ case of the occurrence will be conserved, according to the following rules:
+
+ \list
+
+ \o All upper-case occurrences are replaced with the upper-case new text.
+
+ \o All lower-case occurrences are replaced with the lower-case new text.
+
+ \o Capitalized occurrences are replaced with the capitalized new text.
+
+ \o Other occurrences are replaced with the new text as entered.
+
+ \o If an occurrence and the new text have the same prefix or suffix,
+ then the case of the prefix and/or suffix are preserved, and the
+ other rules are applied on the rest of the occurrence only.
+
+ \endlist
+
\section1 Advanced Search
To search through projects, files on a file system or the currently open
diff --git a/doc/src/howto/creator-cli.qdoc b/doc/src/howto/creator-cli.qdoc
index 3606b7fcca..2fb12005f3 100644
--- a/doc/src/howto/creator-cli.qdoc
+++ b/doc/src/howto/creator-cli.qdoc
@@ -54,6 +54,12 @@
\endlist
+ To open a project that is located in a particular folder, you can pass on the folder
+ name as a command line argument. \QC looks for a session that matches the folder name and
+ loads it. Or it looks for a project file in the folder and opens it. For example:
+
+ \c {qtcreator .}
+
The following table summarizes the available options:
\table
diff --git a/doc/src/howto/creator-vcs.qdoc b/doc/src/howto/creator-vcs.qdoc
index 0ef423249a..f3514e448b 100644
--- a/doc/src/howto/creator-vcs.qdoc
+++ b/doc/src/howto/creator-vcs.qdoc
@@ -199,6 +199,7 @@
display a description of the change including the diff.
Right-clicking on an identifier brings up a context menu that lets you
show annotation views of previous versions (see \l{Annotating Files}).
+ With Git you can also choose to cherry-pick or revert a change.
\image qtcreator-vcs-log.png
diff --git a/doc/src/qtquick/qtquick-creating.qdoc b/doc/src/qtquick/qtquick-creating.qdoc
index e6ee96d48b..a2dd925780 100644
--- a/doc/src/qtquick/qtquick-creating.qdoc
+++ b/doc/src/qtquick/qtquick-creating.qdoc
@@ -62,7 +62,7 @@
projects in a \l{Previewing QML Files}{preview tool} and you need
not build them. You do not
need to have the development environment installed on your
- computer to create and run this type of projects.
+ computer to create and run this type of project.
\o \gui {Qt Quick 1 Application (from Existing QML File)} converts
existing Qt Quick 1 applications to Qt Quick application projects.
diff --git a/doc/templates/style/offline.css b/doc/templates/style/offline.css
index c59c1ff80e..ce2d67db70 100644
--- a/doc/templates/style/offline.css
+++ b/doc/templates/style/offline.css
@@ -487,6 +487,11 @@ border-top: 1px solid #999;
padding-top:11px;
}
+.footer a[href*="http://"], a[href*="ftp://"],a[href*="https://"]{
+background-size: 13px 11px;
+padding-left: 16px;
+}
+
.footerNavi{
width:auto;
text-align:right;
diff --git a/lib/qtcreator/qtcomponents/qtcomponents.qbs b/lib/qtcreator/qtcomponents/qtcomponents.qbs
index 7453269b6c..02feb04119 100644
--- a/lib/qtcreator/qtcomponents/qtcomponents.qbs
+++ b/lib/qtcreator/qtcomponents/qtcomponents.qbs
@@ -1,90 +1,16 @@
import qbs.base 1.0
Product {
- type: ["installed_content"]
name: "QtComponents"
Group {
+ qbs.install: true
qbs.installDir: "lib/qtcreator/qtcomponents/"
- fileTags: ["install"]
files: [
- "Button.qml",
- "ButtonRow.qml",
- "CheckBox.qml",
- "ChoiceList.qml",
- "ContextMenu.qml",
- "Dial.qml",
- "Frame.qml",
- "GroupBox.qml",
- "Menu.qml",
- "MenuItem.qml",
- "ProgressBar.qml",
- "RadioButton.qml",
- "ScrollArea.qml",
- "ScrollBar.qml",
- "Slider.qml",
- "SpinBox.qml",
- "SplitterRow.qml",
- "Switch.qml",
- "Tab.qml",
- "TabBar.qml",
- "TabFrame.qml",
- "TableColumn.qml",
- "TableView.qml",
- "TextArea.qml",
- "TextField.qml",
- "ToolBar.qml",
- "ToolButton.qml",
+ "*.qml",
"qmldir",
- ]
- }
-
- Group {
- qbs.installDir: "lib/qtcreator/qtcomponents/custom"
- fileTags: ["install"]
- prefix: "custom/"
- files: [
- "BasicButton.qml",
- "Button.qml",
- "ButtonColumn.qml",
- "ButtonGroup.js",
- "ButtonRow.qml",
- "CheckBox.qml",
- "ChoiceList.qml",
- "components.pro",
- "GroupBox.qml",
- "ProgressBar.qml",
- "Slider.qml",
- "SpinBox.qml",
- "SplitterRow.qml",
- "TextField.qml",
- "qmldir",
- ]
- }
-
- Group {
- qbs.installDir: "lib/qtcreator/qtcomponents/custom/behaviors"
- fileTags: ["install"]
- files: [
- "custom/behaviors/ButtonBehavior.qml",
- "custom/behaviors/ModalPopupBehavior.qml",
- ]
- }
-
- Group {
- qbs.installDir: "lib/qtcreator/qtcomponents/custom/private"
- fileTags: ["install"]
- files: [
- "custom/private/ChoiceListPopup.qml",
- ]
- }
-
- Group {
- qbs.installDir: "lib/qtcreator/qtcomponents/images"
- fileTags: ["install"]
- files: [
- "images/folder_new.png",
+ "custom",
+ "images"
]
}
}
-
diff --git a/qbs/defaults.js b/qbs/defaults.js
new file mode 100644
index 0000000000..b486888e90
--- /dev/null
+++ b/qbs/defaults.js
@@ -0,0 +1,17 @@
+function testsEnabled(qbs)
+{
+ return qbs.getenv("TEST") || qbs.buildVariant === "debug";
+}
+
+function defines(qbs)
+{
+ var list = [
+ 'IDE_LIBRARY_BASENAME="lib"',
+ "QT_DISABLE_DEPRECATED_BEFORE=0x040900",
+ "QT_NO_CAST_TO_ASCII",
+ "QT_NO_CAST_FROM_ASCII"
+ ]
+ if (testsEnabled(qbs))
+ list.push("WITH_TESTS")
+ return list
+}
diff --git a/qbs/pluginspec/pluginspec.qbs b/qbs/pluginspec/pluginspec.qbs
index dea785fe29..9e7861f016 100644
--- a/qbs/pluginspec/pluginspec.qbs
+++ b/qbs/pluginspec/pluginspec.qbs
@@ -9,27 +9,14 @@ Module {
property int ide_version_minor: project.ide_version_minor
property int ide_version_release: project.ide_version_release
property string qtcreator_version: ide_version_major + '.' + ide_version_minor + '.' + ide_version_release
- property string destdir: product.destination
-
property var pluginspecreplacements: product.pluginspecreplacements
-
- FileTagger {
- pattern: "*.in"
- fileTags: ["pluginSpecIn"]
- }
-
Rule {
inputs: ["pluginSpecIn"]
Artifact {
fileTags: ["pluginSpec"]
- fileName: {
- var destdir = input.modules.pluginspec.destdir;
- if (!destdir.match(/\/$/))
- destdir += "/";
- return destdir + input.fileName.replace(/\.[^\.]*$/,'');
- }
+ fileName: input.fileName.replace(/\.[^\.]*$/,'')
}
prepare: {
diff --git a/qtcreator.pri b/qtcreator.pri
index 784fca03f8..cc16ef9079 100644
--- a/qtcreator.pri
+++ b/qtcreator.pri
@@ -1,7 +1,7 @@
!isEmpty(QTCREATOR_PRI_INCLUDED):error("qtcreator.pri already included")
QTCREATOR_PRI_INCLUDED = 1
-QTCREATOR_VERSION = 2.6.2
+QTCREATOR_VERSION = 2.6.81
isEqual(QT_MAJOR_VERSION, 5) {
@@ -162,8 +162,7 @@ LIBS += -L$$IDE_LIBRARY_PATH
DEFINES += IDE_LIBRARY_BASENAME=\\\"$$IDE_LIBRARY_BASENAME\\\"
}
-#DEFINES += QT_NO_CAST_FROM_ASCII
-DEFINES += QT_NO_CAST_TO_ASCII
+DEFINES += QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
!macx:DEFINES += QT_USE_FAST_OPERATOR_PLUS QT_USE_FAST_CONCATENATION
unix {
diff --git a/qtcreator.qbs b/qtcreator.qbs
index 0b4b579df7..4413f66cae 100644
--- a/qtcreator.qbs
+++ b/qtcreator.qbs
@@ -1,15 +1,12 @@
import qbs.base 1.0
import qbs.fileinfo 1.0 as FileInfo
+import "qbs/defaults.js" as Defaults
Project {
property string ide_version_major: '2'
property string ide_version_minor: '6'
- property string ide_version_release: '2'
+ property string ide_version_release: '81'
property string qtcreator_version: ide_version_major + '.' + ide_version_minor + '.' + ide_version_release
- property var additionalCppDefines: [
- 'IDE_LIBRARY_BASENAME="lib"',
- "QT_DISABLE_DEPRECATED_BEFORE=0x040900"
- ]
moduleSearchPaths: "qbs"
references: [
@@ -62,7 +59,7 @@ Project {
"src/plugins/mercurial/mercurial.qbs",
"src/plugins/perforce/perforce.qbs",
"src/plugins/projectexplorer/projectexplorer.qbs",
- "src/plugins/qmldesigner/qmldesigner.qbs",
+// "src/plugins/qmldesigner/qmldesigner.qbs",
"src/plugins/qmljseditor/qmljseditor.qbs",
"src/plugins/qmljstools/qmljstools.qbs",
"src/plugins/qmlprofiler/qmlprofiler.qbs",
@@ -80,9 +77,10 @@ Project {
"src/plugins/valgrind/valgrind.qbs",
"src/plugins/vcsbase/vcsbase.qbs",
"src/plugins/welcome/welcome.qbs",
- "src/share/share.qbs",
"src/tools/qtcdebugger/qtcdebugger.qbs",
+ "src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs",
"src/tools/qtpromaker/qtpromaker.qbs",
+ "src/plugins/cpaster/frontend/frontend.qbs",
"src/tools/sdktool/sdktool.qbs"
]
@@ -131,16 +129,19 @@ Project {
return cmd;
}
}
+
+ ProductModule {
+ Depends { name: "cpp" }
+ cpp.includePaths: product.buildDirectory
+ }
}
- Product {
+ Application {
name: "qtcreator"
- type: ["application", "installed_content"]
- destination: "bin"
consoleApplication: qbs.debugInformation
cpp.rpaths: ["$ORIGIN/../lib/qtcreator"]
- cpp.defines: project.additionalCppDefines
+ cpp.defines: Defaults.defines(qbs)
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain == "gcc" || qbs.toolchain == "mingw"))
return ["-Wl,-s"]
@@ -166,13 +167,15 @@ Project {
"src/shared/qtsingleapplication/qtsingleapplication.cpp",
"src/shared/qtsingleapplication/qtlocalpeer.h",
"src/shared/qtsingleapplication/qtlocalpeer.cpp",
- "src/shared/qtlockedfile/qtlockedfile.cpp"
+ "src/shared/qtlockedfile/qtlockedfile.cpp",
+ "src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp",
+ "src/tools/qtcreatorcrashhandler/crashhandlersetup.h"
]
Group {
condition: qbs.targetOS == "linux" || qbs.targetOS == "macx"
files: "bin/qtcreator.sh"
- fileTags: "install"
+ qbs.install: true
qbs.installDir: "bin"
}
@@ -189,6 +192,11 @@ Project {
"src/shared/qtlockedfile/qtlockedfile_win.cpp"
]
}
+
+ Group {
+ fileTagsFilter: product.type
+ qbs.install: true
+ qbs.installDir: "bin"
+ }
}
}
-
diff --git a/share/qtcreator/dumper/bridge.py b/share/qtcreator/dumper/bridge.py
index da75a51e54..4033b7c655 100644
--- a/share/qtcreator/dumper/bridge.py
+++ b/share/qtcreator/dumper/bridge.py
@@ -5,6 +5,19 @@ cdbLoaded = False
lldbLoaded = False
gdbLoaded = False
+def warn(message):
+ print "XXX: %s\n" % message.encode("latin1")
+
+
+def showException(msg, exType, exValue, exTraceback):
+ warn("**** CAUGHT EXCEPTION: %s ****" % msg)
+ try:
+ import traceback
+ for line in traceback.format_exception(exType, exValue, exTraceback):
+ warn("%s" % line)
+ except:
+ pass
+
try:
#import cdb_bridge
cdbLoaded = True
@@ -30,10 +43,10 @@ try:
#
#######################################################################
- try:
- gdb.execute("set auto-load-scripts no")
- except:
- pass
+ #try:
+ # gdb.execute("set auto-load-scripts no")
+ #except:
+ # pass
#######################################################################
@@ -42,28 +55,28 @@ try:
#
#######################################################################
+ def savePrint(output):
+ try:
+ print(output)
+ except:
+ out = ""
+ for c in output:
+ cc = ord(c)
+ if cc > 127:
+ out += "\\\\%d" % cc
+ elif cc < 0:
+ out += "\\\\%d" % (cc + 256)
+ else:
+ out += c
+ print(out)
+
def registerCommand(name, func):
class Command(gdb.Command):
def __init__(self):
super(Command, self).__init__(name, gdb.COMMAND_OBSCURE)
def invoke(self, args, from_tty):
- output = func(args)
- try:
- print(output)
- except:
- out = ""
- for c in output:
- cc = ord(c)
- if cc > 127:
- out += "\\\\%d" % cc
- elif cc < 0:
- out += "\\\\%d" % (cc + 256)
- else:
- out += c
- print(out)
-
-
+ savePrint(func(args))
Command()
@@ -78,16 +91,16 @@ try:
if isGoodGdb():
return gdb.parse_and_eval(exp)
# Work around non-existing gdb.parse_and_eval as in released 7.0
- gdb.execute("set logging redirect on")
+# gdb.execute("set logging redirect on")
gdb.execute("set logging on")
try:
gdb.execute("print %s" % exp)
except:
gdb.execute("set logging off")
- gdb.execute("set logging redirect off")
+# gdb.execute("set logging redirect off")
return None
gdb.execute("set logging off")
- gdb.execute("set logging redirect off")
+# gdb.execute("set logging redirect off")
return gdb.history(0)
@@ -189,13 +202,13 @@ try:
block = block.superblock
else:
# Assuming gdb 7.0 release or 6.8-symbianelf.
- filename, file = createTempFile()
+ filename = createTempFile()
#warn("VARLIST: %s " % varList)
#warn("FILENAME: %s " % filename)
gdb.execute("set logging off")
- gdb.execute("set logging redirect off")
+# gdb.execute("set logging redirect off")
gdb.execute("set logging file %s" % filename)
- gdb.execute("set logging redirect on")
+# gdb.execute("set logging redirect on")
gdb.execute("set logging on")
try:
gdb.execute("info args")
@@ -215,7 +228,7 @@ try:
except:
pass
gdb.execute("set logging off")
- gdb.execute("set logging redirect off")
+# gdb.execute("set logging redirect off")
try:
temp = open(filename, "r")
@@ -230,7 +243,7 @@ try:
temp.close()
except:
pass
- removeTempFile(filename, file)
+ removeTempFile(filename)
#warn("VARLIST: %s " % varList)
for name in varList:
#warn("NAME %s " % name)
@@ -260,11 +273,11 @@ try:
return gdb.execute(command, to_string=True).split("\n")
except:
pass
- filename, file = createTempFile()
+ filename = createTempFile()
gdb.execute("set logging off")
- gdb.execute("set logging redirect off")
+# gdb.execute("set logging redirect off")
gdb.execute("set logging file %s" % filename)
- gdb.execute("set logging redirect on")
+# gdb.execute("set logging redirect on")
gdb.execute("set logging on")
msg = ""
try:
@@ -276,17 +289,18 @@ try:
except:
msg = "Unknown error"
gdb.execute("set logging off")
- gdb.execute("set logging redirect off")
+# gdb.execute("set logging redirect off")
if len(msg):
# Having that might confuse result handlers in the gdbengine.
#warn("CLI ERROR: %s " % msg)
+ removeTempFile(filename)
return "CLI ERROR: %s " % msg
temp = open(filename, "r")
lines = []
for line in temp:
lines.append(line)
temp.close()
- removeTempFile(filename, file)
+ removeTempFile(filename)
return lines
def selectedInferior():
@@ -339,7 +353,7 @@ try:
ReferenceCode = gdb.TYPE_CODE_REF
CharCode = gdb.TYPE_CODE_CHAR
BoolCode = gdb.TYPE_CODE_BOOL
- ComplexCode = gdb.TYPE_CODE_COMPLEX # Fortran ?
+ ComplexCode = gdb.TYPE_CODE_COMPLEX
TypedefCode = gdb.TYPE_CODE_TYPEDEF
NamespaceCode = gdb.TYPE_CODE_NAMESPACE
#Code = gdb.TYPE_CODE_DECFLOAT # Decimal floating point.
@@ -383,8 +397,8 @@ try:
def invoke(self, args, from_tty):
print(eval(args))
- registerCommand("pp", pp)
-
+ PPCommand()
+
# Just convienience for 'python print gdb.parse_and_eval(...)'
class PPPCommand(gdb.Command):
def __init__(self):
@@ -394,6 +408,29 @@ try:
PPPCommand()
+
+ def scanStack(p, n):
+ p = long(p)
+ r = []
+ for i in xrange(n):
+ f = gdb.parse_and_eval("{void*}%s" % p)
+ m = gdb.execute("info symbol %s" % f, to_string=True)
+ if not m.startswith("No symbol matches"):
+ r.append(m)
+ p += f.type.sizeof
+ return r
+
+ class ScanStackCommand(gdb.Command):
+ def __init__(self):
+ super(ScanStackCommand, self).__init__("scanStack", gdb.COMMAND_OBSCURE)
+ def invoke(self, args, from_tty):
+ if len(args) == 0:
+ args = 20
+ savePrint(scanStack(gdb.parse_and_eval("$sp"), int(args)))
+
+ ScanStackCommand()
+
+
except:
pass
diff --git a/share/qtcreator/dumper/dumper.cpp b/share/qtcreator/dumper/dumper.cpp
index 4d556ddfcc..8d8fa4195a 100644
--- a/share/qtcreator/dumper/dumper.cpp
+++ b/share/qtcreator/dumper/dumper.cpp
@@ -2251,11 +2251,11 @@ static void qDumpQVariantHelper(const QVariant *v, QString *value,
# endif
default: {
static const char *qTypeFormat = sizeof(void *) == sizeof(long)
- ? "'" NS "%s " NS "qVariantValue<" NS "%s >'(*('" NS "QVariant'*)0x%lx)"
- : "'" NS "%s " NS "qVariantValue<" NS "%s >'(*('" NS "QVariant'*)0x%llx)";
+ ? "'" NS "%s " NS "qvariant_cast<" NS "%s >'(*('" NS "QVariant'*)0x%lx)"
+ : "'" NS "%s " NS "qvariant_cast<" NS "%s >'(*('" NS "QVariant'*)0x%llx)";
static const char *nonQTypeFormat = sizeof(void *) == sizeof(long)
- ? "'%s " NS "qVariantValue<%s >'(*('" NS "QVariant'*)0x%lx)"
- : "'%s " NS "qVariantValue<%s >'(*('" NS "QVariant'*)0x%llx)";
+ ? "'%s " NS "qvariant_cast<%s >'(*('" NS "QVariant'*)0x%lx)"
+ : "'%s " NS "qvariant_cast<%s >'(*('" NS "QVariant'*)0x%llx)";
char buf[1000];
const char *format = (v->typeName()[0] == 'Q') ? qTypeFormat : nonQTypeFormat;
qsnprintf(buf, sizeof(buf) - 1, format, v->typeName(), v->typeName(), v);
diff --git a/share/qtcreator/dumper/dumper.py b/share/qtcreator/dumper/dumper.py
index 52aad054ca..9fa2d55dae 100644
--- a/share/qtcreator/dumper/dumper.py
+++ b/share/qtcreator/dumper/dumper.py
@@ -2,6 +2,8 @@ import sys
import base64
import __builtin__
import os
+import os.path
+import subprocess
import tempfile
# Fails on Windows.
@@ -22,11 +24,12 @@ tempFileCounter = 0
try:
# Test if 2.6 is used (Windows), trigger exception and default
# to 2nd version.
- tempfile.NamedTemporaryFile(prefix="py_",delete=True)
+ file = tempfile.NamedTemporaryFile(prefix="py_",delete=True)
+ file.close()
def createTempFile():
- file = tempfile.NamedTemporaryFile(prefix="py_",delete=False)
+ file = tempfile.NamedTemporaryFile(prefix="py_",delete=True)
file.close()
- return file.name, file
+ return file.name
except:
def createTempFile():
@@ -34,9 +37,9 @@ except:
tempFileCounter += 1
fileName = "%s/py_tmp_%d_%d" \
% (tempfile.gettempdir(), os.getpid(), tempFileCounter)
- return fileName, None
+ return fileName
-def removeTempFile(name, file):
+def removeTempFile(name):
try:
os.remove(name)
except:
@@ -47,7 +50,7 @@ verbosity = 1
# Some "Enums"
-# Encodings
+# Encodings. Keep that synchronized with DebuggerEncoding in watchutils.h
Unencoded8Bit, \
Base64Encoded8BitWithQuotes, \
Base64Encoded16BitWithQuotes, \
@@ -77,17 +80,33 @@ Hex2EncodedFloat4, \
Hex2EncodedFloat8 \
= range(27)
-# Display modes
+# Display modes. Keep that synchronized with DebuggerDisplay in watchutils.h
StopDisplay, \
-DisplayImage1, \
-DisplayString, \
-DisplayImage, \
-DisplayProcess \
- = range(5)
+DisplayImageData, \
+DisplayUtf16String, \
+DisplayImageFile, \
+DisplayProcess, \
+DisplayLatin1String, \
+DisplayUtf8String \
+ = range(7)
-qqStringCutOff = 1000
+qqStringCutOff = 10000
+#
+# Gnuplot based display for array-like structures.
+#
+gnuplotPipe = {}
+gnuplotPid = {}
+
+def hasPlot():
+ fileName = "/usr/bin/gnuplot"
+ return os.path.isfile(fileName) and os.access(fileName, os.X_OK)
+
+
+#
+# Threads
+#
def hasInferiorThreadList():
#return False
try:
@@ -96,6 +115,9 @@ def hasInferiorThreadList():
except:
return False
+#
+# VTable
+#
def hasVTable(type):
fields = type.fields()
if len(fields) == 0:
@@ -309,16 +331,6 @@ def numericTemplateArgument(type, position):
return int(msg)
-def showException(msg, exType, exValue, exTraceback):
- warn("**** CAUGHT EXCEPTION: %s ****" % msg)
- try:
- import traceback
- for line in traceback.format_exception(exType, exValue, exTraceback):
- warn("%s" % line)
- except:
- pass
-
-
class OutputSafer:
def __init__(self, d):
self.d = d
@@ -527,11 +539,6 @@ def simpleEncoding(typeobj):
return Hex2EncodedFloat8
return None
-def warn(message):
- if True or verbosity > 0:
- print "XXX: %s\n" % message.encode("latin1")
- pass
-
def check(exp):
if not exp:
raise RuntimeError("Check failed")
@@ -653,9 +660,7 @@ def call(value, func, *args):
return call2(value, func, args)
def makeValue(type, init):
- type = stripClassTag(type)
- if type.find(":") >= 0:
- type = "'" + type + "'"
+ type = "::" + stripClassTag(str(type));
# Avoid malloc symbol clash with QVector.
gdb.execute("set $d = (%s*)calloc(sizeof(%s), 1)" % (type, type))
gdb.execute("set *$d = {%s}" % init)
@@ -678,9 +683,7 @@ def makeStdString(init):
def makeExpression(value):
- type = stripClassTag(str(value.type))
- if type.find(":") >= 0:
- type = "'" + type + "'"
+ type = "::" + stripClassTag(str(value.type))
#warn(" TYPE: %s" % type)
#exp = "(*(%s*)(&%s))" % (type, value.address)
exp = "(*(%s*)(%s))" % (type, value.address)
@@ -747,11 +750,18 @@ def qByteArrayData(value):
# Qt 4:
return private['data'], int(private['size']), int(private['alloc'])
-def encodeByteArray(value):
+def computeLimit(size, limit):
+ if limit is None:
+ return size
+ if limit == 0:
+ return min(size, qqStringCutOff)
+ return min(size, limit)
+
+def encodeByteArray(value, limit = None):
data, size, alloc = qByteArrayData(value)
if alloc != 0:
check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
- limit = min(size, qqStringCutOff)
+ limit = computeLimit(size, limit)
s = readRawMemory(data, limit)
if limit < size:
s += "2e2e2e"
@@ -770,11 +780,11 @@ def qStringData(value):
# Qt 4.
return private['data'], int(private['size']), int(private['alloc'])
-def encodeString(value):
+def encodeString(value, limit = 0):
data, size, alloc = qStringData(value)
if alloc != 0:
check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
- limit = min(size, qqStringCutOff)
+ limit = computeLimit(size, limit)
s = readRawMemory(data, 2 * limit)
if limit < size:
s += "2e002e002e00"
@@ -969,7 +979,7 @@ registerCommand("p2", p2)
class Dumper:
- def __init__(self, args):
+ def defaultInit(self):
self.output = []
self.currentIName = ""
self.currentPrintsAddress = True
@@ -984,15 +994,18 @@ class Dumper:
self.currentTypePriority = -100
self.typeformats = {}
self.formats = {}
- self.expandedINames = ""
+ self.useDynamicType = True
+ self.expandedINames = {}
- self.output.append('data=[')
+ def __init__(self, args):
+ self.defaultInit()
+ watchers = ""
+ resultVarName = ""
options = []
varList = []
- watchers = ""
- resultVarName = ""
+ self.output.append('data=[')
for arg in args.split(' '):
pos = arg.find(":") + 1
if arg.startswith("options:"):
@@ -1352,6 +1365,45 @@ class Dumper:
self.put('",')
return True
+ def putPlotData(self, type, base, n, plotFormat):
+ if self.isExpanded():
+ self.putArrayData(type, base, n)
+ if not hasPlot():
+ return
+ if not isSimpleType(type):
+ self.putValue(self.currentValue + " (not plottable)")
+ return
+ global gnuplotPipe
+ global gnuplotPid
+ format = self.currentItemFormat()
+ iname = self.currentIName
+ #if False:
+ if format != plotFormat:
+ if iname in gnuplotPipe:
+ os.kill(gnuplotPid[iname], 9)
+ del gnuplotPid[iname]
+ gnuplotPipe[iname].terminate()
+ del gnuplotPipe[iname]
+ return
+ base = base.cast(type.pointer())
+ if not iname in gnuplotPipe:
+ gnuplotPipe[iname] = subprocess.Popen(["gnuplot"],
+ stdin=subprocess.PIPE)
+ gnuplotPid[iname] = gnuplotPipe[iname].pid
+ f = gnuplotPipe[iname].stdin;
+ f.write("set term wxt noraise\n")
+ f.write("set title 'Data fields'\n")
+ f.write("set xlabel 'Index'\n")
+ f.write("set ylabel 'Value'\n")
+ f.write("set grid\n")
+ f.write("set style data lines;\n")
+ f.write("plot '-' title '%s'\n" % iname)
+ for i in range(1, n):
+ f.write(" %s\n" % base.dereference())
+ base += 1
+ f.write("e\n")
+
+
def putArrayData(self, type, base, n,
childNumChild = None, maxNumChild = 10000):
base = base.cast(type.pointer())
@@ -1431,7 +1483,7 @@ class Dumper:
if value.is_optimized_out:
self.putValue("<optimized out>")
else:
- self.putValue(int(value))
+ self.putValue(value)
self.putNumChild(0)
return
@@ -1455,6 +1507,16 @@ class Dumper:
self.putNumChild(0)
return
+ if type.code == ComplexCode:
+ self.putAddress(value.address)
+ self.putType(typeName)
+ if value.is_optimized_out:
+ self.putValue("<optimized out>")
+ else:
+ self.putValue("%s" % value)
+ self.putNumChild(0)
+ return
+
if type.code == TypedefCode:
if typeName in qqDumpers:
self.putType(typeName)
@@ -1481,32 +1543,7 @@ class Dumper:
return
if type.code == ArrayCode:
- targetType = type.target()
- self.putAddress(value.address)
- self.putType(typeName)
- self.putNumChild(1)
- format = self.currentItemFormat()
- if format == None and str(targetType.unqualified()) == "char":
- # Use Latin1 as default for char [].
- self.putValue(encodeCharArray(value), Hex2EncodedLatin1)
- elif format == 0:
- # Explicitly requested Latin1 formatting.
- self.putValue(encodeCharArray(value), Hex2EncodedLatin1)
- elif format == 1:
- # Explicitly requested UTF-8 formatting.
- self.putValue(encodeCharArray(value), Hex2EncodedUtf8)
- elif format == 2:
- # Explicitly requested Local 8-bit formatting.
- self.putValue(encodeCharArray(value), Hex2EncodedLocal8Bit)
- else:
- self.putValue("@0x%x" % long(value.cast(targetType.pointer())))
- if self.currentIName in self.expandedINames:
- p = value.cast(targetType.pointer())
- ts = targetType.sizeof
- if not self.tryPutArrayContents(targetType, p, type.sizeof/ts):
- with Children(self, childType=targetType,
- addrBase=p, addrStep=ts):
- self.putFields(value)
+ qdump____c_style_array__(self, value)
return
if type.code == PointerCode:
@@ -1721,6 +1758,17 @@ class Dumper:
#except:
# pass
+ # D arrays, gdc compiled.
+ if typeName.endswith("[]"):
+ n = value["length"]
+ base = value["ptr"]
+ self.putType(typeName)
+ self.putAddress(value.address)
+ self.putItemCount(n)
+ if self.isExpanded():
+ self.putArrayData(base.type.target(), base, n)
+ return
+
#warn("GENERIC STRUCT: %s" % type)
#warn("INAME: %s " % self.currentIName)
#warn("INAMES: %s " % self.expandedINames)
@@ -1899,6 +1947,41 @@ def threadnames(arg):
registerCommand("threadnames", threadnames)
+#######################################################################
+#
+# Import plain gdb pretty printers
+#
+#######################################################################
+
+class PlainDumper:
+ def __init__(self, printer):
+ self.printer = printer
+
+ def __call__(self, d, value):
+ printer = self.printer.invoke(value)
+ lister = getattr(printer, "children", None)
+ children = [] if lister is None else list(lister())
+ d.putType(self.printer.name)
+ d.putValue(printer.to_string())
+ d.putNumChild(len(children))
+ if d.isExpanded():
+ with Children(d):
+ for child in children:
+ d.putSubItem(child[0], child[1])
+
+def importPlainDumper(printer):
+ name = printer.name.replace("::", "__")
+ qqDumpers[name] = PlainDumper(printer)
+ qqFormats[name] = ""
+
+def importPlainDumpers(args):
+ for obj in gdb.objfiles():
+ for printers in obj.pretty_printers + gdb.pretty_printers:
+ for printer in printers.subprinters:
+ importPlainDumper(printer)
+
+registerCommand("importPlainDumpers", importPlainDumpers)
+
#######################################################################
#
diff --git a/share/qtcreator/dumper/qttypes.py b/share/qtcreator/dumper/qttypes.py
index 48dec6f25c..4db7baacd7 100644
--- a/share/qtcreator/dumper/qttypes.py
+++ b/share/qtcreator/dumper/qttypes.py
@@ -11,6 +11,11 @@ from __future__ import with_statement
def mapForms():
return "Normal,Compact"
+def arrayForms():
+ if hasPlot():
+ return "Normal,Plot"
+ return "Normal"
+
def mapCompact(format, keyType, valueType):
if format == 2:
return True # Compact.
@@ -38,10 +43,22 @@ def qdump__QBasicAtomicPointer(d, value):
d.putItem(value["_q_value"])
+def qform__QByteArray():
+ return "Inline,As Latin1 in Separate Window,As UTF-8 in Separate Window"
+
def qdump__QByteArray(d, value):
d.putByteArrayValue(value)
data, size, alloc = qByteArrayData(value)
d.putNumChild(size)
+ format = d.currentItemFormat()
+ if format == 1:
+ d.putDisplay(StopDisplay)
+ elif format == 2:
+ d.putField("editformat", DisplayLatin1String)
+ d.putField("editvalue", encodeByteArray(value, None))
+ elif format == 3:
+ d.putField("editformat", DisplayUtf8String)
+ d.putField("editvalue", encodeByteArray(value, None))
if d.isExpanded():
d.putArrayData(lookupType("char"), data, size)
@@ -104,8 +121,16 @@ def qdump__QModelIndex(d, value):
return
r = value["r"]
c = value["c"]
- p = value["p"]
+ try:
+ p = value["p"]
+ except:
+ p = value["i"]
m = value["m"]
+ if isNull(m) or r < 0 or c < 0:
+ d.putValue("(invalid)")
+ d.putPlainChildren(value)
+ return
+
mm = m.dereference()
mm = mm.cast(mm.type.unqualified())
try:
@@ -115,6 +140,7 @@ def qdump__QModelIndex(d, value):
rowCount = int(parseAndEvaluate("%s.rowCount(%s)" % (mm_, mi_)))
columnCount = int(parseAndEvaluate("%s.columnCount(%s)" % (mm_, mi_)))
except:
+ d.putValue(" ")
d.putPlainChildren(value)
return
@@ -126,30 +152,23 @@ def qdump__QModelIndex(d, value):
except:
d.putValue("(invalid)")
- if r >= 0 and c >= 0 and not isNull(m):
- d.putNumChild(rowCount * columnCount)
- if d.isExpanded():
- with Children(d):
- i = 0
- for row in xrange(rowCount):
- for column in xrange(columnCount):
- with UnnamedSubItem(d, i):
- d.putName("[%s, %s]" % (row, column))
- mi2 = parseAndEvaluate("%s.index(%d,%d,%s)"
- % (mm_, row, column, mi_))
- d.putItem(mi2)
- i = i + 1
- #d.putCallItem("parent", val, "parent")
- #with SubItem(d, "model"):
- # d.putValue(m)
- # d.putType(d.ns + "QAbstractItemModel*")
- # d.putNumChild(1)
- else:
- d.putValue("(invalid)")
- d.putNumChild(0)
- if d.isExpanded():
- with Children(d):
- pass
+ d.putNumChild(rowCount * columnCount)
+ if d.isExpanded():
+ with Children(d):
+ i = 0
+ for row in xrange(rowCount):
+ for column in xrange(columnCount):
+ with UnnamedSubItem(d, i):
+ d.putName("[%s, %s]" % (row, column))
+ mi2 = parseAndEvaluate("%s.index(%d,%d,%s)"
+ % (mm_, row, column, mi_))
+ d.putItem(mi2)
+ i = i + 1
+ #d.putCallItem("parent", val, "parent")
+ #with SubItem(d, "model"):
+ # d.putValue(m)
+ # d.putType(d.ns + "QAbstractItemModel*")
+ # d.putNumChild(1)
#gdb.execute("call free($mi)")
@@ -216,8 +235,15 @@ def qdump__QDir(d, value):
d.putStringValue(data["dirEntry"]["m_filePath"])
if d.isExpanded():
with Children(d):
+ qdir = d.ns + "QDir::"
d.putCallItem("absolutePath", value, "absolutePath")
d.putCallItem("canonicalPath", value, "canonicalPath")
+ d.putSubItem("entryList", parseAndEvaluate(
+ "'%sentryList'(%s, %sNoFilter, %sNoSort)"
+ % (qdir, value.address, qdir, qdir)), False)
+ d.putSubItem("entryInfoList", parseAndEvaluate(
+ "'%sentryInfoList'(%s, %sNoFilter, %sNoSort)"
+ % (qdir, value.address, qdir, qdir)), False)
def qdump__QFile(d, value):
@@ -559,7 +585,7 @@ def qdump__QImage(d, value):
if False:
# Take four bytes at a time, this is critical for performance.
# In fact, even four at a time is too slow beyond 100x100 or so.
- d.putField("editformat", 1) # Magic marker for direct "QImage" data.
+ d.putField("editformat", DisplayImageData)
d.put('%s="' % name)
d.put("%08x" % int(d_ptr["width"]))
d.put("%08x" % int(d_ptr["height"]))
@@ -576,7 +602,7 @@ def qdump__QImage(d, value):
p = bits.cast(lookupType("unsigned char").pointer())
gdb.execute("dump binary memory %s %s %s" %
(filename, cleanAddress(p), cleanAddress(p + nbytes)))
- d.putDisplay(DisplayImage, " %d %d %d %s"
+ d.putDisplay(DisplayImageFile, " %d %d %d %s"
% (d_ptr["width"], d_ptr["height"], d_ptr["format"], filename))
@@ -781,10 +807,15 @@ def qdump__QObject(d, value):
staticMetaObject = value["staticMetaObject"]
d_ptr = value["d_ptr"]["d"].cast(privateType.pointer()).dereference()
#warn("D_PTR: %s " % d_ptr)
+ objectName = None
try:
objectName = d_ptr["objectName"]
except: # Qt 5
- objectName = d_ptr["extraData"].dereference()["objectName"]
+ p = d_ptr["extraData"]
+ if not isNull(p):
+ objectName = p.dereference()["objectName"]
+ if not objectName is None:
+ d.putStringValue(objectName)
except:
d.putPlainChildren(value)
return
@@ -816,13 +847,20 @@ def qdump__QObject(d, value):
#warn("MO.D: %s " % mo["d"])
metaData = mo["d"]["data"]
metaStringData = mo["d"]["stringdata"]
+ # This is char * in Qt 4 and ByteArrayData * in Qt 5.
+ # Force it to the char * data in the Qt 5 case.
+ try:
+ offset = metaStringData["offset"]
+ metaStringData = metaStringData.cast(lookupType('char*')) + int(offset)
+ except:
+ pass
+
#extradata = mo["d"]["extradata"] # Capitalization!
#warn("METADATA: %s " % metaData)
#warn("STRINGDATA: %s " % metaStringData)
#warn("TYPE: %s " % value.type)
#warn("INAME: %s " % d.currentIName())
#d.putValue("")
- d.putStringValue(objectName)
#QSignalMapper::staticMetaObject
#checkRef(d_ptr["ref"])
d.putNumChild(4)
@@ -1444,8 +1482,21 @@ def qdump__QString(d, value):
if format == 1:
d.putDisplay(StopDisplay)
elif format == 2:
- d.putField("editformat", 2)
- d.putField("editvalue", encodeString(value))
+ d.putField("editformat", DisplayUtf16String)
+ d.putField("editvalue", encodeString(value, None))
+
+
+def qdump__QStringRef(d, value):
+ s = value["m_string"].dereference()
+ data, size, alloc = qStringData(s)
+ data += int(value["m_position"])
+ size = value["m_size"]
+ s = readRawMemory(data, 2 * size)
+ d.putValue(s, Hex4EncodedLittleEndian)
+ d.putNumChild(3)
+ if d.isExpanded():
+ with Children(d):
+ d.putFields(value)
def qdump__QStringList(d, value):
@@ -1721,6 +1772,10 @@ def qedit__QVector(expr, value):
gdb.execute(cmd)
+def qform__QVector():
+ return arrayForms()
+
+
def qdump__QVector(d, value):
private = value["d"]
checkRef(private["ref"])
@@ -1741,8 +1796,7 @@ def qdump__QVector(d, value):
check(0 <= size and size <= alloc and alloc <= 1000 * 1000 * 1000)
d.putItemCount(size)
d.putNumChild(size)
- if d.isExpanded():
- d.putArrayData(innerType, p, size)
+ d.putPlotData(innerType, p, size, 2)
def qdump__QWeakPointer(d, value):
@@ -1786,6 +1840,42 @@ def qdump__QxXmlAttributes(d, value):
#
#######################################################################
+def qdump____c_style_array__(d, value):
+ type = value.type.unqualified()
+ targetType = type.target()
+ typeName = str(type)
+ d.putAddress(value.address)
+ d.putType(typeName)
+ d.putNumChild(1)
+ format = d.currentItemFormat()
+ isDefault = format == None and str(targetType.unqualified()) == "char"
+ if isDefault or (format >= 0 and format <= 2):
+ blob = readRawMemory(value.address, type.sizeof)
+
+ if isDefault:
+ # Use Latin1 as default for char [].
+ d.putValue(blob, Hex2EncodedLatin1)
+ elif format == 0:
+ # Explicitly requested Latin1 formatting.
+ d.putValue(blob, Hex2EncodedLatin1)
+ elif format == 1:
+ # Explicitly requested UTF-8 formatting.
+ d.putValue(blob, Hex2EncodedUtf8)
+ elif format == 2:
+ # Explicitly requested Local 8-bit formatting.
+ d.putValue(blob, Hex2EncodedLocal8Bit)
+ else:
+ d.putValue("@0x%x" % long(value.cast(targetType.pointer())))
+
+ if d.currentIName in d.expandedINames:
+ p = value.address
+ ts = targetType.sizeof
+ if not d.tryPutArrayContents(targetType, p, type.sizeof / ts):
+ with Children(d, childType=targetType,
+ addrBase=p, addrStep=ts):
+ d.putFields(value)
+
+
def qdump__std__array(d, value):
size = numericTemplateArgument(value.type, 1)
d.putItemCount(size)
@@ -2001,6 +2091,9 @@ def qdump__std__stack(d, value):
qdump__std__deque(d, value["c"])
+def qform__std__string():
+ return "Inline,In Separate Window"
+
def qdump__std__string(d, value):
data = value["_M_dataplus"]["_M_p"]
baseType = value.type.unqualified().strip_typedefs()
@@ -2021,40 +2114,36 @@ def qdump__std__string(d, value):
check(rep['_M_refcount'] >= -1) # Can be -1 accoring to docs.
check(0 <= size and size <= alloc and alloc <= 100*1000*1000)
p = gdb.Value(data.cast(charType.pointer()))
- s = ""
# Override "std::basic_string<...>
if str(charType) == "char":
d.putType("std::string", 1)
elif str(charType) == "wchar_t":
d.putType("std::wstring", 1)
- n = min(size, 1000)
+ n = min(size, qqStringCutOff)
+ mem = readRawMemory(p, n * charType.sizeof)
if charType.sizeof == 1:
- format = "%02x"
- for i in xrange(size):
- s += format % int(p.dereference())
- p += 1
- d.putValue(s, Hex2EncodedLatin1)
- d.putNumChild(0)
+ encodingType = Hex2EncodedLatin1
+ displayType = DisplayLatin1String
elif charType.sizeof == 2:
- format = "%02x%02x"
- for i in xrange(size):
- val = int(p.dereference())
- s += format % (val % 256, val / 256)
- p += 1
- d.putValue(s, Hex4EncodedLittleEndian)
+ encodingType = Hex4EncodedLatin1
+ displayType = DisplayUtf16String
else:
- # FIXME: This is not always a proper solution.
- format = "%02x%02x%02x%02x"
- for i in xrange(size):
- val = int(p.dereference())
- hi = val / 65536
- lo = val % 65536
- s += format % (lo % 256, lo / 256, hi % 256, hi / 256)
- p += 1
- d.putValue(s, Hex8EncodedLittleEndian)
+ encodinfType = Hex8EncodedLatin1
+ displayType = DisplayUtf16String
+ d.putAddress(value.address)
d.putNumChild(0)
+ d.putValue(mem, encodingType)
+
+ format = d.currentItemFormat()
+ if format == 1:
+ d.putDisplay(StopDisplay)
+ elif format == 2:
+ d.putField("editformat", displayType)
+ if n != size:
+ mem = readRawMemory(p, size * charType.sizeof)
+ d.putField("editvalue", mem)
def qdump__std__shared_ptr(d, value):
@@ -2506,6 +2595,10 @@ def qdump__CPlusPlus__Internal__Value(d, value):
d.putValue(value["l"])
d.putPlainChildren(value)
+def qdump__Utils__FileName(d, value):
+ d.putStringValue(value)
+ d.putPlainChildren(value)
+
def qdump__Utils__ElfSection(d, value):
d.putByteArrayValue(value["name"])
d.putPlainChildren(value)
@@ -2662,20 +2755,24 @@ if False:
d.putItem(v["a"])
- def qdump__Function(d, value):
+if False:
+
+ def qform__basic__Function():
+ return "Normal,Displayed"
+
+ def qdump__basic__Function(d, value):
min = value["min"]
max = value["max"]
data, size, alloc = qByteArrayData(value["var"])
- var = extractCString(data)
+ var = extractCString(data, 0)
data, size, alloc = qByteArrayData(value["f"])
- f = extractCString(data)
+ f = extractCString(data, 0)
d.putValue("%s, %s=%f..%f" % (f, var, min, max))
d.putNumChild(0)
- d.putField("typeformats", "Normal,Displayed");
format = d.currentItemFormat()
- if format == 0:
+ if format == 1:
d.putDisplay(StopDisplay)
- elif format == 1:
+ elif format == 2:
input = "plot [%s=%f:%f] %s" % (var, min, max, f)
d.putDisplay(DisplayProcess, input, "gnuplot")
@@ -2792,3 +2889,5 @@ if False:
if d.isExpanded():
with Children(d):
d.putFields(value)
+
+
diff --git a/share/qtcreator/qml/qmldump/main.cpp b/share/qtcreator/qml/qmldump/main.cpp
index f7b6e5112f..6870f4d7f0 100644
--- a/share/qtcreator/qml/qmldump/main.cpp
+++ b/share/qtcreator/qml/qmldump/main.cpp
@@ -584,10 +584,10 @@ int main(int argc, char *argv[])
// find all QMetaObjects reachable when the specified module is imported
if (action != Path) {
- importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toAscii();
+ importCode += QString("import %0 %1\n").arg(pluginImportUri, pluginImportVersion).toLatin1();
} else {
// pluginImportVersion can be empty
- importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toAscii();
+ importCode += QString("import \".\" %2\n").arg(pluginImportVersion).toLatin1();
}
// create a component with these imports to make sure the imports are valid
diff --git a/share/qtcreator/qml/qmlobserver/main.cpp b/share/qtcreator/qml/qmlobserver/main.cpp
index eae8e6055e..7f61c99ee3 100644
--- a/share/qtcreator/qml/qmlobserver/main.cpp
+++ b/share/qtcreator/qml/qmlobserver/main.cpp
@@ -48,30 +48,6 @@ QtMsgHandler systemMsgOutput = 0;
static QDeclarativeViewer *openFile(const QString &fileName);
static void showViewer(QDeclarativeViewer *viewer);
-#if defined (Q_OS_SYMBIAN)
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-
-void myMessageOutput(QtMsgType type, const char *msg)
-{
- static int fd = -1;
- if (fd == -1)
- fd = ::open("E:\\qml.log", O_WRONLY | O_CREAT);
-
- ::write(fd, msg, strlen(msg));
- ::write(fd, "\n", 1);
- ::fsync(fd);
-
- switch (type) {
- case QtFatalMsg:
- abort();
- }
-}
-
-#else // !defined (Q_OS_SYMBIAN)
-
QWeakPointer<LoggerWidget> logger;
QString warnings;
@@ -112,8 +88,6 @@ void myMessageOutput(QtMsgType type, const char *msg)
}
}
-#endif
-
static QDeclarativeViewer* globalViewer = 0;
// The qml file that is shown if the user didn't specify a QML file
@@ -208,11 +182,6 @@ struct ViewerOptions
warningsConfig(DefaultWarnings),
sizeToView(true)
{
-#if defined(Q_OS_SYMBIAN)
- maximized = true;
- useNativeFileBrowser = false;
-#endif
-
#if defined(Q_OS_MAC)
useGL = true;
#endif
@@ -462,7 +431,6 @@ static QDeclarativeViewer *createViewer()
viewer->setScript(opts.script);
}
-#if !defined(Q_OS_SYMBIAN)
logger = viewer->warningsWidget();
if (opts.warningsConfig == ShowWarnings) {
logger.data()->setDefaultVisibility(LoggerWidget::ShowWarnings);
@@ -470,7 +438,6 @@ static QDeclarativeViewer *createViewer()
} else if (opts.warningsConfig == HideWarnings){
logger.data()->setDefaultVisibility(LoggerWidget::HideWarnings);
}
-#endif
if (opts.experimentalGestures)
viewer->enableExperimentalGestures();
@@ -522,11 +489,7 @@ QDeclarativeViewer *openFile(const QString &fileName)
int main(int argc, char ** argv)
{
-#if defined (Q_OS_SYMBIAN)
- qInstallMsgHandler(myMessageOutput);
-#else
systemMsgOutput = qInstallMsgHandler(myMessageOutput);
-#endif
#if defined (Q_WS_X11) || defined (Q_OS_MAC)
//### default to using raster graphics backend for now
diff --git a/share/qtcreator/qml/qmlobserver/qmlruntime.cpp b/share/qtcreator/qml/qmlobserver/qmlruntime.cpp
index 40dc5270d1..39c39046b6 100644
--- a/share/qtcreator/qml/qmlobserver/qmlruntime.cpp
+++ b/share/qtcreator/qml/qmlobserver/qmlruntime.cpp
@@ -828,20 +828,14 @@ void QDeclarativeViewer::createMenu()
orientation->setExclusive(true);
connect(orientation, SIGNAL(triggered(QAction*)), this, SLOT(changeOrientation(QAction*)));
-#if defined(Q_OS_SYMBIAN)
- QAction *autoOrientationAction = new QAction(tr("Auto-orientation"), this);
- autoOrientationAction->setCheckable(true);
-#endif
QAction *portraitAction = new QAction(tr("Portrait"), this);
portraitAction->setCheckable(true);
QAction *landscapeAction = new QAction(tr("Landscape"), this);
landscapeAction->setCheckable(true);
-#if !defined(Q_OS_SYMBIAN)
QAction *portraitInvAction = new QAction(tr("Portrait (inverted)"), this);
portraitInvAction->setCheckable(true);
QAction *landscapeInvAction = new QAction(tr("Landscape (inverted)"), this);
landscapeInvAction->setCheckable(true);
-#endif
QAction *aboutAction = new QAction(tr("&About Qt..."), this);
aboutAction->setMenuRole(QAction::AboutQtRole);
@@ -887,7 +881,6 @@ void QDeclarativeViewer::createMenu()
fileMenu->addAction(reloadAction);
fileMenu->addSeparator();
fileMenu->addAction(closeAction);
-#if !defined(Q_OS_SYMBIAN)
fileMenu->addAction(quitAction);
QMenu *recordMenu = menu->addMenu(tr("&Recording"));
@@ -899,29 +892,19 @@ void QDeclarativeViewer::createMenu()
debugMenu->addAction(showWarningsWindow);
debugMenu->addAction(designModeBehaviorAction);
debugMenu->addAction(appOnTopAction);
-#endif // ! Q_OS_SYMBIAN
QMenu *settingsMenu = menu->addMenu(tr("&Settings"));
settingsMenu->addAction(proxyAction);
-#if defined(Q_OS_SYMBIAN)
- settingsMenu->addAction(fullscreenAction);
-#else
settingsMenu->addAction(recordOptions);
settingsMenu->addMenu(loggerWindow->preferencesMenu());
-#endif // !Q_OS_SYMBIAN
settingsMenu->addAction(rotateAction);
QMenu *propertiesMenu = settingsMenu->addMenu(tr("Properties"));
-#if defined(Q_OS_SYMBIAN)
- orientation->addAction(autoOrientationAction);
-#endif
orientation->addAction(portraitAction);
orientation->addAction(landscapeAction);
-#if !defined(Q_OS_SYMBIAN)
orientation->addAction(portraitInvAction);
orientation->addAction(landscapeInvAction);
-#endif
propertiesMenu->addActions(orientation->actions());
QMenu *helpMenu = menu->addMenu(tr("&Help"));
@@ -1201,12 +1184,7 @@ bool QDeclarativeViewer::open(const QString& file_or_url)
canvas->engine()->clearComponentCache();
QDeclarativeContext *ctxt = canvas->rootContext();
ctxt->setContextProperty("qmlViewer", this);
-#ifdef Q_OS_SYMBIAN
- ctxt->setContextProperty("qmlViewerFolder", "E:\\"); // Documents on your S60 phone
-#else
ctxt->setContextProperty("qmlViewerFolder", QDir::currentPath());
-#endif
-
ctxt->setContextProperty("runtime", Runtime::instance());
QString fileName = url.toLocalFile();
diff --git a/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.cpp
index 8c788e4176..c106815e26 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.cpp
@@ -29,6 +29,8 @@
#include "changenodesourcecommand.h"
+#include <QDataStream>
+
namespace QmlDesigner {
ChangeNodeSourceCommand::ChangeNodeSourceCommand()
diff --git a/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.h b/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.h
index 288c464d1f..0644a596c5 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.h
+++ b/share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.h
@@ -31,6 +31,7 @@
#define CHANGENODESOURCECOMMAND_H
#include <QMetaType>
+#include <QString>
#include <QDataStream>
namespace QmlDesigner {
diff --git a/share/qtcreator/qml/qmlpuppet/commands/commands.pri b/share/qtcreator/qml/qmlpuppet/commands/commands.pri
index 5ae623cf3f..3d347f73db 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/commands.pri
+++ b/share/qtcreator/qml/qmlpuppet/commands/commands.pri
@@ -1,6 +1,8 @@
INCLUDEPATH += $$PWD/
HEADERS += $$PWD/synchronizecommand.h
+HEADERS += $$PWD//debugoutputcommand.h
+HEADERS += $$PWD/endpuppetcommand.h
HEADERS += $$PWD/tokencommand.h
HEADERS += $$PWD/componentcompletedcommand.h
HEADERS += $$PWD/completecomponentcommand.h
@@ -22,9 +24,11 @@ HEADERS += $$PWD/removepropertiescommand.h
HEADERS += $$PWD/reparentinstancescommand.h
HEADERS += $$PWD/valueschangedcommand.h
HEADERS += $$PWD/changeauxiliarycommand.h
-
+HEADERS += $$PWD/removesharedmemorycommand.h
SOURCES += $$PWD/synchronizecommand.cpp
+SOURCES += $$PWD/debugoutputcommand.cpp
+SOURCES += $$PWD/endpuppetcommand.cpp
SOURCES += $$PWD/tokencommand.cpp
SOURCES += $$PWD/componentcompletedcommand.cpp
SOURCES += $$PWD/completecomponentcommand.cpp
@@ -46,3 +50,4 @@ SOURCES += $$PWD/createinstancescommand.cpp
SOURCES += $$PWD/createscenecommand.cpp
SOURCES += $$PWD/pixmapchangedcommand.cpp
SOURCES += $$PWD/changeauxiliarycommand.cpp
+SOURCES += $$PWD/removesharedmemorycommand.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.cpp
index d83246a883..124ab897fe 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.cpp
@@ -29,6 +29,8 @@
#include "completecomponentcommand.h"
+#include <QDataStream>
+
namespace QmlDesigner {
CompleteComponentCommand::CompleteComponentCommand()
diff --git a/share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.cpp
index 7d5e8f7b4f..478710ba78 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.cpp
@@ -29,6 +29,8 @@
#include "componentcompletedcommand.h"
+#include <QDataStream>
+
namespace QmlDesigner {
ComponentCompletedCommand::ComponentCompletedCommand()
diff --git a/share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.cpp
new file mode 100644
index 0000000000..1eacfd247f
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.cpp
@@ -0,0 +1,74 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+
+
+#include "debugoutputcommand.h"
+
+namespace QmlDesigner {
+
+DebugOutputCommand::DebugOutputCommand()
+{
+}
+
+DebugOutputCommand::DebugOutputCommand(const QString &text, DebugOutputCommand::Type type)
+ : m_text(text),
+ m_type(type)
+{
+}
+
+qint32 DebugOutputCommand::type() const
+{
+ return m_type;
+}
+
+QString DebugOutputCommand::text() const
+{
+ return m_text;
+}
+
+QDataStream &operator<<(QDataStream &out, const DebugOutputCommand &command)
+{
+ out << command.type();
+ out << command.text();
+
+ return out;
+}
+
+QDataStream &operator>>(QDataStream &in, DebugOutputCommand &command)
+{
+ in >> command.m_type;
+ in >> command.m_text;
+
+ return in;
+}
+
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.h b/share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.h
new file mode 100644
index 0000000000..0c0e232b13
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/commands/debugoutputcommand.h
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLDESIGNER_DEBUGOUTPUTCOMMAND_H
+#define QMLDESIGNER_DEBUGOUTPUTCOMMAND_H
+
+#include <QMetaType>
+#include <QString>
+#include <QDataStream>
+
+namespace QmlDesigner {
+
+class DebugOutputCommand
+{
+ friend QDataStream &operator>>(QDataStream &in, DebugOutputCommand &command);
+
+public:
+ enum Type {
+ DebugType,
+ WarningType,
+ ErrorType,
+ FatalType
+ };
+
+ DebugOutputCommand();
+ DebugOutputCommand(const QString &text, Type type);
+
+ qint32 type() const;
+ QString text() const;
+
+private:
+ QString m_text;
+ quint32 m_type;
+};
+
+QDataStream &operator<<(QDataStream &out, const DebugOutputCommand &command);
+QDataStream &operator>>(QDataStream &in, DebugOutputCommand &command);
+
+} // namespace QmlDesigner
+
+Q_DECLARE_METATYPE(QmlDesigner::DebugOutputCommand)
+
+#endif // QMLDESIGNER_DEBUGOUTPUTCOMMAND_H
diff --git a/share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.cpp
new file mode 100644
index 0000000000..22e8225569
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.cpp
@@ -0,0 +1,48 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "endpuppetcommand.h"
+
+namespace QmlDesigner {
+
+EndPuppetCommand::EndPuppetCommand()
+{
+}
+
+QDataStream &operator<<(QDataStream &out, const EndPuppetCommand &/*command*/)
+{
+ return out;
+}
+
+QDataStream &operator>>(QDataStream &in, EndPuppetCommand &/*command*/)
+{
+ return in;
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/extrasplugin/extrasplugin.h b/share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.h
index a42b78b915..eb0ce6e3f5 100644
--- a/src/plugins/qmldesigner/extrasplugin/extrasplugin.h
+++ b/share/qtcreator/qml/qmlpuppet/commands/endpuppetcommand.h
@@ -26,29 +26,24 @@
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
+#ifndef QMLDESIGNER_ENDPUPPETCOMMAND_H
+#define QMLDESIGNER_ENDPUPPETCOMMAND_H
-#ifndef EXTRASPLUGIN_H
-#define EXTRASPLUGIN_H
-
-#include <iwidgetplugin.h>
+#include <qmetatype.h>
namespace QmlDesigner {
-class ExtrasPlugin : public QObject, QmlDesigner::IWidgetPlugin
+class EndPuppetCommand
{
- Q_OBJECT
-#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QmlDesignerPlugin" FILE "extrasplugin.json")
-#endif
- Q_INTERFACES(QmlDesigner::IWidgetPlugin)
-
public:
- ExtrasPlugin();
-
- QString metaInfo() const;
- QString pluginName() const;
+ EndPuppetCommand();
};
+QDataStream &operator<<(QDataStream &out, const EndPuppetCommand &command);
+QDataStream &operator>>(QDataStream &in, EndPuppetCommand &command);
+
} // namespace QmlDesigner
-#endif // EXTRASPLUGIN_H
+Q_DECLARE_METATYPE(QmlDesigner::EndPuppetCommand)
+
+#endif // QMLDESIGNER_ENDPUPPETCOMMAND_H
diff --git a/share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.cpp
index bd918e5040..e256d7ae45 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.cpp
@@ -29,6 +29,8 @@
#include "removeinstancescommand.h"
+#include <QDataStream>
+
namespace QmlDesigner {
RemoveInstancesCommand::RemoveInstancesCommand()
diff --git a/share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.cpp
new file mode 100644
index 0000000000..63bb675f7b
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.cpp
@@ -0,0 +1,76 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+
+
+#include "removesharedmemorycommand.h"
+
+#include <QDataStream>
+
+namespace QmlDesigner {
+
+RemoveSharedMemoryCommand::RemoveSharedMemoryCommand()
+{
+}
+
+RemoveSharedMemoryCommand::RemoveSharedMemoryCommand(const QString &typeName, const QVector<qint32> &keyNumberVector)
+ : m_typeName(typeName),
+ m_keyNumberVector(keyNumberVector)
+{
+}
+
+QString RemoveSharedMemoryCommand::typeName() const
+{
+ return m_typeName;
+}
+
+QVector<qint32> RemoveSharedMemoryCommand::keyNumbers() const
+{
+ return m_keyNumberVector;
+}
+
+QDataStream &operator<<(QDataStream &out, const RemoveSharedMemoryCommand &command)
+{
+ out << command.typeName();
+ out << command.keyNumbers();
+
+ return out;
+}
+
+QDataStream &operator>>(QDataStream &in, RemoveSharedMemoryCommand &command)
+{
+ in >> command.m_typeName;
+ in >> command.m_keyNumberVector;
+
+ return in;
+}
+
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.h b/share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.h
new file mode 100644
index 0000000000..da46fc0a20
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/commands/removesharedmemorycommand.h
@@ -0,0 +1,66 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+
+
+#ifndef QMLDESIGNER_REMOVESHAREDMEMORYCOMMAND_H
+#define QMLDESIGNER_REMOVESHAREDMEMORYCOMMAND_H
+
+#include <QMetaType>
+#include <QString>
+#include <QVector>
+
+namespace QmlDesigner {
+
+class RemoveSharedMemoryCommand
+{
+ friend QDataStream &operator>>(QDataStream &in, RemoveSharedMemoryCommand &command);
+
+public:
+ RemoveSharedMemoryCommand();
+ RemoveSharedMemoryCommand(const QString &typeName, const QVector<qint32> &keyNumberVector);
+
+ QString typeName() const;
+ QVector<qint32> keyNumbers() const;
+
+private:
+ QString m_typeName;
+ QVector<qint32> m_keyNumberVector;
+};
+
+QDataStream &operator<<(QDataStream &out, const RemoveSharedMemoryCommand &command);
+QDataStream &operator>>(QDataStream &in, RemoveSharedMemoryCommand &command);
+
+} // namespace QmlDesigner
+
+Q_DECLARE_METATYPE(QmlDesigner::RemoveSharedMemoryCommand)
+
+#endif // QMLDESIGNER_REMOVESHAREDMEMORYCOMMAND_H
diff --git a/share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.cpp
index da7de58b01..faac957fec 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.cpp
@@ -29,6 +29,8 @@
#include "reparentinstancescommand.h"
+#include <QDataStream>
+
namespace QmlDesigner {
ReparentInstancesCommand::ReparentInstancesCommand()
diff --git a/share/qtcreator/qml/qmlpuppet/commands/tokencommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/tokencommand.cpp
index b57343d3b1..024dc9a997 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/tokencommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/tokencommand.cpp
@@ -29,6 +29,8 @@
#include "tokencommand.h"
+#include <QDataStream>
+
namespace QmlDesigner {
TokenCommand::TokenCommand()
diff --git a/share/qtcreator/qml/qmlpuppet/commands/tokencommand.h b/share/qtcreator/qml/qmlpuppet/commands/tokencommand.h
index acbd8fd017..6cf171c0e5 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/tokencommand.h
+++ b/share/qtcreator/qml/qmlpuppet/commands/tokencommand.h
@@ -33,6 +33,7 @@
#include <QMetaType>
#include <QVector>
+#include <QString>
#include <QDataStream>
namespace QmlDesigner {
diff --git a/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.cpp b/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.cpp
index 0447208bf2..f832a74b75 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.cpp
+++ b/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.cpp
@@ -29,14 +29,23 @@
#include "valueschangedcommand.h"
+#include <QSharedMemory>
+#include <QCache>
+
+#include <cstring>
+
namespace QmlDesigner {
+static QCache<qint32, QSharedMemory> globalSharedMemoryCache(10000);
+
ValuesChangedCommand::ValuesChangedCommand()
+ : m_keyNumber(0)
{
}
ValuesChangedCommand::ValuesChangedCommand(const QVector<PropertyValueContainer> &valueChangeVector)
- : m_valueChangeVector (valueChangeVector)
+ : m_valueChangeVector (valueChangeVector),
+ m_keyNumber(0)
{
}
@@ -45,17 +54,91 @@ QVector<PropertyValueContainer> ValuesChangedCommand::valueChanges() const
return m_valueChangeVector;
}
+quint32 ValuesChangedCommand::keyNumber() const
+{
+ return m_keyNumber;
+}
+
+void ValuesChangedCommand::removeSharedMemorys(const QVector<qint32> &keyNumberVector)
+{
+ foreach (qint32 keyNumber, keyNumberVector) {
+ QSharedMemory *sharedMemory = globalSharedMemoryCache.take(keyNumber);
+ delete sharedMemory;
+ }
+}
+
+static const QLatin1String valueKeyTemplateString("Values-%1");
+
+static QSharedMemory *createSharedMemory(qint32 key, int byteCount)
+{
+ QSharedMemory *sharedMemory = new QSharedMemory(QString(valueKeyTemplateString).arg(key));
+
+ bool sharedMemoryIsCreated = sharedMemory->create(byteCount);
+ if (!sharedMemoryIsCreated) {
+ if (sharedMemory->isAttached())
+ sharedMemory->attach();
+ sharedMemory->detach();
+ sharedMemoryIsCreated = sharedMemory->create(byteCount);
+ }
+
+ if (sharedMemoryIsCreated) {
+ globalSharedMemoryCache.insert(key, sharedMemory);
+ return sharedMemory;
+ }
+
+ return 0;
+}
+
QDataStream &operator<<(QDataStream &out, const ValuesChangedCommand &command)
{
+ static const bool dontUseSharedMemory = !qgetenv("DESIGNER_DONT_USE_SHARED_MEMORY").isEmpty();
+
+ if (!dontUseSharedMemory && command.valueChanges().count() > 5) {
+ static quint32 keyCounter = 0;
+ ++keyCounter;
+ command.m_keyNumber = keyCounter;
+ QByteArray outDataStreamByteArray;
+ QDataStream temporaryOutDataStream(&outDataStreamByteArray, QIODevice::WriteOnly);
+ temporaryOutDataStream.setVersion(QDataStream::Qt_4_8);
+
+ temporaryOutDataStream << command.valueChanges();;
+
+ QSharedMemory *sharedMemory = createSharedMemory(keyCounter, outDataStreamByteArray.size());
+
+ if (sharedMemory) {
+ std::memcpy(sharedMemory->data(), outDataStreamByteArray.constData(), sharedMemory->size());
+ out << command.keyNumber();
+ return out;
+ }
+ }
+
+ out << qint32(0);
out << command.valueChanges();
return out;
}
+void readSharedMemory(qint32 key, QVector<PropertyValueContainer> *valueChangeVector)
+{
+ QSharedMemory sharedMemory(QString(valueKeyTemplateString).arg(key));
+ bool canAttach = sharedMemory.attach(QSharedMemory::ReadOnly);
+
+ if (canAttach) {
+ QDataStream in(QByteArray::fromRawData(static_cast<const char*>(sharedMemory.constData()), sharedMemory.size()));
+ in.setVersion(QDataStream::Qt_4_8);
+ in >> *valueChangeVector;
+ }
+}
+
QDataStream &operator>>(QDataStream &in, ValuesChangedCommand &command)
{
- in >> command.m_valueChangeVector;
+ in >> command.m_keyNumber;
+ if (command.keyNumber() > 0) {
+ readSharedMemory(command.keyNumber(), &command.m_valueChangeVector);
+ } else {
+ in >> command.m_valueChangeVector;
+ }
return in;
}
diff --git a/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.h b/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.h
index 03e0d6dbb8..20ce63ba3f 100644
--- a/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.h
+++ b/share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.h
@@ -39,6 +39,7 @@ namespace QmlDesigner {
class ValuesChangedCommand
{
+ friend QDataStream &operator<<(QDataStream &out, const ValuesChangedCommand &command);
friend QDataStream &operator>>(QDataStream &in, ValuesChangedCommand &command);
public:
@@ -46,9 +47,13 @@ public:
ValuesChangedCommand(const QVector<PropertyValueContainer> &valueChangeVector);
QVector<PropertyValueContainer> valueChanges() const;
+ quint32 keyNumber() const;
+
+ static void removeSharedMemorys(const QVector<qint32> &keyNumberVector);
private:
QVector<PropertyValueContainer> m_valueChangeVector;
+ mutable quint32 m_keyNumber;
};
QDataStream &operator<<(QDataStream &out, const ValuesChangedCommand &command);
diff --git a/share/qtcreator/qml/qmlpuppet/container/imagecontainer.cpp b/share/qtcreator/qml/qmlpuppet/container/imagecontainer.cpp
index 8095c016fb..8b26d407ac 100644
--- a/share/qtcreator/qml/qmlpuppet/container/imagecontainer.cpp
+++ b/share/qtcreator/qml/qmlpuppet/container/imagecontainer.cpp
@@ -29,15 +29,30 @@
#include "imagecontainer.h"
+#include <QSharedMemory>
+#include <QCache>
+
+#include <cstring>
+
+#define QTC_ASSERT_STRINGIFY_HELPER(x) #x
+#define QTC_ASSERT_STRINGIFY(x) QTC_ASSERT_STRINGIFY_HELPER(x)
+#define QTC_ASSERT_STRING(cond) qDebug("SOFT ASSERT: \"" cond"\" in file " __FILE__ ", line " QTC_ASSERT_STRINGIFY(__LINE__))
+#define QTC_ASSERT(cond, action) if (cond) {} else { QTC_ASSERT_STRING(#cond); action; } do {} while (0)
+
namespace QmlDesigner {
+static QCache<qint32, QSharedMemory> globalSharedMemoryCache(10000);
+
ImageContainer::ImageContainer()
- : m_instanceId(-1)
+ : m_instanceId(-1),
+ m_keyNumber(-2)
{
}
-ImageContainer::ImageContainer(qint32 instanceId, const QImage &image)
- : m_image(image), m_instanceId(instanceId)
+ImageContainer::ImageContainer(qint32 instanceId, const QImage &image, qint32 keyNumber)
+ : m_image(image),
+ m_instanceId(instanceId),
+ m_keyNumber(keyNumber)
{
}
@@ -51,39 +66,167 @@ QImage ImageContainer::image() const
return m_image;
}
-QDataStream &operator<<(QDataStream &out, const ImageContainer &container)
+qint32 ImageContainer::keyNumber() const
{
- out << container.instanceId();
+ return m_keyNumber;
+}
- const QImage image = container.image();
- const QByteArray data(reinterpret_cast<const char*>(image.constBits()), image.byteCount());
+void ImageContainer::setImage(const QImage &image)
+{
+ QTC_ASSERT(m_image.isNull(), /**/);
+
+ m_image = image;
+}
+
+void ImageContainer::removeSharedMemorys(const QVector<qint32> &keyNumberVector)
+{
+ foreach (qint32 keyNumber, keyNumberVector) {
+ QSharedMemory *sharedMemory = globalSharedMemoryCache.take(keyNumber);
+ delete sharedMemory;
+ }
+}
+
+static const QLatin1String imageKeyTemplateString("Image-%1");
+
+static QSharedMemory *createSharedMemory(qint32 key, int byteCount)
+{
+ QSharedMemory *sharedMemory = globalSharedMemoryCache.take(key);
+
+ if (sharedMemory == 0)
+ sharedMemory = new QSharedMemory(QString(imageKeyTemplateString).arg(key));
+
+ bool sharedMemoryIsCreated = sharedMemory->isAttached();
+ if (!sharedMemoryIsCreated)
+ sharedMemoryIsCreated = sharedMemory->attach();
+
+ bool sharedMemorySizeIsSmallerThanByteCount = sharedMemory->size() < byteCount;
+ bool sharedMemorySizeIsDoubleBiggerThanByteCount = sharedMemory->size() * 2 > byteCount;
+
+ if (!sharedMemoryIsCreated || sharedMemorySizeIsSmallerThanByteCount || sharedMemorySizeIsDoubleBiggerThanByteCount) {
+ sharedMemory->detach();
+ sharedMemoryIsCreated = sharedMemory->create(byteCount);
+ }
+
+ if (sharedMemoryIsCreated) {
+ globalSharedMemoryCache.insert(key, sharedMemory);
+ return sharedMemory;
+ }
+
+ return 0;
+}
+static void writeSharedMemory(QSharedMemory *sharedMemory, const QImage &image)
+{
+ sharedMemory->lock();
+
+ qint32 headerData[5];
+ headerData[0] = image.byteCount();
+ headerData[1] = image.bytesPerLine();
+ headerData[2] = image.size().width();
+ headerData[3] = image.size().height();
+ headerData[4] = image.format();
+
+ std::memcpy(sharedMemory->data(), headerData, 20);
+ std::memcpy(reinterpret_cast<char*>(sharedMemory->data()) + 20, image.constBits(), image.byteCount());
+
+ sharedMemory->unlock();
+}
+
+static void writeStream(QDataStream &out, const QImage &image)
+{
out << qint32(image.bytesPerLine());
out << image.size();
out << qint32(image.format());
out << qint32(image.byteCount());
out.writeRawData(reinterpret_cast<const char*>(image.constBits()), image.byteCount());
+}
+
+QDataStream &operator<<(QDataStream &out, const ImageContainer &container)
+{
+ const int extraDataSize = 20;
+ static const bool dontUseSharedMemory = !qgetenv("DESIGNER_DONT_USE_SHARED_MEMORY").isEmpty();
+
+ out << container.instanceId();
+ out << container.keyNumber();
+
+ const QImage image = container.image();
+
+ if (dontUseSharedMemory) {
+ out << qint32(0);
+ writeStream(out, image);
+ } else {
+ QSharedMemory *sharedMemory = createSharedMemory(container.keyNumber(), image.byteCount() + extraDataSize);
+
+ out << qint32(sharedMemory != 0); // send if shared memory is used
+
+ if (sharedMemory)
+ writeSharedMemory(sharedMemory, image);
+ else
+ writeStream(out, image);
+ }
return out;
}
-QDataStream &operator>>(QDataStream &in, ImageContainer &container)
+static void readSharedMemory(qint32 key, ImageContainer &container)
{
+ QSharedMemory sharedMemory(QString(imageKeyTemplateString).arg(key));
+
+ bool canAttach = sharedMemory.attach(QSharedMemory::ReadOnly);
+
+ if (canAttach && sharedMemory.size() >= 20)
+ {
+ sharedMemory.lock();
+ qint32 headerData[5];
+ std::memcpy(headerData, sharedMemory.constData(), 20);
+
+ qint32 byteCount = headerData[0];
+// qint32 bytesPerLine = headerData[1];
+ qint32 imageWidth = headerData[2];
+ qint32 imageHeight = headerData[3];
+ qint32 imageFormat = headerData[4];
+
+ QImage image = QImage(imageWidth, imageHeight, QImage::Format(imageFormat));
+
+ std::memcpy(image.bits(), reinterpret_cast<const qint32*>(sharedMemory.constData()) + 5, byteCount);
- qint32 byteSize;
+ container.setImage(image);
+
+ sharedMemory.unlock();
+ }
+}
+
+static void readStream(QDataStream &in, ImageContainer &container)
+{
+ qint32 byteCount;
qint32 bytesPerLine;
QSize imageSize;
- qint32 format;
-
- in >> container.m_instanceId;
+ qint32 imageFormat;
in >> bytesPerLine;
in >> imageSize;
- in >> format;
- in >> byteSize;
+ in >> imageFormat;
+ in >> byteCount;
+
+ QImage image = QImage(imageSize, QImage::Format(imageFormat));
+
+ in.readRawData(reinterpret_cast<char*>(image.bits()), byteCount);
+
+ container.setImage(image);
+}
+
+QDataStream &operator>>(QDataStream &in, ImageContainer &container)
+{
+ qint32 sharedMemoryIsUsed;
+
+ in >> container.m_instanceId;
+ in >> container.m_keyNumber;
+ in >> sharedMemoryIsUsed;
- container.m_image = QImage(imageSize, QImage::Format(format));
- in.readRawData(reinterpret_cast<char*>(container.m_image.bits()), byteSize);
+ if (sharedMemoryIsUsed) {
+ readSharedMemory(container.keyNumber(), container);
+ } else
+ readStream(in, container);
return in;
}
diff --git a/share/qtcreator/qml/qmlpuppet/container/imagecontainer.h b/share/qtcreator/qml/qmlpuppet/container/imagecontainer.h
index 72e7c0d9de..0e15dbd75c 100644
--- a/share/qtcreator/qml/qmlpuppet/container/imagecontainer.h
+++ b/share/qtcreator/qml/qmlpuppet/container/imagecontainer.h
@@ -40,14 +40,20 @@ class ImageContainer
friend QDataStream &operator>>(QDataStream &in, ImageContainer &container);
public:
ImageContainer();
- ImageContainer(qint32 instanceId, const QImage &image);
+ ImageContainer(qint32 instanceId, const QImage &image, qint32 keyNumber);
qint32 instanceId() const;
QImage image() const;
+ qint32 keyNumber() const;
+
+ void setImage(const QImage &image);
+
+ static void removeSharedMemorys(const QVector<qint32> &keyNumberVector);
private:
QImage m_image;
qint32 m_instanceId;
+ qint32 m_keyNumber;
};
QDataStream &operator<<(QDataStream &out, const ImageContainer &container);
diff --git a/share/qtcreator/qml/qmlpuppet/container/instancecontainer.cpp b/share/qtcreator/qml/qmlpuppet/container/instancecontainer.cpp
index 03e56b6a72..b885c7d993 100644
--- a/share/qtcreator/qml/qmlpuppet/container/instancecontainer.cpp
+++ b/share/qtcreator/qml/qmlpuppet/container/instancecontainer.cpp
@@ -29,6 +29,8 @@
#include "instancecontainer.h"
+#include <QDataStream>
+
namespace QmlDesigner {
InstanceContainer::InstanceContainer()
diff --git a/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.cpp b/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.cpp
index 9ddac9e0a5..711b0dc793 100644
--- a/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.cpp
+++ b/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.cpp
@@ -29,6 +29,8 @@
#include "reparentcontainer.h"
+#include <QDataStream>
+
namespace QmlDesigner {
ReparentContainer::ReparentContainer()
diff --git a/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.h b/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.h
index e3e11a29a8..db2e1872cd 100644
--- a/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.h
+++ b/share/qtcreator/qml/qmlpuppet/container/reparentcontainer.h
@@ -31,6 +31,7 @@
#define REPARENTCONTAINER_H
#include <qmetatype.h>
+#include <QString>
#include <QDataStream>
namespace QmlDesigner {
diff --git a/share/qtcreator/qml/qmlpuppet/instances/instances.pri b/share/qtcreator/qml/qmlpuppet/instances/instances.pri
index b9ed533142..daf1d3ed51 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/instances.pri
+++ b/share/qtcreator/qml/qmlpuppet/instances/instances.pri
@@ -1,35 +1,5 @@
INCLUDEPATH += $$PWD/
-HEADERS += $$PWD/behaviornodeinstance.h
-
-HEADERS += $$PWD/dummycontextobject.h
-
-HEADERS += $$PWD/childrenchangeeventfilter.h
-HEADERS += $$PWD/componentnodeinstance.h
-HEADERS += $$PWD/dummynodeinstance.h
HEADERS += $$PWD/nodeinstanceclientproxy.h
-HEADERS += $$PWD/nodeinstancemetaobject.h
-HEADERS += $$PWD/nodeinstanceserver.h
-HEADERS += $$PWD/nodeinstancesignalspy.h
-HEADERS += $$PWD/objectnodeinstance.h
-HEADERS += $$PWD/qmlpropertychangesnodeinstance.h
-HEADERS += $$PWD/qmlstatenodeinstance.h
-HEADERS += $$PWD/qmltransitionnodeinstance.h
-HEADERS += $$PWD/servernodeinstance.h
-HEADERS += $$PWD/anchorchangesnodeinstance.h
-SOURCES += $$PWD/behaviornodeinstance.cpp
-SOURCES += $$PWD/dummycontextobject.cpp
-SOURCES += $$PWD/childrenchangeeventfilter.cpp
-SOURCES += $$PWD/componentnodeinstance.cpp
-SOURCES += $$PWD/dummynodeinstance.cpp
SOURCES += $$PWD/nodeinstanceclientproxy.cpp
-SOURCES += $$PWD/nodeinstancemetaobject.cpp
-SOURCES += $$PWD/nodeinstanceserver.cpp
-SOURCES += $$PWD/nodeinstancesignalspy.cpp
-SOURCES += $$PWD/objectnodeinstance.cpp
-SOURCES += $$PWD/qmlpropertychangesnodeinstance.cpp
-SOURCES += $$PWD/qmlstatenodeinstance.cpp
-SOURCES += $$PWD/qmltransitionnodeinstance.cpp
-SOURCES += $$PWD/servernodeinstance.cpp
-SOURCES += $$PWD/anchorchangesnodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.cpp b/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.cpp
index c7f99bb38f..05fd208112 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.cpp
+++ b/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.cpp
@@ -54,6 +54,7 @@
#include "changestatecommand.h"
#include "completecomponentcommand.h"
#include "synchronizecommand.h"
+#include "removesharedmemorycommand.h"
#include "tokencommand.h"
#include "informationchangedcommand.h"
@@ -64,6 +65,8 @@
#include "statepreviewimagechangedcommand.h"
#include "componentcompletedcommand.h"
#include "changenodesourcecommand.h"
+#include "endpuppetcommand.h"
+#include "debugoutputcommand.h"
namespace QmlDesigner {
@@ -92,7 +95,6 @@ void NodeInstanceClientProxy::writeCommand(const QVariant &command)
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_8);
-
out << quint32(0);
out << quint32(m_writeCommandCounter);
m_writeCommandCounter++;
@@ -138,6 +140,11 @@ void NodeInstanceClientProxy::token(const TokenCommand &command)
writeCommand(QVariant::fromValue(command));
}
+void NodeInstanceClientProxy::debugOutput(const DebugOutputCommand &command)
+{
+ writeCommand(QVariant::fromValue(command));
+}
+
void NodeInstanceClientProxy::flush()
{
}
@@ -276,11 +283,22 @@ void NodeInstanceClientProxy::changeNodeSource(const ChangeNodeSourceCommand &co
{
nodeInstanceServer()->changeNodeSource(command);
}
+
+void NodeInstanceClientProxy::removeSharedMemory(const RemoveSharedMemoryCommand &command)
+{
+ nodeInstanceServer()->removeSharedMemory(command);
+}
void NodeInstanceClientProxy::redirectToken(const TokenCommand &command)
{
nodeInstanceServer()->token(command);
}
+void NodeInstanceClientProxy::redirectToken(const EndPuppetCommand & /*command*/)
+{
+ qDebug() << "End Process: " << QCoreApplication::applicationPid();
+ QCoreApplication::exit();
+}
+
void NodeInstanceClientProxy::dispatchCommand(const QVariant &command)
{
static const int createInstancesCommandType = QMetaType::type("CreateInstancesCommand");
@@ -298,7 +316,9 @@ void NodeInstanceClientProxy::dispatchCommand(const QVariant &command)
static const int completeComponentCommandType = QMetaType::type("CompleteComponentCommand");
static const int synchronizeCommandType = QMetaType::type("SynchronizeCommand");
static const int changeNodeSourceCommandType = QMetaType::type("ChangeNodeSourceCommand");
+ static const int removeSharedMemoryCommandType = QMetaType::type("RemoveSharedMemoryCommand");
static const int tokenCommandType = QMetaType::type("TokenCommand");
+ static const int endPuppetCommandType = QMetaType::type("EndPuppetCommand");
if (command.userType() == createInstancesCommandType) {
createInstances(command.value<CreateInstancesCommand>());
@@ -328,8 +348,12 @@ void NodeInstanceClientProxy::dispatchCommand(const QVariant &command)
completeComponent(command.value<CompleteComponentCommand>());
else if (command.userType() == changeNodeSourceCommandType)
changeNodeSource(command.value<ChangeNodeSourceCommand>());
+ else if (command.userType() == removeSharedMemoryCommandType)
+ removeSharedMemory(command.value<RemoveSharedMemoryCommand>());
else if (command.userType() == tokenCommandType)
redirectToken(command.value<TokenCommand>());
+ else if (command.userType() == endPuppetCommandType)
+ redirectToken(command.value<EndPuppetCommand>());
else if (command.userType() == synchronizeCommandType) {
SynchronizeCommand synchronizeCommand = command.value<SynchronizeCommand>();
m_synchronizeId = synchronizeCommand.synchronizeId();
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.h b/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.h
index dffd19d5e8..cf7e038ac1 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.h
+++ b/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceclientproxy.h
@@ -57,6 +57,7 @@ class RemovePropertiesCommand;
class CompleteComponentCommand;
class ChangeStateCommand;
class ChangeNodeSourceCommand;
+class EndPuppetCommand;
class NodeInstanceClientProxy : public QObject, public NodeInstanceClientInterface
@@ -71,8 +72,9 @@ public:
void pixmapChanged(const PixmapChangedCommand &command);
void childrenChanged(const ChildrenChangedCommand &command);
void statePreviewImagesChanged(const StatePreviewImageChangedCommand &command);
- void componentCompleted(const ComponentCompletedCommand &command);
+ void componentCompleted(const ComponentCompletedCommand &command);
void token(const TokenCommand &command);
+ void debugOutput(const DebugOutputCommand &command);
void flush();
void synchronizeWithClientProcess();
@@ -99,7 +101,9 @@ protected:
void changeState(const ChangeStateCommand &command);
void completeComponent(const CompleteComponentCommand &command);
void changeNodeSource(const ChangeNodeSourceCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
void redirectToken(const TokenCommand &command);
+ void redirectToken(const EndPuppetCommand &command);
private slots:
void readDataStream();
diff --git a/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceclientinterface.h b/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceclientinterface.h
index 2ed876ea93..064e9b6d9d 100644
--- a/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceclientinterface.h
+++ b/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceclientinterface.h
@@ -41,6 +41,8 @@ class ChildrenChangedCommand;
class StatePreviewImageChangedCommand;
class ComponentCompletedCommand;
class TokenCommand;
+class RemoveSharedMemoryCommand;
+class DebugOutputCommand;
class NodeInstanceClientInterface
{
@@ -52,6 +54,7 @@ public:
virtual void statePreviewImagesChanged(const StatePreviewImageChangedCommand &command) = 0;
virtual void componentCompleted(const ComponentCompletedCommand &command) = 0;
virtual void token(const TokenCommand &command) = 0;
+ virtual void debugOutput(const DebugOutputCommand &command) = 0;
virtual void flush() {};
virtual void synchronizeWithClientProcess() {}
diff --git a/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.cpp b/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.cpp
index 70590c6419..9155a4b17f 100644
--- a/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.cpp
+++ b/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.cpp
@@ -59,7 +59,9 @@
#include "componentcompletedcommand.h"
#include "synchronizecommand.h"
#include "tokencommand.h"
-
+#include "removesharedmemorycommand.h"
+#include "endpuppetcommand.h"
+#include "debugoutputcommand.h"
namespace QmlDesigner {
@@ -170,6 +172,15 @@ void NodeInstanceServerInterface::registerCommands()
qRegisterMetaType<TokenCommand>("TokenCommand");
qRegisterMetaTypeStreamOperators<TokenCommand>("TokenCommand");
+
+ qRegisterMetaType<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
+ qRegisterMetaTypeStreamOperators<RemoveSharedMemoryCommand>("RemoveSharedMemoryCommand");
+
+ qRegisterMetaType<EndPuppetCommand>("EndPuppetCommand");
+ qRegisterMetaTypeStreamOperators<EndPuppetCommand>("EndPuppetCommand");
+
+ qRegisterMetaType<DebugOutputCommand>("DebugOutputCommand");
+ qRegisterMetaTypeStreamOperators<DebugOutputCommand>("DebugOutputCommand");
}
}
diff --git a/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.h b/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.h
index f4f554e302..5abd5cadef 100644
--- a/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.h
+++ b/share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.h
@@ -53,6 +53,7 @@ class ChangeStateCommand;
class CompleteComponentCommand;
class ChangeNodeSourceCommand;
class TokenCommand;
+class RemoveSharedMemoryCommand;
class NodeInstanceServerInterface : public QObject
{
@@ -80,6 +81,7 @@ public:
virtual void completeComponent(const CompleteComponentCommand &command) = 0;
virtual void changeNodeSource(const ChangeNodeSourceCommand &command) = 0;
virtual void token(const TokenCommand &command) = 0;
+ virtual void removeSharedMemory(const RemoveSharedMemoryCommand &command) = 0;
static void registerCommands();
};
diff --git a/share/qtcreator/qml/qmlpuppet/instances/anchorchangesnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.cpp
index 41a34cc7a2..41a34cc7a2 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/anchorchangesnodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.h
new file mode 100644
index 0000000000..9205bd1cfd
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/anchorchangesnodeinstance.h
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+
+#ifndef QMLDESIGNER_ANCHORCHANGESNODEINSTANCE_H
+#define QMLDESIGNER_ANCHORCHANGESNODEINSTANCE_H
+
+#include "objectnodeinstance.h"
+
+#include <QPair>
+#include <QWeakPointer>
+
+QT_BEGIN_NAMESPACE
+class QQmlProperty;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+namespace Internal {
+
+class AnchorChangesNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<AnchorChangesNodeInstance> Pointer;
+ typedef QWeakPointer<AnchorChangesNodeInstance> WeakPointer;
+
+ static Pointer create(QObject *objectToBeWrapped);
+
+ virtual void setPropertyVariant(const QString &name, const QVariant &value);
+ virtual void setPropertyBinding(const QString &name, const QString &expression);
+ virtual QVariant property(const QString &name) const;
+ virtual void resetProperty(const QString &name);
+
+ using ObjectNodeInstance::reparent; // keep the virtual reparent(...) method around
+ void reparent(const ServerNodeInstance &oldParentInstance,
+ const QString &oldParentProperty,
+ const ServerNodeInstance &newParentInstance,
+ const QString &newParentProperty);
+
+protected:
+ AnchorChangesNodeInstance(QObject *object);
+ QObject *changesObject() const;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_ANCHORCHANGESNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.cpp
new file mode 100644
index 0000000000..ac8bd0f6ad
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.cpp
@@ -0,0 +1,92 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "behaviornodeinstance.h"
+
+#include <private/qquickbehavior_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+BehaviorNodeInstance::BehaviorNodeInstance(QObject *object)
+ : ObjectNodeInstance(object),
+ m_isEnabled(true)
+{
+}
+
+BehaviorNodeInstance::Pointer BehaviorNodeInstance::create(QObject *object)
+{
+ QQuickBehavior* behavior = qobject_cast<QQuickBehavior*>(object);
+
+ Q_ASSERT(behavior);
+
+ Pointer instance(new BehaviorNodeInstance(behavior));
+
+ instance->populateResetHashes();
+
+ behavior->setEnabled(false);
+
+ return instance;
+}
+
+void BehaviorNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ if (name == "enabled")
+ return;
+
+ ObjectNodeInstance::setPropertyVariant(name, value);
+}
+
+void BehaviorNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+{
+ if (name == "enabled")
+ return;
+
+ ObjectNodeInstance::setPropertyBinding(name, expression);
+}
+
+QVariant BehaviorNodeInstance::property(const QString &name) const
+{
+ if (name == "enabled")
+ return QVariant::fromValue(m_isEnabled);
+
+ return ObjectNodeInstance::property(name);
+}
+
+void BehaviorNodeInstance::resetProperty(const QString &name)
+{
+ if (name == "enabled")
+ m_isEnabled = true;
+
+ ObjectNodeInstance::resetProperty(name);
+}
+
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/instances/behaviornodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.h
index 91dc0cef70..91dc0cef70 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/behaviornodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/behaviornodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/instances/childrenchangeeventfilter.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/childrenchangeeventfilter.cpp
index 608d28d13a..608d28d13a 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/childrenchangeeventfilter.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/childrenchangeeventfilter.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/childrenchangeeventfilter.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/childrenchangeeventfilter.h
index f69eb1dc67..f69eb1dc67 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/childrenchangeeventfilter.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/childrenchangeeventfilter.h
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.cpp
new file mode 100644
index 0000000000..59f090f970
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.cpp
@@ -0,0 +1,93 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#include "componentnodeinstance.h"
+
+#include <QQmlComponent>
+#include <QQmlContext>
+
+#include <QDebug>
+
+namespace QmlDesigner {
+namespace Internal {
+
+
+ComponentNodeInstance::ComponentNodeInstance(QQmlComponent *component)
+ : ObjectNodeInstance(component)
+{
+}
+
+QQmlComponent *ComponentNodeInstance::component() const
+{
+ Q_ASSERT(qobject_cast<QQmlComponent*>(object()));
+ return static_cast<QQmlComponent*>(object());
+}
+
+ComponentNodeInstance::Pointer ComponentNodeInstance::create(QObject *object)
+{
+ QQmlComponent *component = qobject_cast<QQmlComponent *>(object);
+
+ Q_ASSERT(component);
+
+ Pointer instance(new ComponentNodeInstance(component));
+
+ instance->populateResetHashes();
+
+ return instance;
+}
+
+bool ComponentNodeInstance::hasContent() const
+{
+ return true;
+}
+
+void ComponentNodeInstance::setNodeSource(const QString &source)
+{
+ QByteArray importArray;
+ foreach (const QString &import, nodeInstanceServer()->imports()) {
+ importArray.append(import.toUtf8());
+ }
+
+ QByteArray data(source.toUtf8());
+
+ data.prepend(importArray);
+ data.append("\n");
+
+ component()->setData(data, QUrl(nodeInstanceServer()->fileUrl().toString() +
+ QLatin1Char('_')+ id()));
+ setId(id());
+
+ if (component()->isError()) {
+ foreach (const QQmlError &error, component()->errors())
+ qDebug() << error;
+ }
+
+}
+
+} // Internal
+} // QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.h
new file mode 100644
index 0000000000..a16f798de9
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/componentnodeinstance.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef COMPONENTNODEINSTANCE_H
+#define COMPONENTNODEINSTANCE_H
+
+#include "objectnodeinstance.h"
+
+QT_BEGIN_NAMESPACE
+class QQmlComponent;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+namespace Internal {
+
+class ComponentNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<ComponentNodeInstance> Pointer;
+ typedef QWeakPointer<ComponentNodeInstance> WeakPointer;
+ ComponentNodeInstance(QQmlComponent *component);
+ static Pointer create(QObject *objectToBeWrapped);
+
+ bool hasContent() const;
+
+ void setNodeSource(const QString &source);
+
+private: //function
+ QQmlComponent *component() const;
+
+};
+
+} // Internal
+} // QmlDesigner
+
+#endif // COMPONENTNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/instances/dummycontextobject.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummycontextobject.cpp
index 9d04a30460..9d04a30460 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/dummycontextobject.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummycontextobject.cpp
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummycontextobject.h
index 10e22c60b5..10adcca087 100644
--- a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummycontextobject.h
@@ -27,30 +27,34 @@
**
****************************************************************************/
-#ifndef CUSTOMSTYLEPLUGIN_H
-#define CUSTOMSTYLEPLUGIN_H
+#ifndef DUMMYCONTEXTOBJECT_H
+#define DUMMYCONTEXTOBJECT_H
-#include <iwidgetplugin.h>
+#include <QObject>
+#include <QPointer>
+#include <qqml.h>
namespace QmlDesigner {
-class CustomStylePlugin : public QObject, QmlDesigner::IWidgetPlugin
+class DummyContextObject : public QObject
{
Q_OBJECT
-#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QmlDesignerPlugin" FILE "customstyleplugin.json")
-#endif
- Q_INTERFACES(QmlDesigner::IWidgetPlugin)
+ Q_PROPERTY(QObject * parent READ parentDummy WRITE setParentDummy NOTIFY parentDummyChanged DESIGNABLE false FINAL)
public:
- CustomStylePlugin();
- ~CustomStylePlugin() {}
+ explicit DummyContextObject(QObject *parent = 0);
- QString metaInfo() const;
- QString pluginName() const;
+ QObject *parentDummy() const;
+ void setParentDummy(QObject *parentDummy);
+signals:
+ void parentDummyChanged();
+
+private:
+ QPointer<QObject> m_dummyParent;
};
} // namespace QmlDesigner
-#endif // CUSTOMSTYLEPLUGIN_H
+QML_DECLARE_TYPE(QmlDesigner::DummyContextObject)
+#endif // DUMMYCONTEXTOBJECT_H
diff --git a/share/qtcreator/qml/qmlpuppet/instances/dummynodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummynodeinstance.cpp
index 3ee9ae4eff..3ee9ae4eff 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/dummynodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummynodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/dummynodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummynodeinstance.h
index 357dcb4263..357dcb4263 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/dummynodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/dummynodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/instances.pri b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/instances.pri
index 1eeb3d40b5..28a733cf66 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/instances.pri
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/instances.pri
@@ -1,15 +1,45 @@
INCLUDEPATH += $$PWD/
-HEADERS += $$PWD/qt5nodeinstanceserver.h \
- instances/qt5informationnodeinstanceserver.h \
- instances/qt5rendernodeinstanceserver.h \
- instances/qt5previewnodeinstanceserver.h
+HEADERS += $$PWD/qt5nodeinstanceserver.h
+HEADERS += $$PWD/qt5informationnodeinstanceserver.h
+HEADERS += $$PWD/qt5rendernodeinstanceserver.h
+HEADERS += $$PWD/qt5previewnodeinstanceserver.h
HEADERS += $$PWD/qt5nodeinstanceclientproxy.h
-HEADERS += $$PWD/sgitemnodeinstance.h
+HEADERS += $$PWD/quickitemnodeinstance.h
+HEADERS += $$PWD/behaviornodeinstance.h
+HEADERS += $$PWD/dummycontextobject.h
+HEADERS += $$PWD/childrenchangeeventfilter.h
+HEADERS += $$PWD/componentnodeinstance.h
+HEADERS += $$PWD/dummynodeinstance.h
+HEADERS += $$PWD/nodeinstancemetaobject.h
+HEADERS += $$PWD/nodeinstanceserver.h
+HEADERS += $$PWD/nodeinstancesignalspy.h
+HEADERS += $$PWD/objectnodeinstance.h
+HEADERS += $$PWD/qmlpropertychangesnodeinstance.h
+HEADERS += $$PWD/qmlstatenodeinstance.h
+HEADERS += $$PWD/qmltransitionnodeinstance.h
+HEADERS += $$PWD/servernodeinstance.h
+HEADERS += $$PWD/anchorchangesnodeinstance.h
+HEADERS += $$PWD/positionernodeinstance.h
-SOURCES += $$PWD/qt5nodeinstanceserver.cpp \
- instances/qt5informationnodeinstanceserver.cpp \
- instances/qt5rendernodeinstanceserver.cpp \
- instances/qt5previewnodeinstanceserver.cpp
+SOURCES += $$PWD/qt5nodeinstanceserver.cpp
+SOURCES += $$PWD/qt5informationnodeinstanceserver.cpp
+SOURCES += $$PWD/qt5rendernodeinstanceserver.cpp
+SOURCES += $$PWD/qt5previewnodeinstanceserver.cpp
SOURCES += $$PWD/qt5nodeinstanceclientproxy.cpp
-SOURCES += $$PWD/sgitemnodeinstance.cpp
+SOURCES += $$PWD/quickitemnodeinstance.cpp
+SOURCES += $$PWD/behaviornodeinstance.cpp
+SOURCES += $$PWD/dummycontextobject.cpp
+SOURCES += $$PWD/childrenchangeeventfilter.cpp
+SOURCES += $$PWD/componentnodeinstance.cpp
+SOURCES += $$PWD/dummynodeinstance.cpp
+SOURCES += $$PWD/nodeinstancemetaobject.cpp
+SOURCES += $$PWD/nodeinstanceserver.cpp
+SOURCES += $$PWD/nodeinstancesignalspy.cpp
+SOURCES += $$PWD/objectnodeinstance.cpp
+SOURCES += $$PWD/qmlpropertychangesnodeinstance.cpp
+SOURCES += $$PWD/qmlstatenodeinstance.cpp
+SOURCES += $$PWD/qmltransitionnodeinstance.cpp
+SOURCES += $$PWD/servernodeinstance.cpp
+SOURCES += $$PWD/anchorchangesnodeinstance.cpp
+SOURCES += $$PWD/positionernodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.cpp
new file mode 100644
index 0000000000..5ffdd8c185
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.cpp
@@ -0,0 +1,359 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "nodeinstancemetaobject.h"
+
+#include "objectnodeinstance.h"
+#include <QSharedPointer>
+#include <QMetaProperty>
+#include <qnumeric.h>
+#include <QDebug>
+
+#include <private/qqmlengine_p.h>
+#include <private/qqmlpropertycache_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+static QHash<QDynamicMetaObjectData *, bool> nodeInstanceMetaObjectList;
+
+struct MetaPropertyData {
+ inline QPair<QVariant, bool> &getDataRef(int idx) {
+ while (m_data.count() <= idx)
+ m_data << QPair<QVariant, bool>(QVariant(), false);
+ return m_data[idx];
+ }
+
+ inline QVariant &getData(int idx) {
+ QPair<QVariant, bool> &prop = getDataRef(idx);
+ if (!prop.second) {
+ prop.first = QVariant();
+ prop.second = true;
+ }
+ return prop.first;
+ }
+
+ inline bool hasData(int idx) const {
+ if (idx >= m_data.count())
+ return false;
+ return m_data[idx].second;
+ }
+
+ inline int count() { return m_data.count(); }
+
+ QList<QPair<QVariant, bool> > m_data;
+};
+
+static bool constructedMetaData(const QQmlVMEMetaData* data)
+{
+ return data->varPropertyCount == 0
+ && data->propertyCount == 0
+ && data->aliasCount == 0
+ && data->signalCount == 0
+ && data->methodCount == 0;
+}
+
+static QQmlVMEMetaData* fakeMetaData()
+{
+ QQmlVMEMetaData* data = new QQmlVMEMetaData;
+ data->varPropertyCount = 0;
+ data->propertyCount = 0;
+ data->aliasCount = 0;
+ data->signalCount = 0;
+ data->methodCount = 0;
+
+ return data;
+}
+
+static const QQmlVMEMetaData* vMEMetaDataForObject(QObject *object)
+{
+ QQmlVMEMetaObject *metaObject = QQmlVMEMetaObject::get(object);
+ if (metaObject)
+ return metaObject->metaData;
+
+ return fakeMetaData();
+}
+
+static QQmlPropertyCache *cacheForObject(QObject *object, QQmlEngine *engine)
+{
+ QQmlVMEMetaObject *metaObject = QQmlVMEMetaObject::get(object);
+ if (metaObject)
+ return metaObject->cache;
+
+ return QQmlEnginePrivate::get(engine)->cache(object);
+}
+
+NodeInstanceMetaObject *NodeInstanceMetaObject::createNodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QQmlEngine *engine)
+{
+ //Avoid setting up multiple NodeInstanceMetaObjects on the same QObject
+ QObjectPrivate *op = QObjectPrivate::get(nodeInstance->object());
+ QDynamicMetaObjectData *parent = op->metaObject;
+ if (nodeInstanceMetaObjectList.contains(parent))
+ return static_cast<NodeInstanceMetaObject *>(parent);
+
+ return new NodeInstanceMetaObject(nodeInstance, engine);
+}
+
+NodeInstanceMetaObject *NodeInstanceMetaObject::createNodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QObject *object, const QString &prefix, QQmlEngine *engine)
+{
+ //Avoid setting up multiple NodeInstanceMetaObjects on the same QObject
+ QObjectPrivate *op = QObjectPrivate::get(nodeInstance->object());
+ QDynamicMetaObjectData *parent = op->metaObject;
+ if (nodeInstanceMetaObjectList.contains(parent))
+ return static_cast<NodeInstanceMetaObject *>(parent);
+
+ return new NodeInstanceMetaObject(nodeInstance, object, prefix, engine);
+}
+
+void NodeInstanceMetaObject::init(QObject *object, QQmlEngine *engine)
+{
+ //Creating QQmlOpenMetaObjectType
+ m_type = new QQmlOpenMetaObjectType(metaObjectParent(), engine);
+ m_type->addref();
+ //Assigning type to this
+ copyTypeMetaObject();
+
+ //Assign this to object
+ QObjectPrivate *op = QObjectPrivate::get(object);
+ op->metaObject = this;
+
+ //create cache
+ cache = m_cache = QQmlEnginePrivate::get(engine)->cache(this);
+ cache->addref();
+
+ //If our parent is not a VMEMetaObject we just se the flag to false again
+ if (constructedMetaData(metaData))
+ QQmlData::get(object)->hasVMEMetaObject = false;
+
+ nodeInstanceMetaObjectList.insert(this, true);
+ hasAssignedMetaObjectData = true;
+}
+
+NodeInstanceMetaObject::NodeInstanceMetaObject(const ObjectNodeInstance::Pointer &nodeInstance, QQmlEngine *engine)
+ : QQmlVMEMetaObject(nodeInstance->object(), cacheForObject(nodeInstance->object(), engine), vMEMetaDataForObject(nodeInstance->object())),
+ m_nodeInstance(nodeInstance),
+ m_context(engine->contextForObject(nodeInstance->object())),
+ m_data(new MetaPropertyData),
+ m_cache(0)
+{
+ init(nodeInstance->object(), engine);
+
+ QQmlData *ddata = QQmlData::get(nodeInstance->object(), false);
+
+ //Assign cache to object
+ if (ddata && ddata->propertyCache) {
+ cache->setParent(ddata->propertyCache);
+ cache->invalidate(engine, this);
+ ddata->propertyCache = m_cache;
+ }
+
+}
+
+NodeInstanceMetaObject::NodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QObject *object, const QString &prefix, QQmlEngine *engine)
+ : QQmlVMEMetaObject(object, cacheForObject(object, engine), vMEMetaDataForObject(object)),
+ m_nodeInstance(nodeInstance),
+ m_prefix(prefix),
+ m_context(engine->contextForObject(object)),
+
+ m_data(new MetaPropertyData),
+ m_cache(0)
+{
+ init(object, engine);
+}
+
+NodeInstanceMetaObject::~NodeInstanceMetaObject()
+{
+ if (cache->count() > 1) // qml is chrashing because the property cache is not removed from the engine
+ cache->release();
+ else
+ m_type->release();
+
+ nodeInstanceMetaObjectList.remove(this);
+}
+
+void NodeInstanceMetaObject::createNewProperty(const QString &name)
+{
+ int id = createProperty(name.toLatin1(), 0);
+ setValue(id, QVariant());
+ Q_ASSERT(id >= 0);
+ Q_UNUSED(id);
+
+
+ //Updating cache
+ QQmlPropertyCache *oldParent = m_cache->parent();
+ QQmlEnginePrivate::get(m_context->engine())->cache(this)->invalidate(m_context->engine(), this);
+ m_cache->setParent(oldParent);
+
+ QQmlProperty property(myObject(), name, m_context);
+ Q_ASSERT(property.isValid());
+}
+
+int NodeInstanceMetaObject::createProperty(const char *name, const char *)
+{
+ int id = m_type->createProperty(name);
+ copyTypeMetaObject();
+ return id;
+}
+
+void NodeInstanceMetaObject::setValue(int id, const QVariant &value)
+{
+ QPair<QVariant, bool> &prop = m_data->getDataRef(id);
+ prop.first = propertyWriteValue(id, value);
+ prop.second = true;
+ QMetaObject::activate(myObject(), id + m_type->signalOffset(), 0);
+}
+
+QVariant NodeInstanceMetaObject::propertyWriteValue(int, const QVariant &value)
+{
+ return value;
+}
+
+int NodeInstanceMetaObject::openMetaCall(QMetaObject::Call call, int id, void **a)
+{
+ if ((call == QMetaObject::ReadProperty || call == QMetaObject::WriteProperty)
+ && id >= m_type->propertyOffset()) {
+ int propId = id - m_type->propertyOffset();
+ if (call == QMetaObject::ReadProperty) {
+ //propertyRead(propId);
+ *reinterpret_cast<QVariant *>(a[0]) = m_data->getData(propId);
+ } else if (call == QMetaObject::WriteProperty) {
+ if (propId <= m_data->count() || m_data->m_data[propId].first != *reinterpret_cast<QVariant *>(a[0])) {
+ //propertyWrite(propId);
+ QPair<QVariant, bool> &prop = m_data->getDataRef(propId);
+ prop.first = propertyWriteValue(propId, *reinterpret_cast<QVariant *>(a[0]));
+ prop.second = true;
+ //propertyWritten(propId);
+ activate(myObject(), m_type->signalOffset() + propId, 0);
+ }
+ }
+ return -1;
+ } else {
+ QAbstractDynamicMetaObject *directParent = parent();
+ if (directParent)
+ return directParent->metaCall(call, id, a);
+ else
+ return myObject()->qt_metacall(call, id, a);
+ }
+}
+
+int NodeInstanceMetaObject::metaCall(QMetaObject::Call call, int id, void **a)
+{
+ int metaCallReturnValue = -1;
+
+ const QMetaProperty propertyById = QQmlVMEMetaObject::property(id);
+
+ if (call == QMetaObject::WriteProperty
+ && propertyById.userType() == QMetaType::QVariant
+ && reinterpret_cast<QVariant *>(a[0])->type() == QVariant::Double
+ && qIsNaN(reinterpret_cast<QVariant *>(a[0])->toDouble())) {
+ return -1;
+ }
+
+ if (call == QMetaObject::WriteProperty
+ && propertyById.userType() == QMetaType::Double
+ && qIsNaN(*reinterpret_cast<double*>(a[0]))) {
+ return -1;
+ }
+
+ if (call == QMetaObject::WriteProperty
+ && propertyById.userType() == QMetaType::Float
+ && qIsNaN(*reinterpret_cast<float*>(a[0]))) {
+ return -1;
+ }
+
+ QVariant oldValue;
+
+ if (call == QMetaObject::WriteProperty && !propertyById.hasNotifySignal())
+ {
+ oldValue = propertyById.read(myObject());
+ }
+
+ ObjectNodeInstance::Pointer objectNodeInstance = m_nodeInstance.toStrongRef();
+
+ QAbstractDynamicMetaObject *directParent = parent();
+ if (directParent && id < directParent->propertyOffset()) {
+ metaCallReturnValue = directParent->metaCall(call, id, a);
+ } else {
+ openMetaCall(call, id, a);
+ }
+
+ if ((call == QMetaObject::WriteProperty || call == QMetaObject::ReadProperty) && metaCallReturnValue < 0) {
+ if (objectNodeInstance
+ && objectNodeInstance->nodeInstanceServer()
+ && objectNodeInstance->nodeInstanceServer()->dummyContextObject()
+ && !(objectNodeInstance && !objectNodeInstance->isRootNodeInstance()
+ && property(id).name() == QLatin1String("parent"))) {
+
+ QObject *contextDummyObject = objectNodeInstance->nodeInstanceServer()->dummyContextObject();
+ int properyIndex = contextDummyObject->metaObject()->indexOfProperty(propertyById.name());
+ if (properyIndex >= 0)
+ metaCallReturnValue = contextDummyObject->qt_metacall(call, properyIndex, a);
+ }
+ }
+
+ if (metaCallReturnValue >= 0
+ && call == QMetaObject::WriteProperty
+ && !propertyById.hasNotifySignal()
+ && oldValue != propertyById.read(myObject()))
+ notifyPropertyChange(id);
+
+ return metaCallReturnValue;
+}
+
+void NodeInstanceMetaObject::notifyPropertyChange(int id)
+{
+ ObjectNodeInstance::Pointer objectNodeInstance = m_nodeInstance.toStrongRef();
+ const QMetaProperty propertyById = property(id);
+
+ if (objectNodeInstance && objectNodeInstance->nodeInstanceServer()) {
+ if (id < propertyOffset()) {
+ objectNodeInstance->nodeInstanceServer()->notifyPropertyChange(objectNodeInstance->instanceId(), m_prefix + propertyById.name());
+ } else {
+ objectNodeInstance->nodeInstanceServer()->notifyPropertyChange(objectNodeInstance->instanceId(), m_prefix + name(id - propertyOffset()));
+ }
+ }
+}
+
+int NodeInstanceMetaObject::count() const
+{
+ return m_type->propertyCount();
+}
+
+QByteArray NodeInstanceMetaObject::name(int idx) const
+{
+ return m_type->propertyName(idx);
+}
+
+void NodeInstanceMetaObject::copyTypeMetaObject()
+{
+ *static_cast<QMetaObject *>(this) = *m_type->metaObject();
+}
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.h
new file mode 100644
index 0000000000..bd24359b16
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancemetaobject.h
@@ -0,0 +1,107 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef NODEINSTANCEMETAOBJECT_H
+#define NODEINSTANCEMETAOBJECT_H
+
+#include <QQmlContext>
+#include <QScopedPointer>
+#include <private/qqmlopenmetaobject_p.h>
+#include <private/qqmlvmemetaobject_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+class ObjectNodeInstance;
+typedef QSharedPointer<ObjectNodeInstance> ObjectNodeInstancePointer;
+typedef QWeakPointer<ObjectNodeInstance> ObjectNodeInstanceWeakPointer;
+
+struct MetaPropertyData;
+
+class NodeInstanceMetaObject : public QQmlVMEMetaObject
+{
+public:
+ static NodeInstanceMetaObject *createNodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QQmlEngine *engine);
+ static NodeInstanceMetaObject *createNodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QObject *object, const QString &prefix, QQmlEngine *engine);
+ ~NodeInstanceMetaObject();
+ void createNewProperty(const QString &name);
+
+protected:
+ NodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QQmlEngine *engine);
+ NodeInstanceMetaObject(const ObjectNodeInstancePointer &nodeInstance, QObject *object, const QString &prefix, QQmlEngine *engine);
+
+ int openMetaCall(QMetaObject::Call _c, int _id, void **_a);
+ int metaCall(QMetaObject::Call _c, int _id, void **_a);
+ void notifyPropertyChange(int id);
+ void setValue(int id, const QVariant &value);
+ int createProperty(const char *, const char *);
+ QVariant propertyWriteValue(int, const QVariant &);
+
+ QObject *myObject() const { return QQmlVMEMetaObject::object; }
+ QAbstractDynamicMetaObject *parent() const { return const_cast<QAbstractDynamicMetaObject *>(dynamicMetaObjectParent()); }
+
+ const QAbstractDynamicMetaObject *dynamicMetaObjectParent() const
+ {
+ if (QQmlVMEMetaObject::parent.isT1())
+ return QQmlVMEMetaObject::parent.asT1()->toDynamicMetaObject(QQmlVMEMetaObject::object);
+ else
+ return 0;
+ }
+
+ const QMetaObject *metaObjectParent() const
+ {
+ if (QQmlVMEMetaObject::parent.isT1())
+ return QQmlVMEMetaObject::parent.asT1()->toDynamicMetaObject(QQmlVMEMetaObject::object);
+
+ return QQmlVMEMetaObject::parent.asT2();
+ }
+
+ int propertyOffset() const { return cache->propertyOffset(); }
+
+ int count() const;
+ QByteArray name(int) const;
+
+ void copyTypeMetaObject();
+
+private:
+ void init(QObject *, QQmlEngine *engine);
+
+ ObjectNodeInstanceWeakPointer m_nodeInstance;
+ QString m_prefix;
+ QPointer<QQmlContext> m_context;
+ QQmlOpenMetaObjectType *m_type;
+ QScopedPointer<MetaPropertyData> m_data;
+ //QAbstractDynamicMetaObject *m_parent;
+ QQmlPropertyCache *m_cache;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // NODEINSTANCEMETAOBJECT_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.cpp
new file mode 100644
index 0000000000..c2ed5183dd
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.cpp
@@ -0,0 +1,1177 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#include "nodeinstanceserver.h"
+
+#include <QQmlEngine>
+#include <QFileSystemWatcher>
+#include <QUrl>
+#include <QSet>
+#include <QDir>
+#include <QVariant>
+#include <QMetaType>
+#include <QQmlComponent>
+#include <QQmlContext>
+#include <qqmllist.h>
+#include <QAbstractAnimation>
+#include <private/qabstractanimation_p.h>
+#include <QMutableVectorIterator>
+#include <private/qquickview_p.h>
+
+#include "servernodeinstance.h"
+#include "objectnodeinstance.h"
+#include "childrenchangeeventfilter.h"
+#include "propertyabstractcontainer.h"
+#include "propertybindingcontainer.h"
+#include "propertyvaluecontainer.h"
+#include "instancecontainer.h"
+#include "createinstancescommand.h"
+#include "changefileurlcommand.h"
+#include "clearscenecommand.h"
+#include "reparentinstancescommand.h"
+#include "changevaluescommand.h"
+#include "changeauxiliarycommand.h"
+#include "changebindingscommand.h"
+#include "changeidscommand.h"
+#include "removeinstancescommand.h"
+#include "nodeinstanceclientinterface.h"
+#include "removepropertiescommand.h"
+#include "valueschangedcommand.h"
+#include "informationchangedcommand.h"
+#include "pixmapchangedcommand.h"
+#include "commondefines.h"
+#include "childrenchangeeventfilter.h"
+#include "changestatecommand.h"
+#include "childrenchangedcommand.h"
+#include "completecomponentcommand.h"
+#include "componentcompletedcommand.h"
+#include "createscenecommand.h"
+#include "changenodesourcecommand.h"
+#include "tokencommand.h"
+#include "removesharedmemorycommand.h"
+
+#include "dummycontextobject.h"
+
+
+namespace QmlDesigner {
+
+NodeInstanceServer::NodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) :
+ NodeInstanceServerInterface(),
+ m_childrenChangeEventFilter(new Internal::ChildrenChangeEventFilter(this)),
+ m_nodeInstanceClient(nodeInstanceClient),
+ m_timer(0),
+ m_renderTimerInterval(16),
+ m_slowRenderTimer(false),
+ m_slowRenderTimerInterval(200)
+{
+ qmlRegisterType<DummyContextObject>("QmlDesigner", 1, 0, "DummyContextObject");
+
+ connect(m_childrenChangeEventFilter.data(), SIGNAL(childrenChanged(QObject*)), this, SLOT(emitParentChanged(QObject*)));
+}
+
+NodeInstanceServer::~NodeInstanceServer()
+{
+}
+
+QList<ServerNodeInstance> NodeInstanceServer::createInstances(const QVector<InstanceContainer> &containerVector)
+{
+ Q_ASSERT(declarativeView() || quickView());
+ QList<ServerNodeInstance> instanceList;
+ foreach (const InstanceContainer &instanceContainer, containerVector) {
+ ServerNodeInstance instance;
+ if (instanceContainer.nodeSourceType() == InstanceContainer::ComponentSource) {
+ instance = ServerNodeInstance::create(this, instanceContainer, ServerNodeInstance::WrapAsComponent);
+ } else {
+ instance = ServerNodeInstance::create(this, instanceContainer, ServerNodeInstance::DoNotWrapAsComponent);
+ }
+ insertInstanceRelationship(instance);
+ instanceList.append(instance);
+ instance.internalObject()->installEventFilter(childrenChangeEventFilter());
+ if (instanceContainer.instanceId() == 0) {
+ m_rootNodeInstance = instance;
+ resizeCanvasSizeToRootItemSize();
+ }
+
+ foreach (QQmlContext* context, allSubContextsForObject(instance.internalObject()))
+ setupDummysForContext(context);
+ }
+
+ return instanceList;
+}
+
+void NodeInstanceServer::createInstances(const CreateInstancesCommand &command)
+{
+ createInstances(command.instances());
+ refreshBindings();
+ startRenderTimer();
+}
+
+ServerNodeInstance NodeInstanceServer::instanceForId(qint32 id) const
+{
+ if (id < 0)
+ return ServerNodeInstance();
+
+ Q_ASSERT(m_idInstanceHash.contains(id));
+ return m_idInstanceHash.value(id);
+}
+
+bool NodeInstanceServer::hasInstanceForId(qint32 id) const
+{
+ if (id < 0)
+ return false;
+
+ return m_idInstanceHash.contains(id);
+}
+
+ServerNodeInstance NodeInstanceServer::instanceForObject(QObject *object) const
+{
+ Q_ASSERT(m_objectInstanceHash.contains(object));
+ return m_objectInstanceHash.value(object);
+}
+
+bool NodeInstanceServer::hasInstanceForObject(QObject *object) const
+{
+ if (object == 0)
+ return false;
+
+ return m_objectInstanceHash.contains(object);
+}
+
+void NodeInstanceServer::setRenderTimerInterval(int timerInterval)
+{
+ m_renderTimerInterval = timerInterval;
+}
+
+void NodeInstanceServer::setSlowRenderTimerInterval(int timerInterval)
+{
+ m_slowRenderTimerInterval = timerInterval;
+}
+
+void NodeInstanceServer::setTimerId(int timerId)
+{
+ m_timer = timerId;
+}
+
+int NodeInstanceServer::timerId() const
+{
+ return m_timer;
+}
+
+int NodeInstanceServer::renderTimerInterval() const
+{
+ return m_renderTimerInterval;
+}
+
+void NodeInstanceServer::startRenderTimer()
+{
+ if (m_slowRenderTimer)
+ stopRenderTimer();
+
+ if (m_timer == 0)
+ m_timer = startTimer(m_renderTimerInterval);
+
+ m_slowRenderTimer = false;
+}
+
+void NodeInstanceServer::slowDownRenderTimer()
+{
+ if (!m_slowRenderTimer)
+ stopRenderTimer();
+
+ if (m_timer != 0) {
+ killTimer(m_timer);
+ m_timer = 0;
+ }
+
+ if (m_timer == 0)
+ m_timer = startTimer(m_slowRenderTimerInterval);
+
+ m_slowRenderTimer = true;
+}
+
+void NodeInstanceServer::stopRenderTimer()
+{
+ if (m_timer) {
+ killTimer(m_timer);
+ m_timer = 0;
+ }
+}
+
+void NodeInstanceServer::createScene(const CreateSceneCommand &command)
+{
+ initializeView(command.imports());
+ QUnifiedTimer::instance()->setSlowdownFactor(0.00001);
+ QUnifiedTimer::instance()->setSlowModeEnabled(true);
+
+ QList<ServerNodeInstance> instanceList = setupScene(command);
+
+ refreshBindings();
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::clearScene(const ClearSceneCommand &/*command*/)
+{
+ stopRenderTimer();
+
+ removeAllInstanceRelationships();
+ m_fileSystemWatcherHash.clear();
+ m_rootNodeInstance.makeInvalid();
+ m_changedPropertyList.clear();
+ m_fileUrl.clear();
+}
+
+void NodeInstanceServer::removeInstances(const RemoveInstancesCommand &command)
+{
+ ServerNodeInstance oldState = activeStateInstance();
+ if (activeStateInstance().isValid())
+ activeStateInstance().deactivateState();
+
+ foreach (qint32 instanceId, command.instanceIds()) {
+ removeInstanceRelationsip(instanceId);
+ }
+
+ if (oldState.isValid())
+ oldState.activateState();
+
+ refreshBindings();
+ startRenderTimer();
+}
+
+void NodeInstanceServer::removeProperties(const RemovePropertiesCommand &command)
+{
+ bool hasDynamicProperties = false;
+ foreach (const PropertyAbstractContainer &container, command.properties()) {
+ hasDynamicProperties |= container.isDynamic();
+ resetInstanceProperty(container);
+ }
+
+ if (hasDynamicProperties)
+ refreshBindings();
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::reparentInstances(const QVector<ReparentContainer> &containerVector)
+{
+ foreach (const ReparentContainer &container, containerVector) {
+ ServerNodeInstance instance = instanceForId(container.instanceId());
+ if (instance.isValid()) {
+ instance.reparent(instanceForId(container.oldParentInstanceId()), container.oldParentProperty(), instanceForId(container.newParentInstanceId()), container.newParentProperty());
+ }
+ }
+
+}
+
+void NodeInstanceServer::reparentInstances(const ReparentInstancesCommand &command)
+{
+ reparentInstances(command.reparentInstances());
+ refreshBindings();
+ startRenderTimer();
+}
+
+void NodeInstanceServer::changeState(const ChangeStateCommand &command)
+{
+ if (hasInstanceForId(command.stateInstanceId())) {
+ if (activeStateInstance().isValid())
+ activeStateInstance().deactivateState();
+ ServerNodeInstance instance = instanceForId(command.stateInstanceId());
+ instance.activateState();
+ } else {
+ if (activeStateInstance().isValid())
+ activeStateInstance().deactivateState();
+ }
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::completeComponent(const CompleteComponentCommand &command)
+{
+ QList<ServerNodeInstance> instanceList;
+
+ foreach (qint32 instanceId, command.instances()) {
+ if (hasInstanceForId(instanceId)) {
+ ServerNodeInstance instance = instanceForId(instanceId);
+ instance.doComponentComplete();
+ instanceList.append(instance);
+ }
+ }
+
+ refreshBindings();
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::changeNodeSource(const ChangeNodeSourceCommand &command)
+{
+ if (hasInstanceForId(command.instanceId())) {
+ ServerNodeInstance instance = instanceForId(command.instanceId());
+ if (instance.isValid())
+ instance.setNodeSource(command.nodeSource());
+ }
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::token(const TokenCommand &/*command*/)
+{
+
+}
+
+void NodeInstanceServer::removeSharedMemory(const RemoveSharedMemoryCommand &/*command*/)
+{
+}
+
+void NodeInstanceServer::setupImports(const QVector<AddImportContainer> &containerVector)
+{
+ foreach (const AddImportContainer &container, containerVector) {
+ QString importStatement = QString("import ");
+
+ if (!container.fileName().isEmpty())
+ importStatement += '"' + container.fileName() + '"';
+ else if (!container.url().isEmpty())
+ importStatement += container.url().toString();
+
+ if (!container.version().isEmpty())
+ importStatement += ' ' + container.version();
+
+ if (!container.alias().isEmpty())
+ importStatement += " as " + container.alias();
+
+ importStatement.append('\n');
+
+ if (!m_importList.contains(importStatement))
+ m_importList.append(importStatement);
+ }
+
+ delete m_importComponent.data();
+ delete m_importComponentObject.data();
+
+ QString componentString;
+ foreach (const QString &importStatement, m_importList)
+ componentString += QString("%1").arg(importStatement);
+
+ componentString += QString("Item {}\n");
+
+ if (quickView()) {
+ QQuickViewPrivate::get(quickView())->component = new QQmlComponent(engine(), quickView());
+ m_importComponent = QQuickViewPrivate::get(quickView())->component;
+ } else {
+ m_importComponent = new QQmlComponent(engine(), 0);
+ }
+
+ m_importComponent->setData(componentString.toUtf8(), fileUrl());
+ m_importComponentObject = m_importComponent->create();
+
+ if (!m_importComponent->errorString().isEmpty())
+ qDebug() << "QmlDesigner.NodeInstances: import wrong: " << m_importComponent->errorString();
+}
+
+void NodeInstanceServer::setupFileUrl(const QUrl &fileUrl)
+{
+ if (!fileUrl.isEmpty()) {
+ engine()->setBaseUrl(fileUrl);
+ m_fileUrl = fileUrl;
+ }
+}
+
+void NodeInstanceServer::setupDummyData(const QUrl &fileUrl)
+{
+ if (!fileUrl.isEmpty()) {
+ QStringList dummyDataDirectoryList = dummyDataDirectories(QFileInfo(fileUrl.toLocalFile()).path());
+ foreach (const QString &dummyDataDirectory, dummyDataDirectoryList) {
+ loadDummyDataFiles(dummyDataDirectory);
+ loadDummyDataContext(dummyDataDirectory);
+ }
+ }
+
+ if (m_dummyContextObject.isNull())
+ setupDefaultDummyData();
+}
+
+void NodeInstanceServer::setupDefaultDummyData()
+{
+ QQmlComponent component(engine());
+ QByteArray defaultContextObjectArray("import QtQuick 1.0\n"
+ "import QmlDesigner 1.0\n"
+ "DummyContextObject {\n"
+ " parent: QtObject {\n"
+ " property real width: 360\n"
+ " property real height: 640\n"
+ " }\n"
+ "}\n");
+
+ component.setData(defaultContextObjectArray, fileUrl());
+ m_dummyContextObject = component.create();
+
+ if (component.isError()) {
+ QList<QQmlError> errors = component.errors();
+ foreach (const QQmlError &error, errors) {
+ qWarning() << error;
+ }
+ }
+
+ if (m_dummyContextObject) {
+ qWarning() << "Loaded default dummy context object.";
+ m_dummyContextObject->setParent(this);
+ }
+
+ refreshBindings();
+}
+
+QList<ServerNodeInstance> NodeInstanceServer::setupInstances(const CreateSceneCommand &command)
+{
+ QList<ServerNodeInstance> instanceList = createInstances(command.instances());
+
+ foreach (const IdContainer &container, command.ids()) {
+ if (hasInstanceForId(container.instanceId()))
+ instanceForId(container.instanceId()).setId(container.id());
+ }
+
+ foreach (const PropertyValueContainer &container, command.valueChanges()) {
+ if (container.isDynamic())
+ setInstancePropertyVariant(container);
+ }
+
+ foreach (const PropertyValueContainer &container, command.valueChanges()) {
+ if (!container.isDynamic())
+ setInstancePropertyVariant(container);
+ }
+
+ reparentInstances(command.reparentInstances());
+
+ foreach (const PropertyBindingContainer &container, command.bindingChanges()) {
+ if (container.isDynamic())
+ setInstancePropertyBinding(container);
+ }
+
+ foreach (const PropertyBindingContainer &container, command.bindingChanges()) {
+ if (!container.isDynamic())
+ setInstancePropertyBinding(container);
+ }
+
+ foreach (const PropertyValueContainer &container, command.auxiliaryChanges()) {
+ setInstanceAuxiliaryData(container);
+ }
+
+ foreach (ServerNodeInstance instance, instanceList)
+ instance.doComponentComplete();
+
+ return instanceList;
+}
+
+void NodeInstanceServer::changeFileUrl(const ChangeFileUrlCommand &command)
+{
+ m_fileUrl = command.fileUrl();
+
+ if (engine())
+ engine()->setBaseUrl(m_fileUrl);
+
+ refreshBindings();
+ startRenderTimer();
+}
+
+void NodeInstanceServer::changePropertyValues(const ChangeValuesCommand &command)
+{
+ bool hasDynamicProperties = false;
+ foreach (const PropertyValueContainer &container, command.valueChanges()) {
+ hasDynamicProperties |= container.isDynamic();
+ setInstancePropertyVariant(container);
+ }
+
+ if (hasDynamicProperties)
+ refreshBindings();
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::changeAuxiliaryValues(const ChangeAuxiliaryCommand &command)
+{
+ foreach (const PropertyValueContainer &container, command.auxiliaryChanges()) {
+ setInstanceAuxiliaryData(container);
+ }
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::changePropertyBindings(const ChangeBindingsCommand &command)
+{
+ bool hasDynamicProperties = false;
+ foreach (const PropertyBindingContainer &container, command.bindingChanges()) {
+ hasDynamicProperties |= container.isDynamic();
+ setInstancePropertyBinding(container);
+ }
+
+ if (hasDynamicProperties)
+ refreshBindings();
+
+ startRenderTimer();
+}
+
+void NodeInstanceServer::changeIds(const ChangeIdsCommand &command)
+{
+ foreach (const IdContainer &container, command.ids()) {
+ if (hasInstanceForId(container.instanceId()))
+ instanceForId(container.instanceId()).setId(container.id());
+ }
+
+ refreshBindings();
+ startRenderTimer();
+}
+
+QQmlContext *NodeInstanceServer::context() const
+{
+ if (m_importComponentObject) {
+ QQmlContext *importComponentContext = QQmlEngine::contextForObject(m_importComponentObject.data());
+ if (importComponentContext) // this should be the default
+ return importComponentContext;
+ }
+
+ if (engine())
+ return rootContext();
+
+ return 0;
+}
+
+QQmlContext *NodeInstanceServer::rootContext() const
+{
+ return engine()->rootContext();
+}
+
+const QVector<NodeInstanceServer::InstancePropertyPair> NodeInstanceServer::changedPropertyList() const
+{
+ return m_changedPropertyList;
+}
+
+void NodeInstanceServer::clearChangedPropertyList()
+{
+ m_changedPropertyList.clear();
+}
+
+void NodeInstanceServer::setupDummysForContext(QQmlContext *context)
+{
+ foreach (const DummyPair& dummyPair, m_dummyObjectList) {
+ if (dummyPair.second) {
+ context->setContextProperty(dummyPair.first, dummyPair.second.data());
+ }
+ }
+}
+
+
+QList<QQmlContext*> NodeInstanceServer::allSubContextsForObject(QObject *object)
+{
+ QList<QQmlContext*> contextList;
+
+ if (object) {
+ foreach (QObject *subObject, allSubObjectsForObject(object)) {
+ QQmlContext *contextOfObject = QQmlEngine::contextForObject(subObject);
+ if (contextOfObject) {
+ if (contextOfObject != context() && !contextList.contains(contextOfObject))
+ contextList.append(contextOfObject);
+ }
+ }
+ }
+
+ return contextList;
+}
+
+QList<QObject*> NodeInstanceServer::allSubObjectsForObject(QObject *object)
+{
+ QList<QObject*> subChildren;
+ if (object) {
+ subChildren = object->findChildren<QObject*>();
+ }
+
+ return subChildren;
+}
+
+void NodeInstanceServer::removeAllInstanceRelationships()
+{
+ // prevent destroyed() signals calling back
+
+ foreach (ServerNodeInstance instance, m_objectInstanceHash) {
+ if (instance.isValid())
+ instance.setId(QString());
+ }
+
+ //first the root object
+ if (rootNodeInstance().internalObject())
+ rootNodeInstance().internalObject()->disconnect();
+
+ rootNodeInstance().makeInvalid();
+
+
+ foreach (ServerNodeInstance instance, m_objectInstanceHash) {
+ if (instance.internalObject())
+ instance.internalObject()->disconnect();
+ instance.makeInvalid();
+ }
+
+ m_idInstanceHash.clear();
+ m_objectInstanceHash.clear();
+}
+
+QFileSystemWatcher *NodeInstanceServer::dummydataFileSystemWatcher()
+{
+ if (m_dummdataFileSystemWatcher.isNull()) {
+ m_dummdataFileSystemWatcher = new QFileSystemWatcher(this);
+ connect(m_dummdataFileSystemWatcher.data(), SIGNAL(fileChanged(QString)), this, SLOT(refreshDummyData(QString)));
+ }
+
+ return m_dummdataFileSystemWatcher.data();
+}
+
+QFileSystemWatcher *NodeInstanceServer::fileSystemWatcher()
+{
+ if (m_fileSystemWatcher.isNull()) {
+ m_fileSystemWatcher = new QFileSystemWatcher(this);
+ connect(m_fileSystemWatcher.data(), SIGNAL(fileChanged(QString)), this, SLOT(refreshLocalFileProperty(QString)));
+ }
+
+ return m_fileSystemWatcher.data();
+}
+
+Internal::ChildrenChangeEventFilter *NodeInstanceServer::childrenChangeEventFilter() const
+{
+ return m_childrenChangeEventFilter.data();
+}
+
+void NodeInstanceServer::addFilePropertyToFileSystemWatcher(QObject *object, const QString &propertyName, const QString &path)
+{
+ if (!m_fileSystemWatcherHash.contains(path)) {
+ m_fileSystemWatcherHash.insert(path, ObjectPropertyPair(object, propertyName));
+ fileSystemWatcher()->addPath(path);
+ }
+}
+
+void NodeInstanceServer::removeFilePropertyFromFileSystemWatcher(QObject *object, const QString &propertyName, const QString &path)
+{
+ if (m_fileSystemWatcherHash.contains(path)) {
+ fileSystemWatcher()->removePath(path);
+ m_fileSystemWatcherHash.remove(path, ObjectPropertyPair(object, propertyName));
+ }
+}
+
+void NodeInstanceServer::refreshLocalFileProperty(const QString &path)
+{
+ if (m_fileSystemWatcherHash.contains(path)) {
+ foreach (const ObjectPropertyPair &objectPropertyPair, m_fileSystemWatcherHash) {
+ QObject *object = objectPropertyPair.first.data();
+ QString propertyName = objectPropertyPair.second;
+
+ if (hasInstanceForObject(object)) {
+ instanceForObject(object).refreshProperty(propertyName);
+ }
+ }
+ }
+}
+
+void NodeInstanceServer::refreshDummyData(const QString &path)
+{
+ engine()->clearComponentCache();
+ QFileInfo filePath(path);
+ if (filePath.completeBaseName().contains("_dummycontext")) {
+ loadDummyContextObjectFile(filePath);
+ } else {
+ loadDummyDataFile(filePath);
+ }
+
+ refreshBindings();
+ startRenderTimer();
+}
+
+void NodeInstanceServer::addChangedProperty(const InstancePropertyPair &property)
+{
+ if (!m_changedPropertyList.contains(property))
+ m_changedPropertyList.append(property);
+}
+
+void NodeInstanceServer::emitParentChanged(QObject *child)
+{
+ if (hasInstanceForObject(child)) {
+ addChangedProperty(InstancePropertyPair(instanceForObject(child), "parent"));
+ }
+}
+
+Internal::ChildrenChangeEventFilter *NodeInstanceServer::childrenChangeEventFilter()
+{
+ if (m_childrenChangeEventFilter.isNull()) {
+ m_childrenChangeEventFilter = new Internal::ChildrenChangeEventFilter(this);
+ connect(m_childrenChangeEventFilter.data(), SIGNAL(childrenChanged(QObject*)), this, SLOT(emitParentChanged(QObject*)));
+ }
+
+ return m_childrenChangeEventFilter.data();
+}
+
+void NodeInstanceServer::resetInstanceProperty(const PropertyAbstractContainer &propertyContainer)
+{
+ if (hasInstanceForId(propertyContainer.instanceId())) { // TODO ugly workaround
+ ServerNodeInstance instance = instanceForId(propertyContainer.instanceId());
+ Q_ASSERT(instance.isValid());
+
+ const QString name = propertyContainer.name();
+
+ if (activeStateInstance().isValid() && !instance.isSubclassOf("QtQuick/PropertyChanges")) {
+ bool statePropertyWasReseted = activeStateInstance().resetStateProperty(instance, name, instance.resetVariant(name));
+ if (!statePropertyWasReseted)
+ instance.resetProperty(name);
+ } else {
+ instance.resetProperty(name);
+ }
+
+ if (propertyContainer.isDynamic() && propertyContainer.instanceId() == 0 && engine())
+ rootContext()->setContextProperty(name, QVariant());
+ }
+}
+
+
+void NodeInstanceServer::setInstancePropertyBinding(const PropertyBindingContainer &bindingContainer)
+{
+ if (hasInstanceForId(bindingContainer.instanceId())) {
+ ServerNodeInstance instance = instanceForId(bindingContainer.instanceId());
+
+ const QString name = bindingContainer.name();
+ const QString expression = bindingContainer.expression();
+
+
+ if (activeStateInstance().isValid() && !instance.isSubclassOf("QtQuick/PropertyChanges")) {
+ bool stateBindingWasUpdated = activeStateInstance().updateStateBinding(instance, name, expression);
+ if (!stateBindingWasUpdated) {
+ if (bindingContainer.isDynamic())
+ instance.setPropertyDynamicBinding(name, bindingContainer.dynamicTypeName(), expression);
+ else
+ instance.setPropertyBinding(name, expression);
+ }
+ } else {
+ if (bindingContainer.isDynamic())
+ instance.setPropertyDynamicBinding(name, bindingContainer.dynamicTypeName(), expression);
+ else
+ instance.setPropertyBinding(name, expression);
+ }
+ }
+}
+
+
+void NodeInstanceServer::removeProperties(const QList<PropertyAbstractContainer> &propertyList)
+{
+ foreach (const PropertyAbstractContainer &property, propertyList)
+ resetInstanceProperty(property);
+}
+
+void NodeInstanceServer::setInstancePropertyVariant(const PropertyValueContainer &valueContainer)
+{
+ if (hasInstanceForId(valueContainer.instanceId())) {
+ ServerNodeInstance instance = instanceForId(valueContainer.instanceId());
+
+
+ const QString name = valueContainer.name();
+ const QVariant value = valueContainer.value();
+
+
+ if (activeStateInstance().isValid() && !instance.isSubclassOf("QtQuick/PropertyChanges")) {
+ bool stateValueWasUpdated = activeStateInstance().updateStateVariant(instance, name, value);
+ if (!stateValueWasUpdated) {
+ if (valueContainer.isDynamic())
+ instance.setPropertyDynamicVariant(name, valueContainer.dynamicTypeName(), value);
+ else
+ instance.setPropertyVariant(name, value);
+ }
+ } else { //base state
+ if (valueContainer.isDynamic())
+ instance.setPropertyDynamicVariant(name, valueContainer.dynamicTypeName(), value);
+ else
+ instance.setPropertyVariant(name, value);
+ }
+
+ if (valueContainer.isDynamic() && valueContainer.instanceId() == 0 && engine())
+ rootContext()->setContextProperty(name, Internal::ObjectNodeInstance::fixResourcePaths(value));
+ }
+}
+
+void NodeInstanceServer::setInstanceAuxiliaryData(const PropertyValueContainer &auxiliaryContainer)
+{
+ //instanceId() == 0: the item is root
+ if (auxiliaryContainer.instanceId() == 0 && (auxiliaryContainer.name() == QLatin1String("width") ||
+ auxiliaryContainer.name() == QLatin1String("height"))) {
+
+ if (!auxiliaryContainer.value().isNull()) {
+ setInstancePropertyVariant(auxiliaryContainer);
+ } else {
+ rootNodeInstance().resetProperty(auxiliaryContainer.name());
+ }
+ }
+ if (auxiliaryContainer.name().endsWith(QLatin1String("@NodeInstance"))) {
+ QString propertyName = auxiliaryContainer.name().leftRef(auxiliaryContainer.name().count() - 12).toString();
+ if (!auxiliaryContainer.value().isNull()) {
+ setInstancePropertyVariant(PropertyValueContainer(auxiliaryContainer.instanceId(),
+ propertyName,
+ auxiliaryContainer.value(),
+ auxiliaryContainer.dynamicTypeName()));
+ } else {
+ rootNodeInstance().resetProperty(propertyName);
+ }
+ }
+}
+
+
+QUrl NodeInstanceServer::fileUrl() const
+{
+ return m_fileUrl;
+}
+
+ServerNodeInstance NodeInstanceServer::activeStateInstance() const
+{
+ return m_activeStateInstance;
+}
+
+ServerNodeInstance NodeInstanceServer::rootNodeInstance() const
+{
+ return m_rootNodeInstance;
+}
+
+void NodeInstanceServer::setStateInstance(const ServerNodeInstance &stateInstance)
+{
+ m_activeStateInstance = stateInstance;
+}
+
+void NodeInstanceServer::clearStateInstance()
+{
+ m_activeStateInstance = ServerNodeInstance();
+}
+
+void NodeInstanceServer::timerEvent(QTimerEvent *event)
+{
+ if (event->timerId() == m_timer) {
+ collectItemChangesAndSendChangeCommands();
+ }
+
+ NodeInstanceServerInterface::timerEvent(event);
+}
+
+NodeInstanceClientInterface *NodeInstanceServer::nodeInstanceClient() const
+{
+ return m_nodeInstanceClient;
+}
+
+static QVector<InformationContainer> createInformationVector(const QList<ServerNodeInstance> &instanceList, bool initial)
+{
+ QVector<InformationContainer> informationVector;
+
+ foreach (const ServerNodeInstance &instance, instanceList) {
+ informationVector.append(InformationContainer(instance.instanceId(), Position, instance.position()));
+ informationVector.append(InformationContainer(instance.instanceId(), Transform, instance.transform()));
+ informationVector.append(InformationContainer(instance.instanceId(), SceneTransform, instance.sceneTransform()));
+ informationVector.append(InformationContainer(instance.instanceId(), Size, instance.size()));
+ informationVector.append(InformationContainer(instance.instanceId(), BoundingRect, instance.boundingRect()));
+ informationVector.append(InformationContainer(instance.instanceId(), Transform, instance.transform()));
+ informationVector.append(InformationContainer(instance.instanceId(), HasContent, instance.hasContent()));
+ informationVector.append(InformationContainer(instance.instanceId(), IsMovable, instance.isMovable()));
+ informationVector.append(InformationContainer(instance.instanceId(), IsResizable, instance.isResizable()));
+ informationVector.append(InformationContainer(instance.instanceId(), IsInPositioner, instance.isInPositioner()));
+ informationVector.append(InformationContainer(instance.instanceId(), PenWidth, instance.penWidth()));
+ informationVector.append(InformationContainer(instance.instanceId(), IsAnchoredByChildren, instance.isAnchoredByChildren()));
+ informationVector.append(InformationContainer(instance.instanceId(), IsAnchoredBySibling, instance.isAnchoredBySibling()));
+
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.fill"), instance.hasAnchor("anchors.fill")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.centerIn"), instance.hasAnchor("anchors.centerIn")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.right"), instance.hasAnchor("anchors.right")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.top"), instance.hasAnchor("anchors.top")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.left"), instance.hasAnchor("anchors.left")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.bottom"), instance.hasAnchor("anchors.bottom")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.horizontalCenter"), instance.hasAnchor("anchors.horizontalCenter")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.verticalCenter"), instance.hasAnchor("anchors.verticalCenter")));
+ informationVector.append(InformationContainer(instance.instanceId(), HasAnchor, QString("anchors.baseline"), instance.hasAnchor("anchors.baseline")));
+
+ QPair<QString, ServerNodeInstance> anchorPair = instance.anchor("anchors.fill");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.fill"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.centerIn");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.centerIn"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.right");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.right"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.top");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.top"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.left");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.left"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.bottom");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.bottom"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.horizontalCenter");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.horizontalCenter"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.verticalCenter");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.verticalCenter"), anchorPair.first, anchorPair.second.instanceId()));
+
+ anchorPair = instance.anchor("anchors.baseline");
+ informationVector.append(InformationContainer(instance.instanceId(), Anchor, QString("anchors.baseline"), anchorPair.first, anchorPair.second.instanceId()));
+
+ QStringList propertyNames = instance.propertyNames();
+
+ if (initial) {
+ foreach (const QString &propertyName,propertyNames)
+ informationVector.append(InformationContainer(instance.instanceId(), InstanceTypeForProperty, propertyName, instance.instanceType(propertyName)));
+ }
+
+ foreach (const QString &propertyName,instance.propertyNames()) {
+ bool hasChanged = false;
+ bool hasBinding = instance.hasBindingForProperty(propertyName, &hasChanged);
+ if (hasChanged)
+ informationVector.append(InformationContainer(instance.instanceId(), HasBindingForProperty, propertyName, hasBinding));
+ }
+
+ }
+
+ return informationVector;
+}
+
+
+ChildrenChangedCommand NodeInstanceServer::createChildrenChangedCommand(const ServerNodeInstance &parentInstance, const QList<ServerNodeInstance> &instanceList) const
+{
+ QVector<qint32> instanceVector;
+
+ foreach (const ServerNodeInstance &instance, instanceList)
+ instanceVector.append(instance.instanceId());
+
+ return ChildrenChangedCommand(parentInstance.instanceId(), instanceVector, createInformationVector(instanceList, false));
+}
+
+InformationChangedCommand NodeInstanceServer::createAllInformationChangedCommand(const QList<ServerNodeInstance> &instanceList, bool initial) const
+{
+ return InformationChangedCommand(createInformationVector(instanceList, initial));
+}
+
+static bool supportedVariantType(int type)
+{
+ return type < int(QVariant::UserType) && type != QMetaType::QObjectStar;
+}
+
+ValuesChangedCommand NodeInstanceServer::createValuesChangedCommand(const QList<ServerNodeInstance> &instanceList) const
+{
+ QVector<PropertyValueContainer> valueVector;
+
+ foreach (const ServerNodeInstance &instance, instanceList) {
+ foreach (const QString &propertyName, instance.propertyNames()) {
+ QVariant propertyValue = instance.property(propertyName);
+ if (supportedVariantType(propertyValue.userType()))
+ valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, propertyValue, QString()));
+ }
+ }
+
+ return ValuesChangedCommand(valueVector);
+}
+
+ComponentCompletedCommand NodeInstanceServer::createComponentCompletedCommand(const QList<ServerNodeInstance> &instanceList)
+{
+ QVector<qint32> idVector;
+ foreach (const ServerNodeInstance &instance, instanceList) {
+ if (instance.instanceId() >= 0)
+ idVector.append(instance.instanceId());
+ }
+
+ return ComponentCompletedCommand(idVector);
+}
+
+ValuesChangedCommand NodeInstanceServer::createValuesChangedCommand(const QVector<InstancePropertyPair> &propertyList) const
+{
+ QVector<PropertyValueContainer> valueVector;
+
+ foreach (const InstancePropertyPair &property, propertyList) {
+ const QString propertyName = property.second;
+ const ServerNodeInstance instance = property.first;
+
+ if (instance.isValid()) {
+ QVariant propertyValue = instance.property(propertyName);
+ if (QMetaType::isRegistered(propertyValue.userType()) && supportedVariantType(propertyValue.type())) {
+ valueVector.append(PropertyValueContainer(instance.instanceId(), propertyName, propertyValue, QString()));
+ }
+ }
+ }
+
+ return ValuesChangedCommand(valueVector);
+}
+
+QStringList NodeInstanceServer::imports() const
+{
+ return m_importList;
+}
+
+void NodeInstanceServer::addImportString(const QString &import)
+{
+ m_importList.append(import);
+}
+
+QObject *NodeInstanceServer::dummyContextObject() const
+{
+ return m_dummyContextObject.data();
+}
+
+void NodeInstanceServer::notifyPropertyChange(qint32 instanceid, const QString &propertyName)
+{
+ if (hasInstanceForId(instanceid))
+ addChangedProperty(InstancePropertyPair(instanceForId(instanceid), propertyName));
+}
+
+void NodeInstanceServer::insertInstanceRelationship(const ServerNodeInstance &instance)
+{
+ Q_ASSERT(instance.isValid());
+ Q_ASSERT(!m_idInstanceHash.contains(instance.instanceId()));
+ Q_ASSERT(!m_objectInstanceHash.contains(instance.internalObject()));
+ m_objectInstanceHash.insert(instance.internalObject(), instance);
+ m_idInstanceHash.insert(instance.instanceId(), instance);
+}
+
+void NodeInstanceServer::removeInstanceRelationsip(qint32 instanceId)
+{
+ if (hasInstanceForId(instanceId)) {
+ ServerNodeInstance instance = instanceForId(instanceId);
+ if (instance.isValid())
+ instance.setId(QString());
+ m_idInstanceHash.remove(instanceId);
+ m_objectInstanceHash.remove(instance.internalObject());
+ instance.makeInvalid();
+ }
+}
+
+PixmapChangedCommand NodeInstanceServer::createPixmapChangedCommand(const QList<ServerNodeInstance> &instanceList) const
+{
+ QVector<ImageContainer> imageVector;
+
+ foreach (const ServerNodeInstance &instance, instanceList) {
+ if (instance.isValid() && instance.hasContent())
+ imageVector.append(ImageContainer(instance.instanceId(), instance.renderImage(), instance.instanceId()));
+ }
+
+ return PixmapChangedCommand(imageVector);
+}
+
+void NodeInstanceServer::loadDummyDataFile(const QFileInfo& qmlFileInfo)
+{
+ QQmlComponent component(engine(), qmlFileInfo.filePath());
+ QObject *dummyData = component.create();
+ if (component.isError()) {
+ QList<QQmlError> errors = component.errors();
+ foreach (const QQmlError &error, errors) {
+ qWarning() << error;
+ }
+ }
+
+ QVariant oldDummyDataObject = rootContext()->contextProperty(qmlFileInfo.completeBaseName());
+
+ if (dummyData) {
+ qWarning() << "Loaded dummy data:" << qmlFileInfo.filePath();
+ rootContext()->setContextProperty(qmlFileInfo.completeBaseName(), dummyData);
+ dummyData->setParent(this);
+ m_dummyObjectList.append(DummyPair(qmlFileInfo.completeBaseName(), dummyData));
+ }
+
+ if (!oldDummyDataObject.isNull())
+ delete oldDummyDataObject.value<QObject*>();
+
+ if (!dummydataFileSystemWatcher()->files().contains(qmlFileInfo.filePath()))
+ dummydataFileSystemWatcher()->addPath(qmlFileInfo.filePath());
+
+ if (rootNodeInstance().isValid() && rootNodeInstance().internalObject()) {
+ foreach (QQmlContext *context, allSubContextsForObject(rootNodeInstance().internalObject()))
+ setupDummysForContext(context);
+ }
+}
+
+void NodeInstanceServer::loadDummyContextObjectFile(const QFileInfo& qmlFileInfo)
+{
+ delete m_dummyContextObject.data();
+
+ QQmlComponent component(engine(), qmlFileInfo.filePath());
+ m_dummyContextObject = component.create();
+
+ if (component.isError()) {
+ QList<QQmlError> errors = component.errors();
+ foreach (const QQmlError &error, errors) {
+ qWarning() << error;
+ }
+ }
+
+ if (m_dummyContextObject) {
+ qWarning() << "Loaded dummy context object:" << qmlFileInfo.filePath();
+ m_dummyContextObject->setParent(this);
+ }
+
+ if (!dummydataFileSystemWatcher()->files().contains(qmlFileInfo.filePath()))
+ dummydataFileSystemWatcher()->addPath(qmlFileInfo.filePath());
+
+ refreshBindings();
+}
+
+void NodeInstanceServer::loadDummyDataFiles(const QString& directory)
+{
+ QDir dir(directory, "*.qml");
+ QList<QFileInfo> filePathList = dir.entryInfoList();
+ foreach (const QFileInfo &qmlFileInfo, filePathList) {
+ loadDummyDataFile(qmlFileInfo);
+ }
+}
+
+void NodeInstanceServer::loadDummyDataContext(const QString& directory)
+{
+ QDir dir(directory+"/context", "*.qml");
+ QList<QFileInfo> filePathList = dir.entryInfoList();
+ QString baseName = QFileInfo(fileUrl().toLocalFile()).completeBaseName();
+ foreach (const QFileInfo &qmlFileInfo, filePathList) {
+ if (qmlFileInfo.completeBaseName() == baseName)
+ loadDummyContextObjectFile(qmlFileInfo);
+ }
+}
+
+void NodeInstanceServer::sendDebugOutput(DebugOutputCommand::Type type, const QString &message)
+{
+ DebugOutputCommand command(message, type);
+ nodeInstanceClient()->debugOutput(command);
+}
+
+QStringList NodeInstanceServer::dummyDataDirectories(const QString& directoryPath)
+{
+ QStringList dummyDataDirectoryList;
+ QDir directory(directoryPath);
+ while (true) {
+ if (directory.isRoot() || !directory.exists())
+ return dummyDataDirectoryList;
+
+ if (directory.exists("dummydata"))
+ dummyDataDirectoryList.prepend(directory.absoluteFilePath("dummydata"));
+
+ directory.cdUp();
+ }
+}
+
+}
+
+
+
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.h
new file mode 100644
index 0000000000..031fa6b401
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstanceserver.h
@@ -0,0 +1,230 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef NODEINSTANCESERVER_H
+#define NODEINSTANCESERVER_H
+
+#include <QUrl>
+#include <QVector>
+#include <QSet>
+#include <QStringList>
+#include <QPointer>
+
+#include <nodeinstanceserverinterface.h>
+#include "servernodeinstance.h"
+#include "debugoutputcommand.h"
+
+QT_BEGIN_NAMESPACE
+class QFileSystemWatcher;
+class QQmlView;
+class QQuickView;
+class QQmlEngine;
+class QFileInfo;
+class QQmlComponent;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+class NodeInstanceClientInterface;
+class ValuesChangedCommand;
+class PixmapChangedCommand;
+class InformationChangedCommand;
+class ChildrenChangedCommand;
+class ReparentContainer;
+class ComponentCompletedCommand;
+class AddImportContainer;
+
+namespace Internal {
+ class ChildrenChangeEventFilter;
+}
+
+class NodeInstanceServer : public NodeInstanceServerInterface
+{
+ Q_OBJECT
+public:
+ typedef QPair<QPointer<QObject>, QString> ObjectPropertyPair;
+ typedef QPair<qint32, QString> IdPropertyPair;
+ typedef QPair<ServerNodeInstance, QString> InstancePropertyPair;
+ typedef QPair<QString, QPointer<QObject> > DummyPair;
+
+ explicit NodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient);
+ ~NodeInstanceServer();
+
+ void createInstances(const CreateInstancesCommand &command);
+ void changeFileUrl(const ChangeFileUrlCommand &command);
+ void changePropertyValues(const ChangeValuesCommand &command);
+ void changePropertyBindings(const ChangeBindingsCommand &command);
+ void changeAuxiliaryValues(const ChangeAuxiliaryCommand &command);
+ void changeIds(const ChangeIdsCommand &command);
+ void createScene(const CreateSceneCommand &command);
+ void clearScene(const ClearSceneCommand &command);
+ void removeInstances(const RemoveInstancesCommand &command);
+ void removeProperties(const RemovePropertiesCommand &command);
+ void reparentInstances(const ReparentInstancesCommand &command);
+ void changeState(const ChangeStateCommand &command);
+ void completeComponent(const CompleteComponentCommand &command);
+ void changeNodeSource(const ChangeNodeSourceCommand &command);
+ void token(const TokenCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
+
+ ServerNodeInstance instanceForId(qint32 id) const;
+ bool hasInstanceForId(qint32 id) const;
+
+ ServerNodeInstance instanceForObject(QObject *object) const;
+ bool hasInstanceForObject(QObject *object) const;
+
+ virtual QQmlEngine *engine() const = 0;
+ QQmlContext *context() const;
+
+ void removeAllInstanceRelationships();
+
+ QFileSystemWatcher *fileSystemWatcher();
+ QFileSystemWatcher *dummydataFileSystemWatcher();
+ Internal::ChildrenChangeEventFilter *childrenChangeEventFilter() const;
+ void addFilePropertyToFileSystemWatcher(QObject *object, const QString &propertyName, const QString &path);
+ void removeFilePropertyFromFileSystemWatcher(QObject *object, const QString &propertyName, const QString &path);
+
+ QUrl fileUrl() const;
+
+ ServerNodeInstance activeStateInstance() const;
+ void setStateInstance(const ServerNodeInstance &stateInstance);
+ void clearStateInstance();
+
+ ServerNodeInstance rootNodeInstance() const;
+
+ void notifyPropertyChange(qint32 instanceid, const QString &propertyName);
+
+ QStringList imports() const;
+ QObject *dummyContextObject() const;
+
+ virtual QQmlView *declarativeView() const = 0;
+ virtual QQuickView *quickView() const = 0;
+
+ void sendDebugOutput(DebugOutputCommand::Type type, const QString &message);
+
+public slots:
+ void refreshLocalFileProperty(const QString &path);
+ void refreshDummyData(const QString &path);
+ void emitParentChanged(QObject *child);
+
+protected:
+ QList<ServerNodeInstance> createInstances(const QVector<InstanceContainer> &container);
+ void reparentInstances(const QVector<ReparentContainer> &containerVector);
+ void addImportString(const QString &import);
+
+ Internal::ChildrenChangeEventFilter *childrenChangeEventFilter();
+ void resetInstanceProperty(const PropertyAbstractContainer &propertyContainer);
+ void setInstancePropertyBinding(const PropertyBindingContainer &bindingContainer);
+ void setInstancePropertyVariant(const PropertyValueContainer &valueContainer);
+ void setInstanceAuxiliaryData(const PropertyValueContainer &auxiliaryContainer);
+ void removeProperties(const QList<PropertyAbstractContainer> &propertyList);
+
+ void insertInstanceRelationship(const ServerNodeInstance &instance);
+ void removeInstanceRelationsip(qint32 instanceId);
+
+ NodeInstanceClientInterface *nodeInstanceClient() const;
+
+ void timerEvent(QTimerEvent *);
+
+ virtual void collectItemChangesAndSendChangeCommands() = 0;
+
+ ValuesChangedCommand createValuesChangedCommand(const QList<ServerNodeInstance> &instanceList) const;
+ ValuesChangedCommand createValuesChangedCommand(const QVector<InstancePropertyPair> &propertyList) const;
+ PixmapChangedCommand createPixmapChangedCommand(const QList<ServerNodeInstance> &instanceList) const;
+ InformationChangedCommand createAllInformationChangedCommand(const QList<ServerNodeInstance> &instanceList, bool initial = false) const;
+ ChildrenChangedCommand createChildrenChangedCommand(const ServerNodeInstance &parentInstance, const QList<ServerNodeInstance> &instanceList) const;
+ ComponentCompletedCommand createComponentCompletedCommand(const QList<ServerNodeInstance> &instanceList);
+
+ void addChangedProperty(const InstancePropertyPair &property);
+
+ virtual void startRenderTimer();
+ void slowDownRenderTimer();
+ void stopRenderTimer();
+ void setRenderTimerInterval(int timerInterval);
+ int renderTimerInterval() const;
+ void setSlowRenderTimerInterval(int timerInterval);
+
+ virtual void initializeView(const QVector<AddImportContainer> &importVector) = 0;
+ virtual QList<ServerNodeInstance> setupScene(const CreateSceneCommand &command) = 0;
+ void loadDummyDataFiles(const QString& directory);
+ void loadDummyDataContext(const QString& directory);
+ void loadDummyDataFile(const QFileInfo& fileInfo);
+ void loadDummyContextObjectFile(const QFileInfo& fileInfo);
+ static QStringList dummyDataDirectories(const QString& directoryPath);
+
+ void setTimerId(int timerId);
+ int timerId() const;
+
+ QQmlContext *rootContext() const;
+
+
+ const QVector<InstancePropertyPair> changedPropertyList() const;
+ void clearChangedPropertyList();
+
+ virtual void refreshBindings() = 0;
+
+ void setupDummysForContext(QQmlContext *context);
+
+ void setupFileUrl(const QUrl &fileUrl);
+ void setupImports(const QVector<AddImportContainer> &container);
+ void setupDummyData(const QUrl &fileUrl);
+ void setupDefaultDummyData();
+ QList<ServerNodeInstance> setupInstances(const CreateSceneCommand &command);
+
+ QList<QQmlContext*> allSubContextsForObject(QObject *object);
+ static QList<QObject*> allSubObjectsForObject(QObject *object);
+
+ virtual void resizeCanvasSizeToRootItemSize() = 0;
+
+private:
+ ServerNodeInstance m_rootNodeInstance;
+ ServerNodeInstance m_activeStateInstance;
+ QHash<qint32, ServerNodeInstance> m_idInstanceHash;
+ QHash<QObject*, ServerNodeInstance> m_objectInstanceHash;
+ QMultiHash<QString, ObjectPropertyPair> m_fileSystemWatcherHash;
+ QList<QPair<QString, QPointer<QObject> > > m_dummyObjectList;
+ QPointer<QFileSystemWatcher> m_fileSystemWatcher;
+ QPointer<QFileSystemWatcher> m_dummdataFileSystemWatcher;
+ QPointer<Internal::ChildrenChangeEventFilter> m_childrenChangeEventFilter;
+ QUrl m_fileUrl;
+ NodeInstanceClientInterface *m_nodeInstanceClient;
+ int m_timer;
+ int m_renderTimerInterval;
+ bool m_slowRenderTimer;
+ int m_slowRenderTimerInterval;
+ QVector<InstancePropertyPair> m_changedPropertyList;
+ QStringList m_importList;
+ QPointer<QObject> m_dummyContextObject;
+ QPointer<QQmlComponent> m_importComponent;
+ QPointer<QObject> m_importComponentObject;
+};
+
+}
+
+#endif // NODEINSTANCESERVER_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.cpp
new file mode 100644
index 0000000000..f8e737b307
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.cpp
@@ -0,0 +1,124 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "nodeinstancesignalspy.h"
+#include "objectnodeinstance.h"
+
+#include <QMetaProperty>
+#include <QMetaObject>
+#include <QDebug>
+#include <QSharedPointer>
+#include <private/qqmlmetatype_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+NodeInstanceSignalSpy::NodeInstanceSignalSpy() :
+ QObject()
+{
+ blockSignals(true);
+}
+
+void NodeInstanceSignalSpy::setObjectNodeInstance(const ObjectNodeInstance::Pointer &nodeInstance)
+{
+ methodeOffset = QObject::staticMetaObject.methodCount() + 1;
+ registerObject(nodeInstance->object());
+ m_objectNodeInstance = nodeInstance;
+
+}
+
+void NodeInstanceSignalSpy::registerObject(QObject *spiedObject, const QString &prefix)
+{
+ if (m_registeredObjectList.contains(spiedObject)) // prevent cycles
+ return;
+
+ m_registeredObjectList.append(spiedObject);
+ for (int index = QObject::staticMetaObject.propertyOffset();
+ index < spiedObject->metaObject()->propertyCount();
+ index++) {
+ QMetaProperty metaProperty = spiedObject->metaObject()->property(index);
+
+ // handle dot properties and connect the signals to the object
+ if (metaProperty.isReadable()
+ && !metaProperty.isWritable()
+ && QQmlMetaType::isQObject(metaProperty.userType())) {
+ QObject *propertyObject = QQmlMetaType::toQObject(metaProperty.read(spiedObject));
+ if (propertyObject)
+ registerObject(propertyObject, prefix + metaProperty.name() + QLatin1Char('.'));
+ } else if (metaProperty.hasNotifySignal()) {
+ QMetaMethod metaMethod = metaProperty.notifySignal();
+ bool isConnecting = QMetaObject::connect(spiedObject, metaMethod.methodIndex(), this, methodeOffset, Qt::DirectConnection);
+ Q_ASSERT(isConnecting);
+ Q_UNUSED(isConnecting);
+ m_indexPropertyHash.insert(methodeOffset, prefix + metaProperty.name());
+ methodeOffset++;
+ }
+
+ // search recursive in objects
+ if (metaProperty.isReadable()
+ && metaProperty.isWritable()
+ && QQmlMetaType::isQObject(metaProperty.userType())) {
+ QObject *propertyObject = QQmlMetaType::toQObject(metaProperty.read(spiedObject));
+ if (propertyObject)
+ registerObject(propertyObject, prefix + metaProperty.name() + QLatin1Char('/'));
+ }
+
+ // search recursive in objects list
+ if (metaProperty.isReadable()
+ && QQmlMetaType::isList(metaProperty.userType())) {
+ QQmlListReference list(spiedObject, metaProperty.name());
+
+ if (list.canCount() && list.canAt()) {
+
+ for (int i = 0; i < list.count(); i++) {
+ QObject *propertyObject = list.at(i);
+ if (propertyObject)
+ registerObject(propertyObject, prefix + metaProperty.name() + QLatin1Char('/'));
+ }
+ }
+ }
+ }
+}
+
+int NodeInstanceSignalSpy::qt_metacall(QMetaObject::Call call, int methodId, void **a)
+{
+ if (call == QMetaObject::InvokeMetaMethod && methodId > QObject::staticMetaObject.methodCount()) {
+ ObjectNodeInstance::Pointer nodeInstance = m_objectNodeInstance.toStrongRef();
+
+ if (nodeInstance && nodeInstance->nodeInstanceServer() && nodeInstance->isValid()) {
+ nodeInstance->nodeInstanceServer()->notifyPropertyChange(nodeInstance->instanceId(), m_indexPropertyHash.value(methodId));
+ }
+
+ }
+
+ return QObject::qt_metacall(call, methodId, a);
+}
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancesignalspy.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.h
index 6f8bdacdf8..6f8bdacdf8 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancesignalspy.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/nodeinstancesignalspy.h
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.cpp
new file mode 100644
index 0000000000..7ef12724be
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.cpp
@@ -0,0 +1,1180 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "objectnodeinstance.h"
+
+
+
+#include <QEvent>
+#include <QQmlContext>
+#include <QQmlError>
+#include <QQmlEngine>
+#include <QQmlProperty>
+#include <QQmlComponent>
+#include <QSharedPointer>
+#include <QFileInfo>
+#include <QFileSystemWatcher>
+#include <QPixmapCache>
+#include <QQuickItem>
+
+#include <QTextDocument>
+#include <QLibraryInfo>
+
+#include <private/qqmlbinding_p.h>
+#include <private/qqmlmetatype_p.h>
+#include <private/qqmlvaluetype_p.h>
+#include <private/qquicktransition_p.h>
+#include <private/qquickanimation_p.h>
+#include <private/qqmltimer_p.h>
+#include <private/qqmlengine_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+ObjectNodeInstance::ObjectNodeInstance(QObject *object)
+ : m_instanceId(-1),
+ m_deleteHeldInstance(true),
+ m_object(object),
+ m_metaObject(0),
+ m_isInPositioner(false)
+{
+
+}
+
+ObjectNodeInstance::~ObjectNodeInstance()
+{
+ destroy();
+}
+
+void ObjectNodeInstance::destroy()
+{
+ if (deleteHeldInstance()) {
+ // Remove from old property
+ if (object()) {
+ setId(QString());
+ if (m_instanceId >= 0) {
+ reparent(parentInstance(), m_parentProperty, ObjectNodeInstance::Pointer(), QString());
+ }
+ }
+
+ if (object()) {
+ QObject *obj = object();
+ m_object.clear();
+ delete obj;
+ }
+ }
+
+ m_metaObject = 0;
+ m_instanceId = -1;
+}
+
+void ObjectNodeInstance::setInstanceId(qint32 id)
+{
+ m_instanceId = id;
+}
+
+qint32 ObjectNodeInstance::instanceId() const
+{
+ return m_instanceId;
+}
+
+NodeInstanceServer *ObjectNodeInstance::nodeInstanceServer() const
+{
+ return m_nodeInstanceServer.data();
+}
+
+void ObjectNodeInstance::setNodeInstanceServer(NodeInstanceServer *server)
+{
+ Q_ASSERT(!m_nodeInstanceServer.data());
+
+ m_nodeInstanceServer = server;
+}
+
+static bool hasPropertiesWitoutNotifications(const QMetaObject *metaObject)
+{
+ for (int propertyIndex = QObject::staticMetaObject.propertyCount(); propertyIndex < metaObject->propertyCount(); propertyIndex++) {
+ if (!metaObject->property(propertyIndex).hasNotifySignal())
+ return true;
+ }
+
+ return false;
+}
+
+void ObjectNodeInstance::initializePropertyWatcher(const ObjectNodeInstance::Pointer &objectNodeInstance)
+{
+ const QMetaObject *metaObject = objectNodeInstance->object()->metaObject();
+ m_metaObject = NodeInstanceMetaObject::createNodeInstanceMetaObject(objectNodeInstance, nodeInstanceServer()->engine());
+ for (int propertyIndex = QObject::staticMetaObject.propertyCount(); propertyIndex < metaObject->propertyCount(); propertyIndex++) {
+ if (QQmlMetaType::isQObject(metaObject->property(propertyIndex).userType())) {
+ QObject *propertyObject = QQmlMetaType::toQObject(metaObject->property(propertyIndex).read(objectNodeInstance->object()));
+ if (propertyObject && hasPropertiesWitoutNotifications(propertyObject->metaObject())) {
+ NodeInstanceMetaObject::createNodeInstanceMetaObject(objectNodeInstance,
+ propertyObject,
+ metaObject->property(propertyIndex).name(),
+ nodeInstanceServer()->engine());
+ }
+ }
+ }
+
+ m_signalSpy.setObjectNodeInstance(objectNodeInstance);
+}
+
+void ObjectNodeInstance::initialize(const ObjectNodeInstance::Pointer &objectNodeInstance)
+{
+ initializePropertyWatcher(objectNodeInstance);
+}
+
+void ObjectNodeInstance::setId(const QString &id)
+{
+ if (!m_id.isEmpty() && context()) {
+ context()->engine()->rootContext()->setContextProperty(m_id, 0);
+ }
+
+ if (!id.isEmpty() && context()) {
+ context()->engine()->rootContext()->setContextProperty(id, object()); // will also force refresh of all bindings
+ }
+
+ m_id = id;
+}
+
+QString ObjectNodeInstance::id() const
+{
+ return m_id;
+}
+
+bool ObjectNodeInstance::isTransition() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isPositioner() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isQuickItem() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::equalGraphicsItem(QGraphicsItem * /*item*/) const
+{
+ return false;
+}
+
+QTransform ObjectNodeInstance::transform() const
+{
+ return QTransform();
+}
+
+QTransform ObjectNodeInstance::customTransform() const
+{
+ return QTransform();
+}
+
+QTransform ObjectNodeInstance::sceneTransform() const
+{
+ return QTransform();
+}
+
+double ObjectNodeInstance::rotation() const
+{
+ return 0.0;
+}
+
+double ObjectNodeInstance::scale() const
+{
+ return 1.0;
+}
+
+QList<QGraphicsTransform *> ObjectNodeInstance::transformations() const
+{
+ QList<QGraphicsTransform *> transformationsList;
+
+ return transformationsList;
+}
+
+QPointF ObjectNodeInstance::transformOriginPoint() const
+{
+ return QPoint();
+}
+
+double ObjectNodeInstance::zValue() const
+{
+ return 0.0;
+}
+
+double ObjectNodeInstance::opacity() const
+{
+ return 1.0;
+}
+
+bool ObjectNodeInstance::hasAnchor(const QString &/*name*/) const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isAnchoredBySibling() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isAnchoredByChildren() const
+{
+ return false;
+}
+
+QPair<QString, ServerNodeInstance> ObjectNodeInstance::anchor(const QString &/*name*/) const
+{
+ return qMakePair(QString(), ServerNodeInstance());
+}
+
+
+static bool isList(const QQmlProperty &property)
+{
+ return property.propertyTypeCategory() == QQmlProperty::List;
+}
+
+static bool isObject(const QQmlProperty &property)
+{
+ return (property.propertyTypeCategory() == QQmlProperty::Object) ||
+ //QVariant can also store QObjects. Lets trust our model.
+ (QLatin1String(property.propertyTypeName()) == QLatin1String("QVariant"));
+}
+
+static QVariant objectToVariant(QObject *object)
+{
+ return QVariant::fromValue(object);
+}
+
+static bool hasFullImplementedListInterface(const QQmlListReference &list)
+{
+ return list.isValid() && list.canCount() && list.canAt() && list.canAppend() && list.canClear();
+}
+
+static void removeObjectFromList(const QQmlProperty &property, QObject *objectToBeRemoved, QQmlEngine * engine)
+{
+ QQmlListReference listReference(property.object(), property.name().toLatin1(), engine);
+
+ if (!hasFullImplementedListInterface(listReference)) {
+ qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!";
+ return;
+ }
+
+ int count = listReference.count();
+
+ QObjectList objectList;
+
+ for (int i = 0; i < count; i ++) {
+ QObject *listItem = listReference.at(i);
+ if (listItem && listItem != objectToBeRemoved)
+ objectList.append(listItem);
+ }
+
+ listReference.clear();
+
+ foreach (QObject *object, objectList)
+ listReference.append(object);
+}
+
+void ObjectNodeInstance::removeFromOldProperty(QObject *object, QObject *oldParent, const QString &oldParentProperty)
+{
+ QQmlProperty property(oldParent, oldParentProperty, context());
+
+ if (!property.isValid())
+ return;
+
+ if (isList(property)) {
+ removeObjectFromList(property, object, nodeInstanceServer()->engine());
+ } else if (isObject(property)) {
+ if (nodeInstanceServer()->hasInstanceForObject(oldParent)) {
+ nodeInstanceServer()->instanceForObject(oldParent).resetProperty(oldParentProperty);
+ }
+ }
+
+ if (object && object->parent())
+ object->setParent(0);
+}
+
+void ObjectNodeInstance::addToNewProperty(QObject *object, QObject *newParent, const QString &newParentProperty)
+{
+ QQmlProperty property(newParent, newParentProperty, context());
+
+ if (isList(property)) {
+ QQmlListReference list = qvariant_cast<QQmlListReference>(property.read());
+
+ if (!hasFullImplementedListInterface(list)) {
+ qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!";
+ return;
+ }
+
+ list.append(object);
+ } else if (isObject(property)) {
+ property.write(objectToVariant(object));
+ }
+
+ QQuickItem *quickItem = qobject_cast<QQuickItem*>(object);
+
+ if (object && !(quickItem && quickItem->parentItem()))
+ object->setParent(newParent);
+
+ Q_ASSERT(objectToVariant(object).isValid());
+}
+
+void ObjectNodeInstance::reparent(const ObjectNodeInstance::Pointer &oldParentInstance, const QString &oldParentProperty, const ObjectNodeInstance::Pointer &newParentInstance, const QString &newParentProperty)
+{
+ if (oldParentInstance) {
+ removeFromOldProperty(object(), oldParentInstance->object(), oldParentProperty);
+ m_parentProperty.clear();
+ }
+
+ if (newParentInstance) {
+ m_parentProperty = newParentProperty;
+ addToNewProperty(object(), newParentInstance->object(), newParentProperty);
+ }
+}
+QVariant ObjectNodeInstance::convertSpecialCharacter(const QVariant& value) const
+{
+ QVariant specialCharacterConvertedValue = value;
+ if (value.type() == QVariant::String) {
+ QString string = value.toString();
+ string.replace(QLatin1String("\\n"), QLatin1String("\n"));
+ string.replace(QLatin1String("\\t"), QLatin1String("\t"));
+ specialCharacterConvertedValue = string;
+ }
+
+ return specialCharacterConvertedValue;
+}
+
+
+QVariant ObjectNodeInstance::fixResourcePaths(const QVariant &value)
+{
+ if (value.type() == QVariant::Url)
+ {
+ const QUrl url = value.toUrl();
+ if (url.scheme() == QLatin1String("qrc")) {
+ const QString path = QLatin1String("qrc:") + url.path();
+ QString qrcSearchPath = qgetenv("QMLDESIGNER_RC_PATHS");
+ if (!qrcSearchPath.isEmpty()) {
+ const QStringList searchPaths = qrcSearchPath.split(QLatin1Char(';'));
+ foreach (const QString &qrcPath, searchPaths) {
+ const QStringList qrcDefintion = qrcPath.split(QLatin1Char('='));
+ if (qrcDefintion.count() == 2) {
+ QString fixedPath = path;
+ fixedPath.replace(QLatin1String("qrc:") + qrcDefintion.first(), qrcDefintion.last() + QLatin1Char('/'));
+ if (QFileInfo(fixedPath).exists()) {
+ fixedPath.replace(QLatin1String("//"), QLatin1String("/"));
+ fixedPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
+ return QUrl(fixedPath);
+ }
+ }
+ }
+ }
+ }
+ }
+ if (value.type() == QVariant::String) {
+ const QString str = value.toString();
+ if (str.contains(QLatin1String("qrc:"))) {
+ QString qrcSearchPath = qgetenv("QMLDESIGNER_RC_PATHS");
+ if (!qrcSearchPath.isEmpty()) {
+ const QStringList searchPaths = qrcSearchPath.split(QLatin1Char(';'));
+ foreach (const QString &qrcPath, searchPaths) {
+ const QStringList qrcDefintion = qrcPath.split(QLatin1Char('='));
+ if (qrcDefintion.count() == 2) {
+ QString fixedPath = str;
+ fixedPath.replace(QLatin1String("qrc:") + qrcDefintion.first(), qrcDefintion.last() + QLatin1Char('/'));
+ if (QFileInfo(fixedPath).exists()) {
+ fixedPath.replace(QLatin1String("//"), QLatin1String("/"));
+ fixedPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
+ return fixedPath;
+ }
+ }
+ }
+ }
+ }
+ }
+ return value;
+}
+
+void ObjectNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ QQmlProperty property(object(), name, context());
+
+ if (!property.isValid())
+ return;
+
+ QVariant fixedValue = fixResourcePaths(value);
+
+ QVariant oldValue = property.read();
+ if (oldValue.type() == QVariant::Url) {
+ QUrl url = oldValue.toUrl();
+ QString path = url.toLocalFile();
+ if (QFileInfo(path).exists() && nodeInstanceServer() && !path.isEmpty())
+ nodeInstanceServer()->removeFilePropertyFromFileSystemWatcher(object(), name, path);
+ }
+
+ if (hasValidResetBinding(name)) {
+ QQmlPropertyPrivate::setBinding(property, 0, QQmlPropertyPrivate::BypassInterceptor | QQmlPropertyPrivate::DontRemoveBinding);
+ }
+
+ bool isWritten = property.write(convertSpecialCharacter(fixedValue));
+
+ if (!isWritten)
+ qDebug() << "ObjectNodeInstance.setPropertyVariant: Cannot be written: " << object() << name << fixedValue;
+
+ QVariant newValue = property.read();
+ if (newValue.type() == QVariant::Url) {
+ QUrl url = newValue.toUrl();
+ QString path = url.toLocalFile();
+ if (QFileInfo(path).exists() && nodeInstanceServer() && !path.isEmpty())
+ nodeInstanceServer()->addFilePropertyToFileSystemWatcher(object(), name, path);
+ }
+}
+
+void ObjectNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+{
+ QQmlProperty property(object(), name, context());
+
+ if (!property.isValid())
+ return;
+
+ if (property.isProperty()) {
+ QQmlBinding *binding = new QQmlBinding(expression, object(), context());
+ binding->setTarget(property);
+ binding->setNotifyOnValueChanged(true);
+ QQmlAbstractBinding *oldBinding = QQmlPropertyPrivate::setBinding(property, binding);
+ if (oldBinding && !hasValidResetBinding(name))
+ oldBinding->destroy();
+ binding->update();
+ if (binding->hasError()) {
+ //qDebug() <<" ObjectNodeInstance.setPropertyBinding has Error: " << object() << name << expression << binding->error(engine()).toString();
+ if (property.property().userType() == QVariant::String)
+ property.write(QVariant(QString("#%1#").arg(expression)));
+ }
+
+ } else {
+ qWarning() << "ObjectNodeInstance.setPropertyBinding: Cannot set binding for property" << name << ": property is unknown for type";
+ }
+}
+
+void ObjectNodeInstance::deleteObjectsInList(const QQmlProperty &property)
+{
+ QObjectList objectList;
+ QQmlListReference list = qvariant_cast<QQmlListReference>(property.read());
+
+ if (!hasFullImplementedListInterface(list)) {
+ qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!";
+ return;
+ }
+
+ for (int i = 0; i < list.count(); i++) {
+ objectList += list.at(i);
+ }
+
+ list.clear();
+}
+
+void ObjectNodeInstance::resetProperty(const QString &name)
+{
+ doResetProperty(name);
+
+ if (name == "font.pixelSize")
+ doResetProperty("font.pointSize");
+
+ if (name == "font.pointSize")
+ doResetProperty("font.pixelSize");
+}
+
+void ObjectNodeInstance::refreshProperty(const QString &name)
+{
+ QQmlProperty property(object(), name, context());
+
+ if (!property.isValid())
+ return;
+
+ QVariant oldValue(property.read());
+
+ if (property.isResettable())
+ property.reset();
+ else
+ property.write(resetValue(name));
+
+ if (oldValue.type() == QVariant::Url) {
+ QByteArray key = oldValue.toUrl().toEncoded(QUrl::UrlFormattingOption(0x100));
+ QString pixmapKey = QString::fromLatin1(key.constData(), key.count());
+ QPixmapCache::remove(pixmapKey);
+ }
+
+ property.write(oldValue);
+}
+
+bool ObjectNodeInstance::hasBindingForProperty(const QString &name, bool *hasChanged) const
+{
+ QQmlProperty property(object(), name, context());
+
+ bool hasBinding = QQmlPropertyPrivate::binding(property);
+
+ if (hasChanged) {
+ *hasChanged = hasBinding != m_hasBindingHash.value(name, false);
+ if (*hasChanged)
+ m_hasBindingHash.insert(name, hasBinding);
+ }
+
+ return QQmlPropertyPrivate::binding(property);
+}
+
+void ObjectNodeInstance::doResetProperty(const QString &propertyName)
+{
+ m_modelAbstractPropertyHash.remove(propertyName);
+
+ QQmlProperty property(object(), propertyName, context());
+
+ if (!property.isValid())
+ return;
+
+ QVariant oldValue = property.read();
+ if (oldValue.type() == QVariant::Url) {
+ QUrl url = oldValue.toUrl();
+ QString path = url.toLocalFile();
+ if (QFileInfo(path).exists() && nodeInstanceServer())
+ nodeInstanceServer()->removeFilePropertyFromFileSystemWatcher(object(), propertyName, path);
+ }
+
+
+ QQmlAbstractBinding *binding = QQmlPropertyPrivate::binding(property);
+ if (binding && !(hasValidResetBinding(propertyName) && resetBinding(propertyName) == binding)) {
+ binding->setEnabled(false, 0);
+ binding->destroy();
+ }
+
+
+ if (hasValidResetBinding(propertyName)) {
+ QQmlAbstractBinding *binding = resetBinding(propertyName);
+ QQmlPropertyPrivate::setBinding(property, binding, QQmlPropertyPrivate::DontRemoveBinding);
+ binding->update();
+ } else if (property.isResettable()) {
+ property.reset();
+ } else if (property.propertyTypeCategory() == QQmlProperty::List) {
+ QQmlListReference list = qvariant_cast<QQmlListReference>(property.read());
+
+ if (!hasFullImplementedListInterface(list)) {
+ qWarning() << "Property list interface not fully implemented for Class " << property.property().typeName() << " in property " << property.name() << "!";
+ return;
+ }
+
+ list.clear();
+ } else if (property.isWritable()) {
+ if (property.read() == resetValue(propertyName))
+ return;
+
+ property.write(resetValue(propertyName));
+ }
+}
+
+QVariant ObjectNodeInstance::property(const QString &name) const
+{
+ if (m_modelAbstractPropertyHash.contains(name))
+ return QVariant::fromValue(m_modelAbstractPropertyHash.value(name));
+
+ // TODO: handle model nodes
+
+ QQmlProperty property(object(), name, context());
+ if (property.property().isEnumType()) {
+ QVariant value = property.read();
+ return property.property().enumerator().valueToKey(value.toInt());
+ }
+
+ if (property.propertyType() == QVariant::Url) {
+ QUrl url = property.read().toUrl();
+ if (url.isEmpty())
+ return QVariant();
+
+ if (url.scheme() == "file") {
+ int basePathLength = nodeInstanceServer()->fileUrl().toLocalFile().lastIndexOf('/');
+ return QUrl(url.toLocalFile().mid(basePathLength + 1));
+ }
+ }
+
+ return property.read();
+}
+
+QStringList allPropertyNames(QObject *object, const QString &baseName = QString(), QObjectList *inspectedObjects = new QObjectList)
+{
+ QStringList propertyNameList;
+
+
+ if (inspectedObjects== 0 || inspectedObjects->contains(object))
+ return propertyNameList;
+
+ inspectedObjects->append(object);
+
+
+ const QMetaObject *metaObject = object->metaObject();
+ for (int index = 0; index < metaObject->propertyCount(); ++index) {
+ QMetaProperty metaProperty = metaObject->property(index);
+ QQmlProperty declarativeProperty(object, QLatin1String(metaProperty.name()));
+ if (declarativeProperty.isValid() && declarativeProperty.propertyTypeCategory() == QQmlProperty::Object) {
+ if (declarativeProperty.name() != "parent") {
+ QObject *childObject = QQmlMetaType::toQObject(declarativeProperty.read());
+ if (childObject)
+ propertyNameList.append(allPropertyNames(childObject, baseName + QString::fromUtf8(metaProperty.name()) + '.', inspectedObjects));
+ }
+ } else if (QQmlValueTypeFactory::valueType(metaProperty.userType())) {
+ QQmlValueType *valueType = QQmlValueTypeFactory::valueType(metaProperty.userType());
+ valueType->setValue(metaProperty.read(object));
+ propertyNameList.append(allPropertyNames(valueType, baseName + QString::fromUtf8(metaProperty.name()) + '.', inspectedObjects));
+ } else {
+ propertyNameList.append(baseName + QString::fromUtf8(metaProperty.name()));
+ }
+ }
+
+ return propertyNameList;
+}
+
+QStringList ObjectNodeInstance::propertyNames() const
+{
+ if (isValid())
+ return allPropertyNames(object());
+ return QStringList();
+}
+
+QString ObjectNodeInstance::instanceType(const QString &name) const
+{
+ QQmlProperty property(object(), name, context());
+ if (!property.isValid())
+ return QLatin1String("undefined");
+ return property.propertyTypeName();
+}
+
+QList<ServerNodeInstance> ObjectNodeInstance::childItems() const
+{
+ return QList<ServerNodeInstance>();
+}
+
+QList<ServerNodeInstance> ObjectNodeInstance::stateInstances() const
+{
+ return QList<ServerNodeInstance>();
+}
+
+void ObjectNodeInstance::setNodeSource(const QString & /*source*/)
+{
+}
+
+void ObjectNodeInstance::setDeleteHeldInstance(bool deleteInstance)
+{
+ m_deleteHeldInstance = deleteInstance;
+}
+
+bool ObjectNodeInstance::deleteHeldInstance() const
+{
+ return m_deleteHeldInstance;
+}
+
+ObjectNodeInstance::Pointer ObjectNodeInstance::create(QObject *object)
+{
+ Pointer instance(new ObjectNodeInstance(object));
+
+ instance->populateResetHashes();
+
+ return instance;
+}
+
+static void stopAnimation(QObject *object)
+{
+ if (object == 0)
+ return;
+
+ QQuickTransition *transition = qobject_cast<QQuickTransition*>(object);
+ QQuickAbstractAnimation *animation = qobject_cast<QQuickAbstractAnimation*>(object);
+ QQmlTimer *timer = qobject_cast<QQmlTimer*>(object);
+ if (transition) {
+ transition->setFromState("");
+ transition->setToState("");
+ } else if (animation) {
+// QQuickScriptAction *scriptAimation = qobject_cast<QQuickScriptAction*>(animation);
+// if (scriptAimation) FIXME
+// scriptAimation->setScript(QQmlScriptString());
+ animation->setLoops(1);
+ animation->complete();
+ animation->setDisableUserControl();
+ } else if (timer) {
+ timer->blockSignals(true);
+ }
+}
+
+void allSubObject(QObject *object, QObjectList &objectList)
+{
+ // don't add null pointer and stop if the object is already in the list
+ if (!object || objectList.contains(object))
+ return;
+
+ objectList.append(object);
+
+ for (int index = QObject::staticMetaObject.propertyOffset();
+ index < object->metaObject()->propertyCount();
+ index++) {
+ QMetaProperty metaProperty = object->metaObject()->property(index);
+
+ // search recursive in property objects
+ if (metaProperty.isReadable()
+ && metaProperty.isWritable()
+ && QQmlMetaType::isQObject(metaProperty.userType())) {
+ if (metaProperty.name() != QLatin1String("parent")) {
+ QObject *propertyObject = QQmlMetaType::toQObject(metaProperty.read(object));
+ allSubObject(propertyObject, objectList);
+ }
+
+ }
+
+ // search recursive in property object lists
+ if (metaProperty.isReadable()
+ && QQmlMetaType::isList(metaProperty.userType())) {
+ QQmlListReference list(object, metaProperty.name());
+ if (list.canCount() && list.canAt()) {
+ for (int i = 0; i < list.count(); i++) {
+ QObject *propertyObject = list.at(i);
+ allSubObject(propertyObject, objectList);
+
+ }
+ }
+ }
+ }
+
+ // search recursive in object children list
+ foreach (QObject *childObject, object->children()) {
+ allSubObject(childObject, objectList);
+ }
+
+ // search recursive in quick item childItems list
+ QQuickItem *quickItem = qobject_cast<QQuickItem*>(object);
+ if (quickItem) {
+ foreach (QQuickItem *childItem, quickItem->childItems()) {
+ allSubObject(childItem, objectList);
+ }
+ }
+}
+
+static void disableTiledBackingStore(QObject *object)
+{
+ Q_UNUSED(object);
+}
+
+QStringList propertyNameForWritableProperties(QObject *object, const QString &baseName = QString(), QObjectList *inspectedObjects = new QObjectList())
+{
+ QStringList propertyNameList;
+
+ if (inspectedObjects == 0 || inspectedObjects->contains(object))
+ return propertyNameList;
+
+ inspectedObjects->append(object);
+
+ const QMetaObject *metaObject = object->metaObject();
+ for (int index = 0; index < metaObject->propertyCount(); ++index) {
+ QMetaProperty metaProperty = metaObject->property(index);
+ QQmlProperty declarativeProperty(object, QLatin1String(metaProperty.name()));
+ if (declarativeProperty.isValid() && !declarativeProperty.isWritable() && declarativeProperty.propertyTypeCategory() == QQmlProperty::Object) {
+ if (declarativeProperty.name() != "parent") {
+ QObject *childObject = QQmlMetaType::toQObject(declarativeProperty.read());
+ if (childObject)
+ propertyNameList.append(propertyNameForWritableProperties(childObject, baseName + QString::fromUtf8(metaProperty.name()) + '.', inspectedObjects));
+ }
+ } else if (QQmlValueTypeFactory::valueType(metaProperty.userType())) {
+ QQmlValueType *valueType = QQmlValueTypeFactory::valueType(metaProperty.userType());
+ valueType->setValue(metaProperty.read(object));
+ propertyNameList.append(propertyNameForWritableProperties(valueType, baseName + QString::fromUtf8(metaProperty.name()) + '.', inspectedObjects));
+ }
+
+ if (metaProperty.isReadable() && metaProperty.isWritable()) {
+ propertyNameList.append(baseName + QString::fromUtf8(metaProperty.name()));
+ }
+ }
+
+ return propertyNameList;
+}
+
+static void fixResourcePathsForObject(QObject *object)
+{
+ if (qgetenv("QMLDESIGNER_RC_PATHS").isEmpty())
+ return;
+
+ QStringList propertyNameList = propertyNameForWritableProperties(object);
+
+ foreach (const QString &propertyName, propertyNameList) {
+ QQmlProperty property(object, propertyName, QQmlEngine::contextForObject(object));
+
+ const QVariant value = property.read();
+ const QVariant fixedValue = ObjectNodeInstance::fixResourcePaths(value);
+ if (value != fixedValue) {
+ property.write(fixedValue);
+ }
+ }
+}
+
+void tweakObjects(QObject *object)
+{
+ QObjectList objectList;
+ allSubObject(object, objectList);
+ foreach (QObject* childObject, objectList) {
+ disableTiledBackingStore(childObject);
+ stopAnimation(childObject);
+ fixResourcePathsForObject(childObject);
+ }
+}
+
+QObject *ObjectNodeInstance::createComponentWrap(const QString &nodeSource, const QStringList &imports, QQmlContext *context)
+{
+ QQmlComponent *component = new QQmlComponent(context->engine());
+
+ QByteArray importArray;
+
+ foreach (const QString &import, imports) {
+ importArray.append(import.toUtf8());
+ }
+
+ QByteArray data(nodeSource.toUtf8());
+
+ data.prepend(importArray);
+
+ component->setData(data, context->baseUrl().resolved(QUrl("createComponent.qml")));
+
+ QObject *object = component;
+ tweakObjects(object);
+
+ if (object && context)
+ QQmlEngine::setContextForObject(object, context);
+
+ QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
+
+ return object;
+}
+
+
+//The component might also be shipped with Creator.
+//To avoid trouble with import "." we use the component shipped with Creator.
+static inline QString fixComponentPathForIncompatibleQt(const QString &componentPath)
+{
+ QString result = componentPath;
+ const QLatin1String importString("/imports/");
+
+ if (componentPath.contains(importString)) {
+ int index = componentPath.indexOf(importString) + 8;
+ const QString relativeImportPath = componentPath.right(componentPath.length() - index);
+ QString fixedComponentPath = QLibraryInfo::location(QLibraryInfo::ImportsPath) + relativeImportPath;
+ fixedComponentPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
+ if (QFileInfo(fixedComponentPath).exists())
+ return fixedComponentPath;
+ QString fixedPath = QFileInfo(fixedComponentPath).path();
+ if (fixedPath.endsWith(QLatin1String(".1.0"))) {
+ //plugin directories might contain the version number
+ fixedPath.chop(4);
+ fixedPath += QLatin1Char('/') + QFileInfo(componentPath).fileName();
+ if (QFileInfo(fixedPath).exists())
+ return fixedPath;
+ }
+ }
+
+ return result;
+}
+
+QObject *ObjectNodeInstance::createComponent(const QString &componentPath, QQmlContext *context)
+{
+ QQmlComponent component(context->engine(), fixComponentPathForIncompatibleQt(componentPath));
+ QObject *object = component.beginCreate(context);
+
+ tweakObjects(object);
+ component.completeCreate();
+
+ if (component.isError()) {
+ qDebug() << componentPath;
+ foreach (const QQmlError &error, component.errors())
+ qDebug() << error;
+ }
+
+ QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
+
+ return object;
+}
+
+QObject *ObjectNodeInstance::createCustomParserObject(const QString &nodeSource, const QStringList &imports, QQmlContext *context)
+{
+ QQmlComponent component(context->engine());
+
+ QByteArray importArray;
+ foreach (const QString &import, imports) {
+ importArray.append(import.toUtf8());
+ }
+
+ QByteArray data(nodeSource.toUtf8());
+
+ data.prepend(importArray);
+
+ component.setData(data, context->baseUrl().resolved(QUrl("createCustomParserObject.qml")));
+
+ QObject *object = component.beginCreate(context);
+ tweakObjects(object);
+ component.completeCreate();
+
+ QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
+
+ return object;
+}
+
+QObject *ObjectNodeInstance::createPrimitive(const QString &typeName, int majorNumber, int minorNumber, QQmlContext *context)
+{
+ QObject *object = 0;
+ QQmlType *type = QQmlMetaType::qmlType(typeName.toUtf8(), majorNumber, minorNumber);
+ if (type) {
+ if (type->typeName() == "QQmlComponent") {
+ object = new QQmlComponent(context->engine(), 0);
+ } else {
+ object = type->create();
+ }
+ } else {
+ qWarning() << "QuickDesigner: Cannot create an object of type"
+ << QString("%1 %2,%3").arg(typeName).arg(majorNumber).arg(minorNumber)
+ << "- type isn't known to declarative meta type system";
+ }
+
+ tweakObjects(object);
+
+ if (object && context)
+ QQmlEngine::setContextForObject(object, context);
+
+ QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);
+
+ return object;
+}
+
+QObject *ObjectNodeInstance::object() const
+{
+ if (!m_object.isNull() && !QObjectPrivate::get(m_object.data())->wasDeleted)
+ return m_object.data();
+ return 0;
+}
+
+bool ObjectNodeInstance::hasContent() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isResizable() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isMovable() const
+{
+ return false;
+}
+
+bool ObjectNodeInstance::isInPositioner() const
+{
+ return m_isInPositioner;
+}
+
+void ObjectNodeInstance::setInPositioner(bool isInPositioner)
+{
+ m_isInPositioner = isInPositioner;
+}
+
+void ObjectNodeInstance::refreshPositioner()
+{
+}
+
+void ObjectNodeInstance::updateAnchors()
+{
+}
+
+QQmlContext *ObjectNodeInstance::context() const
+{
+ if (nodeInstanceServer())
+ return nodeInstanceServer()->context();
+
+ qWarning() << "Error: No NodeInstanceServer";
+ return 0;
+}
+
+QQmlEngine *ObjectNodeInstance::engine() const
+{
+ return nodeInstanceServer()->engine();
+}
+
+void ObjectNodeInstance::paintUpdate()
+{
+}
+
+void ObjectNodeInstance::activateState()
+{
+}
+
+void ObjectNodeInstance::deactivateState()
+{
+}
+
+void ObjectNodeInstance::populateResetHashes()
+{
+ QStringList propertyNameList = propertyNameForWritableProperties(object());
+
+ foreach (const QString &propertyName, propertyNameList) {
+ QQmlProperty property(object(), propertyName, QQmlEngine::contextForObject(object()));
+
+ QQmlAbstractBinding::Pointer binding = QQmlAbstractBinding::getPointer(QQmlPropertyPrivate::binding(property));
+ if (binding) {
+ m_resetBindingHash.insert(propertyName, binding);
+ } else if (property.isWritable()) {
+ m_resetValueHash.insert(propertyName, property.read());
+ }
+ }
+}
+
+QQmlAbstractBinding *ObjectNodeInstance::resetBinding(const QString &propertyName) const
+{
+ return m_resetBindingHash.value(propertyName).data();
+}
+
+bool ObjectNodeInstance::hasValidResetBinding(const QString &propertyName) const
+{
+ return m_resetBindingHash.contains(propertyName) && m_resetBindingHash.value(propertyName).data();
+}
+
+QVariant ObjectNodeInstance::resetValue(const QString &propertyName) const
+{
+ return m_resetValueHash.value(propertyName);
+}
+
+void ObjectNodeInstance::setResetValue(const QString &propertyName, const QVariant &value)
+{
+ m_resetValueHash.insert(propertyName, value);
+}
+
+void ObjectNodeInstance::paint(QPainter * /*painter*/)
+{
+}
+
+QImage ObjectNodeInstance::renderImage() const
+{
+ return QImage();
+}
+
+QObject *ObjectNodeInstance::parent() const
+{
+ if (!object())
+ return 0;
+
+ return object()->parent();
+}
+
+QObject *parentObject(QObject *object)
+{
+ QQuickItem *quickItem = qobject_cast<QQuickItem*>(object);
+ if (quickItem)
+ return quickItem->parentItem();
+
+ return object->parent();
+}
+
+ObjectNodeInstance::Pointer ObjectNodeInstance::parentInstance() const
+{
+ QObject *parentHolder = parent();
+ if (!nodeInstanceServer())
+ return Pointer();
+
+ while (parentHolder) {
+ if (nodeInstanceServer()->hasInstanceForObject(parentHolder))
+ return nodeInstanceServer()->instanceForObject(parentHolder).internalInstance();
+
+ parentHolder = parentObject(parentHolder);
+ }
+
+ return Pointer();
+}
+
+QRectF ObjectNodeInstance::boundingRect() const
+{
+ return QRect();
+}
+
+QPointF ObjectNodeInstance::position() const
+{
+ return QPointF();
+}
+
+QSizeF ObjectNodeInstance::size() const
+{
+ return QSizeF();
+}
+
+int ObjectNodeInstance::penWidth() const
+{
+ return 0;
+}
+
+void ObjectNodeInstance::createDynamicProperty(const QString &name, const QString &/*typeName*/)
+{
+ if (m_metaObject == 0) {
+ qWarning() << "ObjectNodeInstance.createDynamicProperty: No Metaobject.";
+ return;
+ }
+
+ m_metaObject->createNewProperty(name);
+}
+
+bool ObjectNodeInstance::updateStateVariant(const ObjectNodeInstance::Pointer &/*target*/, const QString &/*propertyName*/, const QVariant &/*value*/)
+{
+ return false;
+}
+
+bool ObjectNodeInstance::updateStateBinding(const ObjectNodeInstance::Pointer &/*target*/, const QString &/*propertyName*/, const QString &/*expression*/)
+{
+ return false;
+}
+
+bool ObjectNodeInstance::resetStateProperty(const ObjectNodeInstance::Pointer &/*target*/, const QString &/*propertyName*/, const QVariant &/*resetValue*/)
+{
+ return false;
+}
+
+void ObjectNodeInstance::doComponentComplete()
+{
+
+}
+
+bool ObjectNodeInstance::isRootNodeInstance() const
+{
+ return nodeInstanceServer()->rootNodeInstance().isWrappingThisObject(object());
+}
+
+bool ObjectNodeInstance::isValid() const
+{
+ return instanceId() >= 0 && object();
+}
+
+}
+}
+
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.h
new file mode 100644
index 0000000000..b8451d5b0c
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/objectnodeinstance.h
@@ -0,0 +1,209 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef ABSTRACTNODEINSTANCE_H
+#define ABSTRACTNODEINSTANCE_H
+
+#include "nodeinstanceserver.h"
+#include "nodeinstancemetaobject.h"
+#include "nodeinstancesignalspy.h"
+
+#include <QPainter>
+#include <QSharedPointer>
+#include <QWeakPointer>
+
+QT_BEGIN_NAMESPACE
+class QGraphicsItem;
+class QQmlContext;
+class QQmlEngine;
+class QQmlProperty;
+class QQmlAbstractBinding;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+class NodeInstanceServer;
+
+namespace Internal {
+
+class QmlGraphicsItemNodeInstance;
+class GraphicsWidgetNodeInstance;
+class GraphicsViewNodeInstance;
+class GraphicsSceneNodeInstance;
+class ProxyWidgetNodeInstance;
+class WidgetNodeInstance;
+
+class ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<ObjectNodeInstance> Pointer;
+ typedef QWeakPointer<ObjectNodeInstance> WeakPointer;
+ explicit ObjectNodeInstance(QObject *object);
+
+ virtual ~ObjectNodeInstance();
+ void destroy();
+ //void setModelNode(const ModelNode &node);
+
+ static Pointer create(QObject *objectToBeWrapped);
+ static QObject *createPrimitive(const QString &typeName, int majorNumber, int minorNumber, QQmlContext *context);
+ static QObject *createCustomParserObject(const QString &nodeSource, const QStringList &imports, QQmlContext *context);
+ static QObject *createComponent(const QString &componentPath, QQmlContext *context);
+ static QObject *createComponentWrap(const QString &nodeSource, const QStringList &imports, QQmlContext *context);
+
+ void setInstanceId(qint32 id);
+ qint32 instanceId() const;
+
+ NodeInstanceServer *nodeInstanceServer() const;
+ void setNodeInstanceServer(NodeInstanceServer *server);
+ virtual void initializePropertyWatcher(const Pointer &objectNodeInstance);
+ virtual void initialize(const Pointer &objectNodeInstance);
+ virtual void paint(QPainter *painter);
+ virtual QImage renderImage() const;
+
+ virtual QObject *parent() const;
+
+ Pointer parentInstance() const;
+
+ virtual void reparent(const ObjectNodeInstance::Pointer &oldParentInstance, const QString &oldParentProperty, const ObjectNodeInstance::Pointer &newParentInstance, const QString &newParentProperty);
+
+ virtual void setId(const QString &id);
+ virtual QString id() const;
+
+ virtual bool isTransition() const;
+ virtual bool isPositioner() const;
+ virtual bool isQuickItem() const;
+
+ virtual bool equalGraphicsItem(QGraphicsItem *item) const;
+
+ virtual QRectF boundingRect() const;
+
+ virtual QPointF position() const;
+ virtual QSizeF size() const;
+ virtual QTransform transform() const;
+ virtual QTransform customTransform() const;
+ virtual QTransform sceneTransform() const;
+ virtual double opacity() const;
+
+ virtual int penWidth() const;
+
+ virtual bool hasAnchor(const QString &name) const;
+ virtual QPair<QString, ServerNodeInstance> anchor(const QString &name) const;
+ virtual bool isAnchoredBySibling() const;
+ virtual bool isAnchoredByChildren() const;
+
+ virtual double rotation() const;
+ virtual double scale() const;
+ virtual QList<QGraphicsTransform *> transformations() const;
+ virtual QPointF transformOriginPoint() const;
+ virtual double zValue() const;
+
+ virtual void setPropertyVariant(const QString &name, const QVariant &value);
+ virtual void setPropertyBinding(const QString &name, const QString &expression);
+ virtual QVariant property(const QString &name) const;
+ virtual void resetProperty(const QString &name);
+ virtual void refreshProperty(const QString &name);
+ virtual QString instanceType(const QString &name) const;
+ QStringList propertyNames() const;
+
+ virtual QList<ServerNodeInstance> childItems() const;
+
+ void createDynamicProperty(const QString &name, const QString &typeName);
+ void setDeleteHeldInstance(bool deleteInstance);
+ bool deleteHeldInstance() const;
+
+ virtual void updateAnchors();
+ virtual void paintUpdate();
+
+ virtual void activateState();
+ virtual void deactivateState();
+
+ void populateResetHashes();
+ bool hasValidResetBinding(const QString &propertyName) const;
+ QQmlAbstractBinding *resetBinding(const QString &propertyName) const;
+ QVariant resetValue(const QString &propertyName) const;
+ void setResetValue(const QString &propertyName, const QVariant &value);
+
+ QObject *object() const;
+
+ virtual bool hasContent() const;
+ virtual bool isResizable() const;
+ virtual bool isMovable() const;
+ bool isInPositioner() const;
+ void setInPositioner(bool isInPositioner);
+ virtual void refreshPositioner();
+
+ bool hasBindingForProperty(const QString &name, bool *hasChanged = 0) const;
+
+ QQmlContext *context() const;
+ QQmlEngine *engine() const;
+
+ virtual bool updateStateVariant(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QVariant &value);
+ virtual bool updateStateBinding(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QString &expression);
+ virtual bool resetStateProperty(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QVariant &resetValue);
+
+
+ bool isValid() const;
+ bool isRootNodeInstance() const;
+
+ virtual void doComponentComplete();
+
+ virtual QList<ServerNodeInstance> stateInstances() const;
+
+ virtual void setNodeSource(const QString &source);
+
+ static QVariant fixResourcePaths(const QVariant &value);
+
+protected:
+ void doResetProperty(const QString &propertyName);
+ void removeFromOldProperty(QObject *object, QObject *oldParent, const QString &oldParentProperty);
+ void addToNewProperty(QObject *object, QObject *newParent, const QString &newParentProperty);
+ void deleteObjectsInList(const QQmlProperty &metaProperty);
+ QVariant convertSpecialCharacter(const QVariant& value) const;
+
+private:
+ QHash<QString, QVariant> m_resetValueHash;
+ QHash<QString, QWeakPointer<QQmlAbstractBinding> > m_resetBindingHash;
+ QHash<QString, ServerNodeInstance> m_modelAbstractPropertyHash;
+ mutable QHash<QString, bool> m_hasBindingHash;
+ qint32 m_instanceId;
+ QString m_id;
+
+ QPointer<NodeInstanceServer> m_nodeInstanceServer;
+ QString m_parentProperty;
+ bool m_deleteHeldInstance;
+ QPointer<QObject> m_object;
+ NodeInstanceMetaObject *m_metaObject;
+ NodeInstanceSignalSpy m_signalSpy;
+ bool m_isInPositioner;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // ABSTRACTNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.cpp
new file mode 100644
index 0000000000..4504bbb268
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.cpp
@@ -0,0 +1,97 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#include "positionernodeinstance.h"
+#include <private/qquickpositioners_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+PositionerNodeInstance::PositionerNodeInstance(QQuickBasePositioner *item)
+ : QuickItemNodeInstance(item)
+{
+}
+
+bool PositionerNodeInstance::isPositioner() const
+{
+ return true;
+}
+
+bool PositionerNodeInstance::isResizable() const
+{
+ return true;
+}
+
+void PositionerNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ if (name == "move" || name == "add" || name == "populate")
+ return;
+
+ QuickItemNodeInstance::setPropertyVariant(name, value);
+}
+
+void PositionerNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+{
+ if (name == "move" || name == "add" || name == "populate")
+ return;
+
+ QuickItemNodeInstance::setPropertyBinding(name, expression);
+}
+
+PositionerNodeInstance::Pointer PositionerNodeInstance::create(QObject *object)
+{
+ QQuickBasePositioner *positioner = qobject_cast<QQuickBasePositioner*>(object);
+
+ Q_ASSERT(positioner);
+
+ Pointer instance(new PositionerNodeInstance(positioner));
+
+ instance->setHasContent(anyItemHasContent(positioner));
+ positioner->setFlag(QQuickItem::ItemHasContents, true);
+
+ static_cast<QQmlParserStatus*>(positioner)->classBegin();
+
+ instance->populateResetHashes();
+
+ return instance;
+}
+
+QQuickBasePositioner *PositionerNodeInstance::positioner() const
+{
+ Q_ASSERT(qobject_cast<QQuickBasePositioner*>(object()));
+ return static_cast<QQuickBasePositioner*>(object());
+}
+
+void PositionerNodeInstance::refreshPositioner()
+{
+ bool success = QMetaObject::invokeMethod(positioner(), "prePositioning");
+ Q_ASSERT(success);
+}
+
+}
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.h
new file mode 100644
index 0000000000..456591ed23
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/positionernodeinstance.h
@@ -0,0 +1,67 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef POSITIONERNODEINSTANCE_H
+#define POSITIONERNODEINSTANCE_H
+
+#include "quickitemnodeinstance.h"
+
+QT_BEGIN_NAMESPACE
+class QQuickBasePositioner;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+namespace Internal {
+
+class PositionerNodeInstance : public QuickItemNodeInstance
+{
+public:
+ typedef QSharedPointer<PositionerNodeInstance> Pointer;
+ typedef QWeakPointer<PositionerNodeInstance> WeakPointer;
+
+ static Pointer create(QObject *objectToBeWrapped);
+
+ void setPropertyVariant(const QString &name, const QVariant &value);
+ void setPropertyBinding(const QString &name, const QString &expression);
+
+ bool isPositioner() const;
+
+ bool isResizable() const;
+
+ void refreshPositioner();
+
+protected:
+ PositionerNodeInstance(QQuickBasePositioner *item);
+ QQuickBasePositioner *positioner() const;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // POSITIONERNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.cpp
new file mode 100644
index 0000000000..6d2d220185
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.cpp
@@ -0,0 +1,118 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlpropertychangesnodeinstance.h"
+#include "qmlstatenodeinstance.h"
+#include <QQmlEngine>
+#include <QQmlContext>
+#include <QQmlExpression>
+#include <private/qqmlbinding_p.h>
+#include <QMutableListIterator>
+
+
+#include <private/qquickstate_p_p.h>
+#include <private/qquickpropertychanges_p.h>
+#include <private/qqmlproperty_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+QmlPropertyChangesNodeInstance::QmlPropertyChangesNodeInstance(QQuickPropertyChanges *propertyChangesObject) :
+ ObjectNodeInstance(propertyChangesObject)
+{
+}
+
+QmlPropertyChangesNodeInstance::Pointer QmlPropertyChangesNodeInstance::create(QObject *object)
+{
+ QQuickPropertyChanges *propertyChange = qobject_cast<QQuickPropertyChanges*>(object);
+
+ Q_ASSERT(propertyChange);
+
+ Pointer instance(new QmlPropertyChangesNodeInstance(propertyChange));
+
+ instance->populateResetHashes();
+
+ return instance;
+}
+
+void QmlPropertyChangesNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ QMetaObject metaObject = QQuickPropertyChanges::staticMetaObject;
+
+ if (metaObject.indexOfProperty(name.toLatin1()) > 0) { // 'restoreEntryValues', 'explicit'
+ ObjectNodeInstance::setPropertyVariant(name, value);
+ } else {
+ changesObject()->changeValue(name.toLatin1(), value);
+ QObject *targetObject = changesObject()->object();
+ if (targetObject && nodeInstanceServer()->activeStateInstance().isWrappingThisObject(changesObject()->state())) {
+ ServerNodeInstance targetInstance = nodeInstanceServer()->instanceForObject(targetObject);
+ targetInstance.setPropertyVariant(name, value);
+ }
+ }
+}
+
+void QmlPropertyChangesNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+{
+ QMetaObject metaObject = QQuickPropertyChanges::staticMetaObject;
+
+ if (metaObject.indexOfProperty(name.toLatin1()) > 0) { // 'restoreEntryValues', 'explicit'
+ ObjectNodeInstance::setPropertyBinding(name, expression);
+ } else {
+ changesObject()->changeExpression(name.toLatin1(), expression);
+ }
+}
+
+QVariant QmlPropertyChangesNodeInstance::property(const QString &name) const
+{
+ return changesObject()->property(name.toLatin1());
+}
+
+void QmlPropertyChangesNodeInstance::resetProperty(const QString &name)
+{
+ changesObject()->removeProperty(name.toLatin1());
+}
+
+
+void QmlPropertyChangesNodeInstance::reparent(const ServerNodeInstance &oldParentInstance, const QString &oldParentProperty, const ServerNodeInstance &newParentInstance, const QString &newParentProperty)
+{
+ changesObject()->detachFromState();
+
+ ObjectNodeInstance::reparent(oldParentInstance.internalInstance(), oldParentProperty, newParentInstance.internalInstance(), newParentProperty);
+
+ changesObject()->attachToState();
+}
+
+QQuickPropertyChanges *QmlPropertyChangesNodeInstance::changesObject() const
+{
+ Q_ASSERT(qobject_cast<QQuickPropertyChanges*>(object()));
+ return static_cast<QQuickPropertyChanges*>(object());
+}
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.h
new file mode 100644
index 0000000000..d8a75e8c66
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlpropertychangesnodeinstance.h
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#ifndef QMLPROPERTYCHANGESNODEINSTANCE_H
+#define QMLPROPERTYCHANGESNODEINSTANCE_H
+
+#include "objectnodeinstance.h"
+#include <private/qquickstateoperations_p.h>
+#include <private/qquickpropertychanges_p.h>
+
+#include <QPair>
+#include <QWeakPointer>
+
+QT_BEGIN_NAMESPACE
+class QQuickProperty;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+namespace Internal {
+
+class QmlPropertyChangesNodeInstance;
+
+class QmlPropertyChangesNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<QmlPropertyChangesNodeInstance> Pointer;
+ typedef QWeakPointer<QmlPropertyChangesNodeInstance> WeakPointer;
+
+ static Pointer create(QObject *objectToBeWrapped);
+
+ virtual void setPropertyVariant(const QString &name, const QVariant &value);
+ virtual void setPropertyBinding(const QString &name, const QString &expression);
+ virtual QVariant property(const QString &name) const;
+ virtual void resetProperty(const QString &name);
+
+ using ObjectNodeInstance::reparent; // keep the virtual reparent(...) method around
+ void reparent(const ServerNodeInstance &oldParentInstance, const QString &oldParentProperty, const ServerNodeInstance &newParentInstance, const QString &newParentProperty);
+
+protected:
+ QmlPropertyChangesNodeInstance(QQuickPropertyChanges *object);
+ QQuickPropertyChanges *changesObject() const;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+//QML_DECLARE_TYPE(QmlDesigner::Internal::QmlPropertyChangesObject)
+
+#endif // QMLPROPERTYCHANGESNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.cpp
new file mode 100644
index 0000000000..0a4e830665
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.cpp
@@ -0,0 +1,138 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlstatenodeinstance.h"
+
+#include <private/qquickstategroup_p.h>
+
+#include "qmlpropertychangesnodeinstance.h"
+#include <private/qquickstateoperations_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+/**
+ \class QmlStateNodeInstance
+
+ QmlStateNodeInstance manages a QQuickState object.
+ */
+
+QmlStateNodeInstance::QmlStateNodeInstance(QQuickState *object) :
+ ObjectNodeInstance(object)
+{
+}
+
+QmlStateNodeInstance::Pointer
+ QmlStateNodeInstance::create(QObject *object)
+{
+ QQuickState *stateObject = qobject_cast<QQuickState*>(object);
+
+ Q_ASSERT(stateObject);
+
+ Pointer instance(new QmlStateNodeInstance(stateObject));
+
+ instance->populateResetHashes();
+
+ return instance;
+}
+
+void QmlStateNodeInstance::activateState()
+{
+ if (stateGroup()) {
+ if (!isStateActive()) {
+ nodeInstanceServer()->setStateInstance(nodeInstanceServer()->instanceForObject(object()));
+ stateGroup()->setState(property("name").toString());
+ }
+ }
+}
+
+void QmlStateNodeInstance::deactivateState()
+{
+ if (stateGroup()) {
+ if (isStateActive()) {
+ nodeInstanceServer()->clearStateInstance();
+ stateGroup()->setState(QString());
+ }
+ }
+}
+
+QQuickState *QmlStateNodeInstance::stateObject() const
+{
+ Q_ASSERT(object());
+ Q_ASSERT(qobject_cast<QQuickState*>(object()));
+ return static_cast<QQuickState*>(object());
+}
+
+QQuickStateGroup *QmlStateNodeInstance::stateGroup() const
+{
+ return stateObject()->stateGroup();
+}
+
+bool QmlStateNodeInstance::isStateActive() const
+{
+ return stateObject() && stateGroup() && stateGroup()->state() == property("name");
+}
+
+void QmlStateNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ bool hasParent = parent();
+ bool isStateOfTheRootModelNode = parentInstance() && parentInstance()->isRootNodeInstance();
+ if (name == "when" && (!hasParent || isStateOfTheRootModelNode))
+ return;
+
+ ObjectNodeInstance::setPropertyVariant(name, value);
+}
+
+void QmlStateNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+{
+ bool hasParent = parent();
+ bool isStateOfTheRootModelNode = parentInstance() && parentInstance()->isRootNodeInstance();
+ if (name == "when" && (!hasParent || isStateOfTheRootModelNode))
+ return;
+
+ ObjectNodeInstance::setPropertyBinding(name, expression);
+}
+
+bool QmlStateNodeInstance::updateStateVariant(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QVariant &value)
+{
+ return stateObject()->changeValueInRevertList(target->object(), propertyName.toLatin1(), value);
+}
+
+bool QmlStateNodeInstance::updateStateBinding(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QString &expression)
+{
+ return stateObject()->changeValueInRevertList(target->object(), propertyName.toLatin1(), expression);
+}
+
+bool QmlStateNodeInstance::resetStateProperty(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QVariant & /* resetValue */)
+{
+ return stateObject()->removeEntryFromRevertList(target->object(), propertyName.toLatin1());
+}
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.h
new file mode 100644
index 0000000000..d93dcc8afb
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmlstatenodeinstance.h
@@ -0,0 +1,75 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#ifndef QMLSTATENODEINSTANCE_H
+#define QMLSTATENODEINSTANCE_H
+
+#include "objectnodeinstance.h"
+
+QT_BEGIN_NAMESPACE
+class QQuickState;
+class QQuickStateGroup;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+namespace Internal {
+
+class QmlStateNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<QmlStateNodeInstance> Pointer;
+ typedef QWeakPointer<QmlStateNodeInstance> WeakPointer;
+
+ static Pointer create(QObject *objectToBeWrapped);
+
+ void setPropertyVariant(const QString &name, const QVariant &value);
+ void setPropertyBinding(const QString &name, const QString &expression);
+
+ void activateState();
+ void deactivateState();
+
+ bool updateStateVariant(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QVariant &value);
+ bool updateStateBinding(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QString &expression);
+ bool resetStateProperty(const ObjectNodeInstance::Pointer &target, const QString &propertyName, const QVariant &resetValue);
+
+
+protected:
+
+ QmlStateNodeInstance(QQuickState *object);
+
+ bool isStateActive() const;
+
+ QQuickState *stateObject() const;
+ QQuickStateGroup *stateGroup() const;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // QMLSTATENODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.cpp
new file mode 100644
index 0000000000..e2f713b5aa
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.cpp
@@ -0,0 +1,76 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmltransitionnodeinstance.h"
+#include <private/qquicktransition_p.h>
+
+namespace QmlDesigner {
+namespace Internal {
+
+QmlTransitionNodeInstance::QmlTransitionNodeInstance(QQuickTransition *transition)
+ : ObjectNodeInstance(transition)
+{
+}
+
+QmlTransitionNodeInstance::Pointer QmlTransitionNodeInstance::create(QObject *object)
+{
+ QQuickTransition *transition = qobject_cast<QQuickTransition*>(object);
+
+ Q_ASSERT(transition);
+
+ Pointer instance(new QmlTransitionNodeInstance(transition));
+
+ instance->populateResetHashes();
+
+ transition->setToState("invalidState");
+ transition->setFromState("invalidState");
+
+ return instance;
+}
+
+bool QmlTransitionNodeInstance::isTransition() const
+{
+ return true;
+}
+
+void QmlTransitionNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ if (name == "from" || name == "to")
+ return;
+
+ ObjectNodeInstance::setPropertyVariant(name, value);
+}
+
+QQuickTransition *QmlTransitionNodeInstance::qmlTransition() const
+{
+ Q_ASSERT(qobject_cast<QQuickTransition*>(object()));
+ return static_cast<QQuickTransition*>(object());
+}
+}
+}
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.h
new file mode 100644
index 0000000000..3603516ee9
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qmltransitionnodeinstance.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLTRANSITIONNODEINSTANCE_H
+#define QMLTRANSITIONNODEINSTANCE_H
+
+#include "objectnodeinstance.h"
+
+QT_BEGIN_NAMESPACE
+class QQuickTransition;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+namespace Internal {
+
+class QmlTransitionNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<QmlTransitionNodeInstance> Pointer;
+ typedef QWeakPointer<QmlTransitionNodeInstance> WeakPointer;
+
+ static Pointer create(QObject *objectToBeWrapped);
+
+ void setPropertyVariant(const QString &name, const QVariant &value);
+
+ bool isTransition() const;
+
+protected:
+ QQuickTransition *qmlTransition() const;
+
+private:
+ QmlTransitionNodeInstance(QQuickTransition *transition);
+};
+}
+}
+#endif // QMLTRANSITIONNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp
index 12d2c10fed..8f6c458521 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.cpp
@@ -29,7 +29,8 @@
#include "qt5informationnodeinstanceserver.h"
-#include <QSGItem>
+#include <QQuickItem>
+#include <QQuickView>
#include "servernodeinstance.h"
#include "childrenchangeeventfilter.h"
@@ -58,6 +59,7 @@
#include "componentcompletedcommand.h"
#include "createscenecommand.h"
#include "tokencommand.h"
+#include "removesharedmemorycommand.h"
#include "dummycontextobject.h"
@@ -90,12 +92,14 @@ void Qt5InformationNodeInstanceServer::collectItemChangesAndSendChangeCommands()
if (!inFunction) {
inFunction = true;
+ DesignerSupport::polishItems(quickView());
+
QSet<ServerNodeInstance> informationChangedInstanceSet;
QVector<InstancePropertyPair> propertyChangedList;
bool adjustSceneRect = false;
- if (sgView()) {
- foreach (QSGItem *item, allItems()) {
+ if (quickView()) {
+ foreach (QQuickItem *item, allItems()) {
if (item && hasInstanceForObject(item)) {
ServerNodeInstance instance = instanceForObject(item);
@@ -255,4 +259,10 @@ void Qt5InformationNodeInstanceServer::completeComponent(const CompleteComponent
nodeInstanceClient()->informationChanged(createAllInformationChangedCommand(instanceList, true));
}
+void QmlDesigner::Qt5InformationNodeInstanceServer::removeSharedMemory(const QmlDesigner::RemoveSharedMemoryCommand &command)
+{
+ if (command.typeName() == "Values")
+ ValuesChangedCommand::removeSharedMemorys(command.keyNumbers());
+}
+
} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.h
index 9a8b3e06db..a6b9408946 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5informationnodeinstanceserver.h
@@ -46,6 +46,7 @@ public:
void createScene(const CreateSceneCommand &command);
void completeComponent(const CompleteComponentCommand &command);
void token(const TokenCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
protected:
void collectItemChangesAndSendChangeCommands();
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceclientproxy.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceclientproxy.cpp
index c15b6afe03..1b6e663af2 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceclientproxy.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceclientproxy.cpp
@@ -35,11 +35,14 @@
#include "qt5previewnodeinstanceserver.h"
#include "qt5rendernodeinstanceserver.h"
+#include <designersupport.h>
+
namespace QmlDesigner {
Qt5NodeInstanceClientProxy::Qt5NodeInstanceClientProxy(QObject *parent) :
NodeInstanceClientProxy(parent)
{
+ DesignerSupport::activateDesignerWindowManager();
if (QCoreApplication::arguments().at(2) == QLatin1String("previewmode")) {
setNodeInstanceServer(new Qt5PreviewNodeInstanceServer(this));
} else if (QCoreApplication::arguments().at(2) == QLatin1String("editormode")) {
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.cpp
index 10f312e013..503f3ee903 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.cpp
@@ -30,8 +30,8 @@
#include "qt5nodeinstanceserver.h"
-#include <QSGItem>
-#include <QSGView>
+#include <QQuickItem>
+#include <QQuickView>
#include <designersupport.h>
#include <addimportcontainer.h>
@@ -44,44 +44,38 @@ Qt5NodeInstanceServer::Qt5NodeInstanceServer(NodeInstanceClientInterface *nodeIn
m_designerSupport(new DesignerSupport)
{
addImportString("import QtQuick 2.0\n");
+ DesignerSupport::activateDesignerMode();
}
Qt5NodeInstanceServer::~Qt5NodeInstanceServer()
{
- delete sgView();
+ delete quickView();
delete m_designerSupport;
m_designerSupport = 0;
}
-QSGView *Qt5NodeInstanceServer::sgView() const
+QQuickView *Qt5NodeInstanceServer::quickView() const
{
- return m_sgView.data();
+ return m_quickView.data();
}
void Qt5NodeInstanceServer::initializeView(const QVector<AddImportContainer> &/*importVector*/)
{
- Q_ASSERT(!sgView());
-
- m_sgView = new QSGView;
-#ifndef Q_OS_MAC
- sgView()->setAttribute(Qt::WA_DontShowOnScreen, true);
-#endif
- sgView()->show();
-#ifdef Q_OS_MAC
- sgView()->setAttribute(Qt::WA_DontShowOnScreen, true);
-#endif
- sgView()->setUpdatesEnabled(false);
+ Q_ASSERT(!quickView());
+
+ m_quickView = new QQuickView;
+ DesignerSupport::createOpenGLContext(m_quickView.data());
}
-QDeclarativeView *Qt5NodeInstanceServer::declarativeView() const
+QQmlView *Qt5NodeInstanceServer::declarativeView() const
{
return 0;
}
-QDeclarativeEngine *Qt5NodeInstanceServer::engine() const
+QQmlEngine *Qt5NodeInstanceServer::engine() const
{
- if (sgView())
- return sgView()->engine();
+ if (quickView())
+ return quickView()->engine();
return 0;
}
@@ -92,7 +86,7 @@ void Qt5NodeInstanceServer::resizeCanvasSizeToRootItemSize()
void Qt5NodeInstanceServer::resetAllItems()
{
- foreach (QSGItem *item, allItems())
+ foreach (QQuickItem *item, allItems())
DesignerSupport::resetDirty(item);
}
@@ -104,29 +98,29 @@ QList<ServerNodeInstance> Qt5NodeInstanceServer::setupScene(const CreateSceneCom
QList<ServerNodeInstance> instanceList = setupInstances(command);
- sgView()->resize(rootNodeInstance().boundingRect().size().toSize());
+ quickView()->resize(rootNodeInstance().boundingRect().size().toSize());
return instanceList;
}
-QList<QSGItem*> subItems(QSGItem *parentItem)
+QList<QQuickItem*> subItems(QQuickItem *parentItem)
{
- QList<QSGItem*> itemList;
+ QList<QQuickItem*> itemList;
itemList.append(parentItem->childItems());
- foreach (QSGItem *childItem, parentItem->childItems())
+ foreach (QQuickItem *childItem, parentItem->childItems())
itemList.append(subItems(childItem));
return itemList;
}
-QList<QSGItem*> Qt5NodeInstanceServer::allItems() const
+QList<QQuickItem*> Qt5NodeInstanceServer::allItems() const
{
- QList<QSGItem*> itemList;
+ QList<QQuickItem*> itemList;
- if (sgView()) {
- itemList.append(sgView()->rootItem());
- itemList.append(subItems(sgView()->rootItem()));
+ if (quickView()) {
+ itemList.append(quickView()->rootObject());
+ itemList.append(subItems(quickView()->rootObject()));
}
return itemList;
@@ -150,9 +144,9 @@ void Qt5NodeInstanceServer::createScene(const CreateSceneCommand &command)
void Qt5NodeInstanceServer::clearScene(const ClearSceneCommand &command)
{
- NodeInstanceServer::clearScene(command);
delete m_designerSupport;
m_designerSupport = 0;
+ NodeInstanceServer::clearScene(command);
}
} // QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.h
index 1ecc1e65d4..a0f354fedf 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5nodeinstanceserver.h
@@ -35,7 +35,7 @@
#include "nodeinstanceserver.h"
QT_BEGIN_NAMESPACE
-class QSGItem;
+class QQuickItem;
class DesignerSupport;
QT_END_NAMESPACE
@@ -48,9 +48,9 @@ public:
Qt5NodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient);
~Qt5NodeInstanceServer();
- QSGView *sgView() const;
- QDeclarativeView *declarativeView() const;
- QDeclarativeEngine *engine() const;
+ QQuickView *quickView() const;
+ QQmlView *declarativeView() const;
+ QQmlEngine *engine() const;
void refreshBindings();
DesignerSupport *designerSupport() const;
@@ -63,10 +63,10 @@ protected:
void resizeCanvasSizeToRootItemSize();
void resetAllItems();
QList<ServerNodeInstance> setupScene(const CreateSceneCommand &command);
- QList<QSGItem*> allItems() const;
+ QList<QQuickItem*> allItems() const;
private:
- QWeakPointer<QSGView> m_sgView;
+ QPointer<QQuickView> m_quickView;
DesignerSupport *m_designerSupport;
};
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.cpp
index 368cc6e44d..8e3a5c767b 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.cpp
@@ -32,8 +32,9 @@
#include "nodeinstanceclientinterface.h"
#include "statepreviewimagechangedcommand.h"
#include "createscenecommand.h"
-
-#include <QSGItem>
+#include "removesharedmemorycommand.h"
+#include <QQuickView>
+#include <QQuickItem>
#include <designersupport.h>
namespace QmlDesigner {
@@ -64,14 +65,22 @@ void Qt5PreviewNodeInstanceServer::collectItemChangesAndSendChangeCommands()
{
static bool inFunction = false;
+ if (rootNodeInstance().internalSGItem() == 0)
+ return;
+
if (!inFunction && nodeInstanceClient()->bytesToWrite() < 10000) {
inFunction = true;
+
+ DesignerSupport::polishItems(quickView());
+
QVector<ImageContainer> imageContainerVector;
- imageContainerVector.append(ImageContainer(0, renderPreviewImage()));
+ imageContainerVector.append(ImageContainer(0, renderPreviewImage(), -1));
foreach (ServerNodeInstance instance, rootNodeInstance().stateInstances()) {
instance.activateState();
- imageContainerVector.append(ImageContainer(instance.instanceId(), renderPreviewImage()));
+ QImage previewImage = renderPreviewImage();
+ if (!previewImage.isNull())
+ imageContainerVector.append(ImageContainer(instance.instanceId(), renderPreviewImage(), instance.instanceId()));
instance.deactivateState();
}
@@ -87,9 +96,9 @@ void Qt5PreviewNodeInstanceServer::changeState(const ChangeStateCommand &/*comma
}
-static void updateDirtyNodeRecursive(QSGItem *parentItem)
+static void updateDirtyNodeRecursive(QQuickItem *parentItem)
{
- foreach (QSGItem *childItem, parentItem->childItems())
+ foreach (QQuickItem *childItem, parentItem->childItems())
updateDirtyNodeRecursive(childItem);
DesignerSupport::updateDirtyNode(parentItem);
@@ -114,4 +123,10 @@ QImage Qt5PreviewNodeInstanceServer::renderPreviewImage()
return previewImage;
}
+void QmlDesigner::Qt5PreviewNodeInstanceServer::removeSharedMemory(const QmlDesigner::RemoveSharedMemoryCommand &command)
+{
+ if (command.typeName() == "Image")
+ ImageContainer::removeSharedMemorys(command.keyNumbers());
+}
+
} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.h
index ffd16b5ac7..55f10bdfcc 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5previewnodeinstanceserver.h
@@ -42,6 +42,7 @@ public:
void createScene(const CreateSceneCommand &command);
void changeState(const ChangeStateCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
QImage renderPreviewImage();
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.cpp
index af5336cd84..26772f42ce 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.cpp
@@ -29,7 +29,8 @@
#include "qt5rendernodeinstanceserver.h"
-#include <QSGItem>
+#include <QQuickItem>
+#include <QQuickView>
#include "servernodeinstance.h"
#include "childrenchangeeventfilter.h"
@@ -57,8 +58,8 @@
#include "completecomponentcommand.h"
#include "componentcompletedcommand.h"
#include "createscenecommand.h"
-#include "sgitemnodeinstance.h"
-
+#include "quickitemnodeinstance.h"
+#include "removesharedmemorycommand.h"
#include "dummycontextobject.h"
@@ -69,7 +70,7 @@ namespace QmlDesigner {
Qt5RenderNodeInstanceServer::Qt5RenderNodeInstanceServer(NodeInstanceClientInterface *nodeInstanceClient) :
Qt5NodeInstanceServer(nodeInstanceClient)
{
- Internal::SGItemNodeInstance::createEffectItem(true);
+ Internal::QuickItemNodeInstance::createEffectItem(true);
}
void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands()
@@ -78,12 +79,20 @@ void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands()
if (!inFunction) {
inFunction = true;
- if (sgView() && nodeInstanceClient()->bytesToWrite() < 10000) {
- foreach (QSGItem *item, allItems()) {
- if (item && hasInstanceForObject(item)) {
- ServerNodeInstance instance = instanceForObject(item);
- if (DesignerSupport::isDirty(item, DesignerSupport::ContentUpdateMask))
- m_dirtyInstanceSet.insert(instance);
+ DesignerSupport::polishItems(quickView());
+
+ if (quickView() && nodeInstanceClient()->bytesToWrite() < 10000) {
+ foreach (QQuickItem *item, allItems()) {
+ if (item) {
+ if (hasInstanceForObject(item)
+ && DesignerSupport::isDirty(item, DesignerSupport::ContentUpdateMask)) {
+ m_dirtyInstanceSet.insert(instanceForObject(item));
+ } else if (DesignerSupport::isDirty(item, DesignerSupport::AllMask)) {
+ ServerNodeInstance ancestorInstance = findNodeInstanceForItem(item->parentItem());
+ if (ancestorInstance.isValid())
+ m_dirtyInstanceSet.insert(ancestorInstance);
+ }
+ DesignerSupport::updateDirtyNode(item);
}
}
@@ -94,8 +103,6 @@ void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands()
m_dirtyInstanceSet.clear();
}
- resetAllItems();
-
slowDownRenderTimer();
nodeInstanceClient()->flush();
nodeInstanceClient()->synchronizeWithClientProcess();
@@ -105,6 +112,18 @@ void Qt5RenderNodeInstanceServer::collectItemChangesAndSendChangeCommands()
}
}
+ServerNodeInstance Qt5RenderNodeInstanceServer::findNodeInstanceForItem(QQuickItem *item) const
+{
+ if (item) {
+ if (hasInstanceForObject(item))
+ return instanceForObject(item);
+ else if (item->parentItem())
+ return findNodeInstanceForItem(item->parentItem());
+ }
+
+ return ServerNodeInstance();
+}
+
void Qt5RenderNodeInstanceServer::createScene(const CreateSceneCommand &command)
{
@@ -144,4 +163,10 @@ void Qt5RenderNodeInstanceServer::completeComponent(const CompleteComponentComma
nodeInstanceClient()->pixmapChanged(createPixmapChangedCommand(instanceList));
}
+void QmlDesigner::Qt5RenderNodeInstanceServer::removeSharedMemory(const QmlDesigner::RemoveSharedMemoryCommand &command)
+{
+ if (command.typeName() == "Image")
+ ImageContainer::removeSharedMemorys(command.keyNumbers());
+}
+
} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.h
index 629deb2fd6..7a622f9348 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/qt5rendernodeinstanceserver.h
@@ -43,9 +43,11 @@ public:
void createScene(const CreateSceneCommand &command);
void clearScene(const ClearSceneCommand &command);
void completeComponent(const CompleteComponentCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
protected:
void collectItemChangesAndSendChangeCommands();
+ ServerNodeInstance findNodeInstanceForItem(QQuickItem *item) const;
private:
QSet<ServerNodeInstance> m_dirtyInstanceSet;
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/quickitemnodeinstance.cpp
index 3353fafadb..2a3bbb540a 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/quickitemnodeinstance.cpp
@@ -27,14 +27,17 @@
**
****************************************************************************/
-#include "sgitemnodeinstance.h"
+#include "quickitemnodeinstance.h"
#include "qt5nodeinstanceserver.h"
-#include <QDeclarativeExpression>
-#include <QSGView>
+#include <QQmlExpression>
+#include <QQuickView>
#include <cmath>
+#include <private/qquicktextinput_p.h>
+#include <private/qquicktextedit_p.h>
+
#include <QHash>
#include <QDebug>
@@ -42,9 +45,9 @@
namespace QmlDesigner {
namespace Internal {
-bool SGItemNodeInstance::s_createEffectItem = false;
+bool QuickItemNodeInstance::s_createEffectItem = false;
-SGItemNodeInstance::SGItemNodeInstance(QSGItem *item)
+QuickItemNodeInstance::QuickItemNodeInstance(QQuickItem *item)
: ObjectNodeInstance(item),
m_hasHeight(false),
m_hasWidth(false),
@@ -58,22 +61,25 @@ SGItemNodeInstance::SGItemNodeInstance(QSGItem *item)
{
}
-SGItemNodeInstance::~SGItemNodeInstance()
+QuickItemNodeInstance::~QuickItemNodeInstance()
{
- if (sgItem())
- designerSupport()->derefFromEffectItem(sgItem());
+ if (quickItem())
+ designerSupport()->derefFromEffectItem(quickItem());
}
-bool SGItemNodeInstance::hasContent() const
+bool QuickItemNodeInstance::hasContent() const
{
- return m_hasContent;
+ if (m_hasContent)
+ return true;
+
+ return childItemsHaveContent(quickItem());
}
-QList<ServerNodeInstance> SGItemNodeInstance::childItems() const
+QList<ServerNodeInstance> QuickItemNodeInstance::childItems() const
{
QList<ServerNodeInstance> instanceList;
- foreach (QSGItem *childItem, sgItem()->childItems())
+ foreach (QQuickItem *childItem, quickItem()->childItems())
{
if (childItem && nodeInstanceServer()->hasInstanceForObject(childItem)) {
instanceList.append(nodeInstanceServer()->instanceForObject(childItem));
@@ -89,12 +95,12 @@ QList<ServerNodeInstance> SGItemNodeInstance::childItems() const
return instanceList;
}
-QList<ServerNodeInstance> SGItemNodeInstance::childItemsForChild(QSGItem *childItem) const
+QList<ServerNodeInstance> QuickItemNodeInstance::childItemsForChild(QQuickItem *childItem) const
{
QList<ServerNodeInstance> instanceList;
if (childItem) {
- foreach (QSGItem *childItem, childItem->childItems())
+ foreach (QQuickItem *childItem, childItem->childItems())
{
if (childItem && nodeInstanceServer()->hasInstanceForObject(childItem)) {
instanceList.append(nodeInstanceServer()->instanceForObject(childItem));
@@ -106,18 +112,28 @@ QList<ServerNodeInstance> SGItemNodeInstance::childItemsForChild(QSGItem *childI
return instanceList;
}
-void SGItemNodeInstance::setHasContent(bool hasContent)
+void QuickItemNodeInstance::setHasContent(bool hasContent)
{
m_hasContent = hasContent;
}
-bool anyItemHasContent(QSGItem *graphicsItem)
+bool QuickItemNodeInstance::anyItemHasContent(QQuickItem *quickItem)
{
- if (graphicsItem->flags().testFlag(QSGItem::ItemHasContents))
+ if (quickItem->flags().testFlag(QQuickItem::ItemHasContents))
return true;
- foreach (QSGItem *childItem, graphicsItem->childItems()) {
+ foreach (QQuickItem *childItem, quickItem->childItems()) {
+ if (anyItemHasContent(childItem))
+ return true;
+ }
+
+ return false;
+}
+
+bool QuickItemNodeInstance::childItemsHaveContent(QQuickItem *quickItem)
+{
+ foreach (QQuickItem *childItem, quickItem->childItems()) {
if (anyItemHasContent(childItem))
return true;
}
@@ -125,67 +141,76 @@ bool anyItemHasContent(QSGItem *graphicsItem)
return false;
}
-QPointF SGItemNodeInstance::position() const
+QPointF QuickItemNodeInstance::position() const
{
- return sgItem()->pos();
+ return quickItem()->position();
}
-QTransform SGItemNodeInstance::transform() const
+static QTransform transformForItem(QQuickItem *item, NodeInstanceServer *nodeInstanceServer)
{
- return DesignerSupport::parentTransform(sgItem());
+ QTransform toParentTransform = DesignerSupport::parentTransform(item);
+ if (item->parentItem() && !nodeInstanceServer->hasInstanceForObject(item->parentItem()))
+ return transformForItem(item->parentItem(), nodeInstanceServer) * toParentTransform;
+
+ return toParentTransform;
}
-QTransform SGItemNodeInstance::customTransform() const
+QTransform QuickItemNodeInstance::transform() const
+{
+ return transformForItem(quickItem(), nodeInstanceServer());
+}
+
+QTransform QuickItemNodeInstance::customTransform() const
{
return QTransform();
}
-QTransform SGItemNodeInstance::sceneTransform() const
+QTransform QuickItemNodeInstance::sceneTransform() const
{
- return DesignerSupport::canvasTransform(sgItem());
+ return DesignerSupport::windowTransform(quickItem());
}
-double SGItemNodeInstance::rotation() const
+double QuickItemNodeInstance::rotation() const
{
- return sgItem()->rotation();
+ return quickItem()->rotation();
}
-double SGItemNodeInstance::scale() const
+double QuickItemNodeInstance::scale() const
{
- return sgItem()->scale();
+ return quickItem()->scale();
}
-QPointF SGItemNodeInstance::transformOriginPoint() const
+QPointF QuickItemNodeInstance::transformOriginPoint() const
{
- return sgItem()->transformOriginPoint();
+ return quickItem()->transformOriginPoint();
}
-double SGItemNodeInstance::zValue() const
+double QuickItemNodeInstance::zValue() const
{
- return sgItem()->z();
+ return quickItem()->z();
}
-double SGItemNodeInstance::opacity() const
+double QuickItemNodeInstance::opacity() const
{
- return sgItem()->opacity();
+ return quickItem()->opacity();
}
-QObject *SGItemNodeInstance::parent() const
+QObject *QuickItemNodeInstance::parent() const
{
- if (!sgItem() || !sgItem()->parentItem())
+ if (!quickItem() || !quickItem()->parentItem())
return 0;
- return sgItem()->parentItem();
+ return quickItem()->parentItem();
}
-bool SGItemNodeInstance::equalSGItem(QSGItem *item) const
+bool QuickItemNodeInstance::equalQuickItem(QQuickItem *item) const
{
- return item == sgItem();
+ return item == quickItem();
}
-void SGItemNodeInstance::updateDirtyNodeRecursive(QSGItem *parentItem) const
+void QuickItemNodeInstance::updateDirtyNodeRecursive(QQuickItem *parentItem) const
{
- foreach (QSGItem *childItem, parentItem->childItems()) {
+ foreach (QQuickItem *childItem, parentItem->childItems()) {
if (!nodeInstanceServer()->hasInstanceForObject(childItem))
updateDirtyNodeRecursive(childItem);
}
@@ -193,86 +218,102 @@ void SGItemNodeInstance::updateDirtyNodeRecursive(QSGItem *parentItem) const
DesignerSupport::updateDirtyNode(parentItem);
}
-QImage SGItemNodeInstance::renderImage() const
+QImage QuickItemNodeInstance::renderImage() const
{
- updateDirtyNodeRecursive(sgItem());
+ updateDirtyNodeRecursive(quickItem());
- QRectF boundingRect = boundingRectWithStepChilds(sgItem());
+ QRectF boundingRect = boundingRectWithStepChilds(quickItem());
- QImage renderImage = designerSupport()->renderImageForItem(sgItem(), boundingRect, boundingRect.size().toSize());
+ QImage renderImage = designerSupport()->renderImageForItem(quickItem(), boundingRect, boundingRect.size().toSize());
renderImage = renderImage.convertToFormat(QImage::Format_ARGB32_Premultiplied);
return renderImage;
}
-bool SGItemNodeInstance::isMovable() const
+bool QuickItemNodeInstance::isMovable() const
{
if (isRootNodeInstance())
return false;
- return m_isMovable && sgItem() && sgItem()->parentItem();
+ return m_isMovable && quickItem() && quickItem()->parentItem();
}
-void SGItemNodeInstance::setMovable(bool movable)
+void QuickItemNodeInstance::setMovable(bool movable)
{
m_isMovable = movable;
}
-SGItemNodeInstance::Pointer SGItemNodeInstance::create(QObject *object)
+QuickItemNodeInstance::Pointer QuickItemNodeInstance::create(QObject *object)
{
- QSGItem *sgItem = qobject_cast<QSGItem*>(object);
+ QQuickItem *quickItem = qobject_cast<QQuickItem*>(object);
- Q_ASSERT(sgItem);
+ Q_ASSERT(quickItem);
- Pointer instance(new SGItemNodeInstance(sgItem));
+ Pointer instance(new QuickItemNodeInstance(quickItem));
- instance->setHasContent(anyItemHasContent(sgItem));
- sgItem->setFlag(QSGItem::ItemHasContents, true);
+ instance->setHasContent(anyItemHasContent(quickItem));
+ quickItem->setFlag(QQuickItem::ItemHasContents, true);
- static_cast<QDeclarativeParserStatus*>(sgItem)->classBegin();
+ static_cast<QQmlParserStatus*>(quickItem)->classBegin();
instance->populateResetHashes();
return instance;
}
-void SGItemNodeInstance::initialize(const ObjectNodeInstance::Pointer &objectNodeInstance)
+static void disableTextCursor(QQuickItem *item)
{
+ foreach (QQuickItem *childItem, item->childItems())
+ disableTextCursor(childItem);
+
+ QQuickTextInput *textInput = qobject_cast<QQuickTextInput*>(item);
+ if (textInput)
+ textInput->setCursorVisible(false);
+
+ QQuickTextEdit *textEdit = qobject_cast<QQuickTextEdit*>(item);
+ if (textEdit)
+ textEdit->setCursorVisible(false);
+}
+
+void QuickItemNodeInstance::initialize(const ObjectNodeInstance::Pointer &objectNodeInstance)
+{
+ disableTextCursor(quickItem());
+
if (instanceId() == 0) {
- DesignerSupport::setRootItem(nodeInstanceServer()->sgView(), sgItem());
+ DesignerSupport::setRootItem(nodeInstanceServer()->quickView(), quickItem());
} else {
- sgItem()->setParentItem(qobject_cast<QSGItem*>(nodeInstanceServer()->sgView()->rootObject()));
+ quickItem()->setParentItem(qobject_cast<QQuickItem*>(nodeInstanceServer()->quickView()->rootObject()));
}
if (s_createEffectItem || instanceId() == 0)
- designerSupport()->refFromEffectItem(sgItem());
+ designerSupport()->refFromEffectItem(quickItem());
ObjectNodeInstance::initialize(objectNodeInstance);
- sgItem()->update();
+ quickItem()->update();
}
-bool SGItemNodeInstance::isSGItem() const
+bool QuickItemNodeInstance::isQuickItem() const
{
return true;
}
-QSizeF SGItemNodeInstance::size() const
+QSizeF QuickItemNodeInstance::size() const
{
double width;
- if (DesignerSupport::isValidWidth(sgItem())) {
- width = sgItem()->width();
+ if (DesignerSupport::isValidWidth(quickItem())) {
+ width = quickItem()->width();
} else {
- width = sgItem()->implicitWidth();
+ width = quickItem()->implicitWidth();
}
double height;
- if (DesignerSupport::isValidHeight(sgItem())) {
- height = sgItem()->height();
+ if (DesignerSupport::isValidHeight(quickItem())) {
+ height = quickItem()->height();
} else {
- height = sgItem()->implicitHeight();
+ height = quickItem()->implicitHeight();
}
@@ -284,11 +325,11 @@ static inline bool isRectangleSane(const QRectF &rect)
return rect.isValid() && (rect.width() < 10000) && (rect.height() < 10000);
}
-QRectF SGItemNodeInstance::boundingRectWithStepChilds(QSGItem *parentItem) const
+QRectF QuickItemNodeInstance::boundingRectWithStepChilds(QQuickItem *parentItem) const
{
QRectF boundingRect = parentItem->boundingRect();
- foreach (QSGItem *childItem, parentItem->childItems()) {
+ foreach (QQuickItem *childItem, parentItem->childItems()) {
if (!nodeInstanceServer()->hasInstanceForObject(childItem)) {
QRectF transformedRect = childItem->mapRectToItem(parentItem, boundingRectWithStepChilds(childItem));
if (isRectangleSane(transformedRect))
@@ -299,20 +340,20 @@ QRectF SGItemNodeInstance::boundingRectWithStepChilds(QSGItem *parentItem) const
return boundingRect;
}
-QRectF SGItemNodeInstance::boundingRect() const
+QRectF QuickItemNodeInstance::boundingRect() const
{
- if (sgItem()) {
- if (sgItem()->clip()) {
- return sgItem()->boundingRect();
+ if (quickItem()) {
+ if (quickItem()->clip()) {
+ return quickItem()->boundingRect();
} else {
- return boundingRectWithStepChilds(sgItem());
+ return boundingRectWithStepChilds(quickItem());
}
}
return QRectF();
}
-void SGItemNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+void QuickItemNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
{
if (name == "state")
return; // states are only set by us
@@ -341,48 +382,60 @@ void SGItemNodeInstance::setPropertyVariant(const QString &name, const QVariant
ObjectNodeInstance::setPropertyVariant(name, value);
+ quickItem()->update();
+
refresh();
+
+ if (isInPositioner())
+ parentInstance()->refreshPositioner();
}
-void SGItemNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+void QuickItemNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
{
if (name == "state")
return; // states are only set by us
ObjectNodeInstance::setPropertyBinding(name, expression);
+
+ quickItem()->update();
+
+ refresh();
+
+ if (isInPositioner())
+ parentInstance()->refreshPositioner();
}
-QVariant SGItemNodeInstance::property(const QString &name) const
+QVariant QuickItemNodeInstance::property(const QString &name) const
{
return ObjectNodeInstance::property(name);
}
-void SGItemNodeInstance::resetHorizontal()
+void QuickItemNodeInstance::resetHorizontal()
{
setPropertyVariant("x", m_x);
if (m_width > 0.0) {
setPropertyVariant("width", m_width);
} else {
- setPropertyVariant("width", sgItem()->implicitWidth());
+ setPropertyVariant("width", quickItem()->implicitWidth());
}
}
-void SGItemNodeInstance::resetVertical()
+void QuickItemNodeInstance::resetVertical()
{
setPropertyVariant("y", m_y);
if (m_height > 0.0) {
setPropertyVariant("height", m_height);
} else {
- setPropertyVariant("height", sgItem()->implicitWidth());
+ setPropertyVariant("height", quickItem()->implicitWidth());
}
}
-static void repositioning(QSGItem *item)
+static void repositioning(QQuickItem *item)
{
if (!item)
return;
-// QDeclarativeBasePositioner *positioner = qobject_cast<QDeclarativeBasePositioner*>(item);
+// QQmlBasePositioner *positioner = qobject_cast<QQmlBasePositioner*>(item);
// if (positioner)
// positioner->rePositioning();
@@ -390,41 +443,50 @@ static void repositioning(QSGItem *item)
repositioning(item->parentItem());
}
-void SGItemNodeInstance::refresh()
+void QuickItemNodeInstance::refresh()
{
- repositioning(sgItem());
+ repositioning(quickItem());
}
-void SGItemNodeInstance::doComponentComplete()
+void doComponentCompleteRecursive(QQuickItem *item)
{
- if (sgItem()) {
- if (DesignerSupport::isComponentComplete(sgItem()))
+ if (item) {
+ if (DesignerSupport::isComponentComplete(item))
return;
- static_cast<QDeclarativeParserStatus*>(sgItem())->componentComplete();
+
+ foreach (QQuickItem *childItem, item->childItems())
+ doComponentCompleteRecursive(childItem);
+
+ static_cast<QQmlParserStatus*>(item)->componentComplete();
}
+}
+
+void QuickItemNodeInstance::doComponentComplete()
+{
+ doComponentCompleteRecursive(quickItem());
- sgItem()->update();
+ quickItem()->update();
}
-bool SGItemNodeInstance::isResizable() const
+bool QuickItemNodeInstance::isResizable() const
{
if (isRootNodeInstance())
return false;
- return m_isResizable && sgItem() && sgItem()->parentItem();
+ return m_isResizable && quickItem() && quickItem()->parentItem();
}
-void SGItemNodeInstance::setResizable(bool resizeable)
+void QuickItemNodeInstance::setResizable(bool resizeable)
{
m_isResizable = resizeable;
}
-int SGItemNodeInstance::penWidth() const
+int QuickItemNodeInstance::penWidth() const
{
- return DesignerSupport::borderWidth(sgItem());
+ return DesignerSupport::borderWidth(quickItem());
}
-void SGItemNodeInstance::resetProperty(const QString &name)
+void QuickItemNodeInstance::resetProperty(const QString &name)
{
if (name == "height") {
m_hasHeight = false;
@@ -442,7 +504,7 @@ void SGItemNodeInstance::resetProperty(const QString &name)
if (name == "y")
m_y = 0.0;
- DesignerSupport::resetAnchor(sgItem(), name);
+ DesignerSupport::resetAnchor(quickItem(), name);
if (name == "anchors.fill") {
resetHorizontal();
@@ -467,9 +529,14 @@ void SGItemNodeInstance::resetProperty(const QString &name)
}
ObjectNodeInstance::resetProperty(name);
+
+ quickItem()->update();
+
+ if (isInPositioner())
+ parentInstance()->refreshPositioner();
}
-void SGItemNodeInstance::reparent(const ObjectNodeInstance::Pointer &oldParentInstance, const QString &oldParentProperty, const ObjectNodeInstance::Pointer &newParentInstance, const QString &newParentProperty)
+void QuickItemNodeInstance::reparent(const ObjectNodeInstance::Pointer &oldParentInstance, const QString &oldParentProperty, const ObjectNodeInstance::Pointer &newParentInstance, const QString &newParentProperty)
{
if (oldParentInstance && oldParentInstance->isPositioner()) {
setInPositioner(false);
@@ -492,7 +559,10 @@ void SGItemNodeInstance::reparent(const ObjectNodeInstance::Pointer &oldParentIn
}
refresh();
- DesignerSupport::updateDirtyNode(sgItem());
+ DesignerSupport::updateDirtyNode(quickItem());
+
+ if (parentInstance() && isInPositioner())
+ parentInstance()->refreshPositioner();
}
static bool isValidAnchorName(const QString &name)
@@ -510,17 +580,17 @@ static bool isValidAnchorName(const QString &name)
return anchorNameList.contains(name);
}
-bool SGItemNodeInstance::hasAnchor(const QString &name) const
+bool QuickItemNodeInstance::hasAnchor(const QString &name) const
{
- return DesignerSupport::hasAnchor(sgItem(), name);
+ return DesignerSupport::hasAnchor(quickItem(), name);
}
-QPair<QString, ServerNodeInstance> SGItemNodeInstance::anchor(const QString &name) const
+QPair<QString, ServerNodeInstance> QuickItemNodeInstance::anchor(const QString &name) const
{
- if (!isValidAnchorName(name) || !DesignerSupport::hasAnchor(sgItem(), name))
+ if (!isValidAnchorName(name) || !DesignerSupport::hasAnchor(quickItem(), name))
return ObjectNodeInstance::anchor(name);
- QPair<QString, QObject*> nameObjectPair = DesignerSupport::anchorLineTarget(sgItem(), name, context());
+ QPair<QString, QObject*> nameObjectPair = DesignerSupport::anchorLineTarget(quickItem(), name, context());
QObject *targetObject = nameObjectPair.second;
QString targetName = nameObjectPair.first;
@@ -532,10 +602,10 @@ QPair<QString, ServerNodeInstance> SGItemNodeInstance::anchor(const QString &nam
}
}
-QList<ServerNodeInstance> SGItemNodeInstance::stateInstances() const
+QList<ServerNodeInstance> QuickItemNodeInstance::stateInstances() const
{
QList<ServerNodeInstance> instanceList;
- QList<QObject*> stateList = DesignerSupport::statesForItem(sgItem());
+ QList<QObject*> stateList = DesignerSupport::statesForItem(quickItem());
foreach (QObject *state, stateList)
{
if (state && nodeInstanceServer()->hasInstanceForObject(state))
@@ -545,12 +615,12 @@ QList<ServerNodeInstance> SGItemNodeInstance::stateInstances() const
return instanceList;
}
-bool SGItemNodeInstance::isAnchoredBySibling() const
+bool QuickItemNodeInstance::isAnchoredBySibling() const
{
- if (sgItem()->parentItem()) {
- foreach (QSGItem *siblingItem, sgItem()->parentItem()->childItems()) { // search in siblings for a anchor to this item
+ if (quickItem()->parentItem()) {
+ foreach (QQuickItem *siblingItem, quickItem()->parentItem()->childItems()) { // search in siblings for a anchor to this item
if (siblingItem) {
- if (DesignerSupport::isAnchoredTo(siblingItem, sgItem()))
+ if (DesignerSupport::isAnchoredTo(siblingItem, quickItem()))
return true;
}
}
@@ -559,34 +629,34 @@ bool SGItemNodeInstance::isAnchoredBySibling() const
return false;
}
-bool SGItemNodeInstance::isAnchoredByChildren() const
+bool QuickItemNodeInstance::isAnchoredByChildren() const
{
- if (DesignerSupport::areChildrenAnchoredTo(sgItem(), sgItem())) // search in children for a anchor to this item
+ if (DesignerSupport::areChildrenAnchoredTo(quickItem(), quickItem())) // search in children for a anchor to this item
return true;
return false;
}
-QSGItem *SGItemNodeInstance::sgItem() const
+QQuickItem *QuickItemNodeInstance::quickItem() const
{
if (object() == 0)
return 0;
- Q_ASSERT(qobject_cast<QSGItem*>(object()));
- return static_cast<QSGItem*>(object());
+ Q_ASSERT(qobject_cast<QQuickItem*>(object()));
+ return static_cast<QQuickItem*>(object());
}
-DesignerSupport *SGItemNodeInstance::designerSupport() const
+DesignerSupport *QuickItemNodeInstance::designerSupport() const
{
return qt5NodeInstanceServer()->designerSupport();
}
-Qt5NodeInstanceServer *SGItemNodeInstance::qt5NodeInstanceServer() const
+Qt5NodeInstanceServer *QuickItemNodeInstance::qt5NodeInstanceServer() const
{
return qobject_cast<Qt5NodeInstanceServer*>(nodeInstanceServer());
}
-void SGItemNodeInstance::createEffectItem(bool createEffectItem)
+void QuickItemNodeInstance::createEffectItem(bool createEffectItem)
{
s_createEffectItem = createEffectItem;
}
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/quickitemnodeinstance.h
index d8c99af45e..ad2f4822e2 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/sgitemnodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/quickitemnodeinstance.h
@@ -27,31 +27,31 @@
**
****************************************************************************/
-#ifndef SGITEMNODEINSTANCE_H
-#define SGITEMNODEINSTANCE_H
+#ifndef QuickITEMNODEINSTANCE_H
+#define QuickITEMNODEINSTANCE_H
#include <QtGlobal>
#include "objectnodeinstance.h"
-#include <QSGItem>
+#include <QQuickItem>
#include <designersupport.h>
namespace QmlDesigner {
namespace Internal {
-class SGItemNodeInstance : public ObjectNodeInstance
+class QuickItemNodeInstance : public ObjectNodeInstance
{
public:
- typedef QSharedPointer<SGItemNodeInstance> Pointer;
- typedef QWeakPointer<SGItemNodeInstance> WeakPointer;
+ typedef QSharedPointer<QuickItemNodeInstance> Pointer;
+ typedef QWeakPointer<QuickItemNodeInstance> WeakPointer;
- ~SGItemNodeInstance();
+ ~QuickItemNodeInstance();
static Pointer create(QObject *objectToBeWrapped);
void initialize(const ObjectNodeInstance::Pointer &objectNodeInstance);
- bool isSGItem() const;
+ bool isQuickItem() const;
QRectF boundingRect() const;
QPointF position() const;
@@ -68,12 +68,12 @@ public:
QPointF transformOriginPoint() const;
double zValue() const;
- bool equalSGItem(QSGItem *item) const;
+ bool equalQuickItem(QQuickItem *item) const;
bool hasContent() const;
QList<ServerNodeInstance> childItems() const;
- QList<ServerNodeInstance> childItemsForChild(QSGItem *childItem) const;
+ QList<ServerNodeInstance> childItemsForChild(QQuickItem *childItem) const;
bool isMovable() const;
void setMovable(bool movable);
@@ -109,13 +109,15 @@ public:
static void createEffectItem(bool createEffectItem);
protected:
- SGItemNodeInstance(QSGItem*);
- QSGItem *sgItem() const;
+ QuickItemNodeInstance(QQuickItem*);
+ QQuickItem *quickItem() const;
void resetHorizontal();
void resetVertical();
void refresh();
- QRectF boundingRectWithStepChilds(QSGItem *parentItem) const;
- void updateDirtyNodeRecursive(QSGItem *parentItem) const;
+ QRectF boundingRectWithStepChilds(QQuickItem *parentItem) const;
+ void updateDirtyNodeRecursive(QQuickItem *parentItem) const;
+ static bool anyItemHasContent(QQuickItem *graphicsItem);
+ static bool childItemsHaveContent(QQuickItem *graphicsItem);
private: //variables
bool m_hasHeight;
@@ -133,5 +135,5 @@ private: //variables
} // namespace Internal
} // namespace QmlDesigner
-#endif // SGITEMNODEINSTANCE_H
+#endif // QuickITEMNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.cpp
new file mode 100644
index 0000000000..c249a10121
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.cpp
@@ -0,0 +1,639 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#include "servernodeinstance.h"
+
+#include "objectnodeinstance.h"
+#include "dummynodeinstance.h"
+#include "componentnodeinstance.h"
+#include "qmltransitionnodeinstance.h"
+#include "qmlpropertychangesnodeinstance.h"
+#include "behaviornodeinstance.h"
+#include "qmlstatenodeinstance.h"
+#include "anchorchangesnodeinstance.h"
+#include "positionernodeinstance.h"
+#include "debugoutputcommand.h"
+
+#include "quickitemnodeinstance.h"
+
+#include "nodeinstanceserver.h"
+#include "instancecontainer.h"
+
+#include <QHash>
+#include <QSet>
+#include <QDebug>
+#include <QQuickItem>
+#include <private/qqmlengine_p.h>
+
+#include <QQmlEngine>
+
+/*!
+ \class QmlDesigner::NodeInstance
+ \ingroup CoreInstance
+ \brief NodeInstance is a common handle for the actual object representation of a ModelNode.
+
+ NodeInstance abstracts away the differences e.g. in terms of position and size
+ for QWidget, QGraphicsView, QLayout etc objects. Multiple NodeInstance objects can share
+ the pointer to the same instance object. The actual instance will be deleted when
+ the last NodeInstance object referencing to it is deleted. This can be disabled by
+ setDeleteHeldInstance().
+
+ \see QmlDesigner::NodeInstanceView
+*/
+
+namespace QmlDesigner {
+
+/*!
+\brief Constructor - creates a invalid NodeInstance
+
+
+\see NodeInstanceView
+*/
+ServerNodeInstance::ServerNodeInstance()
+{
+}
+
+/*!
+\brief Destructor
+
+*/
+ServerNodeInstance::~ServerNodeInstance()
+{
+}
+
+/*!
+\brief Constructor - creates a valid NodeInstance
+
+*/
+ServerNodeInstance::ServerNodeInstance(const Internal::ObjectNodeInstance::Pointer &abstractInstance)
+ : m_nodeInstance(abstractInstance)
+{
+
+}
+
+
+ServerNodeInstance::ServerNodeInstance(const ServerNodeInstance &other)
+ : m_nodeInstance(other.m_nodeInstance)
+{
+}
+
+ServerNodeInstance &ServerNodeInstance::operator=(const ServerNodeInstance &other)
+{
+ m_nodeInstance = other.m_nodeInstance;
+ return *this;
+}
+
+/*!
+\brief Paints the NodeInstance with this painter.
+\param painter used QPainter
+*/
+void ServerNodeInstance::paint(QPainter *painter)
+{
+ m_nodeInstance->paint(painter);
+}
+
+QImage ServerNodeInstance::renderImage() const
+{
+ return m_nodeInstance->renderImage();
+}
+
+bool ServerNodeInstance::isRootNodeInstance() const
+{
+ return isValid() && m_nodeInstance->isRootNodeInstance();
+}
+
+bool ServerNodeInstance::isSubclassOf(QObject *object, const QByteArray &superTypeName)
+{
+ if (object == 0)
+ return false;
+
+ const QMetaObject *metaObject = object->metaObject();
+
+ while (metaObject) {
+ QQmlType *qmlType = QQmlMetaType::qmlType(metaObject);
+ if (qmlType && qmlType->qmlTypeName() == superTypeName) // ignore version numbers
+ return true;
+
+ if (metaObject->className() == superTypeName)
+ return true;
+
+ metaObject = metaObject->superClass();
+ }
+
+ return false;
+}
+
+void ServerNodeInstance::setNodeSource(const QString &source)
+{
+ m_nodeInstance->setNodeSource(source);
+}
+
+bool ServerNodeInstance::isSubclassOf(const QString &superTypeName) const
+{
+ return isSubclassOf(internalObject(), superTypeName.toUtf8());
+}
+
+/*!
+\brief Creates a new NodeInstace for this NodeMetaInfo
+
+\param metaInfo MetaInfo for which a Instance should be created
+\param context QQmlContext which should be used
+\returns Internal Pointer of a NodeInstance
+\see NodeMetaInfo
+*/
+Internal::ObjectNodeInstance::Pointer ServerNodeInstance::createInstance(QObject *objectToBeWrapped)
+{
+ Internal::ObjectNodeInstance::Pointer instance;
+
+ if (objectToBeWrapped == 0)
+ instance = Internal::DummyNodeInstance::create();
+ else if (isSubclassOf(objectToBeWrapped, "QQuickBasePositioner"))
+ instance = Internal::PositionerNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QQuickItem"))
+ instance = Internal::QuickItemNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QQmlComponent"))
+ instance = Internal::ComponentNodeInstance::create(objectToBeWrapped);
+ else if (objectToBeWrapped->inherits("QQmlAnchorChanges"))
+ instance = Internal::AnchorChangesNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QQuickPropertyChanges"))
+ instance = Internal::QmlPropertyChangesNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QQuickState"))
+ instance = Internal::QmlStateNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QQuickTransition"))
+ instance = Internal::QmlTransitionNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QQuickBehavior"))
+ instance = Internal::BehaviorNodeInstance::create(objectToBeWrapped);
+ else if (isSubclassOf(objectToBeWrapped, "QObject"))
+ instance = Internal::ObjectNodeInstance::create(objectToBeWrapped);
+ else
+ instance = Internal::DummyNodeInstance::create();
+
+
+ return instance;
+}
+
+ServerNodeInstance ServerNodeInstance::create(NodeInstanceServer *nodeInstanceServer, const InstanceContainer &instanceContainer, ComponentWrap componentWrap)
+{
+ Q_ASSERT(instanceContainer.instanceId() != -1);
+ Q_ASSERT(nodeInstanceServer);
+
+ QObject *object = 0;
+ if (componentWrap == WrapAsComponent) {
+ object = Internal::ObjectNodeInstance::createComponentWrap(instanceContainer.nodeSource(), nodeInstanceServer->imports(), nodeInstanceServer->context());
+ } else if (!instanceContainer.nodeSource().isEmpty()) {
+ object = Internal::ObjectNodeInstance::createCustomParserObject(instanceContainer.nodeSource(), nodeInstanceServer->imports(), nodeInstanceServer->context());
+ if (object == 0)
+ nodeInstanceServer->sendDebugOutput(DebugOutputCommand::ErrorType, QLatin1String("Custom parser object could not be created."));
+ } else if (!instanceContainer.componentPath().isEmpty()) {
+ object = Internal::ObjectNodeInstance::createComponent(instanceContainer.componentPath(), nodeInstanceServer->context());
+ if (object == 0)
+ nodeInstanceServer->sendDebugOutput(DebugOutputCommand::ErrorType, QString("Component with path %1 could not be created.").arg(instanceContainer.componentPath()));
+ } else {
+ object = Internal::ObjectNodeInstance::createPrimitive(instanceContainer.type(), instanceContainer.majorNumber(), instanceContainer.minorNumber(), nodeInstanceServer->context());
+ if (object == 0)
+ nodeInstanceServer->sendDebugOutput(DebugOutputCommand::ErrorType, QLatin1String("Item could not be created."));
+ }
+
+ if (object == 0) {
+ if (instanceContainer.metaType() == InstanceContainer::ItemMetaType) { //If we cannot instanciate the object but we know it has to be an Ttem, we create an Item instead.
+ object = Internal::ObjectNodeInstance::createPrimitive("QtQuick/Item", 2, 0, nodeInstanceServer->context());
+
+ if (object == 0)
+ object = new QQuickItem;
+ } else {
+ object = new QObject;
+ }
+ }
+
+
+ QQmlEnginePrivate::get(nodeInstanceServer->engine())->cache(object->metaObject());
+
+ ServerNodeInstance instance(createInstance(object));
+
+ instance.internalInstance()->setNodeInstanceServer(nodeInstanceServer);
+
+ instance.internalInstance()->setInstanceId(instanceContainer.instanceId());
+
+ instance.internalInstance()->initialize(instance.m_nodeInstance);
+
+ //QObject::connect(instance.internalObject(), SIGNAL(destroyed(QObject*)), nodeInstanceView, SLOT(removeIdFromContext(QObject*)));
+
+ return instance;
+}
+
+void ServerNodeInstance::reparent(const ServerNodeInstance &oldParentInstance, const QString &oldParentProperty, const ServerNodeInstance &newParentInstance, const QString &newParentProperty)
+{
+ m_nodeInstance->reparent(oldParentInstance.m_nodeInstance, oldParentProperty, newParentInstance.m_nodeInstance, newParentProperty);
+}
+
+/*!
+\brief Returns the parent NodeInstance of this NodeInstance.
+
+ If there is not parent than the parent is invalid.
+
+\returns Parent NodeInstance.
+*/
+ServerNodeInstance ServerNodeInstance::parent() const
+{
+ return m_nodeInstance->parentInstance();
+}
+
+bool ServerNodeInstance::hasParent() const
+{
+ return m_nodeInstance->parent();
+}
+
+bool ServerNodeInstance::isValid() const
+{
+ return m_nodeInstance && m_nodeInstance->isValid();
+}
+
+
+/*!
+\brief Returns if the NodeInstance is a QGraphicsItem.
+\returns true if this NodeInstance is a QGraphicsItem
+*/
+bool ServerNodeInstance::equalGraphicsItem(QGraphicsItem *item) const
+{
+ return m_nodeInstance->equalGraphicsItem(item);
+}
+
+/*!
+\brief Returns the bounding rect of the NodeInstance.
+\returns QRectF of the NodeInstance
+*/
+QRectF ServerNodeInstance::boundingRect() const
+{
+ QRectF boundingRect(m_nodeInstance->boundingRect());
+
+//
+// if (modelNode().isValid()) { // TODO implement recursiv stuff
+// if (qFuzzyIsNull(boundingRect.width()))
+// boundingRect.setWidth(nodeState().property("width").value().toDouble());
+//
+// if (qFuzzyIsNull(boundingRect.height()))
+// boundingRect.setHeight(nodeState().property("height").value().toDouble());
+// }
+
+ return boundingRect;
+}
+
+void ServerNodeInstance::setPropertyVariant(const QString &name, const QVariant &value)
+{
+ m_nodeInstance->setPropertyVariant(name, value);
+
+}
+
+void ServerNodeInstance::setPropertyDynamicVariant(const QString &name, const QString &typeName, const QVariant &value)
+{
+ m_nodeInstance->createDynamicProperty(name, typeName);
+ m_nodeInstance->setPropertyVariant(name, value);
+}
+
+void ServerNodeInstance::setPropertyBinding(const QString &name, const QString &expression)
+{
+ m_nodeInstance->setPropertyBinding(name, expression);
+}
+
+void ServerNodeInstance::setPropertyDynamicBinding(const QString &name, const QString &typeName, const QString &expression)
+{
+ m_nodeInstance->createDynamicProperty(name, typeName);
+ m_nodeInstance->setPropertyBinding(name, expression);
+}
+
+void ServerNodeInstance::resetProperty(const QString &name)
+{
+ m_nodeInstance->resetProperty(name);
+}
+
+void ServerNodeInstance::refreshProperty(const QString &name)
+{
+ m_nodeInstance->refreshProperty(name);
+}
+
+void ServerNodeInstance::setId(const QString &id)
+{
+ m_nodeInstance->setId(id);
+}
+
+/*!
+\brief Returns the property value of the property of this NodeInstance.
+\returns QVariant value
+*/
+QVariant ServerNodeInstance::property(const QString &name) const
+{
+ return m_nodeInstance->property(name);
+}
+
+QStringList ServerNodeInstance::propertyNames() const
+{
+ return m_nodeInstance->propertyNames();
+}
+
+bool ServerNodeInstance::hasBindingForProperty(const QString &name, bool *hasChanged) const
+{
+ return m_nodeInstance->hasBindingForProperty(name, hasChanged);
+}
+
+/*!
+\brief Returns the property default value of the property of this NodeInstance.
+\returns QVariant default value which is the reset value to
+*/
+QVariant ServerNodeInstance::defaultValue(const QString &name) const
+{
+ return m_nodeInstance->resetValue(name);
+}
+
+/*!
+\brief Returns the type of the property of this NodeInstance.
+*/
+QString ServerNodeInstance::instanceType(const QString &name) const
+{
+ return m_nodeInstance->instanceType(name);
+}
+
+void ServerNodeInstance::makeInvalid()
+{
+ if (m_nodeInstance)
+ m_nodeInstance->destroy();
+ m_nodeInstance.clear();
+}
+
+bool ServerNodeInstance::hasContent() const
+{
+ return m_nodeInstance->hasContent();
+}
+
+bool ServerNodeInstance::isResizable() const
+{
+ return m_nodeInstance->isResizable();
+}
+
+bool ServerNodeInstance::isMovable() const
+{
+ return m_nodeInstance->isMovable();
+}
+
+bool ServerNodeInstance::isInPositioner() const
+{
+ return m_nodeInstance->isInPositioner();
+}
+
+bool ServerNodeInstance::hasAnchor(const QString &name) const
+{
+ return m_nodeInstance->hasAnchor(name);
+}
+
+int ServerNodeInstance::penWidth() const
+{
+ return m_nodeInstance->penWidth();
+}
+
+bool ServerNodeInstance::isAnchoredBySibling() const
+{
+ return m_nodeInstance->isAnchoredBySibling();
+}
+
+bool ServerNodeInstance::isAnchoredByChildren() const
+{
+ return m_nodeInstance->isAnchoredByChildren();
+}
+
+QPair<QString, ServerNodeInstance> ServerNodeInstance::anchor(const QString &name) const
+{
+ return m_nodeInstance->anchor(name);
+}
+
+QDebug operator<<(QDebug debug, const ServerNodeInstance &instance)
+{
+ if (instance.isValid()) {
+ debug.nospace() << "ServerNodeInstance("
+ << instance.instanceId() << ", "
+ << instance.internalObject() << ", "
+ << instance.id() << ", "
+ << instance.parent() << ')';
+ } else {
+ debug.nospace() << "ServerNodeInstance(invalid)";
+ }
+
+ return debug.space();
+}
+
+uint qHash(const ServerNodeInstance &instance)
+{
+ return ::qHash(instance.instanceId());
+}
+
+bool operator==(const ServerNodeInstance &first, const ServerNodeInstance &second)
+{
+ return first.instanceId() == second.instanceId();
+}
+
+bool ServerNodeInstance::isWrappingThisObject(QObject *object) const
+{
+ return internalObject() && internalObject() == object;
+}
+
+/*!
+\brief Returns the position in parent coordiantes.
+\returns QPointF of the position of the instance.
+*/
+QPointF ServerNodeInstance::position() const
+{
+ return m_nodeInstance->position();
+}
+
+/*!
+\brief Returns the size in local coordiantes.
+\returns QSizeF of the size of the instance.
+*/
+QSizeF ServerNodeInstance::size() const
+{
+ QSizeF instanceSize = m_nodeInstance->size();
+
+ return instanceSize;
+}
+
+QTransform ServerNodeInstance::transform() const
+{
+ return m_nodeInstance->transform();
+}
+
+/*!
+\brief Returns the transform matrix of the instance.
+\returns QTransform of the instance.
+*/
+QTransform ServerNodeInstance::customTransform() const
+{
+ return m_nodeInstance->customTransform();
+}
+
+QTransform ServerNodeInstance::sceneTransform() const
+{
+ return m_nodeInstance->sceneTransform();
+}
+
+double ServerNodeInstance::rotation() const
+{
+ return m_nodeInstance->rotation();
+}
+
+double ServerNodeInstance::scale() const
+{
+ return m_nodeInstance->scale();
+}
+
+QList<QGraphicsTransform *> ServerNodeInstance::transformations() const
+{
+ return m_nodeInstance->transformations();
+}
+
+QPointF ServerNodeInstance::transformOriginPoint() const
+{
+ return m_nodeInstance->transformOriginPoint();
+}
+
+double ServerNodeInstance::zValue() const
+{
+ return m_nodeInstance->zValue();
+}
+
+/*!
+\brief Returns the opacity of the instance.
+\returns 0.0 mean transparent and 1.0 opaque.
+*/
+double ServerNodeInstance::opacity() const
+{
+ return m_nodeInstance->opacity();
+}
+
+
+void ServerNodeInstance::setDeleteHeldInstance(bool deleteInstance)
+{
+ m_nodeInstance->setDeleteHeldInstance(deleteInstance);
+}
+
+
+void ServerNodeInstance::paintUpdate()
+{
+ m_nodeInstance->paintUpdate();
+}
+
+QObject *ServerNodeInstance::internalObject() const
+{
+ if (m_nodeInstance.isNull())
+ return 0;
+
+ return m_nodeInstance->object();
+}
+
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
+QQuickItem *ServerNodeInstance::internalSGItem() const
+{
+ return qobject_cast<QQuickItem*>(internalObject());
+}
+#endif
+
+void ServerNodeInstance::activateState()
+{
+ m_nodeInstance->activateState();
+}
+
+void ServerNodeInstance::deactivateState()
+{
+ m_nodeInstance->deactivateState();
+}
+
+bool ServerNodeInstance::updateStateVariant(const ServerNodeInstance &target, const QString &propertyName, const QVariant &value)
+{
+ return m_nodeInstance->updateStateVariant(target.internalInstance(), propertyName, value);
+}
+
+bool ServerNodeInstance::updateStateBinding(const ServerNodeInstance &target, const QString &propertyName, const QString &expression)
+{
+ return m_nodeInstance->updateStateBinding(target.internalInstance(), propertyName, expression);
+}
+
+QVariant ServerNodeInstance::resetVariant(const QString &propertyName) const
+{
+ return m_nodeInstance->resetValue(propertyName);
+}
+
+bool ServerNodeInstance::resetStateProperty(const ServerNodeInstance &target, const QString &propertyName, const QVariant &resetValue)
+{
+ return m_nodeInstance->resetStateProperty(target.internalInstance(), propertyName, resetValue);
+}
+
+/*!
+ Makes types used in node instances known to the Qml engine. To be called once at initialization time.
+*/
+void ServerNodeInstance::registerQmlTypes()
+{
+// qmlRegisterType<QmlDesigner::Internal::QmlPropertyChangesObject>();
+}
+
+void ServerNodeInstance::doComponentComplete()
+{
+ m_nodeInstance->doComponentComplete();
+}
+
+QList<ServerNodeInstance> ServerNodeInstance::childItems() const
+{
+ return m_nodeInstance->childItems();
+}
+
+QString ServerNodeInstance::id() const
+{
+ return m_nodeInstance->id();
+}
+
+qint32 ServerNodeInstance::instanceId() const
+{
+ if (isValid()) {
+ return m_nodeInstance->instanceId();
+ } else {
+ return -1;
+ }
+}
+
+QObject* ServerNodeInstance::testHandle() const
+{
+ return internalObject();
+}
+
+QList<ServerNodeInstance> ServerNodeInstance::stateInstances() const
+{
+ return m_nodeInstance->stateInstances();
+}
+
+Internal::ObjectNodeInstance::Pointer ServerNodeInstance::internalInstance() const
+{
+ return m_nodeInstance;
+}
+
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.h b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.h
new file mode 100644
index 0000000000..cb5635cb44
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/instances/servernodeinstance.h
@@ -0,0 +1,216 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef SERVERNODEINSTANCE_H
+#define SERVERNODEINSTANCE_H
+
+#include <QSharedPointer>
+#include <QHash>
+#include <QRectF>
+
+#include <nodeinstanceserverinterface.h>
+#include <propertyvaluecontainer.h>
+
+QT_BEGIN_NAMESPACE
+class QPainter;
+class QStyleOptionGraphicsItem;
+class QQmlContext;
+class QGraphicsItem;
+class QGraphicsTransform;
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
+class QQuickItem;
+#endif
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+class NodeInstanceServer;
+class Qt4NodeInstanceServer;
+class Qt4PreviewNodeInstanceServer;
+class Qt5NodeInstanceServer;
+class Qt5PreviewNodeInstanceServer;
+class InstanceContainer;
+
+namespace Internal {
+ class ObjectNodeInstance;
+ class QmlGraphicsItemNodeInstance;
+ class QmlPropertyChangesNodeInstance;
+ class GraphicsObjectNodeInstance;
+ class QmlStateNodeInstance;
+ class QuickItemNodeInstance;
+}
+
+class ServerNodeInstance
+{
+ friend class NodeInstanceServer;
+ friend class Qt4NodeInstanceServer;
+ friend class Qt4PreviewNodeInstanceServer;
+ friend class Qt5NodeInstanceServer;
+ friend class Qt5PreviewNodeInstanceServer;
+ friend class QHash<qint32, ServerNodeInstance>;
+ friend uint qHash(const ServerNodeInstance &instance);
+ friend bool operator==(const ServerNodeInstance &first, const ServerNodeInstance &second);
+ friend QDebug operator<<(QDebug debug, const ServerNodeInstance &instance);
+ friend class NodeMetaInfo;
+ friend class QmlDesigner::Internal::QmlGraphicsItemNodeInstance;
+ friend class QmlDesigner::Internal::QuickItemNodeInstance;
+ friend class QmlDesigner::Internal::GraphicsObjectNodeInstance;
+ friend class QmlDesigner::Internal::ObjectNodeInstance;
+ friend class QmlDesigner::Internal::QmlPropertyChangesNodeInstance;
+ friend class QmlDesigner::Internal::QmlStateNodeInstance;
+
+public:
+ enum ComponentWrap {
+ WrapAsComponent,
+ DoNotWrapAsComponent
+ };
+
+ ServerNodeInstance();
+ ~ServerNodeInstance();
+ ServerNodeInstance(const ServerNodeInstance &other);
+ ServerNodeInstance& operator=(const ServerNodeInstance &other);
+
+ void paint(QPainter *painter);
+ QImage renderImage() const;
+
+ ServerNodeInstance parent() const;
+ bool hasParent() const;
+
+ bool equalGraphicsItem(QGraphicsItem *item) const;
+
+ QRectF boundingRect() const;
+ QPointF position() const;
+ QSizeF size() const;
+ QTransform transform() const;
+ QTransform customTransform() const;
+ QTransform sceneTransform() const;
+ double rotation() const;
+ double scale() const;
+ QList<QGraphicsTransform *> transformations() const;
+ QPointF transformOriginPoint() const;
+ double zValue() const;
+
+ double opacity() const;
+ QVariant property(const QString &name) const;
+ QVariant defaultValue(const QString &name) const;
+ QString instanceType(const QString &name) const;
+ QStringList propertyNames() const;
+
+
+ bool hasBindingForProperty(const QString &name, bool *hasChanged = 0) const;
+
+ bool isValid() const;
+ void makeInvalid();
+ bool hasContent() const;
+ bool isResizable() const;
+ bool isMovable() const;
+ bool isInPositioner() const;
+
+ bool isSubclassOf(const QString &superTypeName) const;
+ bool isRootNodeInstance() const;
+
+ bool isWrappingThisObject(QObject *object) const;
+
+ QVariant resetVariant(const QString &name) const;
+
+ bool hasAnchor(const QString &name) const;
+ bool isAnchoredBySibling() const;
+ bool isAnchoredByChildren() const;
+ QPair<QString, ServerNodeInstance> anchor(const QString &name) const;
+
+ int penWidth() const;
+
+ static void registerQmlTypes();
+
+ void doComponentComplete();
+
+ QList<ServerNodeInstance> childItems() const;
+
+ QString id() const;
+ qint32 instanceId() const;
+
+ QObject* testHandle() const;
+ QSharedPointer<Internal::ObjectNodeInstance> internalInstance() const;
+
+ QList<ServerNodeInstance> stateInstances() const;
+
+private: // functions
+ ServerNodeInstance(const QSharedPointer<Internal::ObjectNodeInstance> &abstractInstance);
+
+ void setPropertyVariant(const QString &name, const QVariant &value);
+ void setPropertyDynamicVariant(const QString &name, const QString &typeName, const QVariant &value);
+
+ void setPropertyBinding(const QString &name, const QString &expression);
+ void setPropertyDynamicBinding(const QString &name, const QString &typeName, const QString &expression);
+
+ void resetProperty(const QString &name);
+ void refreshProperty(const QString &name);
+
+ void activateState();
+ void deactivateState();
+ void refreshState();
+
+ bool updateStateVariant(const ServerNodeInstance &target, const QString &propertyName, const QVariant &value);
+ bool updateStateBinding(const ServerNodeInstance &target, const QString &propertyName, const QString &expression);
+ bool resetStateProperty(const ServerNodeInstance &target, const QString &propertyName, const QVariant &resetValue);
+
+ static ServerNodeInstance create(NodeInstanceServer *nodeInstanceServer, const InstanceContainer &instanceContainer, ComponentWrap componentWrap);
+
+ void setDeleteHeldInstance(bool deleteInstance);
+ void reparent(const ServerNodeInstance &oldParentInstance, const QString &oldParentProperty, const ServerNodeInstance &newParentInstance, const QString &newParentProperty);
+
+
+ void setId(const QString &id);
+
+ static QSharedPointer<Internal::ObjectNodeInstance> createInstance(QObject *objectToBeWrapped);
+
+ void paintUpdate();
+
+ static bool isSubclassOf(QObject *object, const QByteArray &superTypeName);
+
+ void setNodeSource(const QString &source);
+
+
+ QObject *internalObject() const; // should be not used outside of the nodeinstances!!!!
+#if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
+ QQuickItem *internalSGItem() const;
+#endif
+
+private: // variables
+ QSharedPointer<Internal::ObjectNodeInstance> m_nodeInstance;
+};
+
+uint qHash(const ServerNodeInstance &instance);
+bool operator==(const ServerNodeInstance &first, const ServerNodeInstance &second);
+QDebug operator<<(QDebug debug, const ServerNodeInstance &instance);
+}
+
+Q_DECLARE_METATYPE(QmlDesigner::ServerNodeInstance)
+
+#endif // SERVERNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri b/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri
new file mode 100644
index 0000000000..1c561d55e0
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri
@@ -0,0 +1,34 @@
+
+QT += core gui qml quick network v8
+contains (QT_CONFIG, webkit) {
+ QT += webkit
+}
+
+QT += core-private qml-private quick-private gui-private script-private v8-private
+
+DEFINES += QWEAKPOINTER_ENABLE_ARROW
+
+include (../instances/instances.pri)
+include (instances/instances.pri)
+include (../commands/commands.pri)
+include (../container/container.pri)
+include (../interfaces/interfaces.pri)
+
+QT_BREAKPAD_ROOT_PATH = $$(QT_BREAKPAD_ROOT_PATH)
+!isEmpty(QT_BREAKPAD_ROOT_PATH) {
+ include($$QT_BREAKPAD_ROOT_PATH/qtbreakpad.pri)
+}
+
+SOURCES += $$PWD/main.cpp
+RESOURCES += $$PWD/../qmlpuppet.qrc
+DEFINES -= QT_NO_CAST_FROM_ASCII
+
+OTHER_FILES += Info.plist.in
+macx {
+ info.input = Info.plist.in
+ info.output = $$DESTDIR/$${TARGET}.app/Contents/Info.plist
+ QMAKE_SUBSTITUTES += info
+} else {
+ target.path = $$QTC_PREFIX/bin
+ INSTALLS += target
+}
diff --git a/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pro b/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pro
index 6b2b7097ae..48bcfe7d80 100644
--- a/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pro
+++ b/share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pro
@@ -2,40 +2,11 @@ TARGET = qml2puppet
TEMPLATE = app
-QT += core gui declarative network
-
-contains (QT_CONFIG, webkit) {
- QT += webkit
-}
-
-QT += core-private declarative-private gui-private script-private v8-private
-
-DEFINES += QWEAKPOINTER_ENABLE_ARROW
-
-include(../../../../qtcreator.pri)
DESTDIR = $$[QT_INSTALL_BINS]
-include(../../../rpath.pri)
-
-include (instances/instances.pri)
-include (../instances/instances.pri)
-include (../commands/commands.pri)
-include (../container/container.pri)
-include (../interfaces/interfaces.pri)
-QT_BREAKPAD_ROOT_PATH = $$(QT_BREAKPAD_ROOT_PATH)
-!isEmpty(QT_BREAKPAD_ROOT_PATH) {
- include($$QT_BREAKPAD_ROOT_PATH/qtbreakpad.pri)
+build_all:!build_pass {
+ CONFIG -= build_all
+ CONFIG += release
}
-SOURCES += main.cpp
-RESOURCES += ../qmlpuppet.qrc
-
-OTHER_FILES += Info.plist.in
-macx {
- info.input = Info.plist.in
- info.output = $$DESTDIR/$${TARGET}.app/Contents/Info.plist
- QMAKE_SUBSTITUTES += info
-} else {
- target.path = $$QTC_PREFIX/bin
- INSTALLS += target
-}
+include(../../../../../share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri)
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.cpp
new file mode 100644
index 0000000000..d1cbe5ba23
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.cpp
@@ -0,0 +1,84 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+
+
+#include "anchorchangesnodeinstance.h"
+
+namespace QmlDesigner {
+
+namespace Internal {
+
+AnchorChangesNodeInstance::AnchorChangesNodeInstance(QObject *object) :
+ ObjectNodeInstance(object)
+{
+}
+
+AnchorChangesNodeInstance::Pointer AnchorChangesNodeInstance::create(QObject *object)
+{
+ Q_ASSERT(object);
+
+ Pointer instance(new AnchorChangesNodeInstance(object));
+
+ return instance;
+}
+
+void AnchorChangesNodeInstance::setPropertyVariant(const QString &/*name*/, const QVariant &/*value*/)
+{
+}
+
+void AnchorChangesNodeInstance::setPropertyBinding(const QString &/*name*/, const QString &/*expression*/)
+{
+}
+
+QVariant AnchorChangesNodeInstance::property(const QString &/*name*/) const
+{
+ return QVariant();
+}
+
+void AnchorChangesNodeInstance::resetProperty(const QString &/*name*/)
+{
+}
+
+
+void AnchorChangesNodeInstance::reparent(const ServerNodeInstance &/*oldParentInstance*/,
+ const QString &/*oldParentProperty*/,
+ const ServerNodeInstance &/*newParentInstance*/,
+ const QString &/*newParentProperty*/)
+{
+}
+
+QObject *AnchorChangesNodeInstance::changesObject() const
+{
+ return object();
+}
+
+} // namespace Internal
+
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/instances/anchorchangesnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.h
index 595f813cc4..595f813cc4 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/anchorchangesnodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/anchorchangesnodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/instances/behaviornodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.cpp
index f8274db062..f8274db062 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/behaviornodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.h
new file mode 100644
index 0000000000..3d8d7f890d
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/behaviornodeinstance.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef BEHAVIORNODEINSTANCE_H
+#define BEHAVIORNODEINSTANCE_H
+
+#include "objectnodeinstance.h"
+
+namespace QmlDesigner {
+namespace Internal {
+
+class BehaviorNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<BehaviorNodeInstance> Pointer;
+ typedef QWeakPointer<BehaviorNodeInstance> WeakPointer;
+
+ BehaviorNodeInstance(QObject *object);
+
+ static Pointer create(QObject *objectToBeWrapped);
+
+ void setPropertyVariant(const QString &name, const QVariant &value);
+ void setPropertyBinding(const QString &name, const QString &expression);
+
+
+ QVariant property(const QString &name) const;
+ void resetProperty(const QString &name);
+
+private:
+ bool m_isEnabled;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // BEHAVIORNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.cpp
new file mode 100644
index 0000000000..e636519c0d
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.cpp
@@ -0,0 +1,58 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "childrenchangeeventfilter.h"
+
+#include <QEvent>
+
+namespace QmlDesigner {
+namespace Internal {
+
+ChildrenChangeEventFilter::ChildrenChangeEventFilter(QObject *parent)
+ : QObject(parent)
+{
+}
+
+
+bool ChildrenChangeEventFilter::eventFilter(QObject * /*object*/, QEvent *event)
+{
+ switch (event->type()) {
+ case QEvent::ChildAdded:
+ case QEvent::ChildRemoved:
+ {
+ QChildEvent *childEvent = static_cast<QChildEvent*>(event);
+ emit childrenChanged(childEvent->child()); break;
+ }
+ default: break;
+ }
+
+ return false;
+}
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/meegoplugin/meegoplugin.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.h
index 5ed87a3e31..f69eb1dc67 100644
--- a/src/plugins/qmldesigner/meegoplugin/meegoplugin.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/childrenchangeeventfilter.h
@@ -27,28 +27,30 @@
**
****************************************************************************/
-#ifndef MEEGOPLUGIN_H
-#define MEEGOPLUGIN_H
+#ifndef CHILDRENCHANGEEVENTFILTER_H
+#define CHILDRENCHANGEEVENTFILTER_H
-#include <iwidgetplugin.h>
+#include <QObject>
namespace QmlDesigner {
+namespace Internal {
-class MeegoPlugin : public QObject, QmlDesigner::IWidgetPlugin
+class ChildrenChangeEventFilter : public QObject
{
Q_OBJECT
-#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QmlDesignerPlugin" FILE "meegoplugin.json")
-#endif
- Q_INTERFACES(QmlDesigner::IWidgetPlugin)
-
public:
- MeegoPlugin();
+ ChildrenChangeEventFilter(QObject *parent);
+
+
+signals:
+ void childrenChanged(QObject *object);
+
+protected:
+ bool eventFilter(QObject *object, QEvent *event);
- QString metaInfo() const;
- QString pluginName() const;
};
+} // namespace Internal
} // namespace QmlDesigner
-#endif // MEEGOPLUGIN_H
+#endif // CHILDRENCHANGEEVENTFILTER_H
diff --git a/share/qtcreator/qml/qmlpuppet/instances/componentnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/componentnodeinstance.cpp
index f843e0e472..f843e0e472 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/componentnodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/componentnodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/componentnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/componentnodeinstance.h
index c062b41188..c062b41188 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/componentnodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/componentnodeinstance.h
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummycontextobject.cpp
index b7e8816424..9d04a30460 100644
--- a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummycontextobject.cpp
@@ -27,30 +27,26 @@
**
****************************************************************************/
-#include "customstyleplugin.h"
-#include <widgetplugin_helper.h>
-#include <QtPlugin>
+#include "dummycontextobject.h"
namespace QmlDesigner {
-
-CustomStylePlugin::CustomStylePlugin()
+DummyContextObject::DummyContextObject(QObject *parent) :
+ QObject(parent)
{
}
-QString CustomStylePlugin::pluginName() const
+QObject *DummyContextObject::parentDummy() const
{
- return ("CustomStylePlugin");
+ return m_dummyParent.data();
}
-QString CustomStylePlugin::metaInfo() const
+void DummyContextObject::setParentDummy(QObject *parentDummy)
{
- return QString(":/customstyleplugin/customstyle.metainfo");
-}
-
+ if (m_dummyParent.data() != parentDummy) {
+ m_dummyParent = parentDummy;
+ emit parentDummyChanged();
+ }
}
-#if QT_VERSION < 0x050000
-Q_EXPORT_PLUGIN(QmlDesigner::CustomStylePlugin)
-#endif
-
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/instances/dummycontextobject.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummycontextobject.h
index 4041f6705b..4041f6705b 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/dummycontextobject.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummycontextobject.h
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.cpp
new file mode 100644
index 0000000000..216e7f0585
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.cpp
@@ -0,0 +1,108 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+#include "dummynodeinstance.h"
+
+namespace QmlDesigner {
+namespace Internal {
+
+DummyNodeInstance::DummyNodeInstance()
+ : ObjectNodeInstance(new QObject)
+{
+}
+
+DummyNodeInstance::Pointer DummyNodeInstance::create()
+{
+ return Pointer(new DummyNodeInstance);
+}
+
+void DummyNodeInstance::paint(QPainter * /*painter*/)
+{
+}
+
+QRectF DummyNodeInstance::boundingRect() const
+{
+ return QRectF();
+}
+
+QPointF DummyNodeInstance::position() const
+{
+ return QPointF();
+}
+
+QSizeF DummyNodeInstance::size() const
+{
+ return QSizeF();
+}
+
+QTransform DummyNodeInstance::transform() const
+{
+ return QTransform();
+}
+
+double DummyNodeInstance::opacity() const
+{
+ return 0.0;
+}
+
+void DummyNodeInstance::setPropertyVariant(const QString &/*name*/, const QVariant &/*value*/)
+{
+}
+
+void DummyNodeInstance::setPropertyBinding(const QString &/*name*/, const QString &/*expression*/)
+{
+
+}
+
+void DummyNodeInstance::setId(const QString &/*id*/)
+{
+
+}
+
+QVariant DummyNodeInstance::property(const QString &/*name*/) const
+{
+ return QVariant();
+}
+
+QStringList DummyNodeInstance::properties()
+{
+ return QStringList();
+}
+
+QStringList DummyNodeInstance::localProperties()
+{
+ return QStringList();
+}
+
+void DummyNodeInstance::initializePropertyWatcher(const ObjectNodeInstance::Pointer &/*objectNodeInstance*/)
+{
+
+}
+
+} // namespace Internal
+} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.h
new file mode 100644
index 0000000000..846cf5630c
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/dummynodeinstance.h
@@ -0,0 +1,72 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef DUMMYNODEINSTANCE_H
+#define DUMMYNODEINSTANCE_H
+
+#include <QWeakPointer>
+
+#include "objectnodeinstance.h"
+
+namespace QmlDesigner {
+namespace Internal {
+
+class DummyNodeInstance : public ObjectNodeInstance
+{
+public:
+ typedef QSharedPointer<DummyNodeInstance> Pointer;
+ typedef QWeakPointer<DummyNodeInstance> WeakPointer;
+
+ static Pointer create();
+
+ void paint(QPainter *painter);
+
+ QRectF boundingRect() const;
+ QPointF position() const;
+ QSizeF size() const;
+ QTransform transform() const;
+ double opacity() const;
+
+ void setPropertyVariant(const QString &name, const QVariant &value);
+ void setPropertyBinding(const QString &name, const QString &expression);
+ void setId(const QString &id);
+ QVariant property(const QString &name) const;
+ QStringList properties();
+ QStringList localProperties();
+
+ void initializePropertyWatcher(const ObjectNodeInstance::Pointer &objectNodeInstance);
+
+protected:
+ DummyNodeInstance();
+
+};
+
+}
+}
+#endif // DUMMYNODEINSTANCE_H
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/instances.pri b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/instances.pri
index 890faf94ae..ff2d2b91b0 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/instances.pri
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/instances.pri
@@ -8,6 +8,20 @@ HEADERS += $$PWD/qt4previewnodeinstanceserver.h
HEADERS += $$PWD/graphicsobjectnodeinstance.h
HEADERS += $$PWD/positionernodeinstance.h
HEADERS += $$PWD/qmlgraphicsitemnodeinstance.h
+HEADERS += $$PWD/behaviornodeinstance.h
+HEADERS += $$PWD/dummycontextobject.h
+HEADERS += $$PWD/childrenchangeeventfilter.h
+HEADERS += $$PWD/componentnodeinstance.h
+HEADERS += $$PWD/dummynodeinstance.h
+HEADERS += $$PWD/nodeinstancemetaobject.h
+HEADERS += $$PWD/nodeinstanceserver.h
+HEADERS += $$PWD/nodeinstancesignalspy.h
+HEADERS += $$PWD/objectnodeinstance.h
+HEADERS += $$PWD/qmlpropertychangesnodeinstance.h
+HEADERS += $$PWD/qmlstatenodeinstance.h
+HEADERS += $$PWD/qmltransitionnodeinstance.h
+HEADERS += $$PWD/servernodeinstance.h
+HEADERS += $$PWD/anchorchangesnodeinstance.h
SOURCES += $$PWD/qt4nodeinstanceserver.cpp
SOURCES += $$PWD/qt4nodeinstanceclientproxy.cpp
@@ -17,3 +31,17 @@ SOURCES += $$PWD/qt4previewnodeinstanceserver.cpp
SOURCES += $$PWD/graphicsobjectnodeinstance.cpp
SOURCES += $$PWD/qmlgraphicsitemnodeinstance.cpp
SOURCES += $$PWD/positionernodeinstance.cpp
+SOURCES += $$PWD/behaviornodeinstance.cpp
+SOURCES += $$PWD/dummycontextobject.cpp
+SOURCES += $$PWD/childrenchangeeventfilter.cpp
+SOURCES += $$PWD/componentnodeinstance.cpp
+SOURCES += $$PWD/dummynodeinstance.cpp
+SOURCES += $$PWD/nodeinstancemetaobject.cpp
+SOURCES += $$PWD/nodeinstanceserver.cpp
+SOURCES += $$PWD/nodeinstancesignalspy.cpp
+SOURCES += $$PWD/objectnodeinstance.cpp
+SOURCES += $$PWD/qmlpropertychangesnodeinstance.cpp
+SOURCES += $$PWD/qmlstatenodeinstance.cpp
+SOURCES += $$PWD/qmltransitionnodeinstance.cpp
+SOURCES += $$PWD/servernodeinstance.cpp
+SOURCES += $$PWD/anchorchangesnodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancemetaobject.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancemetaobject.cpp
index 2c7f1dd6f6..2c7f1dd6f6 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancemetaobject.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancemetaobject.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancemetaobject.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancemetaobject.h
index 502117f0a0..502117f0a0 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancemetaobject.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancemetaobject.h
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstanceserver.cpp
index 4fabd0bd88..b305af9713 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstanceserver.cpp
@@ -73,6 +73,7 @@
#include "createscenecommand.h"
#include "changenodesourcecommand.h"
#include "tokencommand.h"
+#include "removesharedmemorycommand.h"
#include "dummycontextobject.h"
@@ -342,6 +343,10 @@ void NodeInstanceServer::token(const TokenCommand &/*command*/)
}
+void NodeInstanceServer::removeSharedMemory(const RemoveSharedMemoryCommand &/*command*/)
+{
+}
+
void NodeInstanceServer::setupImports(const QVector<AddImportContainer> &containerVector)
{
foreach (const AddImportContainer &container, containerVector) {
@@ -1022,6 +1027,12 @@ QObject *NodeInstanceServer::dummyContextObject() const
return m_dummyContextObject.data();
}
+void NodeInstanceServer::sendDebugOutput(DebugOutputCommand::Type type, const QString &message)
+{
+ DebugOutputCommand command(message, type);
+ nodeInstanceClient()->debugOutput(command);
+}
+
void NodeInstanceServer::notifyPropertyChange(qint32 instanceid, const QString &propertyName)
{
if (hasInstanceForId(instanceid))
@@ -1055,7 +1066,7 @@ PixmapChangedCommand NodeInstanceServer::createPixmapChangedCommand(const QList<
foreach (const ServerNodeInstance &instance, instanceList) {
if (instance.isValid() && instance.hasContent())
- imageVector.append(ImageContainer(instance.instanceId(), instance.renderImage()));
+ imageVector.append(ImageContainer(instance.instanceId(), instance.renderImage(), instance.instanceId()));
}
return PixmapChangedCommand(imageVector);
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstanceserver.h
index 9c1268ae68..8701c3eb18 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstanceserver.h
@@ -38,6 +38,8 @@
#include <nodeinstanceserverinterface.h>
#include "servernodeinstance.h"
+#include "debugoutputcommand.h"
+
QT_BEGIN_NAMESPACE
class QFileSystemWatcher;
class QDeclarativeView;
@@ -90,6 +92,7 @@ public:
void completeComponent(const CompleteComponentCommand &command);
void changeNodeSource(const ChangeNodeSourceCommand &command);
void token(const TokenCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
ServerNodeInstance instanceForId(qint32 id) const;
bool hasInstanceForId(qint32 id) const;
@@ -124,6 +127,8 @@ public:
virtual QDeclarativeView *declarativeView() const = 0;
virtual QSGView *sgView() const = 0;
+ void sendDebugOutput(DebugOutputCommand::Type type, const QString &message);
+
public slots:
void refreshLocalFileProperty(const QString &path);
void refreshDummyData(const QString &path);
diff --git a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancesignalspy.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.cpp
index d9382c7850..d9382c7850 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/nodeinstancesignalspy.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.h
new file mode 100644
index 0000000000..ae0b94c108
--- /dev/null
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/nodeinstancesignalspy.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef NODEINSTANCESIGNALSPY_H
+#define NODEINSTANCESIGNALSPY_H
+
+#include <QObject>
+#include <QHash>
+#include <QSharedPointer>
+
+namespace QmlDesigner {
+namespace Internal {
+
+class ObjectNodeInstance;
+typedef QSharedPointer<ObjectNodeInstance> ObjectNodeInstancePointer;
+typedef QWeakPointer<ObjectNodeInstance> ObjectNodeInstanceWeakPointer;
+
+class NodeInstanceSignalSpy : public QObject
+{
+public:
+ explicit NodeInstanceSignalSpy();
+
+ void setObjectNodeInstance(const ObjectNodeInstancePointer &nodeInstance);
+
+ virtual int qt_metacall(QMetaObject::Call, int, void **);
+
+protected:
+ void registerObject(QObject *spiedObject, const QString &prefix = QString());
+
+private:
+ int methodeOffset;
+ QHash<int, QString> m_indexPropertyHash;
+ QObjectList m_registeredObjectList;
+ ObjectNodeInstanceWeakPointer m_objectNodeInstance;
+};
+
+} // namespace Internal
+} // namespace QmlDesigner
+
+#endif // NODEINSTANCESIGNALSPY_H
diff --git a/share/qtcreator/qml/qmlpuppet/instances/objectnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/objectnodeinstance.cpp
index 8837b1bc42..47eab50199 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/objectnodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/objectnodeinstance.cpp
@@ -189,7 +189,7 @@ bool ObjectNodeInstance::isPositioner() const
return false;
}
-bool ObjectNodeInstance::isSGItem() const
+bool ObjectNodeInstance::isQuickItem() const
{
return false;
}
diff --git a/share/qtcreator/qml/qmlpuppet/instances/objectnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/objectnodeinstance.h
index 328bc25dca..3e022089fa 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/objectnodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/objectnodeinstance.h
@@ -99,7 +99,7 @@ public:
virtual bool isGraphicsObject() const;
virtual bool isTransition() const;
virtual bool isPositioner() const;
- virtual bool isSGItem() const;
+ virtual bool isQuickItem() const;
virtual bool equalGraphicsItem(QGraphicsItem *item) const;
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/positionernodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/positionernodeinstance.cpp
index 3795754cd8..daf675b193 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/positionernodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/positionernodeinstance.cpp
@@ -65,7 +65,7 @@ void PositionerNodeInstance::setPropertyBinding(const QString &name, const QStri
}
PositionerNodeInstance::Pointer PositionerNodeInstance::create(QObject *object)
-{
+{
QDeclarativeBasePositioner *positioner = qobject_cast<QDeclarativeBasePositioner*>(object);
Q_ASSERT(positioner);
diff --git a/share/qtcreator/qml/qmlpuppet/instances/qmlpropertychangesnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlpropertychangesnodeinstance.cpp
index 28227b8e8e..28227b8e8e 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/qmlpropertychangesnodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlpropertychangesnodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/qmlpropertychangesnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlpropertychangesnodeinstance.h
index 6f1b1c417e..6f1b1c417e 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/qmlpropertychangesnodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlpropertychangesnodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/instances/qmlstatenodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlstatenodeinstance.cpp
index d9ffb55590..d9ffb55590 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/qmlstatenodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlstatenodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/qmlstatenodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlstatenodeinstance.h
index d37d5b993c..d37d5b993c 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/qmlstatenodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmlstatenodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/instances/qmltransitionnodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmltransitionnodeinstance.cpp
index 79e2aa6b9b..79e2aa6b9b 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/qmltransitionnodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmltransitionnodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/qmltransitionnodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmltransitionnodeinstance.h
index fc14f14321..fc14f14321 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/qmltransitionnodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qmltransitionnodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.cpp
index 9f8a9a4ee4..ecb4204989 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.cpp
@@ -73,8 +73,7 @@
#include "componentcompletedcommand.h"
#include "createscenecommand.h"
#include "tokencommand.h"
-
-
+#include "removesharedmemorycommand.h"
#include "dummycontextobject.h"
namespace QmlDesigner {
@@ -98,6 +97,12 @@ void Qt4InformationNodeInstanceServer::token(const TokenCommand &command)
startRenderTimer();
}
+void Qt4InformationNodeInstanceServer::removeSharedMemory(const RemoveSharedMemoryCommand &command)
+{
+ if (command.typeName() == "Values")
+ ValuesChangedCommand::removeSharedMemorys(command.keyNumbers());
+}
+
void Qt4InformationNodeInstanceServer::collectItemChangesAndSendChangeCommands()
{
static bool inFunction = false;
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.h
index b578be77d1..864dba0ec6 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4informationnodeinstanceserver.h
@@ -46,6 +46,7 @@ public:
void createScene(const CreateSceneCommand &command);
void completeComponent(const CompleteComponentCommand &command);
void token(const TokenCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
protected:
void collectItemChangesAndSendChangeCommands();
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.cpp
index 018b353ef9..0c6fc90275 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.cpp
@@ -32,6 +32,7 @@
#include "nodeinstanceclientinterface.h"
#include "statepreviewimagechangedcommand.h"
#include "createscenecommand.h"
+#include "removesharedmemorycommand.h"
#include <QPainter>
#include <QDeclarativeView>
@@ -69,11 +70,11 @@ void Qt4PreviewNodeInstanceServer::collectItemChangesAndSendChangeCommands()
if (!inFunction && nodeInstanceClient()->bytesToWrite() < 10000) {
inFunction = true;
QVector<ImageContainer> imageContainerVector;
- imageContainerVector.append(ImageContainer(0, renderPreviewImage()));
+ imageContainerVector.append(ImageContainer(0, renderPreviewImage(), -1));
foreach (ServerNodeInstance instance, rootNodeInstance().stateInstances()) {
instance.activateState();
- imageContainerVector.append(ImageContainer(instance.instanceId(), renderPreviewImage()));
+ imageContainerVector.append(ImageContainer(instance.instanceId(), renderPreviewImage(), instance.instanceId()));
instance.deactivateState();
}
@@ -89,6 +90,12 @@ void Qt4PreviewNodeInstanceServer::changeState(const ChangeStateCommand &/*comma
}
+void Qt4PreviewNodeInstanceServer::removeSharedMemory(const RemoveSharedMemoryCommand &command)
+{
+ if (command.typeName() == "Image")
+ ImageContainer::removeSharedMemorys(command.keyNumbers());
+}
+
QImage Qt4PreviewNodeInstanceServer::renderPreviewImage()
{
QSize size = rootNodeInstance().boundingRect().size().toSize();
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.h
index cb46187a80..9737370ed6 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4previewnodeinstanceserver.h
@@ -42,6 +42,7 @@ public:
void createScene(const CreateSceneCommand &command);
void changeState(const ChangeStateCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
QImage renderPreviewImage();
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.cpp
index 7fc261a0e7..26e2e8c171 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.cpp
@@ -72,6 +72,7 @@
#include "completecomponentcommand.h"
#include "componentcompletedcommand.h"
#include "createscenecommand.h"
+#include "removesharedmemorycommand.h"
#include "dummycontextobject.h"
@@ -193,4 +194,10 @@ void Qt4RenderNodeInstanceServer::changeState(const ChangeStateCommand &command)
QGraphicsItemPrivate::get(item)->notifyBoundingRectChanged = 1;
}
}
+
+void Qt4RenderNodeInstanceServer::removeSharedMemory(const RemoveSharedMemoryCommand &command)
+{
+ if (command.typeName() == "Image")
+ ImageContainer::removeSharedMemorys(command.keyNumbers());
+}
} // namespace QmlDesigner
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.h
index 122204bf72..c8983e2c42 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/qt4rendernodeinstanceserver.h
@@ -44,6 +44,7 @@ public:
void clearScene(const ClearSceneCommand &command);
void completeComponent(const CompleteComponentCommand &command);
void changeState(const ChangeStateCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
protected:
void collectItemChangesAndSendChangeCommands();
diff --git a/share/qtcreator/qml/qmlpuppet/instances/servernodeinstance.cpp b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/servernodeinstance.cpp
index 3120179c0d..3120179c0d 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/servernodeinstance.cpp
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/servernodeinstance.cpp
diff --git a/share/qtcreator/qml/qmlpuppet/instances/servernodeinstance.h b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/servernodeinstance.h
index 20a1880554..20a1880554 100644
--- a/share/qtcreator/qml/qmlpuppet/instances/servernodeinstance.h
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/instances/servernodeinstance.h
diff --git a/share/qtcreator/qml/qmlpuppet/qmlpuppet/qmlpuppet.pri b/share/qtcreator/qml/qmlpuppet/qmlpuppet/qmlpuppet.pri
index 8f76d142ce..1155dbf423 100644
--- a/share/qtcreator/qml/qmlpuppet/qmlpuppet/qmlpuppet.pri
+++ b/share/qtcreator/qml/qmlpuppet/qmlpuppet/qmlpuppet.pri
@@ -11,14 +11,15 @@ greaterThan(QT_MAJOR_VERSION, 4) {
DEFINES += QWEAKPOINTER_ENABLE_ARROW
-include (instances/instances.pri)
include (../instances/instances.pri)
+include (instances/instances.pri)
include (../commands/commands.pri)
include (../container/container.pri)
include (../interfaces/interfaces.pri)
SOURCES += $$PWD/main.cpp
RESOURCES += $$PWD/../qmlpuppet.qrc
+DEFINES -= QT_NO_CAST_FROM_ASCII
OTHER_FILES += Info.plist.in
macx {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/AlignmentHorizontalButtons.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AlignmentHorizontalButtons.qml
index 23183419a8..23183419a8 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/AlignmentHorizontalButtons.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AlignmentHorizontalButtons.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/AlignmentVerticalButtons.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AlignmentVerticalButtons.qml
index e93b91143d..e93b91143d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/AlignmentVerticalButtons.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AlignmentVerticalButtons.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/AnchorBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AnchorBox.qml
index 61a6101048..61a6101048 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/AnchorBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AnchorBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/AnchorButtons.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AnchorButtons.qml
index 8278f05889..8278f05889 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/AnchorButtons.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/AnchorButtons.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/CheckBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/CheckBox.qml
index 01d58e0f7a..14fdbc7ae5 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/CheckBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/CheckBox.qml
@@ -40,6 +40,8 @@ QWidget { //This is a special checkBox that does color coding for states
property alias checkable: localCheckBox.checkable
property alias text: localLabel.text
+ property alias checked: localCheckBox.checked
+
onBaseStateFlagChanged: {
evaluate();
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorGroupBox.qml
index f814500ad8..2b6b8ef890 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorGroupBox.qml
@@ -172,7 +172,7 @@ QExtGroupBox {
layout: HorizontalLayout {
spacing: 6
- LineEdit {
+ ColorLineEdit {
inputMask: "\\#HHHHHH"
visible: gradientEditing == false
backendValue: colorGroupBox.backendColor
@@ -185,7 +185,12 @@ QExtGroupBox {
id: lineEditWidget;
QLineEdit {
y: 2
- text: color
+ property color colorG: color
+ onColorGChanged: {
+ text = convertColorToString(color);
+ }
+
+ text: "#000000";
width: lineEditWidget.width
height: lineEditWidget.height
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorLabel.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLabel.qml
index 6edd681dd1..6edd681dd1 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorLabel.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLabel.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLineEdit.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLineEdit.qml
new file mode 100644
index 0000000000..26ff5761d8
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorLineEdit.qml
@@ -0,0 +1,161 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 1.0
+import Bauhaus 1.0
+
+QWidget {
+ id: lineEdit
+
+ function escapeString(string) {
+ var str = string;
+ str = str.replace(/\\/g, "\\\\");
+ str.replace(/\"/g, "\\\"");
+ str = str.replace(/\t/g, "\\t");
+ str = str.replace(/\r/g, "\\r");
+ str = str.replace(/\n/g, '\\n');
+ return str;
+ }
+
+ property variant backendValue
+ property alias enabled: lineEdit.enabled
+ property variant baseStateFlag
+ property alias text: lineEditWidget.text
+ property alias readOnly: lineEditWidget.readOnly
+ property alias translation: trCheckbox.visible
+ property alias inputMask: lineEditWidget.inputMask
+
+ minimumHeight: 24;
+
+ onBaseStateFlagChanged: {
+ evaluate();
+ }
+
+ property variant isEnabled: lineEdit.enabled
+ onIsEnabledChanged: {
+ evaluate();
+ }
+
+
+ property bool isInModel: backendValue.isInModel;
+ onIsInModelChanged: {
+ evaluate();
+ }
+ property bool isInSubState: backendValue.isInSubState;
+ onIsInSubStateChanged: {
+ evaluate();
+ }
+
+ function evaluate() {
+ if (!enabled) {
+ lineEditWidget.setStyleSheet("color: "+scheme.disabledColor);
+ } else {
+ if (baseStateFlag) {
+ if (backendValue != null && backendValue.isInModel)
+ lineEditWidget.setStyleSheet("color: "+scheme.changedBaseColor);
+ else
+ lineEditWidget.setStyleSheet("color: "+scheme.defaultColor);
+ } else {
+ if (backendValue != null && backendValue.isInSubState)
+ lineEditWidget.setStyleSheet("color: "+scheme.changedStateColor);
+ else
+ lineEditWidget.setStyleSheet("color: "+scheme.defaultColor);
+ }
+ }
+ }
+
+ ColorScheme { id:scheme; }
+
+ QLineEdit {
+ y: 2
+ id: lineEditWidget
+ styleSheet: "QLineEdit { padding-left: 32; }"
+ width: lineEdit.width
+ height: lineEdit.height
+ toolTip: backendValue.isBound ? backendValue.expression : ""
+
+ property string valueFromBackend: (backendValue === undefined || backendValue.value === undefined) ? "" : backendValue.valueToString;
+
+ onValueFromBackendChanged: {
+ if (backendValue.value === undefined)
+ return;
+ text = backendValue.valueToString;
+ }
+
+ onEditingFinished: {
+ if (backendValue.isTranslated) {
+ backendValue.expression = "qsTr(\"" + escapeString(text) + "\")"
+ } else {
+ backendValue.value = text
+ }
+ evaluate();
+ }
+
+ onFocusChanged: {
+ if (focus)
+ backendValue.lock();
+ else
+ backendValue.unlock();
+ }
+
+
+ }
+ ExtendedFunctionButton {
+ backendValue: lineEdit.backendValue
+ y: 6
+ x: 0
+ visible: lineEdit.enabled
+ }
+ QCheckBox {
+ id: trCheckbox
+ y: 2
+ styleSheetFile: "checkbox_tr.css";
+ toolTip: qsTr("Translate this string")
+ x: lineEditWidget.width - 22
+ height: lineEdit.height - 2;
+ width: 24
+ visible: false
+ checked: backendValue.isTranslated
+ onToggled: {
+ if (trCheckbox.checked) {
+ backendValue.expression = "qsTr(\"" + escapeString(lineEditWidget.text) + "\")"
+ } else {
+ backendValue.value = lineEditWidget.text
+ }
+ evaluate();
+ }
+
+ onVisibleChanged: {
+ if (trCheckbox.visible) {
+ trCheckbox.raise();
+ lineEditWidget.styleSheet = "QLineEdit { padding-left: 32; padding-right: 62;}"
+ }
+ }
+ }
+}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorScheme.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorScheme.qml
index e445aead93..e445aead93 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorScheme.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorScheme.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorTypeButtons.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorTypeButtons.qml
index 7dfdcf8bad..7dfdcf8bad 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ColorTypeButtons.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ColorTypeButtons.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ComboBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ComboBox.qml
index dd5c1633ab..dd5c1633ab 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ComboBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ComboBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/DoubleSpinBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/DoubleSpinBox.qml
index feb58b6023..feb58b6023 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/DoubleSpinBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/DoubleSpinBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/DoubleSpinBoxAlternate.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/DoubleSpinBoxAlternate.qml
index 7f6d69f27d..7f6d69f27d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/DoubleSpinBoxAlternate.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/DoubleSpinBoxAlternate.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExpressionEditor.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExpressionEditor.qml
index 55df6a09ca..55df6a09ca 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExpressionEditor.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExpressionEditor.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Extended.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Extended.qml
index 5cd273fb82..5cd273fb82 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Extended.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Extended.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedFunctionButton.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedFunctionButton.qml
index 46cbfb22b4..46cbfb22b4 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedFunctionButton.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedFunctionButton.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedPane.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedPane.qml
index 650c25b526..650c25b526 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedPane.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedPane.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedSwitches.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedSwitches.qml
index b011f1f4b8..b011f1f4b8 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ExtendedSwitches.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ExtendedSwitches.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlagedButton.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FlagedButton.qml
index 66f3406441..66f3406441 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlagedButton.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FlagedButton.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FontComboBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontComboBox.qml
index e8f4591a86..e8f4591a86 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FontComboBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontComboBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FontGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontGroupBox.qml
index 81697bdf0c..3ecd6aaf64 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FontGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontGroupBox.qml
@@ -34,6 +34,16 @@ GroupBox {
id: fontGroupBox
caption: qsTr("Font")
property variant showStyle: false
+
+ property variant fontFamily: backendValues.font_family
+ property variant pointSize: backendValues.font_pointSize
+ property variant pixelSize: backendValues.font_pixelSize
+
+ property variant boldStyle: backendValues.font_bold
+ property variant italicStyle: backendValues.font_italic
+ property variant underlineStyle: backendValues.font_underline
+ property variant strikeoutStyle: backendValues.font_strikeout
+
layout: VerticalLayout {
QWidget {
@@ -43,7 +53,7 @@ GroupBox {
}
FontComboBox {
- backendValue: backendValues.font_family
+ backendValue: fontFamily
baseStateFlag: isBaseState
}
}
@@ -58,7 +68,7 @@ GroupBox {
onSelectionFlagChanged: {
isSetup = true;
sizeType.currentText = "points";
- if (backendValues.font_pixelSize.isInModel)
+ if (pixelSize.isInModel)
sizeType.currentText = "pixels";
isSetup = false;
}
@@ -70,14 +80,14 @@ GroupBox {
minimum: 0
maximum: 400
visible: !sizeWidget.pixelSize
- backendValue: backendValues.font_pointSize
+ backendValue: pointSize
baseStateFlag: isBaseState;
}
SpinBox {
minimum: 0
maximum: 400
visible: sizeWidget.pixelSize
- backendValue: backendValues.font_pixelSize
+ backendValue: pixelSize
baseStateFlag: isBaseState;
}
QComboBox {
@@ -88,11 +98,11 @@ GroupBox {
if (sizeWidget.isSetup)
return;
if (currentText == "pixels") {
- backendValues.font_pointSize.resetValue();
- backendValues.font_pixelSize.value = 8;
+ pointSize.resetValue();
+ pixelSize.value = 8;
} else {
- backendValues.font_pixelSize.resetValue();
- }
+ pixelSize.resetValue();
+ }
}
}
}
@@ -102,7 +112,12 @@ GroupBox {
Label {
text: qsTr("Font style")
}
- FontStyleButtons {}
+ FontStyleButtons {
+ bold: boldStyle
+ italic: italicStyle
+ underline: underlineStyle
+ strikeout: strikeoutStyle
+ }
}
}
QWidget {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FontStyleButtons.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontStyleButtons.qml
index a589f24177..eec22125ee 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FontStyleButtons.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/FontStyleButtons.qml
@@ -34,6 +34,12 @@ QGroupBox {
id: fontStyleButtons
property int buttonWidth: 46
+
+ property variant bold: backendValues.font_bold
+ property variant italic: backendValues.font_italic
+ property variant underline: backendValues.font_underline
+ property variant strikeout: backendValues.font_strikeout
+
layout: HorizontalLayout {
QWidget {
@@ -48,17 +54,17 @@ QGroupBox {
fixedHeight: 28
height: fixedHeight
styleSheetFile: "styledbuttonleft.css";
- checked: backendValues.font_bold.value;
- backendValue: backendValues.font_bold;
+ checked: bold.value;
+ backendValue: bold;
iconFromFile: flagActive ? "images/bold-h-icon.png" : "images/bold-icon.png"
onClicked: {
- backendValues.font_bold.value = checked;
+ bold.value = checked;
}
ExtendedFunctionButton {
- backendValue: backendValues.font_bold;
+ backendValue: bold
y: 7
x: 2
}
@@ -75,15 +81,15 @@ QGroupBox {
iconFromFile: flagActive ? "images/italic-h-icon.png" : "images/italic-icon.png"
styleSheetFile: "styledbuttonmiddle.css";
- checked: backendValues.font_italic.value;
- backendValue: backendValues.font_italic;
+ checked: italic.value;
+ backendValue: italic;
onClicked: {
- backendValues.font_italic.value = checked;
+ italic.value = checked;
}
ExtendedFunctionButton {
- backendValue: backendValues.font_italic
+ backendValue: italic
y: 7
x: 2
}
@@ -100,15 +106,15 @@ QGroupBox {
iconFromFile: flagActive ? "images/underline-h-icon.png" : "images/underline-icon.png"
styleSheetFile: "styledbuttonmiddle.css";
- checked: backendValues.font_underline.value;
- backendValue: backendValues.font_underline;
+ checked: underline.value;
+ backendValue: underline;
onClicked: {
- backendValues.font_underline.value = checked;
+ underline.value = checked;
}
ExtendedFunctionButton {
- backendValue: backendValues.font_underline;
+ backendValue: underline;
y: 7
x: 2
}
@@ -125,15 +131,15 @@ QGroupBox {
iconFromFile: flagActive ? "images/strikeout-h-icon.png" : "images/strikeout-icon.png"
styleSheetFile: "styledbuttonright.css";
- checked: backendValues.font_strikeout.value;
- backendValue: backendValues.font_strikeout;
+ checked: strikeout.value;
+ backendValue: strikeout;
onClicked: {
- backendValues.font_strikeout.value = checked;
+ strikeout.value = checked;
}
ExtendedFunctionButton {
- backendValue: backendValues.font_strikeout;
+ backendValue: strikeout;
y: 7
x: 2
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Geometry.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Geometry.qml
index 693a5b9459..693a5b9459 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Geometry.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Geometry.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/GroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/GroupBox.qml
index cbfc54181d..cbfc54181d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/GroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/GroupBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/GroupBoxOption.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/GroupBoxOption.qml
index 897c99595f..897c99595f 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/GroupBoxOption.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/GroupBoxOption.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/HorizontalLayout.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/HorizontalLayout.qml
index 711b4a65e9..711b4a65e9 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/HorizontalLayout.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/HorizontalLayout.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/HorizontalWhiteLine.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/HorizontalWhiteLine.qml
index 79a4e7f954..79a4e7f954 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/HorizontalWhiteLine.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/HorizontalWhiteLine.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/IntEditor.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/IntEditor.qml
index ba42f62061..1ba64c796d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/IntEditor.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/IntEditor.qml
@@ -44,6 +44,8 @@ QWidget {
property bool slider: true
property alias alignment: label.alignment
+ property bool editorEnabled: true
+
layout: HorizontalLayout {
Label {
id: label
@@ -53,6 +55,7 @@ QWidget {
}
SpinBox {
+ enabled: editorEnabled
backendValue: (intEditor.backendValue === undefined ||
intEditor.backendValue === null)
? null : intEditor.backendValue;
@@ -73,6 +76,7 @@ QWidget {
id: sliderWidget
QSlider {
id: intSlider
+ enabled: editorEnabled
y: sliderWidget.height / 2 - 12
width: sliderWidget.width
height: 24
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Label.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Label.qml
index 7c96e97d65..7c96e97d65 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Label.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Label.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Layout.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Layout.qml
index efc1259586..efc1259586 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Layout.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Layout.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/LayoutPane.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/LayoutPane.qml
index 0132dd5213..0132dd5213 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/LayoutPane.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/LayoutPane.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/LineEdit.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/LineEdit.qml
index 3463e73340..3463e73340 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/LineEdit.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/LineEdit.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Modifiers.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Modifiers.qml
index edb981703c..edb981703c 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Modifiers.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Modifiers.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/PlaceHolder.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/PlaceHolder.qml
index f759bf4715..f759bf4715 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/PlaceHolder.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/PlaceHolder.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/PropertyFrame.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/PropertyFrame.qml
index b7f4d734df..b7f4d734df 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/PropertyFrame.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/PropertyFrame.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ScrollArea.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ScrollArea.qml
index 1289155a2d..1289155a2d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ScrollArea.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/ScrollArea.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/SliderWidget.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/SliderWidget.qml
index c56423e1d0..c56423e1d0 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/SliderWidget.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/SliderWidget.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/SpinBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/SpinBox.qml
index 869145bf96..869145bf96 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/SpinBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/SpinBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/StandardTextColorGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/StandardTextColorGroupBox.qml
index ca83a90824..ca83a90824 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/StandardTextColorGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/StandardTextColorGroupBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/StandardTextGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/StandardTextGroupBox.qml
index 17d2611bfd..17d2611bfd 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/StandardTextGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/StandardTextGroupBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Switches.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Switches.qml
index 666de7e84d..666de7e84d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Switches.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Switches.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextEditor.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/TextEditor.qml
index 925d4fc6ba..925d4fc6ba 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextEditor.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/TextEditor.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextInputGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/TextInputGroupBox.qml
index 14aa48d858..14aa48d858 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextInputGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/TextInputGroupBox.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Transformation.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Transformation.qml
index e9cdaf5a49..e9cdaf5a49 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Transformation.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Transformation.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Type.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Type.qml
index 0395191a29..0395191a29 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Type.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Type.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/UrlEdit.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/UrlEdit.qml
new file mode 100644
index 0000000000..d1920cdd72
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/UrlEdit.qml
@@ -0,0 +1,57 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 1.0
+import Bauhaus 1.0
+
+QWidget { //This is a special spinBox that does color coding for states
+
+ id: urlEdit
+ property bool enabled: true
+ property variant backendValue;
+ property variant baseStateFlag;
+ property alias filter: fileWidget.filter
+ property alias showComboBox: fileWidget.showComboBox
+
+ minimumHeight: 22;
+
+ layout: HorizontalLayout {
+ spacing: 4
+ FileWidget {
+ id: fileWidget
+ enabled: (isBaseState || backendValues.id.value != "") && urlEdit.enabled
+ fileName: backendValue.value;
+ onFileNameChanged: {
+ backendValue.value = fileName;
+ }
+ itemNode: anchorBackend.itemNode
+ showComboBox: false
+ }
+ }
+}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/VerticalLayout.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/VerticalLayout.qml
index 93e667d57e..93e667d57e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/VerticalLayout.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/VerticalLayout.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/Visibility.qml b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Visibility.qml
index dcb4053880..dcb4053880 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/Visibility.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/Visibility.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorbottom.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorbottom.css
index 98ad512dc9..bdb2e7b1ef 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorbottom.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorbottom.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/anchor-bottom-normal.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-bottom-pressed.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-bottom-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorbox.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorbox.css
index d93895b1c8..389072879c 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorbox.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorbox.css
@@ -4,9 +4,9 @@ QPushButton::checked
border-radius: 4px;
border-image: none;
background-color: #909090;
-}
+}
-QPushButton:pressed
+QPushButton:pressed
{
border: 2px solid #000000;
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorfill.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorfill.css
index c382641d03..53a80982ef 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorfill.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorfill.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/anchor-fill-normal.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-fill-pressed.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-fill-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorhorizontal.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorhorizontal.css
index 28be04e0ea..8b985609d2 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorhorizontal.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorhorizontal.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/anchor-horizontal-normal.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-horizontal-pressed.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-horizontal-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorleft.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorleft.css
index 53c9604c0a..a5eebcc683 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorleft.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorleft.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/anchor-left-normal.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-left-pressed.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-left-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorright.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorright.css
index ee1690e23c..a30a01b0cb 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorright.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorright.css
@@ -1,11 +1,11 @@
QPushButton {
- border-image: url(:/qmldesigner/images/anchor-right-normal.png);
+ border-image: url(:/qmldesigner/images/anchor-right-normal.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-right-pressed.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-right-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorspacer.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorspacer.css
index 22cfdf8598..e88ce664f3 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorspacer.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorspacer.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/anchor-spacer.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-spacer.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-spacer.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchortop.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchortop.css
index 2310144c1e..68a9e3e4bc 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchortop.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchortop.css
@@ -1,11 +1,11 @@
QPushButton {
- border-image: url(:/qmldesigner/images/anchor-top-normal.png);
+ border-image: url(:/qmldesigner/images/anchor-top-normal.png);
}
-
+
QPushButton:pressed {
- border-image: url(:/qmldesigner/images/anchor-top-pressed.png);
+ border-image: url(:/qmldesigner/images/anchor-top-pressed.png);
}
-
+
QPushButton:checked {
- border-image: url(:/qmldesigner/images/anchor-top-pressed.png);
+ border-image: url(:/qmldesigner/images/anchor-top-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorvertical.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorvertical.css
index 578030e065..617e091981 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/anchorvertical.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/anchorvertical.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/anchor-vertical-normal.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/anchor-vertical-pressed.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/anchor-vertical-pressed.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/applybutton.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/applybutton.css
index d7680978b3..dadd1baece 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/applybutton.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/applybutton.css
@@ -2,7 +2,7 @@ QPushButton {
border-image: url(:/qmldesigner/images/apply.png) 3;
border-width: 3;
}
-
+
QPushButton:hover {
border-image: url(:/qmldesigner/images/applybright.png) 3;
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/aspectlock.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/aspectlock.css
index f47f0e50ca..1368648c13 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/aspectlock.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/aspectlock.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/aspectlockoff.png);
}
-
+
QPushButton:pressed {
- border-image: url(:/qmldesigner/images/aspectlockset.png);
+ border-image: url(:/qmldesigner/images/aspectlockset.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/aspectlockset.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/cancelbutton.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/cancelbutton.css
index 2078aa0d34..55e50d74cd 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/cancelbutton.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/cancelbutton.css
@@ -1,8 +1,8 @@
QPushButton {
border-image: url(:/qmldesigner/images/cancel.png) 3;
- border-width: 3;
+ border-width: 3;
}
-
+
QPushButton:hover {
border-image: url(:/qmldesigner/images/cancelbright.png) 3;
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/checkbox_tr.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/checkbox_tr.css
index 92e3b2c6b1..92e3b2c6b1 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/checkbox_tr.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/checkbox_tr.css
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentbottom-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentbottom-h-icon.png
index db20dcdd7c..db20dcdd7c 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentbottom-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentbottom-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentbottom-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentbottom-icon.png
index d4319c39a8..d4319c39a8 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentbottom-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentbottom-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentcenterh-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentcenterh-h-icon.png
index 004221a6ab..004221a6ab 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentcenterh-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentcenterh-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentcenterh-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentcenterh-icon.png
index fa80a4f8e3..fa80a4f8e3 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentcenterh-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentcenterh-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentleft-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentleft-h-icon.png
index e40f3ef007..e40f3ef007 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentleft-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentleft-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentleft-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentleft-icon.png
index af91e4173e..af91e4173e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentleft-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentleft-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentmiddle-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentmiddle-h-icon.png
index 138c28517d..138c28517d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentmiddle-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentmiddle-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentmiddle-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentmiddle-icon.png
index c620e95bb2..c620e95bb2 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentmiddle-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentmiddle-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentright-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentright-h-icon.png
index 739f74c9ca..739f74c9ca 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentright-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentright-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentright-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentright-icon.png
index 068ab27fcf..068ab27fcf 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmentright-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmentright-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmenttop-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmenttop-h-icon.png
index 656d018627..656d018627 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmenttop-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmenttop-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmenttop-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmenttop-icon.png
index d6a6865a7d..d6a6865a7d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/alignmenttop-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/alignmenttop-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/apply.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/apply.png
index 845b46cbcd..845b46cbcd 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/apply.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/apply.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/behaivour.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/behaivour.png
index 7eea89104e..7eea89104e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/behaivour.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/behaivour.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/blended-image-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/blended-image-icon.png
index 7c0911d63d..7c0911d63d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/blended-image-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/blended-image-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/bold-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/bold-h-icon.png
index 96f5d4e6ad..96f5d4e6ad 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/bold-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/bold-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/bold-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/bold-icon.png
index ba86fb4fc7..ba86fb4fc7 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/bold-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/bold-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/button.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/button.png
index cc16dbbec3..cc16dbbec3 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/button.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/button.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/cancel.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/cancel.png
index 7b696cc87d..7b696cc87d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/cancel.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/cancel.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/default-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/default-icon.png
index a90779f02a..a90779f02a 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/default-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/default-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/downArrow.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/downArrow.png
index b92cb987b9..b92cb987b9 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/downArrow.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/downArrow.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/expression.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/expression.png
index 3dc2e44b3a..3dc2e44b3a 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/expression.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/expression.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/extended.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/extended.png
index 82587ae0ec..82587ae0ec 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/extended.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/extended.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/grid-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/grid-icon.png
index 113e14c00a..113e14c00a 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/grid-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/grid-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_gradient.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_gradient.png
index 4360c84965..4360c84965 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_gradient.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_gradient.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_none.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_none.png
index 8fa7a86dc8..8fa7a86dc8 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_none.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_none.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_solid.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_solid.png
index 0cf124e72e..0cf124e72e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/icon_color_solid.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/icon_color_solid.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/image-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/image-icon.png
index 4dfcae7d47..4dfcae7d47 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/image-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/image-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/italic-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/italic-h-icon.png
index 397ccd18ee..397ccd18ee 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/italic-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/italic-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/italic-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/italic-icon.png
index 0c3c7a3b20..0c3c7a3b20 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/italic-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/italic-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/item-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/item-icon.png
index 82587ae0ec..82587ae0ec 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/item-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/item-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/layout.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/layout.png
index 113e14c00a..113e14c00a 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/layout.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/layout.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/leftArrow.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/leftArrow.png
index 45187cf047..45187cf047 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/leftArrow.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/leftArrow.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/list-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/list-icon.png
index 9c96743f0e..9c96743f0e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/list-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/list-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/mouse-area-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/mouse-area-icon.png
index 8c23b6c0fc..8c23b6c0fc 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/mouse-area-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/mouse-area-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/placeholder.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/placeholder.png
index d2b333fdbd..d2b333fdbd 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/placeholder.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/placeholder.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/rect-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/rect-icon.png
index 4555d886fb..4555d886fb 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/rect-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/rect-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/reset-button.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/reset-button.png
index bf53422b9e..bf53422b9e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/reset-button.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/reset-button.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/rightArrow.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/rightArrow.png
index 118436bbcc..118436bbcc 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/rightArrow.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/rightArrow.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/standard.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/standard.png
index 7c0911d63d..7c0911d63d 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/standard.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/standard.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/strikeout-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/strikeout-h-icon.png
index 9e40e7dfe4..9e40e7dfe4 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/strikeout-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/strikeout-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/strikeout-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/strikeout-icon.png
index 94278fa6b4..94278fa6b4 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/strikeout-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/strikeout-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/submenu.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/submenu.png
index a91a6a98a1..a91a6a98a1 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/submenu.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/submenu.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/text-edit-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/text-edit-icon.png
index 6a064ab07c..6a064ab07c 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/text-edit-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/text-edit-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/text-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/text-icon.png
index 9ce62037ba..9ce62037ba 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/text-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/text-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/underline-h-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/underline-h-icon.png
index 02ea8c81a8..02ea8c81a8 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/underline-h-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/underline-h-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/underline-icon.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/underline-icon.png
index 5d86d7c0e9..5d86d7c0e9 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/underline-icon.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/underline-icon.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/upArrow.png b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/upArrow.png
index e689de743e..e689de743e 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/images/upArrow.png
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/images/upArrow.png
Binary files differ
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/layoutWidget.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/layoutWidget.css
index ce857900b8..85f3d8efda 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/layoutWidget.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/layoutWidget.css
@@ -4,9 +4,9 @@ QPushButton::checked
border: 4px solid #4f4f41;
border-image: none;
background-color: #9a9b9e;
- }
+ }
- QPushButton:pressed
+ QPushButton:pressed
{
border: 1px solid #5f5f51;
background-color: #dadbde;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/propertyEditor.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/propertyEditor.css
index 053d2f9a0e..e621398dd2 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/propertyEditor.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/propertyEditor.css
@@ -3,9 +3,9 @@ QFrame, QSpinBox {
font-size: 11px;
}
-QFrame
+QFrame
{
- border-radius: 0px;
+ border-radius: 0px;
}
WidgetFrame {
@@ -34,7 +34,7 @@ QScrollArea {
background-color: #4f4f4f;
}
-QGroupBox
+QGroupBox
{
background-color: #4f4f4f;
border: 1px solid #4F4F4F;
@@ -42,7 +42,7 @@ QGroupBox
font: bold ;
}
-QLineEdit
+QLineEdit
{
color: white;
font-size: 11px;
@@ -82,7 +82,7 @@ QTextEdit
- QSpinBox
+ QSpinBox
{
font-size: 11px;
color: white;
@@ -96,12 +96,12 @@ QTextEdit
background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 #2c2c2c, stop: 1 #333333);
-
+
max-height: 16px;
min-height: 16px;
}
-
- QDoubleSpinBox
+
+ QDoubleSpinBox
{
font-size: 11px;
color: white;
@@ -117,7 +117,7 @@ QTextEdit
max-height: 16px;
min-height: 16px;
}
-
+
QSpinBox::down-button {
subcontrol-origin: border;
subcontrol-position: bottom right;
@@ -136,7 +136,7 @@ QSpinBox::down-button:pressed {
border-image: url(:/qmldesigner/images/spindown_pressed.png) 1;
}
-
+
QSpinBox::up-button {
subcontrol-origin: border;
subcontrol-position: top right; /* position at bottom right corner */
@@ -153,8 +153,8 @@ QSpinBox::up-button:hover {
QSpinBox::up-button:pressed {
border-image: url(:/qmldesigner/images/spinup_pressed.png) 1;
}
-
-
+
+
QDoubleSpinBox::down-button {
subcontrol-origin: border;
subcontrol-position: bottom right;
@@ -171,7 +171,7 @@ QDoubleSpinBox::down-button:hover {
QDoubleSpinBox::down-button:pressed {
border-image: url(:/qmldesigner/images/spindown_pressed.png) 1;
}
-
+
QDoubleSpinBox::up-button {
subcontrol-origin: border;
subcontrol-position: top right;
@@ -188,7 +188,7 @@ QDoubleSpinBox::up-button:hover {
QDoubleSpinBox::up-button:pressed {
border-image: url(:/qmldesigner/images/spinup_pressed.png) 1;
}
-
+
QToolButton
{
background: none;
@@ -235,7 +235,7 @@ QComboBox[editable="true"]:on, QMenuBar::item:on {
border-width: 3;
}
-QComboBox
+QComboBox
{
font-size: 11px;
color: white;
@@ -270,7 +270,7 @@ QComboBox[editable="false"]::down-arrow {
QComboBox[editable="false"]::down-arrow:on {
position: relative;
- top: 1px;
+ top: 1px;
}
QComboBox[editable="true"] {
@@ -410,8 +410,8 @@ QMenu {
border-radius: 4px;
padding: 2px 25px 2px 20px;
}
-
- QMenu::item:disabled {
+
+ QMenu::item:disabled {
color: #aaaaaa;
}
QMenu::separator {
@@ -420,7 +420,7 @@ QMenu::separator {
margin-left: 5px;
margin-right: 5px;
}
-
+
QComboBox QAbstractItemView {
show-decoration-selected: 1;
background-color: #494949;
@@ -430,7 +430,7 @@ QMenu::separator {
selection-background-color: #d2d2d2;
selection-color: #404040;
}
-
+
QSlider::groove:horizontal {
height: 2px;
border-image: url(:/qmldesigner/images/slider_line.png) 0;
@@ -440,7 +440,7 @@ QMenu::separator {
QSlider::handle:horizontal {
background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f);
width: 16px;
- height: 16px;
+ height: 16px;
border: 1px solid #5c5c5c;
width: 18px;
margin: -4px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */
diff --git a/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/qmldir b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/qmldir
new file mode 100644
index 0000000000..25a7d54444
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/qmldir
@@ -0,0 +1,48 @@
+AlignmentHorizontalButtons 1.0 AlignmentHorizontalButtons.qml
+AlignmentVerticalButtons 1.0 AlignmentVerticalButtons.qml
+AnchorBox 1.0 AnchorBox.qml
+AnchorButtons 1.0 AnchorButtons.qml
+CheckBox 1.0 CheckBox.qml
+ColorGroupBox 1.0 ColorGroupBox.qml
+ColorLabel 1.0 ColorLabel.qml
+ColorLineEdit 1.0 ColorLineEdit.qml
+ColorScheme 1.0 ColorScheme.qml
+ColorTypeButtons 1.0 ColorTypeButtons.qml
+ComboBox 1.0 ComboBox.qml
+DoubleSpinBox 1.0 DoubleSpinBox.qml
+DoubleSpinBoxAlternate 1.0 DoubleSpinBoxAlternate.qml
+ExpressionEditor 1.0 ExpressionEditor.qml
+Extended 1.0 Extended.qml
+ExtendedFunctionButton 1.0 ExtendedFunctionButton.qml
+ExtendedPane 1.0 ExtendedPane.qml
+ExtendedSwitches 1.0 ExtendedSwitches.qml
+FlagedButton 1.0 FlagedButton.qml
+FontComboBox 1.0 FontComboBox.qml
+FontGroupBox 1.0 FontGroupBox.qml
+FontStyleButtons 1.0 FontStyleButtons.qml
+Geometry 1.0 Geometry.qml
+GroupBox 1.0 GroupBox.qml
+GroupBoxOption 1.0 GroupBoxOption.qml
+HorizontalLayout 1.0 HorizontalLayout.qml
+HorizontalWhiteLine 1.0 HorizontalWhiteLine.qml
+IntEditor 1.0 IntEditor.qml
+Label 1.0 Label.qml
+Layout 1.0 Layout.qml
+LayoutPane 1.0 LayoutPane.qml
+LineEdit 1.0 LineEdit.qml
+Modifiers 1.0 Modifiers.qml
+PlaceHolder 1.0 PlaceHolder.qml
+PropertyFrame 1.0 PropertyFrame.qml
+ScrollArea 1.0 ScrollArea.qml
+SliderWidget 1.0 SliderWidget.qml
+SpinBox 1.0 SpinBox.qml
+StandardTextColorGroupBox 1.0 StandardTextColorGroupBox.qml
+StandardTextGroupBox 1.0 StandardTextGroupBox.qml
+Switches 1.0 Switches.qml
+TextEditor 1.0 TextEditor.qml
+TextInputGroupBox 1.0 TextInputGroupBox.qml
+Transformation 1.0 Transformation.qml
+Type 1.0 Type.qml
+VerticalLayout 1.0 VerticalLayout.qml
+Visibility 1.0 Visibility.qml
+UrlEdit 1.0 UrlEdit.qml
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/specialCheckBox.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/specialCheckBox.css
index bcd93fb2ca..da6ca9ec02 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/specialCheckBox.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/specialCheckBox.css
@@ -4,7 +4,7 @@ QCheckBox {
border-radius: 2px;
color: white;
}
-
+
QToolButton {
color: white;
font: bold;
@@ -24,4 +24,3 @@ QCheckBox {
}
- \ No newline at end of file
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonleft.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonleft.css
index 7e46341a8f..086b0d71d0 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonleft.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonleft.css
@@ -1,11 +1,11 @@
QPushButton {
border-image: url(:/qmldesigner/images/button-normal-left.png);
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/button-pressed-left.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/button-pressed-left.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonmiddle.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonmiddle.css
index 739a17099f..0c6608ad25 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonmiddle.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonmiddle.css
@@ -2,11 +2,11 @@ QPushButton {
border-image: url(:/qmldesigner/images/button-normal-middle.png);
padding: 6px;
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/button-pressed-middle.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/button-pressed-middle.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonright.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonright.css
index ea879f2638..a7f748579c 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/styledbuttonright.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/styledbuttonright.css
@@ -2,11 +2,11 @@ QPushButton {
border-image: url(:/qmldesigner/images/button-normal-right.png);
padding: 6px;
}
-
+
QPushButton:pressed {
border-image: url(:/qmldesigner/images/button-pressed-right.png);
}
-
+
QPushButton:checked {
border-image: url(:/qmldesigner/images/button-pressed-right.png);
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/switch.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/switch.css
index 80bd9f04e5..80bd9f04e5 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/switch.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/switch.css
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/typeLabel.css b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/typeLabel.css
index b332ad7b64..b332ad7b64 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/typeLabel.css
+++ b/share/qtcreator/qmldesigner/propertyeditor/HelperWidgets/typeLabel.css
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/BooleanEditorTemplate.template b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/BooleanEditorTemplate.template
new file mode 100644
index 0000000000..f3432a9161
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/BooleanEditorTemplate.template
@@ -0,0 +1,14 @@
+QWidget {
+ layout: HorizontalLayout {
+ Label {
+ text: "%1"
+ toolTip: "%1"
+ }
+ CheckBox {
+ text: backendValues.%2.value
+ backendValue: backendValues.%2
+ baseStateFlag: isBaseState
+ checkable: true
+ }
+ }
+} \ No newline at end of file
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/ColorEditorTemplate.template b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/ColorEditorTemplate.template
new file mode 100644
index 0000000000..e8e4f17d72
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/ColorEditorTemplate.template
@@ -0,0 +1,5 @@
+ColorGroupBox {
+ caption: "%1"
+ finished: finishedNotify
+ backendColor: backendValues.%2
+} \ No newline at end of file
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/IntEditorTemplate.template b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/IntEditorTemplate.template
new file mode 100644
index 0000000000..c3c35be70c
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/IntEditorTemplate.template
@@ -0,0 +1,6 @@
+IntEditor {
+ backendValue: backendValues.%2
+ caption: "%1"
+ baseStateFlag: isBaseState
+ slider: false
+} \ No newline at end of file
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/RealEditorTemplate.template b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/RealEditorTemplate.template
new file mode 100644
index 0000000000..cdae8e7ff8
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/RealEditorTemplate.template
@@ -0,0 +1,5 @@
+DoubleSpinBoxAlternate {
+ text: "%1"
+ backendValue: backendValues.%2
+ baseStateFlag: isBaseState
+} \ No newline at end of file
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/StringEditorTemplate.template b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/StringEditorTemplate.template
new file mode 100644
index 0000000000..5152da59d6
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/StringEditorTemplate.template
@@ -0,0 +1,12 @@
+QWidget {
+ layout: HorizontalLayout {
+ Label {
+ text: "%1"
+ toolTip: "%1"
+ }
+ LineEdit {
+ backendValue: backendValues.%2
+ baseStateFlag: isBaseState
+ }
+ }
+} \ No newline at end of file
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/TemplateTypes.qml b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/TemplateTypes.qml
new file mode 100644
index 0000000000..c707885075
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/TemplateTypes.qml
@@ -0,0 +1,29 @@
+
+AutoTypes {
+ imports: [ "import HelperWidgets 1.0", "import QtQuick 1.0", "import Bauhaus 1.0" ]
+
+ Type {
+ typeNames: ["int"]
+ sourceFile: "IntEditorTemplate.template"
+ }
+ Type {
+ typeNames: ["real", "double", "qreal"]
+ sourceFile: "RealEditorTemplate.template"
+ }
+ Type {
+ typeNames: ["string", "QString"]
+ sourceFile: "StringEditorTemplate.template"
+ }
+ Type {
+ typeNames: ["QUrl", "url"]
+ sourceFile: "UrlEditorTemplate.template"
+ }
+ Type {
+ typeNames: ["bool", "boolean"]
+ sourceFile: "BooleanEditorTemplate.template"
+ }
+ Type {
+ typeNames: ["color", "QColor"]
+ sourceFile: "ColorEditorTemplate.template"
+ }
+}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/UrlEditorTemplate.template b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/UrlEditorTemplate.template
new file mode 100644
index 0000000000..39e401b18e
--- /dev/null
+++ b/share/qtcreator/qmldesigner/propertyeditor/PropertyTemplates/UrlEditorTemplate.template
@@ -0,0 +1,12 @@
+QWidget {
+ layout: HorizontalLayout {
+ Label {
+ text: "%1"
+ toolTip: "%1"
+ }
+ UrlEdit {
+ backendValue: backendValues.%2
+ baseStateFlag: isBaseState
+ }
+ }
+}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/BorderImageSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/BorderImageSpecifics.qml
index a5248a76ef..c671e3eb64 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/BorderImageSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/BorderImageSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
@@ -60,7 +61,7 @@ QWidget {
backendValues.source.value = fileName;
}
itemNode: anchorBackend.itemNode
- filter: "*.png *.gif *.jpg"
+ filter: "*.png *.gif *.jpg *.bmp *.jpeg"
showComboBox: true
}
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlickableGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlickableGroupBox.qml
index 96a0e5214e..578b06af84 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlickableGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlickableGroupBox.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
GroupBox {
finished: finishedNotify;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlickableSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlickableSpecifics.qml
index e0f646b6c0..5e03d64f02 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlickableSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlickableSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlipableSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlipableSpecifics.qml
index c461c30c80..6f9c400cd4 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlipableSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlipableSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlowSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlowSpecifics.qml
index 4ef73b0fee..a255b3d7bf 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/FlowSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/FlowSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/GridSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/GridSpecifics.qml
index 8574770155..f4dede2c05 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/GridSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/GridSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/GridViewSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/GridViewSpecifics.qml
index 25fb1adfe5..956d797e9f 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/GridViewSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/GridViewSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ImageSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/ImageSpecifics.qml
index 84d9e8d2c1..04a9b9b420 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ImageSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/ImageSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
@@ -58,7 +59,7 @@ QWidget {
backendValues.source.value = fileName;
}
itemNode: anchorBackend.itemNode
- filter: "*.png *.gif *.jpg"
+ filter: "*.png *.gif *.jpg *.bmp *.jpeg"
showComboBox: true
}
}
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ItemPane.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/ItemPane.qml
index e0c70248a1..f179a92514 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ItemPane.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/ItemPane.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
PropertyFrame {
id: frame;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/ListViewSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/ListViewSpecifics.qml
index 1a83a50605..862241d93c 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/ListViewSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/ListViewSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/MouseAreaSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/MouseAreaSpecifics.qml
index a0764a2e96..ae5c98024a 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/MouseAreaSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/MouseAreaSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/PathViewSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/PathViewSpecifics.qml
index e28e9bb969..a4a8243b15 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/PathViewSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/PathViewSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/RectangleColorGroupBox.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/RectangleColorGroupBox.qml
index 7ebd5733a1..4455e4f558 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/RectangleColorGroupBox.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/RectangleColorGroupBox.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
GroupBox {
id: rectangleColorGroupBox
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/RectangleSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/RectangleSpecifics.qml
index 1f1bceb42a..ec0343d368 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/RectangleSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/RectangleSpecifics.qml
@@ -29,7 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
-
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
@@ -53,7 +53,7 @@ QWidget {
rightMargin: 24
IntEditor {
- enabled: colorsBox.hasBorder
+ editorEnabled: colorsBox.hasBorder
opacity: enabled ? 1 : 0.6
toolTip: enabled ? qsTr("Border width") : qsTr("Border has to be solid to change width")
id: borderWidth;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/RowSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/RowSpecifics.qml
index db2655ff8f..4fe8a643ea 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/RowSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/RowSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextEditSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextEditSpecifics.qml
index 7a33bedae3..b04cb2bf3f 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextEditSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextEditSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
id: textSpecifics;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextInputSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextInputSpecifics.qml
index 71baaecfc9..3da3ad00e2 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextInputSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextInputSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
id: textSpecifics;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextSpecifics.qml
index b7dedc9e08..c9d4946e08 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/TextSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/TextSpecifics.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
QWidget {
id: textSpecifics;
diff --git a/share/qtcreator/qmldesigner/propertyeditor/Qt/emptyPane.qml b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/emptyPane.qml
index af68862774..e52ab9386f 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/Qt/emptyPane.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtQuick/emptyPane.qml
@@ -29,6 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
+import HelperWidgets 1.0
PropertyFrame {
layout: QVBoxLayout {
diff --git a/share/qtcreator/qmldesigner/propertyeditor/QtWebKit/WebViewSpecifics.qml b/share/qtcreator/qmldesigner/propertyeditor/QtWebKit/WebViewSpecifics.qml
index b351e687d6..aafe95d1d3 100644
--- a/share/qtcreator/qmldesigner/propertyeditor/QtWebKit/WebViewSpecifics.qml
+++ b/share/qtcreator/qmldesigner/propertyeditor/QtWebKit/WebViewSpecifics.qml
@@ -29,7 +29,7 @@
import QtQuick 1.0
import Bauhaus 1.0
-import "../Qt/"
+import HelperWidgets 1.0
QWidget {
layout: QVBoxLayout {
diff --git a/share/qtcreator/scripts/openTerminal.command b/share/qtcreator/scripts/openTerminal.command
index 2d5791da8c..1f81a59050 100755
--- a/share/qtcreator/scripts/openTerminal.command
+++ b/share/qtcreator/scripts/openTerminal.command
@@ -1,11 +1,18 @@
#! /bin/bash
-i=`pwd`
-i=${i//\\/\\\\\\\\}
-i=${i//\"/\\\\\\\"}
-i=${i//\$/\\\\\\\$}
-i=${i//\`/\\\\\\\`}
-i=\\\"$i\\\"
+# ugly escaping: for apple script \ and " need to be escaped, whereas %q takes care of all bash escaping
+declare -a args
+mydir=`pwd`
+mydir=$(printf '%q' "$mydir")
+mydir="${mydir//\\/\\\\}"
+args[0]="cd ${mydir//\"/\\\"};"
+for a in "$@" ; do
+ x=$(printf '%q ' "$a")
+ x="${x//\\/\\\\}"
+ args[${#args[@]}]="${x//\"/\\\"}"
+done
+mArgs=${args[@]:0}
+
osascript <<EOF
--Terminal opens a window by default when it is not running, so check
on applicationIsRunning(applicationName)
@@ -14,7 +21,7 @@ osascript <<EOF
end applicationIsRunning
set terminalWasRunning to applicationIsRunning("Terminal")
- set cdScript to "cd $i"
+ set cdScript to "$mArgs"
tell application "Terminal"
--do script will open a new window if none given, but terminal already opens one if not running
if terminalWasRunning then
diff --git a/share/qtcreator/templates/qml/qtquick1_1/main.qml b/share/qtcreator/templates/qml/qtquick1_1/main.qml
new file mode 100644
index 0000000000..921baa6006
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick1_1/main.qml
@@ -0,0 +1,17 @@
+import QtQuick 1.1
+
+Rectangle {
+ width: 360
+ height: 360
+ Text {
+ anchors.centerIn: parent
+ text: "Hello World"
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: {
+ Qt.quit();
+ }
+ }
+}
+
diff --git a/share/qtcreator/templates/qml/qtquick1_1/main.qmlproject b/share/qtcreator/templates/qml/qtquick1_1/main.qmlproject
new file mode 100644
index 0000000000..4abcb0d975
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick1_1/main.qmlproject
@@ -0,0 +1,21 @@
+/* File generated by Qt Creator, version 2.7.0 */
+
+import QmlProject 1.1
+
+Project {
+# QTC_REPLACE main.qml WITH main
+ mainFile: "main.qml"
+
+ /* Include .qml, .js, and image files from current directory and subdirectories */
+ QmlFiles {
+ directory: "."
+ }
+ JavaScriptFiles {
+ directory: "."
+ }
+ ImageFiles {
+ directory: "."
+ }
+ /* List of plugin directories passed to QML runtime */
+ // importPaths: [ "../exampleplugin" ]
+}
diff --git a/share/qtcreator/templates/qml/qtquick1_1/template.png b/share/qtcreator/templates/qml/qtquick1_1/template.png
new file mode 100644
index 0000000000..ce821c7876
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick1_1/template.png
Binary files differ
diff --git a/share/qtcreator/templates/qml/qtquick1_1/template.xml b/share/qtcreator/templates/qml/qtquick1_1/template.xml
new file mode 100644
index 0000000000..9f6c0bfc6a
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick1_1/template.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<template openeditor="main.qml" priority="2"
+ featuresRequired="QtSupport.Wizards.FeatureQtQuickProject, QtSupport.Wizards.FeatureQtQuick, QtSupport.Wizards.FeatureQtQuick.1.1"
+ id="QB.QML Application for Qt Quick 1.1">
+ <displayname>Qt Quick 1 UI</displayname>
+ <displayname xml:lang="de">Qt Quick 1 UI</displayname>
+ <description>Creates a Qt Quick UI 1 project with a single QML file that contains the main view.
+
+ You can review Qt Quick UI 1 projects in the QML Viewer and you need not build them. You do not need to have the development environment installed on your computer to create and run this type of projects.
+
+ Requires &lt;b&gt;Qt 4.8&lt;/b&gt; or newer.
+ </description>
+</template>
diff --git a/share/qtcreator/templates/qml/qtquick2/main.qml b/share/qtcreator/templates/qml/qtquick2/main.qml
new file mode 100644
index 0000000000..b3d4ef33d4
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick2/main.qml
@@ -0,0 +1,17 @@
+import QtQuick 2.0
+
+Rectangle {
+ width: 360
+ height: 360
+ Text {
+ anchors.centerIn: parent
+ text: "Hello World"
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: {
+ Qt.quit();
+ }
+ }
+}
+
diff --git a/share/qtcreator/templates/qml/qtquick2/main.qmlproject b/share/qtcreator/templates/qml/qtquick2/main.qmlproject
new file mode 100644
index 0000000000..4abcb0d975
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick2/main.qmlproject
@@ -0,0 +1,21 @@
+/* File generated by Qt Creator, version 2.7.0 */
+
+import QmlProject 1.1
+
+Project {
+# QTC_REPLACE main.qml WITH main
+ mainFile: "main.qml"
+
+ /* Include .qml, .js, and image files from current directory and subdirectories */
+ QmlFiles {
+ directory: "."
+ }
+ JavaScriptFiles {
+ directory: "."
+ }
+ ImageFiles {
+ directory: "."
+ }
+ /* List of plugin directories passed to QML runtime */
+ // importPaths: [ "../exampleplugin" ]
+}
diff --git a/share/qtcreator/templates/qml/qtquick2/template.png b/share/qtcreator/templates/qml/qtquick2/template.png
new file mode 100644
index 0000000000..7db0ee91f4
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick2/template.png
Binary files differ
diff --git a/share/qtcreator/templates/qml/qtquick2/template.xml b/share/qtcreator/templates/qml/qtquick2/template.xml
new file mode 100644
index 0000000000..11761a626d
--- /dev/null
+++ b/share/qtcreator/templates/qml/qtquick2/template.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<template openeditor="main.qml" priority="2"
+ featuresRequired="QtSupport.Wizards.FeatureQtQuickProject, QtSupport.Wizards.FeatureQtQuick, QtSupport.Wizards.FeatureQtQuick.2"
+ id="QB.QML Application for Qt Quick 2.0">
+ <displayname>Qt Quick 2 UI</displayname>
+ <displayname xml:lang="de">Qt Quick 2 UI</displayname>
+ <description>Creates a Qt Quick UI 2 project with a single QML file that contains the main view.
+
+ You can review Qt Quick UI 2 projects in the QML Scene and you need not build them. You do not need to have the development environment installed on your computer to create and run this type of projects.
+
+ Requires &lt;b&gt;Qt 5.0&lt;/b&gt; or newer.
+ </description>
+</template>
diff --git a/share/qtcreator/templates/qtquick2app/qtquick2applicationviewer/qtquick2applicationviewer.cpp b/share/qtcreator/templates/qtquick2app/qtquick2applicationviewer/qtquick2applicationviewer.cpp
index 261849538e..f8e98afc74 100644
--- a/share/qtcreator/templates/qtquick2app/qtquick2applicationviewer/qtquick2applicationviewer.cpp
+++ b/share/qtcreator/templates/qtquick2app/qtquick2applicationviewer/qtquick2applicationviewer.cpp
@@ -26,7 +26,7 @@ QString QtQuick2ApplicationViewerPrivate::adjustPath(const QString &path)
if (!QDir::isAbsolutePath(path))
return QString::fromLatin1("%1/../Resources/%2")
.arg(QCoreApplication::applicationDirPath(), path);
-#elif defined(Q_OS_UNIX)
+#elif defined(Q_OS_UNIX) && !defined(Q_OS_ANDROID)
const QString pathInInstallDir =
QString::fromLatin1("%1/../%2").arg(QCoreApplication::applicationDirPath(), path);
if (QFileInfo(pathInInstallDir).exists())
@@ -51,7 +51,11 @@ QtQuick2ApplicationViewer::~QtQuick2ApplicationViewer()
void QtQuick2ApplicationViewer::setMainQmlFile(const QString &file)
{
d->mainQmlFile = QtQuick2ApplicationViewerPrivate::adjustPath(file);
+#ifdef Q_OS_ANDROID
+ setSource(QUrl(QLatin1String("assets:/")+d->mainQmlFile));
+#else
setSource(QUrl::fromLocalFile(d->mainQmlFile));
+#endif
}
void QtQuick2ApplicationViewer::addImportPath(const QString &path)
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/assets/SecondPage.qml b/share/qtcreator/templates/wizards/bb-cascades-app/assets/SecondPage.qml
new file mode 100644
index 0000000000..429ea6078e
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/assets/SecondPage.qml
@@ -0,0 +1,24 @@
+import bb.cascades 1.0
+
+Page {
+ id: seconPage
+ paneProperties: NavigationPaneProperties {
+ backButton: ActionItem {
+ onTriggered: {
+ navigationPane.pop()
+ }
+ }
+ }
+ Container {
+ layout: DockLayout {}
+ Label {
+ text: qsTr("Hello Cascades!")
+ horizontalAlignment: HorizontalAlignment.Center
+ verticalAlignment: VerticalAlignment.Center
+ textStyle {
+ base: SystemDefaults.TextStyles.TitleText
+ }
+ }
+ }
+}
+
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/assets/main.qml b/share/qtcreator/templates/wizards/bb-cascades-app/assets/main.qml
new file mode 100644
index 0000000000..a02479065e
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/assets/main.qml
@@ -0,0 +1,37 @@
+import bb.cascades 1.0
+
+NavigationPane {
+ id: navigationPane
+ Page {
+ Container {
+ layout: DockLayout {}
+ Button {
+ horizontalAlignment: HorizontalAlignment.Center
+ verticalAlignment: VerticalAlignment.Center
+ text: qsTr("Next")
+ onClicked: {
+ var page = getSecondPage();
+ navigationPane.push(page);
+ }
+ property Page secondPage
+ function getSecondPage() {
+ if (! secondPage) {
+ secondPage = secondPageDefinition.createObject();
+ }
+ return secondPage;
+ }
+ attachedObjects: [
+ ComponentDefinition {
+ id: secondPageDefinition
+ source: "SecondPage.qml"
+ }
+ ]
+ }
+ }
+ }
+ onCreationCompleted: {
+ console.log("NavigationPane - onCreationCompleted()");
+ OrientationSupport.supportedDisplayOrientation = SupportedDisplayOrientation.All;
+ }
+}
+
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/bar-descriptor.xml b/share/qtcreator/templates/wizards/bb-cascades-app/bar-descriptor.xml
new file mode 100644
index 0000000000..4737c1bc86
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/bar-descriptor.xml
@@ -0,0 +1,17 @@
+<?xml version='1.0' encoding='utf-8' standalone='no'?>
+<qnx xmlns="http://www.qnx.com/schemas/application/1.0">
+ <id>com.example.%ProjectName%</id>
+ <name>%ProjectName%</name>
+ <versionNumber>1.0.0</versionNumber>
+ <description>DESCRIPTION</description>
+ <initialWindow>
+ <systemChrome>none</systemChrome>
+ <transparent>false</transparent>
+ <autoOrients>true</autoOrients>
+ <aspectRatio>landscape</aspectRatio>
+ </initialWindow>
+ <env value="app/native/lib:/usr/lib/qt4/lib/" var="LD_LIBRARY_PATH"/>
+ <action system="true">run_native</action>
+ <asset path="%ProjectName%" type="Qnx/Elf" entry="true">%ProjectName%</asset>
+ <asset path="%SRC_DIR%/assets">assets</asset>
+</qnx>
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/icon.png b/share/qtcreator/templates/wizards/bb-cascades-app/icon.png
new file mode 100644
index 0000000000..6bbf3761ef
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/icon.png
Binary files differ
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/main.cpp b/share/qtcreator/templates/wizards/bb-cascades-app/main.cpp
new file mode 100644
index 0000000000..682f978a50
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/main.cpp
@@ -0,0 +1,13 @@
+#include "%ProjectName%.hpp"
+
+#include <bb/cascades/Application>
+#include <Qt/qdeclarativedebug.h>
+
+Q_DECL_EXPORT int main(int argc, char **argv)
+{
+ bb::cascades::Application app(argc, argv);
+
+ new %ProjectName%(&app);
+
+ return bb::cascades::Application::exec();
+}
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/project.cpp b/share/qtcreator/templates/wizards/bb-cascades-app/project.cpp
new file mode 100644
index 0000000000..499c13cfbf
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/project.cpp
@@ -0,0 +1,14 @@
+#include "%ProjectName%.hpp"
+
+#include <bb/cascades/Application>
+#include <bb/cascades/QmlDocument>
+#include <bb/cascades/AbstractPane>
+
+%ProjectName%::%ProjectName%(bb::cascades::Application *app)
+ : QObject(app)
+{
+ bb::cascades::QmlDocument *qml = bb::cascades::QmlDocument::create("asset:///main.qml").parent(this);
+ bb::cascades::AbstractPane *root = qml->createRootObject<bb::cascades::AbstractPane>();
+ app->setScene(root);
+}
+
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/project.hpp b/share/qtcreator/templates/wizards/bb-cascades-app/project.hpp
new file mode 100644
index 0000000000..05d9ee0b5f
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/project.hpp
@@ -0,0 +1,16 @@
+#ifndef %ProjectName%_HPP_
+#define %ProjectName%_HPP_
+
+#include <QObject>
+
+namespace bb { namespace cascades { class Application; }}
+
+class %ProjectName% : public QObject
+{
+ Q_OBJECT
+public:
+ %ProjectName%(bb::cascades::Application *app);
+ virtual ~%ProjectName%() {}
+};
+
+#endif /* %ProjectName%_HPP_ */
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/project.pro b/share/qtcreator/templates/wizards/bb-cascades-app/project.pro
new file mode 100644
index 0000000000..1c18913f26
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/project.pro
@@ -0,0 +1,18 @@
+TEMPLATE = app
+
+# Additional import path used to resolve QML modules in Creator's code model
+
+LIBS += -lbbdata -lbb -lbbcascades
+QT += declarative xml
+
+# The .cpp file which was generated for your project. Feel free to hack it.
+SOURCES += main.cpp \
+ %ProjectName%.cpp
+
+HEADERS += %ProjectName%.hpp
+
+OTHER_FILES += bar-descriptor.xml \
+ assets/main.qml \
+ assets/SecondPage.qml
+
+
diff --git a/share/qtcreator/templates/wizards/bb-cascades-app/wizard.xml b/share/qtcreator/templates/wizards/bb-cascades-app/wizard.xml
new file mode 100644
index 0000000000..4935f5307e
--- /dev/null
+++ b/share/qtcreator/templates/wizards/bb-cascades-app/wizard.xml
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Digia.
+**
+**************************************************************************/
+-->
+<wizard version="1" kind="project"
+ class="qt4project" firstpage="10"
+ id="Q.QnxBlackBerryCascadesApp" category="F.QtApplications"
+ featuresRequired="QtSupport.Wizards.FeatureBlackBerry">
+ <icon>icon.png</icon>
+ <displayname>BlackBerry Cascades Application</displayname>;
+ <description>Creates a Cascades application for BlackBerry 10.</description>
+ <files>
+ <file source="main.cpp" openeditor="true"/>
+ <file source="assets/main.qml" openeditor="true"/>
+ <file source="assets/SecondPage.qml" openeditor="true"/>
+ <file source="bar-descriptor.xml" openeditor="true"/>
+ <file source="project.pro" target="%ProjectName%.pro" openproject="true"/>
+ <file source="project.hpp" target="%ProjectName%.hpp" openproject="true"/>
+ <file source="project.cpp" target="%ProjectName%.cpp" openproject="true"/>
+ </files>
+</wizard>
diff --git a/share/qtcreator/templates/wizards/bb-qt5-guiapp/wizard.xml b/share/qtcreator/templates/wizards/bb-qt5-guiapp/wizard.xml
index 4d4cc46060..92f8d4bff5 100644
--- a/share/qtcreator/templates/wizards/bb-qt5-guiapp/wizard.xml
+++ b/share/qtcreator/templates/wizards/bb-qt5-guiapp/wizard.xml
@@ -35,8 +35,8 @@
id="Q.QnxBlackBerryGuiApp" category="F.QtApplications"
featuresRequired="QtSupport.Wizards.FeatureBlackBerry">
<icon>icon.png</icon>
- <displayname>BlackBerry Qt5 Gui Application</displayname>;
- <description>Creates an experimental Qt5 Gui application for BlackBerry 10. You need an own Qt5 build for BlackBerry 10 since Qt5 is not provided in the current BlackBerry 10 NDK and is not included in DevAlpha devices.</description>
+ <displayname>BlackBerry Qt 5 GUI Application</displayname>;
+ <description>Creates an experimental Qt 5 GUI application for BlackBerry 10. You need to provide your own build of Qt 5 for BlackBerry 10 since Qt 5 is not provided in the current BlackBerry 10 NDK and is not included in DevAlpha devices.</description>
<files>
<file source="main.cpp" openeditor="true"/>
<file source="mainwidget.cpp" openeditor="true"/>
diff --git a/share/qtcreator/templates/wizards/bb-qt5-quick2app/wizard.xml b/share/qtcreator/templates/wizards/bb-qt5-quick2app/wizard.xml
index 523a921110..bf33925165 100644
--- a/share/qtcreator/templates/wizards/bb-qt5-quick2app/wizard.xml
+++ b/share/qtcreator/templates/wizards/bb-qt5-quick2app/wizard.xml
@@ -36,7 +36,7 @@
featuresRequired="QtSupport.Wizards.FeatureBlackBerry">
<icon>icon.png</icon>
<displayname>BlackBerry Qt Quick 2 Application</displayname>;
- <description>Creates an experimental Qt Quick 2 application for BlackBerry 10. You need an own Qt5 build for BlackBerry 10 since Qt5 is not provided in the current BlackBerry 10 NDK and is not included in DevAlpha devices.</description>
+ <description>Creates an experimental Qt Quick 2 application for BlackBerry 10. You need to provide your own build of Qt 5 for BlackBerry 10 since Qt 5 is not provided in the current BlackBerry 10 NDK and is not included in DevAlpha devices.</description>
<files>
<file source="main.cpp" openeditor="true"/>
<file source="qml/main.qml" openeditor="true"/>
diff --git a/share/qtcreator/templates/wizards/codesnippet/main.cpp b/share/qtcreator/templates/wizards/codesnippet/main.cpp
new file mode 100644
index 0000000000..59d189b301
--- /dev/null
+++ b/share/qtcreator/templates/wizards/codesnippet/main.cpp
@@ -0,0 +1 @@
+%CODE%
diff --git a/share/qtcreator/templates/wizards/codesnippet/project.pro b/share/qtcreator/templates/wizards/codesnippet/project.pro
new file mode 100644
index 0000000000..6652132d05
--- /dev/null
+++ b/share/qtcreator/templates/wizards/codesnippet/project.pro
@@ -0,0 +1,15 @@
+TEMPLATE = app
+@if "%TYPE%" == "core"
+QT = core
+@else
+QT = core gui
+greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+@endif
+@if "%CONSOLE%" == "true"
+CONFIG += console
+@endif
+@if "%APP_BUNDLE%" == "false"
+CONFIG -= app_bundle
+@endif
+
+SOURCES += main.cpp
diff --git a/share/qtcreator/templates/wizards/codesnippet/wizard.xml b/share/qtcreator/templates/wizards/codesnippet/wizard.xml
new file mode 100644
index 0000000000..7d52a0e017
--- /dev/null
+++ b/share/qtcreator/templates/wizards/codesnippet/wizard.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: http://www.qt-project.org/
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+**
+**************************************************************************/
+
+Custom project wizard configuration example file. Note that by convention,
+the project file goes last.
+The "class" and "firstpage" attributes specify that it is a Qt 4 wizard and
+leave room for the Qt 4 target page.
+-->
+<wizard version="1" kind="project"
+ class="qt4project" firstpage="10"
+ id="Z.Snippet" category="H.QtProjects">
+ <description>Creates a qmake-based test project for which a code snippet can be entered.</description>
+ <displayname>Code Snippet</displayname>;
+ <displaycategory>Other Projects</displaycategory>
+ <files>
+ <file source="main.cpp" openeditor="true"/>
+ <file source="project.pro" target="%ProjectName%.pro" openproject="true"/>
+ </files>
+ <fieldpagetitle>Snippet Parameters</fieldpagetitle>
+ <fields>
+ <field name="CODE">
+ <fieldcontrol class="QTextEdit" defaulttext="int main(int argc, char *argv[]) { return 0; }"/>
+ <fielddescription>Code:</fielddescription>
+ </field>
+ <field name="TYPE">
+ <fielddescription>Type:</fielddescription>
+ <fieldcontrol class="QComboBox" defaultindex="0">
+ <comboentries>
+ <comboentry value="core">
+ <comboentrytext>Headless (QtCore)</comboentrytext>
+ </comboentry>
+ <comboentry value="gui">
+ <comboentrytext>Gui application (QtCore, QtGui, QtWidgets)</comboentrytext>
+ </comboentry>
+ </comboentries>
+ </fieldcontrol>
+ </field>
+ <field name="CONSOLE">
+ <fieldcontrol class="QCheckBox" defaultvalue="true"/>
+ <fielddescription>Console application</fielddescription>
+ </field>
+ <field name="APP_BUNDLE">
+ <fieldcontrol class="QCheckBox"/>
+ <fielddescription>Application bundle (Mac)</fielddescription>
+ </field>
+ </fields>
+</wizard>
diff --git a/share/qtcreator/translations/translations.qbs b/share/qtcreator/translations/translations.qbs
index d6d7534d1c..f6fc8f8813 100644
--- a/share/qtcreator/translations/translations.qbs
+++ b/share/qtcreator/translations/translations.qbs
@@ -4,6 +4,11 @@ Product {
type: "qm"
name: "translations"
Depends { name: "Qt.core" }
- destination: "share/qtcreator/translations"
files: "*.ts"
+
+ Group {
+ fileTagsFilter: product.type
+ qbs.install: true
+ qbs.installDir: "share/qtcreator/translations"
+ }
}
diff --git a/share/share.qbs b/share/share.qbs
index 2b317b883e..e998dcbc7f 100644
--- a/share/share.qbs
+++ b/share/share.qbs
@@ -1,1354 +1,52 @@
import qbs.base 1.0
Product {
- type: ["installed_content"]
name: "SharedContent"
Group {
- condition: qbs.targetOS == "macx"
- qbs.installDir: "share/qtcreator/scripts"
- fileTags: ["install"]
- files: "qtcreator/scripts/openTerminal.command"
- }
-
- Group {
- qbs.installDir: "share/qtcreator/designer"
- fileTags: ["install"]
- prefix: "qtcreator/designer/"
- files: [
- "templates.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/designer/templates"
- fileTags: ["install"]
- prefix: "qtcreator/designer/templates/"
- files: [
- "Dialog_with_Buttons_Bottom.ui",
- "Dialog_with_Buttons_Right.ui",
- "Dialog_without_Buttons.ui",
- "Main_Window.ui",
- "Widget.ui",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/dumper"
- fileTags: ["install"]
- prefix: "qtcreator/dumper/"
- files: [
- "LGPL_EXCEPTION.TXT",
- "LICENSE.LGPL",
- "bridge.py",
- "dumper.cpp",
- "dumper.h",
- "dumper.pro",
- "dumper.py",
- "dumper_p.h",
- "pdumper.py",
- "qttypes.py",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/dumper/test"
- fileTags: ["install"]
- prefix: "qtcreator/dumper/test/"
- files: [
- "dumpertest.pro",
- "main.cpp",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/generic-highlighter"
- fileTags: ["install"]
- prefix: "qtcreator/generic-highlighter/"
- files: [
- "alert.xml",
- "autoconf.xml",
- "bash.xml",
- "cmake.xml",
- "css.xml",
- "doxygen.xml",
- "dtd.xml",
- "html.xml",
- "ini.xml",
- "java.xml",
- "javadoc.xml",
- "perl.xml",
- "ruby.xml",
- "valgrind-suppression.xml",
- "xml.xml",
- "yacc.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/glsl"
- fileTags: ["install"]
- prefix: "qtcreator/glsl/"
- files: [
- "glsl_120.frag",
- "glsl_120.vert",
- "glsl_120_common.glsl",
- "glsl_es_100.frag",
- "glsl_es_100.vert",
- "glsl_es_100_common.glsl",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml-type-descriptions"
- fileTags: ["install"]
- prefix: "qtcreator/qml-type-descriptions/"
- files: [
- "builtins.qmltypes",
- "qmlproject.qmltypes",
- "qmlruntime.qmltypes",
- "qt-labs-folderlistmodel.qmltypes",
- "qt-labs-gestures.qmltypes",
- "qt-labs-particles.qmltypes",
- "qtmobility-connectivity.qmltypes",
- "qtmobility-contacts.qmltypes",
- "qtmobility-feedback.qmltypes",
- "qtmobility-gallery.qmltypes",
- "qtmobility-location.qmltypes",
- "qtmobility-messaging.qmltypes",
- "qtmobility-organizer.qmltypes",
- "qtmobility-publishsubscribe.qmltypes",
- "qtmobility-sensors.qmltypes",
- "qtmobility-serviceframework.qmltypes",
- "qtmobility-systeminfo.qmltypes",
- "qtmultimediakit.qmltypes",
- "qtwebkit.qmltypes",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmldump"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmldump/"
- files: [
- "LGPL_EXCEPTION.TXT",
- "LICENSE.LGPL",
- "main.cpp",
- "qmldump.pro",
- "qmlstreamwriter.cpp",
- "qmlstreamwriter.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmljsdebugger"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmljsdebugger/"
- files: [
- "jsdebuggeragent.cpp",
- "qdeclarativeinspectorservice.cpp",
- "qdeclarativeviewinspector.cpp",
- "qdeclarativeviewinspector_p.h",
- "qmljsdebugger-lib.pri",
- "qmljsdebugger-src.pri",
- "qmljsdebugger.pro",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmljsdebugger/editor"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmljsdebugger/editor/"
- files: [
- "abstractliveedittool.cpp",
- "abstractliveedittool.h",
- "boundingrecthighlighter.cpp",
- "boundingrecthighlighter.h",
- "colorpickertool.cpp",
- "colorpickertool.h",
- "livelayeritem.cpp",
- "livelayeritem.h",
- "liverubberbandselectionmanipulator.cpp",
- "liverubberbandselectionmanipulator.h",
- "liveselectionindicator.cpp",
- "liveselectionindicator.h",
- "liveselectionrectangle.cpp",
- "liveselectionrectangle.h",
- "liveselectiontool.cpp",
- "liveselectiontool.h",
- "livesingleselectionmanipulator.cpp",
- "livesingleselectionmanipulator.h",
- "subcomponentmasklayeritem.cpp",
- "subcomponentmasklayeritem.h",
- "zoomtool.cpp",
- "zoomtool.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmljsdebugger/include"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmljsdebugger/include/"
- files: [
- "jsdebuggeragent.h",
- "qdeclarativeinspectorservice.h",
- "qdeclarativeviewinspector.h",
- "qdeclarativeviewobserver.h",
- "qmlinspectorconstants.h",
- "qmljsdebugger_global.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmljsdebugger/include/qt_private"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmljsdebugger/include/qt_private/"
- files: [
- "qdeclarativedebughelper_p.h",
- "qdeclarativedebugservice_p.h",
- "qdeclarativestate_p.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmljsdebugger/protocol"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmljsdebugger/protocol/"
- files: [
- "inspectorprotocol.h",
- "protocol.pri",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlobserver"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlobserver/"
- files: [
- "LGPL_EXCEPTION.TXT",
- "LICENSE.LGPL",
- "deviceorientation.cpp",
- "deviceorientation.h",
- "deviceorientation_harmattan.cpp",
- "deviceorientation_maemo5.cpp",
- "deviceorientation_symbian.cpp",
- "loggerwidget.cpp",
- "loggerwidget.h",
- "main.cpp",
- "proxysettings.cpp",
- "proxysettings.h",
- "proxysettings.ui",
- "proxysettings_maemo5.ui",
- "qdeclarativetester.cpp",
- "qdeclarativetester.h",
- "qml.icns",
- "qml.pri",
- "qmlobserver.pro",
- "qmlruntime.cpp",
- "qmlruntime.h",
- "recopts.ui",
- "recopts_maemo5.ui",
- "texteditautoresizer_maemo5.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlobserver/browser"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlobserver/browser/"
- files: [
- "Browser.qml",
- "browser.qrc",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlobserver/browser/images"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlobserver/browser/images/"
- files: [
- "folder.png",
- "titlebar.png",
- "titlebar.sci",
- "up.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlobserver/startup"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlobserver/startup/"
- files: [
- "Logo.qml",
- "qt-back.png",
- "qt-blue.jpg",
- "qt-front.png",
- "qt-sketch.jpg",
- "qt-text.png",
- "quick-blur.png",
- "quick-regular.png",
- "shadow.png",
- "startup.qml",
- "startup.qrc",
- "white-star.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/"
- files: [
- "qmlpuppet.pro",
- "qmlpuppet.qrc",
- "qmlpuppet_utilities.pri",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/commands"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/commands/"
- files: [
- "changeauxiliarycommand.cpp",
- "changeauxiliarycommand.h",
- "changebindingscommand.cpp",
- "changebindingscommand.h",
- "changefileurlcommand.cpp",
- "changefileurlcommand.h",
- "changeidscommand.cpp",
- "changeidscommand.h",
- "changenodesourcecommand.cpp",
- "changenodesourcecommand.h",
- "changestatecommand.cpp",
- "changestatecommand.h",
- "changevaluescommand.cpp",
- "changevaluescommand.h",
- "childrenchangedcommand.cpp",
- "childrenchangedcommand.h",
- "clearscenecommand.cpp",
- "clearscenecommand.h",
- "commands.pri",
- "completecomponentcommand.cpp",
- "completecomponentcommand.h",
- "componentcompletedcommand.cpp",
- "componentcompletedcommand.h",
- "createinstancescommand.cpp",
- "createinstancescommand.h",
- "createscenecommand.cpp",
- "createscenecommand.h",
- "informationchangedcommand.cpp",
- "informationchangedcommand.h",
- "pixmapchangedcommand.cpp",
- "pixmapchangedcommand.h",
- "removeinstancescommand.cpp",
- "removeinstancescommand.h",
- "removepropertiescommand.cpp",
- "removepropertiescommand.h",
- "reparentinstancescommand.cpp",
- "reparentinstancescommand.h",
- "statepreviewimagechangedcommand.cpp",
- "statepreviewimagechangedcommand.h",
- "synchronizecommand.cpp",
- "synchronizecommand.h",
- "tokencommand.cpp",
- "tokencommand.h",
- "valueschangedcommand.cpp",
- "valueschangedcommand.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/container"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/container/"
- files: [
- "addimportcontainer.cpp",
- "addimportcontainer.h",
- "container.pri",
- "idcontainer.cpp",
- "idcontainer.h",
- "imagecontainer.cpp",
- "imagecontainer.h",
- "informationcontainer.cpp",
- "informationcontainer.h",
- "instancecontainer.cpp",
- "instancecontainer.h",
- "propertyabstractcontainer.cpp",
- "propertyabstractcontainer.h",
- "propertybindingcontainer.cpp",
- "propertybindingcontainer.h",
- "propertyvaluecontainer.cpp",
- "propertyvaluecontainer.h",
- "reparentcontainer.cpp",
- "reparentcontainer.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/html"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/html/"
- files: [
- "welcome.html",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/images"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/images/"
- files: [
- "template_image.png",
- "webkit.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/instances"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/instances/"
- files: [
- "anchorchangesnodeinstance.cpp",
- "anchorchangesnodeinstance.h",
- "behaviornodeinstance.cpp",
- "behaviornodeinstance.h",
- "childrenchangeeventfilter.cpp",
- "childrenchangeeventfilter.h",
- "componentnodeinstance.cpp",
- "componentnodeinstance.h",
- "dummycontextobject.cpp",
- "dummycontextobject.h",
- "dummynodeinstance.cpp",
- "dummynodeinstance.h",
- "instances.pri",
- "nodeinstanceclientproxy.cpp",
- "nodeinstanceclientproxy.h",
- "nodeinstancemetaobject.cpp",
- "nodeinstancemetaobject.h",
- "nodeinstanceserver.cpp",
- "nodeinstanceserver.h",
- "nodeinstancesignalspy.cpp",
- "nodeinstancesignalspy.h",
- "objectnodeinstance.cpp",
- "objectnodeinstance.h",
- "qmlpropertychangesnodeinstance.cpp",
- "qmlpropertychangesnodeinstance.h",
- "qmlstatenodeinstance.cpp",
- "qmlstatenodeinstance.h",
- "qmltransitionnodeinstance.cpp",
- "qmltransitionnodeinstance.h",
- "servernodeinstance.cpp",
- "servernodeinstance.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/interfaces"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/interfaces/"
- files: [
- "commondefines.h",
- "interfaces.pri",
- "nodeinstanceclientinterface.h",
- "nodeinstanceserverinterface.cpp",
- "nodeinstanceserverinterface.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/qml2puppet"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/qml2puppet/"
- files: [
- "main.cpp",
- "qml2puppet.pro",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/qml2puppet/instances"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/qml2puppet/instances/"
- files: [
- "instances.pri",
- "qt5informationnodeinstanceserver.cpp",
- "qt5informationnodeinstanceserver.h",
- "qt5nodeinstanceclientproxy.cpp",
- "qt5nodeinstanceclientproxy.h",
- "qt5nodeinstanceserver.cpp",
- "qt5nodeinstanceserver.h",
- "qt5previewnodeinstanceserver.cpp",
- "qt5previewnodeinstanceserver.h",
- "qt5rendernodeinstanceserver.cpp",
- "qt5rendernodeinstanceserver.h",
- "sgitemnodeinstance.cpp",
- "sgitemnodeinstance.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/qmlpuppet"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/qmlpuppet/"
- files: [
- "main.cpp",
- "qmlpuppet.pri",
- "qmlpuppet.pro",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qml/qmlpuppet/qmlpuppet/instances"
- fileTags: ["install"]
- prefix: "qtcreator/qml/qmlpuppet/qmlpuppet/instances/"
- files: [
- "graphicsobjectnodeinstance.cpp",
- "graphicsobjectnodeinstance.h",
- "instances.pri",
- "positionernodeinstance.cpp",
- "positionernodeinstance.h",
- "qmlgraphicsitemnodeinstance.cpp",
- "qmlgraphicsitemnodeinstance.h",
- "qt4informationnodeinstanceserver.cpp",
- "qt4informationnodeinstanceserver.h",
- "qt4nodeinstanceclientproxy.cpp",
- "qt4nodeinstanceclientproxy.h",
- "qt4nodeinstanceserver.cpp",
- "qt4nodeinstanceserver.h",
- "qt4previewnodeinstanceserver.cpp",
- "qt4previewnodeinstanceserver.h",
- "qt4rendernodeinstanceserver.cpp",
- "qt4rendernodeinstanceserver.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qmldesigner/propertyeditor/Qt"
- fileTags: ["install"]
- prefix: "qtcreator/qmldesigner/propertyeditor/Qt/"
- files: [
- "AlignmentHorizontalButtons.qml",
- "AlignmentVerticalButtons.qml",
- "AnchorBox.qml",
- "AnchorButtons.qml",
- "BorderImageSpecifics.qml",
- "CheckBox.qml",
- "ColorGroupBox.qml",
- "ColorLabel.qml",
- "ColorScheme.qml",
- "ColorTypeButtons.qml",
- "ComboBox.qml",
- "DoubleSpinBox.qml",
- "DoubleSpinBoxAlternate.qml",
- "ExpressionEditor.qml",
- "Extended.qml",
- "ExtendedFunctionButton.qml",
- "ExtendedPane.qml",
- "ExtendedSwitches.qml",
- "FlagedButton.qml",
- "FlickableGroupBox.qml",
- "FlickableSpecifics.qml",
- "FlipableSpecifics.qml",
- "FlowSpecifics.qml",
- "FontComboBox.qml",
- "FontGroupBox.qml",
- "FontStyleButtons.qml",
- "Geometry.qml",
- "GridSpecifics.qml",
- "GridViewSpecifics.qml",
- "GroupBox.qml",
- "GroupBoxOption.qml",
- "HorizontalLayout.qml",
- "HorizontalWhiteLine.qml",
- "ImageSpecifics.qml",
- "IntEditor.qml",
- "ItemPane.qml",
- "Label.qml",
- "Layout.qml",
- "LayoutPane.qml",
- "LineEdit.qml",
- "ListViewSpecifics.qml",
- "Modifiers.qml",
- "MouseAreaSpecifics.qml",
- "PathViewSpecifics.qml",
- "PlaceHolder.qml",
- "PropertyFrame.qml",
- "RectangleColorGroupBox.qml",
- "RectangleSpecifics.qml",
- "RowSpecifics.qml",
- "ScrollArea.qml",
- "SliderWidget.qml",
- "SpinBox.qml",
- "StandardTextColorGroupBox.qml",
- "StandardTextGroupBox.qml",
- "Switches.qml",
- "TextEditSpecifics.qml",
- "TextEditor.qml",
- "TextInputGroupBox.qml",
- "TextInputSpecifics.qml",
- "TextSpecifics.qml",
- "Transformation.qml",
- "Type.qml",
- "VerticalLayout.qml",
- "Visibility.qml",
- "anchorbottom.css",
- "anchorbox.css",
- "anchorfill.css",
- "anchorhorizontal.css",
- "anchorleft.css",
- "anchorright.css",
- "anchorspacer.css",
- "anchortop.css",
- "anchorvertical.css",
- "applybutton.css",
- "aspectlock.css",
- "cancelbutton.css",
- "checkbox_tr.css",
- "emptyPane.qml",
- "layoutWidget.css",
- "propertyEditor.css",
- "specialCheckBox.css",
- "styledbuttonleft.css",
- "styledbuttonmiddle.css",
- "styledbuttonright.css",
- "switch.css",
- "typeLabel.css",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qmldesigner/propertyeditor/Qt/images"
- fileTags: ["install"]
- prefix: "qtcreator/qmldesigner/propertyeditor/Qt/images/"
- files: [
- "alignmentbottom-h-icon.png",
- "alignmentbottom-icon.png",
- "alignmentcenterh-h-icon.png",
- "alignmentcenterh-icon.png",
- "alignmentleft-h-icon.png",
- "alignmentleft-icon.png",
- "alignmentmiddle-h-icon.png",
- "alignmentmiddle-icon.png",
- "alignmentright-h-icon.png",
- "alignmentright-icon.png",
- "alignmenttop-h-icon.png",
- "alignmenttop-icon.png",
- "apply.png",
- "behaivour.png",
- "blended-image-icon.png",
- "bold-h-icon.png",
- "bold-icon.png",
- "button.png",
- "cancel.png",
- "default-icon.png",
- "downArrow.png",
- "expression.png",
- "extended.png",
- "grid-icon.png",
- "icon_color_gradient.png",
- "icon_color_none.png",
- "icon_color_solid.png",
- "image-icon.png",
- "italic-h-icon.png",
- "italic-icon.png",
- "item-icon.png",
- "layout.png",
- "leftArrow.png",
- "list-icon.png",
- "mouse-area-icon.png",
- "placeholder.png",
- "rect-icon.png",
- "reset-button.png",
- "rightArrow.png",
- "standard.png",
- "strikeout-h-icon.png",
- "strikeout-icon.png",
- "submenu.png",
- "text-edit-icon.png",
- "text-icon.png",
- "underline-h-icon.png",
- "underline-icon.png",
- "upArrow.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qmldesigner/propertyeditor/QtWebKit"
- fileTags: ["install"]
- prefix: "qtcreator/qmldesigner/propertyeditor/QtWebKit/"
- files: [
- "WebViewSpecifics.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qmlicons/Qt/16x16"
- fileTags: ["install"]
- prefix: "qtcreator/qmlicons/Qt/16x16/"
- files: [
- "BorderImage.png",
- "BusyIndicator.png",
- "Button.png",
- "ButtonColumn.png",
- "ButtonRow.png",
- "CheckBox.png",
- "ChoiceList.png",
- "ColorAnimation.png",
- "Component.png",
- "CountBubble.png",
- "DatePickerDialog.png",
- "Flickable.png",
- "Flipable.png",
- "FocusScope.png",
- "GridView.png",
- "Image.png",
- "InfoBanner.png",
- "Item.png",
- "ListButton.png",
- "ListDelegate.png",
- "ListView.png",
- "MoreIndicator.png",
- "MouseArea.png",
- "PageIndicator.png",
- "ParallelAnimation.png",
- "PathView.png",
- "PauseAnimation.png",
- "ProgressBar.png",
- "PropertyChanges.png",
- "RadioButton.png",
- "RatingIndicator.png",
- "Rectangle.png",
- "SequentialAnimation.png",
- "Slider.png",
- "State.png",
- "Switch.png",
- "TabBar.png",
- "TabButton.png",
- "Text.png",
- "TextArea.png",
- "TextEdit.png",
- "TextField.png",
- "TextInput.png",
- "TimePickerDialog.png",
- "ToolBar.png",
- "Transition.png",
- "Tumbler.png",
- "TumblerButton.png",
- "TumblerColumn.png",
- "TumblerDialog.png",
- "Window.png",
- "item-icon16.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/qmlicons/QtWebkit/16x16"
- fileTags: ["install"]
- prefix: "qtcreator/qmlicons/QtWebkit/16x16/"
- files: [
- "WebView.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/schemes"
- fileTags: ["install"]
- prefix: "qtcreator/schemes/"
- files: [
- "MS_Visual_C++.kms",
- "Xcode.kms",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/snippets"
- fileTags: ["install"]
- prefix: "qtcreator/snippets/"
- files: [
- "cpp.xml",
- "qml.xml",
- "text.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/styles"
- fileTags: ["install"]
- prefix: "qtcreator/styles/"
- files: [
- "darkvim.xml",
- "default.xml",
- "grayscale.xml",
- "inkpot.xml",
- "intellij.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/html5app"
- fileTags: ["install"]
- prefix: "qtcreator/templates/html5app/"
- files: [
- "app.pro",
- "main.cpp",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/html5app/html"
- fileTags: ["install"]
- prefix: "qtcreator/templates/html5app/html/"
- files: [
- "index.html",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/html5app/html5applicationviewer"
- fileTags: ["install"]
- prefix: "qtcreator/templates/html5app/html5applicationviewer/"
- files: [
- "html5applicationviewer.cpp",
- "html5applicationviewer.h",
- "html5applicationviewer.pri",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/html5app/html5applicationviewer/touchnavigation"
- fileTags: ["install"]
- prefix: "qtcreator/templates/html5app/html5applicationviewer/touchnavigation/"
- files: [
- "navigationcontroller.cpp",
- "navigationcontroller.h",
- "touchnavigation.pri",
- "webnavigation.cpp",
- "webnavigation.h",
- "webtouchevent.cpp",
- "webtouchevent.h",
- "webtouchnavigation.cpp",
- "webtouchnavigation.h",
- "webtouchphysics.cpp",
- "webtouchphysics.h",
- "webtouchphysicsinterface.cpp",
- "webtouchphysicsinterface.h",
- "webtouchscroller.cpp",
- "webtouchscroller.h",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/mobileapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/mobileapp/"
- files: [
- "app.pro",
- "main.cpp",
- "mainwindow.cpp",
- "mainwindow.h",
- "mainwindow.ui",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qt4project"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qt4project/"
- files: [
- "main.cpp",
- "mywidget.cpp",
- "mywidget.h",
- "mywidget_form.cpp",
- "mywidget_form.h",
- "widget.ui",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qt4project/customwidgetwizard"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qt4project/customwidgetwizard/"
- files: [
- "tpl_collection.cpp",
- "tpl_collection.h",
- "tpl_plugin.pro",
- "tpl_resources.qrc",
- "tpl_single.cpp",
- "tpl_single.h",
- "tpl_widget.cpp",
- "tpl_widget.h",
- "tpl_widget_include.pri",
- "tpl_widget_lib.pro",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquick2app"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquick2app/"
- files: [
- "app.pro",
- "main.cpp",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquick2app/qml/app/qtquick20"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquick2app/qml/app/qtquick20/"
- files: [
- "main.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquick2app/qtquick2applicationviewer"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquick2app/qtquick2applicationviewer/"
- files: [
- "qtquick2applicationviewer.cpp",
- "qtquick2applicationviewer.h",
- "qtquick2applicationviewer.pri",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquickapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquickapp/"
- files: [
- "app.pro",
- "main.cpp",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquickapp/qml/app/meego10"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquickapp/qml/app/meego10/"
- files: [
- "MainPage.qml",
- "main.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquickapp/qml/app/qtquick10"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquickapp/qml/app/qtquick10/"
- files: [
- "main.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/qtquickapp/qmlapplicationviewer"
- fileTags: ["install"]
- prefix: "qtcreator/templates/qtquickapp/qmlapplicationviewer/"
- files: [
- "qmlapplicationviewer.cpp",
- "qmlapplicationviewer.h",
- "qmlapplicationviewer.pri",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/shared"
- fileTags: ["install"]
- prefix: "qtcreator/templates/shared/"
- files: [
- "app.desktop",
- "deployment.pri",
- "icon64.png",
- "icon80.png",
- "manifest.aegis",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/"
- files: [
- "README.txt",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-bardescriptor"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-bardescriptor/"
- files: [
- "bar-descriptor.xml",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-guiapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-guiapp/"
- files: [
- "bar-descriptor.xml",
- "icon.png",
- "main.cpp",
- "mainwidget.cpp",
- "mainwidget.h",
- "mainwidget.ui",
- "project.pro",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-qt5-bardescriptor"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-qt5-bardescriptor/"
- files: [
- "bar-descriptor.xml",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-qt5-guiapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-qt5-guiapp/"
- files: [
- "bar-descriptor.xml",
- "icon.png",
- "main.cpp",
- "mainwidget.cpp",
- "mainwidget.h",
- "mainwidget.ui",
- "project.pro",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-qt5-quick2app"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-qt5-quick2app/"
- files: [
- "bar-descriptor.xml",
- "icon.png",
- "main.cpp",
- "project.pro",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-qt5-quick2app/qml"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-qt5-quick2app/qml/"
- files: [
- "main.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-quickapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-quickapp/"
- files: [
- "bar-descriptor.xml",
- "icon.png",
- "main.cpp",
- "project.pro",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/bb-quickapp/qml"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/bb-quickapp/qml/"
- files: [
- "main.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/helloworld"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/helloworld/"
- files: [
- "console.png",
- "main.cpp",
- "project.pro",
- "wizard_sample.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/listmodel"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/listmodel/"
- files: [
- "listmodel.cpp",
- "listmodel.h",
- "wizard_sample.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/plaincapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/plaincapp/"
- files: [
- "console.png",
- "main.c",
- "project.pro",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/plaincapp-cmake"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/plaincapp-cmake/"
- files: [
- "CMakeLists.txt",
- "console.png",
- "main.c",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/plaincppapp"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/plaincppapp/"
- files: [
- "console.png",
- "main.cpp",
- "project.pro",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/plaincppapp-cmake"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/plaincppapp-cmake/"
- files: [
- "CMakeLists.txt",
- "console.png",
- "main.cpp",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/qtquick1-extension"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/qtquick1-extension/"
- files: [
- "lib.png",
- "object.cpp",
- "object.h",
- "plugin.cpp",
- "plugin.h",
- "project.pro",
- "qmldir",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/qtquick2-extension"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/qtquick2-extension/"
- files: [
- "lib.png",
- "object.cpp",
- "object.h",
- "plugin.cpp",
- "plugin.h",
- "project.pro",
- "qmldir",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/qtcreatorplugin"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/qtcreatorplugin/"
- files: [
- "MyPlugin.pluginspec.in",
- "myplugin.cpp",
- "myplugin.h",
- "myplugin.pro",
- "myplugin_global.h",
- "mypluginconstants.h",
- "qtcreator_logo_24.png",
- "wizard.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/templates/wizards/scriptgeneratedproject"
- fileTags: ["install"]
- prefix: "qtcreator/templates/wizards/scriptgeneratedproject/"
- files: [
- "generate.pl",
- "wizard_sample.xml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/"
- files: [
- "develop.qml",
- "examples.qml",
- "examples_fallback.xml",
- "gettingstarted.qml",
- "images_areaofinterest.xml",
- "qtcreator_tutorials.xml",
- "tutorials.qml",
- "welcomescreen.qml",
- "welcomescreen.qmlproject",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/dummydata"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/dummydata/"
- files: [
- "examplesModel.qml",
- "pagesModel.qml",
- "projectList.qml",
- "sessionList.qml",
- "tutorialsModel.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/widgets"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/widgets/"
- files: [
- "CustomColors.qml",
- "CustomFonts.qml",
- "CustomTab.qml",
- "CustomizedGridView.qml",
- "Delegate.qml",
- "GettingStartedItem.qml",
- "IconAndLink.qml",
- "LinkedText.qml",
- "LinksBar.qml",
- "Logo.qml",
- "PageCaption.qml",
- "PageLoader.qml",
- "ProjectItem.qml",
- "RecentProjects.qml",
- "SearchBar.qml",
- "SessionItem.qml",
- "Sessions.qml",
- "ToolTip.qml",
- "qmldir",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/widgets/dummydata"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/widgets/dummydata/"
- files: [
- "examplesModel.qml",
- "mockupTags.qml",
- "pagesModel.qml",
- "tabsModel.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/widgets/dummydata/context"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/widgets/dummydata/context/"
- files: [
- "ExampleDelegate.qml",
- "ExampleGridView.qml",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/widgets/images"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/widgets/images/"
- files: [
- "arrowBig.png",
- "arrow_down.png",
- "arrow_up.png",
- "bullet.png",
- "dropshadow.png",
- "gettingStarted01.png",
- "gettingStarted02.png",
- "gettingStarted03.png",
- "gettingStarted04.png",
- "info.png",
- "more.png",
- "qtcreator.png",
- "tab.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/widgets/images/icons"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/widgets/images/icons/"
- files: [
- "adressbook.png",
- "buildrun.png",
- "clone.png",
- "communityIcon.png",
- "components.png",
- "createIcon.png",
- "ddays09.png",
- "ddays10.png",
- "ddays11.png",
- "delete.png",
- "developing_with_qt_creator.png",
- "feedbackIcon.png",
- "ico_community.png",
- "labsIcon.png",
- "openIcon.png",
- "qt_quick_1.png",
- "qt_quick_2.png",
- "qt_quick_3.png",
- "qt_sdk.png",
- "qtquick.png",
- "qwidget.png",
- "rename.png",
- "userguideIcon.png",
- "videoIcon.png",
- ]
- }
-
- Group {
- qbs.installDir: "share/qtcreator/welcomescreen/widgets/images/mockup"
- fileTags: ["install"]
- prefix: "qtcreator/welcomescreen/widgets/images/mockup/"
- files: [
- "designer-examples.png",
- "desktop-examples.png",
- "draganddrop-examples.png",
- "itemview-examples.png",
- "layout-examples.png",
- "mainwindow-examples.png",
- "network-examples.png",
- "opengl-examples.png",
- "penguin.png",
- "qtscript-examples.png",
- "thread-examples.png",
- ]
+ qbs.install: true
+ qbs.installDir: "share/qtcreator"
+ prefix: "qtcreator/"
+ files: [
+ "designer",
+ "dumper",
+ "generic-highlighter",
+ "glsl",
+ "qml",
+ "qmldesigner",
+ "qmlicons",
+ "qml-type-descriptions",
+ "schemes",
+ "snippets",
+ "styles",
+ "templates",
+ "welcomescreen"
+ ]
+ }
+
+ Group {
+ qbs.install: true
+ qbs.installDir: "share/qtcreator/externaltools"
+ prefix: "../src/share/qtcreator/externaltools/"
+ files: {
+ var list = [
+ "lrelease.xml",
+ "lupdate.xml",
+ "qmlviewer.xml",
+ "sort.xml",
+ ]
+ switch (qbs.targetOS) {
+ case "windows":
+ list.push("notepad_win.xml");
+ break;
+ case "mac":
+ list.push("vi_mac.xml");
+ break;
+ default:
+ list.push("vi.xml");
+ }
+ return list;
+ }
}
}
diff --git a/share/update-share-qbs.py b/share/update-share-qbs.py
deleted file mode 100755
index 2ff480c143..0000000000
--- a/share/update-share-qbs.py
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/env python
-#
-# Script for automatically updating share.qbs
-# Usage: Just call it without arguments.
-#
-
-import os
-import posixpath as path
-import inspect
-
-scriptFileName = path.basename(inspect.getfile(inspect.currentframe()))
-shareDirPath = path.dirname(inspect.getfile(inspect.currentframe()))
-print "updating " + shareDirPath + "/share.qbs"
-
-os.chdir(shareDirPath)
-try:
- f = open('share.qbs', 'w')
-except:
- print "Could not open share.qbs"
- quit(1)
-
-def writeln(line):
- f.write(line)
- f.write("\n")
-
-writeln("import qbs.base 1.0")
-writeln("")
-writeln("Product {")
-writeln(" type: [\"installed_content\"]")
-writeln(" name: \"SharedContent\"")
-writeln("")
-writeln(" Group {")
-writeln(" condition: qbs.targetOS == \"macx\"")
-writeln(" qbs.installDir: \"share/qtcreator/scripts\"")
-writeln(" fileTags: [\"install\"]")
-writeln(" files: \"qtcreator/scripts/openTerminal.command\"")
-writeln(" }")
-
-filenamedict = {}
-blacklist = [
- scriptFileName,
- "static.pro", "share.pro", "share.qbs",
- "Info.plist.in"
-]
-blacklistdirs = [
- "qtcreator/translations",
- "qtcreator/scripts"
-]
-for root, dirs, files in os.walk("."):
- try:
- dirs.remove('.moc')
- dirs.remove('.rcc')
- dirs.remove('.uic')
- dirs.remove('.obj')
- except: pass
-
- root = root.replace('\\', '/')
- if root.startswith("./"):
- root = path.normpath(root[2:])
- if root in blacklistdirs:
- continue
- for file in files:
- if not (file in blacklist):
- if not root in filenamedict:
- filenamedict[root] = [file]
- else:
- filenamedict[root].append(file)
-
-for directory in sorted(filenamedict.iterkeys()):
- prefix = directory
- if not prefix.endswith("/"):
- prefix += "/"
- normalizedDirectory = path.normpath(directory.replace('\\', '/'))
- writeln("")
- writeln(" Group {")
- writeln(" qbs.installDir: \"share/" + normalizedDirectory + "\"")
- writeln(" fileTags: [\"install\"]")
- writeln(" prefix: \"" + prefix + "\"")
- writeln(" files: [")
- for fname in sorted(filenamedict[directory]):
- writeln(" \"" + fname + "\",")
- writeln(" ]")
- writeln(" }")
-
-writeln("}")
-writeln("")
-
diff --git a/src/app/app.pro b/src/app/app.pro
index a2a666dd1d..1242209065 100644
--- a/src/app/app.pro
+++ b/src/app/app.pro
@@ -5,7 +5,8 @@ TEMPLATE = app
TARGET = $$IDE_APP_TARGET
DESTDIR = $$IDE_APP_PATH
-SOURCES += main.cpp
+HEADERS += ../tools/qtcreatorcrashhandler/crashhandlersetup.h
+SOURCES += main.cpp ../tools/qtcreatorcrashhandler/crashhandlersetup.cpp
include(../rpath.pri)
@@ -38,3 +39,5 @@ OTHER_FILES += qtcreator.rc \
$$PWD/app_version.h.in
QMAKE_SUBSTITUTES += $$PWD/app_version.h.in
+
+CONFIG += no_batch
diff --git a/src/app/main.cpp b/src/app/main.cpp
index 1e22fe2212..6257e5e367 100644
--- a/src/app/main.cpp
+++ b/src/app/main.cpp
@@ -28,6 +28,7 @@
****************************************************************************/
#include "qtsingleapplication.h"
+#include "../tools/qtcreatorcrashhandler/crashhandlersetup.h"
#include <app/app_version.h>
#include <extensionsystem/iplugin.h>
@@ -295,7 +296,7 @@ int main(int argc, char **argv)
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
// QML is unusable with the xlib backend
- QApplication::setGraphicsSystem("raster");
+ QApplication::setGraphicsSystem(QLatin1String("raster"));
#endif
SharedTools::QtSingleApplication app((QLatin1String(appNameC)), argc, argv);
@@ -303,6 +304,8 @@ int main(int argc, char **argv)
const int threadCount = QThreadPool::globalInstance()->maxThreadCount();
QThreadPool::globalInstance()->setMaxThreadCount(qMax(4, 2 * threadCount));
+ setupCrashHandler(); // Display a backtrace once a serious signal is delivered.
+
#ifdef ENABLE_QT_BREAKPAD
QtSystemExceptionHandler systemExceptionHandler;
#endif
@@ -350,7 +353,7 @@ int main(int argc, char **argv)
#else
uiLanguages << QLocale::system().name();
#endif
- QString overrideLanguage = settings->value("General/OverrideLanguage").toString();
+ QString overrideLanguage = settings->value(QLatin1String("General/OverrideLanguage")).toString();
if (!overrideLanguage.isEmpty())
uiLanguages.prepend(overrideLanguage);
const QString &creatorTrPath = QCoreApplication::applicationDirPath()
@@ -470,7 +473,7 @@ int main(int argc, char **argv)
if (app.isRunning(pid)) {
// Nah app is still running, ask the user
int button = askMsgSendFailed();
- while(button == QMessageBox::Retry) {
+ while (button == QMessageBox::Retry) {
if (app.sendMessage(PluginManager::serializedArguments(), 5000 /*timeout*/, pid))
return 0;
if (!app.isRunning(pid)) // App quit while we were trying so start a new creator
@@ -510,5 +513,7 @@ int main(int argc, char **argv)
QTimer::singleShot(100, &pluginManager, SLOT(startTests()));
#endif
- return app.exec();
+ const int r = app.exec();
+ cleanupCrashHandler();
+ return r;
}
diff --git a/src/libs/3rdparty/botan/botan.cpp b/src/libs/3rdparty/botan/botan.cpp
index 4431ce17fb..000c3ea823 100644
--- a/src/libs/3rdparty/botan/botan.cpp
+++ b/src/libs/3rdparty/botan/botan.cpp
@@ -47182,44 +47182,3 @@ u32bit version_minor() { return BOTAN_VERSION_MINOR; }
u32bit version_patch() { return BOTAN_VERSION_PATCH; }
}
-
-namespace Botan {
-PublicKeyPtr createRsaPublicKey(const BigInt &e, const BigInt &n)
-{
- return PublicKeyPtr(new RSA_PublicKey(e, n));
-}
-
-PublicKeyPtr createDsaPublicKey(const DL_Group &group, const BigInt &y)
-{
- return PublicKeyPtr(new DSA_PublicKey(group, y));
-}
-
-PrivateKeyPtr createRsaPrivateKey(RandomNumberGenerator &rng, const BigInt &p, const BigInt &q,
- const BigInt &e, const BigInt &d, const BigInt &n)
-{
- return PrivateKeyPtr(new RSA_PrivateKey(rng, p, q, e, d, n));
-}
-
-PrivateKeyPtr createRsaPrivateKey(RandomNumberGenerator &rng, size_t bits, size_t exp)
-{
- return PrivateKeyPtr(new RSA_PrivateKey(rng, bits, exp));
-}
-
-PrivateKeyPtr createDsaPrivateKey(RandomNumberGenerator &rng, const DL_Group &group,
- const BigInt &private_key)
-{
- return PrivateKeyPtr(new DSA_PrivateKey(rng, group, private_key));
-}
-
-PrivateKeyPtr loadPkcs8PrivateKey(DataSource& source, RandomNumberGenerator& rng,
- const User_Interface& ui)
-{
- return PrivateKeyPtr(PKCS8::load_key(source, rng, ui));
-}
-
-DhPrivateKeyPtr createDhPrivateKey(RandomNumberGenerator &rng, const DL_Group &grp, const BigInt &x)
-{
- return DhPrivateKeyPtr(new DH_PrivateKey(rng, grp, x));
-}
-
-}
diff --git a/src/libs/3rdparty/botan/botan.h b/src/libs/3rdparty/botan/botan.h
index 13ec9fd00b..a073890986 100644
--- a/src/libs/3rdparty/botan/botan.h
+++ b/src/libs/3rdparty/botan/botan.h
@@ -9,7 +9,6 @@
#define BOTAN_AMALGAMATION_H__
#include <QtGlobal>
-#include <QSharedPointer>
#include <iosfwd>
#include <map>
@@ -16182,26 +16181,7 @@ class BOTAN_DLL ANSI_X919_MAC : public MessageAuthenticationCode
SecureVector<byte> state;
size_t position;
};
-}
-
-namespace Botan {
-typedef QSharedPointer<Public_Key> PublicKeyPtr;
-BOTAN_DLL PublicKeyPtr createRsaPublicKey(const BigInt &e, const BigInt &n);
-BOTAN_DLL PublicKeyPtr createDsaPublicKey(const DL_Group& group, const BigInt& y);
-
-typedef QSharedPointer<Private_Key> PrivateKeyPtr;
-BOTAN_DLL PrivateKeyPtr createRsaPrivateKey(RandomNumberGenerator& rng, const BigInt& p,
- const BigInt& q, const BigInt& e, const BigInt& d = 0, const BigInt& n = 0);
-BOTAN_DLL PrivateKeyPtr createRsaPrivateKey(RandomNumberGenerator& rng, size_t bits,
- size_t exp = 65537);
-BOTAN_DLL PrivateKeyPtr createDsaPrivateKey(RandomNumberGenerator& rng, const DL_Group& group,
- const BigInt& private_key = 0);
-BOTAN_DLL PrivateKeyPtr loadPkcs8PrivateKey(DataSource& source, RandomNumberGenerator& rng,
- const User_Interface& ui);
-typedef QSharedPointer<DH_PrivateKey> DhPrivateKeyPtr;
-BOTAN_DLL DhPrivateKeyPtr createDhPrivateKey(RandomNumberGenerator& rng, const DL_Group& grp,
- const BigInt& x = 0);
}
diff --git a/src/libs/3rdparty/botan/botan.pri b/src/libs/3rdparty/botan/botan.pri
index 1088c99732..ee2a167f1f 100644
--- a/src/libs/3rdparty/botan/botan.pri
+++ b/src/libs/3rdparty/botan/botan.pri
@@ -18,6 +18,8 @@ macx:DEFINES += BOTAN_TARGET_OS_IS_DARWIN
*clang*:DEFINES += BOTAN_BUILD_COMPILER_IS_CLANG
*icc*:DEFINES += BOTAN_BUILD_COMPILER_IS_INTEL
+CONFIG(x86_64):DEFINES += BOTAN_TARGET_ARCH_IS_X86_64
+
win32 {
DEFINES += BOTAN_TARGET_OS_IS_WINDOWS \
BOTAN_TARGET_OS_HAS_LOADLIBRARY BOTAN_TARGET_OS_HAS_WIN32_GET_SYSTEMTIME \
diff --git a/src/libs/3rdparty/cplusplus/AST.cpp b/src/libs/3rdparty/cplusplus/AST.cpp
index 31cacbcc43..13c4568fb7 100644
--- a/src/libs/3rdparty/cplusplus/AST.cpp
+++ b/src/libs/3rdparty/cplusplus/AST.cpp
@@ -403,12 +403,22 @@ unsigned CallAST::lastToken() const
/** \generated */
unsigned CaptureAST::firstToken() const
{
+ if (amper_token)
+ return amper_token;
+ if (identifier)
+ if (unsigned candidate = identifier->firstToken())
+ return candidate;
return 0;
}
/** \generated */
unsigned CaptureAST::lastToken() const
{
+ if (identifier)
+ if (unsigned candidate = identifier->lastToken())
+ return candidate;
+ if (amper_token)
+ return amper_token + 1;
return 1;
}
@@ -1077,9 +1087,16 @@ unsigned EnumSpecifierAST::firstToken() const
{
if (enum_token)
return enum_token;
+ if (key_token)
+ return key_token;
if (name)
if (unsigned candidate = name->firstToken())
return candidate;
+ if (colon_token)
+ return colon_token;
+ if (type_specifier_list)
+ if (unsigned candidate = type_specifier_list->firstToken())
+ return candidate;
if (lbrace_token)
return lbrace_token;
if (enumerator_list)
@@ -1104,9 +1121,16 @@ unsigned EnumSpecifierAST::lastToken() const
return candidate;
if (lbrace_token)
return lbrace_token + 1;
+ if (type_specifier_list)
+ if (unsigned candidate = type_specifier_list->lastToken())
+ return candidate;
+ if (colon_token)
+ return colon_token + 1;
if (name)
if (unsigned candidate = name->lastToken())
return candidate;
+ if (key_token)
+ return key_token + 1;
if (enum_token)
return enum_token + 1;
return 1;
@@ -1369,6 +1393,8 @@ unsigned FunctionDeclaratorAST::firstToken() const
if (cv_qualifier_list)
if (unsigned candidate = cv_qualifier_list->firstToken())
return candidate;
+ if (ref_qualifier_token)
+ return ref_qualifier_token;
if (exception_specification)
if (unsigned candidate = exception_specification->firstToken())
return candidate;
@@ -1393,6 +1419,8 @@ unsigned FunctionDeclaratorAST::lastToken() const
if (exception_specification)
if (unsigned candidate = exception_specification->lastToken())
return candidate;
+ if (ref_qualifier_token)
+ return ref_qualifier_token + 1;
if (cv_qualifier_list)
if (unsigned candidate = cv_qualifier_list->lastToken())
return candidate;
@@ -1744,26 +1772,18 @@ unsigned MemInitializerAST::firstToken() const
if (name)
if (unsigned candidate = name->firstToken())
return candidate;
- if (lparen_token)
- return lparen_token;
- if (expression_list)
- if (unsigned candidate = expression_list->firstToken())
+ if (expression)
+ if (unsigned candidate = expression->firstToken())
return candidate;
- if (rparen_token)
- return rparen_token;
return 0;
}
/** \generated */
unsigned MemInitializerAST::lastToken() const
{
- if (rparen_token)
- return rparen_token + 1;
- if (expression_list)
- if (unsigned candidate = expression_list->lastToken())
+ if (expression)
+ if (unsigned candidate = expression->lastToken())
return candidate;
- if (lparen_token)
- return lparen_token + 1;
if (name)
if (unsigned candidate = name->lastToken())
return candidate;
@@ -2043,33 +2063,7 @@ unsigned NewExpressionAST::lastToken() const
}
/** \generated */
-unsigned NewInitializerAST::firstToken() const
-{
- if (lparen_token)
- return lparen_token;
- if (expression)
- if (unsigned candidate = expression->firstToken())
- return candidate;
- if (rparen_token)
- return rparen_token;
- return 0;
-}
-
-/** \generated */
-unsigned NewInitializerAST::lastToken() const
-{
- if (rparen_token)
- return rparen_token + 1;
- if (expression)
- if (unsigned candidate = expression->lastToken())
- return candidate;
- if (lparen_token)
- return lparen_token + 1;
- return 1;
-}
-
-/** \generated */
-unsigned NewPlacementAST::firstToken() const
+unsigned ExpressionListParenAST::firstToken() const
{
if (lparen_token)
return lparen_token;
@@ -2082,7 +2076,7 @@ unsigned NewPlacementAST::firstToken() const
}
/** \generated */
-unsigned NewPlacementAST::lastToken() const
+unsigned ExpressionListParenAST::lastToken() const
{
if (rparen_token)
return rparen_token + 1;
@@ -3075,12 +3069,16 @@ unsigned PointerToMemberAST::firstToken() const
if (cv_qualifier_list)
if (unsigned candidate = cv_qualifier_list->firstToken())
return candidate;
+ if (ref_qualifier_token)
+ return ref_qualifier_token;
return 0;
}
/** \generated */
unsigned PointerToMemberAST::lastToken() const
{
+ if (ref_qualifier_token)
+ return ref_qualifier_token + 1;
if (cv_qualifier_list)
if (unsigned candidate = cv_qualifier_list->lastToken())
return candidate;
@@ -3910,26 +3908,18 @@ unsigned TypeConstructorCallAST::firstToken() const
if (type_specifier_list)
if (unsigned candidate = type_specifier_list->firstToken())
return candidate;
- if (lparen_token)
- return lparen_token;
- if (expression_list)
- if (unsigned candidate = expression_list->firstToken())
+ if (expression)
+ if (unsigned candidate = expression->firstToken())
return candidate;
- if (rparen_token)
- return rparen_token;
return 0;
}
/** \generated */
unsigned TypeConstructorCallAST::lastToken() const
{
- if (rparen_token)
- return rparen_token + 1;
- if (expression_list)
- if (unsigned candidate = expression_list->lastToken())
+ if (expression)
+ if (unsigned candidate = expression->lastToken())
return candidate;
- if (lparen_token)
- return lparen_token + 1;
if (type_specifier_list)
if (unsigned candidate = type_specifier_list->lastToken())
return candidate;
@@ -3998,26 +3988,18 @@ unsigned TypenameCallExpressionAST::firstToken() const
if (name)
if (unsigned candidate = name->firstToken())
return candidate;
- if (lparen_token)
- return lparen_token;
- if (expression_list)
- if (unsigned candidate = expression_list->firstToken())
+ if (expression)
+ if (unsigned candidate = expression->firstToken())
return candidate;
- if (rparen_token)
- return rparen_token;
return 0;
}
/** \generated */
unsigned TypenameCallExpressionAST::lastToken() const
{
- if (rparen_token)
- return rparen_token + 1;
- if (expression_list)
- if (unsigned candidate = expression_list->lastToken())
+ if (expression)
+ if (unsigned candidate = expression->lastToken())
return candidate;
- if (lparen_token)
- return lparen_token + 1;
if (name)
if (unsigned candidate = name->lastToken())
return candidate;
@@ -4362,9 +4344,6 @@ unsigned RangeBasedForStatementAST::firstToken() const
if (declarator)
if (unsigned candidate = declarator->firstToken())
return candidate;
- if (initializer)
- if (unsigned candidate = initializer->firstToken())
- return candidate;
if (colon_token)
return colon_token;
if (expression)
@@ -4391,9 +4370,6 @@ unsigned RangeBasedForStatementAST::lastToken() const
return candidate;
if (colon_token)
return colon_token + 1;
- if (initializer)
- if (unsigned candidate = initializer->lastToken())
- return candidate;
if (declarator)
if (unsigned candidate = declarator->lastToken())
return candidate;
@@ -4407,3 +4383,67 @@ unsigned RangeBasedForStatementAST::lastToken() const
return 1;
}
+/** \generated */
+unsigned AlignofExpressionAST::firstToken() const
+{
+ if (alignof_token)
+ return alignof_token;
+ if (lparen_token)
+ return lparen_token;
+ if (typeId)
+ if (unsigned candidate = typeId->firstToken())
+ return candidate;
+ if (rparen_token)
+ return rparen_token;
+ return 0;
+}
+
+/** \generated */
+unsigned AlignofExpressionAST::lastToken() const
+{
+ if (rparen_token)
+ return rparen_token + 1;
+ if (typeId)
+ if (unsigned candidate = typeId->lastToken())
+ return candidate;
+ if (lparen_token)
+ return lparen_token + 1;
+ if (alignof_token)
+ return alignof_token + 1;
+ return 1;
+}
+
+/** \generated */
+unsigned AliasDeclarationAST::firstToken() const
+{
+ if (using_token)
+ return using_token;
+ if (identifier_token)
+ return identifier_token;
+ if (equal_token)
+ return equal_token;
+ if (typeId)
+ if (unsigned candidate = typeId->firstToken())
+ return candidate;
+ if (semicolon_token)
+ return semicolon_token;
+ return 0;
+}
+
+/** \generated */
+unsigned AliasDeclarationAST::lastToken() const
+{
+ if (semicolon_token)
+ return semicolon_token + 1;
+ if (typeId)
+ if (unsigned candidate = typeId->lastToken())
+ return candidate;
+ if (equal_token)
+ return equal_token + 1;
+ if (identifier_token)
+ return identifier_token + 1;
+ if (using_token)
+ return using_token + 1;
+ return 1;
+}
+
diff --git a/src/libs/3rdparty/cplusplus/AST.h b/src/libs/3rdparty/cplusplus/AST.h
index 24e031c72e..961bc2e1a7 100644
--- a/src/libs/3rdparty/cplusplus/AST.h
+++ b/src/libs/3rdparty/cplusplus/AST.h
@@ -125,6 +125,8 @@ public:
virtual AST *clone(MemoryPool *pool) const = 0;
virtual AccessDeclarationAST *asAccessDeclaration() { return 0; }
+ virtual AliasDeclarationAST *asAliasDeclaration() { return 0; }
+ virtual AlignofExpressionAST *asAlignofExpression() { return 0; }
virtual ArrayAccessAST *asArrayAccess() { return 0; }
virtual ArrayDeclaratorAST *asArrayDeclarator() { return 0; }
virtual ArrayInitializerAST *asArrayInitializer() { return 0; }
@@ -168,6 +170,7 @@ public:
virtual ExceptionDeclarationAST *asExceptionDeclaration() { return 0; }
virtual ExceptionSpecificationAST *asExceptionSpecification() { return 0; }
virtual ExpressionAST *asExpression() { return 0; }
+ virtual ExpressionListParenAST *asExpressionListParen() { return 0; }
virtual ExpressionOrDeclarationStatementAST *asExpressionOrDeclarationStatement() { return 0; }
virtual ExpressionStatementAST *asExpressionStatement() { return 0; }
virtual ForStatementAST *asForStatement() { return 0; }
@@ -195,8 +198,6 @@ public:
virtual NestedNameSpecifierAST *asNestedNameSpecifier() { return 0; }
virtual NewArrayDeclaratorAST *asNewArrayDeclarator() { return 0; }
virtual NewExpressionAST *asNewExpression() { return 0; }
- virtual NewInitializerAST *asNewInitializer() { return 0; }
- virtual NewPlacementAST *asNewPlacement() { return 0; }
virtual NewTypeIdAST *asNewTypeId() { return 0; }
virtual NoExceptSpecificationAST *asNoExceptSpecification() { return 0; }
virtual NumericLiteralAST *asNumericLiteral() { return 0; }
@@ -1457,8 +1458,10 @@ public:
ParameterDeclarationClauseAST *parameter_declaration_clause;
unsigned rparen_token;
SpecifierListAST *cv_qualifier_list;
+ unsigned ref_qualifier_token;
ExceptionSpecificationAST *exception_specification;
TrailingReturnTypeAST *trailing_return_type;
+ // Some FunctionDeclarators can also be interpreted as an initializer, like for 'A b(c);'
ExpressionAST *as_cpp_initializer;
public: // annotations
@@ -1470,6 +1473,7 @@ public:
, parameter_declaration_clause(0)
, rparen_token(0)
, cv_qualifier_list(0)
+ , ref_qualifier_token(0)
, exception_specification(0)
, trailing_return_type(0)
, as_cpp_initializer(0)
@@ -1630,7 +1634,10 @@ class CPLUSPLUS_EXPORT EnumSpecifierAST: public SpecifierAST
{
public:
unsigned enum_token;
+ unsigned key_token; // struct, class or 0
NameAST *name;
+ unsigned colon_token; // can be 0 if there is no enum-base
+ SpecifierListAST *type_specifier_list; // ditto
unsigned lbrace_token;
EnumeratorListAST *enumerator_list;
unsigned stray_comma_token;
@@ -1642,7 +1649,10 @@ public: // annotations
public:
EnumSpecifierAST()
: enum_token(0)
+ , key_token(0)
, name(0)
+ , colon_token(0)
+ , type_specifier_list(0)
, lbrace_token(0)
, enumerator_list(0)
, stray_comma_token(0)
@@ -1918,7 +1928,6 @@ public:
SpecifierListAST *type_specifier_list;
DeclaratorAST *declarator;
// or an expression
- ExpressionAST *initializer;
unsigned colon_token;
ExpressionAST *expression;
unsigned rparen_token;
@@ -1933,7 +1942,6 @@ public:
, lparen_token(0)
, type_specifier_list(0)
, declarator(0)
- , initializer(0)
, colon_token(0)
, expression(0)
, rparen_token(0)
@@ -2138,16 +2146,13 @@ class CPLUSPLUS_EXPORT MemInitializerAST: public AST
{
public:
NameAST *name;
- unsigned lparen_token;
- ExpressionListAST *expression_list;
- unsigned rparen_token;
+ // either a BracedInitializerAST or a ExpressionListParenAST
+ ExpressionAST *expression;
public:
MemInitializerAST()
: name(0)
- , lparen_token(0)
- , expression_list(0)
- , rparen_token(0)
+ , expression(0)
{}
virtual MemInitializerAST *asMemInitializer() { return this; }
@@ -2402,7 +2407,37 @@ protected:
virtual bool match0(AST *, ASTMatcher *);
};
-class CPLUSPLUS_EXPORT NewPlacementAST: public AST
+class CPLUSPLUS_EXPORT AliasDeclarationAST: public DeclarationAST
+{
+public:
+ unsigned using_token;
+ unsigned identifier_token;
+ unsigned equal_token;
+ TypeIdAST *typeId;
+ unsigned semicolon_token;
+
+public:
+ AliasDeclarationAST()
+ : using_token(0)
+ , identifier_token(0)
+ , equal_token(0)
+ , typeId(0)
+ , semicolon_token(0)
+ {}
+
+ virtual AliasDeclarationAST *asAliasDeclaration() { return this; }
+
+ virtual unsigned firstToken() const;
+ virtual unsigned lastToken() const;
+
+ virtual AliasDeclarationAST *clone(MemoryPool *pool) const;
+
+protected:
+ virtual void accept0(ASTVisitor *visitor);
+ virtual bool match0(AST *, ASTMatcher *);
+};
+
+class CPLUSPLUS_EXPORT ExpressionListParenAST: public ExpressionAST
{
public:
unsigned lparen_token;
@@ -2410,18 +2445,18 @@ public:
unsigned rparen_token;
public:
- NewPlacementAST()
+ ExpressionListParenAST()
: lparen_token(0)
, expression_list(0)
, rparen_token(0)
{}
- virtual NewPlacementAST *asNewPlacement() { return this; }
+ virtual ExpressionListParenAST *asExpressionListParen() { return this; }
virtual unsigned firstToken() const;
virtual unsigned lastToken() const;
- virtual NewPlacementAST *clone(MemoryPool *pool) const;
+ virtual ExpressionListParenAST *clone(MemoryPool *pool) const;
protected:
virtual void accept0(ASTVisitor *visitor);
@@ -2459,7 +2494,7 @@ class CPLUSPLUS_EXPORT NewExpressionAST: public ExpressionAST
public:
unsigned scope_token;
unsigned new_token;
- NewPlacementAST *new_placement;
+ ExpressionListParenAST *new_placement;
unsigned lparen_token;
ExpressionAST *type_id;
@@ -2467,7 +2502,7 @@ public:
NewTypeIdAST *new_type_id;
- NewInitializerAST *new_initializer;
+ ExpressionAST *new_initializer; // either ExpressionListParenAST or BracedInitializerAST
public:
NewExpressionAST()
@@ -2493,32 +2528,6 @@ protected:
virtual bool match0(AST *, ASTMatcher *);
};
-class CPLUSPLUS_EXPORT NewInitializerAST: public AST
-{
-public:
- unsigned lparen_token;
- ExpressionAST *expression;
- unsigned rparen_token;
-
-public:
- NewInitializerAST()
- : lparen_token(0)
- , expression(0)
- , rparen_token(0)
- {}
-
- virtual NewInitializerAST *asNewInitializer() { return this; }
-
- virtual unsigned firstToken() const;
- virtual unsigned lastToken() const;
-
- virtual NewInitializerAST *clone(MemoryPool *pool) const;
-
-protected:
- virtual void accept0(ASTVisitor *visitor);
- virtual bool match0(AST *, ASTMatcher *);
-};
-
class CPLUSPLUS_EXPORT NewTypeIdAST: public AST
{
public:
@@ -2768,17 +2777,13 @@ class CPLUSPLUS_EXPORT TypenameCallExpressionAST: public ExpressionAST
public:
unsigned typename_token;
NameAST *name;
- unsigned lparen_token;
- ExpressionListAST *expression_list;
- unsigned rparen_token;
+ ExpressionAST *expression; // either ExpressionListParenAST or BracedInitializerAST
public:
TypenameCallExpressionAST()
: typename_token(0)
, name(0)
- , lparen_token(0)
- , expression_list(0)
- , rparen_token(0)
+ , expression(0)
{}
virtual TypenameCallExpressionAST *asTypenameCallExpression() { return this; }
@@ -2797,16 +2802,12 @@ class CPLUSPLUS_EXPORT TypeConstructorCallAST: public ExpressionAST
{
public:
SpecifierListAST *type_specifier_list;
- unsigned lparen_token;
- ExpressionListAST *expression_list;
- unsigned rparen_token;
+ ExpressionAST *expression; // either ExpressionListParenAST or BracedInitializerAST
public:
TypeConstructorCallAST()
: type_specifier_list(0)
- , lparen_token(0)
- , expression_list(0)
- , rparen_token(0)
+ , expression(0)
{}
virtual TypeConstructorCallAST *asTypeConstructorCall() { return this; }
@@ -2828,6 +2829,7 @@ public:
NestedNameSpecifierListAST *nested_name_specifier_list;
unsigned star_token;
SpecifierListAST *cv_qualifier_list;
+ unsigned ref_qualifier_token;
public:
PointerToMemberAST()
@@ -2835,6 +2837,7 @@ public:
, nested_name_specifier_list(0)
, star_token(0)
, cv_qualifier_list(0)
+ , ref_qualifier_token(0)
{}
virtual PointerToMemberAST *asPointerToMember() { return this; }
@@ -3025,6 +3028,34 @@ protected:
virtual bool match0(AST *, ASTMatcher *);
};
+class CPLUSPLUS_EXPORT AlignofExpressionAST: public ExpressionAST
+{
+public:
+ unsigned alignof_token;
+ unsigned lparen_token;
+ TypeIdAST *typeId;
+ unsigned rparen_token;
+
+public:
+ AlignofExpressionAST()
+ : alignof_token(0)
+ , lparen_token(0)
+ , typeId(0)
+ , rparen_token(0)
+ {}
+
+ virtual AlignofExpressionAST *asAlignofExpression() { return this; }
+
+ virtual unsigned firstToken() const;
+ virtual unsigned lastToken() const;
+
+ virtual AlignofExpressionAST *clone(MemoryPool *pool) const;
+
+protected:
+ virtual void accept0(ASTVisitor *visitor);
+ virtual bool match0(AST *, ASTMatcher *);
+};
+
class CPLUSPLUS_EXPORT PointerLiteralAST: public ExpressionAST
{
public:
@@ -4364,7 +4395,13 @@ protected:
class CaptureAST: public AST
{
public:
+ unsigned amper_token;
+ NameAST *identifier;
+
+public:
CaptureAST()
+ : amper_token(0)
+ , identifier(0)
{}
virtual CaptureAST *asCapture() { return this; }
diff --git a/src/libs/3rdparty/cplusplus/ASTClone.cpp b/src/libs/3rdparty/cplusplus/ASTClone.cpp
index 6a3b7a5dda..73565b8037 100644
--- a/src/libs/3rdparty/cplusplus/ASTClone.cpp
+++ b/src/libs/3rdparty/cplusplus/ASTClone.cpp
@@ -22,7 +22,7 @@
// W A R N I N G
// -------------
//
-// This file is automatically generated.
+// This file is automatically generated by "cplusplus-update-frontend".
// Changes will be lost.
//
@@ -487,6 +487,7 @@ FunctionDeclaratorAST *FunctionDeclaratorAST::clone(MemoryPool *pool) const
for (SpecifierListAST *iter = cv_qualifier_list, **ast_iter = &ast->cv_qualifier_list;
iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
*ast_iter = new (pool) SpecifierListAST((iter->value) ? iter->value->clone(pool) : 0);
+ ast->ref_qualifier_token = ref_qualifier_token;
if (exception_specification)
ast->exception_specification = exception_specification->clone(pool);
if (trailing_return_type)
@@ -557,8 +558,13 @@ EnumSpecifierAST *EnumSpecifierAST::clone(MemoryPool *pool) const
{
EnumSpecifierAST *ast = new (pool) EnumSpecifierAST;
ast->enum_token = enum_token;
+ ast->key_token = key_token;
if (name)
ast->name = name->clone(pool);
+ ast->colon_token = colon_token;
+ for (SpecifierListAST *iter = type_specifier_list, **ast_iter = &ast->type_specifier_list;
+ iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
+ *ast_iter = new (pool) SpecifierListAST((iter->value) ? iter->value->clone(pool) : 0);
ast->lbrace_token = lbrace_token;
for (EnumeratorListAST *iter = enumerator_list, **ast_iter = &ast->enumerator_list;
iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
@@ -680,8 +686,6 @@ RangeBasedForStatementAST *RangeBasedForStatementAST::clone(MemoryPool *pool) co
*ast_iter = new (pool) SpecifierListAST((iter->value) ? iter->value->clone(pool) : 0);
if (declarator)
ast->declarator = declarator->clone(pool);
- if (initializer)
- ast->initializer = initializer->clone(pool);
ast->colon_token = colon_token;
if (expression)
ast->expression = expression->clone(pool);
@@ -772,11 +776,8 @@ MemInitializerAST *MemInitializerAST::clone(MemoryPool *pool) const
MemInitializerAST *ast = new (pool) MemInitializerAST;
if (name)
ast->name = name->clone(pool);
- ast->lparen_token = lparen_token;
- for (ExpressionListAST *iter = expression_list, **ast_iter = &ast->expression_list;
- iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
- *ast_iter = new (pool) ExpressionListAST((iter->value) ? iter->value->clone(pool) : 0);
- ast->rparen_token = rparen_token;
+ if (expression)
+ ast->expression = expression->clone(pool);
return ast;
}
@@ -878,9 +879,21 @@ NamespaceAliasDefinitionAST *NamespaceAliasDefinitionAST::clone(MemoryPool *pool
return ast;
}
-NewPlacementAST *NewPlacementAST::clone(MemoryPool *pool) const
+AliasDeclarationAST *AliasDeclarationAST::clone(MemoryPool *pool) const
{
- NewPlacementAST *ast = new (pool) NewPlacementAST;
+ AliasDeclarationAST *ast = new (pool) AliasDeclarationAST;
+ ast->using_token = using_token;
+ ast->identifier_token = identifier_token;
+ ast->equal_token = equal_token;
+ if (typeId)
+ ast->typeId = typeId->clone(pool);
+ ast->semicolon_token = semicolon_token;
+ return ast;
+}
+
+ExpressionListParenAST *ExpressionListParenAST::clone(MemoryPool *pool) const
+{
+ ExpressionListParenAST *ast = new (pool) ExpressionListParenAST;
ast->lparen_token = lparen_token;
for (ExpressionListAST *iter = expression_list, **ast_iter = &ast->expression_list;
iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
@@ -917,16 +930,6 @@ NewExpressionAST *NewExpressionAST::clone(MemoryPool *pool) const
return ast;
}
-NewInitializerAST *NewInitializerAST::clone(MemoryPool *pool) const
-{
- NewInitializerAST *ast = new (pool) NewInitializerAST;
- ast->lparen_token = lparen_token;
- if (expression)
- ast->expression = expression->clone(pool);
- ast->rparen_token = rparen_token;
- return ast;
-}
-
NewTypeIdAST *NewTypeIdAST::clone(MemoryPool *pool) const
{
NewTypeIdAST *ast = new (pool) NewTypeIdAST;
@@ -1038,11 +1041,8 @@ TypenameCallExpressionAST *TypenameCallExpressionAST::clone(MemoryPool *pool) co
ast->typename_token = typename_token;
if (name)
ast->name = name->clone(pool);
- ast->lparen_token = lparen_token;
- for (ExpressionListAST *iter = expression_list, **ast_iter = &ast->expression_list;
- iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
- *ast_iter = new (pool) ExpressionListAST((iter->value) ? iter->value->clone(pool) : 0);
- ast->rparen_token = rparen_token;
+ if (expression)
+ ast->expression = expression->clone(pool);
return ast;
}
@@ -1052,11 +1052,8 @@ TypeConstructorCallAST *TypeConstructorCallAST::clone(MemoryPool *pool) const
for (SpecifierListAST *iter = type_specifier_list, **ast_iter = &ast->type_specifier_list;
iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
*ast_iter = new (pool) SpecifierListAST((iter->value) ? iter->value->clone(pool) : 0);
- ast->lparen_token = lparen_token;
- for (ExpressionListAST *iter = expression_list, **ast_iter = &ast->expression_list;
- iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
- *ast_iter = new (pool) ExpressionListAST((iter->value) ? iter->value->clone(pool) : 0);
- ast->rparen_token = rparen_token;
+ if (expression)
+ ast->expression = expression->clone(pool);
return ast;
}
@@ -1071,6 +1068,7 @@ PointerToMemberAST *PointerToMemberAST::clone(MemoryPool *pool) const
for (SpecifierListAST *iter = cv_qualifier_list, **ast_iter = &ast->cv_qualifier_list;
iter; iter = iter->next, ast_iter = &(*ast_iter)->next)
*ast_iter = new (pool) SpecifierListAST((iter->value) ? iter->value->clone(pool) : 0);
+ ast->ref_qualifier_token = ref_qualifier_token;
return ast;
}
@@ -1138,6 +1136,17 @@ SizeofExpressionAST *SizeofExpressionAST::clone(MemoryPool *pool) const
return ast;
}
+AlignofExpressionAST *AlignofExpressionAST::clone(MemoryPool *pool) const
+{
+ AlignofExpressionAST *ast = new (pool) AlignofExpressionAST;
+ ast->alignof_token = alignof_token;
+ ast->lparen_token = lparen_token;
+ if (typeId)
+ ast->typeId = typeId->clone(pool);
+ ast->rparen_token = rparen_token;
+ return ast;
+}
+
PointerLiteralAST *PointerLiteralAST::clone(MemoryPool *pool) const
{
PointerLiteralAST *ast = new (pool) PointerLiteralAST;
@@ -1694,6 +1703,9 @@ LambdaCaptureAST *LambdaCaptureAST::clone(MemoryPool *pool) const
CaptureAST *CaptureAST::clone(MemoryPool *pool) const
{
CaptureAST *ast = new (pool) CaptureAST;
+ ast->amper_token = amper_token;
+ if (identifier)
+ ast->identifier = identifier->clone(pool);
return ast;
}
diff --git a/src/libs/3rdparty/cplusplus/ASTMatch0.cpp b/src/libs/3rdparty/cplusplus/ASTMatch0.cpp
index 81e74316b6..c49b5dae65 100644
--- a/src/libs/3rdparty/cplusplus/ASTMatch0.cpp
+++ b/src/libs/3rdparty/cplusplus/ASTMatch0.cpp
@@ -22,7 +22,7 @@
// W A R N I N G
// -------------
//
-// This file is automatically generated.
+// This file is automatically generated by "cplusplus-update-frontend".
// Changes will be lost.
//
@@ -592,33 +592,33 @@ bool NamespaceAliasDefinitionAST::match0(AST *pattern, ASTMatcher *matcher)
return false;
}
-bool NewPlacementAST::match0(AST *pattern, ASTMatcher *matcher)
+bool AliasDeclarationAST::match0(AST *pattern, ASTMatcher *matcher)
{
- if (NewPlacementAST *_other = pattern->asNewPlacement())
+ if (AliasDeclarationAST *_other = pattern->asAliasDeclaration())
return matcher->match(this, _other);
return false;
}
-bool NewArrayDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher)
+bool ExpressionListParenAST::match0(AST *pattern, ASTMatcher *matcher)
{
- if (NewArrayDeclaratorAST *_other = pattern->asNewArrayDeclarator())
+ if (ExpressionListParenAST *_other = pattern->asExpressionListParen())
return matcher->match(this, _other);
return false;
}
-bool NewExpressionAST::match0(AST *pattern, ASTMatcher *matcher)
+bool NewArrayDeclaratorAST::match0(AST *pattern, ASTMatcher *matcher)
{
- if (NewExpressionAST *_other = pattern->asNewExpression())
+ if (NewArrayDeclaratorAST *_other = pattern->asNewArrayDeclarator())
return matcher->match(this, _other);
return false;
}
-bool NewInitializerAST::match0(AST *pattern, ASTMatcher *matcher)
+bool NewExpressionAST::match0(AST *pattern, ASTMatcher *matcher)
{
- if (NewInitializerAST *_other = pattern->asNewInitializer())
+ if (NewExpressionAST *_other = pattern->asNewExpression())
return matcher->match(this, _other);
return false;
@@ -776,6 +776,14 @@ bool SizeofExpressionAST::match0(AST *pattern, ASTMatcher *matcher)
return false;
}
+bool AlignofExpressionAST::match0(AST *pattern, ASTMatcher *matcher)
+{
+ if (AlignofExpressionAST *_other = pattern->asAlignofExpression())
+ return matcher->match(this, _other);
+
+ return false;
+}
+
bool PointerLiteralAST::match0(AST *pattern, ASTMatcher *matcher)
{
if (PointerLiteralAST *_other = pattern->asPointerLiteral())
diff --git a/src/libs/3rdparty/cplusplus/ASTMatcher.cpp b/src/libs/3rdparty/cplusplus/ASTMatcher.cpp
index a773c07b3e..4fbb9d6f8e 100644
--- a/src/libs/3rdparty/cplusplus/ASTMatcher.cpp
+++ b/src/libs/3rdparty/cplusplus/ASTMatcher.cpp
@@ -23,7 +23,7 @@
// W A R N I N G
// -------------
//
-// This file is automatically generated.
+// This file is automatically generated by "cplusplus-update-frontend".
// Changes will be lost.
//
@@ -809,6 +809,8 @@ bool ASTMatcher::match(FunctionDeclaratorAST *node, FunctionDeclaratorAST *patte
else if (! AST::match(node->cv_qualifier_list, pattern->cv_qualifier_list, this))
return false;
+ pattern->ref_qualifier_token = node->ref_qualifier_token;
+
if (! pattern->exception_specification)
pattern->exception_specification = node->exception_specification;
else if (! AST::match(node->exception_specification, pattern->exception_specification, this))
@@ -933,11 +935,20 @@ bool ASTMatcher::match(EnumSpecifierAST *node, EnumSpecifierAST *pattern)
pattern->enum_token = node->enum_token;
+ pattern->key_token = node->key_token;
+
if (! pattern->name)
pattern->name = node->name;
else if (! AST::match(node->name, pattern->name, this))
return false;
+ pattern->colon_token = node->colon_token;
+
+ if (! pattern->type_specifier_list)
+ pattern->type_specifier_list = node->type_specifier_list;
+ else if (! AST::match(node->type_specifier_list, pattern->type_specifier_list, this))
+ return false;
+
pattern->lbrace_token = node->lbrace_token;
if (! pattern->enumerator_list)
@@ -1152,11 +1163,6 @@ bool ASTMatcher::match(RangeBasedForStatementAST *node, RangeBasedForStatementAS
else if (! AST::match(node->declarator, pattern->declarator, this))
return false;
- if (! pattern->initializer)
- pattern->initializer = node->initializer;
- else if (! AST::match(node->initializer, pattern->initializer, this))
- return false;
-
pattern->colon_token = node->colon_token;
if (! pattern->expression)
@@ -1319,15 +1325,11 @@ bool ASTMatcher::match(MemInitializerAST *node, MemInitializerAST *pattern)
else if (! AST::match(node->name, pattern->name, this))
return false;
- pattern->lparen_token = node->lparen_token;
-
- if (! pattern->expression_list)
- pattern->expression_list = node->expression_list;
- else if (! AST::match(node->expression_list, pattern->expression_list, this))
+ if (! pattern->expression)
+ pattern->expression = node->expression;
+ else if (! AST::match(node->expression, pattern->expression, this))
return false;
- pattern->rparen_token = node->rparen_token;
-
return true;
}
@@ -1492,7 +1494,28 @@ bool ASTMatcher::match(NamespaceAliasDefinitionAST *node, NamespaceAliasDefiniti
return true;
}
-bool ASTMatcher::match(NewPlacementAST *node, NewPlacementAST *pattern)
+bool ASTMatcher::match(AliasDeclarationAST *node, AliasDeclarationAST *pattern)
+{
+ (void) node;
+ (void) pattern;
+
+ pattern->using_token = node->using_token;
+
+ pattern->identifier_token = node->identifier_token;
+
+ pattern->equal_token = node->equal_token;
+
+ if (! pattern->typeId)
+ pattern->typeId = node->typeId;
+ else if (! AST::match(node->typeId, pattern->typeId, this))
+ return false;
+
+ pattern->semicolon_token = node->semicolon_token;
+
+ return true;
+}
+
+bool ASTMatcher::match(ExpressionListParenAST *node, ExpressionListParenAST *pattern)
{
(void) node;
(void) pattern;
@@ -1562,23 +1585,6 @@ bool ASTMatcher::match(NewExpressionAST *node, NewExpressionAST *pattern)
return true;
}
-bool ASTMatcher::match(NewInitializerAST *node, NewInitializerAST *pattern)
-{
- (void) node;
- (void) pattern;
-
- pattern->lparen_token = node->lparen_token;
-
- if (! pattern->expression)
- pattern->expression = node->expression;
- else if (! AST::match(node->expression, pattern->expression, this))
- return false;
-
- pattern->rparen_token = node->rparen_token;
-
- return true;
-}
-
bool ASTMatcher::match(NewTypeIdAST *node, NewTypeIdAST *pattern)
{
(void) node;
@@ -1768,15 +1774,11 @@ bool ASTMatcher::match(TypenameCallExpressionAST *node, TypenameCallExpressionAS
else if (! AST::match(node->name, pattern->name, this))
return false;
- pattern->lparen_token = node->lparen_token;
-
- if (! pattern->expression_list)
- pattern->expression_list = node->expression_list;
- else if (! AST::match(node->expression_list, pattern->expression_list, this))
+ if (! pattern->expression)
+ pattern->expression = node->expression;
+ else if (! AST::match(node->expression, pattern->expression, this))
return false;
- pattern->rparen_token = node->rparen_token;
-
return true;
}
@@ -1790,15 +1792,11 @@ bool ASTMatcher::match(TypeConstructorCallAST *node, TypeConstructorCallAST *pat
else if (! AST::match(node->type_specifier_list, pattern->type_specifier_list, this))
return false;
- pattern->lparen_token = node->lparen_token;
-
- if (! pattern->expression_list)
- pattern->expression_list = node->expression_list;
- else if (! AST::match(node->expression_list, pattern->expression_list, this))
+ if (! pattern->expression)
+ pattern->expression = node->expression;
+ else if (! AST::match(node->expression, pattern->expression, this))
return false;
- pattern->rparen_token = node->rparen_token;
-
return true;
}
@@ -1821,6 +1819,8 @@ bool ASTMatcher::match(PointerToMemberAST *node, PointerToMemberAST *pattern)
else if (! AST::match(node->cv_qualifier_list, pattern->cv_qualifier_list, this))
return false;
+ pattern->ref_qualifier_token = node->ref_qualifier_token;
+
return true;
}
@@ -1925,6 +1925,25 @@ bool ASTMatcher::match(SizeofExpressionAST *node, SizeofExpressionAST *pattern)
return true;
}
+bool ASTMatcher::match(AlignofExpressionAST *node, AlignofExpressionAST *pattern)
+{
+ (void) node;
+ (void) pattern;
+
+ pattern->alignof_token = node->alignof_token;
+
+ pattern->lparen_token = node->lparen_token;
+
+ if (! pattern->typeId)
+ pattern->typeId = node->typeId;
+ else if (! AST::match(node->typeId, pattern->typeId, this))
+ return false;
+
+ pattern->rparen_token = node->rparen_token;
+
+ return true;
+}
+
bool ASTMatcher::match(PointerLiteralAST *node, PointerLiteralAST *pattern)
{
(void) node;
@@ -2879,6 +2898,13 @@ bool ASTMatcher::match(CaptureAST *node, CaptureAST *pattern)
(void) node;
(void) pattern;
+ pattern->amper_token = node->amper_token;
+
+ if (! pattern->identifier)
+ pattern->identifier = node->identifier;
+ else if (! AST::match(node->identifier, pattern->identifier, this))
+ return false;
+
return true;
}
diff --git a/src/libs/3rdparty/cplusplus/ASTMatcher.h b/src/libs/3rdparty/cplusplus/ASTMatcher.h
index 202a577741..29842253cd 100644
--- a/src/libs/3rdparty/cplusplus/ASTMatcher.h
+++ b/src/libs/3rdparty/cplusplus/ASTMatcher.h
@@ -32,6 +32,8 @@ public:
virtual ~ASTMatcher();
virtual bool match(AccessDeclarationAST *node, AccessDeclarationAST *pattern);
+ virtual bool match(AliasDeclarationAST *node, AliasDeclarationAST *pattern);
+ virtual bool match(AlignofExpressionAST *node, AlignofExpressionAST *pattern);
virtual bool match(ArrayAccessAST *node, ArrayAccessAST *pattern);
virtual bool match(ArrayDeclaratorAST *node, ArrayDeclaratorAST *pattern);
virtual bool match(ArrayInitializerAST *node, ArrayInitializerAST *pattern);
@@ -71,6 +73,7 @@ public:
virtual bool match(EnumSpecifierAST *node, EnumSpecifierAST *pattern);
virtual bool match(EnumeratorAST *node, EnumeratorAST *pattern);
virtual bool match(ExceptionDeclarationAST *node, ExceptionDeclarationAST *pattern);
+ virtual bool match(ExpressionListParenAST *node, ExpressionListParenAST *pattern);
virtual bool match(ExpressionOrDeclarationStatementAST *node, ExpressionOrDeclarationStatementAST *pattern);
virtual bool match(ExpressionStatementAST *node, ExpressionStatementAST *pattern);
virtual bool match(ForStatementAST *node, ForStatementAST *pattern);
@@ -97,8 +100,6 @@ public:
virtual bool match(NestedNameSpecifierAST *node, NestedNameSpecifierAST *pattern);
virtual bool match(NewArrayDeclaratorAST *node, NewArrayDeclaratorAST *pattern);
virtual bool match(NewExpressionAST *node, NewExpressionAST *pattern);
- virtual bool match(NewInitializerAST *node, NewInitializerAST *pattern);
- virtual bool match(NewPlacementAST *node, NewPlacementAST *pattern);
virtual bool match(NewTypeIdAST *node, NewTypeIdAST *pattern);
virtual bool match(NoExceptSpecificationAST *node, NoExceptSpecificationAST *pattern);
virtual bool match(NumericLiteralAST *node, NumericLiteralAST *pattern);
diff --git a/src/libs/3rdparty/cplusplus/ASTPatternBuilder.h b/src/libs/3rdparty/cplusplus/ASTPatternBuilder.h
index 41ad4964b2..04a0fdd12c 100644
--- a/src/libs/3rdparty/cplusplus/ASTPatternBuilder.h
+++ b/src/libs/3rdparty/cplusplus/ASTPatternBuilder.h
@@ -22,7 +22,7 @@
// W A R N I N G
// -------------
//
-// This file is automatically generated.
+// This file is automatically generated by "cplusplus-update-frontend".
// Changes will be lost.
//
@@ -374,10 +374,11 @@ public:
return __ast;
}
- EnumSpecifierAST *EnumSpecifier(NameAST *name = 0, EnumeratorListAST *enumerator_list = 0)
+ EnumSpecifierAST *EnumSpecifier(NameAST *name = 0, SpecifierListAST *type_specifier_list = 0, EnumeratorListAST *enumerator_list = 0)
{
EnumSpecifierAST *__ast = new (&pool) EnumSpecifierAST;
__ast->name = name;
+ __ast->type_specifier_list = type_specifier_list;
__ast->enumerator_list = enumerator_list;
return __ast;
}
@@ -447,12 +448,11 @@ public:
return __ast;
}
- RangeBasedForStatementAST *RangeBasedForStatement(SpecifierListAST *type_specifier_list = 0, DeclaratorAST *declarator = 0, ExpressionAST *initializer = 0, ExpressionAST *expression = 0, StatementAST *statement = 0)
+ RangeBasedForStatementAST *RangeBasedForStatement(SpecifierListAST *type_specifier_list = 0, DeclaratorAST *declarator = 0, ExpressionAST *expression = 0, StatementAST *statement = 0)
{
RangeBasedForStatementAST *__ast = new (&pool) RangeBasedForStatementAST;
__ast->type_specifier_list = type_specifier_list;
__ast->declarator = declarator;
- __ast->initializer = initializer;
__ast->expression = expression;
__ast->statement = statement;
return __ast;
@@ -505,11 +505,11 @@ public:
return __ast;
}
- MemInitializerAST *MemInitializer(NameAST *name = 0, ExpressionListAST *expression_list = 0)
+ MemInitializerAST *MemInitializer(NameAST *name = 0, ExpressionAST *expression = 0)
{
MemInitializerAST *__ast = new (&pool) MemInitializerAST;
__ast->name = name;
- __ast->expression_list = expression_list;
+ __ast->expression = expression;
return __ast;
}
@@ -578,9 +578,16 @@ public:
return __ast;
}
- NewPlacementAST *NewPlacement(ExpressionListAST *expression_list = 0)
+ AliasDeclarationAST *AliasDeclaration(TypeIdAST *typeId = 0)
+ {
+ AliasDeclarationAST *__ast = new (&pool) AliasDeclarationAST;
+ __ast->typeId = typeId;
+ return __ast;
+ }
+
+ ExpressionListParenAST *ExpressionListParen(ExpressionListAST *expression_list = 0)
{
- NewPlacementAST *__ast = new (&pool) NewPlacementAST;
+ ExpressionListParenAST *__ast = new (&pool) ExpressionListParenAST;
__ast->expression_list = expression_list;
return __ast;
}
@@ -592,7 +599,7 @@ public:
return __ast;
}
- NewExpressionAST *NewExpression(NewPlacementAST *new_placement = 0, ExpressionAST *type_id = 0, NewTypeIdAST *new_type_id = 0, NewInitializerAST *new_initializer = 0)
+ NewExpressionAST *NewExpression(ExpressionListParenAST *new_placement = 0, ExpressionAST *type_id = 0, NewTypeIdAST *new_type_id = 0, ExpressionAST *new_initializer = 0)
{
NewExpressionAST *__ast = new (&pool) NewExpressionAST;
__ast->new_placement = new_placement;
@@ -602,13 +609,6 @@ public:
return __ast;
}
- NewInitializerAST *NewInitializer(ExpressionAST *expression = 0)
- {
- NewInitializerAST *__ast = new (&pool) NewInitializerAST;
- __ast->expression = expression;
- return __ast;
- }
-
NewTypeIdAST *NewTypeId(SpecifierListAST *type_specifier_list = 0, PtrOperatorListAST *ptr_operator_list = 0, NewArrayDeclaratorListAST *new_array_declarator_list = 0)
{
NewTypeIdAST *__ast = new (&pool) NewTypeIdAST;
@@ -678,19 +678,19 @@ public:
return __ast;
}
- TypenameCallExpressionAST *TypenameCallExpression(NameAST *name = 0, ExpressionListAST *expression_list = 0)
+ TypenameCallExpressionAST *TypenameCallExpression(NameAST *name = 0, ExpressionAST *expression = 0)
{
TypenameCallExpressionAST *__ast = new (&pool) TypenameCallExpressionAST;
__ast->name = name;
- __ast->expression_list = expression_list;
+ __ast->expression = expression;
return __ast;
}
- TypeConstructorCallAST *TypeConstructorCall(SpecifierListAST *type_specifier_list = 0, ExpressionListAST *expression_list = 0)
+ TypeConstructorCallAST *TypeConstructorCall(SpecifierListAST *type_specifier_list = 0, ExpressionAST *expression = 0)
{
TypeConstructorCallAST *__ast = new (&pool) TypeConstructorCallAST;
__ast->type_specifier_list = type_specifier_list;
- __ast->expression_list = expression_list;
+ __ast->expression = expression;
return __ast;
}
@@ -747,6 +747,13 @@ public:
return __ast;
}
+ AlignofExpressionAST *AlignofExpression(TypeIdAST *typeId = 0)
+ {
+ AlignofExpressionAST *__ast = new (&pool) AlignofExpressionAST;
+ __ast->typeId = typeId;
+ return __ast;
+ }
+
PointerLiteralAST *PointerLiteral()
{
PointerLiteralAST *__ast = new (&pool) PointerLiteralAST;
@@ -1100,9 +1107,10 @@ public:
return __ast;
}
- CaptureAST *Capture()
+ CaptureAST *Capture(NameAST *identifier = 0)
{
CaptureAST *__ast = new (&pool) CaptureAST;
+ __ast->identifier = identifier;
return __ast;
}
@@ -1132,33 +1140,33 @@ public:
return __ast;
}
- CatchClauseListAST *CatchClauseList(CatchClauseAST *value, CatchClauseListAST *next = 0)
+ AttributeListAST *AttributeList(AttributeAST *value, AttributeListAST *next = 0)
{
- CatchClauseListAST *__list = new (&pool) CatchClauseListAST;
+ AttributeListAST *__list = new (&pool) AttributeListAST;
__list->next = next;
__list->value = value;
return __list;
}
- PostfixDeclaratorListAST *PostfixDeclaratorList(PostfixDeclaratorAST *value, PostfixDeclaratorListAST *next = 0)
+ BaseSpecifierListAST *BaseSpecifierList(BaseSpecifierAST *value, BaseSpecifierListAST *next = 0)
{
- PostfixDeclaratorListAST *__list = new (&pool) PostfixDeclaratorListAST;
+ BaseSpecifierListAST *__list = new (&pool) BaseSpecifierListAST;
__list->next = next;
__list->value = value;
return __list;
}
- ExpressionListAST *ExpressionList(ExpressionAST *value, ExpressionListAST *next = 0)
+ CaptureListAST *CaptureList(CaptureAST *value, CaptureListAST *next = 0)
{
- ExpressionListAST *__list = new (&pool) ExpressionListAST;
+ CaptureListAST *__list = new (&pool) CaptureListAST;
__list->next = next;
__list->value = value;
return __list;
}
- QtPropertyDeclarationItemListAST *QtPropertyDeclarationItemList(QtPropertyDeclarationItemAST *value, QtPropertyDeclarationItemListAST *next = 0)
+ CatchClauseListAST *CatchClauseList(CatchClauseAST *value, CatchClauseListAST *next = 0)
{
- QtPropertyDeclarationItemListAST *__list = new (&pool) QtPropertyDeclarationItemListAST;
+ CatchClauseListAST *__list = new (&pool) CatchClauseListAST;
__list->next = next;
__list->value = value;
return __list;
@@ -1172,9 +1180,9 @@ public:
return __list;
}
- ObjCMessageArgumentDeclarationListAST *ObjCMessageArgumentDeclarationList(ObjCMessageArgumentDeclarationAST *value, ObjCMessageArgumentDeclarationListAST *next = 0)
+ DeclaratorListAST *DeclaratorList(DeclaratorAST *value, DeclaratorListAST *next = 0)
{
- ObjCMessageArgumentDeclarationListAST *__list = new (&pool) ObjCMessageArgumentDeclarationListAST;
+ DeclaratorListAST *__list = new (&pool) DeclaratorListAST;
__list->next = next;
__list->value = value;
return __list;
@@ -1188,25 +1196,25 @@ public:
return __list;
}
- NameListAST *NameList(NameAST *value, NameListAST *next = 0)
+ ExpressionListAST *ExpressionList(ExpressionAST *value, ExpressionListAST *next = 0)
{
- NameListAST *__list = new (&pool) NameListAST;
+ ExpressionListAST *__list = new (&pool) ExpressionListAST;
__list->next = next;
__list->value = value;
return __list;
}
- AttributeListAST *AttributeList(AttributeAST *value, AttributeListAST *next = 0)
+ MemInitializerListAST *MemInitializerList(MemInitializerAST *value, MemInitializerListAST *next = 0)
{
- AttributeListAST *__list = new (&pool) AttributeListAST;
+ MemInitializerListAST *__list = new (&pool) MemInitializerListAST;
__list->next = next;
__list->value = value;
return __list;
}
- ObjCSelectorArgumentListAST *ObjCSelectorArgumentList(ObjCSelectorArgumentAST *value, ObjCSelectorArgumentListAST *next = 0)
+ NameListAST *NameList(NameAST *value, NameListAST *next = 0)
{
- ObjCSelectorArgumentListAST *__list = new (&pool) ObjCSelectorArgumentListAST;
+ NameListAST *__list = new (&pool) NameListAST;
__list->next = next;
__list->value = value;
return __list;
@@ -1220,105 +1228,105 @@ public:
return __list;
}
- BaseSpecifierListAST *BaseSpecifierList(BaseSpecifierAST *value, BaseSpecifierListAST *next = 0)
+ NewArrayDeclaratorListAST *NewArrayDeclaratorList(NewArrayDeclaratorAST *value, NewArrayDeclaratorListAST *next = 0)
{
- BaseSpecifierListAST *__list = new (&pool) BaseSpecifierListAST;
+ NewArrayDeclaratorListAST *__list = new (&pool) NewArrayDeclaratorListAST;
__list->next = next;
__list->value = value;
return __list;
}
- ObjCPropertyAttributeListAST *ObjCPropertyAttributeList(ObjCPropertyAttributeAST *value, ObjCPropertyAttributeListAST *next = 0)
+ ObjCMessageArgumentDeclarationListAST *ObjCMessageArgumentDeclarationList(ObjCMessageArgumentDeclarationAST *value, ObjCMessageArgumentDeclarationListAST *next = 0)
{
- ObjCPropertyAttributeListAST *__list = new (&pool) ObjCPropertyAttributeListAST;
+ ObjCMessageArgumentDeclarationListAST *__list = new (&pool) ObjCMessageArgumentDeclarationListAST;
__list->next = next;
__list->value = value;
return __list;
}
- MemInitializerListAST *MemInitializerList(MemInitializerAST *value, MemInitializerListAST *next = 0)
+ ObjCMessageArgumentListAST *ObjCMessageArgumentList(ObjCMessageArgumentAST *value, ObjCMessageArgumentListAST *next = 0)
{
- MemInitializerListAST *__list = new (&pool) MemInitializerListAST;
+ ObjCMessageArgumentListAST *__list = new (&pool) ObjCMessageArgumentListAST;
__list->next = next;
__list->value = value;
return __list;
}
- StatementListAST *StatementList(StatementAST *value, StatementListAST *next = 0)
+ ObjCPropertyAttributeListAST *ObjCPropertyAttributeList(ObjCPropertyAttributeAST *value, ObjCPropertyAttributeListAST *next = 0)
{
- StatementListAST *__list = new (&pool) StatementListAST;
+ ObjCPropertyAttributeListAST *__list = new (&pool) ObjCPropertyAttributeListAST;
__list->next = next;
__list->value = value;
return __list;
}
- ParameterDeclarationListAST *ParameterDeclarationList(ParameterDeclarationAST *value, ParameterDeclarationListAST *next = 0)
+ ObjCSelectorArgumentListAST *ObjCSelectorArgumentList(ObjCSelectorArgumentAST *value, ObjCSelectorArgumentListAST *next = 0)
{
- ParameterDeclarationListAST *__list = new (&pool) ParameterDeclarationListAST;
+ ObjCSelectorArgumentListAST *__list = new (&pool) ObjCSelectorArgumentListAST;
__list->next = next;
__list->value = value;
return __list;
}
- ObjCMessageArgumentListAST *ObjCMessageArgumentList(ObjCMessageArgumentAST *value, ObjCMessageArgumentListAST *next = 0)
+ ObjCSynthesizedPropertyListAST *ObjCSynthesizedPropertyList(ObjCSynthesizedPropertyAST *value, ObjCSynthesizedPropertyListAST *next = 0)
{
- ObjCMessageArgumentListAST *__list = new (&pool) ObjCMessageArgumentListAST;
+ ObjCSynthesizedPropertyListAST *__list = new (&pool) ObjCSynthesizedPropertyListAST;
__list->next = next;
__list->value = value;
return __list;
}
- NewArrayDeclaratorListAST *NewArrayDeclaratorList(NewArrayDeclaratorAST *value, NewArrayDeclaratorListAST *next = 0)
+ ParameterDeclarationListAST *ParameterDeclarationList(ParameterDeclarationAST *value, ParameterDeclarationListAST *next = 0)
{
- NewArrayDeclaratorListAST *__list = new (&pool) NewArrayDeclaratorListAST;
+ ParameterDeclarationListAST *__list = new (&pool) ParameterDeclarationListAST;
__list->next = next;
__list->value = value;
return __list;
}
- SpecifierListAST *SpecifierList(SpecifierAST *value, SpecifierListAST *next = 0)
+ PostfixDeclaratorListAST *PostfixDeclaratorList(PostfixDeclaratorAST *value, PostfixDeclaratorListAST *next = 0)
{
- SpecifierListAST *__list = new (&pool) SpecifierListAST;
+ PostfixDeclaratorListAST *__list = new (&pool) PostfixDeclaratorListAST;
__list->next = next;
__list->value = value;
return __list;
}
- ObjCSynthesizedPropertyListAST *ObjCSynthesizedPropertyList(ObjCSynthesizedPropertyAST *value, ObjCSynthesizedPropertyListAST *next = 0)
+ PtrOperatorListAST *PtrOperatorList(PtrOperatorAST *value, PtrOperatorListAST *next = 0)
{
- ObjCSynthesizedPropertyListAST *__list = new (&pool) ObjCSynthesizedPropertyListAST;
+ PtrOperatorListAST *__list = new (&pool) PtrOperatorListAST;
__list->next = next;
__list->value = value;
return __list;
}
- DeclaratorListAST *DeclaratorList(DeclaratorAST *value, DeclaratorListAST *next = 0)
+ QtInterfaceNameListAST *QtInterfaceNameList(QtInterfaceNameAST *value, QtInterfaceNameListAST *next = 0)
{
- DeclaratorListAST *__list = new (&pool) DeclaratorListAST;
+ QtInterfaceNameListAST *__list = new (&pool) QtInterfaceNameListAST;
__list->next = next;
__list->value = value;
return __list;
}
- QtInterfaceNameListAST *QtInterfaceNameList(QtInterfaceNameAST *value, QtInterfaceNameListAST *next = 0)
+ QtPropertyDeclarationItemListAST *QtPropertyDeclarationItemList(QtPropertyDeclarationItemAST *value, QtPropertyDeclarationItemListAST *next = 0)
{
- QtInterfaceNameListAST *__list = new (&pool) QtInterfaceNameListAST;
+ QtPropertyDeclarationItemListAST *__list = new (&pool) QtPropertyDeclarationItemListAST;
__list->next = next;
__list->value = value;
return __list;
}
- PtrOperatorListAST *PtrOperatorList(PtrOperatorAST *value, PtrOperatorListAST *next = 0)
+ SpecifierListAST *SpecifierList(SpecifierAST *value, SpecifierListAST *next = 0)
{
- PtrOperatorListAST *__list = new (&pool) PtrOperatorListAST;
+ SpecifierListAST *__list = new (&pool) SpecifierListAST;
__list->next = next;
__list->value = value;
return __list;
}
- CaptureListAST *CaptureList(CaptureAST *value, CaptureListAST *next = 0)
+ StatementListAST *StatementList(StatementAST *value, StatementListAST *next = 0)
{
- CaptureListAST *__list = new (&pool) CaptureListAST;
+ StatementListAST *__list = new (&pool) StatementListAST;
__list->next = next;
__list->value = value;
return __list;
diff --git a/src/libs/3rdparty/cplusplus/ASTVisit.cpp b/src/libs/3rdparty/cplusplus/ASTVisit.cpp
index f30523ee53..76adc01c53 100644
--- a/src/libs/3rdparty/cplusplus/ASTVisit.cpp
+++ b/src/libs/3rdparty/cplusplus/ASTVisit.cpp
@@ -22,7 +22,7 @@
// W A R N I N G
// -------------
//
-// This file is automatically generated.
+// This file is automatically generated by "cplusplus-update-frontend".
// Changes will be lost.
//
@@ -410,6 +410,7 @@ void EnumSpecifierAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
accept(name, visitor);
+ accept(type_specifier_list, visitor);
accept(enumerator_list, visitor);
}
visitor->endVisit(this);
@@ -493,7 +494,6 @@ void RangeBasedForStatementAST::accept0(ASTVisitor *visitor)
if (visitor->visit(this)) {
accept(type_specifier_list, visitor);
accept(declarator, visitor);
- accept(initializer, visitor);
accept(expression, visitor);
accept(statement, visitor);
}
@@ -557,7 +557,7 @@ void MemInitializerAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
accept(name, visitor);
- accept(expression_list, visitor);
+ accept(expression, visitor);
}
visitor->endVisit(this);
}
@@ -636,7 +636,15 @@ void NamespaceAliasDefinitionAST::accept0(ASTVisitor *visitor)
visitor->endVisit(this);
}
-void NewPlacementAST::accept0(ASTVisitor *visitor)
+void AliasDeclarationAST::accept0(ASTVisitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(typeId, visitor);
+ }
+ visitor->endVisit(this);
+}
+
+void ExpressionListParenAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
accept(expression_list, visitor);
@@ -663,14 +671,6 @@ void NewExpressionAST::accept0(ASTVisitor *visitor)
visitor->endVisit(this);
}
-void NewInitializerAST::accept0(ASTVisitor *visitor)
-{
- if (visitor->visit(this)) {
- accept(expression, visitor);
- }
- visitor->endVisit(this);
-}
-
void NewTypeIdAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
@@ -753,7 +753,7 @@ void TypenameCallExpressionAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
accept(name, visitor);
- accept(expression_list, visitor);
+ accept(expression, visitor);
}
visitor->endVisit(this);
}
@@ -762,7 +762,7 @@ void TypeConstructorCallAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
accept(type_specifier_list, visitor);
- accept(expression_list, visitor);
+ accept(expression, visitor);
}
visitor->endVisit(this);
}
@@ -828,6 +828,14 @@ void SizeofExpressionAST::accept0(ASTVisitor *visitor)
visitor->endVisit(this);
}
+void AlignofExpressionAST::accept0(ASTVisitor *visitor)
+{
+ if (visitor->visit(this)) {
+ accept(typeId, visitor);
+ }
+ visitor->endVisit(this);
+}
+
void PointerLiteralAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
@@ -1229,6 +1237,7 @@ void LambdaCaptureAST::accept0(ASTVisitor *visitor)
void CaptureAST::accept0(ASTVisitor *visitor)
{
if (visitor->visit(this)) {
+ accept(identifier, visitor);
}
visitor->endVisit(this);
}
diff --git a/src/libs/3rdparty/cplusplus/ASTVisitor.h b/src/libs/3rdparty/cplusplus/ASTVisitor.h
index eab93a20bb..a7d3f728f6 100644
--- a/src/libs/3rdparty/cplusplus/ASTVisitor.h
+++ b/src/libs/3rdparty/cplusplus/ASTVisitor.h
@@ -74,6 +74,8 @@ public:
virtual void postVisit(AST *) {}
virtual bool visit(AccessDeclarationAST *) { return true; }
+ virtual bool visit(AliasDeclarationAST *) { return true; }
+ virtual bool visit(AlignofExpressionAST *) { return true; }
virtual bool visit(ArrayAccessAST *) { return true; }
virtual bool visit(ArrayDeclaratorAST *) { return true; }
virtual bool visit(ArrayInitializerAST *) { return true; }
@@ -113,6 +115,7 @@ public:
virtual bool visit(EnumSpecifierAST *) { return true; }
virtual bool visit(EnumeratorAST *) { return true; }
virtual bool visit(ExceptionDeclarationAST *) { return true; }
+ virtual bool visit(ExpressionListParenAST *) { return true; }
virtual bool visit(ExpressionOrDeclarationStatementAST *) { return true; }
virtual bool visit(ExpressionStatementAST *) { return true; }
virtual bool visit(ForStatementAST *) { return true; }
@@ -139,8 +142,6 @@ public:
virtual bool visit(NestedNameSpecifierAST *) { return true; }
virtual bool visit(NewArrayDeclaratorAST *) { return true; }
virtual bool visit(NewExpressionAST *) { return true; }
- virtual bool visit(NewInitializerAST *) { return true; }
- virtual bool visit(NewPlacementAST *) { return true; }
virtual bool visit(NewTypeIdAST *) { return true; }
virtual bool visit(NoExceptSpecificationAST *) { return true; }
virtual bool visit(NumericLiteralAST *) { return true; }
@@ -218,6 +219,8 @@ public:
virtual bool visit(WhileStatementAST *) { return true; }
virtual void endVisit(AccessDeclarationAST *) {}
+ virtual void endVisit(AliasDeclarationAST *) {}
+ virtual void endVisit(AlignofExpressionAST *) {}
virtual void endVisit(ArrayAccessAST *) {}
virtual void endVisit(ArrayDeclaratorAST *) {}
virtual void endVisit(ArrayInitializerAST *) {}
@@ -257,6 +260,7 @@ public:
virtual void endVisit(EnumSpecifierAST *) {}
virtual void endVisit(EnumeratorAST *) {}
virtual void endVisit(ExceptionDeclarationAST *) {}
+ virtual void endVisit(ExpressionListParenAST *) {}
virtual void endVisit(ExpressionOrDeclarationStatementAST *) {}
virtual void endVisit(ExpressionStatementAST *) {}
virtual void endVisit(ForStatementAST *) {}
@@ -283,8 +287,6 @@ public:
virtual void endVisit(NestedNameSpecifierAST *) {}
virtual void endVisit(NewArrayDeclaratorAST *) {}
virtual void endVisit(NewExpressionAST *) {}
- virtual void endVisit(NewInitializerAST *) {}
- virtual void endVisit(NewPlacementAST *) {}
virtual void endVisit(NewTypeIdAST *) {}
virtual void endVisit(NoExceptSpecificationAST *) {}
virtual void endVisit(NumericLiteralAST *) {}
diff --git a/src/libs/3rdparty/cplusplus/ASTfwd.h b/src/libs/3rdparty/cplusplus/ASTfwd.h
index f429fe7101..722a5b0d38 100644
--- a/src/libs/3rdparty/cplusplus/ASTfwd.h
+++ b/src/libs/3rdparty/cplusplus/ASTfwd.h
@@ -32,6 +32,8 @@ class ASTVisitor;
class ASTMatcher;
class AccessDeclarationAST;
+class AliasDeclarationAST;
+class AlignofExpressionAST;
class ArrayAccessAST;
class ArrayDeclaratorAST;
class ArrayInitializerAST;
@@ -75,6 +77,7 @@ class EnumeratorAST;
class ExceptionDeclarationAST;
class ExceptionSpecificationAST;
class ExpressionAST;
+class ExpressionListParenAST;
class ExpressionOrDeclarationStatementAST;
class ExpressionStatementAST;
class ForStatementAST;
@@ -102,8 +105,6 @@ class NestedExpressionAST;
class NestedNameSpecifierAST;
class NewArrayDeclaratorAST;
class NewExpressionAST;
-class NewInitializerAST;
-class NewPlacementAST;
class NewTypeIdAST;
class NoExceptSpecificationAST;
class NumericLiteralAST;
diff --git a/src/libs/3rdparty/cplusplus/Bind.cpp b/src/libs/3rdparty/cplusplus/Bind.cpp
index 380b0ccaef..b21b167655 100644
--- a/src/libs/3rdparty/cplusplus/Bind.cpp
+++ b/src/libs/3rdparty/cplusplus/Bind.cpp
@@ -129,9 +129,8 @@ void Bind::setDeclSpecifiers(Symbol *symbol, const FullySpecifiedType &declSpeci
symbol->setStorage(storage);
if (Function *funTy = symbol->asFunction()) {
- if (declSpecifiers.isVirtual()) {
+ if (declSpecifiers.isVirtual())
funTy->setVirtual(true);
- }
}
if (declSpecifiers.isDeprecated())
@@ -182,6 +181,13 @@ void Bind::operator()(DeclarationAST *ast, Scope *scope)
(void) switchScope(previousScope);
}
+void Bind::operator()(StatementAST *ast, Scope *scope)
+{
+ Scope *previousScope = switchScope(scope);
+ statement(ast);
+ (void) switchScope(previousScope);
+}
+
FullySpecifiedType Bind::operator()(ExpressionAST *ast, Scope *scope)
{
Scope *previousScope = switchScope(scope);
@@ -466,9 +472,8 @@ void Bind::enumerator(EnumeratorAST *ast, Enum *symbol)
EnumeratorDeclaration *e = control()->newEnumeratorDeclaration(ast->identifier_token, name);
e->setType(control()->integerType(IntegerType::Int)); // ### introduce IntegerType::Enumerator
- if (ExpressionAST *expr = ast->expression) {
+ if (ExpressionAST *expr = ast->expression)
e->setConstantValue(asStringLiteral(expr->firstToken(), expr->lastToken()));
- }
symbol->addMember(e);
}
@@ -517,9 +522,7 @@ void Bind::memInitializer(MemInitializerAST *ast, Function *fun)
/*const Name *name =*/ this->name(ast->name);
Scope *previousScope = switchScope(fun);
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- /*ExpressionTy value =*/ this->expression(it->value);
- }
+ this->expression(ast->expression);
(void) switchScope(previousScope);
}
@@ -539,14 +542,18 @@ const Name *Bind::nestedNameSpecifier(NestedNameSpecifierAST *ast)
return class_or_namespace_name;
}
-bool Bind::visit(NewPlacementAST *ast)
+bool Bind::visit(ExpressionListParenAST *ast)
{
- (void) ast;
- assert(!"unreachable");
+ // unsigned lparen_token = ast->lparen_token;
+ for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
+ /*ExpressionTy value =*/ this->expression(it->value);
+ }
+ // unsigned rparen_token = ast->rparen_token;
+
return false;
}
-void Bind::newPlacement(NewPlacementAST *ast)
+void Bind::newPlacement(ExpressionListParenAST *ast)
{
if (! ast)
return;
@@ -578,23 +585,6 @@ FullySpecifiedType Bind::newArrayDeclarator(NewArrayDeclaratorAST *ast, const Fu
return type;
}
-bool Bind::visit(NewInitializerAST *ast)
-{
- (void) ast;
- assert(!"unreachable");
- return false;
-}
-
-void Bind::newInitializer(NewInitializerAST *ast)
-{
- if (! ast)
- return;
-
- // unsigned lparen_token = ast->lparen_token;
- ExpressionTy expression = this->expression(ast->expression);
- // unsigned rparen_token = ast->rparen_token;
-}
-
bool Bind::visit(NewTypeIdAST *ast)
{
(void) ast;
@@ -1084,6 +1074,7 @@ void Bind::capture(CaptureAST *ast)
if (! ast)
return;
+ name(ast->identifier);
}
bool Bind::visit(LambdaDeclaratorAST *ast)
@@ -1330,7 +1321,6 @@ bool Bind::visit(RangeBasedForStatementAST *ast)
block->addMember(decl);
}
- /*ExpressionTy initializer =*/ this->expression(ast->initializer);
/*ExpressionTy expression =*/ this->expression(ast->expression);
this->statement(ast->statement);
(void) switchScope(previousScope);
@@ -1636,7 +1626,7 @@ bool Bind::visit(NewExpressionAST *ast)
ExpressionTy type_id = this->expression(ast->type_id);
// unsigned rparen_token = ast->rparen_token;
this->newTypeId(ast->new_type_id);
- this->newInitializer(ast->new_initializer);
+ this->expression(ast->new_initializer);
return false;
}
@@ -1653,11 +1643,7 @@ bool Bind::visit(TypenameCallExpressionAST *ast)
{
// unsigned typename_token = ast->typename_token;
/*const Name *name =*/ this->name(ast->name);
- // unsigned lparen_token = ast->lparen_token;
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- ExpressionTy value = this->expression(it->value);
- }
- // unsigned rparen_token = ast->rparen_token;
+ this->expression(ast->expression);
return false;
}
@@ -1667,11 +1653,7 @@ bool Bind::visit(TypeConstructorCallAST *ast)
for (SpecifierListAST *it = ast->type_specifier_list; it; it = it->next) {
type = this->specifier(it->value, type);
}
- // unsigned lparen_token = ast->lparen_token;
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- ExpressionTy value = this->expression(it->value);
- }
- // unsigned rparen_token = ast->rparen_token;
+ this->expression(ast->expression);
return false;
}
@@ -1804,7 +1786,7 @@ bool Bind::visit(BracedInitializerAST *ast)
{
// unsigned lbrace_token = ast->lbrace_token;
for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- ExpressionTy value = this->expression(it->value);
+ /*ExpressionTy value =*/ this->expression(it->value);
}
// unsigned comma_token = ast->comma_token;
// unsigned rbrace_token = ast->rbrace_token;
@@ -1868,9 +1850,8 @@ bool Bind::visit(SimpleDeclarationAST *ast)
const Name *declName = 0;
unsigned sourceLocation = location(it->value, ast->firstToken());
- if (declaratorId && declaratorId->name) {
+ if (declaratorId && declaratorId->name)
declName = declaratorId->name->name;
- }
Declaration *decl = control()->newDeclaration(sourceLocation, declName);
decl->setType(declTy);
@@ -1901,7 +1882,10 @@ bool Bind::visit(SimpleDeclarationAST *ast)
if (Function *funTy = decl->type()->asFunctionType()) {
funTy->setMethodKey(methodKey);
- if (funTy->isVirtual() && it->value->equal_token)
+ bool pureVirtualInit = it->value->equal_token
+ && it->value->initializer
+ && it->value->initializer->asNumericLiteral();
+ if (funTy->isVirtual() && pureVirtualInit)
funTy->setPureVirtual(true);
}
}
@@ -2655,10 +2639,14 @@ bool Bind::visit(TemplateIdAST *ast)
}
const Identifier *id = identifier(ast->identifier_token);
+ const int tokenKindBeforeIdentifier(translationUnit()->tokenKind(ast->identifier_token - 1));
+ const bool isSpecialization = (tokenKindBeforeIdentifier == T_CLASS ||
+ tokenKindBeforeIdentifier == T_STRUCT);
if (templateArguments.empty())
- _name = control()->templateNameId(id);
+ _name = control()->templateNameId(id, isSpecialization);
else
- _name = control()->templateNameId(id, &templateArguments[0], templateArguments.size());
+ _name = control()->templateNameId(id, isSpecialization, &templateArguments[0],
+ templateArguments.size());
ast->name = _name;
return false;
@@ -2985,6 +2973,8 @@ bool Bind::visit(EnumSpecifierAST *ast)
Enum *e = control()->newEnum(sourceLocation, enumName);
e->setStartOffset(tokenAt(sourceLocation).end()); // at the end of the enum or identifier token.
e->setEndOffset(tokenAt(ast->lastToken() - 1).end());
+ if (ast->key_token)
+ e->setScoped(true);
ast->symbol = e;
_scope->addMember(e);
diff --git a/src/libs/3rdparty/cplusplus/Bind.h b/src/libs/3rdparty/cplusplus/Bind.h
index de0cf12557..ca2c6084ba 100644
--- a/src/libs/3rdparty/cplusplus/Bind.h
+++ b/src/libs/3rdparty/cplusplus/Bind.h
@@ -34,6 +34,7 @@ public:
void operator()(TranslationUnitAST *ast, Namespace *globalNamespace);
void operator()(DeclarationAST *ast, Scope *scope);
+ void operator()(StatementAST *ast, Scope *scope);
FullySpecifiedType operator()(ExpressionAST *ast, Scope *scope);
FullySpecifiedType operator()(NewTypeIdAST *ast, Scope *scope);
@@ -85,9 +86,8 @@ protected:
FullySpecifiedType exceptionSpecification(ExceptionSpecificationAST *ast, const FullySpecifiedType &init);
void memInitializer(MemInitializerAST *ast, Function *fun);
const Name *nestedNameSpecifier(NestedNameSpecifierAST *ast);
- void newPlacement(NewPlacementAST *ast);
+ void newPlacement(ExpressionListParenAST *ast);
FullySpecifiedType newArrayDeclarator(NewArrayDeclaratorAST *ast, const FullySpecifiedType &init);
- void newInitializer(NewInitializerAST *ast);
FullySpecifiedType newTypeId(NewTypeIdAST *ast);
OperatorNameId::Kind cppOperator(OperatorAST *ast);
void parameterDeclarationClause(ParameterDeclarationClauseAST *ast, unsigned lparen_token, Function *fun);
@@ -122,9 +122,7 @@ protected:
virtual bool visit(DynamicExceptionSpecificationAST *ast);
virtual bool visit(MemInitializerAST *ast);
virtual bool visit(NestedNameSpecifierAST *ast);
- virtual bool visit(NewPlacementAST *ast);
virtual bool visit(NewArrayDeclaratorAST *ast);
- virtual bool visit(NewInitializerAST *ast);
virtual bool visit(NewTypeIdAST *ast);
virtual bool visit(OperatorAST *ast);
virtual bool visit(ParameterDeclarationClauseAST *ast);
@@ -199,6 +197,7 @@ protected:
virtual bool visit(ObjCSelectorExpressionAST *ast);
virtual bool visit(LambdaExpressionAST *ast);
virtual bool visit(BracedInitializerAST *ast);
+ virtual bool visit(ExpressionListParenAST *ast);
// DeclarationAST
virtual bool visit(SimpleDeclarationAST *ast);
diff --git a/src/libs/3rdparty/cplusplus/Control.cpp b/src/libs/3rdparty/cplusplus/Control.cpp
index ba709de052..8f6136534f 100644
--- a/src/libs/3rdparty/cplusplus/Control.cpp
+++ b/src/libs/3rdparty/cplusplus/Control.cpp
@@ -131,9 +131,18 @@ template <> struct Compare<TemplateNameId>
const Identifier *id = name.identifier();
const Identifier *otherId = otherName.identifier();
- if (id == otherId)
- return std::lexicographical_compare(name.firstTemplateArgument(), name.lastTemplateArgument(),
- otherName.firstTemplateArgument(), otherName.lastTemplateArgument());
+ if (id == otherId) {
+ // we have to differentiate TemplateNameId with respect to specialization or
+ // instantiation
+ if (name.isSpecialization() == otherName.isSpecialization()) {
+ return std::lexicographical_compare(name.firstTemplateArgument(),
+ name.lastTemplateArgument(),
+ otherName.firstTemplateArgument(),
+ otherName.lastTemplateArgument());
+ } else {
+ return name.isSpecialization();
+ }
+ }
return id < otherId;
}
@@ -211,9 +220,10 @@ public:
}
template <typename _Iterator>
- const TemplateNameId *findOrInsertTemplateNameId(const Identifier *id, _Iterator first, _Iterator last)
+ const TemplateNameId *findOrInsertTemplateNameId(const Identifier *id, bool isSpecialization,
+ _Iterator first, _Iterator last)
{
- return templateNameIds.intern(TemplateNameId(id, first, last));
+ return templateNameIds.intern(TemplateNameId(id, isSpecialization, first, last));
}
const DestructorNameId *findOrInsertDestructorNameId(const Name *name)
@@ -598,10 +608,11 @@ const NumericLiteral *Control::numericLiteral(const char *chars)
}
const TemplateNameId *Control::templateNameId(const Identifier *id,
+ bool isSpecialization,
const FullySpecifiedType *const args,
unsigned argv)
{
- return d->findOrInsertTemplateNameId(id, args, args + argv);
+ return d->findOrInsertTemplateNameId(id, isSpecialization, args, args + argv);
}
const DestructorNameId *Control::destructorNameId(const Name *name)
diff --git a/src/libs/3rdparty/cplusplus/Control.h b/src/libs/3rdparty/cplusplus/Control.h
index 4132d5f3cf..cef4df40f7 100644
--- a/src/libs/3rdparty/cplusplus/Control.h
+++ b/src/libs/3rdparty/cplusplus/Control.h
@@ -51,6 +51,7 @@ public:
/// Returns the canonical template name id.
const TemplateNameId *templateNameId(const Identifier *id,
+ bool isSpecialization,
const FullySpecifiedType *const args = 0,
unsigned argc = 0);
diff --git a/src/libs/3rdparty/cplusplus/Keywords.cpp b/src/libs/3rdparty/cplusplus/Keywords.cpp
index cac51a4fd6..1da78381ac 100644
--- a/src/libs/3rdparty/cplusplus/Keywords.cpp
+++ b/src/libs/3rdparty/cplusplus/Keywords.cpp
@@ -573,6 +573,26 @@ static inline int classify7(const char *s, bool q, bool x) {
}
}
}
+ else if (x && s[0] == 'a') {
+ if (s[1] == 'l') {
+ if (s[2] == 'i') {
+ if (s[3] == 'g') {
+ if (s[4] == 'n') {
+ if (s[5] == 'a') {
+ if (s[6] == 's') {
+ return T_ALIGNAS;
+ }
+ }
+ else if (s[5] == 'o') {
+ if (s[6] == 'f') {
+ return T_ALIGNOF;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
else if (s[0] == 'd') {
if (s[1] == 'e') {
if (s[2] == 'f') {
diff --git a/src/libs/3rdparty/cplusplus/Literals.cpp b/src/libs/3rdparty/cplusplus/Literals.cpp
index 20e3a967a9..ca0cfc8735 100644
--- a/src/libs/3rdparty/cplusplus/Literals.cpp
+++ b/src/libs/3rdparty/cplusplus/Literals.cpp
@@ -206,9 +206,8 @@ bool Identifier::isEqualTo(const Name *other) const
return true;
else if (other) {
- if (const Identifier *nameId = other->asNameId()) {
+ if (const Identifier *nameId = other->asNameId())
return equalTo(nameId);
- }
}
return false;
}
diff --git a/src/libs/3rdparty/cplusplus/Names.cpp b/src/libs/3rdparty/cplusplus/Names.cpp
index 9024b65a91..4c5cb7db79 100644
--- a/src/libs/3rdparty/cplusplus/Names.cpp
+++ b/src/libs/3rdparty/cplusplus/Names.cpp
@@ -128,6 +128,27 @@ bool TemplateNameId::isEqualTo(const Name *other) const
return true;
}
+bool TemplateNameId::Compare::operator()(const TemplateNameId *name,
+ const TemplateNameId *other) const
+{
+ const Identifier *id = name->identifier();
+ const Identifier *otherId = other->identifier();
+
+ if (id == otherId) {
+ // we have to differentiate TemplateNameId with respect to specialization or instantiation
+ if (name->isSpecialization() == other->isSpecialization()) {
+ return std::lexicographical_compare(name->firstTemplateArgument(),
+ name->lastTemplateArgument(),
+ other->firstTemplateArgument(),
+ other->lastTemplateArgument());
+ } else {
+ return name->isSpecialization();
+ }
+ }
+
+ return id < otherId;
+}
+
OperatorNameId::OperatorNameId(Kind kind)
: _kind(kind)
{ }
diff --git a/src/libs/3rdparty/cplusplus/Names.h b/src/libs/3rdparty/cplusplus/Names.h
index 70c782591f..e600ec1daf 100644
--- a/src/libs/3rdparty/cplusplus/Names.h
+++ b/src/libs/3rdparty/cplusplus/Names.h
@@ -80,8 +80,11 @@ class CPLUSPLUS_EXPORT TemplateNameId: public Name
{
public:
template <typename _Iterator>
- TemplateNameId(const Identifier *identifier, _Iterator first, _Iterator last)
- : _identifier(identifier), _templateArguments(first, last) {}
+ TemplateNameId(const Identifier *identifier, bool isSpecialization, _Iterator first,
+ _Iterator last)
+ : _identifier(identifier)
+ , _templateArguments(first, last)
+ , _isSpecialization(isSpecialization) {}
virtual ~TemplateNameId();
@@ -100,6 +103,15 @@ public:
TemplateArgumentIterator firstTemplateArgument() const { return _templateArguments.begin(); }
TemplateArgumentIterator lastTemplateArgument() const { return _templateArguments.end(); }
+ bool isSpecialization() const { return _isSpecialization; }
+ // this is temporary solution needed in ClassOrNamespace::nestedType
+ // when we try to find correct specialization for instantiation
+ void setIsSpecialization(bool isSpecialization) { _isSpecialization = isSpecialization; }
+
+ // Comparator needed to distinguish between two different TemplateNameId(e.g.:used in std::map)
+ struct Compare: std::binary_function<const TemplateNameId *, const TemplateNameId *, bool> {
+ bool operator()(const TemplateNameId *name, const TemplateNameId *other) const;
+ };
protected:
virtual void accept0(NameVisitor *visitor) const;
@@ -107,6 +119,8 @@ protected:
private:
const Identifier *_identifier;
std::vector<FullySpecifiedType> _templateArguments;
+ // now TemplateNameId can be a specialization or an instantiation
+ bool _isSpecialization;
};
class CPLUSPLUS_EXPORT OperatorNameId: public Name
diff --git a/src/libs/3rdparty/cplusplus/Parser.cpp b/src/libs/3rdparty/cplusplus/Parser.cpp
index e1800229e7..71f0fad2d2 100644
--- a/src/libs/3rdparty/cplusplus/Parser.cpp
+++ b/src/libs/3rdparty/cplusplus/Parser.cpp
@@ -28,7 +28,6 @@
#include "QtContextKeywords.h"
#include <string>
#include <cstdio> // for putchar
-
#ifdef _MSC_VER
# define va_copy(dst, src) ((dst) = (src))
#elif defined(__INTEL_COMPILER) && !defined(va_copy)
@@ -107,7 +106,7 @@ inline int precedence(int tokenKind, bool templateArguments)
{
// ### this will/might need some tuning for C++0x
// (see: [temp.names]p3)
- if (templateArguments && tokenKind == T_GREATER)
+ if (templateArguments && (tokenKind == T_GREATER || tokenKind == T_GREATER_GREATER))
return -1;
if (lookAtAssignmentOperator(tokenKind))
@@ -212,6 +211,11 @@ bool Parser::switchTemplateArguments(bool templateArguments)
return previousTemplateArguments;
}
+bool Parser::maybeSplitGreaterGreaterToken(int n)
+{
+ return _translationUnit->maybeSplitGreaterGreaterToken(_tokenIndex + n - 1);
+}
+
bool Parser::blockErrors(bool block)
{ return _translationUnit->blockErrors(block); }
@@ -367,6 +371,18 @@ bool Parser::skip(int l, int r)
return false;
}
+int Parser::find(int token, int stopAt)
+{
+ for (int i = 1; ; ++i) {
+ const int tk = LA(i);
+ if (!tk || tk == stopAt)
+ return 0;
+ if (tk == token)
+ return i;
+ }
+ return 0;
+}
+
void Parser::match(int kind, unsigned *token)
{
if (LA() == kind)
@@ -421,9 +437,9 @@ bool Parser::parseTemplateId(NameAST *&node, unsigned template_token)
ast->template_token = template_token;
ast->identifier_token = consumeToken();
ast->less_token = consumeToken();
- if (LA() == T_GREATER || parseTemplateArgumentList(
+ if (maybeSplitGreaterGreaterToken() || LA() == T_GREATER || parseTemplateArgumentList(
ast->template_argument_list)) {
- if (LA() == T_GREATER) {
+ if (maybeSplitGreaterGreaterToken() || LA() == T_GREATER) {
ast->greater_token = consumeToken();
node = ast;
return true;
@@ -811,6 +827,9 @@ bool Parser::parseUsing(DeclarationAST *&node)
if (LA(2) == T_NAMESPACE)
return parseUsingDirective(node);
+ if (_cxx0xEnabled && LA(2) == T_IDENTIFIER && parseAliasDeclaration(node))
+ return true;
+
UsingAST *ast = new (_pool) UsingAST;
ast->using_token = consumeToken();
@@ -840,6 +859,37 @@ bool Parser::parseUsingDirective(DeclarationAST *&node)
return false;
}
+// alias-declaration = 'using' identifier attribute-specifier-seq(opt) '=' type-id ';'
+bool Parser::parseAliasDeclaration(DeclarationAST *&node)
+{
+ DEBUG_THIS_RULE();
+ if (LA() != T_USING || LA(2) != T_IDENTIFIER)
+ return false;
+
+ if (!find(T_EQUAL, T_SEMICOLON))
+ return false;
+
+ AliasDeclarationAST *alias = new (_pool) AliasDeclarationAST;
+ alias->using_token = consumeToken();
+ alias->identifier_token = consumeToken();
+
+ // ### attributes!
+ while (LA() != T_EQUAL)
+ consumeToken();
+
+ alias->equal_token = consumeToken();
+
+ ExpressionAST *expr = 0;
+ parseTypeId(expr);
+ if (expr)
+ alias->typeId = expr->asTypeId();
+
+ match(T_SEMICOLON, &alias->semicolon_token);
+
+ node = alias;
+ return true;
+}
+
bool Parser::parseConversionFunctionId(NameAST *&node)
{
DEBUG_THIS_RULE();
@@ -847,9 +897,8 @@ bool Parser::parseConversionFunctionId(NameAST *&node)
return false;
unsigned operator_token = consumeToken();
SpecifierListAST *type_specifier = 0;
- if (! parseTypeSpecifier(type_specifier)) {
+ if (! parseTypeSpecifier(type_specifier))
return false;
- }
PtrOperatorListAST *ptr_operators = 0, **ptr_operators_tail = &ptr_operators;
while (parsePtrOperator(*ptr_operators_tail))
ptr_operators_tail = &(*ptr_operators_tail)->next;
@@ -1057,7 +1106,7 @@ bool Parser::parseTemplateDeclaration(DeclarationAST *&node)
if (LA() == T_LESS) {
ast->less_token = consumeToken();
- if (LA() == T_GREATER || parseTemplateParameterList(ast->template_parameter_list))
+ if (maybeSplitGreaterGreaterToken() || LA() == T_GREATER || parseTemplateParameterList(ast->template_parameter_list))
match(T_GREATER, &ast->greater_token);
}
@@ -1165,7 +1214,7 @@ bool Parser::parseCvQualifiers(SpecifierListAST *&node)
spec->specifier_token = consumeToken();
*ast = new (_pool) SpecifierListAST(spec);
ast = &(*ast)->next;
- } else if(LA() == T___ATTRIBUTE__) {
+ } else if (LA() == T___ATTRIBUTE__) {
parseAttributeSpecifier(*ast);
ast = &(*ast)->next;
} else {
@@ -1176,6 +1225,21 @@ bool Parser::parseCvQualifiers(SpecifierListAST *&node)
return start != cursor();
}
+bool Parser::parseRefQualifier(unsigned &ref_qualifier)
+{
+ DEBUG_THIS_RULE();
+
+ if (!_cxx0xEnabled)
+ return false;
+
+ if (LA() == T_AMPER || LA() == T_AMPER_AMPER) {
+ ref_qualifier = consumeToken();
+ return true;
+ }
+
+ return false;
+}
+
/**
* \brief Handles override and final from C++ 2011, they are pseudo keywords and has special meaning only in function declaration
*/
@@ -1257,7 +1321,7 @@ bool Parser::parseTemplateArgument(ExpressionAST *&node)
if (_cxx0xEnabled && LA() == T_DOT_DOT_DOT)
index = 2;
- if (LA(index) == T_COMMA || LA(index) == T_GREATER)
+ if (LA(index) == T_COMMA || maybeSplitGreaterGreaterToken(index) || LA(index) == T_GREATER)
return true;
}
@@ -1425,11 +1489,12 @@ bool Parser::parseDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specif
bool blocked = blockErrors(true);
if (parseInitializer(initializer, &node->equal_token)) {
- NestedExpressionAST *expr = 0;
+ // maybe the initializer also parses as a FunctionDeclarator?
+ ExpressionListParenAST *expr = 0;
if (initializer)
- expr = initializer->asNestedExpression();
+ expr = initializer->asExpressionListParen();
if (expr) {
- if (expr->expression && expr->rparen_token && (LA() == T_COMMA || LA() == T_SEMICOLON)) {
+ if (expr->expression_list && expr->rparen_token && (LA() == T_COMMA || LA() == T_SEMICOLON)) {
rewind(lparen_token);
// check for ambiguous declarators.
@@ -1474,8 +1539,7 @@ bool Parser::parseDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specif
ast->rparen_token = consumeToken();
// ### parse attributes
parseCvQualifiers(ast->cv_qualifier_list);
- parseOverrideFinalQualifiers(ast->cv_qualifier_list);
- // ### parse ref-qualifiers
+ parseRefQualifier(ast->ref_qualifier_token);
parseExceptionSpecification(ast->exception_specification);
if (_cxx0xEnabled && ! node->ptr_operator_list && LA() == T_ARROW) {
@@ -1484,9 +1548,8 @@ bool Parser::parseDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specif
for (SpecifierListAST *iter = decl_specifier_list; !hasAuto && iter; iter = iter->next) {
SpecifierAST *spec = iter->value;
if (SimpleSpecifierAST *simpleSpec = spec->asSimpleSpecifier()) {
- if (_translationUnit->tokenKind(simpleSpec->specifier_token) == T_AUTO) {
+ if (_translationUnit->tokenKind(simpleSpec->specifier_token) == T_AUTO)
hasAuto = true;
- }
}
}
@@ -1494,14 +1557,15 @@ bool Parser::parseDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specif
parseTrailingReturnType(ast->trailing_return_type);
}
+ parseOverrideFinalQualifiers(ast->cv_qualifier_list);
+
*postfix_ptr = new (_pool) PostfixDeclaratorListAST(ast);
postfix_ptr = &(*postfix_ptr)->next;
} else if (LA() == T_LBRACKET) {
ArrayDeclaratorAST *ast = new (_pool) ArrayDeclaratorAST;
ast->lbracket_token = consumeToken();
- if (LA() == T_RBRACKET || parseConstantExpression(ast->expression)) {
+ if (LA() == T_RBRACKET || parseConstantExpression(ast->expression))
match(T_RBRACKET, &ast->rbracket_token);
- }
*postfix_ptr = new (_pool) PostfixDeclaratorListAST(ast);
postfix_ptr = &(*postfix_ptr)->next;
} else
@@ -1579,6 +1643,7 @@ bool Parser::parseAbstractDeclarator(DeclaratorAST *&node, SpecifierListAST *dec
ast->rparen_token = consumeToken();
}
parseCvQualifiers(ast->cv_qualifier_list);
+ parseRefQualifier(ast->ref_qualifier_token);
parseExceptionSpecification(ast->exception_specification);
*postfix_ptr = new (_pool) PostfixDeclaratorListAST(ast);
postfix_ptr = &(*postfix_ptr)->next;
@@ -1621,16 +1686,19 @@ bool Parser::parseEnumSpecifier(SpecifierListAST *&node)
{
DEBUG_THIS_RULE();
if (LA() == T_ENUM) {
- unsigned enum_token = consumeToken();
- if (_cxx0xEnabled && LA() == T_CLASS)
- consumeToken();
+ EnumSpecifierAST *ast = new (_pool) EnumSpecifierAST;
- NameAST *name = 0;
- parseName(name);
+ ast->enum_token = consumeToken();
+ if (_cxx0xEnabled && (LA() == T_CLASS || LA() == T_STRUCT))
+ ast->key_token = consumeToken();
+
+ parseName(ast->name);
+
+ if (_cxx0xEnabled && LA() == T_COLON) {
+ ast->colon_token = consumeToken();
+ parseTypeSpecifier(ast->type_specifier_list);
+ }
if (LA() == T_LBRACE) {
- EnumSpecifierAST *ast = new (_pool) EnumSpecifierAST;
- ast->enum_token = enum_token;
- ast->name = name;
ast->lbrace_token = consumeToken();
unsigned comma_token = 0;
EnumeratorListAST **enumerator_ptr = &ast->enumerator_list;
@@ -1643,9 +1711,8 @@ bool Parser::parseEnumSpecifier(SpecifierListAST *&node)
skipUntil(T_IDENTIFIER);
}
- if (parseEnumerator(*enumerator_ptr)) {
+ if (parseEnumerator(*enumerator_ptr))
enumerator_ptr = &(*enumerator_ptr)->next;
- }
if (LA() == T_COMMA && LA(2) == T_RBRACE)
ast->stray_comma_token = consumeToken();
@@ -1654,9 +1721,12 @@ bool Parser::parseEnumSpecifier(SpecifierListAST *&node)
match(T_COMMA, &comma_token);
}
match(T_RBRACE, &ast->rbrace_token);
- node = new (_pool) SpecifierListAST(ast);
- return true;
+ } else if (!_cxx0xEnabled) {
+ return false;
}
+
+ node = new (_pool) SpecifierListAST(ast);
+ return true;
}
return false;
}
@@ -1727,7 +1797,7 @@ bool Parser::parseTemplateTypeParameter(DeclarationAST *&node)
if (LA() == T_LESS)
ast->less_token = consumeToken();
parseTemplateParameterList(ast->template_parameter_list);
- if (LA() == T_GREATER)
+ if (maybeSplitGreaterGreaterToken() || LA() == T_GREATER)
ast->greater_token = consumeToken();
if (LA() == T_CLASS)
ast->class_token = consumeToken();
@@ -1747,7 +1817,7 @@ bool Parser::parseTemplateTypeParameter(DeclarationAST *&node)
return false;
}
-bool Parser::lookAtTypeParameter() const
+bool Parser::lookAtTypeParameter()
{
if (LA() == T_CLASS || LA() == T_TYPENAME) {
if (LA(2) == T_IDENTIFIER) {
@@ -1758,7 +1828,7 @@ bool Parser::lookAtTypeParameter() const
return true;
default:
- return false;
+ return maybeSplitGreaterGreaterToken(3);
}
} else if (LA(2) == T_COLON_COLON) {
// found something like template <typename ::foo::bar>...
@@ -1872,7 +1942,10 @@ bool Parser::parseParameterDeclaration(ParameterDeclarationAST *&node)
parseDeclaratorOrAbstractDeclarator(ast->declarator, decl_specifier_seq);
if (LA() == T_EQUAL) {
ast->equal_token = consumeToken();
- parseLogicalOrExpression(ast->expression);
+ if (!_cxx0xEnabled)
+ parseLogicalOrExpression(ast->expression);
+ else
+ parseInitializerClause0x(ast->expression);
}
node = ast;
@@ -2104,11 +2177,10 @@ bool Parser::parseQtPropertyDeclaration(DeclarationAST *&node)
SimpleNameAST *property_name = new (_pool) SimpleNameAST;
// special case: keywords are allowed for property names!
- if (tok().isKeyword()) {
+ if (tok().isKeyword())
property_name->identifier_token = consumeToken();
- } else {
+ else
match(T_IDENTIFIER, &property_name->identifier_token);
- }
ast->property_name = property_name;
QtPropertyDeclarationItemListAST **iter = &ast->property_declaration_item_list;
@@ -2446,7 +2518,9 @@ bool Parser::parseExceptionSpecification(ExceptionSpecificationAST *&node)
} else if (_cxx0xEnabled && LA() == T_NOEXCEPT) {
NoExceptSpecificationAST *ast = new (_pool) NoExceptSpecificationAST;
ast->noexcept_token = consumeToken();
- if (LA() == T_LPAREN && parseConstantExpression(ast->expression)) {
+ if (LA() == T_LPAREN) {
+ ast->lparen_token = consumeToken();
+ parseConstantExpression(ast->expression);
match(T_RPAREN, &ast->rparen_token);
}
node = ast;
@@ -2493,6 +2567,10 @@ bool Parser::parseInitDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_sp
consumeToken();
}
+ const bool isFunctionDeclarator = node
+ && node->postfix_declarator_list
+ && node->postfix_declarator_list->lastValue()
+ && node->postfix_declarator_list->lastValue()->asFunctionDeclarator();
if (declaringClass && LA() == T_COLON
&& (! node || ! node->postfix_declarator_list)) {
unsigned colon_token = consumeToken();
@@ -2506,7 +2584,20 @@ bool Parser::parseInitDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_sp
return true;
}
rewind(colon_token);
- } else if (node->core_declarator && (LA() == T_EQUAL || (! declaringClass && LA() == T_LPAREN))) {
+ } else if (isFunctionDeclarator && declaringClass && node->core_declarator && LA() == T_EQUAL && LA(3) == T_SEMICOLON) { // = 0, = delete, = default
+ if (!_cxx0xEnabled || LA(2) == T_NUMERIC_LITERAL) {
+ parseInitializer(node->initializer, &node->equal_token);
+ } else {
+ node->equal_token = consumeToken();
+
+ IdExpressionAST *id_expr = new (_pool) IdExpressionAST;
+ node->initializer = id_expr;
+
+ SimpleNameAST *simple_name = new (_pool) SimpleNameAST;
+ id_expr->name = simple_name;
+ simple_name->identifier_token = consumeToken();
+ }
+ } else if (node->core_declarator && (LA() == T_EQUAL || (_cxx0xEnabled && !isFunctionDeclarator && LA() == T_LBRACE) || (! declaringClass && LA() == T_LPAREN))) {
parseInitializer(node->initializer, &node->equal_token);
}
return true;
@@ -2555,7 +2646,7 @@ bool Parser::parseInitializer0x(ExpressionAST *&node, unsigned *equals_token)
}
else if (LA() == T_LPAREN) {
- return parsePrimaryExpression(node);
+ return parseExpressionListParen(node);
}
return false;
@@ -2581,8 +2672,7 @@ bool Parser::parseInitializerClause0x(ExpressionAST *&node)
if (LA() == T_LBRACE)
return parseBracedInitList0x(node);
- parseAssignmentExpression(node);
- return true;
+ return parseAssignmentExpression(node);
}
bool Parser::parseInitializerList0x(ExpressionListAST *&node)
@@ -2650,7 +2740,9 @@ bool Parser::parseMemInitializerList(MemInitializerListAST *&node)
else if (_cxx0xEnabled && LA() == T_DOT_DOT_DOT && LA(2) == T_LBRACE)
break;
- else if (LA() == T_COMMA || (LA() == T_IDENTIFIER && (LA(2) == T_LPAREN || LA(2) == T_COLON_COLON))) {
+ else if (LA() == T_COMMA
+ || (LA() == T_IDENTIFIER
+ && (LA(2) == T_LPAREN || LA(2) == T_COLON_COLON || (_cxx0xEnabled && LA(2) == T_LBRACE)))) {
if (LA() != T_COMMA)
error(cursor(), "expected `,'");
else
@@ -2687,9 +2779,18 @@ bool Parser::parseMemInitializer(MemInitializerListAST *&node)
MemInitializerAST *ast = new (_pool) MemInitializerAST;
ast->name = name;
- match(T_LPAREN, &ast->lparen_token);
- parseExpressionList(ast->expression_list);
- match(T_RPAREN, &ast->rparen_token);
+
+ if (LA() == T_LPAREN) {
+ parseExpressionListParen(ast->expression);
+ } else if (_cxx0xEnabled && LA() == T_LBRACE) {
+ parseBracedInitList0x(ast->expression);
+ } else {
+ if (!_cxx0xEnabled)
+ error(cursor(), "expected '('");
+ else
+ error(cursor(), "expected '(' or '{'");
+ return false;
+ }
node = new (_pool) MemInitializerListAST;
node->value = ast;
@@ -2731,12 +2832,9 @@ bool Parser::parseExpressionList(ExpressionListAST *&node)
{
DEBUG_THIS_RULE();
-#ifdef CPLUSPLUS_WITH_CXXOX_INITIALIZER_LIST
if (_cxx0xEnabled)
return parseInitializerList0x(node);
-#endif
- // ### remove me
ExpressionListAST **expression_list_ptr = &node;
ExpressionAST *expression = 0;
if (parseAssignmentExpression(expression)) {
@@ -2846,7 +2944,7 @@ bool Parser::parseUnqualifiedName(NameAST *&node, bool acceptTemplateId)
if (acceptTemplateId && LA(2) == T_LESS) {
bool blocked = blockErrors(true);
if (parseTemplateId(node)
- && (! _templateArguments || (LA() == T_COMMA || LA() == T_GREATER ||
+ && (! _templateArguments || (LA() == T_COMMA || maybeSplitGreaterGreaterToken() || LA() == T_GREATER ||
LA() == T_LPAREN || LA() == T_RPAREN ||
LA() == T_STAR || LA() == T_AMPER || // ptr-operators
LA() == T_COLON_COLON))) {
@@ -3088,7 +3186,10 @@ bool Parser::parseReturnStatement(StatementAST *&node)
if (LA() == T_RETURN) {
ReturnStatementAST *ast = new (_pool) ReturnStatementAST;
ast->return_token = consumeToken();
- parseExpression(ast->expression);
+ if (_cxx0xEnabled && LA() == T_LBRACE)
+ parseBracedInitList0x(ast->expression);
+ else
+ parseExpression(ast->expression);
match(T_SEMICOLON, &ast->semicolon_token);
node = ast;
return true;
@@ -3377,7 +3478,10 @@ bool Parser::parseForStatement(StatementAST *&node)
ast->colon_token = consumeToken();
blockErrors(blocked);
- parseExpression(ast->expression);
+ if (LA() == T_LBRACE)
+ parseBracedInitList0x(ast->expression);
+ else
+ parseExpression(ast->expression);
match(T_RPAREN, &ast->rparen_token);
parseStatement(ast->statement);
@@ -3755,7 +3859,6 @@ bool Parser::parseBuiltinTypeSpecifier(SpecifierListAST *&node)
if (parseExpression(ast->expression))
match(T_RPAREN, &ast->rparen_token);
node = new (_pool) SpecifierListAST(ast);
- skipUntilDeclaration();
return true;
} else if (lookAtBuiltinTypeSpecifier()) {
SimpleSpecifierAST *ast = new (_pool) SimpleSpecifierAST;
@@ -3800,12 +3903,17 @@ bool Parser::parseSimpleDeclaration(DeclarationAST *&node, ClassSpecifierAST *de
startOfNamedTypeSpecifier = cursor();
if (parseName(named_type_specifier)) {
- if (LA() == T_LPAREN && identifier(named_type_specifier) == className(declaringClass)) {
- // looks like a constructor declaration
- rewind(startOfNamedTypeSpecifier);
- break;
- }
+ const Identifier *classIdentifier = className(declaringClass);
+ if (QualifiedNameAST *qn = named_type_specifier->asQualifiedName())
+ if (NestedNameSpecifierListAST *namesList = qn->nested_name_specifier_list)
+ if (NestedNameSpecifierAST *lastName = namesList->lastValue())
+ classIdentifier = identifier(lastName->class_or_namespace_name);
+ if (LA() == T_LPAREN && identifier(named_type_specifier) == classIdentifier) {
+ // looks like a constructor declaration
+ rewind(startOfNamedTypeSpecifier);
+ break;
+ }
NamedTypeSpecifierAST *spec = new (_pool) NamedTypeSpecifierAST;
spec->name = named_type_specifier;
@@ -3818,7 +3926,9 @@ bool Parser::parseSimpleDeclaration(DeclarationAST *&node, ClassSpecifierAST *de
}
} else if (! has_type_specifier && LA() == T_ENUM) {
unsigned startOfTypeSpecifier = cursor();
- if (! parseElaboratedTypeSpecifier(*decl_specifier_seq_ptr) || LA() == T_LBRACE) {
+ if (! parseElaboratedTypeSpecifier(*decl_specifier_seq_ptr)
+ || LA() == T_LBRACE
+ || (_cxx0xEnabled && LA() == T_COLON)) {
rewind(startOfTypeSpecifier);
if (! parseEnumSpecifier(*decl_specifier_seq_ptr)) {
error(startOfTypeSpecifier,
@@ -4599,13 +4709,16 @@ bool Parser::parseTypenameCallExpression(ExpressionAST *&node)
if (LA() == T_TYPENAME) {
unsigned typename_token = consumeToken();
NameAST *name = 0;
- if (parseName(name) && LA() == T_LPAREN) {
+ if (parseName(name)
+ && (LA() == T_LPAREN || (_cxx0xEnabled && LA() == T_LBRACE))) {
TypenameCallExpressionAST *ast = new (_pool) TypenameCallExpressionAST;
ast->typename_token = typename_token;
ast->name = name;
- ast->lparen_token = consumeToken();
- parseExpressionList(ast->expression_list);
- match(T_RPAREN, &ast->rparen_token);
+ if (LA() == T_LPAREN) {
+ parseExpressionListParen(ast->expression);
+ } else { // T_LBRACE
+ parseBracedInitList0x(ast->expression);
+ }
node = ast;
return true;
}
@@ -4658,21 +4771,19 @@ bool Parser::parseCorePostfixExpression(ExpressionAST *&node)
bool blocked = blockErrors(true);
if (lookAtBuiltinTypeSpecifier() &&
parseSimpleTypeSpecifier(type_specifier) &&
- LA() == T_LPAREN) {
- unsigned lparen_token = consumeToken();
- ExpressionListAST *expression_list = 0;
- parseExpressionList(expression_list);
- if (LA() == T_RPAREN) {
- unsigned rparen_token = consumeToken();
- TypeConstructorCallAST *ast = new (_pool) TypeConstructorCallAST;
- ast->type_specifier_list = type_specifier;
- ast->lparen_token = lparen_token;
- ast->expression_list = expression_list;
- ast->rparen_token = rparen_token;
- node = ast;
- blockErrors(blocked);
- return true;
+ (LA() == T_LPAREN || (_cxx0xEnabled && LA() == T_LBRACE))) {
+ ExpressionAST *expr = 0;
+ if (LA() == T_LPAREN) {
+ parseExpressionListParen(expr);
+ } else { // T_LBRACE
+ parseBracedInitList0x(expr);
}
+ TypeConstructorCallAST *ast = new (_pool) TypeConstructorCallAST;
+ ast->type_specifier_list = type_specifier;
+ ast->expression = expr;
+ node = ast;
+ blockErrors(blocked);
+ return true;
}
rewind(start);
@@ -4722,6 +4833,14 @@ bool Parser::parsePostfixExpression(ExpressionAST *&node)
match(T_RBRACKET, &ast->rbracket_token);
ast->base_expression = node;
node = ast;
+ } else if (_cxx0xEnabled && LA() == T_LBRACE && node->asIdExpression()) {
+ // this is slightly inconsistent: simple-type-specifier '(' expression-list ')'
+ // gets parsed as a CallAST while simple-type-specifier brace-init-list
+ // is a TypenameCallExpressionAST
+ TypenameCallExpressionAST *ast = new (_pool) TypenameCallExpressionAST;
+ ast->name = node->asIdExpression()->name;
+ parseBracedInitList0x(ast->expression);
+ node = ast;
} else if (LA() == T_PLUS_PLUS || LA() == T_MINUS_MINUS) {
PostIncrDecrAST *ast = new (_pool) PostIncrDecrAST;
ast->incr_decr_token = consumeToken();
@@ -4808,6 +4927,24 @@ bool Parser::parseUnaryExpression(ExpressionAST *&node)
return true;
}
+ case T_ALIGNOF: {
+ if (!_cxx0xEnabled)
+ break;
+
+ AlignofExpressionAST *ast = new (_pool) AlignofExpressionAST;
+ ast->alignof_token = consumeToken();
+
+ match(T_LPAREN, &ast->lparen_token);
+ ExpressionAST *temp = 0;
+ parseTypeId(temp);
+ if (temp)
+ ast->typeId = temp->asTypeId();
+ match(T_RPAREN, &ast->rparen_token);
+
+ node = ast;
+ return true;
+ }
+
default:
break;
} // switch
@@ -4823,15 +4960,15 @@ bool Parser::parseUnaryExpression(ExpressionAST *&node)
}
// new-placement ::= T_LPAREN expression-list T_RPAREN
-bool Parser::parseNewPlacement(NewPlacementAST *&node)
+bool Parser::parseExpressionListParen(ExpressionAST *&node)
{
DEBUG_THIS_RULE();
if (LA() == T_LPAREN) {
unsigned lparen_token = consumeToken();
ExpressionListAST *expression_list = 0;
- if (parseExpressionList(expression_list) && expression_list && LA() == T_RPAREN) {
+ if (parseExpressionList(expression_list) && LA() == T_RPAREN) {
unsigned rparen_token = consumeToken();
- NewPlacementAST *ast = new (_pool) NewPlacementAST;
+ ExpressionListParenAST *ast = new (_pool) ExpressionListParenAST;
ast->lparen_token = lparen_token;
ast->expression_list = expression_list;
ast->rparen_token = rparen_token;
@@ -4843,6 +4980,7 @@ bool Parser::parseNewPlacement(NewPlacementAST *&node)
return false;
}
+
// new-expression ::= T_COLON_COLON? T_NEW new-placement.opt
// new-type-id new-initializer.opt
// new-expression ::= T_COLON_COLON? T_NEW new-placement.opt
@@ -4859,14 +4997,14 @@ bool Parser::parseNewExpression(ExpressionAST *&node)
ast->new_token = consumeToken();
- NewPlacementAST *new_placement = 0;
+ ExpressionAST *parenExpressionList = 0;
- if (parseNewPlacement(new_placement)) {
+ if (parseExpressionListParen(parenExpressionList)) {
unsigned after_new_placement = cursor();
NewTypeIdAST *new_type_id = 0;
if (parseNewTypeId(new_type_id)) {
- ast->new_placement = new_placement;
+ ast->new_placement = parenExpressionList->asExpressionListParen();
ast->new_type_id = new_type_id;
parseNewInitializer(ast->new_initializer);
// recognized new-placement.opt new-type-id new-initializer.opt
@@ -4879,7 +5017,7 @@ bool Parser::parseNewExpression(ExpressionAST *&node)
unsigned lparen_token = consumeToken();
ExpressionAST *type_id = 0;
if (parseTypeId(type_id) && LA() == T_RPAREN) {
- ast->new_placement = new_placement;
+ ast->new_placement = parenExpressionList->asExpressionListParen();
ast->lparen_token = lparen_token;
ast->type_id = type_id;
ast->rparen_token = consumeToken();
@@ -4950,21 +5088,13 @@ bool Parser::parseNewArrayDeclarator(NewArrayDeclaratorListAST *&node)
return true;
}
-bool Parser::parseNewInitializer(NewInitializerAST *&node)
+bool Parser::parseNewInitializer(ExpressionAST *&node)
{
DEBUG_THIS_RULE();
- if (LA() == T_LPAREN) {
- unsigned lparen_token = consumeToken();
- ExpressionAST *expression = 0;
- if (LA() == T_RPAREN || parseExpression(expression)) {
- NewInitializerAST *ast = new (_pool) NewInitializerAST;
- ast->lparen_token = lparen_token;
- ast->expression = expression;
- match(T_RPAREN, &ast->rparen_token);
- node = ast;
- return true;
- }
- }
+ if (LA() == T_LPAREN)
+ return parseExpressionListParen(node);
+ else if (_cxx0xEnabled && LA() == T_LBRACE)
+ return parseBracedInitList0x(node);
return false;
}
@@ -5188,8 +5318,13 @@ void Parser::parseExpressionWithOperatorPrecedence(ExpressionAST *&lhs, int minP
if (operPrecedence <= Prec::Conditional && isCPlusPlus) {
// in C++ you can put a throw in the right-most expression of a conditional expression,
// or an assignment, so some special handling:
- if (!parseAssignmentExpression(rhs))
- return;
+ if (_cxx0xEnabled) {
+ if (!parseInitializerClause0x(rhs))
+ return;
+ } else {
+ if (!parseAssignmentExpression(rhs))
+ return;
+ }
} else {
// for C & all other expressions:
if (!parseCastExpression(rhs))
@@ -5649,9 +5784,8 @@ bool Parser::parseObjCMethodDefinition(DeclarationAST *&node)
// - (void) foo; { body; }
// so a method is a forward declaration when it doesn't have a _body_.
// However, we still need to read the semicolon.
- if (LA() == T_SEMICOLON) {
+ if (LA() == T_SEMICOLON)
ast->semicolon_token = consumeToken();
- }
parseFunctionBody(ast->function_body);
@@ -6156,41 +6290,56 @@ bool Parser::parseLambdaCapture(LambdaCaptureAST *&node)
return true;
}
-bool Parser::parseCapture(CaptureAST *&)
+bool Parser::parseCapture(CaptureAST *&node)
{
DEBUG_THIS_RULE();
- if (LA() == T_IDENTIFIER) {
- consumeToken();
- return true;
- } else if (LA() == T_AMPER && LA(2) == T_IDENTIFIER) {
- consumeToken();
+ if (LA() == T_THIS) {
consumeToken();
return true;
+ }
- } else if (LA() == T_THIS) {
+ if (LA() == T_AMPER)
consumeToken();
+
+ if (LA() == T_IDENTIFIER) {
+ SimpleNameAST *ast = new (_pool) SimpleNameAST;
+ ast->identifier_token = consumeToken();
+
+ node = new (_pool) CaptureAST;
+ node->identifier = ast;
return true;
}
return false;
}
-bool Parser::parseCaptureList(CaptureListAST *&)
+bool Parser::parseCaptureList(CaptureListAST *&node)
{
DEBUG_THIS_RULE();
CaptureAST *capture = 0;
if (parseCapture(capture)) {
+ node = new (_pool) CaptureListAST;
+ node->value = capture;
+
+ CaptureListAST **l = &node->next;
while (LA() == T_COMMA) {
consumeToken(); // consume `,'
-
+ CaptureAST *capture = 0;
parseCapture(capture);
+ if (capture) {
+ *l = new (_pool) CaptureListAST;
+ (*l)->value = capture;
+ l = &(*l)->next;
+ }
}
+
+ return true;
}
- return true;
+ return false;
}
bool Parser::parseLambdaDeclarator(LambdaDeclaratorAST *&node)
diff --git a/src/libs/3rdparty/cplusplus/Parser.h b/src/libs/3rdparty/cplusplus/Parser.h
index 406e8f2d69..f5971e4040 100644
--- a/src/libs/3rdparty/cplusplus/Parser.h
+++ b/src/libs/3rdparty/cplusplus/Parser.h
@@ -82,6 +82,7 @@ public:
bool parseConstantExpression(ExpressionAST *&node);
bool parseCtorInitializer(CtorInitializerAST *&node);
bool parseCvQualifiers(SpecifierListAST *&node);
+ bool parseRefQualifier(unsigned &ref_qualifier);
bool parseOverrideFinalQualifiers(SpecifierListAST *&node);
bool parseDeclaratorOrAbstractDeclarator(DeclaratorAST *&node, SpecifierListAST *decl_specifier_list);
bool parseDeclaration(DeclarationAST *&node);
@@ -131,8 +132,8 @@ public:
bool parseNamespaceAliasDefinition(DeclarationAST *&node);
bool parseNewArrayDeclarator(NewArrayDeclaratorListAST *&node);
bool parseNewExpression(ExpressionAST *&node);
- bool parseNewPlacement(NewPlacementAST *&node);
- bool parseNewInitializer(NewInitializerAST *&node);
+ bool parseExpressionListParen(ExpressionAST *&node);
+ bool parseNewInitializer(ExpressionAST *&node);
bool parseNewTypeId(NewTypeIdAST *&node);
bool parseOperator(OperatorAST *&node);
bool parseConversionFunctionId(NameAST *&node);
@@ -189,6 +190,7 @@ public:
bool parseUnqualifiedName(NameAST *&node, bool acceptTemplateId = true);
bool parseUsing(DeclarationAST *&node);
bool parseUsingDirective(DeclarationAST *&node);
+ bool parseAliasDeclaration(DeclarationAST *&node);
bool parseWhileStatement(StatementAST *&node);
void parseExpressionWithOperatorPrecedence(ExpressionAST *&lhs, int minPrecedence);
@@ -254,8 +256,9 @@ public:
void skipUntilDeclaration();
bool skipUntilStatement();
bool skip(int l, int r);
+ int find(int token, int stopAt);
- bool lookAtTypeParameter() const;
+ bool lookAtTypeParameter();
bool lookAtCVQualifier() const;
bool lookAtFunctionSpecifier() const;
bool lookAtStorageClassSpecifier() const;
@@ -273,6 +276,7 @@ public:
int peekAtQtContextKeyword() const;
bool switchTemplateArguments(bool templateArguments);
+ bool maybeSplitGreaterGreaterToken(int n = 1);
bool blockErrors(bool block);
void warning(unsigned index, const char *format, ...);
diff --git a/src/libs/3rdparty/cplusplus/Symbol.cpp b/src/libs/3rdparty/cplusplus/Symbol.cpp
index b6216f002c..cd8ec1ffdd 100644
--- a/src/libs/3rdparty/cplusplus/Symbol.cpp
+++ b/src/libs/3rdparty/cplusplus/Symbol.cpp
@@ -105,7 +105,7 @@ Symbol::Symbol(TranslationUnit *translationUnit, unsigned sourceLocation, const
Symbol::Symbol(Clone *clone, Subst *subst, Symbol *original)
: _name(clone->name(original->_name, subst)),
- _scope(0),
+ _scope(original->_scope),
_next(0),
_fileId(clone->control()->stringLiteral(original->fileName(), original->fileNameLength())),
_sourceLocation(original->_sourceLocation),
diff --git a/src/libs/3rdparty/cplusplus/Symbols.cpp b/src/libs/3rdparty/cplusplus/Symbols.cpp
index 2ac8075f1c..1a16c5ed7f 100644
--- a/src/libs/3rdparty/cplusplus/Symbols.cpp
+++ b/src/libs/3rdparty/cplusplus/Symbols.cpp
@@ -231,12 +231,6 @@ bool Function::isEqualTo(const Type *other) const
return false;
else if (isVolatile() != o->isVolatile())
return false;
-#ifdef ICHECK_BUILD
- else if (isInvokable() != o->isInvokable())
- return false;
- else if (isSignal() != o->isSignal())
- return false;
-#endif
const Name *l = unqualifiedName();
const Name *r = o->unqualifiedName();
@@ -256,37 +250,6 @@ bool Function::isEqualTo(const Type *other) const
return false;
}
-#ifdef ICHECK_BUILD
-bool Function::isEqualTo(const Function* fct, bool ignoreName/* = false*/) const
-{
- if (!ignoreName)
- return isEqualTo((Type*)fct);
-
- if (! fct)
- return false;
- else if (isConst() != fct->isConst())
- return false;
- else if (isVolatile() != fct->isVolatile())
- return false;
- else if (isInvokable() != fct->isInvokable())
- return false;
- else if (isSignal() != fct->isSignal())
- return false;
-
- if (_arguments->symbolCount() != fct->_arguments->symbolCount())
- return false;
- else if (! _returnType.isEqualTo(fct->_returnType))
- return false;
- for (unsigned i = 0; i < _arguments->symbolCount(); ++i) {
- Symbol *l = _arguments->symbolAt(i);
- Symbol *r = fct->_arguments->symbolAt(i);
- if (! l->type().isEqualTo(r->type()))
- return false;
- }
- return true;
-}
-#endif
-
void Function::accept0(TypeVisitor *visitor)
{ visitor->visit(this); }
@@ -458,10 +421,12 @@ void Block::visitSymbol0(SymbolVisitor *visitor)
Enum::Enum(TranslationUnit *translationUnit, unsigned sourceLocation, const Name *name)
: Scope(translationUnit, sourceLocation, name)
+ , _isScoped(false)
{ }
Enum::Enum(Clone *clone, Subst *subst, Enum *original)
: Scope(clone, subst, original)
+ , _isScoped(original->isScoped())
{ }
Enum::~Enum()
@@ -484,6 +449,16 @@ bool Enum::isEqualTo(const Type *other) const
return l->isEqualTo(r);
}
+bool Enum::isScoped() const
+{
+ return _isScoped;
+}
+
+void Enum::setScoped(bool scoped)
+{
+ _isScoped = scoped;
+}
+
void Enum::accept0(TypeVisitor *visitor)
{ visitor->visit(this); }
diff --git a/src/libs/3rdparty/cplusplus/Symbols.h b/src/libs/3rdparty/cplusplus/Symbols.h
index e7fae94892..b6a711b8f8 100644
--- a/src/libs/3rdparty/cplusplus/Symbols.h
+++ b/src/libs/3rdparty/cplusplus/Symbols.h
@@ -279,10 +279,16 @@ public:
virtual Enum *asEnumType()
{ return this; }
+ bool isScoped() const;
+ void setScoped(bool scoped);
+
protected:
virtual void visitSymbol0(SymbolVisitor *visitor);
virtual void accept0(TypeVisitor *visitor);
virtual bool matchType0(const Type *otherType, TypeMatcher *matcher) const;
+
+private:
+ bool _isScoped;
};
class CPLUSPLUS_EXPORT Function: public Scope, public Type
@@ -341,10 +347,6 @@ public:
bool isPureVirtual() const;
void setPureVirtual(bool isPureVirtual);
-#ifdef ICHECK_BUILD
- bool isEqualTo(const Function* fct, bool ignoreName = false) const;
-#endif
-
// Symbol's interface
virtual FullySpecifiedType type() const;
diff --git a/src/libs/3rdparty/cplusplus/Templates.cpp b/src/libs/3rdparty/cplusplus/Templates.cpp
index 3cf6ff62be..c81ed51b09 100644
--- a/src/libs/3rdparty/cplusplus/Templates.cpp
+++ b/src/libs/3rdparty/cplusplus/Templates.cpp
@@ -414,9 +414,10 @@ void CloneName::visit(const TemplateNameId *name)
for (unsigned i = 0; i < args.size(); ++i)
args[i] = _clone->type(name->templateArgumentAt(i), _subst);
if (args.empty())
- _name = _control->templateNameId(_clone->identifier(name->identifier()));
+ _name = _control->templateNameId(_clone->identifier(name->identifier()), name->isSpecialization());
else
- _name = _control->templateNameId(_clone->identifier(name->identifier()), &args[0], args.size());
+ _name = _control->templateNameId(_clone->identifier(name->identifier()), name->isSpecialization(),
+ &args[0], args.size());
}
void CloneName::visit(const DestructorNameId *name)
@@ -499,9 +500,8 @@ Symbol *Clone::instantiate(Template *templ, const FullySpecifiedType *const args
if (argc < templ->templateParameterCount()) {
for (unsigned i = argc; i < templ->templateParameterCount(); ++i) {
Symbol *formal = templ->templateParameterAt(i);
- if (TypenameArgument *tn = formal->asTypenameArgument()) {
+ if (TypenameArgument *tn = formal->asTypenameArgument())
subst.bind(name(formal->name(), &subst), type(tn->type(), &subst));
- }
}
}
if (Symbol *inst = symbol(templ->declaration(), &subst)) {
@@ -529,7 +529,8 @@ FullySpecifiedType Subst::apply(const Name *name) const
const NamedType *name = apply(q->base())->asNamedType();
const NamedType *unqualified = apply(q->name())->asNamedType();
if (name && name->name()->identifier() != 0 && unqualified)
- return control()->namedType(control()->qualifiedNameId(name->name()->identifier(), unqualified->name()));
+ return control()->namedType(control()->qualifiedNameId(name->name()->identifier(),
+ unqualified->name()));
}
}
diff --git a/src/libs/3rdparty/cplusplus/Templates.h b/src/libs/3rdparty/cplusplus/Templates.h
index 04064a8906..2784f02d7f 100644
--- a/src/libs/3rdparty/cplusplus/Templates.h
+++ b/src/libs/3rdparty/cplusplus/Templates.h
@@ -54,6 +54,8 @@ public:
FullySpecifiedType &operator[](const Name *name) { return _map[name]; }
+ bool contains(const Name *name) const { return _map.find(name) != _map.end(); }
+
private:
Control *_control;
Subst *_previous;
diff --git a/src/libs/3rdparty/cplusplus/Token.cpp b/src/libs/3rdparty/cplusplus/Token.cpp
index dcc18601c2..ed3319aeab 100644
--- a/src/libs/3rdparty/cplusplus/Token.cpp
+++ b/src/libs/3rdparty/cplusplus/Token.cpp
@@ -46,7 +46,7 @@ static const char *token_names[] = {
("|="), ("||"), ("+"), ("+="), ("++"), ("#"), ("##"), ("?"), ("}"),
("]"), (")"), (";"), ("*"), ("*="), ("~"), ("~="),
- ("asm"), ("auto"), ("bool"), ("break"), ("case"), ("catch"),
+ ("alignas"), ("alignof"), ("asm"), ("auto"), ("bool"), ("break"), ("case"), ("catch"),
("char"), ("char16_t"), ("char32_t"),
("class"), ("const"), ("const_cast"), ("constexpr"), ("continue"),
("decltype"), ("default"),
diff --git a/src/libs/3rdparty/cplusplus/Token.h b/src/libs/3rdparty/cplusplus/Token.h
index a89e552256..3d253151bd 100644
--- a/src/libs/3rdparty/cplusplus/Token.h
+++ b/src/libs/3rdparty/cplusplus/Token.h
@@ -115,7 +115,9 @@ enum Kind {
T_LAST_OPERATOR = T_TILDE_EQUAL,
T_FIRST_KEYWORD,
- T_ASM = T_FIRST_KEYWORD,
+ T_ALIGNAS = T_FIRST_KEYWORD,
+ T_ALIGNOF,
+ T_ASM,
T_AUTO,
T_BOOL,
T_BREAK,
diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
index a26a23eabc..949badccf5 100644
--- a/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
+++ b/src/libs/3rdparty/cplusplus/TranslationUnit.cpp
@@ -206,16 +206,16 @@ void TranslationUnit::tokenize()
lex(&tk);
// Gather where the expansion happens and its length.
- unsigned macroOffset = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
+ //unsigned macroOffset = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
lex(&tk);
lex(&tk); // Skip the separating comma
- unsigned macroLength = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
+ //unsigned macroLength = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
lex(&tk);
// NOTE: We are currently not using the macro offset and length. They
// are kept here for now because of future use.
- Q_UNUSED(macroOffset)
- Q_UNUSED(macroLength)
+ //Q_UNUSED(macroOffset)
+ //Q_UNUSED(macroLength)
// Now we need to gather the real line and columns from the upcoming
// tokens. But notice this is only relevant for tokens which are expanded
@@ -552,6 +552,34 @@ unsigned TranslationUnit::findPreviousLineOffset(unsigned tokenIndex) const
return lineOffset;
}
+bool TranslationUnit::maybeSplitGreaterGreaterToken(unsigned tokenIndex)
+{
+ Token &tok = _tokens->at(tokenIndex);
+ if (tok.kind() != T_GREATER_GREATER)
+ return false;
+
+ tok.f.kind = T_GREATER;
+ tok.f.length = 1;
+
+ Token newGreater;
+ newGreater.f.kind = T_GREATER;
+ newGreater.f.expanded = tok.f.expanded;
+ newGreater.f.generated = tok.f.generated;
+ newGreater.f.length = 1;
+ newGreater.offset = tok.offset + 1;
+
+ _tokens->insert(_tokens->begin() + tokenIndex + 1, newGreater);
+
+ std::map<unsigned, std::pair<unsigned, unsigned> >::const_iterator it =
+ _expandedLineColumn.find(tok.offset);
+ if (it != _expandedLineColumn.end()) {
+ const std::pair<unsigned, unsigned> newPosition(it->second.first, it->second.second + 1);
+ _expandedLineColumn.insert(std::make_pair(newGreater.offset, newPosition));
+ }
+
+ return true;
+}
+
void TranslationUnit::showErrorLine(unsigned index, unsigned column, FILE *out)
{
unsigned lineOffset = _lineOffsets[findLineNumber(_tokens->at(index).offset)];
diff --git a/src/libs/3rdparty/cplusplus/TranslationUnit.h b/src/libs/3rdparty/cplusplus/TranslationUnit.h
index 95832f4328..a79bcc0d0e 100644
--- a/src/libs/3rdparty/cplusplus/TranslationUnit.h
+++ b/src/libs/3rdparty/cplusplus/TranslationUnit.h
@@ -134,7 +134,9 @@ public:
unsigned findPreviousLineOffset(unsigned tokenIndex) const;
-public:
+ bool maybeSplitGreaterGreaterToken(unsigned tokenIndex);
+
+private:
struct PPLine {
unsigned offset;
unsigned line;
@@ -156,7 +158,6 @@ public:
{ return offset < other.offset; }
};
-private:
unsigned findLineNumber(unsigned offset) const;
unsigned findColumnNumber(unsigned offset, unsigned lineNumber) const;
PPLine findPreprocessorLine(unsigned offset) const;
diff --git a/src/libs/QtcLibrary.qbs b/src/libs/QtcLibrary.qbs
index 1145ddd40e..ce553a06f9 100644
--- a/src/libs/QtcLibrary.qbs
+++ b/src/libs/QtcLibrary.qbs
@@ -1,17 +1,33 @@
import qbs.base 1.0
+import "../../qbs/defaults.js" as Defaults
DynamicLibrary {
Depends { name: "cpp" }
- cpp.defines: project.additionalCppDefines
+ Depends {
+ condition: Defaults.testsEnabled(qbs)
+ name: "Qt.test"
+ }
+
+ cpp.defines: Defaults.defines(qbs)
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain == "gcc" || qbs.toolchain == "mingw"))
return ["-Wl,-s"]
}
+ cpp.includePaths: [ "." ]
+
+ ProductModule {
+ Depends { name: "cpp" }
+ cpp.includePaths: [ "." ]
+ }
- destination: {
- if (qbs.targetOS == "windows")
- return "bin"
- else
- return "lib/qtcreator"
+ Group {
+ fileTagsFilter: product.type
+ qbs.install: true
+ qbs.installDir: {
+ if (qbs.targetOS == "windows")
+ return "bin"
+ else
+ return "lib/qtcreator"
+ }
}
}
diff --git a/src/libs/aggregation/aggregation.qbs b/src/libs/aggregation/aggregation.qbs
index 1c81766995..b3ab339798 100644
--- a/src/libs/aggregation/aggregation.qbs
+++ b/src/libs/aggregation/aggregation.qbs
@@ -4,18 +4,13 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "Aggregation"
- cpp.includePaths: [
- ".",
- ".."
- ]
- cpp.defines: base.concat("AGGREGATION_LIBRARY")
-
Depends { name: "cpp" }
Depends { name: "Qt.core" }
+ cpp.defines: base.concat("AGGREGATION_LIBRARY")
files: [
- "aggregation_global.h",
+ "aggregate.cpp",
"aggregate.h",
- "aggregate.cpp"
+ "aggregation_global.h",
]
}
diff --git a/src/libs/cplusplus/AlreadyConsideredClassContainer.h b/src/libs/cplusplus/AlreadyConsideredClassContainer.h
new file mode 100644
index 0000000000..4ada3866c4
--- /dev/null
+++ b/src/libs/cplusplus/AlreadyConsideredClassContainer.h
@@ -0,0 +1,45 @@
+#ifndef CPLUSPLUS_ALREADYCONSIDEREDCLASSCONTAINER_H
+#define CPLUSPLUS_ALREADYCONSIDEREDCLASSCONTAINER_H
+
+#include <QSet>
+
+namespace CPlusPlus {
+
+template<typename T>
+class AlreadyConsideredClassContainer
+{
+public:
+ AlreadyConsideredClassContainer() : _class(0) {}
+ void insert(const T *item)
+ {
+ if (_container.isEmpty())
+ _class = item;
+ _container.insert(item);
+ }
+ bool contains(const T *item)
+ {
+ if (_container.contains(item))
+ return true;
+
+ foreach (const T *existingItem, _container) {
+ if (existingItem->isEqualTo(item))
+ return true;
+ }
+
+ return false;
+ }
+
+ void clear(const T *item)
+ {
+ if (_class != item || _container.size() == 1)
+ _container.clear();
+ }
+
+private:
+ QSet<const T *> _container;
+ const T * _class;
+};
+
+} // namespace CPlusPlus
+
+#endif // CPLUSPLUS_ALREADYCONSIDEREDCLASSCONTAINER_H
diff --git a/src/libs/cplusplus/CppDocument.cpp b/src/libs/cplusplus/CppDocument.cpp
index 25a4015514..5c804dd6a8 100644
--- a/src/libs/cplusplus/CppDocument.cpp
+++ b/src/libs/cplusplus/CppDocument.cpp
@@ -89,9 +89,8 @@ protected:
bool preVisit(Symbol *s)
{
if (s->asBlock()) {
- if (s->line() < line || (s->line() == line && s->column() <= column)) {
+ if (s->line() < line || (s->line() == line && s->column() <= column))
return true;
- }
// skip blocks
} if (s->line() < line || (s->line() == line && s->column() <= column)) {
symbol = s;
@@ -340,9 +339,10 @@ QStringList Document::includedFiles() const
return files;
}
+// This assumes to be called with a QDir::cleanPath cleaned fileName.
void Document::addIncludeFile(const QString &fileName, unsigned line)
{
- _includes.append(Include(QDir::cleanPath(fileName), line));
+ _includes.append(Include(fileName, line));
}
void Document::appendMacro(const Macro &macro)
@@ -593,13 +593,14 @@ void Document::check(CheckMode mode)
if (! _translationUnit->ast())
return; // nothing to do.
- if (TranslationUnitAST *ast = _translationUnit->ast()->asTranslationUnit()) {
+ if (TranslationUnitAST *ast = _translationUnit->ast()->asTranslationUnit())
semantic(ast, _globalNamespace);
- } else if (ExpressionAST *ast = _translationUnit->ast()->asExpression()) {
+ else if (StatementAST *ast = _translationUnit->ast()->asStatement())
semantic(ast, _globalNamespace);
- } else if (DeclarationAST *ast = translationUnit()->ast()->asDeclaration()) {
+ else if (ExpressionAST *ast = _translationUnit->ast()->asExpression())
+ semantic(ast, _globalNamespace);
+ else if (DeclarationAST *ast = translationUnit()->ast()->asDeclaration())
semantic(ast, _globalNamespace);
- }
}
void Document::keepSourceAndAST()
diff --git a/src/libs/cplusplus/CppDocument.h b/src/libs/cplusplus/CppDocument.h
index 10d8320d6e..4b87e94b39 100644
--- a/src/libs/cplusplus/CppDocument.h
+++ b/src/libs/cplusplus/CppDocument.h
@@ -312,6 +312,11 @@ public:
QList<UndefinedMacroUse> undefinedMacroUses() const
{ return _undefinedMacroUses; }
+ void setIncludeGuardMacroName(const QByteArray &includeGuardMacroName)
+ { _includeGuardMacroName = includeGuardMacroName; }
+ QByteArray includeGuardMacroName() const
+ { return _includeGuardMacroName; }
+
const Macro *findMacroDefinitionAt(unsigned line) const;
const MacroUse *findMacroUseAt(unsigned offset) const;
const UndefinedMacroUse *findUndefinedMacroUseAt(unsigned offset) const;
@@ -327,12 +332,19 @@ private:
Control *_control;
TranslationUnit *_translationUnit;
Namespace *_globalNamespace;
+
+ /// All messages generated during lexical/syntactic/semantic analysis.
QList<DiagnosticMessage> _diagnosticMessages;
+
QList<Include> _includes;
QList<Macro> _definedMacros;
QList<Block> _skippedBlocks;
QList<MacroUse> _macroUses;
QList<UndefinedMacroUse> _undefinedMacroUses;
+
+ /// the macro name of the include guard, if there is one.
+ QByteArray _includeGuardMacroName;
+
QByteArray _source;
QDateTime _lastModified;
QAtomicInt _keepSourceAndASTCount;
diff --git a/src/libs/cplusplus/CppRewriter.cpp b/src/libs/cplusplus/CppRewriter.cpp
index 5c353e5aa9..f4d6788d46 100644
--- a/src/libs/cplusplus/CppRewriter.cpp
+++ b/src/libs/cplusplus/CppRewriter.cpp
@@ -263,7 +263,8 @@ public:
QVarLengthArray<FullySpecifiedType, 8> args(name->templateArgumentCount());
for (unsigned i = 0; i < name->templateArgumentCount(); ++i)
args[i] = rewrite->rewriteType(name->templateArgumentAt(i));
- temps.append(control()->templateNameId(identifier(name->identifier()), args.data(), args.size()));
+ temps.append(control()->templateNameId(identifier(name->identifier()), name->isSpecialization(),
+ args.data(), args.size()));
}
virtual void visit(const DestructorNameId *name)
@@ -406,9 +407,8 @@ FullySpecifiedType UseMinimalNames::apply(const Name *name, Rewrite *rewrite) co
const QList<LookupItem> results = context.lookup(name, scope);
foreach (const LookupItem &r, results) {
- if (Symbol *d = r.declaration()) {
+ if (Symbol *d = r.declaration())
return control->namedType(LookupContext::minimalName(d, _target, control));
- }
return r.type();
}
@@ -519,15 +519,15 @@ static inline QString fixNestedTemplates(QString s)
CPLUSPLUS_EXPORT QString simplifySTLType(const QString &typeIn)
{
QString type = typeIn;
- if (type.startsWith("class ")) // MSVC prepends class,struct
+ if (type.startsWith(QLatin1String("class "))) // MSVC prepends class,struct
type.remove(0, 6);
- if (type.startsWith("struct "))
+ if (type.startsWith(QLatin1String("struct ")))
type.remove(0, 7);
type.replace(QLatin1Char('*'), QLatin1Char('@'));
for (int i = 0; i < 10; ++i) {
- int start = type.indexOf("std::allocator<");
+ int start = type.indexOf(QLatin1String("std::allocator<"));
if (start == -1)
break;
// search for matching '>'
@@ -575,7 +575,7 @@ CPLUSPLUS_EXPORT QString simplifySTLType(const QString &typeIn)
type.replace(setRE.cap(0), QString::fromLatin1("set<%1>").arg(inner));
// std::map
- if (inner.startsWith("std::pair<")) {
+ if (inner.startsWith(QLatin1String("std::pair<"))) {
// search for outermost ',', split key and value
int pos;
int level = 0;
@@ -595,19 +595,18 @@ CPLUSPLUS_EXPORT QString simplifySTLType(const QString &typeIn)
pos++;
const QString value = inner.mid(pos, inner.size() - pos - 1).trimmed();
const QString valueEsc = QRegExp::escape(value);
- QRegExp mapRE1(QString("map<%1, ?%2, ?std::less<%3 ?>, ?%4\\s*>")
+ QRegExp mapRE1(QString::fromLatin1("map<%1, ?%2, ?std::less<%3 ?>, ?%4\\s*>")
.arg(keyEsc, valueEsc, keyEsc, allocEsc));
mapRE1.setMinimal(true);
QTC_ASSERT(mapRE1.isValid(), return typeIn);
if (mapRE1.indexIn(type) != -1) {
- type.replace(mapRE1.cap(0), QString("map<%1, %2>").arg(key, value));
+ type.replace(mapRE1.cap(0), QString::fromLatin1("map<%1, %2>").arg(key, value));
} else {
- QRegExp mapRE2(QString("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>")
+ QRegExp mapRE2(QString::fromLatin1("map<const %1, ?%2, ?std::less<const %3>, ?%4\\s*>")
.arg(keyEsc, valueEsc, keyEsc, allocEsc));
mapRE2.setMinimal(true);
- if (mapRE2.indexIn(type) != -1) {
- type.replace(mapRE2.cap(0), QString("map<const %1, %2>").arg(key, value));
- }
+ if (mapRE2.indexIn(type) != -1)
+ type.replace(mapRE2.cap(0), QString::fromLatin1("map<const %1, %2>").arg(key, value));
}
}
}
diff --git a/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp b/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp
index b5075cfa70..0d25bbf1f1 100644
--- a/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp
+++ b/src/libs/cplusplus/DeprecatedGenTemplateInstance.cpp
@@ -253,6 +253,7 @@ private:
}
const TemplateNameId *templId = control()->templateNameId(name->identifier(),
+ name->isSpecialization(),
arguments.data(),
arguments.size());
_type = control()->namedType(templId);
@@ -269,13 +270,15 @@ private:
} else if (const TemplateNameId *templId = name->asTemplateNameId()) {
QVarLengthArray<FullySpecifiedType, 8> arguments(templId->templateArgumentCount());
- for (unsigned templateArgIndex = 0; templateArgIndex < templId->templateArgumentCount(); ++templateArgIndex) {
+ for (unsigned templateArgIndex = 0; templateArgIndex < templId->templateArgumentCount();
+ ++templateArgIndex) {
FullySpecifiedType argTy = templId->templateArgumentAt(templateArgIndex);
arguments[templateArgIndex] = q->apply(argTy);
}
const Identifier *id = control()->identifier(templId->identifier()->chars(),
templId->identifier()->size());
- return control()->templateNameId(id, arguments.data(), arguments.size());
+ return control()->templateNameId(id, templId->isSpecialization(), arguments.data(),
+ arguments.size());
} else if (const QualifiedNameId *qq = name->asQualifiedNameId()) {
const Name *base = instantiate(qq->base());
@@ -304,25 +307,25 @@ private:
virtual void visit(const DestructorNameId *name)
{
Overview oo;
- qWarning() << "ignored name:" << oo(name);
+ qWarning() << "ignored name:" << oo.prettyName(name);
}
virtual void visit(const OperatorNameId *name)
{
Overview oo;
- qWarning() << "ignored name:" << oo(name);
+ qWarning() << "ignored name:" << oo.prettyName(name);
}
virtual void visit(const ConversionNameId *name)
{
Overview oo;
- qWarning() << "ignored name:" << oo(name);
+ qWarning() << "ignored name:" << oo.prettyName(name);
}
virtual void visit(const SelectorNameId *name)
{
Overview oo;
- qWarning() << "ignored name:" << oo(name);
+ qWarning() << "ignored name:" << oo.prettyName(name);
}
private:
diff --git a/src/libs/cplusplus/Dumpers.cpp b/src/libs/cplusplus/Dumpers.cpp
index 96ac6cb46b..3b181d0d07 100644
--- a/src/libs/cplusplus/Dumpers.cpp
+++ b/src/libs/cplusplus/Dumpers.cpp
@@ -55,24 +55,25 @@ static QString indent(QString s, int level = 2)
QString CPlusPlus::toString(const Name *name, QString id)
{
Overview oo;
- return QString("%0: %1").arg(id, name ? oo(name) : QLatin1String("(null)"));
+ return QString::fromLatin1("%0: %1").arg(id, name ? oo.prettyName(name) : QLatin1String("(null)"));
}
QString CPlusPlus::toString(FullySpecifiedType ty, QString id)
{
Overview oo;
- return QString("%0: %1 (a %2)").arg(id, oo(ty), ty.type() ? typeid(*ty.type()).name() : "(null)");
+ return QString::fromLatin1("%0: %1 (a %2)").arg(id, oo.prettyType(ty),
+ QLatin1String(ty.type() ? typeid(*ty.type()).name() : "(null)"));
}
QString CPlusPlus::toString(const Symbol *s, QString id)
{
if (!s)
- return QString("%0: (null)").arg(id);
+ return QString::fromLatin1("%0: (null)").arg(id);
- return QString("%0: %1 (%2) at %3:%4:%5\n%6").arg(
+ return QString::fromLatin1("%0: %1 (%2) at %3:%4:%5\n%6").arg(
id,
QString::fromLatin1(typeid(*s).name()),
- QString::fromUtf8(s->identifier()->chars()),
+ s->identifier() ? QString::fromUtf8(s->identifier()->chars()) : QLatin1String("no id"),
QString::fromLatin1(s->fileName()),
QString::number(s->line()),
QString::number(s->column()),
@@ -81,33 +82,28 @@ QString CPlusPlus::toString(const Symbol *s, QString id)
QString CPlusPlus::toString(LookupItem it, QString id)
{
- QString result = QString("%1:").arg(id);
- if (it.declaration()) {
- result.append(QString("\n%1").arg(indent(toString(it.declaration(), QLatin1String("Decl")))));
- }
- if (it.type().isValid()) {
- result.append(QString("\n%1").arg(indent(toString(it.type()))));
- }
- if (it.scope()) {
- result.append(QString("\n%1").arg(indent(toString(it.scope(), QLatin1String("Scope")))));
- }
- if (it.binding()) {
- result.append(QString("\n%1").arg(indent(toString(it.binding(), QLatin1String("Binding")))));
- }
+ QString result = QString::fromLatin1("%1:").arg(id);
+ if (it.declaration())
+ result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.declaration(), QLatin1String("Decl")))));
+ if (it.type().isValid())
+ result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.type()))));
+ if (it.scope())
+ result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.scope(), QLatin1String("Scope")))));
+ if (it.binding())
+ result.append(QString::fromLatin1("\n%1").arg(indent(toString(it.binding(), QLatin1String("Binding")))));
return result;
}
QString CPlusPlus::toString(const ClassOrNamespace *binding, QString id)
{
if (!binding)
- return QString("%0: (null)").arg(id);
+ return QString::fromLatin1("%0: (null)").arg(id);
- QString result = QString("%0: %1 symbols").arg(
+ QString result = QString::fromLatin1("%0: %1 symbols").arg(
id,
QString::number(binding->symbols().length()));
- if (binding->templateId()) {
- result.append(QString("\n%1").arg(indent(toString(binding->templateId(), QLatin1String("Template")))));
- }
+ if (binding->templateId())
+ result.append(QString::fromLatin1("\n%1").arg(indent(toString(binding->templateId(), QLatin1String("Template")))));
return result;
}
diff --git a/src/libs/cplusplus/ExpressionUnderCursor.cpp b/src/libs/cplusplus/ExpressionUnderCursor.cpp
index ecdb33cc3a..437fef0393 100644
--- a/src/libs/cplusplus/ExpressionUnderCursor.cpp
+++ b/src/libs/cplusplus/ExpressionUnderCursor.cpp
@@ -98,11 +98,10 @@ int ExpressionUnderCursor::startOfExpression_helper(BackwardsScanner &tk, int in
return index - 1;
} else if (tk[index - 1].is(T_IDENTIFIER)) {
if (tk[index - 2].is(T_TILDE)) {
- if (tk[index - 3].is(T_COLON_COLON)) {
+ if (tk[index - 3].is(T_COLON_COLON))
return startOfExpression(tk, index - 3);
- } else if (tk[index - 3].is(T_DOT) || tk[index - 3].is(T_ARROW)) {
+ else if (tk[index - 3].is(T_DOT) || tk[index - 3].is(T_ARROW))
return startOfExpression(tk, index - 3);
- }
return index - 2;
} else if (tk[index - 2].is(T_COLON_COLON)) {
return startOfExpression(tk, index - 1);
@@ -157,6 +156,8 @@ int ExpressionUnderCursor::startOfExpression_helper(BackwardsScanner &tk, int in
return index - 1;
} else if (tk[index - 1].is(T_RPAREN)) {
int matchingBraceIndex = tk.startOfMatchingBrace(index);
+ if (! matchingBraceIndex)
+ return matchingBraceIndex;
if (matchingBraceIndex != index) {
if (tk[matchingBraceIndex - 1].is(T_GREATER)) {
int lessIndex = tk.startOfMatchingBrace(matchingBraceIndex);
diff --git a/src/libs/cplusplus/FastPreprocessor.cpp b/src/libs/cplusplus/FastPreprocessor.cpp
index 2eec161779..b1d9f50b60 100644
--- a/src/libs/cplusplus/FastPreprocessor.cpp
+++ b/src/libs/cplusplus/FastPreprocessor.cpp
@@ -30,13 +30,13 @@
#include "FastPreprocessor.h"
#include <Literals.h>
#include <TranslationUnit.h>
-#include <QDebug>
+#include <QDir>
using namespace CPlusPlus;
FastPreprocessor::FastPreprocessor(const Snapshot &snapshot)
- : _snapshot(snapshot),
- _preproc(this, &_env)
+ : _snapshot(snapshot)
+ , _preproc(this, &_env)
{ }
QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QString &source)
@@ -49,7 +49,7 @@ QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QString &source)
if (Document::Ptr doc = _snapshot.document(fileName)) {
_merged.insert(fileName);
- mergeEnvironment(QLatin1String("<configuration>"));
+ mergeEnvironment(Preprocessor::configurationFileName);
foreach (const Document::Include &i, doc->includes())
mergeEnvironment(i.fileName());
}
@@ -63,7 +63,9 @@ QByteArray FastPreprocessor::run(Document::Ptr newDoc, const QString &source)
void FastPreprocessor::sourceNeeded(unsigned line, QString &fileName, IncludeType)
{
Q_ASSERT(_currentDoc);
- _currentDoc->addIncludeFile(fileName, line);
+ // CHECKME: Is that cleanName needed?
+ QString cleanName = QDir::cleanPath(fileName);
+ _currentDoc->addIncludeFile(cleanName, line);
mergeEnvironment(fileName);
}
diff --git a/src/libs/cplusplus/FastPreprocessor.h b/src/libs/cplusplus/FastPreprocessor.h
index c802e75976..35f852151f 100644
--- a/src/libs/cplusplus/FastPreprocessor.h
+++ b/src/libs/cplusplus/FastPreprocessor.h
@@ -71,6 +71,7 @@ public:
const Macro &,
const QVector<MacroArgumentReference> &);
virtual void stopExpandingMacro(unsigned, const Macro &) {}
+ virtual void markAsIncludeGuard(const QByteArray &) {}
virtual void startSkippingBlocks(unsigned) {}
virtual void stopSkippingBlocks(unsigned) {}
diff --git a/src/libs/cplusplus/FindUsages.cpp b/src/libs/cplusplus/FindUsages.cpp
index 19292dbfb3..dbf6dcdf9b 100644
--- a/src/libs/cplusplus/FindUsages.cpp
+++ b/src/libs/cplusplus/FindUsages.cpp
@@ -260,6 +260,8 @@ void FindUsages::checkExpression(unsigned startToken, unsigned endToken, Scope *
if (! scope)
scope = _currentScope;
+ // make possible to instantiate templates
+ typeofExpression.setExpandTemplates(true);
const QList<LookupItem> results = typeofExpression(expression, scope, TypeOfExpression::Preprocess);
reportResult(endToken, results);
}
@@ -535,11 +537,7 @@ void FindUsages::memInitializer(MemInitializerAST *ast)
(void) switchScope(previousScope);
}
}
- // unsigned lparen_token = ast->lparen_token;
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- this->expression(it->value);
- }
- // unsigned rparen_token = ast->rparen_token;
+ this->expression(ast->expression);
}
bool FindUsages::visit(NestedNameSpecifierAST *ast)
@@ -558,14 +556,17 @@ void FindUsages::nestedNameSpecifier(NestedNameSpecifierAST *ast)
// unsigned scope_token = ast->scope_token;
}
-bool FindUsages::visit(NewPlacementAST *ast)
+bool FindUsages::visit(ExpressionListParenAST *ast)
{
- (void) ast;
- Q_ASSERT(!"unreachable");
+ // unsigned lparen_token = ast->lparen_token;
+ for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
+ this->expression(it->value);
+ }
+ // unsigned rparen_token = ast->rparen_token;
return false;
}
-void FindUsages::newPlacement(NewPlacementAST *ast)
+void FindUsages::newPlacement(ExpressionListParenAST *ast)
{
if (! ast)
return;
@@ -594,23 +595,6 @@ void FindUsages::newArrayDeclarator(NewArrayDeclaratorAST *ast)
// unsigned rbracket_token = ast->rbracket_token;
}
-bool FindUsages::visit(NewInitializerAST *ast)
-{
- (void) ast;
- Q_ASSERT(!"unreachable");
- return false;
-}
-
-void FindUsages::newInitializer(NewInitializerAST *ast)
-{
- if (! ast)
- return;
-
- // unsigned lparen_token = ast->lparen_token;
- this->expression(ast->expression);
- // unsigned rparen_token = ast->rparen_token;
-}
-
bool FindUsages::visit(NewTypeIdAST *ast)
{
(void) ast;
@@ -887,6 +871,7 @@ void FindUsages::capture(CaptureAST *ast)
if (! ast)
return;
+ this->name(ast->identifier);
}
bool FindUsages::visit(LambdaDeclaratorAST *ast)
@@ -1025,7 +1010,6 @@ bool FindUsages::visit(RangeBasedForStatementAST *ast)
this->specifier(it->value);
}
this->declarator(ast->declarator);
- this->expression(ast->initializer);
// unsigned comma_token = ast->comma_token;
this->expression(ast->expression);
// unsigned rparen_token = ast->rparen_token;
@@ -1296,7 +1280,7 @@ bool FindUsages::visit(NewExpressionAST *ast)
this->expression(ast->type_id);
// unsigned rparen_token = ast->rparen_token;
this->newTypeId(ast->new_type_id);
- this->newInitializer(ast->new_initializer);
+ this->expression(ast->new_initializer);
return false;
}
@@ -1313,11 +1297,7 @@ bool FindUsages::visit(TypenameCallExpressionAST *ast)
{
// unsigned typename_token = ast->typename_token;
/*const Name *name =*/ this->name(ast->name);
- // unsigned lparen_token = ast->lparen_token;
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- this->expression(it->value);
- }
- // unsigned rparen_token = ast->rparen_token;
+ this->expression(ast->expression);
return false;
}
@@ -1326,11 +1306,7 @@ bool FindUsages::visit(TypeConstructorCallAST *ast)
for (SpecifierListAST *it = ast->type_specifier_list; it; it = it->next) {
this->specifier(it->value);
}
- // unsigned lparen_token = ast->lparen_token;
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next) {
- this->expression(it->value);
- }
- // unsigned rparen_token = ast->rparen_token;
+ this->expression(ast->expression);
return false;
}
diff --git a/src/libs/cplusplus/FindUsages.h b/src/libs/cplusplus/FindUsages.h
index 1fa616e940..504104cf71 100644
--- a/src/libs/cplusplus/FindUsages.h
+++ b/src/libs/cplusplus/FindUsages.h
@@ -103,9 +103,8 @@ protected:
void exceptionSpecification(ExceptionSpecificationAST *ast);
void memInitializer(MemInitializerAST *ast);
void nestedNameSpecifier(NestedNameSpecifierAST *ast);
- void newPlacement(NewPlacementAST *ast);
+ void newPlacement(ExpressionListParenAST *ast);
void newArrayDeclarator(NewArrayDeclaratorAST *ast);
- void newInitializer(NewInitializerAST *ast);
void newTypeId(NewTypeIdAST *ast);
void cppOperator(OperatorAST *ast);
void parameterDeclarationClause(ParameterDeclarationClauseAST *ast);
@@ -136,9 +135,7 @@ protected:
virtual bool visit(DynamicExceptionSpecificationAST *ast);
virtual bool visit(MemInitializerAST *ast);
virtual bool visit(NestedNameSpecifierAST *ast);
- virtual bool visit(NewPlacementAST *ast);
virtual bool visit(NewArrayDeclaratorAST *ast);
- virtual bool visit(NewInitializerAST *ast);
virtual bool visit(NewTypeIdAST *ast);
virtual bool visit(OperatorAST *ast);
virtual bool visit(ParameterDeclarationClauseAST *ast);
@@ -213,6 +210,7 @@ protected:
virtual bool visit(ObjCSelectorExpressionAST *ast);
virtual bool visit(LambdaExpressionAST *ast);
virtual bool visit(BracedInitializerAST *ast);
+ virtual bool visit(ExpressionListParenAST *ast);
// DeclarationAST
virtual bool visit(SimpleDeclarationAST *ast);
diff --git a/src/libs/cplusplus/Icons.cpp b/src/libs/cplusplus/Icons.cpp
index 4c756679f0..39ec346e16 100644
--- a/src/libs/cplusplus/Icons.cpp
+++ b/src/libs/cplusplus/Icons.cpp
@@ -88,13 +88,12 @@ Icons::IconType Icons::iconTypeForSymbol(const Symbol *symbol)
function = symbol->type()->asFunctionType();
if (function->isSlot()) {
- if (function->isPublic()) {
+ if (function->isPublic())
return SlotPublicIconType;
- } else if (function->isProtected()) {
+ else if (function->isProtected())
return SlotProtectedIconType;
- } else if (function->isPrivate()) {
+ else if (function->isPrivate())
return SlotPrivateIconType;
- }
} else if (function->isSignal()) {
return SignalIconType;
} else if (symbol->isPublic()) {
@@ -107,13 +106,12 @@ Icons::IconType Icons::iconTypeForSymbol(const Symbol *symbol)
} else if (symbol->enclosingScope() && symbol->enclosingScope()->isEnum()) {
return EnumeratorIconType;
} else if (symbol->isDeclaration() || symbol->isArgument()) {
- if (symbol->isPublic()) {
+ if (symbol->isPublic())
return VarPublicIconType;
- } else if (symbol->isProtected()) {
+ else if (symbol->isProtected())
return VarProtectedIconType;
- } else if (symbol->isPrivate()) {
+ else if (symbol->isPrivate())
return VarPrivateIconType;
- }
} else if (symbol->isEnum()) {
return EnumIconType;
} else if (symbol->isClass() || symbol->isForwardClassDeclaration()) {
@@ -137,7 +135,7 @@ Icons::IconType Icons::iconTypeForSymbol(const Symbol *symbol)
QIcon Icons::iconForType(IconType type) const
{
- switch(type) {
+ switch (type) {
case ClassIconType:
return _classIcon;
case EnumIconType:
diff --git a/src/libs/cplusplus/LookupContext.cpp b/src/libs/cplusplus/LookupContext.cpp
index 1ac61afe18..04d5bec153 100644
--- a/src/libs/cplusplus/LookupContext.cpp
+++ b/src/libs/cplusplus/LookupContext.cpp
@@ -83,6 +83,9 @@ static void path_helper(Symbol *symbol, QList<const Name *> *names)
} else if (symbol->isFunction()) {
if (const QualifiedNameId *q = symbol->name()->asQualifiedNameId())
addNames(q->base(), names);
+ } else if (Enum *e = symbol->asEnum()) {
+ if (e->isScoped())
+ addNames(symbol->name(), names);
}
}
}
@@ -130,7 +133,7 @@ LookupContext::LookupContext()
LookupContext::LookupContext(Document::Ptr thisDocument,
const Snapshot &snapshot)
- : _expressionDocument(Document::create("<LookupContext>")),
+ : _expressionDocument(Document::create(QLatin1String("<LookupContext>"))),
_thisDocument(thisDocument),
_snapshot(snapshot),
_control(new Control()),
@@ -257,7 +260,8 @@ ClassOrNamespace *LookupContext::globalNamespace() const
return bindings()->globalNamespace();
}
-ClassOrNamespace *LookupContext::lookupType(const Name *name, Scope *scope) const
+ClassOrNamespace *LookupContext::lookupType(const Name *name, Scope *scope,
+ ClassOrNamespace* enclosingTemplateInstantiation) const
{
if (! scope) {
return 0;
@@ -283,16 +287,17 @@ ClassOrNamespace *LookupContext::lookupType(const Name *name, Scope *scope) cons
}
}
return lookupType(name, scope->enclosingScope());
- } else if (ClassOrNamespace *b = bindings()->lookupType(scope)) {
+ } else if (ClassOrNamespace *b = bindings()->lookupType(scope, enclosingTemplateInstantiation)) {
return b->lookupType(name);
}
return 0;
}
-ClassOrNamespace *LookupContext::lookupType(Symbol *symbol) const
+ClassOrNamespace *LookupContext::lookupType(Symbol *symbol,
+ ClassOrNamespace* enclosingTemplateInstantiation) const
{
- return bindings()->lookupType(symbol);
+ return bindings()->lookupType(symbol, enclosingTemplateInstantiation);
}
QList<LookupItem> LookupContext::lookup(const Name *name, Scope *scope) const
@@ -330,6 +335,10 @@ QList<LookupItem> LookupContext::lookup(const Name *name, Scope *scope) const
if (ClassOrNamespace *binding = bindings()->lookupType(fun)) {
candidates = binding->find(name);
+ // try find this name in parent class
+ while (candidates.isEmpty() && (binding = binding->parent()))
+ candidates = binding->find(name);
+
if (! candidates.isEmpty())
return candidates;
}
@@ -349,17 +358,10 @@ QList<LookupItem> LookupContext::lookup(const Name *name, Scope *scope) const
if (! candidates.isEmpty())
return candidates; // it's a template parameter.
- } else if (Class *klass = scope->asClass()) {
-
- if (ClassOrNamespace *binding = bindings()->lookupType(klass)) {
- candidates = binding->find(name);
-
- if (! candidates.isEmpty())
- return candidates;
- }
-
- } else if (Namespace *ns = scope->asNamespace()) {
- if (ClassOrNamespace *binding = bindings()->lookupType(ns))
+ } else if (scope->asNamespace()
+ || scope->asClass()
+ || (scope->asEnum() && scope->asEnum()->isScoped())) {
+ if (ClassOrNamespace *binding = bindings()->lookupType(scope))
candidates = binding->find(name);
if (! candidates.isEmpty())
@@ -419,7 +421,7 @@ QList<ClassOrNamespace *> ClassOrNamespace::usings() const
return _usings;
}
-QList<Enum *> ClassOrNamespace::enums() const
+QList<Enum *> ClassOrNamespace::unscopedEnums() const
{
const_cast<ClassOrNamespace *>(this)->flush();
return _enums;
@@ -547,7 +549,7 @@ void ClassOrNamespace::lookup_helper(const Name *name, ClassOrNamespace *binding
}
}
- foreach (Enum *e, binding->enums())
+ foreach (Enum *e, binding->unscopedEnums())
_factory->lookupInScope(name, e, result, templateId, binding);
foreach (ClassOrNamespace *u, binding->usings())
@@ -591,7 +593,8 @@ void CreateBindings::lookupInScope(const Name *name, Scope *scope,
#ifdef DEBUG_LOOKUP
Overview oo;
- qDebug() << "Found" << id->chars() << "in" << (binding ? oo(binding->_name) : "<null>");
+ qDebug() << "Found" << id->chars() << "in"
+ << (binding ? oo(binding->_name) : QString::fromAscii("<null>"));
#endif // DEBUG_LOOKUP
LookupItem item;
@@ -644,13 +647,11 @@ ClassOrNamespace *ClassOrNamespace::lookupType_helper(const Name *name,
if (const QualifiedNameId *q = name->asQualifiedNameId()) {
QSet<ClassOrNamespace *> innerProcessed;
- if (! q->base()) {
+ if (! q->base())
return globalNamespace()->lookupType_helper(q->name(), &innerProcessed, true, origin);
- }
- if (ClassOrNamespace *binding = lookupType_helper(q->base(), processed, true, origin)) {
+ if (ClassOrNamespace *binding = lookupType_helper(q->base(), processed, true, origin))
return binding->lookupType_helper(q->name(), &innerProcessed, false, origin);
- }
return 0;
@@ -674,16 +675,23 @@ ClassOrNamespace *ClassOrNamespace::lookupType_helper(const Name *name,
if (_usings.size() == 1) {
ClassOrNamespace *delegate = _usings.first();
- if (ClassOrNamespace *r = delegate->lookupType_helper(name, processed, /*searchInEnclosingScope = */ true, origin))
+ if (ClassOrNamespace *r = delegate->lookupType_helper(name,
+ processed,
+ /*searchInEnclosingScope = */ true,
+ origin))
return r;
} else {
if (debug)
- qWarning() << "expected one using declaration. Number of using declarations is:" << _usings.size();
+ qWarning() << "expected one using declaration. Number of using declarations is:"
+ << _usings.size();
}
}
foreach (ClassOrNamespace *u, usings()) {
- if (ClassOrNamespace *r = u->lookupType_helper(name, processed, /*searchInEnclosingScope =*/ false, origin))
+ if (ClassOrNamespace *r = u->lookupType_helper(name,
+ processed,
+ /*searchInEnclosingScope =*/ false,
+ origin))
return r;
}
}
@@ -708,6 +716,42 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
ClassOrNamespace *reference = it->second;
+ const TemplateNameId *templId = name->asTemplateNameId();
+ if (templId) {
+ // if it is a TemplateNameId it could be a specialization(full or partial) or
+ // instantiation of one of the specialization(reference->_specialization) or
+ // base class(reference)
+ if (templId->isSpecialization()) {
+ // if it is a specialization we try to find or create new one and
+ // add to base class(reference)
+ TemplateNameIdTable::const_iterator cit = reference->_specializations.find(templId);
+ if (cit != reference->_specializations.end()) {
+ return cit->second;
+ } else {
+ ClassOrNamespace *newSpecialization = _factory->allocClassOrNamespace(reference);
+#ifdef DEBUG_LOOKUP
+ newSpecialization->_name = templId;
+#endif // DEBUG_LOOKUP
+ reference->_specializations[templId] = newSpecialization;
+ return newSpecialization;
+ }
+ } else {
+ TemplateNameId *nonConstTemplId = const_cast<TemplateNameId *>(templId);
+ // make this instantiation looks like specialization which help to find
+ // full specialization for this instantiation
+ nonConstTemplId->setIsSpecialization(true);
+ TemplateNameIdTable::const_iterator cit = reference->_specializations.find(templId);
+ if (cit != reference->_specializations.end()) {
+ // we found full specialization
+ reference = cit->second;
+ } else {
+ // TODO: find the best specialization(probably partial) for this instantiation
+ }
+ // let's instantiation be instantiation
+ nonConstTemplId->setIsSpecialization(false);
+ }
+ }
+
// The reference binding might still be missing some of its base classes in the case they
// are templates. We need to collect them now. First, we track the bases which are already
// part of the binding so we can identify the missings ones later.
@@ -729,7 +773,6 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
if (!referenceClass)
return reference;
- const TemplateNameId *templId = name->asTemplateNameId();
if ((! templId && _alreadyConsideredClasses.contains(referenceClass)) ||
(templId &&
_alreadyConsideredTemplates.contains(templId))) {
@@ -753,7 +796,7 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
instantiation->_instantiationOrigin = origin;
// The instantiation should have all symbols, enums, and usings from the reference.
- instantiation->_enums.append(reference->enums());
+ instantiation->_enums.append(reference->unscopedEnums());
instantiation->_usings.append(reference->usings());
// It gets a bit complicated if the reference is actually a class template because we
@@ -779,10 +822,11 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
Symbol *clone = cloner.symbol(s, &subst);
instantiation->_symbols.append(clone);
#ifdef DEBUG_LOOKUP
- Overview oo;oo.setShowFunctionSignatures(true);oo.setShowReturnTypes(true);oo.setShowTemplateParameters(true);
+ Overview oo;oo.showFunctionSignatures = true;oo.showReturnTypes = true; oo.showTemplateParameters = true;
qDebug()<<"cloned"<<oo(clone->type());
#endif // DEBUG_LOOKUP
}
+ instantiateNestedClasses(reference, cloner, subst, instantiation);
} else {
instantiation->_symbols.append(reference->symbols());
}
@@ -846,6 +890,7 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
instantiation->addUsing(baseBinding);
}
} else {
+ instantiation->_classOrNamespaces = reference->_classOrNamespaces;
instantiation->_symbols.append(reference->symbols());
}
@@ -856,20 +901,11 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
if (allBases.isEmpty() || allBases.size() == knownUsings.size())
return reference;
- QList<const Name *> fullyQualifiedNameForReferenceClass =
- LookupContext::fullyQualifiedName(referenceClass);
// Find the missing bases for regular (non-template) types.
// Ex.: class A : public B<Some>::Type {};
foreach (const Name *baseName, allBases) {
ClassOrNamespace *binding = this;
if (const QualifiedNameId *qBaseName = baseName->asQualifiedNameId()) {
- QList<const Name *> fullyQualifiedNameForBaseClass;
- addNames(baseName, &fullyQualifiedNameForBaseClass);
- if (compareFullyQualifiedName(fullyQualifiedNameForReferenceClass,
- fullyQualifiedNameForBaseClass)) {
- continue;
- }
-
if (const Name *qualification = qBaseName->base())
binding = lookupType(qualification);
else if (binding->parent() != 0)
@@ -881,9 +917,6 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
continue;
baseName = qBaseName->name();
}
- else if (compareName(name, baseName)) {
- continue;
- }
if (binding) {
ClassOrNamespace * baseBinding = binding->lookupType(baseName);
@@ -896,6 +929,100 @@ ClassOrNamespace *ClassOrNamespace::nestedType(const Name *name, ClassOrNamespac
return reference;
}
+
+void ClassOrNamespace::instantiateNestedClasses(ClassOrNamespace *enclosingTemplateClass,
+ Clone &cloner,
+ Subst &subst,
+ ClassOrNamespace *enclosingTemplateClassInstantiation)
+{
+ NestedClassInstantiator nestedClassInstantiator(_factory, cloner, subst);
+ nestedClassInstantiator.instantiate(enclosingTemplateClass, enclosingTemplateClassInstantiation);
+}
+
+void ClassOrNamespace::NestedClassInstantiator::instantiate(ClassOrNamespace *enclosingTemplateClass,
+ ClassOrNamespace *enclosingTemplateClassInstantiation)
+{
+ if (_alreadyConsideredNestedClassInstantiations.contains(enclosingTemplateClass))
+ return;
+ _alreadyConsideredNestedClassInstantiations.insert(enclosingTemplateClass);
+ ClassOrNamespace::Table::const_iterator cit = enclosingTemplateClass->_classOrNamespaces.begin();
+ for (; cit != enclosingTemplateClass->_classOrNamespaces.end(); ++cit) {
+ const Name *nestedName = cit->first;
+ ClassOrNamespace *nestedClassOrNamespace = cit->second;
+ ClassOrNamespace *nestedClassOrNamespaceInstantiation = nestedClassOrNamespace;
+
+ if (isInstantiateNestedClassNeeded(nestedClassOrNamespace->_symbols)) {
+ nestedClassOrNamespaceInstantiation = _factory->allocClassOrNamespace(nestedClassOrNamespace);
+ nestedClassOrNamespaceInstantiation->_enums.append(nestedClassOrNamespace->unscopedEnums());
+ nestedClassOrNamespaceInstantiation->_usings.append(nestedClassOrNamespace->usings());
+ nestedClassOrNamespaceInstantiation->_instantiationOrigin = nestedClassOrNamespace;
+
+ foreach (Symbol *s, nestedClassOrNamespace->_symbols) {
+ Symbol *clone = _cloner.symbol(s, &_subst);
+ nestedClassOrNamespaceInstantiation->_symbols.append(clone);
+ }
+ }
+
+ instantiate(nestedClassOrNamespace, nestedClassOrNamespaceInstantiation);
+
+ enclosingTemplateClassInstantiation->_classOrNamespaces[nestedName] =
+ nestedClassOrNamespaceInstantiation;
+ }
+ _alreadyConsideredNestedClassInstantiations.remove(enclosingTemplateClass);
+}
+
+bool ClassOrNamespace::NestedClassInstantiator::isInstantiateNestedClassNeeded(const QList<Symbol *> &symbols) const
+{
+ foreach (Symbol *s, symbols) {
+ if (Class *klass = s->asClass()) {
+ int memberCount = klass->memberCount();
+ for (int i = 0; i < memberCount; ++i) {
+ Symbol *memberAsSymbol = klass->memberAt(i);
+ if (Declaration *declaration = memberAsSymbol->asDeclaration()) {
+ if (containsTemplateType(declaration))
+ return true;
+ }
+ else if (Function *function = memberAsSymbol->asFunction()) {
+ if (containsTemplateType(function))
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+}
+
+bool ClassOrNamespace::NestedClassInstantiator::containsTemplateType(Declaration *declaration) const
+{
+ Type *memberType = declaration->type().type();
+ NamedType *memberNamedType = findMemberNamedType(memberType);
+ if (memberNamedType) {
+ const Name *name = memberNamedType->name();
+ if (_subst.contains(name))
+ return true;
+ }
+ return false;
+}
+
+bool ClassOrNamespace::NestedClassInstantiator::containsTemplateType(Function * /*function*/) const
+{
+ //TODO: make implementation
+ return false;
+}
+
+NamedType *ClassOrNamespace::NestedClassInstantiator::findMemberNamedType(Type *memberType) const
+{
+ if (NamedType *namedType = memberType->asNamedType())
+ return namedType;
+ else if (PointerType *pointerType = memberType->asPointerType())
+ return findMemberNamedType(pointerType->elementType().type());
+ else if (ReferenceType *referenceType = memberType->asReferenceType())
+ return findMemberNamedType(referenceType->elementType().type());
+
+ return 0;
+}
+
void ClassOrNamespace::flush()
{
if (! _todo.isEmpty()) {
@@ -917,7 +1044,7 @@ void ClassOrNamespace::addTodo(Symbol *symbol)
_todo.append(symbol);
}
-void ClassOrNamespace::addEnum(Enum *e)
+void ClassOrNamespace::addUnscopedEnum(Enum *e)
{
_enums.append(e);
}
@@ -988,17 +1115,22 @@ ClassOrNamespace *CreateBindings::globalNamespace() const
return _globalNamespace;
}
-ClassOrNamespace *CreateBindings::lookupType(Symbol *symbol)
+ClassOrNamespace *CreateBindings::lookupType(Symbol *symbol, ClassOrNamespace* enclosingTemplateInstantiation)
{
const QList<const Name *> path = LookupContext::path(symbol);
- return lookupType(path);
+ return lookupType(path, enclosingTemplateInstantiation);
}
-ClassOrNamespace *CreateBindings::lookupType(const QList<const Name *> &path)
+ClassOrNamespace *CreateBindings::lookupType(const QList<const Name *> &path, ClassOrNamespace* enclosingTemplateInstantiation)
{
if (path.isEmpty())
return _globalNamespace;
+ if (enclosingTemplateInstantiation) {
+ if (ClassOrNamespace *b = enclosingTemplateInstantiation->lookupType(path.last()))
+ return b;
+ }
+
ClassOrNamespace *b = _globalNamespace->lookupType(path.at(0));
for (int i = 1; b && i < path.size(); ++i)
@@ -1126,7 +1258,12 @@ bool CreateBindings::visit(ForwardClassDeclaration *klass)
bool CreateBindings::visit(Enum *e)
{
- _currentClassOrNamespace->addEnum(e);
+ if (e->isScoped()) {
+ ClassOrNamespace *previous = enterClassOrNamespaceBinding(e);
+ _currentClassOrNamespace = previous;
+ } else {
+ _currentClassOrNamespace->addUnscopedEnum(e);
+ }
return false;
}
@@ -1142,7 +1279,7 @@ bool CreateBindings::visit(Declaration *decl)
_currentClassOrNamespace->addNestedType(decl->name(), e);
} else if (false) {
Overview oo;
- qDebug() << "found entity not found for" << oo(namedTy->name());
+ qDebug() << "found entity not found for" << oo.prettyName(namedTy->name());
}
} else if (Class *klass = ty->asClassType()) {
if (const Identifier *nameId = decl->name()->asNameId()) {
@@ -1167,7 +1304,7 @@ bool CreateBindings::visit(BaseClass *b)
_currentClassOrNamespace->addUsing(base);
} else if (false) {
Overview oo;
- qDebug() << "no entity for:" << oo(b->name());
+ qDebug() << "no entity for:" << oo.prettyName(b->name());
}
return false;
}
@@ -1193,7 +1330,7 @@ bool CreateBindings::visit(UsingNamespaceDirective *u)
_currentClassOrNamespace->addUsing(e);
} else if (false) {
Overview oo;
- qDebug() << "no entity for namespace:" << oo(u->name());
+ qDebug() << "no entity for namespace:" << oo.prettyName(u->name());
}
return false;
}
@@ -1209,7 +1346,7 @@ bool CreateBindings::visit(NamespaceAlias *a)
} else if (false) {
Overview oo;
- qDebug() << "no entity for namespace:" << oo(a->namespaceName());
+ qDebug() << "no entity for namespace:" << oo.prettyName(a->namespaceName());
}
return false;
@@ -1237,7 +1374,7 @@ bool CreateBindings::visit(ObjCBaseClass *b)
_currentClassOrNamespace->addUsing(base);
} else if (false) {
Overview oo;
- qDebug() << "no entity for:" << oo(b->name());
+ qDebug() << "no entity for:" << oo.prettyName(b->name());
}
return false;
}
@@ -1269,7 +1406,7 @@ bool CreateBindings::visit(ObjCBaseProtocol *b)
_currentClassOrNamespace->addUsing(base);
} else if (false) {
Overview oo;
- qDebug() << "no entity for:" << oo(b->name());
+ qDebug() << "no entity for:" << oo.prettyName(b->name());
}
return false;
}
diff --git a/src/libs/cplusplus/LookupContext.h b/src/libs/cplusplus/LookupContext.h
index 831f1276d6..70dafc03b5 100644
--- a/src/libs/cplusplus/LookupContext.h
+++ b/src/libs/cplusplus/LookupContext.h
@@ -32,6 +32,7 @@
#include "CppDocument.h"
#include "LookupItem.h"
+#include "AlreadyConsideredClassContainer.h"
#include <FullySpecifiedType.h>
#include <Type.h>
#include <SymbolVisitor.h>
@@ -40,45 +41,11 @@
#include <QSet>
#include <map>
#include <functional>
+#include <QMap>
namespace CPlusPlus {
class CreateBindings;
-class Class;
-template<typename T>
-class AlreadyConsideredClassContainer
-{
-public:
- AlreadyConsideredClassContainer() : _class(0) {}
- void insert(const T *item)
- {
- if (_container.isEmpty())
- _class = item;
- _container.insert(item);
- }
- bool contains(const T *item)
- {
- if (_container.contains(item))
- return true;
-
- foreach (const T *existingItem, _container) {
- if (existingItem->isEqualTo(item))
- return true;
- }
-
- return false;
- }
-
- void clear(const T *item)
- {
- if (_class != item || _container.size() == 1)
- _container.clear();
- }
-
-private:
- QSet<const T *> _container;
- const T * _class;
-};
class CPLUSPLUS_EXPORT ClassOrNamespace
{
@@ -90,7 +57,7 @@ public:
ClassOrNamespace *parent() const;
QList<ClassOrNamespace *> usings() const;
- QList<Enum *> enums() const;
+ QList<Enum *> unscopedEnums() const;
QList<Symbol *> symbols() const;
ClassOrNamespace *globalNamespace() const;
@@ -110,7 +77,7 @@ private:
void addTodo(Symbol *symbol);
void addSymbol(Symbol *symbol);
- void addEnum(Enum *e);
+ void addUnscopedEnum(Enum *e);
void addUsing(ClassOrNamespace *u);
void addNestedType(const Name *alias, ClassOrNamespace *e);
@@ -126,8 +93,16 @@ private:
ClassOrNamespace *nestedType(const Name *name, ClassOrNamespace *origin);
+ void instantiateNestedClasses(ClassOrNamespace *enclosingTemplateClass,
+ Clone &cloner,
+ Subst &subst,
+ ClassOrNamespace *enclosingTemplateClassInstantiation);
+ bool isInstantiateNestedClassNeeded(const QList<Symbol *>& symbols, const Subst &subst) const;
+
private:
typedef std::map<const Name *, ClassOrNamespace *, Name::Compare> Table;
+ typedef std::map<const TemplateNameId *, ClassOrNamespace *, TemplateNameId::Compare> TemplateNameIdTable;
+
CreateBindings *_factory;
ClassOrNamespace *_parent;
QList<Symbol *> _symbols;
@@ -136,6 +111,7 @@ private:
QList<Enum *> _enums;
QList<Symbol *> _todo;
QSharedPointer<Control> _control;
+ TemplateNameIdTable _specializations;
// it's an instantiation.
const TemplateNameId *_templateId;
@@ -144,6 +120,28 @@ private:
AlreadyConsideredClassContainer<Class> _alreadyConsideredClasses;
AlreadyConsideredClassContainer<TemplateNameId> _alreadyConsideredTemplates;
+ class NestedClassInstantiator
+ {
+ public:
+ NestedClassInstantiator(CreateBindings *factory, Clone &cloner, Subst &subst)
+ : _factory(factory)
+ , _cloner(cloner)
+ , _subst(subst)
+ {}
+ void instantiate(ClassOrNamespace *enclosingTemplateClass,
+ ClassOrNamespace *enclosingTemplateClassInstantiation);
+ private:
+ bool isInstantiateNestedClassNeeded(const QList<Symbol *> &symbols) const;
+ bool containsTemplateType(Declaration *declaration) const;
+ bool containsTemplateType(Function *function) const;
+ NamedType *findMemberNamedType(Type *memberType) const;
+
+ QSet<ClassOrNamespace *> _alreadyConsideredNestedClassInstantiations;
+ CreateBindings *_factory;
+ Clone &_cloner;
+ Subst &_subst;
+ };
+
#ifdef DEBUG_LOOKUP
public:
const Name *_name;
@@ -164,8 +162,10 @@ public:
ClassOrNamespace *globalNamespace() const;
/// Finds the binding associated to the given symbol.
- ClassOrNamespace *lookupType(Symbol *symbol);
- ClassOrNamespace *lookupType(const QList<const Name *> &path);
+ ClassOrNamespace *lookupType(Symbol *symbol,
+ ClassOrNamespace* enclosingTemplateInstantiation = 0);
+ ClassOrNamespace *lookupType(const QList<const Name *> &path,
+ ClassOrNamespace* enclosingTemplateInstantiation = 0);
/// Returns the Control that must be used to create temporary symbols.
/// \internal
@@ -262,8 +262,10 @@ public:
ClassOrNamespace *globalNamespace() const;
QList<LookupItem> lookup(const Name *name, Scope *scope) const;
- ClassOrNamespace *lookupType(const Name *name, Scope *scope) const;
- ClassOrNamespace *lookupType(Symbol *symbol) const;
+ ClassOrNamespace *lookupType(const Name *name, Scope *scope,
+ ClassOrNamespace* enclosingTemplateInstantiation = 0) const;
+ ClassOrNamespace *lookupType(Symbol *symbol,
+ ClassOrNamespace* enclosingTemplateInstantiation = 0) const;
ClassOrNamespace *lookupParent(Symbol *symbol) const;
/// \internal
@@ -280,7 +282,11 @@ public:
static const Name *minimalName(Symbol *symbol, ClassOrNamespace *target, Control *control);
void setExpandTemplates(bool expandTemplates)
- { m_expandTemplates = expandTemplates; }
+ {
+ if (_bindings)
+ _bindings->setExpandTemplates(expandTemplates);
+ m_expandTemplates = expandTemplates;
+ }
private:
// The current expression.
diff --git a/src/libs/cplusplus/NamePrettyPrinter.cpp b/src/libs/cplusplus/NamePrettyPrinter.cpp
index 2f509816f5..51f3f9c543 100644
--- a/src/libs/cplusplus/NamePrettyPrinter.cpp
+++ b/src/libs/cplusplus/NamePrettyPrinter.cpp
@@ -90,7 +90,7 @@ void NamePrettyPrinter::visit(const TemplateNameId *name)
else
_name += arg;
}
- if (! _name.isEmpty() && _name.at(_name.length() - 1) == '>')
+ if (! _name.isEmpty() && _name.at(_name.length() - 1) == QLatin1Char('>'))
_name += QLatin1Char(' ');
_name += QLatin1Char('>');
}
@@ -263,7 +263,7 @@ void NamePrettyPrinter::visit(const SelectorNameId *name)
_name += QString::fromLatin1(id->chars(), id->size());
if (name->hasArguments() || name->nameCount() > 1)
- _name += ':';
+ _name += QLatin1Char(':');
}
}
}
diff --git a/src/libs/cplusplus/Overview.cpp b/src/libs/cplusplus/Overview.cpp
index 89306ca52c..6b633d83e0 100644
--- a/src/libs/cplusplus/Overview.cpp
+++ b/src/libs/cplusplus/Overview.cpp
@@ -38,99 +38,17 @@
using namespace CPlusPlus;
Overview::Overview()
- : _markedArgument(0),
- _markedArgumentBegin(0),
- _markedArgumentEnd(0),
- _showArgumentNames(false),
- _showReturnTypes(false),
- _showFunctionSignatures(true),
- _showDefaultArguments(true),
- _showTemplateParameters(false)
+ : starBindFlags(BindToIdentifier), // default to "Qt Style"
+ showArgumentNames(false),
+ showReturnTypes(false),
+ showFunctionSignatures(true),
+ showDefaultArguments(true),
+ showTemplateParameters(false),
+ markedArgument(0),
+ markedArgumentBegin(0),
+ markedArgumentEnd(0)
{ }
-Overview::~Overview()
-{ }
-
-bool Overview::showArgumentNames() const
-{
- return _showArgumentNames;
-}
-
-void Overview::setShowArgumentNames(bool showArgumentNames)
-{
- _showArgumentNames = showArgumentNames;
-}
-
-void Overview::setShowReturnTypes(bool showReturnTypes)
-{
- _showReturnTypes = showReturnTypes;
-}
-
-bool Overview::showReturnTypes() const
-{
- return _showReturnTypes;
-}
-
-unsigned Overview::markedArgument() const
-{
- return _markedArgument;
-}
-
-void Overview::setMarkedArgument(unsigned position)
-{
- _markedArgument = position;
-}
-
-int Overview::markedArgumentBegin() const
-{
- return _markedArgumentBegin;
-}
-
-void Overview::setMarkedArgumentBegin(int begin)
-{
- _markedArgumentBegin = begin;
-}
-
-int Overview::markedArgumentEnd() const
-{
- return _markedArgumentEnd;
-}
-
-void Overview::setMarkedArgumentEnd(int end)
-{
- _markedArgumentEnd = end;
-}
-
-bool Overview::showFunctionSignatures() const
-{
- return _showFunctionSignatures;
-}
-
-void Overview::setShowFunctionSignatures(bool showFunctionSignatures)
-{
- _showFunctionSignatures = showFunctionSignatures;
-}
-
-bool Overview::showDefaultArguments() const
-{
- return _showDefaultArguments;
-}
-
-void Overview::setShowDefaultArguments(bool showDefaultArguments)
-{
- _showDefaultArguments = showDefaultArguments;
-}
-
-bool Overview::showTemplateParameters() const
-{
- return _showTemplateParameters;
-}
-
-void Overview::setShowTemplateParameters(bool showTemplateParameters)
-{
- _showTemplateParameters = showTemplateParameters;
-}
-
QString Overview::prettyName(const Name *name) const
{
NamePrettyPrinter pp(this);
diff --git a/src/libs/cplusplus/Overview.h b/src/libs/cplusplus/Overview.h
index dbca643140..95d0aa33c4 100644
--- a/src/libs/cplusplus/Overview.h
+++ b/src/libs/cplusplus/Overview.h
@@ -37,39 +37,20 @@
namespace CPlusPlus {
+/*!
+ \class Overview
+
+ \brief Converts a FullySpecifiedType and/or any qualified name,
+ to its string representation.
+
+ The public data members (except the ones starting with "marked")
+ determine what exactly and how to print.
+ */
+
class CPLUSPLUS_EXPORT Overview
{
- Overview(const Overview &other);
- void operator =(const Overview &other);
-
public:
Overview();
- ~Overview();
-
- bool showArgumentNames() const;
- void setShowArgumentNames(bool showArgumentNames);
-
- bool showReturnTypes() const;
- void setShowReturnTypes(bool showReturnTypes);
-
- bool showFunctionSignatures() const;
- void setShowFunctionSignatures(bool showFunctionSignatures);
-
- bool showDefaultArguments() const;
- void setShowDefaultArguments(bool showDefaultArguments);
-
- bool showTemplateParameters() const;
- void setShowTemplateParameters(bool showTemplateParameters);
-
- // argument index that you want to mark
- unsigned markedArgument() const;
- void setMarkedArgument(unsigned position);
-
- int markedArgumentBegin() const;
- void setMarkedArgumentBegin(int begin);
-
- int markedArgumentEnd() const;
- void setMarkedArgumentEnd(int end);
QString operator()(const Name *name) const
{ return prettyName(name); }
@@ -85,15 +66,58 @@ public:
QString prettyType(const FullySpecifiedType &type, const Name *name = 0) const;
QString prettyType(const FullySpecifiedType &type, const QString &name) const;
-private:
- unsigned _markedArgument;
- int _markedArgumentBegin;
- int _markedArgumentEnd;
- bool _showArgumentNames: 1;
- bool _showReturnTypes: 1;
- bool _showFunctionSignatures: 1;
- bool _showDefaultArguments: 1;
- bool _showTemplateParameters: 1;
+public:
+ /*!
+ \enum Overview::StarBindFlag
+
+ The StarBindFlags describe how the '*' and '&' in pointers/references
+ should be bound in the string representation.
+
+ This also applies to rvalue references ('&&'), but not to
+ pointers to functions or arrays like in
+
+ void (*p)()
+ void (*p)[]
+
+ since it seems to be quite uncommon to use spaces there.
+
+ See the examples below. These assume that exactly one
+ flag is set. That is, it may look different with
+ flag combinations.
+
+ \value BindToIdentifier
+ e.g. "char *foo", but not "char * foo"
+ \value BindToTypeName
+ e.g. "char*", but not "char *"
+ \value BindToLeftSpecifier
+ e.g. "char * const* const", but not "char * const * const"
+ \value BindToRightSpecifier
+ e.g. "char *const", but not "char * const"
+ */
+ enum StarBindFlag {
+ BindToIdentifier = 0x1,
+ BindToTypeName = 0x2,
+ BindToLeftSpecifier = 0x4,
+ BindToRightSpecifier = 0x8
+ };
+ Q_DECLARE_FLAGS(StarBindFlags, StarBindFlag)
+
+ StarBindFlags starBindFlags;
+ bool showArgumentNames: 1;
+ bool showReturnTypes: 1;
+ bool showFunctionSignatures: 1;
+ bool showDefaultArguments: 1;
+ bool showTemplateParameters: 1;
+
+ /*!
+ You can get the start and end position of a function argument
+ in the resulting string. Set "markedArgument" to the desired
+ argument. After processing, "markedArgumentBegin" and
+ "markedArgumentEnd" will contain the positions.
+ */
+ unsigned markedArgument;
+ int markedArgumentBegin;
+ int markedArgumentEnd;
};
} // namespace CPlusPlus
diff --git a/src/libs/cplusplus/OverviewModel.cpp b/src/libs/cplusplus/OverviewModel.cpp
index 3ca5c69420..b9454c9d61 100644
--- a/src/libs/cplusplus/OverviewModel.cpp
+++ b/src/libs/cplusplus/OverviewModel.cpp
@@ -123,9 +123,8 @@ int OverviewModel::rowCount(const QModelIndex &parent) const
parentSymbol = templateParentSymbol;
if (Scope *parentScope = parentSymbol->asScope()) {
- if (!parentScope->isFunction() && !parentScope->isObjCMethod()) {
+ if (!parentScope->isFunction() && !parentScope->isObjCMethod())
return parentScope->memberCount();
- }
}
return 0;
}
diff --git a/src/libs/cplusplus/PPToken.h b/src/libs/cplusplus/PPToken.h
index be385786b0..6a194cc6a7 100644
--- a/src/libs/cplusplus/PPToken.h
+++ b/src/libs/cplusplus/PPToken.h
@@ -89,7 +89,7 @@ public:
{ return !this->operator==(other); }
bool operator==(const char *other) const
- { return qstrncmp(m_start, other, qstrlen(other)) == 0; }
+ { return m_length == (int) qstrlen(other) && !qstrncmp(m_start, other, m_length); }
bool operator!=(const char *other) const
{ return !this->operator==(other); }
diff --git a/src/libs/cplusplus/PreprocessorClient.h b/src/libs/cplusplus/PreprocessorClient.h
index 23d455a52f..70ce029896 100644
--- a/src/libs/cplusplus/PreprocessorClient.h
+++ b/src/libs/cplusplus/PreprocessorClient.h
@@ -68,7 +68,8 @@ class CPLUSPLUS_EXPORT Client
public:
enum IncludeType {
IncludeLocal,
- IncludeGlobal
+ IncludeGlobal,
+ IncludeNext
};
public:
@@ -89,6 +90,9 @@ public:
= QVector<MacroArgumentReference>()) = 0;
virtual void stopExpandingMacro(unsigned offset, const Macro &macro) = 0;
+ /// Mark the given macro name as the include guard for the current file.
+ virtual void markAsIncludeGuard(const QByteArray &macroName) = 0;
+
/// Start skipping from the given offset.
virtual void startSkippingBlocks(unsigned offset) = 0;
virtual void stopSkippingBlocks(unsigned offset) = 0;
diff --git a/src/libs/cplusplus/ResolveExpression.cpp b/src/libs/cplusplus/ResolveExpression.cpp
index 72e17c040e..f2a8226629 100644
--- a/src/libs/cplusplus/ResolveExpression.cpp
+++ b/src/libs/cplusplus/ResolveExpression.cpp
@@ -357,9 +357,8 @@ void ResolveExpression::thisObject()
bool ResolveExpression::visit(CompoundExpressionAST *ast)
{
CompoundStatementAST *cStmt = ast->statement;
- if (cStmt && cStmt->statement_list) {
+ if (cStmt && cStmt->statement_list)
accept(cStmt->statement_list->lastValue());
- }
return false;
}
@@ -533,7 +532,7 @@ bool ResolveExpression::visit(SimpleNameAST *ast)
continue;
TypeOfExpression exprTyper;
- Document::Ptr doc = _context.snapshot().document(decl->fileName());
+ Document::Ptr doc = _context.snapshot().document(QString::fromLocal8Bit(decl->fileName()));
exprTyper.init(doc, _context.snapshot(), _context.bindings());
Document::Ptr exprDoc =
@@ -774,8 +773,8 @@ QList<LookupItem> ResolveExpression::getMembers(ClassOrNamespace *binding, const
FullySpecifiedType instantiatedTy = rewriteType(decl->type(), &env, _context.control().data());
Overview oo;
- oo.setShowReturnTypes(true);
- oo.setShowFunctionSignatures(true);
+ oo.showReturnTypes = true;
+ oo.showFunctionSignatures = true;
qDebug() << "original:" << oo(decl->type(), decl->name()) << "inst:" << oo(instantiatedTy, decl->name());
@@ -811,16 +810,17 @@ bool ResolveExpression::visit(MemberAccessAST *ast)
return false;
}
-ClassOrNamespace *ResolveExpression::findClass(const FullySpecifiedType &originalTy, Scope *scope) const
+ClassOrNamespace *ResolveExpression::findClass(const FullySpecifiedType &originalTy, Scope *scope,
+ ClassOrNamespace* enclosingTemplateInstantiation) const
{
FullySpecifiedType ty = originalTy.simplified();
ClassOrNamespace *binding = 0;
if (Class *klass = ty->asClassType())
- binding = _context.lookupType(klass);
+ binding = _context.lookupType(klass, enclosingTemplateInstantiation);
else if (NamedType *namedTy = ty->asNamedType())
- binding = _context.lookupType(namedTy->name(), scope);
+ binding = _context.lookupType(namedTy->name(), scope, enclosingTemplateInstantiation);
else if (Function *funTy = ty->asFunctionType())
return findClass(funTy->returnType(), scope);
@@ -828,43 +828,71 @@ ClassOrNamespace *ResolveExpression::findClass(const FullySpecifiedType &origina
return binding;
}
-static void resolveTypedefs(const LookupContext &context,
- FullySpecifiedType *type,
- Scope **scope, ClassOrNamespace *binding)
+class TypedefsResolver
{
- QSet<Symbol *> visited;
- while (NamedType *namedTy = (*type)->asNamedType()) {
+public:
+ TypedefsResolver(const LookupContext &context) : _context(context) {}
+ void resolve(FullySpecifiedType *type, Scope **scope, ClassOrNamespace *binding)
+ {
+ QSet<Symbol *> visited;
+ while (NamedType *namedTy = getNamedType(*type)) {
+ QList<LookupItem> namedTypeItems = getNamedTypeItems(namedTy->name(), *scope, binding);
- // check if namedTy->name() resolves to a typedef
+#ifdef DEBUG_LOOKUP
+ qDebug() << "-- we have" << namedTypeItems.size() << "candidates";
+#endif // DEBUG_LOOKUP
+
+ if (!findTypedef(namedTypeItems, type, scope, visited))
+ break;
+ }
+ }
+
+private:
+ NamedType *getNamedType(FullySpecifiedType& type)
+ {
+ NamedType *namedTy = type->asNamedType();
+ if (! namedTy) {
+ if (PointerType *pointerTy = type->asPointerType())
+ namedTy = pointerTy->elementType()->asNamedType();
+ }
+ return namedTy;
+ }
+
+ QList<LookupItem> getNamedTypeItems(const Name *name, Scope *scope, ClassOrNamespace *binding)
+ {
QList<LookupItem> namedTypeItems;
if (binding)
- namedTypeItems = binding->lookup(namedTy->name());
- if (ClassOrNamespace *scopeCon = context.lookupType(*scope))
- namedTypeItems += scopeCon->lookup(namedTy->name());
+ namedTypeItems = binding->lookup(name);
+ if (ClassOrNamespace *scopeCon = _context.lookupType(scope))
+ namedTypeItems += scopeCon->lookup(name);
-#ifdef DEBUG_LOOKUP
- qDebug() << "-- we have" << namedTypeItems.size() << "candidates";
-#endif // DEBUG_LOOKUP
+ return namedTypeItems;
+ }
+ bool findTypedef(const QList<LookupItem>& namedTypeItems, FullySpecifiedType *type,
+ Scope **scope, QSet<Symbol *>& visited)
+ {
bool foundTypedef = false;
foreach (const LookupItem &it, namedTypeItems) {
- if (it.declaration() && it.declaration()->isTypedef()) {
- if (visited.contains(it.declaration()))
+ Symbol *declaration = it.declaration();
+ if (declaration && declaration->isTypedef()) {
+ if (visited.contains(declaration))
break;
- visited.insert(it.declaration());
+ visited.insert(declaration);
// continue working with the typedefed type and scope
- *type = it.declaration()->type();
+ *type = declaration->type();
*scope = it.scope();
foundTypedef = true;
break;
}
}
- if (!foundTypedef)
- break;
+ return foundTypedef;
}
-}
+
+ const LookupContext &_context;
+};
ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &baseResults,
int accessOp,
@@ -875,9 +903,13 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
int i = 0;
Overview oo;
#endif // DEBUG_LOOKUP
+ TypedefsResolver typedefsResolver(_context);
foreach (const LookupItem &r, baseResults) {
+ if (!r.type().type())
+ continue;
FullySpecifiedType ty = r.type().simplified();
+ FullySpecifiedType originalType = ty;
Scope *scope = r.scope();
#ifdef DEBUG_LOOKUP
@@ -885,15 +917,18 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
qDebug()<<"- before typedef resolving we have:"<<oo(ty);
#endif // DEBUG_LOOKUP
- resolveTypedefs(_context, &ty, &scope, r.binding());
+ typedefsResolver.resolve(&ty, &scope, r.binding());
#ifdef DEBUG_LOOKUP
qDebug()<<"- after typedef resolving:"<<oo(ty);
#endif // DEBUG_LOOKUP
if (accessOp == T_ARROW) {
- if (PointerType *ptrTy = ty->asPointerType()) {
- if (ClassOrNamespace *binding = findClass(ptrTy->elementType(), scope))
+ if (PointerType *ptrTy = originalType->asPointerType()) {
+ FullySpecifiedType type = ptrTy->elementType();
+ if (! ty->isPointerType())
+ type = ty;
+ if (ClassOrNamespace *binding = findClass(type, scope))
return binding;
} else if (ClassOrNamespace *binding = findClass(ty, scope)) {
@@ -913,30 +948,33 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
FullySpecifiedType retTy = instantiatedFunction->returnType().simplified();
- resolveTypedefs(_context, &retTy, &functionScope, r.binding());
+ typedefsResolver.resolve(&retTy, &functionScope, r.binding());
- if (PointerType *ptrTy = retTy->asPointerType()) {
- if (ClassOrNamespace *retBinding = findClass(ptrTy->elementType(), functionScope))
- return retBinding;
+ if (! retTy->isPointerType() && ! retTy->isNamedType())
+ continue;
- if (scope != functionScope) {
- if (ClassOrNamespace *retBinding = findClass(ptrTy->elementType(), scope))
- return retBinding;
- }
+ if (PointerType *ptrTy = retTy->asPointerType())
+ retTy = ptrTy->elementType();
+
+ if (ClassOrNamespace *retBinding = findClass(retTy, functionScope))
+ return retBinding;
+
+ if (scope != functionScope) {
+ if (ClassOrNamespace *retBinding = findClass(retTy, scope))
+ return retBinding;
+ }
- if (ClassOrNamespace *origin = binding->instantiationOrigin()) {
- foreach (Symbol *originSymbol, origin->symbols()) {
- Scope *originScope = originSymbol->asScope();
- if (originScope && originScope != scope && originScope != functionScope) {
- if (ClassOrNamespace *retBinding = findClass(ptrTy->elementType(), originScope))
- return retBinding;
- }
+ if (ClassOrNamespace *origin = binding->instantiationOrigin()) {
+ foreach (Symbol *originSymbol, origin->symbols()) {
+ Scope *originScope = originSymbol->asScope();
+ if (originScope && originScope != scope && originScope != functionScope) {
+ if (ClassOrNamespace *retBinding = findClass(retTy, originScope))
+ return retBinding;
}
}
}
}
}
-
}
} else if (accessOp == T_DOT) {
if (replacedDotOperator) {
@@ -947,7 +985,13 @@ ClassOrNamespace *ResolveExpression::baseExpression(const QList<LookupItem> &bas
}
}
- if (ClassOrNamespace *binding = findClass(ty, scope))
+ ClassOrNamespace *enclosingTemplateInstantiation = 0;
+ if (ClassOrNamespace *binding = r.binding()) {
+ if (binding->instantiationOrigin())
+ enclosingTemplateInstantiation = binding;
+ }
+
+ if (ClassOrNamespace *binding = findClass(ty, scope, enclosingTemplateInstantiation))
return binding;
}
}
diff --git a/src/libs/cplusplus/ResolveExpression.h b/src/libs/cplusplus/ResolveExpression.h
index a6eddfdcca..764268ab91 100644
--- a/src/libs/cplusplus/ResolveExpression.h
+++ b/src/libs/cplusplus/ResolveExpression.h
@@ -56,7 +56,8 @@ public:
const LookupContext &context() const;
protected:
- ClassOrNamespace *findClass(const FullySpecifiedType &ty, Scope *scope) const;
+ ClassOrNamespace *findClass(const FullySpecifiedType &ty, Scope *scope,
+ ClassOrNamespace* enclosingTemplateInstantiation = 0) const;
QList<LookupItem> expression(ExpressionAST *ast);
diff --git a/src/libs/cplusplus/SimpleLexer.cpp b/src/libs/cplusplus/SimpleLexer.cpp
index d56d204170..7f5692da97 100644
--- a/src/libs/cplusplus/SimpleLexer.cpp
+++ b/src/libs/cplusplus/SimpleLexer.cpp
@@ -134,6 +134,9 @@ QList<Token> SimpleLexer::operator()(const QString &text, int state)
else if (inPreproc && tokens.size() == 1 && tk.is(T_IDENTIFIER) &&
spell == QLatin1String("include"))
lex.setScanAngleStringLiteralTokens(true);
+ else if (inPreproc && tokens.size() == 1 && tk.is(T_IDENTIFIER) &&
+ spell == QLatin1String("include_next"))
+ lex.setScanAngleStringLiteralTokens(true);
else if (_objCEnabled
&& inPreproc && tokens.size() == 1 && tk.is(T_IDENTIFIER) &&
spell == QLatin1String("import"))
diff --git a/src/libs/cplusplus/TypeOfExpression.cpp b/src/libs/cplusplus/TypeOfExpression.cpp
index d61259f829..589f94e5ba 100644
--- a/src/libs/cplusplus/TypeOfExpression.cpp
+++ b/src/libs/cplusplus/TypeOfExpression.cpp
@@ -193,7 +193,7 @@ QByteArray TypeOfExpression::preprocessedExpression(const QByteArray &utf8code)
}
Preprocessor preproc(0, m_environment.data());
- return preproc.run("<expression>", utf8code);
+ return preproc.run(QLatin1String("<expression>"), utf8code);
}
namespace CPlusPlus {
diff --git a/src/libs/cplusplus/TypeOfExpression.h b/src/libs/cplusplus/TypeOfExpression.h
index 5d10beb805..85efb2fcea 100644
--- a/src/libs/cplusplus/TypeOfExpression.h
+++ b/src/libs/cplusplus/TypeOfExpression.h
@@ -76,7 +76,7 @@ public:
* expression evaluator instance still exists, and no new call to evaluate
* has been made!
*
- * @param expression The expression to evaluate.
+ * @param utf8code The code of expression to evaluate.
* @param scope The scope enclosing the expression.
*/
QList<LookupItem> operator()(const QByteArray &utf8code,
diff --git a/src/libs/cplusplus/TypePrettyPrinter.cpp b/src/libs/cplusplus/TypePrettyPrinter.cpp
index b4a247a2f5..22b332901c 100644
--- a/src/libs/cplusplus/TypePrettyPrinter.cpp
+++ b/src/libs/cplusplus/TypePrettyPrinter.cpp
@@ -44,6 +44,8 @@ using namespace CPlusPlus;
TypePrettyPrinter::TypePrettyPrinter(const Overview *overview)
: _overview(overview)
, _needsParens(false)
+ , _isIndirectionType(false)
+ , _isIndirectionToArrayOrFunction(false)
{ }
TypePrettyPrinter::~TypePrettyPrinter()
@@ -91,13 +93,28 @@ QString TypePrettyPrinter::switchName(const QString &name)
const QString previousName = _name;
_name = name;
return previousName;
+
}
-QString TypePrettyPrinter::switchText(const QString &name)
+bool TypePrettyPrinter::switchIsIndirectionType(bool isIndirectionType)
{
- QString previousName = _text;
- _text = name;
- return previousName;
+ bool previousIsIndirectionType = _isIndirectionType;
+ _isIndirectionType = isIndirectionType;
+ return previousIsIndirectionType;
+}
+
+bool TypePrettyPrinter::switchIsIndirectionToArrayOrFunction(bool isIndirectionToArrayOrFunction)
+{
+ bool previousIsIndirectionToArrayOrFunction = _isIndirectionToArrayOrFunction;
+ _isIndirectionToArrayOrFunction = isIndirectionToArrayOrFunction;
+ return previousIsIndirectionToArrayOrFunction;
+}
+
+QString TypePrettyPrinter::switchText(const QString &text)
+{
+ QString previousText = _text;
+ _text = text;
+ return previousText;
}
bool TypePrettyPrinter::switchNeedsParens(bool needsParens)
@@ -143,7 +160,7 @@ void TypePrettyPrinter::visit(Namespace *type)
void TypePrettyPrinter::visit(Template *type)
{
if (Symbol *d = type->declaration()) {
- if (overview()->showTemplateParameters() && ! _name.isEmpty()) {
+ if (overview()->showTemplateParameters && ! _name.isEmpty()) {
_name += QLatin1Char('<');
for (unsigned index = 0; index < type->templateParameterCount(); ++index) {
if (index)
@@ -175,6 +192,46 @@ void TypePrettyPrinter::visit(Enum *type)
prependCv(_fullySpecifiedType);
}
+void TypePrettyPrinter::visitIndirectionType(
+ const TypePrettyPrinter::IndirectionType indirectionType,
+ const FullySpecifiedType &elementType,
+ bool isIndirectionToArrayOrFunction)
+{
+ QLatin1Char indirectionSign = indirectionType == aPointerType
+ ? QLatin1Char('*') : QLatin1Char('&');
+
+ const bool prevIsIndirectionType = switchIsIndirectionType(true);
+ const bool hasName = ! _name.isEmpty();
+ if (hasName) {
+ _text.prepend(_name);
+ _name.clear();
+ }
+ prependCv(_fullySpecifiedType);
+
+ if (_text.startsWith(QLatin1Char('&')) && indirectionType != aPointerType)
+ _text.prepend(QLatin1Char(' '));
+
+ const bool prevIsIndirectionToArrayOrFunction
+ = switchIsIndirectionToArrayOrFunction(isIndirectionToArrayOrFunction);
+
+ // Space after indirectionSign?
+ prependSpaceAfterIndirection(hasName);
+
+ // Write indirectionSign or reference
+ if (indirectionType == aRvalueReferenceType)
+ _text.prepend(QLatin1String("&&"));
+ else
+ _text.prepend(indirectionSign);
+
+ // Space before indirectionSign?
+ prependSpaceBeforeIndirection(elementType);
+
+ _needsParens = true;
+ acceptType(elementType);
+ (bool) switchIsIndirectionToArrayOrFunction(prevIsIndirectionToArrayOrFunction);
+ (bool) switchIsIndirectionType(prevIsIndirectionType);
+}
+
void TypePrettyPrinter::visit(IntegerType *type)
{
prependSpaceUnlessBracket();
@@ -246,35 +303,54 @@ void TypePrettyPrinter::visit(PointerToMemberType *type)
acceptType(type->elementType());
}
+void TypePrettyPrinter::prependSpaceBeforeIndirection(const FullySpecifiedType &type)
+{
+ const bool elementTypeIsPointerOrReference = type.type()->isPointerType()
+ || type.type()->isReferenceType();
+ const bool elementIsConstPointerOrReference = elementTypeIsPointerOrReference && type.isConst();
+ const bool shouldBindToLeftSpecifier = _overview->starBindFlags & Overview::BindToLeftSpecifier;
+ if (elementIsConstPointerOrReference && ! shouldBindToLeftSpecifier)
+ _text.prepend(QLatin1String(" "));
+}
+
+void TypePrettyPrinter::prependSpaceAfterIndirection(bool hasName)
+{
+ const bool hasCvSpecifier = _fullySpecifiedType.isConst() || _fullySpecifiedType.isVolatile();
+ const bool shouldBindToIdentifier = _overview->starBindFlags & Overview::BindToIdentifier;
+ const bool shouldBindToRightSpecifier =
+ _overview->starBindFlags & Overview::BindToRightSpecifier;
+
+ const bool spaceBeforeNameNeeded = hasName && ! shouldBindToIdentifier
+ && ! _isIndirectionToArrayOrFunction;
+ const bool spaceBeforeSpecifierNeeded = hasCvSpecifier && ! shouldBindToRightSpecifier;
+
+ const bool case1 = hasCvSpecifier && spaceBeforeSpecifierNeeded;
+ const bool case2 = ! hasCvSpecifier && spaceBeforeNameNeeded;
+ // case 3: In "char *argv[]", put a space between '*' and "argv" when requested
+ const bool case3 = ! hasCvSpecifier && ! shouldBindToIdentifier
+ && ! _isIndirectionToArrayOrFunction && _text.size() && _text.at(0).isLetter();
+ if (case1 || case2 || case3)
+ _text.prepend(QLatin1String(" "));
+}
+
void TypePrettyPrinter::visit(PointerType *type)
{
- if (! _name.isEmpty()) {
- _text.prepend(_name);
- _name.clear();
- }
- prependCv(_fullySpecifiedType);
- _text.prepend(QLatin1String("*"));
- _needsParens = true;
- acceptType(type->elementType());
+ const bool isIndirectionToFunction = type->elementType().type()->isFunctionType();
+ const bool isIndirectionToArray = type->elementType().type()->isArrayType();
+
+ visitIndirectionType(aPointerType, type->elementType(),
+ isIndirectionToFunction || isIndirectionToArray);
}
void TypePrettyPrinter::visit(ReferenceType *type)
{
- if (! _name.isEmpty()) {
- _text.prepend(_name);
- _name.clear();
- }
- prependCv(_fullySpecifiedType);
-
- if (_text.startsWith(QLatin1Char('&')))
- _text.prepend(QLatin1Char(' '));
+ const bool isIndirectionToFunction = type->elementType().type()->isFunctionType();
+ const bool isIndirectionToArray = type->elementType().type()->isArrayType();
+ const IndirectionType indirectionType = type->isRvalueReference()
+ ? aRvalueReferenceType : aReferenceType;
- if (type->isRvalueReference())
- _text.prepend(QLatin1String("&&"));
- else
- _text.prepend(QLatin1String("&"));
- _needsParens = true;
- acceptType(type->elementType());
+ visitIndirectionType(indirectionType, type->elementType(),
+ isIndirectionToFunction || isIndirectionToArray);
}
void TypePrettyPrinter::visit(ArrayType *type)
@@ -309,13 +385,13 @@ void TypePrettyPrinter::visit(Function *type)
}
_text.append(QLatin1Char(')'));
_needsParens = false;
- } else if (! _name.isEmpty() && _overview->showFunctionSignatures()) {
+ } else if (! _name.isEmpty() && _overview->showFunctionSignatures) {
appendSpace();
_text.append(_name);
_name.clear();
}
- if (_overview->showReturnTypes()) {
+ if (_overview->showReturnTypes) {
const QString returnType = _overview->prettyType(type->returnType());
if (!returnType.isEmpty()) {
if (!endsWithPtrOrRef(returnType))
@@ -324,11 +400,12 @@ void TypePrettyPrinter::visit(Function *type)
}
}
- if (_overview->showFunctionSignatures()) {
+ if (_overview->showFunctionSignatures) {
Overview argumentText;
- argumentText.setShowReturnTypes(true);
- argumentText.setShowArgumentNames(false);
- argumentText.setShowFunctionSignatures(true);
+ argumentText.starBindFlags = _overview->starBindFlags;
+ argumentText.showReturnTypes = true;
+ argumentText.showArgumentNames = false;
+ argumentText.showFunctionSignatures = true;
_text += QLatin1Char('(');
@@ -337,25 +414,25 @@ void TypePrettyPrinter::visit(Function *type)
_text += QLatin1String(", ");
if (Argument *arg = type->argumentAt(index)->asArgument()) {
- if (index + 1 == _overview->markedArgument())
- const_cast<Overview*>(_overview)->setMarkedArgumentBegin(_text.length());
+ if (index + 1 == _overview->markedArgument)
+ const_cast<Overview*>(_overview)->markedArgumentBegin = _text.length();
const Name *name = 0;
- if (_overview->showArgumentNames())
+ if (_overview->showArgumentNames)
name = arg->name();
- _text += argumentText(arg->type(), name);
+ _text += argumentText.prettyType(arg->type(), name);
- if (_overview->showDefaultArguments()) {
+ if (_overview->showDefaultArguments) {
if (const StringLiteral *initializer = arg->initializer()) {
_text += QLatin1String(" =");
_text += QString::fromUtf8(initializer->chars(), initializer->size());
}
}
- if (index + 1 == _overview->markedArgument())
- const_cast<Overview*>(_overview)->setMarkedArgumentEnd(_text.length());
+ if (index + 1 == _overview->markedArgument)
+ const_cast<Overview*>(_overview)->markedArgumentEnd = _text.length();
}
}
@@ -365,11 +442,11 @@ void TypePrettyPrinter::visit(Function *type)
_text += QLatin1Char(')');
if (type->isConst()) {
appendSpace();
- _text += "const";
+ _text += QLatin1String("const");
}
if (type->isVolatile()) {
appendSpace();
- _text += "volatile";
+ _text += QLatin1String("volatile");
}
}
}
@@ -393,8 +470,16 @@ void TypePrettyPrinter::prependSpaceUnlessBracket()
const QChar ch = _text.at(0);
- if (ch != QLatin1Char('['))
- _text.prepend(" ");
+ if (ch != QLatin1Char('[')) {
+ const bool shouldBindToTypeNam = _overview->starBindFlags & Overview::BindToTypeName;
+ const bool caseNoIndirection = ! _isIndirectionType;
+ const bool caseIndirectionToArrayOrFunction = _isIndirectionType
+ && _isIndirectionToArrayOrFunction;
+ const bool casePointerNoBind = _isIndirectionType && ! _isIndirectionToArrayOrFunction
+ && ! shouldBindToTypeNam;
+ if (caseNoIndirection || caseIndirectionToArrayOrFunction || casePointerNoBind)
+ _text.prepend(QLatin1Char(' '));
+ }
}
void TypePrettyPrinter::prependWordSeparatorSpace()
@@ -405,19 +490,19 @@ void TypePrettyPrinter::prependWordSeparatorSpace()
const QChar ch = _text.at(0);
if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
- _text.prepend(" ");
+ _text.prepend(QLatin1Char(' '));
}
void TypePrettyPrinter::prependCv(const FullySpecifiedType &ty)
{
if (ty.isVolatile()) {
prependWordSeparatorSpace();
- _text.prepend("volatile");
+ _text.prepend(QLatin1String("volatile"));
}
if (ty.isConst()) {
prependWordSeparatorSpace();
- _text.prepend("const");
+ _text.prepend(QLatin1String("const"));
}
}
diff --git a/src/libs/cplusplus/TypePrettyPrinter.h b/src/libs/cplusplus/TypePrettyPrinter.h
index 07fcb23bde..8ee02528a9 100644
--- a/src/libs/cplusplus/TypePrettyPrinter.h
+++ b/src/libs/cplusplus/TypePrettyPrinter.h
@@ -39,6 +39,14 @@ namespace CPlusPlus {
class Overview;
class FullySpecifiedType;
+/*!
+ \class TypePrettyPrinter
+
+ \brief Helper class for Overview. Does the main type conversation work.
+
+ Don't use this class directly, use Overview instead.
+ */
+
class CPLUSPLUS_EXPORT TypePrettyPrinter: protected TypeVisitor
{
public:
@@ -50,11 +58,7 @@ public:
QString operator()(const FullySpecifiedType &type);
QString operator()(const FullySpecifiedType &type, const QString &name);
-protected:
- QString switchText(const QString &text = QString());
- bool switchNeedsParens(bool needsParens);
- QString switchName(const QString &name);
-
+private:
void acceptType(const FullySpecifiedType &ty);
virtual void visit(UndefinedType *type);
@@ -72,17 +76,30 @@ protected:
virtual void visit(Class *type);
virtual void visit(Enum *type);
+ QString switchName(const QString &name);
+ QString switchText(const QString &text = QString());
+ bool switchNeedsParens(bool needsParens);
+ bool switchIsIndirectionType(bool isIndirectionType);
+ bool switchIsIndirectionToArrayOrFunction(bool isIndirectionToArrayOrFunction);
+
void appendSpace();
void prependSpaceUnlessBracket();
void prependWordSeparatorSpace();
void prependCv(const FullySpecifiedType &ty);
+ void prependSpaceAfterIndirection(bool hasName);
+ void prependSpaceBeforeIndirection(const FullySpecifiedType &type);
+
+ enum IndirectionType { aPointerType, aReferenceType, aRvalueReferenceType };
+ void visitIndirectionType(const IndirectionType indirectionType,
+ const FullySpecifiedType &elementType, bool isIndirectionToArrayOrFunction);
-private:
const Overview *_overview;
QString _name;
QString _text;
FullySpecifiedType _fullySpecifiedType;
bool _needsParens;
+ bool _isIndirectionType;
+ bool _isIndirectionToArrayOrFunction;
};
} // namespace CPlusPlus
diff --git a/src/libs/cplusplus/cplusplus-lib.pri b/src/libs/cplusplus/cplusplus-lib.pri
index 2a8d5d544c..a2ccabdfb4 100644
--- a/src/libs/cplusplus/cplusplus-lib.pri
+++ b/src/libs/cplusplus/cplusplus-lib.pri
@@ -10,6 +10,8 @@ include(../3rdparty/cplusplus/cplusplus.pri)
greaterThan(QT_MAJOR_VERSION, 4): QT += concurrent
+#DEFINES += DEBUG_INCLUDE_GUARD_TRACKING
+
contains(QT, gui) {
HEADERS += \
$$PWD/Icons.h \
@@ -36,6 +38,7 @@ HEADERS += \
$$PWD/TypePrettyPrinter.h \
$$PWD/ResolveExpression.h \
$$PWD/LookupItem.h \
+ $$PWD/AlreadyConsideredClassContainer.h \
$$PWD/LookupContext.h \
$$PWD/ASTParent.h \
$$PWD/ASTPath.h \
diff --git a/src/libs/cplusplus/cplusplus.qbs b/src/libs/cplusplus/cplusplus.qbs
index 6038fc6a2c..08213f11d6 100644
--- a/src/libs/cplusplus/cplusplus.qbs
+++ b/src/libs/cplusplus/cplusplus.qbs
@@ -4,12 +4,7 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "CPlusPlus"
- cpp.includePaths: [
- ".",
- "..",
- "../3rdparty/cplusplus",
- "../../plugins"
- ]
+ cpp.includePaths: base.concat("../3rdparty/cplusplus")
cpp.defines: base.concat([
"NDEBUG",
"CPLUSPLUS_BUILD_LIB"
@@ -22,13 +17,21 @@ QtcLibrary {
Group {
prefix: "../3rdparty/cplusplus/"
files: [
+ "AST.cpp",
+ "AST.h",
+ "ASTClone.cpp",
+ "ASTMatch0.cpp",
+ "ASTMatcher.cpp",
+ "ASTMatcher.h",
"ASTPatternBuilder.cpp",
- "CPlusPlus.h",
- "LiteralTable.cpp",
- "ObjectiveCTypeQualifiers.h",
- "Templates.cpp",
- "Templates.h",
+ "ASTPatternBuilder.h",
+ "ASTVisit.cpp",
"ASTVisitor.cpp",
+ "ASTVisitor.h",
+ "ASTfwd.h",
+ "Bind.cpp",
+ "Bind.h",
+ "CPlusPlus.h",
"Control.cpp",
"Control.h",
"CoreTypes.cpp",
@@ -37,8 +40,12 @@ QtcLibrary {
"DiagnosticClient.h",
"FullySpecifiedType.cpp",
"FullySpecifiedType.h",
+ "Keywords.cpp",
+ "Lexer.cpp",
"Lexer.h",
+ "LiteralTable.cpp",
"LiteralTable.h",
+ "Literals.cpp",
"Literals.h",
"MemoryPool.cpp",
"MemoryPool.h",
@@ -50,48 +57,36 @@ QtcLibrary {
"Names.h",
"ObjectiveCAtKeywords.cpp",
"ObjectiveCTypeQualifiers.cpp",
+ "ObjectiveCTypeQualifiers.h",
+ "Parser.cpp",
+ "Parser.h",
+ "QtContextKeywords.cpp",
+ "QtContextKeywords.h",
"Scope.cpp",
"Scope.h",
+ "Symbol.cpp",
+ "Symbol.h",
"SymbolVisitor.cpp",
"SymbolVisitor.h",
+ "Symbols.cpp",
"Symbols.h",
+ "Templates.cpp",
+ "Templates.h",
+ "Token.cpp",
+ "Token.h",
+ "TranslationUnit.cpp",
+ "TranslationUnit.h",
"Type.cpp",
"Type.h",
"TypeMatcher.cpp",
"TypeMatcher.h",
"TypeVisitor.cpp",
"TypeVisitor.h",
- "AST.cpp",
- "AST.h",
- "ASTClone.cpp",
- "ASTMatch0.cpp",
- "ASTMatcher.cpp",
- "ASTMatcher.h",
- "ASTPatternBuilder.h",
- "ASTVisit.cpp",
- "ASTVisitor.h",
- "ASTfwd.h",
- "Bind.cpp",
- "Bind.h",
- "Keywords.cpp",
- "Lexer.cpp",
- "Literals.cpp",
- "Parser.cpp",
- "Parser.h",
- "QtContextKeywords.cpp",
- "QtContextKeywords.h",
- "Symbol.cpp",
- "Symbol.h",
- "Symbols.cpp",
- "Token.cpp",
- "Token.h",
- "TranslationUnit.cpp",
- "TranslationUnit.h"
]
}
files: [
- "cplusplus.qrc",
+ "AlreadyConsideredClassContainer.h",
"ASTParent.cpp",
"ASTParent.h",
"ASTPath.cpp",
@@ -128,6 +123,8 @@ QtcLibrary {
"Overview.h",
"OverviewModel.cpp",
"OverviewModel.h",
+ "PPToken.cpp",
+ "PPToken.h",
"PreprocessorClient.cpp",
"PreprocessorClient.h",
"PreprocessorEnvironment.cpp",
@@ -144,13 +141,12 @@ QtcLibrary {
"TypeOfExpression.h",
"TypePrettyPrinter.cpp",
"TypePrettyPrinter.h",
+ "cplusplus.qrc",
"findcdbbreakpoint.cpp",
"findcdbbreakpoint.h",
"pp-cctype.h",
"pp-engine.cpp",
"pp-engine.h",
- "PPToken.cpp",
- "PPToken.h",
"pp-scanner.cpp",
"pp-scanner.h",
"pp.h",
@@ -169,7 +165,7 @@ QtcLibrary {
"images/slot_prot.png",
"images/var.png",
"images/var_priv.png",
- "images/var_prot.png"
+ "images/var_prot.png",
]
ProductModule {
@@ -181,4 +177,3 @@ QtcLibrary {
]
}
}
-
diff --git a/src/libs/cplusplus/pp-engine.cpp b/src/libs/cplusplus/pp-engine.cpp
index be5e84deb8..1e3b186f0b 100644
--- a/src/libs/cplusplus/pp-engine.cpp
+++ b/src/libs/cplusplus/pp-engine.cpp
@@ -80,6 +80,7 @@ enum {
}
namespace {
+/// RAII object to save a value, and restore it when the scope is left.
template<typename _T>
class ScopedSwap
{
@@ -100,12 +101,19 @@ public:
}
};
typedef ScopedSwap<bool> ScopedBoolSwap;
-typedef ScopedSwap<unsigned> ScopedUnsignedSwap;
} // anonymous namespace
namespace CPlusPlus {
namespace Internal {
+/// Buffers tokens for the Preprocessor::lex() to read next. Do not use this
+/// class directly, but use Preprocessor::State::pushTokenBuffer .
+///
+/// New tokens are added when undoing look-ahead, or after expanding a macro.
+/// When macro expansion happened, the macro is passed in, and blocked until
+/// all tokens generated by it (and by subsequent expansion of those generated
+/// tokens) are read from the buffer. See Preprocessor::lex() for details on
+/// exactly when the buffer (and subsequently a blocking macro) is removed.
struct TokenBuffer
{
std::deque<PPToken> tokens;
@@ -121,8 +129,9 @@ struct TokenBuffer
return false;
for (const TokenBuffer *it = this; it; it = it->next)
- if (it->macro == macro && it->macro->name() == macro->name())
- return true;
+ if (it->macro)
+ if (it->macro == macro || (it->macro->name() == macro->name()))
+ return true;
return false;
}
};
@@ -368,9 +377,8 @@ protected:
env, client)
!= 0);
++(*_lex);
- if ((*_lex)->is(T_RPAREN)) {
+ if ((*_lex)->is(T_RPAREN))
++(*_lex);
- }
}
}
} else if ((*_lex)->is(T_IDENTIFIER)) {
@@ -549,6 +557,7 @@ Preprocessor::State::State()
, m_offsetRef(0)
, m_lineRef(1)
, m_expansionStatus(NotExpanding)
+ , m_includeGuardState(IncludeGuardState_BeforeIfndef)
{
m_skipping[m_ifLevel] = false;
m_trueTest[m_ifLevel] = false;
@@ -556,22 +565,21 @@ Preprocessor::State::State()
m_expansionResult.reserve(256);
}
-//#define COMPRESS_TOKEN_BUFFER
+#define COMPRESS_TOKEN_BUFFER
void Preprocessor::State::pushTokenBuffer(const PPToken *start, const PPToken *end, const Macro *macro)
{
if (m_tokenBufferDepth <= MAX_TOKEN_BUFFER_DEPTH) {
#ifdef COMPRESS_TOKEN_BUFFER
- // This does not work correctly for boost's preprocessor library, or that library exposes a bug in the code.
if (macro || !m_tokenBuffer) {
+ // If there is a new blocking macro (or no token buffer yet), create
+ // one.
m_tokenBuffer = new TokenBuffer(start, end, macro, m_tokenBuffer);
++m_tokenBufferDepth;
} else {
+ // No new blocking macro is passed in, so tokens can be prepended to
+ // the existing buffer.
m_tokenBuffer->tokens.insert(m_tokenBuffer->tokens.begin(), start, end);
}
- unsigned tkCount = 0;
- for (TokenBuffer *it = m_tokenBuffer; it; it = m_tokenBuffer->next)
- tkCount += it->tokens.size();
- qDebug()<<"New depth:" << m_tokenBufferDepth << "with total token count:" << tkCount;
#else
m_tokenBuffer = new TokenBuffer(start, end, macro, m_tokenBuffer);
++m_tokenBufferDepth;
@@ -589,6 +597,90 @@ void Preprocessor::State::popTokenBuffer()
--m_tokenBufferDepth;
}
+#ifdef DEBUG_INCLUDE_GUARD_TRACKING
+QString Preprocessor::State::guardStateToString(int guardState)
+{
+ switch (guardState) {
+ case IncludeGuardState_NoGuard: return QLatin1String("NoGuard");
+ case IncludeGuardState_BeforeIfndef: return QLatin1String("BeforeIfndef");
+ case IncludeGuardState_AfterIfndef: return QLatin1String("AfterIfndef");
+ case IncludeGuardState_AfterDefine: return QLatin1String("AfterDefine");
+ case IncludeGuardState_AfterEndif: return QLatin1String("AfterEndif");
+ default: return QLatin1String("UNKNOWN");
+ }
+}
+#endif // DEBUG_INCLUDE_GUARD_TRACKING
+
+/**
+ * @brief Update the include-guard tracking state.
+ *
+ * Include guards are the #ifdef/#define/#endif sequence typically found in
+ * header files to prevent repeated definition of the contents of that header
+ * file. So, for a file to have an include guard, it must look like this:
+ * \code
+ * #ifndef SOME_ID
+ * ... all declarations/definitions/etc. go here ...
+ * #endif
+ * \endcode
+ *
+ * SOME_ID is an identifier, and is also the include guard. The only tokens
+ * allowed before the #ifndef and after the #endif are comments (in any form)
+ * or #line directives. The only other requirement is that a #define SOME_ID
+ * occurs inside the #ifndef block, but not nested inside other
+ * #if/#ifdef/#ifndef blocks.
+ *
+ * This method tracks the state, and is called from \c updateIncludeGuardState
+ * which handles the most common no-op cases.
+ *
+ * @param hint indicates what kind of token is encountered in the input
+ * @param idToken the identifier token that ought to be in the input
+ * after a #ifndef or a #define .
+ */
+void Preprocessor::State::updateIncludeGuardState_helper(IncludeGuardStateHint hint, PPToken *idToken)
+{
+#ifdef DEBUG_INCLUDE_GUARD_TRACKING
+ int oldIncludeGuardState = m_includeGuardState;
+ QByteArray oldIncludeGuardMacroName = m_includeGuardMacroName;
+#endif // DEBUG_INCLUDE_GUARD_TRACKING
+
+ switch (m_includeGuardState) {
+ case IncludeGuardState_NoGuard:
+ break;
+ case IncludeGuardState_BeforeIfndef:
+ if (hint == IncludeGuardStateHint_Ifndef
+ && idToken && idToken->is(T_IDENTIFIER)) {
+ m_includeGuardMacroName = idToken->asByteArrayRef().toByteArray();
+ m_includeGuardState = IncludeGuardState_AfterIfndef;
+ } else {
+ m_includeGuardState = IncludeGuardState_NoGuard;
+ }
+ break;
+ case IncludeGuardState_AfterIfndef:
+ if (hint == IncludeGuardStateHint_Define
+ && idToken && idToken->is(T_IDENTIFIER)
+ && idToken->asByteArrayRef() == m_includeGuardMacroName)
+ m_includeGuardState = IncludeGuardState_AfterDefine;
+ break;
+ case IncludeGuardState_AfterDefine:
+ if (hint == IncludeGuardStateHint_Endif)
+ m_includeGuardState = IncludeGuardState_AfterEndif;
+ break;
+ case IncludeGuardState_AfterEndif:
+ m_includeGuardState = IncludeGuardState_NoGuard;
+ m_includeGuardMacroName.clear();
+ break;
+ }
+
+#ifdef DEBUG_INCLUDE_GUARD_TRACKING
+ qDebug() << "***" << guardStateToString(oldIncludeGuardState)
+ << "->" << guardStateToString(m_includeGuardState)
+ << "hint:" << hint
+ << "guard:" << oldIncludeGuardMacroName << "->" << m_includeGuardMacroName;
+#endif // DEBUG_INCLUDE_GUARD_TRACKING
+}
+
+const QString Preprocessor::configurationFileName = QLatin1String("<configuration>");
+
Preprocessor::Preprocessor(Client *client, Environment *env)
: m_client(client)
, m_env(env)
@@ -609,8 +701,11 @@ QByteArray Preprocessor::run(const QString &fileName,
{
m_scratchBuffer.clear();
- QByteArray preprocessed;
- preprocess(fileName, source, &preprocessed, noLines, markGeneratedTokens, false);
+ QByteArray preprocessed, includeGuardMacroName;
+ preprocess(fileName, source, &preprocessed, &includeGuardMacroName, noLines,
+ markGeneratedTokens, false);
+ if (!includeGuardMacroName.isEmpty())
+ m_client->markAsIncludeGuard(includeGuardMacroName);
return preprocessed;
}
@@ -692,13 +787,22 @@ void Preprocessor::lex(PPToken *tk)
{
_Lagain:
if (m_state.m_tokenBuffer) {
+ // There is a token buffer, so read from there.
if (m_state.m_tokenBuffer->tokens.empty()) {
+ // The token buffer is empty, so pop it, and start over.
m_state.popTokenBuffer();
goto _Lagain;
}
*tk = m_state.m_tokenBuffer->tokens.front();
m_state.m_tokenBuffer->tokens.pop_front();
+ // The token buffer might now be empty. We leave it in, because the
+ // token we just read might expand into new tokens, or might be a call
+ // to the macro that generated this token. In either case, the macro
+ // that generated the token still needs to be blocked (!), which is
+ // recorded in the token buffer. Removing the blocked macro and the
+ // empty token buffer happens the next time that this method is called.
} else {
+ // No token buffer, so have the lexer scan the next token.
tk->setSource(m_state.m_source);
m_state.m_lexer->scan(tk);
}
@@ -718,6 +822,7 @@ _Lclassify:
} while (isContinuationToken(*tk));
goto _Lclassify;
} else if (tk->is(T_IDENTIFIER) && !isQtReservedWord(tk->asByteArrayRef())) {
+ m_state.updateIncludeGuardState(State::IncludeGuardStateHint_OtherToken);
if (m_state.m_inCondition && tk->asByteArrayRef() == "defined") {
handleDefined(tk);
} else {
@@ -725,6 +830,8 @@ _Lclassify:
if (handleIdentifier(tk))
goto _Lagain;
}
+ } else if (tk->isNot(T_COMMENT) && tk->isNot(T_EOF_SYMBOL)) {
+ m_state.updateIncludeGuardState(State::IncludeGuardStateHint_OtherToken);
}
}
}
@@ -1093,16 +1200,17 @@ void Preprocessor::trackExpansionCycles(PPToken *tk)
m_state.m_expandedTokensInfo.clear();
} else if (m_state.m_expansionStatus == Expanding) {
m_state.m_expansionStatus = JustFinishedExpansion;
- maybeStartOutputLine();
- writeOutput("# expansion begin ");
- QByteArray expansionInfo;
- expansionInfo.reserve(m_state.m_expandedTokensInfo.size() * 2); // Rough estimate
+ QByteArray *buffer = currentOutputBuffer();
+ if (!buffer)
+ return;
+
+ maybeStartOutputLine();
// Offset and length of the macro invocation
- expansionInfo.append(QByteArray::number(tk->offset));
- expansionInfo.append(',');
- expansionInfo.append(QByteArray::number(tk->length()));
+ char chunk[40];
+ qsnprintf(chunk, sizeof(chunk), "# expansion begin %d,%d", tk->offset, tk->length());
+ buffer->append(chunk);
// Expanded tokens
unsigned generatedCount = 0;
@@ -1110,28 +1218,24 @@ void Preprocessor::trackExpansionCycles(PPToken *tk)
const QPair<unsigned, unsigned> &p = m_state.m_expandedTokensInfo.at(i);
if (p.first) {
if (generatedCount) {
- expansionInfo.append(" ~");
- expansionInfo.append(QByteArray::number(generatedCount));
+ qsnprintf(chunk, sizeof(chunk), " ~%d", generatedCount);
+ buffer->append(chunk);
generatedCount = 0;
}
- expansionInfo.append(' ');
- expansionInfo.append(QByteArray::number(p.first));
- expansionInfo.append(':');
- expansionInfo.append(QByteArray::number(p.second));
+ qsnprintf(chunk, sizeof(chunk), " %d:%d", p.first, p.second);
+ buffer->append(chunk);
} else {
++generatedCount;
}
}
if (generatedCount) {
- expansionInfo.append(" ~");
- expansionInfo.append(QByteArray::number(generatedCount));
+ qsnprintf(chunk, sizeof(chunk), " ~%d", generatedCount);
+ buffer->append(chunk);
}
- expansionInfo.append('\n');
-
- writeOutput(expansionInfo);
- writeOutput(m_state.m_expansionResult);
+ buffer->append('\n');
+ buffer->append(m_state.m_expansionResult);
maybeStartOutputLine();
- writeOutput("# expansion end\n");
+ buffer->append("# expansion end\n");
}
lex(tk);
@@ -1229,15 +1333,15 @@ void Preprocessor::enforceSpacing(const Preprocessor::PPToken &tk, bool forceSpa
/// invalid pp-tokens are used as markers to force whitespace checks.
void Preprocessor::preprocess(const QString &fileName, const QByteArray &source,
- QByteArray *result, bool noLines,
+ QByteArray *result, QByteArray *includeGuardMacroName,
+ bool noLines,
bool markGeneratedTokens, bool inCondition,
unsigned offsetRef, unsigned lineRef)
{
if (source.isEmpty())
return;
- const State savedState = m_state;
- m_state = State();
+ ScopedSwap<State> savedState(m_state, State());
m_state.m_currentFileName = fileName;
m_state.m_source = source;
m_state.m_lexer = new Lexer(source.constBegin(), source.constEnd());
@@ -1252,12 +1356,9 @@ void Preprocessor::preprocess(const QString &fileName, const QByteArray &source,
m_state.m_offsetRef = offsetRef;
m_state.m_lineRef = lineRef;
- const QString previousFileName = m_env->currentFile;
- m_env->currentFile = fileName;
- m_env->currentFileUtf8 = fileName.toUtf8();
-
- const unsigned previousCurrentLine = m_env->currentLine;
- m_env->currentLine = 1;
+ ScopedSwap<QString> savedFileName(m_env->currentFile, fileName);
+ ScopedSwap<QByteArray> savedUtf8FileName(m_env->currentFileUtf8, fileName.toUtf8());
+ ScopedSwap<unsigned> savedCurrentLine(m_env->currentLine, 1);
if (!m_state.m_noLines)
generateOutputLineMarker(1);
@@ -1298,14 +1399,14 @@ void Preprocessor::preprocess(const QString &fileName, const QByteArray &source,
removeTrailingOutputLines();
+ if (includeGuardMacroName) {
+ if (m_state.m_includeGuardState == State::IncludeGuardState_AfterDefine
+ || m_state.m_includeGuardState == State::IncludeGuardState_AfterEndif)
+ *includeGuardMacroName = m_state.m_includeGuardMacroName;
+ }
delete m_state.m_lexer;
while (m_state.m_tokenBuffer)
m_state.popTokenBuffer();
- m_state = savedState;
-
- m_env->currentFile = previousFileName;
- m_env->currentFileUtf8 = previousFileName.toUtf8();
- m_env->currentLine = previousCurrentLine;
}
bool Preprocessor::collectActualArguments(PPToken *tk, QVector<QVector<PPToken> > *actuals)
@@ -1315,6 +1416,13 @@ bool Preprocessor::collectActualArguments(PPToken *tk, QVector<QVector<PPToken>
lex(tk); // consume the identifier
+ // consume comments
+ while (tk->isComment()) {
+ lex(tk);
+ if (!tk)
+ return false;
+ }
+
if (tk->isNot(T_LPAREN))
//### TODO: error message
return false;
@@ -1404,33 +1512,38 @@ void Preprocessor::handlePreprocessorDirective(PPToken *tk)
if (tk->is(T_IDENTIFIER)) {
const ByteArrayRef directive = tk->asByteArrayRef();
- if (!skipping() && directive == ppDefine)
+ if (!skipping() && directive == ppDefine) {
handleDefineDirective(tk);
- else if (!skipping() && directive == ppUndef)
- handleUndefDirective(tk);
- else if (!skipping() && (directive == ppInclude
- || directive == ppIncludeNext
- || directive == ppImport))
- handleIncludeDirective(tk);
- else if (directive == ppIf)
- handleIfDirective(tk);
- else if (directive == ppIfDef)
- handleIfDefDirective(false, tk);
- else if (directive == ppIfNDef)
+ } else if (directive == ppIfNDef) {
handleIfDefDirective(true, tk);
- else if (directive == ppEndIf)
+ } else if (directive == ppEndIf) {
handleEndIfDirective(tk, poundToken);
- else if (directive == ppElse)
- handleElseDirective(tk, poundToken);
- else if (directive == ppElif)
- handleElifDirective(tk, poundToken);
+ } else {
+ m_state.updateIncludeGuardState(State::IncludeGuardStateHint_OtherToken);
+
+ if (!skipping() && directive == ppUndef)
+ handleUndefDirective(tk);
+ else if (!skipping() && (directive == ppInclude
+ || directive == ppImport))
+ handleIncludeDirective(tk, false);
+ else if (!skipping() && directive == ppIncludeNext)
+ handleIncludeDirective(tk, true);
+ else if (directive == ppIf)
+ handleIfDirective(tk);
+ else if (directive == ppIfDef)
+ handleIfDefDirective(false, tk);
+ else if (directive == ppElse)
+ handleElseDirective(tk, poundToken);
+ else if (directive == ppElif)
+ handleElifDirective(tk, poundToken);
+ }
}
skipPreprocesorDirective(tk);
}
-void Preprocessor::handleIncludeDirective(PPToken *tk)
+void Preprocessor::handleIncludeDirective(PPToken *tk, bool includeNext)
{
m_state.m_lexer->setScanAngleStringLiteralTokens(true);
lex(tk); // consume "include" token
@@ -1453,7 +1566,9 @@ void Preprocessor::handleIncludeDirective(PPToken *tk)
// qDebug("include [[%s]]", included.toUtf8().constData());
Client::IncludeType mode;
- if (included.at(0) == '"')
+ if (includeNext)
+ mode = Client::IncludeNext;
+ else if (included.at(0) == '"')
mode = Client::IncludeLocal;
else if (included.at(0) == '<')
mode = Client::IncludeGlobal;
@@ -1481,6 +1596,8 @@ void Preprocessor::handleDefineDirective(PPToken *tk)
macro.setName(macroName);
macro.setOffset(tk->offset);
+ PPToken idToken(*tk);
+
lex(tk);
if (isContinuationToken(*tk) && tk->is(T_LPAREN) && ! tk->whitespace()) {
@@ -1515,6 +1632,9 @@ void Preprocessor::handleDefineDirective(PPToken *tk)
}
if (isContinuationToken(*tk) && tk->is(T_RPAREN))
lex(tk); // consume ")" token
+ } else {
+ if (m_state.m_ifLevel == 1)
+ m_state.updateIncludeGuardState(State::IncludeGuardStateHint_Define, &idToken);
}
QVector<PPToken> bodyTokens;
@@ -1540,9 +1660,8 @@ void Preprocessor::handleDefineDirective(PPToken *tk)
}
}
} else if (macroReference) {
- if (tk->is(T_LPAREN)) {
+ if (tk->is(T_LPAREN))
m_client->notifyMacroReference(previousOffset, previousLine, *macroReference);
- }
macroReference = 0;
}
@@ -1612,7 +1731,7 @@ QByteArray Preprocessor::expand(PPToken *tk, PPToken *lastConditionToken)
// qDebug("*** Condition before: [%s]", condition.constData());
QByteArray result;
result.reserve(256);
- preprocess(m_state.m_currentFileName, condition, &result, true, false, true, begin, line);
+ preprocess(m_state.m_currentFileName, condition, &result, 0, true, false, true, begin, line);
result.squeeze();
// qDebug("*** Condition after: [%s]", result.constData());
@@ -1733,6 +1852,9 @@ void Preprocessor::handleEndIfDirective(PPToken *tk, const PPToken &poundToken)
--m_state.m_ifLevel;
if (m_client && wasSkipping && !m_state.m_skipping[m_state.m_ifLevel])
m_client->stopSkippingBlocks(poundToken.offset - 1);
+
+ if (m_state.m_ifLevel == 0)
+ m_state.updateIncludeGuardState(State::IncludeGuardStateHint_Endif);
}
lex(tk); // consume "endif" token
@@ -1744,6 +1866,9 @@ void Preprocessor::handleIfDefDirective(bool checkUndefined, PPToken *tk)
lex(tk); // consume "ifdef" token
if (tk->is(T_IDENTIFIER)) {
+ if (checkUndefined && m_state.m_ifLevel == 0)
+ m_state.updateIncludeGuardState(State::IncludeGuardStateHint_Ifndef, tk);
+
bool value = false;
const ByteArrayRef macroName = tk->asByteArrayRef();
if (Macro *macro = macroDefinition(macroName, tk->offset, tk->lineno, m_env, m_client)) {
@@ -1751,7 +1876,7 @@ void Preprocessor::handleIfDefDirective(bool checkUndefined, PPToken *tk)
// the macro is a feature constraint(e.g. QT_NO_XXX)
if (checkUndefined && macroName.startsWith("QT_NO_")) {
- if (macro->fileName() == QLatin1String("<configuration>")) {
+ if (macro->fileName() == configurationFileName) {
// and it' defined in a pro file (e.g. DEFINES += QT_NO_QOBJECT)
value = false; // take the branch
diff --git a/src/libs/cplusplus/pp-engine.h b/src/libs/cplusplus/pp-engine.h
index 500ad1d4f2..2bad2a5f6d 100644
--- a/src/libs/cplusplus/pp-engine.h
+++ b/src/libs/cplusplus/pp-engine.h
@@ -75,10 +75,14 @@ class CPLUSPLUS_EXPORT Preprocessor
typedef Internal::Value Value;
public:
+ static const QString configurationFileName;
+
+public:
Preprocessor(Client *client, Environment *env);
QByteArray run(const QString &filename, const QString &source);
- QByteArray run(const QString &filename, const QByteArray &source, bool noLines = false, bool markGeneratedTokens = true);
+ QByteArray run(const QString &filename, const QByteArray &source,
+ bool noLines = false, bool markGeneratedTokens = true);
bool expandFunctionlikeMacros() const;
void setExpandFunctionlikeMacros(bool expandFunctionlikeMacros);
@@ -87,9 +91,9 @@ public:
void setKeepComments(bool keepComments);
private:
- void preprocess(const QString &filename,
- const QByteArray &source,
- QByteArray *result, bool noLines, bool markGeneratedTokens, bool inCondition,
+ void preprocess(const QString &filename, const QByteArray &source,
+ QByteArray *result, QByteArray *includeGuardMacroName,
+ bool noLines, bool markGeneratedTokens, bool inCondition,
unsigned offsetRef = 0, unsigned lineRef = 1);
enum { MAX_LEVEL = 512 };
@@ -130,6 +134,61 @@ private:
ExpansionStatus m_expansionStatus;
QByteArray m_expansionResult;
QVector<QPair<unsigned, unsigned> > m_expandedTokensInfo;
+
+ enum {
+ /// State to indicate that no guard is possible anymore.
+ IncludeGuardState_NoGuard = 0,
+ /// Initial state before the first non-comment token.
+ IncludeGuardState_BeforeIfndef,
+ /// State to indicate that the first interesting token was a
+ /// #ifndef token.
+ IncludeGuardState_AfterIfndef,
+ /// State to indicate that the only interesting tokens were
+ /// a #ifndef and a #define .
+ IncludeGuardState_AfterDefine,
+ /// State for after reading the #endif belonging to the #ifndef
+ IncludeGuardState_AfterEndif
+ } m_includeGuardState;
+ QByteArray m_includeGuardMacroName;
+
+ enum IncludeGuardStateHint {
+ /// anything that is not a comment, a #ifndef, a #define, or a
+ /// #endif
+ IncludeGuardStateHint_OtherToken = 0,
+ /// we hit a #ifndef
+ IncludeGuardStateHint_Ifndef,
+ /// we hit a #define
+ IncludeGuardStateHint_Define,
+ /// we hit a #endif
+ IncludeGuardStateHint_Endif
+ };
+
+ /// Update the include-guard state.
+ ///
+ /// \param hint indicates what kind of token is encountered in the input
+ /// \param idToken the identifier token that ought to be in the input
+ /// after a #ifndef or a #define .
+ inline void updateIncludeGuardState(IncludeGuardStateHint hint,
+ PPToken *idToken = 0)
+ {
+ // some quick checks for the majority of the uninteresting cases:
+ if (m_includeGuardState == IncludeGuardState_NoGuard)
+ return; // no valid guard is possible
+ if (m_includeGuardState == IncludeGuardState_AfterDefine
+ && hint == IncludeGuardStateHint_OtherToken)
+ return; // after the #define of the guard, and before the
+ // #endif, any non-endif token won't change the state
+ if (m_inCondition)
+ return; // include guards can never occur in pp-conditions
+
+ updateIncludeGuardState_helper(hint, idToken);
+ }
+
+ private:
+#ifdef DEBUG_INCLUDE_GUARD_TRACKING
+ static QString guardStateToString(int guardState);
+#endif // DEBUG_INCLUDE_GUARD_TRACKING
+ void updateIncludeGuardState_helper(IncludeGuardStateHint hint, PPToken *idToken);
};
void handleDefined(PPToken *tk);
@@ -152,7 +211,7 @@ private:
void scanActualArgument(PPToken *tk, QVector<PPToken> *tokens);
void handlePreprocessorDirective(PPToken *tk);
- void handleIncludeDirective(PPToken *tk);
+ void handleIncludeDirective(PPToken *tk, bool includeNext);
void handleDefineDirective(PPToken *tk);
QByteArray expand(PPToken *tk, PPToken *lastConditionToken = 0);
const Internal::PPToken evalExpression(PPToken *tk, Value &result);
diff --git a/src/libs/extensionsystem/extensionsystem.qbs b/src/libs/extensionsystem/extensionsystem.qbs
index bbdd8b74b3..f7a90814cb 100644
--- a/src/libs/extensionsystem/extensionsystem.qbs
+++ b/src/libs/extensionsystem/extensionsystem.qbs
@@ -4,10 +4,6 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "ExtensionSystem"
- cpp.includePaths: [
- ".",
- ".."
- ]
cpp.defines: base.concat([
"EXTENSIONSYSTEM_LIBRARY",
"IDE_TEST_DIR=\".\""
@@ -18,10 +14,6 @@ QtcLibrary {
Depends { name: "Aggregation" }
files: [
- "plugindetailsview.ui",
- "pluginerrorview.ui",
- "pluginview.qrc",
- "pluginview.ui",
"extensionsystem_global.h",
"invoker.cpp",
"invoker.h",
@@ -34,19 +26,23 @@ QtcLibrary {
"plugincollection.h",
"plugindetailsview.cpp",
"plugindetailsview.h",
+ "plugindetailsview.ui",
"pluginerroroverview.cpp",
"pluginerroroverview.h",
"pluginerroroverview.ui",
"pluginerrorview.cpp",
"pluginerrorview.h",
+ "pluginerrorview.ui",
"pluginmanager.cpp",
"pluginmanager.h",
"pluginmanager_p.h",
+ "pluginspec.cpp",
"pluginspec.h",
"pluginspec_p.h",
"pluginview.cpp",
"pluginview.h",
- "pluginspec.cpp",
+ "pluginview.qrc",
+ "pluginview.ui",
"images/error.png",
"images/notloaded.png",
"images/ok.png",
diff --git a/src/libs/extensionsystem/invoker.cpp b/src/libs/extensionsystem/invoker.cpp
index d805361fab..834a9e68bd 100644
--- a/src/libs/extensionsystem/invoker.cpp
+++ b/src/libs/extensionsystem/invoker.cpp
@@ -37,6 +37,7 @@ InvokerBase::InvokerBase()
useRet = false;
nag = true;
success = true;
+ connectionType = Qt::AutoConnection;
target = 0;
}
@@ -53,6 +54,11 @@ bool InvokerBase::wasSuccessful() const
return success;
}
+void InvokerBase::setConnectionType(Qt::ConnectionType c)
+{
+ connectionType = c;
+}
+
void InvokerBase::invoke(QObject *t, const char *slot)
{
target = t;
@@ -72,11 +78,11 @@ void InvokerBase::invoke(QObject *t, const char *slot)
return;
QMetaMethod method = target->metaObject()->method(idx);
if (useRet)
- success = method.invoke(target, ret,
+ success = method.invoke(target, connectionType, ret,
arg[0], arg[1], arg[2], arg[3], arg[4],
arg[5], arg[6], arg[7], arg[8], arg[9]);
else
- success = method.invoke(target,
+ success = method.invoke(target, connectionType,
arg[0], arg[1], arg[2], arg[3], arg[4],
arg[5], arg[6], arg[7], arg[8], arg[9]);
}
diff --git a/src/libs/extensionsystem/invoker.h b/src/libs/extensionsystem/invoker.h
index dea44e9b7d..5eaf194bb7 100644
--- a/src/libs/extensionsystem/invoker.h
+++ b/src/libs/extensionsystem/invoker.h
@@ -46,6 +46,7 @@ public:
~InvokerBase();
bool wasSuccessful() const;
+ void setConnectionType(Qt::ConnectionType connectionType);
template <class T> void addArgument(const T &t)
{
@@ -73,6 +74,7 @@ private:
int lastArg;
bool success;
bool useRet;
+ Qt::ConnectionType connectionType;
mutable bool nag;
};
diff --git a/src/libs/extensionsystem/optionsparser.cpp b/src/libs/extensionsystem/optionsparser.cpp
index e0cecc384e..3838d0fda7 100644
--- a/src/libs/extensionsystem/optionsparser.cpp
+++ b/src/libs/extensionsystem/optionsparser.cpp
@@ -72,8 +72,10 @@ bool OptionsParser::parse()
continue;
if (checkForProfilingOption())
continue;
+#ifdef WITH_TESTS
if (checkForTestOption())
continue;
+#endif
if (checkForAppOption())
continue;
if (checkForPluginOption())
@@ -103,10 +105,10 @@ bool OptionsParser::checkForTestOption()
if (m_currentArg != QLatin1String(TEST_OPTION))
return false;
if (nextToken(RequiredToken)) {
- if(m_currentArg == "all") {
- foreach(PluginSpec *spec, m_pmPrivate->pluginSpecs) {
- if (spec && !m_pmPrivate->testSpecs.contains(spec))
- m_pmPrivate->testSpecs.append(spec);
+ if (m_currentArg == QLatin1String("all")) {
+ foreach (PluginSpec *spec, m_pmPrivate->pluginSpecs) {
+ if (spec && !m_pmPrivate->containsTestSpec(spec))
+ m_pmPrivate->testSpecs.append(PluginManagerPrivate::TestSpec(spec));
}
} else {
PluginSpec *spec = m_pmPrivate->pluginByName(m_currentArg);
@@ -115,8 +117,20 @@ bool OptionsParser::checkForTestOption()
*m_errorString = QCoreApplication::translate("PluginManager",
"The plugin '%1' does not exist.").arg(m_currentArg);
m_hasError = true;
- } else if(!m_pmPrivate->testSpecs.contains(spec)) {
- m_pmPrivate->testSpecs.append(spec);
+ } else if (!m_pmPrivate->containsTestSpec(spec)) {
+ // Collect optional test functions. Everything following the plugin
+ // name until the next option is interpreted as a test function. E.g.
+ // in './qtcreator -test Git myFile' the argument 'myFile' will be
+ // be interpreted as an function name and not a file to open.
+ const QStringList::const_iterator current(m_it);
+ QStringList testFunctions;
+ while (nextToken() && !m_currentArg.startsWith(QLatin1Char('-')))
+ testFunctions.append(m_currentArg);
+ // Make sure a following nextToken() call will get the current/next option.
+ if (current != m_it && m_it != m_end)
+ --m_it;
+ m_pmPrivate->testSpecs.append(
+ PluginManagerPrivate::TestSpec(spec, testFunctions));
}
}
}
@@ -172,9 +186,8 @@ bool OptionsParser::checkForPluginOption()
if (!spec)
return false;
spec->addArgument(m_currentArg);
- if (requiresParameter && nextToken(RequiredToken)) {
+ if (requiresParameter && nextToken(RequiredToken))
spec->addArgument(m_currentArg);
- }
return true;
}
diff --git a/src/libs/extensionsystem/pluginerroroverview.cpp b/src/libs/extensionsystem/pluginerroroverview.cpp
index e27737d1dd..16bae32116 100644
--- a/src/libs/extensionsystem/pluginerroroverview.cpp
+++ b/src/libs/extensionsystem/pluginerroroverview.cpp
@@ -35,43 +35,12 @@
Q_DECLARE_METATYPE(ExtensionSystem::PluginSpec*)
namespace ExtensionSystem {
-namespace Internal {
-
-class PluginErrorOverviewPrivate : public QObject
-{
- Q_OBJECT
-public:
- PluginErrorOverviewPrivate(QDialog *dialog);
- ~PluginErrorOverviewPrivate();
-
-private slots:
- void showDetails(QListWidgetItem *item);
-
-private:
- Ui::PluginErrorOverview *m_ui;
-};
-
-} // Internal
-} // ExtensionSystem
-
-using namespace ExtensionSystem;
-using namespace ExtensionSystem::Internal;
PluginErrorOverview::PluginErrorOverview(QWidget *parent) :
QDialog(parent),
- d(new PluginErrorOverviewPrivate(this))
-{
-}
-
-PluginErrorOverview::~PluginErrorOverview()
+ m_ui(new Internal::Ui::PluginErrorOverview)
{
- delete d;
-}
-
-PluginErrorOverviewPrivate::PluginErrorOverviewPrivate(QDialog *dialog)
- : m_ui(new Ui::PluginErrorOverview)
-{
- m_ui->setupUi(dialog);
+ m_ui->setupUi(this);
m_ui->buttonBox->addButton(tr("Continue"), QDialogButtonBox::AcceptRole);
foreach (PluginSpec *spec, PluginManager::plugins()) {
@@ -90,12 +59,12 @@ PluginErrorOverviewPrivate::PluginErrorOverviewPrivate(QDialog *dialog)
m_ui->pluginList->setCurrentRow(0);
}
-PluginErrorOverviewPrivate::~PluginErrorOverviewPrivate()
+PluginErrorOverview::~PluginErrorOverview()
{
delete m_ui;
}
-void PluginErrorOverviewPrivate::showDetails(QListWidgetItem *item)
+void PluginErrorOverview::showDetails(QListWidgetItem *item)
{
if (item) {
PluginSpec *spec = item->data(Qt::UserRole).value<PluginSpec *>();
@@ -105,4 +74,4 @@ void PluginErrorOverviewPrivate::showDetails(QListWidgetItem *item)
}
}
-#include "pluginerroroverview.moc"
+} // namespace ExtensionSystem
diff --git a/src/libs/extensionsystem/pluginerroroverview.h b/src/libs/extensionsystem/pluginerroroverview.h
index f7da6208e4..6aa2ee7899 100644
--- a/src/libs/extensionsystem/pluginerroroverview.h
+++ b/src/libs/extensionsystem/pluginerroroverview.h
@@ -34,13 +34,15 @@
#include <QDialog>
-namespace ExtensionSystem {
+QT_BEGIN_NAMESPACE
+class QListWidgetItem;
+QT_END_NAMESPACE
-class PluginManager;
+namespace ExtensionSystem {
namespace Internal {
-class PluginErrorOverviewPrivate;
-}
+namespace Ui { class PluginErrorOverview; }
+} // namespace Internal
class EXTENSIONSYSTEM_EXPORT PluginErrorOverview : public QDialog
{
@@ -50,8 +52,11 @@ public:
explicit PluginErrorOverview(QWidget *parent = 0);
~PluginErrorOverview();
+private slots:
+ void showDetails(QListWidgetItem *item);
+
private:
- Internal::PluginErrorOverviewPrivate *d;
+ Internal::Ui::PluginErrorOverview *m_ui;
};
} // ExtensionSystem
diff --git a/src/libs/extensionsystem/pluginmanager.cpp b/src/libs/extensionsystem/pluginmanager.cpp
index de8c7b6153..caa9078e21 100644
--- a/src/libs/extensionsystem/pluginmanager.cpp
+++ b/src/libs/extensionsystem/pluginmanager.cpp
@@ -133,7 +133,7 @@ enum { debugLeaks = 0 };
invokable methods of the "provider" object in the object pool.
The \c{ExtensionSystem::invoke} function template encapsulates
- {ExtensionSystem::Invoker} construction for the common case where
+ {ExtensionSystem::Invoker} construction for the common case where
the success of the call is not checked.
\code
@@ -335,9 +335,8 @@ bool PluginManager::hasError()
{
foreach (PluginSpec *spec, plugins()) {
// only show errors on startup if plugin is enabled.
- if (spec->hasError() && spec->isEnabled() && !spec->isDisabledIndirectly()) {
+ if (spec->hasError() && spec->isEnabled() && !spec->isDisabledIndirectly())
return true;
- }
}
return false;
}
@@ -505,11 +504,10 @@ QString PluginManager::serializedArguments()
foreach (const QString &argument, m_instance->d->arguments) {
rc += separator;
const QFileInfo fi(argument);
- if (fi.exists() && fi.isRelative()) {
+ if (fi.exists() && fi.isRelative())
rc += fi.absoluteFilePath();
- } else {
+ else
rc += argument;
- }
}
}
return rc;
@@ -618,8 +616,11 @@ void PluginManager::formatOptions(QTextStream &str, int optionIndentation, int d
QString(), QLatin1String("Profile plugin loading"),
optionIndentation, descriptionIndentation);
#ifdef WITH_TESTS
- formatOption(str, QLatin1String(OptionsParser::TEST_OPTION),
- QLatin1String("plugin|all"), QLatin1String("Run plugin's tests"),
+ formatOption(str, QString::fromLatin1(OptionsParser::TEST_OPTION)
+ + QLatin1String(" <plugin> [testfunction[:testdata]]..."), QString(),
+ QLatin1String("Run plugin's tests"), optionIndentation, descriptionIndentation);
+ formatOption(str, QString::fromLatin1(OptionsParser::TEST_OPTION) + QLatin1String(" all"),
+ QString(), QLatin1String("Run tests from all plugins"),
optionIndentation, descriptionIndentation);
#endif
}
@@ -664,28 +665,67 @@ void PluginManager::formatPluginVersions(QTextStream &str)
void PluginManager::startTests()
{
#ifdef WITH_TESTS
- foreach (PluginSpec *pluginSpec, d->testSpecs) {
+ foreach (const PluginManagerPrivate::TestSpec &testSpec, d->testSpecs) {
+ const PluginSpec * const pluginSpec = testSpec.pluginSpec;
if (!pluginSpec->plugin())
continue;
- const QMetaObject *mo = pluginSpec->plugin()->metaObject();
- QStringList methods;
- methods.append("arg0");
- // We only want slots starting with "test"
- for (int i = mo->methodOffset(); i < mo->methodCount(); ++i) {
+
+ // Collect all test functions/methods of the plugin.
+ QStringList allTestFunctions;
+ const QMetaObject *metaObject = pluginSpec->plugin()->metaObject();
+
+ for (int i = metaObject->methodOffset(); i < metaObject->methodCount(); ++i) {
#if QT_VERSION >= 0x050000
- const QByteArray signature = mo->method(i).methodSignature();
+ const QByteArray signature = metaObject->method(i).methodSignature();
#else
- const QByteArray signature = mo->method(i).signature();
+ const QByteArray signature = metaObject->method(i).signature();
#endif
if (signature.startsWith("test") && !signature.endsWith("_data()")) {
const QString method = QString::fromLatin1(signature);
- methods.append(method.left(method.size()-2));
+ const QString methodName = method.left(method.size() - 2);
+ allTestFunctions.append(methodName);
+ }
+ }
+
+ QStringList testFunctionsToExecute;
+
+ // User did not specify any test functions, so add every test function.
+ if (testSpec.testFunctions.isEmpty()) {
+ testFunctionsToExecute = allTestFunctions;
+
+ // User specified test functions. Add them if they are valid.
+ } else {
+ foreach (const QString &userTestFunction, testSpec.testFunctions) {
+ // There might be a test data suffix like in "testfunction:testdata1".
+ QString testFunctionName = userTestFunction;
+ const int index = testFunctionName.indexOf(QLatin1Char(':'));
+ if (index != -1)
+ testFunctionName = testFunctionName.left(index);
+
+ if (allTestFunctions.contains(testFunctionName)) {
+ // If the specified test data is invalid, the QTest framework will
+ // print a reasonable error message for us.
+ testFunctionsToExecute.append(userTestFunction);
+ } else {
+ QTextStream out(stdout);
+ out << "Unknown test function \"" << testFunctionName
+ << "\" for plugin \"" << pluginSpec->name() << "\"." << endl
+ << " Available test functions for plugin \"" << pluginSpec->name()
+ << "\" are:" << endl;
+ foreach (const QString &testFunction, allTestFunctions)
+ out << " " << testFunction << endl;
+ }
}
}
+
+ // QTest::qExec() expects basically QCoreApplication::arguments(),
+ // so prepend a fake argument for the application name.
+ testFunctionsToExecute.prepend(QLatin1String("arg0"));
+
// Don't run QTest::qExec with only one argument, that'd run
// *all* slots as tests.
- if (methods.size() > 1)
- QTest::qExec(pluginSpec->plugin(), methods);
+ if (testFunctionsToExecute.size() > 1)
+ QTest::qExec(pluginSpec->plugin(), testFunctionsToExecute);
}
if (!d->testSpecs.isEmpty())
QTimer::singleShot(1, QCoreApplication::instance(), SLOT(quit()));
@@ -710,8 +750,8 @@ QString PluginManager::testDataDirectory()
QByteArray ba = qgetenv("QTCREATOR_TEST_DIR");
QString s = QString::fromLocal8Bit(ba.constData(), ba.size());
if (s.isEmpty()) {
- s = IDE_TEST_DIR;
- s.append("/tests");
+ s = QLatin1String(IDE_TEST_DIR);
+ s.append(QLatin1String("/tests"));
}
s = QDir::cleanPath(s);
return s;
@@ -840,7 +880,7 @@ void PluginManagerPrivate::writeSettings()
return;
QStringList tempDisabledPlugins;
QStringList tempForceEnabledPlugins;
- foreach(PluginSpec *spec, pluginSpecs) {
+ foreach (PluginSpec *spec, pluginSpecs) {
if (!spec->isDisabledByDefault() && !spec->isEnabled())
tempDisabledPlugins.append(spec->name());
if (spec->isDisabledByDefault() && spec->isEnabled())
@@ -857,9 +897,8 @@ void PluginManagerPrivate::writeSettings()
*/
void PluginManagerPrivate::readSettings()
{
- if (globalSettings) {
+ if (globalSettings)
defaultDisabledPlugins = globalSettings->value(QLatin1String(C_IGNORED_PLUGINS)).toStringList();
- }
if (settings) {
disabledPlugins = settings->value(QLatin1String(C_IGNORED_PLUGINS)).toStringList();
forceEnabledPlugins = settings->value(QLatin1String(C_FORCEENABLED_PLUGINS)).toStringList();
@@ -996,9 +1035,8 @@ void PluginManagerPrivate::shutdown()
shutdownEventLoop->exec();
}
deleteAll();
- if (!allObjects.isEmpty()) {
+ if (!allObjects.isEmpty())
qDebug() << "There are" << allObjects.size() << "objects left in the plugin manager pool: " << allObjects;
- }
}
/*!
@@ -1173,7 +1211,7 @@ void PluginManagerPrivate::readPluginPaths()
searchPaths << subdir.absoluteFilePath();
}
defaultCollection = new PluginCollection(QString());
- pluginCategories.insert("", defaultCollection);
+ pluginCategories.insert(QString(), defaultCollection);
foreach (const QString &specFile, specFiles) {
PluginSpec *spec = new PluginSpec;
@@ -1270,11 +1308,10 @@ void PluginManagerPrivate::profilingReport(const char *what, const PluginSpec *s
const int absoluteElapsedMS = m_profileTimer->elapsed();
const int elapsedMS = absoluteElapsedMS - m_profileElapsedMS;
m_profileElapsedMS = absoluteElapsedMS;
- if (spec) {
+ if (spec)
qDebug("%-22s %-22s %8dms (%8dms)", what, qPrintable(spec->name()), absoluteElapsedMS, elapsedMS);
- } else {
+ else
qDebug("%-45s %8dms (%8dms)", what, absoluteElapsedMS, elapsedMS);
- }
}
}
diff --git a/src/libs/extensionsystem/pluginmanager_p.h b/src/libs/extensionsystem/pluginmanager_p.h
index a70e834637..74296419ed 100644
--- a/src/libs/extensionsystem/pluginmanager_p.h
+++ b/src/libs/extensionsystem/pluginmanager_p.h
@@ -79,9 +79,26 @@ public:
void writeSettings();
void disablePluginIndirectly(PluginSpec *spec);
+ class TestSpec {
+ public:
+ TestSpec(PluginSpec *pluginSpec, const QStringList &testFunctions = QStringList())
+ : pluginSpec(pluginSpec), testFunctions(testFunctions) {}
+ PluginSpec *pluginSpec;
+ QStringList testFunctions;
+ };
+
+ bool containsTestSpec(PluginSpec *pluginSpec) const
+ {
+ foreach (const TestSpec &testSpec, testSpecs) {
+ if (testSpec.pluginSpec == pluginSpec)
+ return true;
+ }
+ return false;
+ }
+
QHash<QString, PluginCollection *> pluginCategories;
QList<PluginSpec *> pluginSpecs;
- QList<PluginSpec *> testSpecs;
+ QList<TestSpec> testSpecs;
QStringList pluginPaths;
QString extension;
QList<QObject *> allObjects; // ### make this a QList<QPointer<QObject> > > ?
diff --git a/src/libs/extensionsystem/pluginspec.cpp b/src/libs/extensionsystem/pluginspec.cpp
index 63a3266378..d6623e42c1 100644
--- a/src/libs/extensionsystem/pluginspec.cpp
+++ b/src/libs/extensionsystem/pluginspec.cpp
@@ -441,6 +441,7 @@ namespace {
const char PLUGIN_VERSION[] = "version";
const char PLUGIN_COMPATVERSION[] = "compatVersion";
const char PLUGIN_EXPERIMENTAL[] = "experimental";
+ const char PLUGIN_DISABLED_BY_DEFAULT[] = "disabledByDefault";
const char VENDOR[] = "vendor";
const char COPYRIGHT[] = "copyright";
const char LICENSE[] = "license";
@@ -492,10 +493,10 @@ bool PluginSpecPrivate::read(const QString &fileName)
= url
= category
= location
- = "";
+ = QString();
state = PluginSpec::Invalid;
hasError = false;
- errorString = "";
+ errorString.clear();
dependencies.clear();
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
@@ -558,7 +559,7 @@ static inline QString msgAttributeMissing(const char *elt, const char *attribute
static inline QString msgInvalidFormat(const char *content)
{
- return QCoreApplication::translate("PluginSpec", "'%1' has invalid format").arg(content);
+ return QCoreApplication::translate("PluginSpec", "'%1' has invalid format").arg(QLatin1String(content));
}
static inline QString msgInvalidElement(const QString &name)
@@ -583,16 +584,17 @@ static inline QString msgUnexpectedToken()
void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
{
QString element = reader.name().toString();
- if (element != QString(PLUGIN)) {
- reader.raiseError(QCoreApplication::translate("PluginSpec", "Expected element '%1' as top level element").arg(PLUGIN));
+ if (element != QLatin1String(PLUGIN)) {
+ reader.raiseError(QCoreApplication::translate("PluginSpec", "Expected element '%1' as top level element")
+ .arg(QLatin1String(PLUGIN)));
return;
}
- name = reader.attributes().value(PLUGIN_NAME).toString();
+ name = reader.attributes().value(QLatin1String(PLUGIN_NAME)).toString();
if (name.isEmpty()) {
reader.raiseError(msgAttributeMissing(PLUGIN, PLUGIN_NAME));
return;
}
- version = reader.attributes().value(PLUGIN_VERSION).toString();
+ version = reader.attributes().value(QLatin1String(PLUGIN_VERSION)).toString();
if (version.isEmpty()) {
reader.raiseError(msgAttributeMissing(PLUGIN, PLUGIN_VERSION));
return;
@@ -601,42 +603,40 @@ void PluginSpecPrivate::readPluginSpec(QXmlStreamReader &reader)
reader.raiseError(msgInvalidFormat(PLUGIN_VERSION));
return;
}
- compatVersion = reader.attributes().value(PLUGIN_COMPATVERSION).toString();
+ compatVersion = reader.attributes().value(QLatin1String(PLUGIN_COMPATVERSION)).toString();
if (!compatVersion.isEmpty() && !isValidVersion(compatVersion)) {
reader.raiseError(msgInvalidFormat(PLUGIN_COMPATVERSION));
return;
} else if (compatVersion.isEmpty()) {
compatVersion = version;
}
- QString experimentalString = reader.attributes().value(PLUGIN_EXPERIMENTAL).toString();
- experimental = (experimentalString.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0);
- if (!experimentalString.isEmpty() && !experimental
- && experimentalString.compare(QLatin1String("false"), Qt::CaseInsensitive) != 0) {
- reader.raiseError(msgInvalidFormat(PLUGIN_EXPERIMENTAL));
+ disabledByDefault = readBooleanValue(reader, PLUGIN_DISABLED_BY_DEFAULT);
+ experimental = readBooleanValue(reader, PLUGIN_EXPERIMENTAL);
+ if (reader.hasError())
return;
- }
- disabledByDefault = experimental;
- enabled = !experimental;
+ if (experimental)
+ disabledByDefault = true;
+ enabled = !disabledByDefault;
while (!reader.atEnd()) {
reader.readNext();
switch (reader.tokenType()) {
case QXmlStreamReader::StartElement:
element = reader.name().toString();
- if (element == VENDOR)
+ if (element == QLatin1String(VENDOR))
vendor = reader.readElementText().trimmed();
- else if (element == COPYRIGHT)
+ else if (element == QLatin1String(COPYRIGHT))
copyright = reader.readElementText().trimmed();
- else if (element == LICENSE)
+ else if (element == QLatin1String(LICENSE))
license = reader.readElementText().trimmed();
- else if (element == DESCRIPTION)
+ else if (element == QLatin1String(DESCRIPTION))
description = reader.readElementText().trimmed();
- else if (element == URL)
+ else if (element == QLatin1String(URL))
url = reader.readElementText().trimmed();
- else if (element == CATEGORY)
+ else if (element == QLatin1String(CATEGORY))
category = reader.readElementText().trimmed();
- else if (element == DEPENDENCYLIST)
+ else if (element == QLatin1String(DEPENDENCYLIST))
readDependencies(reader);
- else if (element == ARGUMENTLIST)
+ else if (element == QLatin1String(ARGUMENTLIST))
readArgumentDescriptions(reader);
else
reader.raiseError(msgInvalidElement(name));
@@ -666,18 +666,17 @@ void PluginSpecPrivate::readArgumentDescriptions(QXmlStreamReader &reader)
switch (reader.tokenType()) {
case QXmlStreamReader::StartElement:
element = reader.name().toString();
- if (element == ARGUMENT) {
+ if (element == QLatin1String(ARGUMENT))
readArgumentDescription(reader);
- } else {
+ else
reader.raiseError(msgInvalidElement(name));
- }
break;
case QXmlStreamReader::Comment:
case QXmlStreamReader::Characters:
break;
case QXmlStreamReader::EndElement:
element = reader.name().toString();
- if (element == ARGUMENTLIST)
+ if (element == QLatin1String(ARGUMENTLIST))
return;
reader.raiseError(msgUnexpectedClosing(element));
break;
@@ -695,18 +694,29 @@ void PluginSpecPrivate::readArgumentDescriptions(QXmlStreamReader &reader)
void PluginSpecPrivate::readArgumentDescription(QXmlStreamReader &reader)
{
PluginArgumentDescription arg;
- arg.name = reader.attributes().value(ARGUMENT_NAME).toString();
+ arg.name = reader.attributes().value(QLatin1String(ARGUMENT_NAME)).toString();
if (arg.name.isEmpty()) {
reader.raiseError(msgAttributeMissing(ARGUMENT, ARGUMENT_NAME));
return;
}
- arg.parameter = reader.attributes().value(ARGUMENT_PARAMETER).toString();
+ arg.parameter = reader.attributes().value(QLatin1String(ARGUMENT_PARAMETER)).toString();
arg.description = reader.readElementText();
if (reader.tokenType() != QXmlStreamReader::EndElement)
reader.raiseError(msgUnexpectedToken());
argumentDescriptions.push_back(arg);
}
+bool PluginSpecPrivate::readBooleanValue(QXmlStreamReader &reader, const char *key)
+{
+ const QString valueString = reader.attributes().value(QLatin1String(key)).toString();
+ const bool isOn = valueString.compare(QLatin1String("true"), Qt::CaseInsensitive) == 0;
+ if (!valueString.isEmpty() && !isOn
+ && valueString.compare(QLatin1String("false"), Qt::CaseInsensitive) != 0) {
+ reader.raiseError(msgInvalidFormat(key));
+ }
+ return isOn;
+}
+
/*!
\fn void PluginSpecPrivate::readDependencies(QXmlStreamReader &reader)
\internal
@@ -719,18 +729,17 @@ void PluginSpecPrivate::readDependencies(QXmlStreamReader &reader)
switch (reader.tokenType()) {
case QXmlStreamReader::StartElement:
element = reader.name().toString();
- if (element == DEPENDENCY) {
+ if (element == QLatin1String(DEPENDENCY))
readDependencyEntry(reader);
- } else {
+ else
reader.raiseError(msgInvalidElement(name));
- }
break;
case QXmlStreamReader::Comment:
case QXmlStreamReader::Characters:
break;
case QXmlStreamReader::EndElement:
element = reader.name().toString();
- if (element == DEPENDENCYLIST)
+ if (element == QLatin1String(DEPENDENCYLIST))
return;
reader.raiseError(msgUnexpectedClosing(element));
break;
@@ -748,19 +757,19 @@ void PluginSpecPrivate::readDependencies(QXmlStreamReader &reader)
void PluginSpecPrivate::readDependencyEntry(QXmlStreamReader &reader)
{
PluginDependency dep;
- dep.name = reader.attributes().value(DEPENDENCY_NAME).toString();
+ dep.name = reader.attributes().value(QLatin1String(DEPENDENCY_NAME)).toString();
if (dep.name.isEmpty()) {
reader.raiseError(msgAttributeMissing(DEPENDENCY, DEPENDENCY_NAME));
return;
}
- dep.version = reader.attributes().value(DEPENDENCY_VERSION).toString();
+ dep.version = reader.attributes().value(QLatin1String(DEPENDENCY_VERSION)).toString();
if (!dep.version.isEmpty() && !isValidVersion(dep.version)) {
reader.raiseError(msgInvalidFormat(DEPENDENCY_VERSION));
return;
}
dep.type = PluginDependency::Required;
- if (reader.attributes().hasAttribute(DEPENDENCY_TYPE)) {
- QString typeValue = reader.attributes().value(DEPENDENCY_TYPE).toString();
+ if (reader.attributes().hasAttribute(QLatin1String(DEPENDENCY_TYPE))) {
+ QString typeValue = reader.attributes().value(QLatin1String(DEPENDENCY_TYPE)).toString();
if (typeValue == QLatin1String(DEPENDENCY_TYPE_HARD)) {
dep.type = PluginDependency::Required;
} else if (typeValue == QLatin1String(DEPENDENCY_TYPE_SOFT)) {
@@ -793,7 +802,7 @@ bool PluginSpecPrivate::provides(const QString &pluginName, const QString &plugi
*/
QRegExp &PluginSpecPrivate::versionRegExp()
{
- static QRegExp reg("([0-9]+)(?:[.]([0-9]+))?(?:[.]([0-9]+))?(?:_([0-9]+))?");
+ static QRegExp reg(QLatin1String("([0-9]+)(?:[.]([0-9]+))?(?:[.]([0-9]+))?(?:_([0-9]+))?"));
return reg;
}
/*!
@@ -916,21 +925,21 @@ bool PluginSpecPrivate::loadLibrary()
#ifdef QT_NO_DEBUG
#ifdef Q_OS_WIN
- QString libName = QString("%1/%2.dll").arg(location).arg(name);
+ QString libName = QString::fromLatin1("%1/%2.dll").arg(location).arg(name);
#elif defined(Q_OS_MAC)
- QString libName = QString("%1/lib%2.dylib").arg(location).arg(name);
+ QString libName = QString::fromLatin1("%1/lib%2.dylib").arg(location).arg(name);
#else
- QString libName = QString("%1/lib%2.so").arg(location).arg(name);
+ QString libName = QString::fromLatin1("%1/lib%2.so").arg(location).arg(name);
#endif
#else //Q_NO_DEBUG
#ifdef Q_OS_WIN
- QString libName = QString("%1/%2d.dll").arg(location).arg(name);
+ QString libName = QString::fromLatin1("%1/%2d.dll").arg(location).arg(name);
#elif defined(Q_OS_MAC)
- QString libName = QString("%1/lib%2_debug.dylib").arg(location).arg(name);
+ QString libName = QString::fromLatin1("%1/lib%2_debug.dylib").arg(location).arg(name);
#else
- QString libName = QString("%1/lib%2.so").arg(location).arg(name);
+ QString libName = QString::fromLatin1("%1/lib%2.so").arg(location).arg(name);
#endif
#endif
@@ -1018,9 +1027,8 @@ bool PluginSpecPrivate::delayedInitialize()
{
if (hasError)
return false;
- if (state != PluginSpec::Running) {
+ if (state != PluginSpec::Running)
return false;
- }
if (!plugin) {
errorString = QCoreApplication::translate("PluginSpec", "Internal error: have no plugin instance to perform delayedInitialize");
hasError = true;
diff --git a/src/libs/extensionsystem/pluginspec_p.h b/src/libs/extensionsystem/pluginspec_p.h
index 519a366369..1be74b1ef0 100644
--- a/src/libs/extensionsystem/pluginspec_p.h
+++ b/src/libs/extensionsystem/pluginspec_p.h
@@ -103,6 +103,7 @@ private:
void readDependencyEntry(QXmlStreamReader &reader);
void readArgumentDescriptions(QXmlStreamReader &reader);
void readArgumentDescription(QXmlStreamReader &reader);
+ bool readBooleanValue(QXmlStreamReader &reader, const char *key);
static QRegExp &versionRegExp();
};
diff --git a/src/libs/extensionsystem/pluginview.cpp b/src/libs/extensionsystem/pluginview.cpp
index c47348ae18..edfe4ae94f 100644
--- a/src/libs/extensionsystem/pluginview.cpp
+++ b/src/libs/extensionsystem/pluginview.cpp
@@ -92,8 +92,8 @@ PluginView::PluginView(QWidget *parent)
m_ui->categoryWidget->setColumnWidth(C_LOAD, 40);
// cannot disable these
- m_whitelist << QString("Core") << QString("Locator")
- << QString("Find") << QString("TextEditor");
+ m_whitelist << QString::fromLatin1("Core") << QString::fromLatin1("Locator")
+ << QString::fromLatin1("Find") << QString::fromLatin1("TextEditor");
connect(PluginManager::instance(), SIGNAL(pluginsChanged()), this, SLOT(updateList()));
connect(m_ui->categoryWidget, SIGNAL(currentItemChanged(QTreeWidgetItem*,QTreeWidgetItem*)),
diff --git a/src/libs/glsl/glsl.g b/src/libs/glsl/glsl.g
index 137465416d..3c7632ee03 100644
--- a/src/libs/glsl/glsl.g
+++ b/src/libs/glsl/glsl.g
@@ -580,7 +580,7 @@ AST *Parser::parse(int startToken)
QString message = QLatin1String("Syntax error");
if (yytoken != -1) {
const QLatin1String s(spell[yytoken]);
- message = QString("Unexpected token `%1'").arg(s);
+ message = QString::fromLatin1("Unexpected token `%1'").arg(s);
}
for (; _tos; --_tos) {
@@ -600,7 +600,7 @@ AST *Parser::parse(int startToken)
if (next > 0) {
if (! yyrecovering && ! _recovered) {
_recovered = true;
- error(line, QString("Expected `%1'").arg(QLatin1String(spell[*tptr])));
+ error(line, QString::fromLatin1("Expected `%1'").arg(QLatin1String(spell[*tptr])));
}
yyrecovering = 3;
diff --git a/src/libs/glsl/glsl.pro b/src/libs/glsl/glsl.pro
index 14dc79d67c..2268ab55f7 100644
--- a/src/libs/glsl/glsl.pro
+++ b/src/libs/glsl/glsl.pro
@@ -1,6 +1,8 @@
TEMPLATE = lib
TARGET = GLSL
-DEFINES += GLSL_BUILD_LIB QT_CREATOR
+DEFINES += \
+ GLSL_BUILD_LIB \
+ QT_CREATOR
include(../../qtcreatorlibrary.pri)
include(glsl-lib.pri)
diff --git a/src/libs/glsl/glsl.qbs b/src/libs/glsl/glsl.qbs
index 7ee3557673..fc5c0ab7f5 100644
--- a/src/libs/glsl/glsl.qbs
+++ b/src/libs/glsl/glsl.qbs
@@ -4,10 +4,6 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "GLSL"
- cpp.includePaths: [
- ".",
- ".."
- ]
cpp.defines: base.concat([
"QT_CREATOR",
"GLSL_BUILD_LIB"
@@ -17,40 +13,34 @@ QtcLibrary {
Depends { name: "Qt.gui" }
files: [
+ "glsl.g",
"glsl.h",
- "glsllexer.h",
- "glslparser.h",
- "glslparsertable_p.h",
+ "glslast.cpp",
"glslast.h",
+ "glslastdump.cpp",
+ "glslastdump.h",
+ "glslastvisitor.cpp",
"glslastvisitor.h",
+ "glslengine.cpp",
"glslengine.h",
- "glslmemorypool.h",
- "glslastdump.h",
- "glslsemantic.h",
- "glsltype.h",
- "glsltypes.h",
- "glslsymbol.h",
- "glslsymbols.h",
"glslkeywords.cpp",
- "glslparser.cpp",
- "glslparsertable.cpp",
"glsllexer.cpp",
- "glslast.cpp",
- "glslastvisitor.cpp",
- "glslengine.cpp",
+ "glsllexer.h",
"glslmemorypool.cpp",
- "glslastdump.cpp",
+ "glslmemorypool.h",
+ "glslparser.cpp",
+ "glslparser.h",
+ "glslparsertable.cpp",
+ "glslparsertable_p.h",
"glslsemantic.cpp",
- "glsltype.cpp",
- "glsltypes.cpp",
+ "glslsemantic.h",
"glslsymbol.cpp",
+ "glslsymbol.h",
"glslsymbols.cpp",
- "glsl.g"
+ "glslsymbols.h",
+ "glsltype.cpp",
+ "glsltype.h",
+ "glsltypes.cpp",
+ "glsltypes.h",
]
-
- ProductModule {
- Depends { name: "cpp" }
- cpp.includePaths: ["."]
- }
}
-
diff --git a/src/libs/glsl/glslparser.cpp b/src/libs/glsl/glslparser.cpp
index cca1ecc96f..4d5fd6efcb 100644
--- a/src/libs/glsl/glslparser.cpp
+++ b/src/libs/glsl/glslparser.cpp
@@ -162,7 +162,7 @@ AST *Parser::parse(int startToken)
QString message = QLatin1String("Syntax error");
if (yytoken != -1) {
const QLatin1String s(spell[yytoken]);
- message = QString("Unexpected token `%1'").arg(s);
+ message = QString::fromLatin1("Unexpected token `%1'").arg(s);
}
for (; _tos; --_tos) {
@@ -182,7 +182,7 @@ AST *Parser::parse(int startToken)
if (next > 0) {
if (! yyrecovering && ! _recovered) {
_recovered = true;
- error(line, QString("Expected `%1'").arg(QLatin1String(spell[*tptr])));
+ error(line, QString::fromLatin1("Expected `%1'").arg(QLatin1String(spell[*tptr])));
}
yyrecovering = 3;
diff --git a/src/libs/glsl/glslsemantic.cpp b/src/libs/glsl/glslsemantic.cpp
index 9ee66bbe20..a1523be479 100644
--- a/src/libs/glsl/glslsemantic.cpp
+++ b/src/libs/glsl/glslsemantic.cpp
@@ -125,9 +125,9 @@ Semantic::ExprResult Semantic::functionIdentifier(FunctionIdentifierAST *ast)
if (s->asOverloadSet() != 0 || s->asFunction() != 0)
result.type = s->type();
else
- _engine->error(ast->lineno, QString("`%1' cannot be used as a function").arg(*ast->name));
+ _engine->error(ast->lineno, QString::fromLatin1("`%1' cannot be used as a function").arg(*ast->name));
} else {
- _engine->error(ast->lineno, QString("`%1' was not declared in this scope").arg(*ast->name));
+ _engine->error(ast->lineno, QString::fromLatin1("`%1' was not declared in this scope").arg(*ast->name));
}
} else if (ast->type) {
const Type *ty = type(ast->type);
@@ -184,11 +184,10 @@ bool Semantic::visit(StructTypeAST::Field *ast)
bool Semantic::visit(IdentifierExpressionAST *ast)
{
if (ast->name) {
- if (Symbol *s = _scope->lookup(*ast->name)) {
+ if (Symbol *s = _scope->lookup(*ast->name))
_expr.type = s->type();
- } else {
- _engine->error(ast->lineno, QString("`%1' was not declared in this scope").arg(*ast->name));
- }
+ else
+ _engine->error(ast->lineno, QString::fromLatin1("`%1' was not declared in this scope").arg(*ast->name));
}
return false;
}
@@ -225,7 +224,7 @@ bool Semantic::visit(BinaryExpressionAST *ast)
if (const IndexType *idxType = left.type->asIndexType())
_expr = idxType->indexElementType();
else
- _engine->error(ast->lineno, QString("Invalid type `%1' for array subscript").arg(left.type->toString()));
+ _engine->error(ast->lineno, QString::fromLatin1("Invalid type `%1' for array subscript").arg(left.type->toString()));
}
break;
@@ -291,19 +290,17 @@ bool Semantic::visit(MemberAccessExpressionAST *ast)
ExprResult expr = expression(ast->expr);
if (expr.type && ast->field) {
if (const VectorType *vecTy = expr.type->asVectorType()) {
- if (Symbol *s = vecTy->find(*ast->field)) {
+ if (Symbol *s = vecTy->find(*ast->field))
_expr.type = s->type();
- } else {
- _engine->error(ast->lineno, QString("`%1' has no member named `%2'").arg(vecTy->name()).arg(*ast->field));
- }
+ else
+ _engine->error(ast->lineno, QString::fromLatin1("`%1' has no member named `%2'").arg(vecTy->name()).arg(*ast->field));
} else if (const Struct *structTy = expr.type->asStructType()) {
- if (Symbol *s = structTy->find(*ast->field)) {
+ if (Symbol *s = structTy->find(*ast->field))
_expr.type = s->type();
- } else {
- _engine->error(ast->lineno, QString("`%1' has no member named `%2'").arg(structTy->name()).arg(*ast->field));
- }
+ else
+ _engine->error(ast->lineno, QString::fromLatin1("`%1' has no member named `%2'").arg(structTy->name()).arg(*ast->field));
} else {
- _engine->error(ast->lineno, QString("Requested for member `%1', in a non class or vec instance").arg(*ast->field));
+ _engine->error(ast->lineno, QString::fromLatin1("Requested for member `%1', in a non class or vec instance").arg(*ast->field));
}
}
return false;
@@ -375,9 +372,9 @@ bool Semantic::visit(FunctionCallExpressionAST *ast)
if (id.isValid()) {
if (const Function *funTy = id.type->asFunctionType()) {
if (actuals.size() < funTy->argumentCount())
- _engine->error(ast->lineno, QString("not enough arguments"));
+ _engine->error(ast->lineno, QString::fromLatin1("not enough arguments"));
else if (actuals.size() > funTy->argumentCount())
- _engine->error(ast->lineno, QString("too many arguments"));
+ _engine->error(ast->lineno, QString::fromLatin1("too many arguments"));
_expr.type = funTy->returnType();
} else if (const OverloadSet *overloads = id.type->asOverloadSetType()) {
QVector<GLSL::Function *> candidates;
@@ -733,7 +730,7 @@ bool Semantic::visit(BasicTypeAST *ast)
break;
default:
- _engine->error(ast->lineno, QString("Unknown type `%1'").arg(QLatin1String(GLSLParserTable::spell[ast->token])));
+ _engine->error(ast->lineno, QString::fromLatin1("Unknown type `%1'").arg(QLatin1String(GLSLParserTable::spell[ast->token])));
}
return false;
@@ -748,7 +745,7 @@ bool Semantic::visit(NamedTypeAST *ast)
return false;
}
}
- _engine->error(ast->lineno, QString("Undefined type `%1'").arg(*ast->name));
+ _engine->error(ast->lineno, QString::fromLatin1("Undefined type `%1'").arg(*ast->name));
}
return false;
diff --git a/src/libs/glsl/glsltypes.cpp b/src/libs/glsl/glsltypes.cpp
index e89d2099ba..f23f3f14c1 100644
--- a/src/libs/glsl/glsltypes.cpp
+++ b/src/libs/glsl/glsltypes.cpp
@@ -150,7 +150,7 @@ QString VectorType::toString() const
prefix = "u";
else if (elementType()->asDoubleType() != 0)
prefix = "d";
- return QString("%1vec%2").arg(QLatin1String(prefix)).arg(_dimension);
+ return QString::fromLatin1("%1vec%2").arg(QLatin1String(prefix)).arg(_dimension);
}
void VectorType::add(Symbol *symbol)
@@ -274,7 +274,7 @@ QString MatrixType::toString() const
prefix = "u";
else if (elementType()->asDoubleType() != 0)
prefix = "d";
- return QString("%1mat%2x%3").arg(QLatin1String(prefix)).arg(_columns).arg(_rows);
+ return QString::fromLatin1("%1mat%2x%3").arg(QLatin1String(prefix)).arg(_columns).arg(_rows);
}
bool MatrixType::isEqualTo(const Type *other) const
diff --git a/src/libs/languageutils/componentversion.cpp b/src/libs/languageutils/componentversion.cpp
index 080ff003ac..b043802a00 100644
--- a/src/libs/languageutils/componentversion.cpp
+++ b/src/libs/languageutils/componentversion.cpp
@@ -76,7 +76,7 @@ bool ComponentVersion::isValid() const
QString ComponentVersion::toString() const
{
- return QString("%1.%2").arg(QString::number(_major),
+ return QString::fromLatin1("%1.%2").arg(QString::number(_major),
QString::number(_minor));
}
diff --git a/src/libs/languageutils/languageutils.qbs b/src/libs/languageutils/languageutils.qbs
index abd23f95c8..811c4a9609 100644
--- a/src/libs/languageutils/languageutils.qbs
+++ b/src/libs/languageutils/languageutils.qbs
@@ -4,11 +4,7 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "LanguageUtils"
- cpp.includePaths: [
- ".",
- "..",
- "../3rdparty/cplusplus"
- ]
+ cpp.includePaths: base.concat("../3rdparty/cplusplus")
cpp.defines: base.concat([
"QT_CREATOR",
"LANGUAGEUTILS_BUILD_DIR"
@@ -19,11 +15,11 @@ QtcLibrary {
Depends { name: "Qt.core" }
files: [
- "languageutils_global.h",
- "fakemetaobject.h",
+ "componentversion.cpp",
"componentversion.h",
"fakemetaobject.cpp",
- "componentversion.cpp"
+ "fakemetaobject.h",
+ "languageutils_global.h",
]
}
diff --git a/src/libs/qmldebug/declarativetoolsclient.cpp b/src/libs/qmldebug/declarativetoolsclient.cpp
index e0cc197891..ba540eeb6b 100644
--- a/src/libs/qmldebug/declarativetoolsclient.cpp
+++ b/src/libs/qmldebug/declarativetoolsclient.cpp
@@ -83,12 +83,12 @@ public:
static inline QString toString(Message message)
{
- return staticMetaObject.enumerator(0).valueToKey(message);
+ return QString::fromUtf8(staticMetaObject.enumerator(0).valueToKey(message));
}
static inline QString toString(Tool tool)
{
- return staticMetaObject.enumerator(1).valueToKey(tool);
+ return QString::fromUtf8(staticMetaObject.enumerator(1).valueToKey(tool));
}
};
@@ -153,7 +153,7 @@ void DeclarativeToolsClient::messageReceived(const QByteArray &message)
int objectCount;
ds >> objectCount;
- log(LogReceive, type, QString("%1 [list of debug ids]").arg(objectCount));
+ log(LogReceive, type, QString::fromLatin1("%1 [list of debug ids]").arg(objectCount));
m_currentDebugIds.clear();
@@ -173,13 +173,12 @@ void DeclarativeToolsClient::messageReceived(const QByteArray &message)
log(LogReceive, type, QString::number(toolId));
- if (toolId == Constants::ZoomMode) {
+ if (toolId == Constants::ZoomMode)
emit zoomToolActivated();
- } else if (toolId == Constants::SelectionToolMode) {
+ else if (toolId == Constants::SelectionToolMode)
emit selectToolActivated();
- } else if (toolId == Constants::MarqueeSelectionToolMode) {
+ else if (toolId == Constants::MarqueeSelectionToolMode)
emit selectMarqueeToolActivated();
- }
break;
}
case InspectorProtocol::AnimationSpeedChanged: {
@@ -255,7 +254,7 @@ void DeclarativeToolsClient::setCurrentObjects(const QList<int> &debugIds)
ds << id;
}
- log(LogSend, cmd, QString("%1 [list of ids]").arg(debugIds.length()));
+ log(LogSend, cmd, QString::fromLatin1("%1 [list of ids]").arg(debugIds.length()));
sendMessage(message);
}
@@ -283,7 +282,7 @@ void DeclarativeToolsClient::setObjectIdList(
}
log(LogSend, cmd,
- QString("%1 %2 [list of debug / object ids]").arg(debugIds.length()));
+ QString::fromLatin1("%1 %2 [list of debug / object ids]").arg(debugIds.length()));
sendMessage(message);
}
@@ -464,9 +463,9 @@ void DeclarativeToolsClient::createQmlObject(const QString &qmlText,
<< filename
<< order;
- log(LogSend, cmd, QString("%1 %2 [%3] %4").arg(qmlText,
+ log(LogSend, cmd, QString::fromLatin1("%1 %2 [%3] %4").arg(qmlText,
QString::number(parentDebugId),
- imports.join(","), filename));
+ imports.join(QLatin1String(",")), filename));
sendMessage(message);
}
@@ -498,7 +497,7 @@ void DeclarativeToolsClient::reparentQmlObject(int debugId, int newParent)
<< debugId
<< newParent;
- log(LogSend, cmd, QString("%1 %2").arg(QString::number(debugId),
+ log(LogSend, cmd, QString::fromLatin1("%1 %2").arg(QString::number(debugId),
QString::number(newParent)));
sendMessage(message);
diff --git a/src/libs/qmldebug/qmldebug.qbs b/src/libs/qmldebug/qmldebug.qbs
index c2e8a40996..beba356937 100644
--- a/src/libs/qmldebug/qmldebug.qbs
+++ b/src/libs/qmldebug/qmldebug.qbs
@@ -4,13 +4,7 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "QmlDebug"
- cpp.includePaths: [
- ".",
- ".."
- ]
- cpp.defines: base.concat([
- "QMLDEBUG_LIB"
- ])
+ cpp.defines: base.concat("QMLDEBUG_LIB")
Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["gui", "network"] }
@@ -27,28 +21,23 @@ QtcLibrary {
"declarativetoolsclient.h",
"qdebugmessageclient.cpp",
"qdebugmessageclient.h",
+ "qmldebug_global.h",
"qmldebugclient.cpp",
"qmldebugclient.h",
"qmldebugconstants.h",
- "qmldebug_global.h",
+ "qmlenginedebugclient.h",
"qmloutputparser.cpp",
"qmloutputparser.h",
"qmlprofilereventlocation.h",
"qmlprofilereventtypes.h",
"qmlprofilertraceclient.cpp",
"qmlprofilertraceclient.h",
+ "qmltoolsclient.cpp",
+ "qmltoolsclient.h",
"qpacketprotocol.cpp",
"qpacketprotocol.h",
- "qmlenginedebugclient.h",
"qv8profilerclient.cpp",
"qv8profilerclient.h",
- "qmltoolsclient.cpp",
- "qmltoolsclient.h"
]
-
- ProductModule {
- Depends { name: "cpp" }
- cpp.includePaths: ["."]
- }
}
diff --git a/src/libs/qmldebug/qmldebugclient.cpp b/src/libs/qmldebug/qmldebugclient.cpp
index de4748b83d..5fc4f6c50f 100644
--- a/src/libs/qmldebug/qmldebugclient.cpp
+++ b/src/libs/qmldebug/qmldebugclient.cpp
@@ -203,11 +203,10 @@ void QmlDebugConnectionPrivate::readyRead()
QHash<QString, QmlDebugClient *>::Iterator iter =
plugins.find(name);
- if (iter == plugins.end()) {
+ if (iter == plugins.end())
qWarning() << "QML Debug Client: Message received for missing plugin" << name;
- } else {
+ else
(*iter)->messageReceived(message);
- }
}
}
}
diff --git a/src/libs/qmldebug/qmlprofilertraceclient.cpp b/src/libs/qmldebug/qmlprofilertraceclient.cpp
index 412c7d59e9..157c8ac4f6 100644
--- a/src/libs/qmldebug/qmlprofilertraceclient.cpp
+++ b/src/libs/qmldebug/qmlprofilertraceclient.cpp
@@ -118,9 +118,8 @@ void QmlProfilerTraceClient::setRecording(bool v)
d->recording = v;
- if (status() == Enabled) {
+ if (status() == Enabled)
sendRecordingStatus();
- }
emit recordingChanged(v);
}
@@ -225,9 +224,8 @@ void QmlProfilerTraceClient::messageReceived(const QByteArray &data)
if (!stream.atEnd())
stream >> column;
- if (d->rangeCount[range] > 0) {
+ if (d->rangeCount[range] > 0)
d->rangeLocations[range].push(QmlEventLocation(fileName, line, column));
- }
} else {
if (d->rangeCount[range] > 0) {
--d->rangeCount[range];
diff --git a/src/libs/qmldebug/qmltoolsclient.cpp b/src/libs/qmldebug/qmltoolsclient.cpp
index 7c40ace7c8..7c19e05655 100644
--- a/src/libs/qmldebug/qmltoolsclient.cpp
+++ b/src/libs/qmldebug/qmltoolsclient.cpp
@@ -112,7 +112,7 @@ void QmlToolsClient::messageReceived(const QByteArray &message)
}
}
log(LogReceive, type + ':' + event,
- QString("[%1]").arg(debugIdStrings.join(QLatin1String(","))));
+ QString::fromLatin1("[%1]").arg(debugIdStrings.join(QLatin1String(","))));
emit currentObjectsChanged(m_currentDebugIds);
}
} else {
@@ -140,7 +140,7 @@ void QmlToolsClient::setCurrentObjects(const QList<int> &debugIds)
ds << QByteArray(REQUEST) << m_requestId++
<< QByteArray(SELECT) << m_currentDebugIds;
- log(LogSend, SELECT, QString("%1 [list of ids]").arg(debugIds.length()));
+ log(LogSend, SELECT, QString::fromLatin1("%1 [list of ids]").arg(debugIds.length()));
sendMessage(message);
}
@@ -275,9 +275,9 @@ void QmlToolsClient::createQmlObject(const QString &qmlText,
<< filename
<< order;
- log(LogSend, CREATE_OBJECT, QString("%1 %2 [%3] %4").arg(qmlText,
+ log(LogSend, CREATE_OBJECT, QString::fromLatin1("%1 %2 [%3] %4").arg(qmlText,
QString::number(parentDebugId),
- imports.join(","), filename));
+ imports.join(QLatin1String(",")), filename));
sendMessage(message);
}
@@ -306,7 +306,7 @@ void QmlToolsClient::reparentQmlObject(int debugId, int newParent)
ds << QByteArray(REQUEST) << m_requestId++
<< QByteArray(MOVE_OBJECT) << debugId << newParent;
- log(LogSend, MOVE_OBJECT, QString("%1 %2").arg(QString::number(debugId),
+ log(LogSend, MOVE_OBJECT, QString::fromLatin1("%1 %2").arg(QString::number(debugId),
QString::number(newParent)));
sendMessage(message);
@@ -339,7 +339,7 @@ void QmlToolsClient::log(LogDirection direction,
else
msg += QLatin1String("receiving ");
- msg += message;
+ msg += QLatin1String(message);
msg += QLatin1Char(' ');
msg += extra;
emit logActivity(name(), msg);
diff --git a/src/libs/qmldebug/qpacketprotocol.cpp b/src/libs/qmldebug/qpacketprotocol.cpp
index 258d0edb16..57675e4ca3 100644
--- a/src/libs/qmldebug/qpacketprotocol.cpp
+++ b/src/libs/qmldebug/qpacketprotocol.cpp
@@ -226,7 +226,7 @@ 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.
diff --git a/src/libs/qmldebug/qv8profilerclient.cpp b/src/libs/qmldebug/qv8profilerclient.cpp
index d8aaad52cf..f93335c4fe 100644
--- a/src/libs/qmldebug/qv8profilerclient.cpp
+++ b/src/libs/qmldebug/qv8profilerclient.cpp
@@ -57,11 +57,10 @@ void QV8ProfilerClientPrivate::sendRecordingStatus()
QByteArray option("");
QByteArray title("");
- if (recording) {
+ if (recording)
option = "start";
- } else {
+ else
option = "stop";
- }
stream << cmd << option << title;
q->sendMessage(ba);
}
@@ -108,9 +107,8 @@ void QV8ProfilerClient::setRecording(bool v)
d->recording = v;
- if (status() == Enabled) {
+ if (status() == Enabled)
sendRecordingStatus();
- }
emit recordingChanged(v);
}
diff --git a/src/libs/qmleditorwidgets/colorbox.cpp b/src/libs/qmleditorwidgets/colorbox.cpp
index 70e905bfc7..ca6aef689f 100644
--- a/src/libs/qmleditorwidgets/colorbox.cpp
+++ b/src/libs/qmleditorwidgets/colorbox.cpp
@@ -199,7 +199,7 @@ void ColorBox::paintEvent(QPaintEvent *event)
}
m_cache = QPixmap::fromImage(cache);
}
-
+
p.drawPixmap(5, 5, m_cache);
int x = clamp(m_color.hsvSaturationF() * 120, 0, 119) + 5;
diff --git a/src/libs/qmleditorwidgets/colorbox.h b/src/libs/qmleditorwidgets/colorbox.h
index 166f1aedef..f057501e5a 100644
--- a/src/libs/qmleditorwidgets/colorbox.h
+++ b/src/libs/qmleditorwidgets/colorbox.h
@@ -30,7 +30,7 @@
#ifndef COLORBOX_H
#define COLORBOX_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QWidget>
#include <qdeclarative.h>
diff --git a/src/libs/qmleditorwidgets/colorbutton.cpp b/src/libs/qmleditorwidgets/colorbutton.cpp
index 96f992e54e..4ef410160f 100644
--- a/src/libs/qmleditorwidgets/colorbutton.cpp
+++ b/src/libs/qmleditorwidgets/colorbutton.cpp
@@ -89,15 +89,15 @@ static inline QColor properColor(const QString &str)
namespace QmlEditorWidgets {
-void ColorButton::setColor(const QString &colorStr)
+void ColorButton::setColor(const QVariant &colorStr)
{
- if (m_colorString == colorStr)
+ if (m_colorString == colorStr.toString())
return;
- setEnabled(isColorString(colorStr));
+ setEnabled(isColorString(colorStr.toString()));
- m_colorString = colorStr;
+ m_colorString = colorStr.toString();
update();
emit colorChanged();
}
diff --git a/src/libs/qmleditorwidgets/colorbutton.h b/src/libs/qmleditorwidgets/colorbutton.h
index 418f8b06ba..4f40e6485f 100644
--- a/src/libs/qmleditorwidgets/colorbutton.h
+++ b/src/libs/qmleditorwidgets/colorbutton.h
@@ -30,7 +30,7 @@
#ifndef COLORBUTTON_H
#define COLORBUTTON_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QToolButton>
#include <qdeclarative.h>
@@ -40,15 +40,20 @@ class QMLEDITORWIDGETS_EXPORT ColorButton : public QToolButton {
Q_OBJECT
-Q_PROPERTY(QString color READ color WRITE setColor NOTIFY colorChanged)
+Q_PROPERTY(QVariant color READ color WRITE setColor NOTIFY colorChanged)
Q_PROPERTY(bool noColor READ noColor WRITE setNoColor)
Q_PROPERTY(bool showArrow READ showArrow WRITE setShowArrow)
public:
- ColorButton(QWidget *parent = 0) : QToolButton (parent), m_colorString("#ffffff"), m_noColor(false), m_showArrow(true) {}
+ ColorButton(QWidget *parent = 0) :
+ QToolButton (parent),
+ m_colorString(QLatin1String("#ffffff")),
+ m_noColor(false),
+ m_showArrow(true)
+ {}
- void setColor(const QString &colorStr);
- QString color() const { return m_colorString; }
+ void setColor(const QVariant &colorStr);
+ QVariant color() const { return m_colorString; }
QColor convertedColor() const;
bool noColor() const { return m_noColor; }
void setNoColor(bool f) { m_noColor = f; update(); }
diff --git a/src/libs/qmleditorwidgets/colorwidgets.h b/src/libs/qmleditorwidgets/colorwidgets.h
index 6be25e76a9..39760d5586 100644
--- a/src/libs/qmleditorwidgets/colorwidgets.h
+++ b/src/libs/qmleditorwidgets/colorwidgets.h
@@ -30,7 +30,7 @@
#ifndef COLORWIDGET_H
#define COLORWIDGET_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
namespace QmlEditorWidgets {
diff --git a/src/libs/qmleditorwidgets/contextpanetextwidget.cpp b/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
index fc7b81ed0b..495fa82533 100644
--- a/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
+++ b/src/libs/qmleditorwidgets/contextpanetextwidget.cpp
@@ -95,7 +95,7 @@ ContextPaneTextWidget::ContextPaneTextWidget(QWidget *parent) :
static inline bool checkIfBoolean(QVariant v)
{
- return (v.toString() == "true" || v.toString() == "false");
+ return (v.toString() == QLatin1String("true") || v.toString() == QLatin1String("false"));
}
void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader)
@@ -103,7 +103,7 @@ void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader)
if (propertyReader->hasProperty(QLatin1String("font.pointSize"))) {
QVariant variant = propertyReader->readProperty(QLatin1String("font.pointSize"));
bool b;
- ui->fontSizeSpinBox->setValue(variant.toInt(&b));
+ ui->fontSizeSpinBox->setValue(variant.toInt(&b));
ui->fontSizeSpinBox->setEnabled(b);
ui->fontSizeSpinBox->setIsPointSize(true);
} else if (!propertyReader->hasProperty(QLatin1String("font.pixelSize"))) {
@@ -169,17 +169,15 @@ void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader)
ui->strikeoutButton->setChecked(false);
}
- if (propertyReader->hasProperty(QLatin1String("color"))) {
- ui->colorButton->setColor(propertyReader->readProperty("color").toString());
- } else {
+ if (propertyReader->hasProperty(QLatin1String("color")))
+ ui->colorButton->setColor(propertyReader->readProperty(QLatin1String("color")).toString());
+ else
ui->colorButton->setColor(QLatin1String("black"));
- }
- if (propertyReader->hasProperty(QLatin1String("styleColor"))) {
- ui->textColorButton->setColor(propertyReader->readProperty("styleColor").toString());
- } else {
+ if (propertyReader->hasProperty(QLatin1String("styleColor")))
+ ui->textColorButton->setColor(propertyReader->readProperty(QLatin1String("styleColor")).toString());
+ else
ui->textColorButton->setColor(QLatin1String("black"));
- }
if (propertyReader->hasProperty(QLatin1String("font.family"))) {
QString familyName = propertyReader->readProperty(QLatin1String("font.family")).toString();
@@ -197,7 +195,7 @@ void ContextPaneTextWidget::setProperties(QmlJS::PropertyReader *propertyReader)
QString alignment = propertyReader->readProperty(QLatin1String("horizontalAlignment")).toString();
ui->leftAlignmentButton->setChecked(true);
ui->leftAlignmentButton->setEnabled(true);
- if (alignment == QLatin1String("Text.AlignHCenter") || alignment == "AlignHCenter")
+ if (alignment == QLatin1String("Text.AlignHCenter") || alignment == QLatin1String("AlignHCenter"))
ui->centerHAlignmentButton->setChecked(true);
else if (alignment == QLatin1String("Text.AlignRight") || alignment == QLatin1String("AlignRight"))
ui->rightAlignmentButton->setChecked(true);
@@ -264,7 +262,7 @@ void ContextPaneTextWidget::onTextColorButtonToggled(bool flag)
if (flag)
ui->colorButton->setChecked(false);
QPoint p = mapToGlobal(ui->textColorButton->pos());
- parentContextWidget->colorDialog()->setupColor(ui->textColorButton->color());
+ parentContextWidget->colorDialog()->setupColor(ui->textColorButton->color().toString());
p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p);
parentContextWidget->onShowColorDialog(flag, p);
}
@@ -275,8 +273,8 @@ void ContextPaneTextWidget::onColorButtonToggled(bool flag)
ui->textColorButton->setChecked(false);
ContextPaneWidget *parentContextWidget = qobject_cast<ContextPaneWidget*>(parentWidget());
QPoint p = mapToGlobal(ui->colorButton->pos());
- parentContextWidget->colorDialog()->setupColor(ui->colorButton->color());
- p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p);
+ parentContextWidget->colorDialog()->setupColor(ui->colorButton->color().toString());
+ p = parentContextWidget->colorDialog()->parentWidget()->mapFromGlobal(p);
parentContextWidget->onShowColorDialog(flag, p);
}
@@ -301,7 +299,7 @@ void ContextPaneTextWidget::onColorDialogCancled()
}
void ContextPaneTextWidget::onFontSizeChanged(int)
-{
+{
if (m_fontSizeTimer > 0)
killTimer(m_fontSizeTimer);
m_fontSizeTimer = startTimer(200);
@@ -310,11 +308,10 @@ void ContextPaneTextWidget::onFontSizeChanged(int)
void ContextPaneTextWidget::onFontFormatChanged()
{
int size = ui->fontSizeSpinBox->value();
- if (ui->fontSizeSpinBox->isPointSize()) {
+ if (ui->fontSizeSpinBox->isPointSize())
emit removeAndChangeProperty(QLatin1String("font.pixelSize"), QLatin1String("font.pointSize"), size, true);
- } else {
+ else
emit removeAndChangeProperty(QLatin1String("font.pointSize"), QLatin1String("font.pixelSize"), size, true);
- }
}
@@ -354,7 +351,7 @@ void ContextPaneTextWidget::onStrikeoutCheckedChanged(bool value)
void ContextPaneTextWidget::onCurrentFontChanged(const QFont &font)
{
font.family();
- emit propertyChanged(QLatin1String("font.family"), QVariant(QString('\"') + font.family() + QString('\"')));
+ emit propertyChanged(QLatin1String("font.family"), QVariant(QLatin1Char('"') + font.family() + QLatin1Char('"')));
}
void ContextPaneTextWidget::onHorizontalAlignmentChanged()
diff --git a/src/libs/qmleditorwidgets/contextpanetextwidget.h b/src/libs/qmleditorwidgets/contextpanetextwidget.h
index 33174b0ea9..b82a456157 100644
--- a/src/libs/qmleditorwidgets/contextpanetextwidget.h
+++ b/src/libs/qmleditorwidgets/contextpanetextwidget.h
@@ -30,7 +30,7 @@
#ifndef CONTEXTPANETEXTWIDGET_H
#define CONTEXTPANETEXTWIDGET_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QWidget>
QT_BEGIN_NAMESPACE
diff --git a/src/libs/qmleditorwidgets/contextpanewidget.cpp b/src/libs/qmleditorwidgets/contextpanewidget.cpp
index ed3063304f..ea2b975090 100644
--- a/src/libs/qmleditorwidgets/contextpanewidget.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidget.cpp
@@ -28,6 +28,9 @@
****************************************************************************/
#include "contextpanewidget.h"
+
+#include <utils/hostosinfo.h>
+
#include <QToolButton>
#include <QFontComboBox>
#include <QComboBox>
@@ -48,6 +51,8 @@
#include "customcolordialog.h"
#include "colorbutton.h"
+using namespace Utils;
+
namespace QmlEditorWidgets {
/* XPM */
@@ -101,12 +106,12 @@ DragWidget::DragWidget(QWidget *parent) : QFrame(parent)
// TODO: The following code should be enabled for OSX
// when QTBUG-23205 is fixed
-#ifndef Q_OS_MAC
- m_dropShadowEffect = new QGraphicsDropShadowEffect;
- m_dropShadowEffect->setBlurRadius(6);
- m_dropShadowEffect->setOffset(2, 2);
- setGraphicsEffect(m_dropShadowEffect);
-#endif
+ if (!HostOsInfo::isMacHost()) {
+ m_dropShadowEffect = new QGraphicsDropShadowEffect;
+ m_dropShadowEffect->setBlurRadius(6);
+ m_dropShadowEffect->setOffset(2, 2);
+ setGraphicsEffect(m_dropShadowEffect);
+ }
}
void DragWidget::mousePressEvent(QMouseEvent * event)
@@ -126,12 +131,12 @@ void DragWidget::mouseReleaseEvent(QMouseEvent *event)
m_startPos = QPoint(-1, -1);
// TODO: The following code should be enabled for OSX
// when QTBUG-23205 is fixed
-#ifndef Q_OS_MAC
- m_dropShadowEffect = new QGraphicsDropShadowEffect;
- m_dropShadowEffect->setBlurRadius(6);
- m_dropShadowEffect->setOffset(2, 2);
- setGraphicsEffect(m_dropShadowEffect);
-#endif
+ if (!HostOsInfo::isMacHost()) {
+ m_dropShadowEffect = new QGraphicsDropShadowEffect;
+ m_dropShadowEffect->setBlurRadius(6);
+ m_dropShadowEffect->setOffset(2, 2);
+ setGraphicsEffect(m_dropShadowEffect);
+ }
}
QFrame::mouseReleaseEvent(event);
}
@@ -176,16 +181,14 @@ void DragWidget::protectedMoved()
void DragWidget::leaveEvent(QEvent *)
{
-#ifdef Q_OS_MAC
- unsetCursor();
-#endif
+ if (HostOsInfo::isMacHost())
+ unsetCursor();
}
void DragWidget::enterEvent(QEvent *)
{
-#ifdef Q_OS_MAC
- setCursor(Qt::ArrowCursor);
-#endif
+ if (HostOsInfo::isMacHost())
+ setCursor(Qt::ArrowCursor);
}
ContextPaneWidget::ContextPaneWidget(QWidget *parent) : DragWidget(parent), m_currentWidget(0)
@@ -231,9 +234,8 @@ ContextPaneWidget::ContextPaneWidget(QWidget *parent) : DragWidget(parent), m_cu
m_disableAction->setCheckable(true);
connect(m_disableAction.data(), SIGNAL(toggled(bool)), this, SLOT(onDisable(bool)));
m_pinned = false;
-#ifdef Q_OS_MAC
- setCursor(Qt::ArrowCursor);
-#endif
+ if (HostOsInfo::isMacHost())
+ setCursor(Qt::ArrowCursor);
}
ContextPaneWidget::~ContextPaneWidget()
@@ -241,7 +243,7 @@ ContextPaneWidget::~ContextPaneWidget()
//if the pane was never activated the widget is not in a widget tree
if (!m_bauhausColorDialog.isNull())
delete m_bauhausColorDialog.data();
- m_bauhausColorDialog.clear();
+ m_bauhausColorDialog = 0;
}
void ContextPaneWidget::activate(const QPoint &pos, const QPoint &alternative, const QPoint &alternative2, bool pinned)
@@ -341,17 +343,17 @@ bool ContextPaneWidget::setType(const QStringList &types)
m_rectangleWidget->hide();
m_easingWidget->hide();
- if (types.contains("Text") ||
- types.contains("TextEdit") ||
- types.contains("TextInput")) {
+ if (types.contains(QLatin1String("Text")) ||
+ types.contains(QLatin1String("TextEdit")) ||
+ types.contains(QLatin1String("TextInput"))) {
m_currentWidget = m_textWidget;
m_textWidget->show();
m_textWidget->setStyleVisible(true);
m_textWidget->setVerticalAlignmentVisible(true);
- if (types.contains("TextInput")) {
+ if (types.contains(QLatin1String("TextInput"))) {
m_textWidget->setVerticalAlignmentVisible(false);
m_textWidget->setStyleVisible(false);
- } else if (types.contains("TextEdit")) {
+ } else if (types.contains(QLatin1String("TextEdit"))) {
m_textWidget->setStyleVisible(false);
}
resize(sizeHint());
@@ -364,7 +366,7 @@ bool ContextPaneWidget::setType(const QStringList &types)
resize(sizeHint());
return true;
}
- if (types.contains("Rectangle")) {
+ if (types.contains(QLatin1String("Rectangle"))) {
m_currentWidget = m_rectangleWidget;
m_rectangleWidget->enabableGradientEditing(!isPropertyChanges());
m_rectangleWidget->show();
@@ -372,14 +374,14 @@ bool ContextPaneWidget::setType(const QStringList &types)
return true;
}
- if (types.contains("BorderImage")) {
+ if (types.contains(QLatin1String("BorderImage"))) {
m_currentWidget = m_borderImageWidget;
m_borderImageWidget->show();
resize(sizeHint());
return true;
}
- if (types.contains("Image")) {
+ if (types.contains(QLatin1String("Image"))) {
m_currentWidget = m_imageWidget;
m_imageWidget->show();
resize(sizeHint());
@@ -390,8 +392,10 @@ bool ContextPaneWidget::setType(const QStringList &types)
bool ContextPaneWidget::acceptsType(const QStringList &types)
{
- return types.contains("Text") || types.contains("TextEdit") || types.contains("TextInput") || m_easingWidget->acceptsType(types) ||
- types.contains("Rectangle") || types.contains("Image") || types.contains("BorderImage");
+ return types.contains(QLatin1String("Text")) || types.contains(QLatin1String("TextEdit")) ||
+ types.contains(QLatin1String("TextInput")) || m_easingWidget->acceptsType(types) ||
+ types.contains(QLatin1String("Rectangle")) || types.contains(QLatin1String("Image")) ||
+ types.contains(QLatin1String("BorderImage"));
}
void ContextPaneWidget::onTogglePane()
@@ -409,7 +413,7 @@ void ContextPaneWidget::onTogglePane()
}
void ContextPaneWidget::onShowColorDialog(bool checked, const QPoint &p)
-{
+{
if (checked) {
colorDialog()->setParent(parentWidget());
colorDialog()->move(p);
@@ -421,7 +425,7 @@ void ContextPaneWidget::onShowColorDialog(bool checked, const QPoint &p)
}
void ContextPaneWidget::onDisable(bool b)
-{
+{
enabledChanged(b);
if (!b) {
hide();
@@ -446,7 +450,7 @@ void ContextPaneWidget::protectedMoved()
}
QWidget* ContextPaneWidget::createFontWidget()
-{
+{
m_textWidget = new ContextPaneTextWidget(this);
connect(m_textWidget, SIGNAL(propertyChanged(QString,QVariant)), this, SIGNAL(propertyChanged(QString,QVariant)));
connect(m_textWidget, SIGNAL(removeProperty(QString)), this, SIGNAL(removeProperty(QString)));
diff --git a/src/libs/qmleditorwidgets/contextpanewidget.h b/src/libs/qmleditorwidgets/contextpanewidget.h
index 02e31cceb1..22a445ffa0 100644
--- a/src/libs/qmleditorwidgets/contextpanewidget.h
+++ b/src/libs/qmleditorwidgets/contextpanewidget.h
@@ -30,9 +30,9 @@
#ifndef CONTEXTPANEWIDGET_H
#define CONTEXTPANEWIDGET_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QFrame>
-#include <QWeakPointer>
+#include <QPointer>
QT_BEGIN_NAMESPACE
class QToolButton;
@@ -75,7 +75,7 @@ private:
QGraphicsDropShadowEffect *m_dropShadowEffect;
QGraphicsOpacityEffect *m_opacityEffect;
QPoint m_startPos;
- QWeakPointer<QWidget> m_secondaryTarget;
+ QPointer<QWidget> m_secondaryTarget;
};
class QMLEDITORWIDGETS_EXPORT ContextPaneWidget : public DragWidget
@@ -137,9 +137,9 @@ private:
ContextPaneWidgetImage *m_imageWidget;
ContextPaneWidgetImage *m_borderImageWidget;
ContextPaneWidgetRectangle *m_rectangleWidget;
- QWeakPointer<CustomColorDialog> m_bauhausColorDialog;
- QWeakPointer<QAction> m_resetAction;
- QWeakPointer<QAction> m_disableAction;
+ QPointer<CustomColorDialog> m_bauhausColorDialog;
+ QPointer<QAction> m_resetAction;
+ QPointer<QAction> m_disableAction;
QString m_colorName;
QPoint m_originalPos;
bool m_pinned;
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp b/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
index af8674b3a7..c9aeee733a 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidgetimage.cpp
@@ -28,6 +28,9 @@
****************************************************************************/
#include "contextpanewidgetimage.h"
+
+#include <utils/hostosinfo.h>
+
#include "ui_contextpanewidgetimage.h"
#include "ui_contextpanewidgetborderimage.h"
#include <qmljs/qmljspropertyreader.h>
@@ -51,7 +54,7 @@ bool LabelFilter::eventFilter(QObject *obj, QEvent *event)
emit doubleClicked();
event->accept();
return true;
- }
+ }
return QObject::eventFilter(obj, event);
}
@@ -110,11 +113,11 @@ ContextPaneWidgetImage::ContextPaneWidgetImage(QWidget *parent, bool borderImage
connect(ui->horizontalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
connect(ui->verticalStretchRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
connect(ui->preserveAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
- connect(ui->cropAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
+ connect(ui->cropAspectFitRadioButton, SIGNAL(toggled(bool)), this, SLOT(onStretchChanged()));
}
previewDialog();
m_fileWidget->setShowComboBox(true);
- m_fileWidget->setFilter("*.png *.gif *.jpg");
+ m_fileWidget->setFilter(QLatin1String("*.png *.gif *.jpg"));
connect(m_fileWidget, SIGNAL(fileNameChanged(QUrl)), this, SLOT(onFileNameChanged()));
connect(labelFilter, SIGNAL(doubleClicked()), this, SLOT(onPixmapDoubleClicked()));
@@ -150,16 +153,16 @@ void ContextPaneWidgetImage::setProperties(QmlJS::PropertyReader *propertyReader
if (propertyReader->hasProperty(QLatin1String("horizontalTileMode"))) {
QString fillMode = propertyReader->readProperty(QLatin1String("horizontalTileMode")).toString();
- if (fillMode.contains("BorderImage."))
- fillMode.remove("BorderImage.");
+ if (fillMode.contains(QLatin1String("BorderImage.")))
+ fillMode.remove(QLatin1String("BorderImage."));
uiBorderImage->horizontalStretchRadioButton->setChecked(true);
- if (fillMode == "Stretch")
+ if (fillMode == QLatin1String("Stretch"))
uiBorderImage->horizontalStretchRadioButton->setChecked(true);
- if (fillMode == "Repeat")
+ if (fillMode == QLatin1String("Repeat"))
uiBorderImage->horizontalTileRadioButton->setChecked(true);
- if (fillMode == "Round")
+ if (fillMode == QLatin1String("Round"))
uiBorderImage->horizontalTileRadioButtonNoCrop->setChecked(true);
} else {
//uiBorderImage
@@ -167,16 +170,16 @@ void ContextPaneWidgetImage::setProperties(QmlJS::PropertyReader *propertyReader
}
if (propertyReader->hasProperty(QLatin1String("verticalTileMode"))) {
QString fillMode = propertyReader->readProperty(QLatin1String("verticalTileMode")).toString();
- if (fillMode.contains("BorderImage."))
- fillMode.remove("BorderImage.");
+ if (fillMode.contains(QLatin1String("BorderImage.")))
+ fillMode.remove(QLatin1String("BorderImage."));
uiBorderImage->verticalStretchRadioButton->setChecked(true);
- if (fillMode == "Stretch")
+ if (fillMode == QLatin1String("Stretch"))
uiBorderImage->verticalStretchRadioButton->setChecked(true);
- if (fillMode == "Repeat")
+ if (fillMode == QLatin1String("Repeat"))
uiBorderImage->verticalTileRadioButton->setChecked(true);
- if (fillMode == "Round")
+ if (fillMode == QLatin1String("Round"))
uiBorderImage->verticalTileRadioButtonNoCrop->setChecked(true);
} else {
//uiBorderImage
@@ -185,36 +188,36 @@ void ContextPaneWidgetImage::setProperties(QmlJS::PropertyReader *propertyReader
} else {
if (propertyReader->hasProperty(QLatin1String("fillMode"))) {
QString fillMode = propertyReader->readProperty(QLatin1String("fillMode")).toString();
- if (fillMode.contains("Image."))
- fillMode.remove("Image.");
+ if (fillMode.contains(QLatin1String("Image.")))
+ fillMode.remove(QLatin1String("Image."));
ui->stretchRadioButton->setChecked(true);
- if (fillMode == "Image.Tile" || fillMode == "Tile")
+ if (fillMode == QLatin1String("Image.Tile") || fillMode == QLatin1String("Tile"))
ui->tileRadioButton->setChecked(true);
- if (fillMode == "Image.TileVertically" || fillMode == "TileVertically")
+ if (fillMode == QLatin1String("Image.TileVertically") || fillMode == QLatin1String("TileVertically"))
ui->horizontalStretchRadioButton->setChecked(true);
- if (fillMode == "Image.TileHorizontally" || fillMode == "TileHorizontally")
+ if (fillMode == QLatin1String("Image.TileHorizontally") || fillMode == QLatin1String("TileHorizontally"))
ui->verticalStretchRadioButton->setChecked(true);
- if (fillMode == "Image.PreserveAspectFit" || fillMode == "PreserveAspectFit")
+ if (fillMode == QLatin1String("Image.PreserveAspectFit") || fillMode == QLatin1String("PreserveAspectFit"))
ui->preserveAspectFitRadioButton->setChecked(true);
- if (fillMode == "Image.PreserveAspectCrop" || fillMode == "PreserveAspectCrop")
+ if (fillMode == QLatin1String("Image.PreserveAspectCrop") || fillMode == QLatin1String("PreserveAspectCrop"))
ui->cropAspectFitRadioButton->setChecked(true);
} else {
ui->stretchRadioButton->setChecked(true);
- }
+ }
}
if (propertyReader->hasProperty(QLatin1String("source"))) {
QString source = propertyReader->readProperty(QLatin1String("source")).toString();
m_fileWidget->setFileName(source);
- if (QFile::exists(m_path + '/' + source))
- setPixmap(m_path + '/' + source);
+ if (QFile::exists(m_path + QLatin1Char('/') + source))
+ setPixmap(m_path + QLatin1Char('/') + source);
else
setPixmap(source);
} else {
- m_sizeLabel->setText("");
+ m_sizeLabel->clear();
m_fileWidget->setFileName(QUrl());
- setPixmap("");
+ setPixmap(QString());
}
}
@@ -230,27 +233,27 @@ void PreviewDialog::setZoom(int z)
m_label->setZoom(z);
switch (m_zoom) {
case 1:
- m_zoomLabel->setText("100%");
+ m_zoomLabel->setText(QLatin1String("100%"));
m_slider->setValue(1);
break;
case 2:
- m_zoomLabel->setText("200%");
+ m_zoomLabel->setText(QLatin1String("200%"));
m_slider->setValue(2);
break;
case 4:
- m_zoomLabel->setText("400%");
+ m_zoomLabel->setText(QLatin1String("400%"));
m_slider->setValue(3);
break;
case 6:
- m_zoomLabel->setText("600%");
+ m_zoomLabel->setText(QLatin1String("600%"));
m_slider->setValue(4);
break;
case 8:
- m_zoomLabel->setText("800%");
+ m_zoomLabel->setText(QLatin1String("800%"));
m_slider->setValue(5);
break;
case 10:
- m_zoomLabel->setText("1000%");
+ m_zoomLabel->setText(QLatin1String("1000%"));
m_slider->setValue(6);
break;
default: break;
@@ -333,7 +336,7 @@ void ContextPaneWidgetImage::onFileNameChanged()
}
void ContextPaneWidgetImage::onPixmapDoubleClicked()
-{
+{
previewDialog()->setParent(parentWidget()->parentWidget());
previewDialog()->setMaximumSize(previewDialog()->parentWidget()->size() - QSize(150, 100));
if (m_borderImage)
@@ -355,7 +358,7 @@ void ContextPaneWidgetImage::onPixmapDoubleClicked()
if (previewDialog()->pos().x() < 0)
previewDialog()->move(0, previewDialog()->pos().y());
if (previewDialog()->pos().y() < 0)
- previewDialog()->move(previewDialog()->pos().x(), 0);
+ previewDialog()->move(previewDialog()->pos().x(), 0);
previewDialog()->raise();
}
@@ -420,7 +423,7 @@ static inline bool parseSciFile(const QString &fileName, QString &pixmapFileName
data.open(QIODevice::ReadOnly);
QByteArray raw;
- while(raw = data.readLine(), !raw.isEmpty()) {
+ while (raw = data.readLine(), !raw.isEmpty()) {
QString line = QString::fromUtf8(raw.trimmed());
if (line.isEmpty() || line.startsWith(QLatin1Char('#')))
continue;
@@ -476,10 +479,10 @@ void ContextPaneWidgetImage::setPixmap(const QString &fileName)
Qt::TileRule horizontalTileRule;
Qt::TileRule verticalTileRule;
if (parseSciFile(fileName, pixmapFileName, left, right, top, bottom, horizontalTileRule, verticalTileRule)) {
- localFileName = QFileInfo(fileName).absoluteDir().absolutePath() + '/' + pixmapFileName;
+ localFileName = QFileInfo(fileName).absoluteDir().absolutePath() + QLatin1Char('/') + pixmapFileName;
previewDialog()->previewLabel()->setMargins(left, top, right, bottom);
} else { // sci file not parsed correctly
- uiBorderImage->sizeLabel->setText("");
+ uiBorderImage->sizeLabel->clear();
return;
}
}
@@ -487,7 +490,8 @@ void ContextPaneWidgetImage::setPixmap(const QString &fileName)
if (source.isNull())
source = pix;
previewDialog()->setPixmap(source, previewDialog()->zoom());
- uiBorderImage->sizeLabel->setText(QString::number(source.width()) + 'x' + QString::number(source.height()));
+ uiBorderImage->sizeLabel->setText(QString::number(source.width()) + QLatin1Char('x')
+ + QString::number(source.height()));
QPainter p(&pix);
Qt::TileRule horizontalTileMode = Qt::StretchTile;
Qt::TileRule verticalTileMode = Qt::StretchTile;
@@ -504,14 +508,14 @@ void ContextPaneWidgetImage::setPixmap(const QString &fileName)
qDrawBorderPixmap(&p, QRect(0, 0, 76, 76), margins, source, source.rect(), margins, rules);
//p.drawPixmap(0,0,76,76, source);
} else {
- uiBorderImage->sizeLabel->setText("");
+ uiBorderImage->sizeLabel->clear();
}
uiBorderImage->label->setPixmap(pix);
} else {
if (QFile(fileName).exists()) {
QPixmap source(fileName);
previewDialog()->setPixmap(source, 1);
- ui->sizeLabel->setText(QString::number(source.width()) + 'x' + QString::number(source.height()));
+ ui->sizeLabel->setText(QString::number(source.width()) + QLatin1Char('x') + QString::number(source.height()));
QPainter p(&pix);
if (ui->stretchRadioButton->isChecked()) {
p.drawPixmap(0,0,76,76, source);
@@ -540,7 +544,7 @@ void ContextPaneWidgetImage::setPixmap(const QString &fileName)
p.drawPixmap(offset, 0, cropped.width(), 76, source);
}
} else {
- ui->sizeLabel->setText("");
+ ui->sizeLabel->clear();
}
ui->label->setPixmap(pix);
@@ -610,12 +614,12 @@ PreviewLabel::PreviewLabel(QWidget *parent)
// TODO: The following code should be enabled for OSX
// when QTBUG-23205 is fixed
-#ifndef Q_OS_MAC
- QGraphicsDropShadowEffect *dropShadowEffect = new QGraphicsDropShadowEffect;
- dropShadowEffect->setBlurRadius(4);
- dropShadowEffect->setOffset(2, 2);
- m_hooverInfo->setGraphicsEffect(dropShadowEffect);
-#endif
+ if (!Utils::HostOsInfo::isMacHost()) {
+ QGraphicsDropShadowEffect *dropShadowEffect = new QGraphicsDropShadowEffect;
+ dropShadowEffect->setBlurRadius(4);
+ dropShadowEffect->setOffset(2, 2);
+ m_hooverInfo->setGraphicsEffect(dropShadowEffect);
+ }
m_hooverInfo->setAutoFillBackground(true);
m_hooverInfo->raise();
}
@@ -701,25 +705,25 @@ void PreviewLabel::mousePressEvent(QMouseEvent * event)
QApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
m_dragging_left = true;
event->accept();
- m_hooverInfo->setText("Left " + QString::number(m_left));
+ m_hooverInfo->setText(QLatin1String("Left ") + QString::number(m_left));
m_hooverInfo->show();
} else if (rangeCheck(m_top * m_zoom, event->pos().y())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeVerCursor));
m_dragging_top = true;
event->accept();
- m_hooverInfo->setText("Top " + QString::number(m_top));
+ m_hooverInfo->setText(QLatin1String("Top ") + QString::number(m_top));
m_hooverInfo->show();
} else if (rangeCheck(m_right * m_zoom, width() - event->pos().x())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
m_dragging_right = true;
event->accept();
- m_hooverInfo->setText("Right " + QString::number(m_right));
+ m_hooverInfo->setText(QLatin1String("Right ") + QString::number(m_right));
m_hooverInfo->show();
} else if (rangeCheck(m_bottom * m_zoom, height() - event->pos().y())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeVerCursor));
m_dragging_bottom = true;
event->accept();
- m_hooverInfo->setText("Bottom " + QString::number(m_bottom));
+ m_hooverInfo->setText(QLatin1String("Bottom ") + QString::number(m_bottom));
m_hooverInfo->show();
bottom = true;
} else {
@@ -822,46 +826,46 @@ void PreviewLabel::mouseMoveEvent(QMouseEvent * event)
m_left = p.x() / m_zoom;
m_left = limitPositive(m_left);
event->accept();
- m_hooverInfo->setText("Left " + QString::number(m_left));
+ m_hooverInfo->setText(QLatin1String("Left ") + QString::number(m_left));
update();
} else if (m_dragging_top) {
m_top = p.y() / m_zoom;
m_top = limitPositive(m_top);
event->accept();
- m_hooverInfo->setText("Top " + QString::number(m_top));
+ m_hooverInfo->setText(QLatin1String("Top ") + QString::number(m_top));
update();
} else if (m_dragging_right) {
m_right = (width() - p.x()) / m_zoom;
m_right = limitPositive(m_right);
event->accept();
- m_hooverInfo->setText("Right " + QString::number(m_right));
+ m_hooverInfo->setText(QLatin1String("Right ") + QString::number(m_right));
update();
} else if (m_dragging_bottom) {
m_bottom = (height() - p.y()) / m_zoom;
m_bottom = limitPositive(m_bottom);
event->accept();
- m_hooverInfo->setText("Bottom " + QString::number(m_bottom));
+ m_hooverInfo->setText(QLatin1String("Bottom ") + QString::number(m_bottom));
bottom = true;
update();
} else if (rangeCheck(m_left * m_zoom, p.x())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
event->accept();
- m_hooverInfo->setText("Left " + QString::number(m_left));
+ m_hooverInfo->setText(QLatin1String("Left ") + QString::number(m_left));
m_hooverInfo->show();
} else if (rangeCheck(m_top * m_zoom, p.y())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeVerCursor));
event->accept();
- m_hooverInfo->setText("Top " + QString::number(m_top));
+ m_hooverInfo->setText(QLatin1String("Top ") + QString::number(m_top));
m_hooverInfo->show();
} else if (rangeCheck(m_right * m_zoom, width() - p.x())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeHorCursor));
event->accept();
- m_hooverInfo->setText("Right " + QString::number(m_right));
+ m_hooverInfo->setText(QLatin1String("Right ") + QString::number(m_right));
m_hooverInfo->show();
} else if (rangeCheck(m_bottom * m_zoom, height() - p.y())) {
QApplication::setOverrideCursor(QCursor(Qt::SizeVerCursor));
event->accept();
- m_hooverInfo->setText("Bottom " + QString::number(m_bottom));
+ m_hooverInfo->setText(QLatin1String("Bottom ") + QString::number(m_bottom));
m_hooverInfo->show();
bottom = true;
} else {
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetimage.h b/src/libs/qmleditorwidgets/contextpanewidgetimage.h
index 8c231120a1..6a71909f5c 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetimage.h
+++ b/src/libs/qmleditorwidgets/contextpanewidgetimage.h
@@ -30,11 +30,13 @@
#ifndef CONTEXTPANEWIDGETIMAGE_H
#define CONTEXTPANEWIDGETIMAGE_H
-#include <qmleditorwidgets_global.h>
-#include <QLabel>
-#include <contextpanewidget.h>
+#include "qmleditorwidgets_global.h"
+#include "contextpanewidget.h"
#include <qdrawutil.h>
+#include <QLabel>
+#include <QPointer>
+
QT_BEGIN_NAMESPACE
namespace Ui {
class ContextPaneWidgetImage;
@@ -127,7 +129,7 @@ public:
explicit ContextPaneWidgetImage(QWidget *parent = 0, bool borderImage = false);
~ContextPaneWidgetImage();
void setProperties(QmlJS::PropertyReader *propertyReader);
- void setPath(const QString& path);
+ void setPath(const QString& path);
PreviewDialog* previewDialog();
signals:
@@ -156,7 +158,7 @@ private:
Ui::ContextPaneWidgetImage *ui;
Ui::ContextPaneWidgetBorderImage *uiBorderImage;
QString m_path;
- QWeakPointer<PreviewDialog> m_previewDialog;
+ QPointer<PreviewDialog> m_previewDialog;
FileWidget *m_fileWidget;
QLabel *m_sizeLabel;
bool m_borderImage;
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
index a3c4f15fc4..1bd8924b6b 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
+++ b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.cpp
@@ -74,13 +74,13 @@ ContextPaneWidgetRectangle::~ContextPaneWidgetRectangle()
}
void ContextPaneWidgetRectangle::setProperties(QmlJS::PropertyReader *propertyReader)
-{
+{
m_hasGradient = propertyReader->hasProperty(QLatin1String("gradient"));
m_none = false;
m_hasBorder = false;
if (propertyReader->hasProperty(QLatin1String("color"))) {
- QString str = propertyReader->readProperty("color").toString();
+ QString str = propertyReader->readProperty(QLatin1String("color")).toString();
if (QmlJS::toQColor(str).alpha() == 0)
m_none = true;
ui->colorColorButton->setColor(str);
@@ -90,7 +90,7 @@ void ContextPaneWidgetRectangle::setProperties(QmlJS::PropertyReader *propertyRe
}
if (propertyReader->hasProperty(QLatin1String("border.color"))) {
- ui->borderColorButton->setColor(propertyReader->readProperty("border.color").toString());
+ ui->borderColorButton->setColor(propertyReader->readProperty(QLatin1String("border.color")).toString());
m_hasBorder = true;
} else {
ui->borderColorButton->setColor(QLatin1String("transparent"));
@@ -112,11 +112,11 @@ void ContextPaneWidgetRectangle::setProperties(QmlJS::PropertyReader *propertyRe
if (m_hasGradient && isGradientEditingEnabled()) {
bool isBound;
ui->colorGradient->setChecked(true);
- ui->gradientLine->setGradient(propertyReader->parseGradient("gradient", &isBound));
+ ui->gradientLine->setGradient(propertyReader->parseGradient(QLatin1String("gradient"), &isBound));
if (isBound) {
ui->gradientLabel->setEnabled(false);
ui->gradientLine->setEnabled(false);
- ui->colorColorButton->setColor("invalidColor");
+ ui->colorColorButton->setColor(QLatin1String("invalidColor"));
}
} else {
ui->gradientLine->setEnabled(false);
@@ -205,7 +205,8 @@ void ContextPaneWidgetRectangle::onColorNoneClicked()
{
if (ui->colorNone->isChecked()) {
ui->colorGradient->setEnabled(isGradientEditingEnabled());
- emit removeAndChangeProperty("gradient", "color", "transparent", true);
+ emit removeAndChangeProperty(QLatin1String("gradient"), QLatin1String("color"),
+ QLatin1String("transparent"), true);
}
ui->colorGradient->setEnabled(isGradientEditingEnabled());
}
@@ -214,7 +215,8 @@ void ContextPaneWidgetRectangle::onColorSolidClicked()
{
if (ui->colorSolid->isChecked()) {
ui->gradientLine->setEnabled(false);
- emit removeAndChangeProperty("gradient", "color", "\"black\"", true);
+ emit removeAndChangeProperty(QLatin1String("gradient"), QLatin1String("color"),
+ QLatin1String("\"black\""), true);
}
ui->colorGradient->setEnabled(isGradientEditingEnabled());
}
@@ -222,16 +224,15 @@ void ContextPaneWidgetRectangle::onColorSolidClicked()
void ContextPaneWidgetRectangle::onBorderNoneClicked()
{
if (ui->borderNone->isChecked()) {
- emit removeProperty("border.color");
- emit removeProperty("border.width");//###
+ emit removeProperty(QLatin1String("border.color"));
+ emit removeProperty(QLatin1String("border.width"));//###
}
}
void ContextPaneWidgetRectangle::onBorderSolidClicked()
{
- if (ui->borderSolid->isChecked()) {
- emit propertyChanged("border.color", "\"black\"");
- }
+ if (ui->borderSolid->isChecked())
+ emit propertyChanged(QLatin1String("border.color"), QLatin1String("\"black\""));
}
void ContextPaneWidgetRectangle::onGradientLineDoubleClicked(const QPoint &p)
@@ -258,7 +259,7 @@ void ContextPaneWidgetRectangle::timerEvent(QTimerEvent *event)
m_gradientTimer = -1;
QLinearGradient gradient = ui->gradientLine->gradient();
- QString str = "Gradient {\n";
+ QString str = QLatin1String("Gradient {\n");
foreach (const QGradientStop &stop, gradient.stops()) {
str += QLatin1String("GradientStop {\n");
str += QLatin1String("position: ") + QString::number(stop.first, 'f', 2) + QLatin1String(";\n");
@@ -266,7 +267,7 @@ void ContextPaneWidgetRectangle::timerEvent(QTimerEvent *event)
str += QLatin1String("}\n");
}
str += QLatin1String("}");
- emit propertyChanged("gradient", str);
+ emit propertyChanged(QLatin1String("gradient"), str);
}
}
diff --git a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.h b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.h
index ba8f1c3360..8d2ae8a08d 100644
--- a/src/libs/qmleditorwidgets/contextpanewidgetrectangle.h
+++ b/src/libs/qmleditorwidgets/contextpanewidgetrectangle.h
@@ -30,7 +30,7 @@
#ifndef CONTEXTPANEWIDGETRECTANGLE_H
#define CONTEXTPANEWIDGETRECTANGLE_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QWidget>
QT_BEGIN_NAMESPACE
diff --git a/src/libs/qmleditorwidgets/customcolordialog.cpp b/src/libs/qmleditorwidgets/customcolordialog.cpp
index 7f6cd68521..784bab36cc 100644
--- a/src/libs/qmleditorwidgets/customcolordialog.cpp
+++ b/src/libs/qmleditorwidgets/customcolordialog.cpp
@@ -31,6 +31,8 @@
#include "huecontrol.h"
#include "colorbox.h"
+#include <utils/hostosinfo.h>
+
#include <QHBoxLayout>
#include <QLabel>
#include <QPainter>
@@ -40,6 +42,8 @@
#include <QDialogButtonBox>
#include <QGraphicsEffect>
+using namespace Utils;
+
namespace QmlEditorWidgets {
CustomColorDialog::CustomColorDialog(QWidget *parent) : QFrame(parent )
@@ -51,12 +55,12 @@ CustomColorDialog::CustomColorDialog(QWidget *parent) : QFrame(parent )
// TODO: The following code should be enabled for OSX
// when QTBUG-23205 is fixed
-#ifndef Q_OS_MAC
- QGraphicsDropShadowEffect *dropShadowEffect = new QGraphicsDropShadowEffect;
- dropShadowEffect->setBlurRadius(6);
- dropShadowEffect->setOffset(2, 2);
- setGraphicsEffect(dropShadowEffect);
-#endif
+ if (!HostOsInfo::isMacHost()) {
+ QGraphicsDropShadowEffect *dropShadowEffect = new QGraphicsDropShadowEffect;
+ dropShadowEffect->setBlurRadius(6);
+ dropShadowEffect->setOffset(2, 2);
+ setGraphicsEffect(dropShadowEffect);
+ }
setAutoFillBackground(true);
m_hueControl = new HueControl(this);
@@ -97,10 +101,10 @@ CustomColorDialog::CustomColorDialog(QWidget *parent) : QFrame(parent )
gridLayout->addWidget(colorFrameWidget, 0, 2, 2, 1);
- gridLayout->addWidget(new QLabel("R", this), 0, 3, 1, 1);
- gridLayout->addWidget(new QLabel("G", this), 1, 3, 1, 1);
- gridLayout->addWidget(new QLabel("B", this), 2, 3, 1, 1);
- gridLayout->addWidget(new QLabel("A", this), 3, 3, 1, 1);
+ gridLayout->addWidget(new QLabel(QLatin1String("R"), this), 0, 3, 1, 1);
+ gridLayout->addWidget(new QLabel(QLatin1String("G"), this), 1, 3, 1, 1);
+ gridLayout->addWidget(new QLabel(QLatin1String("B"), this), 2, 3, 1, 1);
+ gridLayout->addWidget(new QLabel(QLatin1String("A"), this), 3, 3, 1, 1);
gridLayout->addWidget(m_rSpinBox, 0, 4, 1, 1);
gridLayout->addWidget(m_gSpinBox, 1, 4, 1, 1);
@@ -183,16 +187,14 @@ void CustomColorDialog::setupWidgets()
void CustomColorDialog::leaveEvent(QEvent *)
{
-#ifdef Q_OS_MAC
- unsetCursor();
-#endif
+ if (HostOsInfo::isMacHost())
+ unsetCursor();
}
void CustomColorDialog::enterEvent(QEvent *)
{
-#ifdef Q_OS_MAC
- setCursor(Qt::ArrowCursor);
-#endif
+ if (HostOsInfo::isMacHost())
+ setCursor(Qt::ArrowCursor);
}
diff --git a/src/libs/qmleditorwidgets/customcolordialog.h b/src/libs/qmleditorwidgets/customcolordialog.h
index fa8e785c09..a61ad7a8bd 100644
--- a/src/libs/qmleditorwidgets/customcolordialog.h
+++ b/src/libs/qmleditorwidgets/customcolordialog.h
@@ -30,7 +30,7 @@
#ifndef CUSTOMCOLORDIALOG_H
#define CUSTOMCOLORDIALOG_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QFrame>
QT_BEGIN_NAMESPACE
diff --git a/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp b/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp
index ade1695b96..0833f6acb9 100644
--- a/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp
+++ b/src/libs/qmleditorwidgets/easingpane/easingcontextpane.cpp
@@ -52,7 +52,7 @@ class EasingSimulation : public QObject
public:
QGraphicsView *m_g;
EasingSimulation(QObject *parent=0, QGraphicsView *v=0):QObject(parent) {
- m_qtLogo = new PixmapItem(QPixmap(":/qt_logo.png"));
+ m_qtLogo = new PixmapItem(QPixmap(QLatin1String(":/qt_logo.png")));
m_scene.addItem(m_qtLogo);
m_scene.setSceneRect(0,0,v->viewport()->width(),m_qtLogo->boundingRect().height());
m_qtLogo->hide();
@@ -145,20 +145,20 @@ EasingContextPane::~EasingContextPane()
bool EasingContextPane::acceptsType(const QStringList &types)
{
- return types.contains("NumberAnimation") ||
- types.contains("PropertyAnimation") ||
- types.contains("ColorAnimation") ||
- types.contains("RotationAnimation");
+ return types.contains(QLatin1String("NumberAnimation")) ||
+ types.contains(QLatin1String("PropertyAnimation")) ||
+ types.contains(QLatin1String("ColorAnimation")) ||
+ types.contains(QLatin1String("RotationAnimation"));
}
void EasingContextPane::setProperties(QmlJS::PropertyReader *propertyReader)
{
m_easingGraph->setGeometry(ui->graphicsView->geometry().adjusted(2,2,-2,-2));
- QString newEasingType = QString("Linear");
+ QString newEasingType = QLatin1String("Linear");
if (propertyReader->hasProperty(QLatin1String("easing.type"))) {
newEasingType = propertyReader->readProperty(QLatin1String("easing.type")).toString();
- if (newEasingType.contains("."))
- newEasingType = newEasingType.right(newEasingType.length() - newEasingType.indexOf(".") - 1);
+ if (newEasingType.contains(QLatin1Char('.')))
+ newEasingType = newEasingType.right(newEasingType.length() - newEasingType.indexOf(QLatin1Char('.')) - 1);
}
m_easingGraph->setEasingName(newEasingType);
@@ -306,13 +306,13 @@ void QmlEditorWidgets::EasingContextPane::on_durationSpinBox_valueChanged(int ne
void QmlEditorWidgets::EasingContextPane::on_easingShapeComboBox_currentIndexChanged(QString newShape)
{
- if (newShape=="Linear")
+ if (newShape==QLatin1String("Linear"))
setLinear();
- else if (newShape=="Bounce")
+ else if (newShape==QLatin1String("Bounce"))
setBounce();
- else if (newShape=="Elastic")
+ else if (newShape==QLatin1String("Elastic"))
setElastic();
- else if (newShape=="Back")
+ else if (newShape==QLatin1String("Back"))
setBack();
else
setOthers();
@@ -343,7 +343,8 @@ void QmlEditorWidgets::EasingContextPane::on_easingExtremesComboBox_currentIndex
void QmlEditorWidgets::EasingContextPane::on_amplitudeSpinBox_valueChanged(double newAmplitude)
{
if ((newAmplitude != m_easingGraph->amplitude()) &&
- (m_easingGraph->easingShape()=="Bounce" || m_easingGraph->easingShape()=="Elastic")) {
+ (m_easingGraph->easingShape()==QLatin1String("Bounce")
+ || m_easingGraph->easingShape()==QLatin1String("Elastic"))) {
m_easingGraph->setAmplitude(newAmplitude);
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.amplitude"), newAmplitude);
@@ -352,7 +353,7 @@ void QmlEditorWidgets::EasingContextPane::on_amplitudeSpinBox_valueChanged(doubl
void QmlEditorWidgets::EasingContextPane::on_periodSpinBox_valueChanged(double newPeriod)
{
- if ((newPeriod != m_easingGraph->period()) && (m_easingGraph->easingShape()=="Elastic")) {
+ if ((newPeriod != m_easingGraph->period()) && (m_easingGraph->easingShape()==QLatin1String("Elastic"))) {
m_easingGraph->setPeriod(newPeriod);
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.period"), newPeriod);
@@ -362,7 +363,7 @@ void QmlEditorWidgets::EasingContextPane::on_periodSpinBox_valueChanged(double n
void QmlEditorWidgets::EasingContextPane::on_overshootSpinBox_valueChanged(double newOvershoot)
{
- if ((newOvershoot != m_easingGraph->overshoot()) && (m_easingGraph->easingShape()=="Back")) {
+ if ((newOvershoot != m_easingGraph->overshoot()) && (m_easingGraph->easingShape()==QLatin1String("Back"))) {
m_easingGraph->setOvershoot(newOvershoot);
m_simulation->updateCurve(m_easingGraph->easingCurve(),ui->durationSpinBox->value());
emit propertyChanged(QLatin1String("easing.overshoot"), newOvershoot);
diff --git a/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp b/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp
index 1d3a347869..9cfeb4e90f 100644
--- a/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp
+++ b/src/libs/qmleditorwidgets/easingpane/easinggraph.cpp
@@ -106,17 +106,17 @@ QEasingCurve EasingGraph::easingCurve() const
QString EasingGraph::easingShape() const
{
QString name = easingName();
- if (name.left(5)=="InOut") return name.right(name.length()-5);
- if (name.left(5)=="OutIn") return name.right(name.length()-5);
- if (name.left(3)=="Out") return name.right(name.length()-3);
- if (name.left(2)=="In") return name.right(name.length()-2);
+ if (name.left(5)==QLatin1String("InOut")) return name.right(name.length()-5);
+ if (name.left(5)==QLatin1String("OutIn")) return name.right(name.length()-5);
+ if (name.left(3)==QLatin1String("Out")) return name.right(name.length()-3);
+ if (name.left(2)==QLatin1String("In")) return name.right(name.length()-2);
return name;
}
void EasingGraph::setEasingShape(const QString &newShape)
{
if (easingShape() != newShape) {
- if (newShape=="Linear")
+ if (newShape==QLatin1String("Linear"))
setEasingName(newShape);
else
setEasingName(m_easingExtremes+newShape);
@@ -126,10 +126,10 @@ void EasingGraph::setEasingShape(const QString &newShape)
QString EasingGraph::easingExtremes() const
{
QString name = easingName();
- if (name.left(5)=="InOut") return "InOut";
- if (name.left(5)=="OutIn") return "OutIn";
- if (name.left(3)=="Out") return "Out";
- if (name.left(2)=="In") return "In";
+ if (name.left(5)==QLatin1String("InOut")) return QLatin1String("InOut");
+ if (name.left(5)==QLatin1String("OutIn")) return QLatin1String("OutIn");
+ if (name.left(3)==QLatin1String("Out")) return QLatin1String("Out");
+ if (name.left(2)==QLatin1String("In")) return QLatin1String("In");
return QString();
}
@@ -137,7 +137,7 @@ void EasingGraph::setEasingExtremes(const QString &newExtremes)
{
if (m_easingExtremes != newExtremes) {
m_easingExtremes = newExtremes;
- if (easingShape()!="Linear")
+ if (easingShape()!=QLatin1String("Linear"))
setEasingName(newExtremes+easingShape());
}
}
@@ -167,7 +167,7 @@ qreal EasingGraph::overshoot() const
void EasingGraph::setOvershoot(qreal newOvershoot)
{
- if ((overshoot() != newOvershoot) && (easingShape()=="Back")) {
+ if ((overshoot() != newOvershoot) && (easingShape()==QLatin1String("Back"))) {
m_curveFunction.setOvershoot(newOvershoot);
emit overshootChanged();
update();
@@ -180,7 +180,7 @@ qreal EasingGraph::amplitude() const
void EasingGraph::setAmplitude(qreal newAmplitude)
{
- if ((amplitude() != newAmplitude) && ((easingShape()=="Bounce") ||(easingShape()=="Elastic"))) {
+ if ((amplitude() != newAmplitude) && ((easingShape()==QLatin1String("Bounce")) ||(easingShape()==QLatin1String("Elastic")))) {
m_curveFunction.setAmplitude(newAmplitude);
emit amplitudeChanged();
update();
@@ -194,7 +194,7 @@ qreal EasingGraph::period() const
void EasingGraph::setPeriod(qreal newPeriod)
{
- if ((period() != newPeriod) && (easingShape()=="Elastic")) {
+ if ((period() != newPeriod) && (easingShape()==QLatin1String("Elastic"))) {
m_curveFunction.setPeriod(newPeriod);
emit periodChanged();
update();
diff --git a/src/libs/qmleditorwidgets/filewidget.cpp b/src/libs/qmleditorwidgets/filewidget.cpp
index 2f2a078e38..930f19d7ef 100644
--- a/src/libs/qmleditorwidgets/filewidget.cpp
+++ b/src/libs/qmleditorwidgets/filewidget.cpp
@@ -42,7 +42,11 @@
namespace QmlEditorWidgets {
-FileWidget::FileWidget(QWidget *parent) : QWidget(parent), m_filter("(*.*)"), m_showComboBox(false), m_lock(false)
+FileWidget::FileWidget(QWidget *parent) :
+ QWidget(parent),
+ m_filter(QLatin1String("(*.*)")),
+ m_showComboBox(false),
+ m_lock(false)
{
m_pushButton = new QToolButton(this);
m_pushButton->setFixedWidth(32);
@@ -56,7 +60,7 @@ FileWidget::FileWidget(QWidget *parent) : QWidget(parent), m_filter("(*.*)"), m_
layout->addWidget(m_comboBox);
m_comboBox->setEditable(true);
layout->addWidget(m_pushButton);
- m_pushButton->setText("...");
+ m_pushButton->setText(QLatin1String("..."));
connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChanged()));
connect(m_pushButton, SIGNAL(released()), this, SLOT(onButtonReleased()));
connect(m_comboBox, SIGNAL(editTextChanged(QString)), this, SLOT(comboBoxChanged()));
@@ -126,7 +130,7 @@ void FileWidget::setupComboBox()
if (m_path.isValid())
dir = QDir(m_path.toLocalFile());
- QStringList filterList = m_filter.split(' ');
+ QStringList filterList = m_filter.split(QLatin1Char(' '));
QDirIterator it(dir.absolutePath(), filterList, QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
diff --git a/src/libs/qmleditorwidgets/filewidget.h b/src/libs/qmleditorwidgets/filewidget.h
index 4c65c83cfc..dca23b6465 100644
--- a/src/libs/qmleditorwidgets/filewidget.h
+++ b/src/libs/qmleditorwidgets/filewidget.h
@@ -31,7 +31,7 @@
#ifndef FILEWIDGET_H
#define FILEWIDGET_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QWidget>
diff --git a/src/libs/qmleditorwidgets/fontsizespinbox.cpp b/src/libs/qmleditorwidgets/fontsizespinbox.cpp
index e571bfcbac..dd53643223 100644
--- a/src/libs/qmleditorwidgets/fontsizespinbox.cpp
+++ b/src/libs/qmleditorwidgets/fontsizespinbox.cpp
@@ -64,16 +64,16 @@ QAbstractSpinBox::StepEnabled FontSizeSpinBox::stepEnabled() const
{
if (value() > 1)
return (StepUpEnabled | StepDownEnabled);
- else
+ else
return StepUpEnabled;
}
void FontSizeSpinBox::setText()
{
QString text = QString::number(m_value);
if (isPointSize())
- text.append(" pt");
+ text.append(QLatin1String(" pt"));
else
- text.append(" px");
+ text.append(QLatin1String(" px"));
lineEdit()->setText(text);
}
@@ -81,20 +81,20 @@ void FontSizeSpinBox::setText()
void FontSizeSpinBox::onEditingFinished()
{
QString str = lineEdit()->text();
- if (str.contains("px")) {
+ if (str.contains(QLatin1String("px"))) {
setIsPixelSize(true);
- str.remove("px");
+ str.remove(QLatin1String("px"));
setValue(str.toInt());
} else {
setIsPointSize(true);
- str.remove("pt");
+ str.remove(QLatin1String("pt"));
setValue(str.toInt());
}
}
QValidator::State FontSizeSpinBox::validate (QString &input, int &p) const
{
- QRegExp rx("\\d+\\s*(px|pt)");
+ QRegExp rx(QLatin1String("\\d+\\s*(px|pt)"));
QRegExpValidator v(rx, 0);
return v.validate(input, p);
}
diff --git a/src/libs/qmleditorwidgets/fontsizespinbox.h b/src/libs/qmleditorwidgets/fontsizespinbox.h
index 33fd388f12..ab79a2cde9 100644
--- a/src/libs/qmleditorwidgets/fontsizespinbox.h
+++ b/src/libs/qmleditorwidgets/fontsizespinbox.h
@@ -30,7 +30,7 @@
#ifndef FONTSIZESPINBOX_H
#define FONTSIZESPINBOX_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QAbstractSpinBox>
namespace QmlEditorWidgets {
diff --git a/src/libs/qmleditorwidgets/gradientline.cpp b/src/libs/qmleditorwidgets/gradientline.cpp
index 73f69d0d1a..c1f1cdf9e0 100644
--- a/src/libs/qmleditorwidgets/gradientline.cpp
+++ b/src/libs/qmleditorwidgets/gradientline.cpp
@@ -62,7 +62,7 @@ static inline QColor invertColor(const QColor color)
GradientLine::GradientLine(QWidget *parent) :
QWidget(parent),
m_activeColor(Qt::black),
- m_gradientName("gradient"),
+ m_gradientName(QLatin1String("gradient")),
m_colorIndex(0),
m_dragActive(false),
m_yOffset(0),
diff --git a/src/libs/qmleditorwidgets/gradientline.h b/src/libs/qmleditorwidgets/gradientline.h
index f2a21d855f..2324514967 100644
--- a/src/libs/qmleditorwidgets/gradientline.h
+++ b/src/libs/qmleditorwidgets/gradientline.h
@@ -30,7 +30,7 @@
#ifndef GRADIENTLINE_H
#define GRADIENTLINE_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QWidget>
#include <QLinearGradient>
diff --git a/src/libs/qmleditorwidgets/huecontrol.h b/src/libs/qmleditorwidgets/huecontrol.h
index fbc83a4411..957dd5f63d 100644
--- a/src/libs/qmleditorwidgets/huecontrol.h
+++ b/src/libs/qmleditorwidgets/huecontrol.h
@@ -30,7 +30,7 @@
#ifndef HUECONTROL_H
#define HUECONTROL_H
-#include <qmleditorwidgets_global.h>
+#include "qmleditorwidgets_global.h"
#include <QWidget>
#include <qdeclarative.h>
diff --git a/src/libs/qmleditorwidgets/qmleditorwidgets.pro b/src/libs/qmleditorwidgets/qmleditorwidgets.pro
index c449baac71..99eced9375 100644
--- a/src/libs/qmleditorwidgets/qmleditorwidgets.pro
+++ b/src/libs/qmleditorwidgets/qmleditorwidgets.pro
@@ -7,5 +7,6 @@ unix:QMAKE_CXXFLAGS_DEBUG += -O3
include(../../qtcreatorlibrary.pri)
include(../qmljs/qmljs.pri)
+include(../utils/utils.pri)
include(qmleditorwidgets-lib.pri)
diff --git a/src/libs/qmleditorwidgets/qmleditorwidgets.qbs b/src/libs/qmleditorwidgets/qmleditorwidgets.qbs
index 551056f6f5..19099b4156 100644
--- a/src/libs/qmleditorwidgets/qmleditorwidgets.qbs
+++ b/src/libs/qmleditorwidgets/qmleditorwidgets.qbs
@@ -4,11 +4,7 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "QmlEditorWidgets"
- cpp.includePaths: [
- ".",
- "..",
- "easingpane"
- ]
+ cpp.includePaths: base.concat("easingpane")
cpp.defines: base.concat([
"QWEAKPOINTER_ENABLE_ARROW",
"BUILD_QMLEDITORWIDGETS_LIB",
@@ -19,49 +15,45 @@ QtcLibrary {
Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "declarative", "script"] }
Depends { name: "QmlJS" }
+ Depends { name: "Utils" }
files: [
- "resources.qrc",
- "fontsizespinbox.h",
- "filewidget.h",
- "contextpanewidgetrectangle.h",
- "contextpanewidgetimage.h",
- "contextpanewidget.h",
- "contextpanetextwidget.h",
- "colorwidgets.h",
- "colorbutton.h",
+ "colorbox.cpp",
"colorbox.h",
+ "colorbutton.cpp",
+ "colorbutton.h",
+ "colorwidgets.cpp",
+ "colorwidgets.h",
+ "contextpanetext.ui",
+ "contextpanetextwidget.cpp",
+ "contextpanetextwidget.h",
+ "contextpanewidget.cpp",
+ "contextpanewidget.h",
+ "contextpanewidgetborderimage.ui",
+ "contextpanewidgetimage.cpp",
+ "contextpanewidgetimage.h",
+ "contextpanewidgetimage.ui",
+ "contextpanewidgetrectangle.cpp",
+ "contextpanewidgetrectangle.h",
+ "contextpanewidgetrectangle.ui",
+ "customcolordialog.cpp",
"customcolordialog.h",
+ "filewidget.cpp",
+ "filewidget.h",
+ "fontsizespinbox.cpp",
+ "fontsizespinbox.h",
+ "gradientline.cpp",
"gradientline.h",
+ "huecontrol.cpp",
"huecontrol.h",
"qmleditorwidgets_global.h",
- "fontsizespinbox.cpp",
- "filewidget.cpp",
- "contextpanewidgetrectangle.cpp",
- "contextpanewidgetimage.cpp",
- "contextpanewidget.cpp",
- "contextpanetextwidget.cpp",
- "colorwidgets.cpp",
- "colorbox.cpp",
- "customcolordialog.cpp",
- "huecontrol.cpp",
- "gradientline.cpp",
- "colorbutton.cpp",
- "contextpanewidgetrectangle.ui",
- "contextpanewidgetimage.ui",
- "contextpanewidgetborderimage.ui",
- "contextpanetext.ui",
- "easingpane/easinggraph.cpp",
+ "resources.qrc",
"easingpane/easingcontextpane.cpp",
- "easingpane/easinggraph.h",
"easingpane/easingcontextpane.h",
+ "easingpane/easingcontextpane.ui",
+ "easingpane/easinggraph.cpp",
+ "easingpane/easinggraph.h",
"easingpane/easingpane.qrc",
- "easingpane/easingcontextpane.ui"
]
-
- ProductModule {
- Depends { name: "cpp" }
- cpp.includePaths: ["."]
- }
}
diff --git a/src/libs/qmljs/consoleitem.cpp b/src/libs/qmljs/consoleitem.cpp
new file mode 100644
index 0000000000..9e9150d145
--- /dev/null
+++ b/src/libs/qmljs/consoleitem.cpp
@@ -0,0 +1,152 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "consoleitem.h"
+
+namespace QmlJS {
+
+///////////////////////////////////////////////////////////////////////
+//
+// ConsoleItem
+//
+///////////////////////////////////////////////////////////////////////
+
+ConsoleItem::ConsoleItem(ConsoleItem *parent, ConsoleItem::ItemType itemType,
+ const QString &text)
+ : m_parentItem(parent),
+ itemType(itemType),
+ line(-1)
+
+{
+ setText(text);
+}
+
+ConsoleItem::~ConsoleItem()
+{
+ qDeleteAll(m_childItems);
+}
+
+ConsoleItem *ConsoleItem::child(int number)
+{
+ return m_childItems.value(number);
+}
+
+int ConsoleItem::childCount() const
+{
+ return m_childItems.size();
+}
+
+int ConsoleItem::childNumber() const
+{
+ if (m_parentItem)
+ return m_parentItem->m_childItems.indexOf(const_cast<ConsoleItem *>(this));
+
+ return 0;
+}
+
+bool ConsoleItem::insertChildren(int position, int count)
+{
+ if (position < 0 || position > m_childItems.size())
+ return false;
+
+ for (int row = 0; row < count; ++row) {
+ ConsoleItem *item = new ConsoleItem(this, ConsoleItem::UndefinedType,
+ QString());
+ m_childItems.insert(position, item);
+ }
+
+ return true;
+}
+
+void ConsoleItem::insertChild(ConsoleItem *item, bool sorted)
+{
+ if (!sorted) {
+ m_childItems.insert(m_childItems.count(), item);
+ return;
+ }
+
+ int i = 0;
+ for (; i < m_childItems.count(); i++) {
+ if (item->m_text < m_childItems[i]->m_text)
+ break;
+ }
+ m_childItems.insert(i, item);
+}
+
+bool ConsoleItem::insertChild(int position, ConsoleItem *item)
+{
+ if (position < 0 || position > m_childItems.size())
+ return false;
+
+ m_childItems.insert(position, item);
+
+ return true;
+}
+
+ConsoleItem *ConsoleItem::parent()
+{
+ return m_parentItem;
+}
+
+bool ConsoleItem::removeChildren(int position, int count)
+{
+ if (position < 0 || position + count > m_childItems.size())
+ return false;
+
+ for (int row = 0; row < count; ++row)
+ delete m_childItems.takeAt(position);
+
+ return true;
+}
+
+bool ConsoleItem::detachChild(int position)
+{
+ if (position < 0 || position > m_childItems.size())
+ return false;
+
+ m_childItems.removeAt(position);
+
+ return true;
+}
+
+void ConsoleItem::setText(const QString &text)
+{
+ m_text = text;
+ for (int i = 0; i < m_text.length(); ++i) {
+ if (m_text.at(i).isPunct())
+ m_text.insert(++i, QChar(0x200b)); // ZERO WIDTH SPACE
+ }
+}
+
+const QString &ConsoleItem::text() const
+{
+ return m_text;
+}
+
+} // QmlJS
diff --git a/src/plugins/remotelinux/deployablefile.h b/src/libs/qmljs/consoleitem.h
index b63c626c66..4ad952ec1b 100644
--- a/src/plugins/remotelinux/deployablefile.h
+++ b/src/libs/qmljs/consoleitem.h
@@ -27,55 +27,58 @@
**
****************************************************************************/
-#ifndef DEPLOYABLEFILE_H
-#define DEPLOYABLEFILE_H
+#ifndef CONSOLEITEM_H
+#define CONSOLEITEM_H
-#include "remotelinux_export.h"
+#include "qmljs_global.h"
-#include <QFileInfo>
-#include <QHash>
+#include <QList>
#include <QString>
-namespace RemoteLinux {
+namespace QmlJS {
-class REMOTELINUX_EXPORT DeployableFile
+class QMLJS_EXPORT ConsoleItem
{
public:
- enum Type
+ enum ItemType
{
- TypeNormal,
- TypeExecutable
+ UndefinedType = 0x01, // Can be used for unknown and for Return values
+ DebugType = 0x02,
+ WarningType = 0x04,
+ ErrorType = 0x08,
+ InputType = 0x10,
+ DefaultTypes = InputType | UndefinedType
};
+ Q_DECLARE_FLAGS(ItemTypes, ItemType)
- DeployableFile() {}
+ ConsoleItem(ConsoleItem *parent,
+ ConsoleItem::ItemType type = ConsoleItem::UndefinedType,
+ const QString &data = QString());
+ ~ConsoleItem();
- DeployableFile(const QString &localFilePath, const QString &remoteDir, Type type = TypeNormal)
- : localFilePath(localFilePath), remoteDir(remoteDir), type(type) {}
+ ConsoleItem *child(int number);
+ int childCount() const;
+ bool insertChildren(int position, int count);
+ void insertChild(ConsoleItem *item, bool sorted);
+ bool insertChild(int position, ConsoleItem *item);
+ ConsoleItem *parent();
+ bool removeChildren(int position, int count);
+ bool detachChild(int position);
+ int childNumber() const;
+ void setText(const QString &text);
+ const QString &text() const;
- bool operator==(const DeployableFile &other) const
- {
- return localFilePath == other.localFilePath
- && remoteDir == other.remoteDir;
- }
-
- QString remoteFilePath() const {
- return remoteDir + QLatin1Char('/') + QFileInfo(localFilePath).fileName();
- }
-
- bool isExecutable() const {
- return type == TypeExecutable;
- }
+private:
+ ConsoleItem *m_parentItem;
+ QList<ConsoleItem *> m_childItems;
+ QString m_text;
- QString localFilePath;
- QString remoteDir;
- Type type;
+public:
+ ConsoleItem::ItemType itemType;
+ QString file;
+ int line;
};
-inline uint qHash(const DeployableFile &d)
-{
- return qHash(qMakePair(d.localFilePath, d.remoteDir));
-}
-
-} // namespace RemoteLinux
+} // QmlJS
-#endif // DEPLOYABLEFILE_H
+#endif // CONSOLEITEM_H
diff --git a/src/plugins/qmldesigner/extrasplugin/extrasplugin.cpp b/src/libs/qmljs/consolemanagerinterface.cpp
index 4aeb6b49a5..5aa6848c36 100644
--- a/src/plugins/qmldesigner/extrasplugin/extrasplugin.cpp
+++ b/src/libs/qmljs/consolemanagerinterface.cpp
@@ -27,30 +27,28 @@
**
****************************************************************************/
-#include "extrasplugin.h"
-#include <widgetplugin_helper.h>
-#include <QtPlugin>
+#include "consolemanagerinterface.h"
-namespace QmlDesigner {
+namespace QmlJS {
+static ConsoleManagerInterface *g_instance = 0;
-ExtrasPlugin::ExtrasPlugin()
+ConsoleManagerInterface::ConsoleManagerInterface(QObject *parent)
+ : QObject(parent)
{
+ Q_ASSERT(!g_instance);
+ g_instance = this;
}
-QString ExtrasPlugin::pluginName() const
+ConsoleManagerInterface::~ConsoleManagerInterface()
{
- return ("ExtrasPlugin");
+ Q_ASSERT(g_instance == this);
+ g_instance = 0;
}
-QString ExtrasPlugin::metaInfo() const
+ConsoleManagerInterface *ConsoleManagerInterface::instance()
{
- return QString(":/extrasplugin/extras.metainfo");
+ return g_instance;
}
-}
-
-#if QT_VERSION < 0x050000
-Q_EXPORT_PLUGIN(QmlDesigner::ExtrasPlugin)
-#endif
-
+} // QmlJS
diff --git a/src/libs/qmljs/consolemanagerinterface.h b/src/libs/qmljs/consolemanagerinterface.h
new file mode 100644
index 0000000000..4ee6067f29
--- /dev/null
+++ b/src/libs/qmljs/consolemanagerinterface.h
@@ -0,0 +1,64 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CONSOLEMANAGERINTERFACE_H
+#define CONSOLEMANAGERINTERFACE_H
+
+#include "qmljs_global.h"
+#include "consoleitem.h"
+
+#include <QObject>
+
+namespace QmlJS {
+
+class IScriptEvaluator;
+class QMLJS_EXPORT ConsoleManagerInterface : public QObject
+{
+ Q_OBJECT
+public:
+ ConsoleManagerInterface(QObject *parent = 0);
+ ~ConsoleManagerInterface();
+
+ static ConsoleManagerInterface *instance();
+
+ virtual void showConsolePane() = 0;
+
+ virtual ConsoleItem *rootItem() const = 0;
+
+ virtual void setScriptEvaluator(IScriptEvaluator *scriptEvaluator) = 0;
+ virtual void setContext(const QString &context) = 0;
+
+ virtual void printToConsolePane(ConsoleItem::ItemType itemType, const QString &text,
+ bool bringToForeground = false) = 0;
+ virtual void printToConsolePane(ConsoleItem *item, bool bringToForeground = false) = 0;
+};
+
+} // QmlJS
+
+#endif // CONSOLEMANAGERINTERFACE_H
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/QmlComponent02.qml b/src/libs/qmljs/iscriptevaluator.h
index 841ca4e869..79bb071bcb 100644
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/QmlComponent02.qml
+++ b/src/libs/qmljs/iscriptevaluator.h
@@ -27,19 +27,22 @@
**
****************************************************************************/
-import Qt 4.7
+#ifndef ISCRIPTEVALUATOR_H
+#define ISCRIPTEVALUATOR_H
-Rectangle {
- color: "#ffdddd"
+#include "qmljs_global.h"
- Image {
- source: "tomato.svg"
- anchors.right: parent.right
- anchors.bottom: parent.bottom
- }
+#include <QString>
- Text {
- text: "QmlComponent02"
- font.pointSize: 14
- }
-}
+namespace QmlJS {
+
+class IScriptEvaluator
+{
+public:
+ IScriptEvaluator() {}
+
+ virtual bool evaluateScript(const QString &script) = 0;
+};
+} // QmlJS
+
+#endif // ISCRIPTEVALUATOR_H
diff --git a/src/libs/qmljs/parser/gen-parser.sh b/src/libs/qmljs/parser/gen-parser.sh
index 1a755052e9..4f779f7cfc 100755
--- a/src/libs/qmljs/parser/gen-parser.sh
+++ b/src/libs/qmljs/parser/gen-parser.sh
@@ -1,5 +1,15 @@
#!/bin/bash
+# This is the script that generates the copy of the QmlJS parser from the sources
+# in the qtdeclarative source tree.
+#
+# It applies a bunch of renames to make the source compatible with the Qt Creator
+# sources as well as rewrites of the licenses.
+#
+# Example:
+# cd src/libs/qmljs/parser
+# QTDIR=~/path/to/qtdeclarative-checkout ./gen-parser.sh
+
me=$(dirname $0)
for i in $QTDIR/src/qml/qml/parser/*.{g,h,cpp,pri}; do
@@ -17,6 +27,8 @@ perl -p -0777 -i -e 's/#include <QtCore\/qglobal.h>\n\nQT_BEGIN_NAMESPACE\n\ncla
# remove qmlglobal_p.h include
perl -p -0777 -i -e 's/#include \"qmlglobal_p.h\"//' qmldirparser.cpp
# remove qmlglobal_p.h include
+perl -p -0777 -i -e 's/#include \"qmlglobal_p.h\"//' qmlerror.cpp
+# remove qmlglobal_p.h include
perl -p -0777 -i -e 's/#include \<QtQml\/qmlfile.h\>//' qmldirparser.cpp
# remove QtQml/qtqmlglobal.h include
perl -p -0777 -i -e 's/#include \<QtQml\/qtqmlglobal.h\>//' qmlerror.h
diff --git a/src/libs/qmljs/parser/parser.patch b/src/libs/qmljs/parser/parser.patch
index da87c056b0..4c56a5e2d5 100644
--- a/src/libs/qmljs/parser/parser.patch
+++ b/src/libs/qmljs/parser/parser.patch
@@ -1,8 +1,8 @@
-diff --git a/src/libs/qmljs/parser/qmljs.g b/src/libs/qmljs/parser/qmljs.g
-index 069be3c..9cbdc23 100644
---- a/src/libs/qmljs/parser/qmljs.g
-+++ b/src/libs/qmljs/parser/qmljs.g
-@@ -111,7 +111,7 @@ double integerFromString(const QString &str, int radix)
+diff --git a/src/libs/qmljs/parser/qmljsengine_p.cpp b/src/libs/qmljs/parser/qmljsengine_p.cpp
+index 73850bb..d7d2189 100644
+--- a/src/libs/qmljs/parser/qmljsengine_p.cpp
++++ b/src/libs/qmljs/parser/qmljsengine_p.cpp
+@@ -110,7 +110,7 @@ double integerFromString(const QString &str, int radix)
Engine::Engine()
@@ -11,7 +11,7 @@ index 069be3c..9cbdc23 100644
{ }
Engine::~Engine()
-@@ -132,6 +132,12 @@ Lexer *Engine::lexer() const
+@@ -131,6 +131,12 @@ Lexer *Engine::lexer() const
void Engine::setLexer(Lexer *lexer)
{ _lexer = lexer; }
@@ -24,11 +24,11 @@ index 069be3c..9cbdc23 100644
MemoryPool *Engine::pool()
{ return &_pool; }
-diff --git b/src/libs/qmljs/parser/qmljsengine_p.h a/src/libs/qmljs/parser/qmljsengine_p.h
-index 5057ea0..487619e 100644
---- b/src/libs/qmljs/parser/qmljsengine_p.h
-+++ a/src/libs/qmljs/parser/qmljsengine_p.h
-@@ -54,6 +54,7 @@ QT_QML_BEGIN_NAMESPACE
+diff --git a/src/libs/qmljs/parser/qmljsengine_p.h b/src/libs/qmljs/parser/qmljsengine_p.h
+index d4ed4b37..4908e02 100644
+--- a/src/libs/qmljs/parser/qmljsengine_p.h
++++ b/src/libs/qmljs/parser/qmljsengine_p.h
+@@ -53,6 +53,7 @@ QT_QML_BEGIN_NAMESPACE
namespace QmlJS {
class Lexer;
@@ -36,7 +36,7 @@ index 5057ea0..487619e 100644
class MemoryPool;
class QML_PARSER_EXPORT DiagnosticMessage
-@@ -81,6 +82,7 @@ public:
+@@ -80,6 +81,7 @@ public:
class QML_PARSER_EXPORT Engine
{
Lexer *_lexer;
@@ -44,7 +44,7 @@ index 5057ea0..487619e 100644
MemoryPool _pool;
QList<AST::SourceLocation> _comments;
QString _extraCode;
-@@ -98,6 +100,9 @@ public:
+@@ -97,6 +99,9 @@ public:
Lexer *lexer() const;
void setLexer(Lexer *lexer);
@@ -54,11 +54,11 @@ index 5057ea0..487619e 100644
MemoryPool *pool();
inline QStringRef midRef(int position, int size) { return _code.midRef(position, size); }
-diff --git b/src/libs/qmljs/parser/qmljsparser.cpp a/src/libs/qmljs/parser/qmljsparser.cpp
-index a731c1a..e986534 100644
---- b/src/libs/qmljs/parser/qmljsparser.cpp
-+++ a/src/libs/qmljs/parser/qmljsparser.cpp
-@@ -137,7 +137,20 @@ bool Parser::parse(int startToken)
+diff --git a/src/libs/qmljs/parser/qmljsparser.cpp b/src/libs/qmljs/parser/qmljsparser.cpp
+index d53960b..71e994f 100644
+--- a/src/libs/qmljs/parser/qmljsparser.cpp
++++ b/src/libs/qmljs/parser/qmljsparser.cpp
+@@ -143,7 +143,20 @@ bool Parser::parse(int startToken)
token_buffer[0].token = startToken;
first_token = &token_buffer[0];
@@ -80,3 +80,244 @@ index a731c1a..e986534 100644
tos = -1;
program = 0;
+diff --git a/src/libs/qmljs/parser/qmlerror.cpp b/src/libs/qmljs/parser/qmlerror.cpp
+index a244235..e334ae9 100644
+--- a/src/libs/qmljs/parser/qmlerror.cpp
++++ b/src/libs/qmljs/parser/qmlerror.cpp
+@@ -63,6 +63,12 @@ QT_BEGIN_NAMESPACE
+
+ \sa QQuickView::errors(), QmlComponent::errors()
+ */
++
++static quint16 qmlSourceCoordinate(int n)
++{
++ return (n > 0 && n <= static_cast<int>(USHRT_MAX)) ? static_cast<quint16>(n) : 0;
++}
++
+ class QmlErrorPrivate
+ {
+ public:
+diff --git a/src/libs/qmljs/parser/qmljskeywords_p.h b/src/libs/qmljs/parser/qmljskeywords_p.h
+index 3c827da..e981040 100644
+--- a/src/libs/qmljs/parser/qmljskeywords_p.h
++++ b/src/libs/qmljs/parser/qmljskeywords_p.h
+@@ -41,6 +41,12 @@
+ // We mean it.
+ //
+
++// Note on the int() casts in the following code:
++// they casts values from Lexer's anonymous enum (aliasing some of the inherited
++// QmlJSGrammar::VariousConstants) to int when used with inherited values of the
++// enum QmlJSGrammar::VariousConstants in a ?: expression to suppress gcc
++// "enumeral mismatch" warning
++
+ static inline int classify2(const QChar *s, bool qmlMode) {
+ if (s[0].unicode() == 'a') {
+ if (s[1].unicode() == 's') {
+@@ -79,7 +85,7 @@ static inline int classify3(const QChar *s, bool qmlMode) {
+ else if (s[0].unicode() == 'i') {
+ if (s[1].unicode() == 'n') {
+ if (s[2].unicode() == 't') {
+- return qmlMode ? Lexer::T_INT : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_INT) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -112,7 +118,7 @@ static inline int classify4(const QChar *s, bool qmlMode) {
+ if (s[1].unicode() == 'y') {
+ if (s[2].unicode() == 't') {
+ if (s[3].unicode() == 'e') {
+- return qmlMode ? Lexer::T_BYTE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_BYTE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -128,7 +134,7 @@ static inline int classify4(const QChar *s, bool qmlMode) {
+ else if (s[1].unicode() == 'h') {
+ if (s[2].unicode() == 'a') {
+ if (s[3].unicode() == 'r') {
+- return qmlMode ? Lexer::T_CHAR : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_CHAR) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -153,7 +159,7 @@ static inline int classify4(const QChar *s, bool qmlMode) {
+ if (s[1].unicode() == 'o') {
+ if (s[2].unicode() == 't') {
+ if (s[3].unicode() == 'o') {
+- return qmlMode ? Lexer::T_GOTO : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_GOTO) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -162,7 +168,7 @@ static inline int classify4(const QChar *s, bool qmlMode) {
+ if (s[1].unicode() == 'o') {
+ if (s[2].unicode() == 'n') {
+ if (s[3].unicode() == 'g') {
+- return qmlMode ? Lexer::T_LONG : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_LONG) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -268,7 +274,7 @@ static inline int classify5(const QChar *s, bool qmlMode) {
+ if (s[2].unicode() == 'n') {
+ if (s[3].unicode() == 'a') {
+ if (s[4].unicode() == 'l') {
+- return qmlMode ? Lexer::T_FINAL : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_FINAL) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -277,7 +283,7 @@ static inline int classify5(const QChar *s, bool qmlMode) {
+ if (s[2].unicode() == 'o') {
+ if (s[3].unicode() == 'a') {
+ if (s[4].unicode() == 't') {
+- return qmlMode ? Lexer::T_FLOAT : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_FLOAT) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -288,7 +294,7 @@ static inline int classify5(const QChar *s, bool qmlMode) {
+ if (s[2].unicode() == 'o') {
+ if (s[3].unicode() == 'r') {
+ if (s[4].unicode() == 't') {
+- return qmlMode ? Lexer::T_SHORT : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_SHORT) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -297,7 +303,7 @@ static inline int classify5(const QChar *s, bool qmlMode) {
+ if (s[2].unicode() == 'p') {
+ if (s[3].unicode() == 'e') {
+ if (s[4].unicode() == 'r') {
+- return qmlMode ? Lexer::T_SUPER : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_SUPER) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -346,7 +352,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
+ if (s[3].unicode() == 'b') {
+ if (s[4].unicode() == 'l') {
+ if (s[5].unicode() == 'e') {
+- return qmlMode ? Lexer::T_DOUBLE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_DOUBLE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -385,7 +391,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
+ if (s[3].unicode() == 'i') {
+ if (s[4].unicode() == 'v') {
+ if (s[5].unicode() == 'e') {
+- return qmlMode ? Lexer::T_NATIVE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_NATIVE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -435,7 +441,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
+ if (s[3].unicode() == 't') {
+ if (s[4].unicode() == 'i') {
+ if (s[5].unicode() == 'c') {
+- return qmlMode ? Lexer::T_STATIC : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_STATIC) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -459,7 +465,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
+ if (s[3].unicode() == 'o') {
+ if (s[4].unicode() == 'w') {
+ if (s[5].unicode() == 's') {
+- return qmlMode ? Lexer::T_THROWS : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_THROWS) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -488,7 +494,7 @@ static inline int classify7(const QChar *s, bool qmlMode) {
+ if (s[4].unicode() == 'e') {
+ if (s[5].unicode() == 'a') {
+ if (s[6].unicode() == 'n') {
+- return qmlMode ? Lexer::T_BOOLEAN : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_BOOLEAN) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -548,7 +554,7 @@ static inline int classify7(const QChar *s, bool qmlMode) {
+ if (s[4].unicode() == 'a') {
+ if (s[5].unicode() == 'g') {
+ if (s[6].unicode() == 'e') {
+- return qmlMode ? Lexer::T_PACKAGE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_PACKAGE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -561,7 +567,7 @@ static inline int classify7(const QChar *s, bool qmlMode) {
+ if (s[4].unicode() == 'a') {
+ if (s[5].unicode() == 't') {
+ if (s[6].unicode() == 'e') {
+- return qmlMode ? Lexer::T_PRIVATE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_PRIVATE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -581,7 +587,7 @@ static inline int classify8(const QChar *s, bool qmlMode) {
+ if (s[5].unicode() == 'a') {
+ if (s[6].unicode() == 'c') {
+ if (s[7].unicode() == 't') {
+- return qmlMode ? Lexer::T_ABSTRACT : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_ABSTRACT) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -683,7 +689,7 @@ static inline int classify8(const QChar *s, bool qmlMode) {
+ if (s[5].unicode() == 'i') {
+ if (s[6].unicode() == 'l') {
+ if (s[7].unicode() == 'e') {
+- return qmlMode ? Lexer::T_VOLATILE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_VOLATILE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -705,7 +711,7 @@ static inline int classify9(const QChar *s, bool qmlMode) {
+ if (s[6].unicode() == 'a') {
+ if (s[7].unicode() == 'c') {
+ if (s[8].unicode() == 'e') {
+- return qmlMode ? Lexer::T_INTERFACE : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_INTERFACE) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -724,7 +730,7 @@ static inline int classify9(const QChar *s, bool qmlMode) {
+ if (s[6].unicode() == 't') {
+ if (s[7].unicode() == 'e') {
+ if (s[8].unicode() == 'd') {
+- return qmlMode ? Lexer::T_PROTECTED : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_PROTECTED) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -743,7 +749,7 @@ static inline int classify9(const QChar *s, bool qmlMode) {
+ if (s[6].unicode() == 'e') {
+ if (s[7].unicode() == 'n') {
+ if (s[8].unicode() == 't') {
+- return qmlMode ? Lexer::T_TRANSIENT : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_TRANSIENT) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -767,7 +773,7 @@ static inline int classify10(const QChar *s, bool qmlMode) {
+ if (s[7].unicode() == 'n') {
+ if (s[8].unicode() == 't') {
+ if (s[9].unicode() == 's') {
+- return qmlMode ? Lexer::T_IMPLEMENTS : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_IMPLEMENTS) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
+@@ -813,7 +819,7 @@ static inline int classify12(const QChar *s, bool qmlMode) {
+ if (s[9].unicode() == 'z') {
+ if (s[10].unicode() == 'e') {
+ if (s[11].unicode() == 'd') {
+- return qmlMode ? Lexer::T_SYNCHRONIZED : Lexer::T_IDENTIFIER;
++ return qmlMode ? int(Lexer::T_SYNCHRONIZED) : Lexer::T_IDENTIFIER;
+ }
+ }
+ }
diff --git a/src/libs/qmljs/parser/parser.pri b/src/libs/qmljs/parser/parser.pri
index aa1069e5c2..4a9242a845 100644
--- a/src/libs/qmljs/parser/parser.pri
+++ b/src/libs/qmljs/parser/parser.pri
@@ -21,3 +21,6 @@ SOURCES += \
$$PWD/qmljsparser.cpp \
$$PWD/qmldirparser.cpp \
$$PWD/qmlerror.cpp \
+
+OTHER_FILES += \
+ $$PWD/qmljs.g
diff --git a/src/libs/qmljs/parser/qmldirparser.cpp b/src/libs/qmljs/parser/qmldirparser.cpp
index cd08a96adf..7e2fcfeaf4 100644
--- a/src/libs/qmljs/parser/qmldirparser.cpp
+++ b/src/libs/qmljs/parser/qmldirparser.cpp
@@ -32,7 +32,7 @@
-#include <QtCore/QDebug>
+#include <QtCore/QtDebug>
QT_BEGIN_NAMESPACE
@@ -86,7 +86,7 @@ bool QmlDirParser::parse(const QString &source)
_components.clear();
_scripts.clear();
- int lineNumber = 0;
+ quint16 lineNumber = 0;
bool firstLine = true;
const QChar *ch = source.constData();
@@ -129,7 +129,7 @@ bool QmlDirParser::parse(const QString &source)
++ch;
if (invalidLine) {
- reportError(lineNumber, -1,
+ reportError(lineNumber, 0,
QString::fromUtf8("invalid qmldir directive contains too many tokens"));
continue;
} else if (sectionCount == 0) {
@@ -137,18 +137,18 @@ bool QmlDirParser::parse(const QString &source)
} else if (sections[0] == QLatin1String("module")) {
if (sectionCount != 2) {
- reportError(lineNumber, -1,
- QString::fromUtf8("module directive requires one argument, but %1 were provided").arg(sectionCount - 1));
+ reportError(lineNumber, 0,
+ QString::fromUtf8("module identifier directive requires one argument, but %1 were provided").arg(sectionCount - 1));
continue;
}
if (!_typeNamespace.isEmpty()) {
- reportError(lineNumber, -1,
- QString::fromUtf8("only one module directive may be defined in a qmldir file"));
+ reportError(lineNumber, 0,
+ QString::fromUtf8("only one module identifier directive may be defined in a qmldir file"));
continue;
}
if (!firstLine) {
- reportError(lineNumber, -1,
- QString::fromUtf8("module directive must be the first directive in a qmldir file"));
+ reportError(lineNumber, 0,
+ QString::fromUtf8("module identifier directive must be the first command in a qmldir file"));
continue;
}
@@ -156,7 +156,7 @@ bool QmlDirParser::parse(const QString &source)
} else if (sections[0] == QLatin1String("plugin")) {
if (sectionCount < 2) {
- reportError(lineNumber, -1,
+ reportError(lineNumber, 0,
QString::fromUtf8("plugin directive requires one or two arguments, but %1 were provided").arg(sectionCount - 1));
continue;
@@ -168,7 +168,7 @@ bool QmlDirParser::parse(const QString &source)
} else if (sections[0] == QLatin1String("internal")) {
if (sectionCount != 3) {
- reportError(lineNumber, -1,
+ reportError(lineNumber, 0,
QString::fromUtf8("internal types require 2 arguments, but %1 were provided").arg(sectionCount - 1));
continue;
}
@@ -177,7 +177,7 @@ bool QmlDirParser::parse(const QString &source)
_components.insertMulti(entry.typeName, entry);
} else if (sections[0] == QLatin1String("typeinfo")) {
if (sectionCount != 2) {
- reportError(lineNumber, -1,
+ reportError(lineNumber, 0,
QString::fromUtf8("typeinfo requires 1 argument, but %1 were provided").arg(sectionCount - 1));
continue;
}
@@ -195,9 +195,9 @@ bool QmlDirParser::parse(const QString &source)
const int dotIndex = version.indexOf(QLatin1Char('.'));
if (dotIndex == -1) {
- reportError(lineNumber, -1, QLatin1String("expected '.'"));
+ reportError(lineNumber, 0, QLatin1String("expected '.'"));
} else if (version.indexOf(QLatin1Char('.'), dotIndex + 1) != -1) {
- reportError(lineNumber, -1, QLatin1String("unexpected '.'"));
+ reportError(lineNumber, 0, QLatin1String("unexpected '.'"));
} else {
bool validVersionNumber = false;
const int majorVersion = parseInt(QStringRef(&version, 0, dotIndex), &validVersionNumber);
@@ -220,7 +220,7 @@ bool QmlDirParser::parse(const QString &source)
}
}
} else {
- reportError(lineNumber, -1,
+ reportError(lineNumber, 0,
QString::fromUtf8("a component declaration requires two or three arguments, but %1 were provided").arg(sectionCount));
}
@@ -230,7 +230,7 @@ bool QmlDirParser::parse(const QString &source)
return hasError();
}
-void QmlDirParser::reportError(int line, int column, const QString &description)
+void QmlDirParser::reportError(quint16 line, quint16 column, const QString &description)
{
QmlError error;
error.setLine(line);
diff --git a/src/libs/qmljs/parser/qmldirparser_p.h b/src/libs/qmljs/parser/qmldirparser_p.h
index f3474dc92f..9262800f31 100644
--- a/src/libs/qmljs/parser/qmldirparser_p.h
+++ b/src/libs/qmljs/parser/qmldirparser_p.h
@@ -128,7 +128,7 @@ public:
#endif
private:
- void reportError(int line, int column, const QString &message);
+ void reportError(quint16 line, quint16 column, const QString &message);
private:
QList<QmlError> _errors;
diff --git a/src/libs/qmljs/parser/qmlerror.cpp b/src/libs/qmljs/parser/qmlerror.cpp
index da9328b57f..cd81100d1e 100644
--- a/src/libs/qmljs/parser/qmlerror.cpp
+++ b/src/libs/qmljs/parser/qmlerror.cpp
@@ -29,6 +29,7 @@
#include "qmlerror.h"
+
#include <QtCore/qdebug.h>
#include <QtCore/qfile.h>
#include <QtCore/qstringlist.h>
@@ -62,6 +63,12 @@ QT_BEGIN_NAMESPACE
\sa QQuickView::errors(), QmlComponent::errors()
*/
+
+static quint16 qmlSourceCoordinate(int n)
+{
+ return (n > 0 && n <= static_cast<int>(USHRT_MAX)) ? static_cast<quint16>(n) : 0;
+}
+
class QmlErrorPrivate
{
public:
@@ -69,12 +76,12 @@ public:
QUrl url;
QString description;
- int line;
- int column;
+ quint16 line;
+ quint16 column;
};
QmlErrorPrivate::QmlErrorPrivate()
-: line(-1), column(-1)
+: line(0), column(0)
{
}
@@ -170,7 +177,7 @@ void QmlError::setDescription(const QString &description)
*/
int QmlError::line() const
{
- if (d) return d->line;
+ if (d) return qmlSourceCoordinate(d->line);
else return -1;
}
@@ -180,7 +187,7 @@ int QmlError::line() const
void QmlError::setLine(int line)
{
if (!d) d = new QmlErrorPrivate;
- d->line = line;
+ d->line = qmlSourceCoordinate(line);
}
/*!
@@ -188,7 +195,7 @@ void QmlError::setLine(int line)
*/
int QmlError::column() const
{
- if (d) return d->column;
+ if (d) return qmlSourceCoordinate(d->column);
else return -1;
}
@@ -198,7 +205,7 @@ int QmlError::column() const
void QmlError::setColumn(int column)
{
if (!d) d = new QmlErrorPrivate;
- d->column = column;
+ d->column = qmlSourceCoordinate(column);
}
/*!
@@ -207,14 +214,20 @@ void QmlError::setColumn(int column)
QString QmlError::toString() const
{
QString rv;
- if (url().isEmpty()) {
+
+ QUrl u(url());
+ int l(line());
+
+ if (u.isEmpty()) {
rv = QLatin1String("<Unknown File>");
- } else if (line() != -1) {
- rv = url().toString() + QLatin1Char(':') + QString::number(line());
- if(column() != -1)
- rv += QLatin1Char(':') + QString::number(column());
+ } else if (l != -1) {
+ rv = u.toString() + QLatin1Char(':') + QString::number(l);
+
+ int c(column());
+ if (c != -1)
+ rv += QLatin1Char(':') + QString::number(c);
} else {
- rv = url().toString();
+ rv = u.toString();
}
rv += QLatin1String(": ") + description();
diff --git a/src/libs/qmljs/parser/qmljs.g b/src/libs/qmljs/parser/qmljs.g
index b6541250ea..66e1fd204b 100644
--- a/src/libs/qmljs/parser/qmljs.g
+++ b/src/libs/qmljs/parser/qmljs.g
@@ -1,37 +1,29 @@
------------------------------------------------------------------------------
+----------------------------------------------------------------------------
--
-- Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-- Contact: http://www.qt-project.org/legal
--
--- This file is part of Qt Creator.
---
--- Commercial License Usage
--- Licensees holding valid commercial Qt licenses may use this file in
--- accordance with the commercial license agreement provided with the
--- Software or, alternatively, in accordance with the terms contained in
--- a written agreement between you and Digia. For licensing terms and
--- conditions see http://qt.digia.com/licensing. For further information
--- use the contact form at http://qt.digia.com/contact-us.
+-- This file is part of the QtQml module of the Qt Toolkit.
--
+-- $QT_BEGIN_LICENSE:LGPL-ONLY$
-- GNU Lesser General Public License Usage
--- Alternatively, this file may be used under the terms of the GNU Lesser
+-- This file may be used under the terms of the GNU Lesser
-- General Public License version 2.1 as published by the Free Software
-- Foundation and appearing in the file LICENSE.LGPL included in the
-- packaging of this file. Please review the following information to
-- ensure the GNU Lesser General Public License version 2.1 requirements
-- will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
--
--- In addition, as a special exception, Digia gives you certain additional
--- rights. These rights are described in the Digia Qt LGPL Exception
--- version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+-- If you have questions regarding the use of this file, please contact
+-- us via http://www.qt-project.org/.
--
------------------------------------------------------------------------------
-
-
+-- $QT_END_LICENSE$
+--
+----------------------------------------------------------------------------
%parser QmlJSGrammar
%decl qmljsparser_p.h
-%impl qdeclarativejsparser.cpp
+%impl qmljsparser.cpp
%expect 2
%expect-rr 2
@@ -68,6 +60,7 @@
%token T_RESERVED_WORD "reserved word"
%token T_MULTILINE_STRING_LITERAL "multiline string literal"
%token T_COMMENT "comment"
+%token T_COMPATIBILITY_SEMICOLON
--- context keywords.
%token T_PUBLIC "public"
@@ -96,8 +89,9 @@
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
-** This file is part of Qt Creator.
+** This file is part of the QtQml module of the Qt Toolkit.
**
+** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
@@ -118,10 +112,20 @@
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
****************************************************************************/
-
-#include <QtCore/QDebug>
+#include <QtCore/QtDebug>
#include <QtCore/QCoreApplication>
#include <string.h>
@@ -138,8 +142,9 @@
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
-** This file is part of Qt Creator.
+** This file is part of the QtQml module of the Qt Toolkit.
**
+** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
@@ -160,10 +165,20 @@
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
****************************************************************************/
-
//
// W A R N I N G
// -------------
@@ -176,8 +191,15 @@
//
//
+// W A R N I N G
+// -------------
+//
// This file is automatically generated from qmljs.g.
-// Changes will be lost.
+// Changes should be made to that file, not here. Any change to this file will
+// be lost!
+//
+// To regenerate this file, run:
+// qlalr --no-debug --no-lines --qt qmljs.g
//
#ifndef QMLJSPARSER_P_H
@@ -369,8 +391,15 @@ protected:
#include <QVarLengthArray>
//
+// W A R N I N G
+// -------------
+//
// This file is automatically generated from qmljs.g.
-// Changes will be lost.
+// Changes should be made to that file, not here. Any change to this file will
+// be lost!
+//
+// To regenerate this file, run:
+// qlalr --no-debug --no-lines --qt qmljs.g
//
using namespace QmlJS;
@@ -2411,6 +2440,7 @@ case $rule_number: {
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_COMPATIBILITY_SEMICOLON ; -- for JSC/V8 compatibility
IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_SEMICOLON ;
/.
case $rule_number: {
@@ -2875,7 +2905,8 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ;
const int errorState = state_stack[tos];
// automatic insertion of `;'
- if (yytoken != -1 && t_action(errorState, T_AUTOMATIC_SEMICOLON) && lexer->canInsertAutomaticSemicolon(yytoken)) {
+ if (yytoken != -1 && ((t_action(errorState, T_AUTOMATIC_SEMICOLON) && lexer->canInsertAutomaticSemicolon(yytoken))
+ || t_action(errorState, T_COMPATIBILITY_SEMICOLON))) {
SavedToken &tk = token_buffer[0];
tk.token = yytoken;
tk.dval = yylval;
@@ -2887,7 +2918,7 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ;
yylloc.startColumn += yylloc.length;
yylloc.length = 0;
- //const QString msg = qApp->translate("QQmlParser", "Missing `;'");
+ //const QString msg = qApp->translate("QmlParser", "Missing `;'");
//diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg));
first_token = &token_buffer[0];
@@ -2917,9 +2948,9 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ;
QString msg;
int token = token_buffer[0].token;
if (token < 0 || token >= TERMINAL_COUNT)
- msg = qApp->translate("QQmlParser", "Syntax error");
+ msg = qApp->translate("QmlParser", "Syntax error");
else
- msg = qApp->translate("QQmlParser", "Unexpected token `%1'").arg(QLatin1String(spell[token]));
+ msg = qApp->translate("QmlParser", "Unexpected token `%1'").arg(QLatin1String(spell[token]));
diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
action = errorState;
@@ -2947,7 +2978,7 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ;
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("QQmlParser", "Expected token `%1'").arg(QLatin1String(spell[*tk]));
+ 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;
@@ -2971,7 +3002,7 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ;
int a = t_action(errorState, tk);
if (a > 0 && t_action(a, yytoken)) {
- const QString msg = qApp->translate("QQmlParser", "Expected token `%1'").arg(QLatin1String(spell[tk]));
+ 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;
@@ -2984,7 +3015,7 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ;
}
}
- const QString msg = qApp->translate("QQmlParser", "Syntax error");
+ const QString msg = qApp->translate("QmlParser", "Syntax error");
diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg));
}
diff --git a/src/libs/qmljs/parser/qmljsgrammar.cpp b/src/libs/qmljs/parser/qmljsgrammar.cpp
index 3fce7c54f0..39bfad5c1b 100644
--- a/src/libs/qmljs/parser/qmljsgrammar.cpp
+++ b/src/libs/qmljs/parser/qmljsgrammar.cpp
@@ -41,46 +41,46 @@ const char *const QmlJSGrammar::spell [] = {
"||", "+", "+=", "++", "?", "}", "]", "%", "%=", "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", "on", 0, 0, 0, 0, 0, 0, 0,
- 0, 0};
+ "^=", "null", "true", "false", "const", "debugger", "reserved word", "multiline string literal", "comment", 0,
+ "public", "import", "as", "on", 0, 0, 0, 0, 0, 0,
+ 0, 0, 0};
const short QmlJSGrammar::lhs [] = {
- 102, 102, 102, 102, 102, 102, 103, 109, 109, 112,
- 112, 114, 113, 113, 113, 113, 113, 113, 113, 113,
- 116, 111, 110, 119, 119, 120, 120, 121, 121, 118,
- 107, 107, 107, 107, 123, 123, 123, 123, 123, 123,
- 123, 107, 131, 131, 131, 132, 132, 133, 133, 107,
- 107, 107, 107, 107, 107, 107, 107, 107, 107, 107,
- 107, 107, 107, 107, 107, 107, 117, 117, 117, 117,
- 117, 136, 136, 136, 136, 136, 136, 136, 136, 136,
- 136, 136, 136, 136, 136, 136, 136, 136, 136, 122,
- 138, 138, 138, 138, 137, 137, 140, 140, 142, 142,
- 142, 142, 142, 142, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 143, 143, 143, 143, 143,
- 143, 143, 143, 143, 143, 144, 144, 115, 115, 115,
- 115, 115, 147, 147, 148, 148, 148, 148, 146, 146,
- 149, 149, 150, 150, 151, 151, 151, 152, 152, 152,
- 152, 152, 152, 152, 152, 152, 152, 153, 153, 153,
- 153, 154, 154, 154, 155, 155, 155, 155, 156, 156,
- 156, 156, 156, 156, 156, 157, 157, 157, 157, 157,
- 157, 158, 158, 158, 158, 158, 159, 159, 159, 159,
- 159, 160, 160, 161, 161, 162, 162, 163, 163, 164,
- 164, 165, 165, 166, 166, 167, 167, 168, 168, 169,
- 169, 170, 170, 171, 171, 141, 141, 172, 172, 173,
- 173, 173, 173, 173, 173, 173, 173, 173, 173, 173,
- 173, 105, 105, 174, 174, 175, 175, 176, 176, 104,
- 104, 104, 104, 104, 104, 104, 104, 104, 104, 104,
- 104, 104, 104, 104, 124, 185, 185, 184, 184, 135,
- 135, 186, 186, 187, 187, 189, 189, 188, 190, 193,
- 191, 191, 194, 192, 192, 125, 126, 126, 127, 127,
- 177, 177, 177, 177, 177, 177, 177, 178, 178, 178,
- 178, 179, 179, 179, 179, 180, 180, 128, 129, 195,
- 195, 198, 198, 196, 196, 199, 197, 181, 181, 181,
- 182, 182, 130, 130, 130, 200, 201, 183, 183, 134,
- 145, 205, 205, 202, 202, 203, 203, 206, 108, 108,
- 207, 207, 106, 106, 204, 204, 139, 139, 208};
+ 103, 103, 103, 103, 103, 103, 104, 110, 110, 113,
+ 113, 115, 114, 114, 114, 114, 114, 114, 114, 114,
+ 117, 112, 111, 120, 120, 121, 121, 122, 122, 119,
+ 108, 108, 108, 108, 124, 124, 124, 124, 124, 124,
+ 124, 108, 132, 132, 132, 133, 133, 134, 134, 108,
+ 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
+ 108, 108, 108, 108, 108, 108, 118, 118, 118, 118,
+ 118, 137, 137, 137, 137, 137, 137, 137, 137, 137,
+ 137, 137, 137, 137, 137, 137, 137, 137, 137, 123,
+ 139, 139, 139, 139, 138, 138, 141, 141, 143, 143,
+ 143, 143, 143, 143, 144, 144, 144, 144, 144, 144,
+ 144, 144, 144, 144, 144, 144, 144, 144, 144, 144,
+ 144, 144, 144, 144, 144, 144, 144, 144, 144, 144,
+ 144, 144, 144, 144, 144, 145, 145, 116, 116, 116,
+ 116, 116, 148, 148, 149, 149, 149, 149, 147, 147,
+ 150, 150, 151, 151, 152, 152, 152, 153, 153, 153,
+ 153, 153, 153, 153, 153, 153, 153, 154, 154, 154,
+ 154, 155, 155, 155, 156, 156, 156, 156, 157, 157,
+ 157, 157, 157, 157, 157, 158, 158, 158, 158, 158,
+ 158, 159, 159, 159, 159, 159, 160, 160, 160, 160,
+ 160, 161, 161, 162, 162, 163, 163, 164, 164, 165,
+ 165, 166, 166, 167, 167, 168, 168, 169, 169, 170,
+ 170, 171, 171, 172, 172, 142, 142, 173, 173, 174,
+ 174, 174, 174, 174, 174, 174, 174, 174, 174, 174,
+ 174, 106, 106, 175, 175, 176, 176, 177, 177, 105,
+ 105, 105, 105, 105, 105, 105, 105, 105, 105, 105,
+ 105, 105, 105, 105, 125, 186, 186, 185, 185, 136,
+ 136, 187, 187, 188, 188, 190, 190, 189, 191, 194,
+ 192, 192, 195, 193, 193, 126, 127, 127, 128, 128,
+ 178, 178, 178, 178, 178, 178, 178, 178, 179, 179,
+ 179, 179, 180, 180, 180, 180, 181, 181, 129, 130,
+ 196, 196, 199, 199, 197, 197, 200, 198, 182, 182,
+ 182, 183, 183, 131, 131, 131, 201, 202, 184, 184,
+ 135, 146, 206, 206, 203, 203, 204, 204, 207, 109,
+ 109, 208, 208, 107, 107, 205, 205, 140, 140, 209};
const short QmlJSGrammar::rhs [] = {
2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
@@ -112,18 +112,18 @@ const short QmlJSGrammar::rhs [] = {
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,
- 1, 2, 1, 1, 0, 1, 0, 1, 2};
+ 7, 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, 1, 2, 1, 1, 0, 1, 0, 1, 2};
const short QmlJSGrammar::action_default [] = {
0, 0, 22, 0, 0, 0, 22, 0, 175, 242,
206, 214, 210, 154, 226, 202, 3, 139, 73, 155,
218, 222, 143, 172, 153, 158, 138, 192, 179, 0,
- 80, 81, 76, 345, 67, 347, 0, 0, 0, 0,
+ 80, 81, 76, 346, 67, 348, 0, 0, 0, 0,
78, 0, 0, 74, 77, 71, 0, 0, 68, 70,
69, 79, 72, 0, 75, 0, 0, 168, 0, 0,
155, 174, 157, 156, 0, 0, 0, 170, 171, 169,
@@ -138,347 +138,348 @@ const short QmlJSGrammar::action_default [] = {
0, 239, 232, 230, 237, 238, 236, 235, 241, 234,
233, 231, 240, 227, 0, 215, 0, 0, 219, 0,
0, 223, 0, 0, 149, 141, 0, 140, 0, 145,
- 159, 0, 346, 334, 335, 0, 332, 0, 333, 0,
- 336, 250, 257, 256, 264, 252, 0, 253, 337, 0,
- 344, 254, 255, 260, 258, 341, 338, 343, 261, 0,
- 272, 0, 0, 0, 0, 345, 67, 0, 347, 68,
+ 159, 0, 347, 335, 336, 0, 333, 0, 334, 0,
+ 337, 250, 257, 256, 264, 252, 0, 253, 338, 0,
+ 345, 254, 255, 260, 258, 342, 339, 344, 261, 0,
+ 272, 0, 0, 0, 0, 346, 67, 0, 348, 68,
244, 286, 69, 0, 0, 0, 273, 0, 0, 262,
- 263, 0, 251, 259, 287, 288, 331, 342, 0, 302,
- 303, 304, 305, 0, 298, 299, 300, 301, 328, 329,
- 0, 0, 0, 0, 0, 291, 292, 248, 246, 208,
- 216, 212, 228, 204, 249, 0, 155, 220, 224, 197,
- 186, 0, 0, 205, 0, 0, 0, 0, 198, 0,
- 0, 0, 0, 0, 190, 188, 191, 189, 187, 200,
- 199, 201, 0, 213, 0, 209, 0, 247, 155, 0,
- 229, 244, 245, 0, 244, 0, 0, 294, 0, 0,
- 0, 296, 0, 217, 0, 0, 221, 0, 0, 225,
- 284, 0, 276, 285, 279, 0, 283, 0, 244, 277,
- 0, 244, 0, 0, 295, 0, 0, 0, 297, 346,
- 334, 0, 0, 336, 0, 330, 0, 320, 0, 0,
- 0, 290, 0, 289, 0, 348, 0, 104, 266, 269,
- 0, 105, 272, 108, 133, 110, 111, 76, 115, 116,
- 67, 117, 120, 74, 77, 68, 244, 69, 79, 123,
- 72, 125, 75, 127, 128, 273, 130, 131, 135, 0,
- 97, 0, 0, 99, 103, 101, 88, 100, 102, 0,
- 98, 87, 267, 265, 143, 144, 149, 0, 142, 0,
- 319, 0, 306, 307, 0, 318, 0, 0, 0, 309,
- 314, 312, 315, 0, 0, 313, 314, 0, 310, 0,
- 311, 268, 317, 0, 268, 316, 0, 321, 322, 0,
- 268, 323, 324, 0, 0, 325, 0, 0, 0, 326,
- 327, 161, 160, 0, 0, 0, 293, 0, 0, 0,
- 308, 281, 274, 0, 282, 278, 0, 280, 270, 0,
- 271, 275, 91, 0, 0, 95, 82, 0, 84, 93,
- 0, 85, 94, 96, 86, 92, 83, 0, 89, 165,
- 163, 167, 164, 162, 166, 339, 6, 340, 4, 2,
- 65, 90, 0, 0, 68, 70, 69, 31, 5, 0,
- 66, 0, 45, 44, 43, 0, 0, 58, 0, 59,
- 35, 36, 37, 38, 40, 41, 62, 39, 0, 45,
- 0, 0, 0, 0, 0, 54, 0, 55, 0, 0,
- 26, 0, 0, 63, 27, 0, 30, 28, 24, 0,
- 29, 25, 0, 56, 0, 57, 143, 0, 60, 64,
- 0, 0, 0, 0, 61, 0, 52, 46, 53, 47,
- 0, 0, 0, 0, 49, 0, 50, 51, 48, 0,
- 0, 143, 268, 0, 0, 42, 105, 272, 108, 133,
- 110, 111, 76, 115, 116, 67, 117, 120, 74, 77,
- 68, 244, 69, 79, 123, 72, 125, 75, 127, 128,
- 273, 130, 131, 135, 0, 32, 33, 0, 34, 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, 349};
+ 263, 0, 251, 259, 287, 288, 332, 343, 0, 303,
+ 304, 305, 306, 0, 299, 300, 301, 302, 329, 330,
+ 0, 0, 0, 0, 0, 291, 292, 293, 248, 246,
+ 208, 216, 212, 228, 204, 249, 0, 155, 220, 224,
+ 197, 186, 0, 0, 205, 0, 0, 0, 0, 198,
+ 0, 0, 0, 0, 0, 190, 188, 191, 189, 187,
+ 200, 199, 201, 0, 213, 0, 209, 0, 247, 155,
+ 0, 229, 244, 245, 0, 244, 0, 0, 295, 0,
+ 0, 0, 297, 0, 217, 0, 0, 221, 0, 0,
+ 225, 284, 0, 276, 285, 279, 0, 283, 0, 244,
+ 277, 0, 244, 0, 0, 296, 0, 0, 0, 298,
+ 347, 335, 0, 0, 337, 0, 331, 0, 321, 0,
+ 0, 0, 290, 0, 289, 0, 349, 0, 104, 266,
+ 269, 0, 105, 272, 108, 133, 110, 111, 76, 115,
+ 116, 67, 117, 120, 74, 77, 68, 244, 69, 79,
+ 123, 72, 125, 75, 127, 128, 273, 130, 131, 135,
+ 0, 97, 0, 0, 99, 103, 101, 88, 100, 102,
+ 0, 98, 87, 267, 265, 143, 144, 149, 0, 142,
+ 0, 320, 0, 307, 308, 0, 319, 0, 0, 0,
+ 310, 315, 313, 316, 0, 0, 314, 315, 0, 311,
+ 0, 312, 268, 318, 0, 268, 317, 0, 322, 323,
+ 0, 268, 324, 325, 0, 0, 326, 0, 0, 0,
+ 327, 328, 161, 160, 0, 0, 0, 294, 0, 0,
+ 0, 309, 281, 274, 0, 282, 278, 0, 280, 270,
+ 0, 271, 275, 91, 0, 0, 95, 82, 0, 84,
+ 93, 0, 85, 94, 96, 86, 92, 83, 0, 89,
+ 165, 163, 167, 164, 162, 166, 340, 6, 341, 4,
+ 2, 65, 90, 0, 0, 68, 70, 69, 31, 5,
+ 0, 66, 0, 45, 44, 43, 0, 0, 58, 0,
+ 59, 35, 36, 37, 38, 40, 41, 62, 39, 0,
+ 45, 0, 0, 0, 0, 0, 54, 0, 55, 0,
+ 0, 26, 0, 0, 63, 27, 0, 30, 28, 24,
+ 0, 29, 25, 0, 56, 0, 57, 143, 0, 60,
+ 64, 0, 0, 0, 0, 61, 0, 52, 46, 53,
+ 47, 0, 0, 0, 0, 49, 0, 50, 51, 48,
+ 0, 0, 143, 268, 0, 0, 42, 105, 272, 108,
+ 133, 110, 111, 76, 115, 116, 67, 117, 120, 74,
+ 77, 68, 244, 69, 79, 123, 72, 125, 75, 127,
+ 128, 273, 130, 131, 135, 0, 32, 33, 0, 34,
+ 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, 350};
const short QmlJSGrammar::goto_default [] = {
- 7, 625, 207, 196, 205, 508, 496, 624, 643, 495,
- 623, 621, 626, 22, 622, 18, 507, 549, 539, 546,
- 541, 526, 191, 195, 197, 201, 233, 208, 230, 530,
- 570, 569, 200, 232, 26, 474, 473, 356, 355, 9,
- 354, 357, 107, 17, 145, 24, 13, 144, 19, 25,
- 57, 23, 8, 28, 27, 269, 15, 263, 10, 259,
- 12, 261, 11, 260, 20, 267, 21, 268, 14, 262,
- 258, 299, 411, 264, 265, 202, 193, 192, 204, 203,
- 229, 194, 360, 359, 231, 463, 462, 321, 322, 465,
- 324, 464, 323, 419, 423, 426, 422, 421, 441, 442,
+ 7, 626, 207, 196, 205, 509, 497, 625, 644, 496,
+ 624, 622, 627, 22, 623, 18, 508, 550, 540, 547,
+ 542, 527, 191, 195, 197, 201, 233, 208, 230, 531,
+ 571, 570, 200, 232, 26, 475, 474, 357, 356, 9,
+ 355, 358, 107, 17, 145, 24, 13, 144, 19, 25,
+ 57, 23, 8, 28, 27, 270, 15, 264, 10, 260,
+ 12, 262, 11, 261, 20, 268, 21, 269, 14, 263,
+ 259, 300, 412, 265, 266, 202, 193, 192, 204, 203,
+ 229, 194, 361, 360, 231, 464, 463, 322, 323, 466,
+ 325, 465, 324, 420, 424, 427, 423, 422, 442, 443,
185, 199, 181, 184, 198, 206, 0};
const short QmlJSGrammar::action_index [] = {
- 404, 1275, 2411, 2411, 2509, 1000, 68, 92, 90, -102,
- 88, 62, 60, 256, -102, 298, 86, -102, -102, 638,
- 83, 134, 172, 219, -102, -102, -102, 454, 194, 1275,
- -102, -102, -102, 381, -102, 2215, 1555, 1275, 1275, 1275,
- -102, 790, 1275, -102, -102, -102, 1275, 1275, -102, -102,
- -102, -102, -102, 1275, -102, 1275, 1275, -102, 1275, 1275,
- 102, 217, -102, -102, 1275, 1275, 1275, -102, -102, -102,
- 204, 1275, 304, 1275, 1275, 1275, 1275, 539, 1275, 1275,
- 1275, 1275, 1275, 1275, 308, 1275, 1275, 1275, 103, 131,
- 135, 308, 210, 225, 216, 308, 444, 390, 434, 1275,
- 82, 1275, 100, 2117, 1275, 1275, -102, -102, -102, -102,
- -102, -102, -102, -102, -102, -102, -102, -102, -102, -102,
- -102, -102, -102, -102, -102, -102, -102, -102, -102, -102,
- -102, -102, -102, -102, -102, -102, -102, -102, -102, -102,
- 139, 1275, -102, -102, 91, 10, -102, 1275, -102, -102,
- 1275, -102, -102, -102, -102, -102, -102, -102, -102, -102,
- -102, -102, -102, -102, 1275, 26, 1275, 1275, 69, 66,
- 1275, -102, 2117, 1275, 1275, -102, 97, -102, 44, -102,
- -102, 67, -102, 297, 78, 24, -102, 291, -102, 36,
- 2411, -102, -102, -102, -102, -102, 234, -102, -102, 12,
- -102, -102, -102, -102, -102, -102, 2411, -102, -102, 464,
- -102, 461, 115, 2509, 42, 381, 58, 46, 2705, 70,
- 1275, -102, 74, 57, 1275, 65, -102, 59, 61, -102,
- -102, 367, -102, -102, -102, -102, -102, -102, 106, -102,
- -102, -102, -102, 87, -102, -102, -102, -102, -102, -102,
- 56, 55, 1275, 99, 84, -102, -102, 1461, -102, 75,
- 48, 52, -102, 306, 72, 53, 579, 77, 110, 370,
- 230, 381, 1275, 286, 1275, 1275, 1275, 1275, 380, 1275,
- 1275, 1275, 1275, 1275, 184, 169, 166, 190, 198, 460,
- 363, 353, 1275, 50, 1275, 63, 1275, -102, 638, 1275,
- -102, 1275, 64, 39, 1275, 30, 2509, -102, 1275, 173,
- 2509, -102, 1275, 79, 1275, 1275, 81, 80, 1275, -102,
- 71, 149, 32, -102, -102, 1275, -102, 381, 1275, -102,
- 73, 1275, 76, 2509, -102, 1275, 142, 2509, -102, -16,
- 381, -42, -12, 2411, -39, -102, 2509, -102, 1275, 154,
- 2509, 14, 2509, -102, 20, 16, -32, -102, -102, 2509,
- -51, 519, -4, 511, 136, 1275, 2509, -2, -35, 395,
- -1, -27, 908, 4, 6, -102, 1370, -102, 0, -36,
- 27, 1275, 47, 22, 1275, 45, 1275, 21, 17, 1275,
- -102, 2313, 144, -102, -102, -102, -102, -102, -102, 1275,
- -102, -102, -102, -102, 274, -102, 1275, -21, -102, 2509,
- -102, 138, -102, -102, 2509, -102, 1275, 132, 5, -102,
- 40, -102, 41, 101, 1275, -102, 38, 34, -102, -38,
- -102, 2509, -102, 105, 2509, -102, 245, -102, -102, 96,
- 2509, 11, -102, -7, -11, -102, 352, 8, 18, -102,
- -102, -102, -102, 1275, 129, 2509, -102, 1275, 130, 2509,
- -102, 49, -102, 226, -102, -102, 1275, -102, -102, 362,
- -102, -102, -102, 107, 1837, -102, -102, 1649, -102, -102,
- 1743, -102, -102, -102, -102, -102, -102, 114, -102, -102,
- -102, -102, -102, -102, -102, -102, -102, 2411, -102, -102,
- -102, 94, 9, 818, 189, -10, 31, -102, -102, 223,
- -102, 191, -102, -102, -102, 300, 178, -102, 1928, -102,
- -102, -102, -102, -102, -102, -102, -102, -102, 257, -25,
- 381, 195, -22, 305, 240, -102, -6, -102, 818, 127,
- -102, -18, 818, -102, -102, 1184, -102, -102, -102, 1092,
- -102, -102, 237, -102, 1928, -102, 294, -8, -102, -102,
- 176, 381, 19, 1928, -102, 165, -102, 174, -102, 2,
- -52, 381, 183, 381, -102, 117, -102, -102, -102, 2019,
- 880, 285, 2607, 1555, 3, -102, 522, 35, 453, 108,
- 1275, 2509, 51, 23, 475, 54, -17, 700, 7, 43,
- -102, 1370, -102, 28, -3, 33, 1275, 37, 15, 1275,
- 25, 1275, 1, 13, 124, -102, -102, 29, -102, -102,
- 728, -102, 250, -43, 627, -102, -102, 231, 372, -102,
- 222, -102, 111, -102, -102, 381, -102, -102, 104, -102,
- -102, -102, -102, -102, -102,
+ 425, 1471, 2619, 2619, 2718, 1193, 69, 100, 86, -103,
+ 97, 62, 60, 236, -103, 278, 93, -103, -103, 609,
+ 83, 117, 266, 184, -103, -103, -103, 514, 179, 1471,
+ -103, -103, -103, 392, -103, 2421, 1754, 1471, 1471, 1471,
+ -103, 1001, 1471, -103, -103, -103, 1471, 1471, -103, -103,
+ -103, -103, -103, 1471, -103, 1471, 1471, -103, 1471, 1471,
+ 115, 169, -103, -103, 1471, 1471, 1471, -103, -103, -103,
+ 152, 1471, 286, 1471, 1471, 1471, 1471, 562, 1471, 1471,
+ 1471, 1471, 1471, 1471, 198, 1471, 1471, 1471, 87, 122,
+ 138, 212, 197, 183, 227, 265, 562, 504, 472, 1471,
+ 79, 1471, 102, 2322, 1471, 1471, -103, -103, -103, -103,
+ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
+ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
+ -103, -103, -103, -103, -103, -103, -103, -103, -103, -103,
+ 132, 1471, -103, -103, 94, 11, -103, 1471, -103, -103,
+ 1471, -103, -103, -103, -103, -103, -103, -103, -103, -103,
+ -103, -103, -103, -103, 1471, 31, 1471, 1471, 67, 68,
+ 1471, -103, 2322, 1471, 1471, -103, 98, -103, 39, -103,
+ -103, 61, -103, 296, 66, 30, -103, 376, -103, 35,
+ 2619, -103, -103, -103, -103, -103, 237, -103, -103, 21,
+ -103, -103, -103, -103, -103, -103, 2619, -103, -103, 513,
+ -103, 541, 114, 2718, 36, 422, 59, 42, 2916, 75,
+ 1471, -103, 77, 53, 1471, 63, -103, 57, 58, -103,
+ -103, 407, -103, -103, -103, -103, -103, -103, 80, -103,
+ -103, -103, -103, 82, -103, -103, -103, -103, -103, -103,
+ 52, 51, 1471, 96, 200, -103, -103, -103, 1659, -103,
+ 76, 44, 46, -103, 298, 73, 48, 736, 78, 95,
+ 363, 233, 347, 1471, 303, 1471, 1471, 1471, 1471, 402,
+ 1471, 1471, 1471, 1471, 1471, 248, 189, 159, 167, 174,
+ 482, 482, 444, 1471, 7, 1471, 64, 1471, -103, 627,
+ 1471, -103, 1471, 65, 34, 1471, 54, 2718, -103, 1471,
+ 140, 2718, -103, 1471, 74, 1471, 1471, 81, 84, 1471,
+ -103, 71, 116, 33, -103, -103, 1471, -103, 313, 1471,
+ -103, 70, 1471, 72, 2718, -103, 1471, 234, 2718, -103,
+ -16, 324, -42, -12, 2619, -39, -103, 2718, -103, 1471,
+ 151, 2718, 12, 2718, -103, 20, 16, -32, -103, -103,
+ 2718, -52, 521, -2, 505, 129, 1471, 2718, -5, -35,
+ 497, 2, -24, 819, 6, 3, -103, 1567, -103, -1,
+ -36, 26, 1471, 47, 22, 1471, 45, 1471, 17, 15,
+ 1471, -103, 2520, 49, -103, -103, -103, -103, -103, -103,
+ 1471, -103, -103, -103, -103, 322, -103, 1471, -25, -103,
+ 2718, -103, 118, -103, -103, 2718, -103, 1471, 112, 8,
+ -103, 40, -103, 41, 106, 1471, -103, 38, 32, -103,
+ -38, -103, 2718, -103, 104, 2718, -103, 247, -103, -103,
+ 99, 2718, -6, -103, -10, -18, -103, 387, 10, 9,
+ -103, -103, -103, -103, 1471, 125, 2718, -103, 1471, 127,
+ 2718, -103, -13, -103, 187, -103, -103, 1471, -103, -103,
+ 398, -103, -103, -103, 110, 2039, -103, -103, 1849, -103,
+ -103, 1944, -103, -103, -103, -103, -103, -103, 105, -103,
+ -103, -103, -103, -103, -103, -103, -103, -103, 2619, -103,
+ -103, -103, 113, -7, 1009, 145, -8, 19, -103, -103,
+ 186, -103, 178, -103, -103, -103, 356, 226, -103, 2131,
+ -103, -103, -103, -103, -103, -103, -103, -103, -103, 322,
+ -26, 364, 205, 43, 316, 206, -103, -3, -103, 1009,
+ 107, -103, -11, 827, -103, -103, 1379, -103, -103, -103,
+ 1286, -103, -103, 195, -103, 2131, -103, 305, -4, -103,
+ -103, 209, 379, 18, 2131, -103, 182, -103, 199, -103,
+ 0, -53, 306, 154, 284, -103, 108, -103, -103, -103,
+ 2223, 918, 300, 2817, 1754, 5, -103, 549, 139, 636,
+ 114, 1471, 2718, 50, 24, 463, 55, -17, 910, 23,
+ 56, -103, 1567, -103, 27, 1, 29, 1471, 37, 14,
+ 1471, 25, 1471, 4, 13, 126, -103, -103, 28, -103,
+ -103, 1100, -103, 267, -41, 714, -103, -103, 121, 301,
+ -103, 215, -103, 91, -103, -103, 336, -103, -103, 89,
+ -103, -103, -103, -103, -103, -103,
- -107, 9, -103, 2, 5, 266, 1, -107, -107, -107,
- -107, -107, -107, -107, -107, -107, -107, -107, -107, -39,
- -107, -107, -107, -107, -107, -107, -107, -107, -107, 86,
- -107, -107, -107, 8, -107, -107, -22, 19, 71, 174,
- -107, 186, 171, -107, -107, -107, 184, 178, -107, -107,
- -107, -107, -107, 144, -107, 124, 150, -107, 165, 161,
- -107, -107, -107, -107, 156, 160, 157, -107, -107, -107,
- -107, 147, -107, 142, 135, 179, 166, -107, 177, 170,
- 117, 72, 134, 92, -107, 75, 94, 66, -107, -107,
- -107, -107, -107, -107, -107, -107, -107, -107, -107, 181,
- -107, 106, -107, 143, 78, 55, -107, -107, -107, -107,
+ -107, 12, -95, 3, 6, 275, 2, -107, -107, -107,
+ -107, -107, -107, -107, -107, -107, -107, -107, -107, -37,
+ -107, -107, -107, -107, -107, -107, -107, -107, -107, 96,
+ -107, -107, -107, 8, -107, -107, -17, 24, 95, 74,
+ -107, 85, 175, -107, -107, -107, 172, 168, -107, -107,
+ -107, -107, -107, 169, -107, 165, 164, -107, 156, 176,
+ -107, -107, -107, -107, 182, 178, 112, -107, -107, -107,
+ -107, 121, -107, 144, 118, 116, 117, -107, 108, 133,
+ 134, 137, 143, 152, -107, 147, 141, 136, -107, -107,
+ -107, -107, -107, -107, -107, -107, -107, -107, -107, 107,
+ -107, 173, -107, 153, 84, 56, -107, -107, -107, -107,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -107, -5, -107, -107, -107, -107, -107, 54, -107, -107,
- 51, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -107, -107, -107, -107, 114, -107, 113, 38, -107, -107,
- 41, -107, 231, 63, 112, -107, -107, -107, -107, -107,
- -107, -107, -107, 30, -107, -107, -107, 52, -107, -107,
+ -107, 36, -107, -107, -107, -107, -107, 30, -107, -107,
+ 0, -107, -107, -107, -107, -107, -107, -107, -107, -107,
+ -107, -107, -107, -107, 79, -107, 99, 44, -107, -107,
+ 46, -107, 194, 70, 64, -107, -107, -107, -107, -107,
+ -107, -107, -107, 29, -107, -107, -107, 65, -107, -107,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -107, -107, -107, -107, -107, -107, 36, -107, -107, 45,
- -107, 42, -107, 40, -107, 80, -107, -107, 77, -107,
- 88, -107, -107, -107, 83, 74, -107, -107, -107, -107,
- -107, -10, -107, -107, -107, -107, -107, -107, -107, -107,
+ -107, -107, -107, -107, -107, -107, 80, -107, -107, 51,
+ -107, 48, -107, 40, -107, 34, -107, -107, 86, -107,
+ 88, -107, -107, -107, 78, 60, -107, -107, -107, -107,
+ -107, -6, -107, -107, -107, -107, -107, -107, -107, -107,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -107, -107, 23, -107, -107, -107, -107, 100, -107, -107,
+ -107, -107, 21, -107, -107, -107, -107, -107, 104, -107,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -107, 4, 223, -107, 230, 236, 222, 205, -107, 127,
- 125, 115, 96, 102, -107, -107, -107, -107, -107, -107,
- -107, -107, 234, -107, 215, -107, 199, -107, -107, 197,
- -107, 190, -107, -107, 163, -107, 90, -107, 0, -107,
- -1, -107, 203, -107, 189, 211, -107, -107, 195, -107,
- -107, -107, -107, -107, -107, 191, -107, 98, 119, -107,
- -107, 95, -107, 81, -107, 79, -107, 82, -107, -107,
- 101, -107, -107, -16, -107, -107, 53, -107, 46, -107,
- 57, -107, 59, -107, -107, -107, -107, -107, -107, 35,
- -107, 33, -107, 39, -107, 89, 67, -107, -107, 58,
- -107, -107, 84, -107, -107, -107, 73, -107, -107, -107,
- -107, 65, -107, 43, 93, -107, 109, -107, -107, 49,
- -107, 47, -107, -107, -107, -107, -107, -107, -107, 50,
- -107, -107, -107, -107, -107, -107, 108, -107, -107, 61,
- -107, -107, -107, -107, 62, -107, 68, -107, -107, -107,
- -107, -107, -23, -107, 69, -107, -19, -107, -107, -107,
- -107, 97, -107, -107, 99, -107, -107, -107, -107, -107,
- 60, -61, -107, -107, 34, -107, 37, -107, 29, -107,
- -107, -107, -107, 32, -107, 76, -107, 44, -107, 56,
- -107, -107, -107, -107, -107, -107, 31, -107, -107, 116,
- -107, -107, -107, -107, -6, -107, -107, 70, -107, -107,
- 64, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -107, -107, -107, -107, -107, -107, -107, 193, -107, -107,
- -107, -107, -107, 7, -107, -107, -107, -107, -107, -107,
- -107, -20, -107, -107, -107, -7, -107, -107, 290, -107,
+ -107, -107, 16, 201, -107, 202, 224, 223, 215, -107,
+ 67, 73, 75, 59, 106, -107, -107, -107, -107, -107,
+ -107, -107, -107, 185, -107, 208, -107, 233, -107, -107,
+ 234, -107, 203, -107, -107, 299, -107, 90, -107, -2,
+ -107, 11, -107, 181, -107, 200, 192, -107, -107, 189,
+ -107, -107, -107, -107, -107, -107, 199, -107, 123, 131,
+ -107, -107, 111, -107, 77, -107, 87, -107, 195, -107,
+ -107, 110, -107, -107, -50, -107, -107, 39, -107, 42,
+ -107, 63, -107, 66, -107, -107, -107, -107, -107, -107,
+ 68, -107, 43, -107, 47, -107, 92, 35, -107, -107,
+ 31, -107, -107, 105, -107, -107, -107, 94, -107, -107,
+ -107, -107, 71, -107, 54, 101, -107, 89, -107, -107,
+ 55, -107, 49, -107, -107, -107, -107, -107, -107, -107,
+ 38, -107, -107, -107, -107, -107, -107, 114, -107, -107,
+ 76, -107, -107, -107, -107, 91, -107, 93, -107, -107,
+ -107, -107, -107, -57, -107, 50, -107, -44, -107, -107,
+ -107, -107, 98, -107, -107, 97, -107, -107, -107, -107,
+ -107, 52, -42, -107, -107, 45, -107, 41, -107, 37,
+ -107, -107, -107, -107, 57, -107, 53, -107, 58, -107,
+ 62, -107, -107, -107, -107, -107, -107, 9, -107, -107,
+ 187, -107, -107, -107, -107, 33, -107, -107, 139, -107,
+ -107, 32, -107, -107, -107, -107, -107, -107, -107, -107,
+ -107, -107, -107, -107, -107, -107, -107, -107, 82, -107,
+ -107, -107, -107, -107, -11, -107, -107, -107, -107, -107,
+ -107, -107, -25, -107, -107, -107, -9, -107, -107, 297,
-107, -107, -107, -107, -107, -107, -107, -107, -107, -107,
- -2, -25, -107, -15, -107, -107, -107, -107, 172, -107,
- -107, -107, 287, -107, -107, 288, -107, -107, -107, 291,
- -107, -107, -107, -107, 336, -107, -107, 20, -107, -107,
- 15, 3, -107, 304, -107, -107, -107, 24, -107, -107,
- -107, 28, 21, 26, -107, -107, -107, -107, -107, 320,
- 104, -107, 13, 381, -3, -107, 6, -107, 10, -107,
- 167, 22, -107, -107, 12, -107, -107, 87, -107, -107,
- -107, 25, -107, -107, -107, -107, 11, -107, 14, 85,
- -107, 121, -107, -107, -107, -107, -107, 27, -107, -107,
- 17, -107, -107, 18, 91, -107, -107, -107, 16, -107,
- -107, -107, -107, -107, -107, -4, -107, -107, -107, -107,
- -107, -107, -107, -107, -107};
+ -107, -3, -26, -107, -10, -107, -107, -107, -107, 160,
+ -107, -107, -107, 120, -107, -107, 279, -107, -107, -107,
+ 285, -107, -107, -107, -107, 329, -107, -107, 17, -107,
+ -107, -13, 14, -107, 385, -107, -107, -107, 23, -107,
+ -107, -107, 28, 18, 20, -107, -107, -107, -107, -107,
+ 313, 188, -107, 26, 267, 7, -107, 5, -107, -1,
+ -107, 69, 19, -107, -107, 10, -107, -107, 103, -107,
+ -107, -107, 27, -107, -107, -107, -107, 15, -107, -5,
+ 61, -107, 81, -107, -107, -107, -107, -107, 13, -107,
+ -107, 25, -107, -107, 22, 119, -107, -107, -107, 4,
+ -107, -107, -107, -107, -107, -107, -15, -107, -107, -107,
+ -107, -107, -107, -107, -107, -107};
const short QmlJSGrammar::action_info [] = {
- 416, 257, 533, -132, 403, -113, 346, -102, 575, 348,
- 572, -121, 531, -103, -121, 545, 345, 430, 342, 348,
- 340, 343, 440, 401, 391, 545, 563, 389, 538, 446,
- 352, 444, -129, 416, -124, -102, 545, 453, 420, 408,
- -124, 431, -132, 424, -126, 424, 424, 620, 440, 457,
- -103, 440, -129, 457, -126, 440, 560, 453, -113, 257,
- 565, 346, 545, 335, 272, 346, 466, 236, 448, 190,
- 149, 164, 141, 170, 99, 511, 272, 409, 257, 312,
- 296, 414, 348, 312, 189, 164, 187, 318, 325, 71,
- 306, 252, 644, 416, 141, 453, 292, 457, 440, 147,
- 304, 71, 443, 183, 179, 141, 0, 141, 0, 172,
- 99, 427, 434, 141, 301, 477, 444, 0, 0, 0,
- 0, 0, 141, 0, 0, 0, 0, 292, 173, 294,
- 58, 294, 542, 251, 331, 542, 333, 141, 141, 101,
- 141, 59, 0, 58, 62, 256, 255, 141, 247, 246,
- 141, 399, 0, 177, 59, 63, 428, 327, 620, 254,
- 314, 101, 141, 478, 315, 640, 639, 242, 241, 249,
- 248, 58, 634, 633, 488, 58, 249, 248, 577, 576,
- 615, 141, 59, 543, 166, 518, 59, 172, 167, 455,
- 459, 85, 418, 86, 85, 142, 86, 249, 248, 413,
- 412, 567, 337, 512, 87, 512, 173, 87, 174, 85,
- 328, 86, 512, 0, 350, 85, 64, 86, 529, 85,
- 512, 86, 87, 85, 512, 86, 568, 566, 87, 64,
- 579, 64, 87, 310, 469, 85, 87, 86, 0, 519,
- 517, 85, 141, 86, 554, 0, 172, 536, 87, 514,
- 85, 514, 86, 141, 87, 85, 545, 86, 514, 0,
- 513, 65, 513, 87, 514, 173, 514, 66, 87, 513,
- 514, 103, 172, 0, 65, 513, 65, 513, 0, 0,
- 66, 513, 66, 637, 636, 0, 0, 470, 468, 172,
- 104, 173, 105, 406, 0, 235, 234, 630, 555, 553,
- 172, 537, 535, 0, 274, 275, 438, 437, 173, 172,
- 406, 631, 629, 635, 0, 580, 73, 74, -90, 173,
- 34, 174, 73, 74, 274, 275, 34, -90, 173, 34,
- 174, 276, 277, 85, 34, 86, 0, 0, 0, 0,
- 0, 628, 0, 75, 76, 0, 87, 0, 0, 75,
- 76, 276, 277, 0, 0, 0, 0, 48, 50, 49,
- 0, 0, 0, 48, 50, 49, 48, 50, 49, 0,
- 0, 48, 50, 49, 0, 0, 279, 280, 0, 0,
- 0, 34, 0, 45, 0, 281, 279, 280, 282, 45,
- 283, 34, 45, 279, 280, 281, 34, 45, 282, 0,
- 283, 34, 281, 279, 280, 282, 0, 283, 0, 0,
- 34, 0, 281, 78, 79, 282, 0, 283, 48, 50,
- 49, 80, 81, 0, 34, 82, 0, 83, 48, 50,
- 49, -345, 0, 48, 50, 49, 0, 0, 48, 50,
- 49, 0, 0, 0, 45, 0, 0, 48, 50, 49,
- 0, 0, 0, 0, 45, 0, 0, 78, 79, 45,
- 0, 48, 50, 49, 45, 80, 81, 78, 79, 82,
- 0, 83, 0, 45, 0, 80, 81, 78, 79, 82,
- 0, 83, 34, 279, 280, 80, 81, 45, 0, 82,
- 34, 83, 281, 34, 0, 282, 0, 283, 6, 5,
- 4, 1, 3, 2, 34, 0, 0, 0, 0, 0,
- 0, -345, 0, 0, 245, 244, 0, 0, 0, 48,
- 50, 49, 245, 244, 0, 240, 239, 48, 50, 49,
- 48, 50, 49, 0, 0, 0, 0, 0, 0, 0,
- 34, 48, 50, 49, 0, 45, 0, 0, 34, 0,
- 0, 34, 0, 45, 0, 0, 45, 0, 0, 0,
- 0, 0, 78, 79, 0, 0, 0, 45, 0, 0,
- 80, 81, 245, 244, 82, 0, 83, 48, 50, 49,
- 240, 239, 151, 240, 239, 48, 50, 49, 48, 50,
- 49, 0, 152, 0, 0, 0, 153, 0, 0, 0,
- 0, 0, 0, 45, 0, 154, 0, 155, 0, 0,
- 308, 45, 0, 0, 45, 0, 0, 0, 156, 0,
- 157, 62, 0, 0, 0, 0, 0, 0, 158, 0,
- 0, 159, 63, 0, 0, 0, 0, 160, 0, 30,
- 31, 151, 0, 161, 0, 0, 0, 0, 0, 33,
- 0, 152, 0, 0, 0, 153, 34, 0, 0, 162,
- 35, 36, 0, 37, 154, 0, 155, 0, 0, 0,
- 503, 0, 0, 0, 44, 0, 0, 156, 0, 157,
- 62, 0, 0, 0, 0, 0, 0, 158, 0, 0,
- 159, 63, 51, 48, 50, 49, 160, 52, 0, 0,
- 0, 0, 161, 0, 0, 0, 0, 0, 43, 54,
- 32, 0, 30, 31, 40, 0, 0, 0, 162, 45,
- 0, 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, 51, 48, 50, 49, 0,
- 52, 503, 0, 0, 0, 44, 0, 0, 0, 0,
- 0, 43, 54, 32, 0, 0, 0, 40, 0, 0,
- 0, 0, 45, 51, 48, 50, 49, 0, 52, 0,
- 0, 0, 30, 31, 0, 0, 0, 0, 0, 43,
- 54, 32, 33, 0, 0, 40, 0, 0, 0, 34,
- 45, 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, 51, 48, 50, 49, 0,
- 52, 503, 0, 0, 0, 44, 0, 0, 0, 0,
- 0, 43, 54, 32, 0, 0, 0, 40, 0, 0,
- 0, 0, 45, 51, 48, 50, 49, 0, 52, 0,
- 0, 0, 30, 31, 0, 0, 0, 0, 0, 43,
- 54, 32, 33, 0, 0, 40, 0, 0, 0, 34,
- 45, 0, 0, 35, 36, 0, 37, 0, 0, 0,
- 30, 31, 0, 503, 0, 0, 0, 44, 0, 0,
- 33, 0, 0, 0, 0, 0, 0, 34, 0, 0,
- 0, 35, 36, 0, 37, 51, 48, 50, 49, 0,
- 52, 41, 0, 0, 0, 44, 0, 0, 0, 0,
- 0, 43, 54, 32, 0, 0, 0, 40, 0, 0,
- 0, 0, 45, 51, 48, 50, 49, 0, 52, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 43,
- 54, 32, 0, 0, 0, 40, 0, 0, 0, 0,
- 45, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 502, 0, 30, 31, 0, 0, 0, 0, 0, 0,
- 0, 0, 215, 0, 0, 0, 0, 0, 0, 34,
- 0, 0, 0, 35, 36, 0, 37, 0, 0, 0,
- 0, 0, 0, 503, 0, 0, 0, 44, 0, 0,
+ 417, 258, -113, 404, 467, -132, -102, 576, 573, 347,
+ -103, 532, 349, -121, 445, 441, 346, 431, 343, 349,
+ 341, 344, 546, 402, 392, 564, 447, 390, 353, 546,
+ -121, 539, -129, -124, -102, 409, -124, 417, 546, 432,
+ 454, 421, 441, 425, -126, 425, 425, 441, 566, 458,
+ 621, 458, -129, 454, -126, 441, 400, -113, 561, 512,
+ 258, 546, 347, -103, 336, 273, 347, 534, 190, 164,
+ 449, 149, 258, 141, 187, 170, 236, 273, 349, 99,
+ 313, 297, 410, 313, 415, 164, 295, 252, 326, 417,
+ 189, 319, 293, 454, 458, 305, 441, 183, 71, 179,
+ 645, 141, 147, 71, 141, 444, 141, 0, 0, 302,
+ 99, 435, 141, 141, 307, 543, 428, 0, 478, 445,
+ 141, 0, 293, 0, 328, 295, 58, 58, 172, 251,
+ 0, 332, 334, 141, 543, 141, 172, 59, 59, 101,
+ 141, 242, 241, 247, 246, 315, -132, 173, 141, 316,
+ 641, 640, 635, 634, 177, 173, 254, 62, 101, 141,
+ 621, 429, 58, 544, 64, 489, 479, 166, 63, 578,
+ 577, 167, 419, 59, 530, 249, 248, 329, 58, 414,
+ 413, 64, 616, 513, 85, 456, 86, 460, 142, 59,
+ 249, 248, 85, 580, 86, 470, 64, 87, 0, 85,
+ 311, 86, 555, 0, 85, 87, 86, 513, 85, 65,
+ 86, 351, 87, 537, 85, 66, 86, 87, 568, 546,
+ 515, 87, 85, 85, 86, 86, 65, 87, 513, 515,
+ 0, 514, 66, 519, 513, 87, 87, 85, 513, 86,
+ 514, 65, 141, 569, 567, 141, 0, 66, 471, 469,
+ 87, 103, 85, 515, 86, 141, 556, 554, 85, 0,
+ 86, 257, 255, 0, 514, 87, 0, 538, 536, 0,
+ 104, 87, 105, 85, 515, 86, 638, 637, 0, 581,
+ 515, 172, 0, 0, 515, 514, 87, 520, 518, 256,
+ 85, 514, 86, 0, 338, 514, 73, 74, 235, 234,
+ 173, 0, 174, 87, 73, 74, 0, 636, 439, 438,
+ 0, 0, 0, 34, 631, 172, 275, 276, 0, 0,
+ 172, 275, 276, 75, 76, 34, 0, 0, 632, 630,
+ 34, 75, 76, -90, 173, 34, 174, 172, -90, 173,
+ 0, 174, 34, 277, 278, 34, 0, 0, 277, 278,
+ 48, 50, 49, 34, 0, 0, 173, 0, 407, 629,
+ 0, 0, 48, 50, 49, 34, 0, 48, 50, 49,
+ 0, 0, 48, 50, 49, 0, 34, 45, 0, 48,
+ 50, 49, 48, 50, 49, 34, 280, 281, 0, 45,
+ 48, 50, 49, 34, 45, 282, 0, 0, 283, 45,
+ 284, 0, 48, 50, 49, 34, 45, 0, 34, 45,
+ 0, 0, 0, 48, 50, 49, 34, 45, 0, 0,
+ 0, 34, 48, 50, 49, 280, 281, 34, 0, 45,
+ 48, 50, 49, 0, 282, 0, 34, 283, 0, 284,
+ 45, 0, 48, 50, 49, 48, 50, 49, 0, 45,
+ 0, 34, 0, 48, 50, 49, 0, 45, 48, 50,
+ 49, 0, 0, 0, 48, 50, 49, 280, 281, 45,
+ 0, 0, 45, 48, 50, 49, 282, 0, 0, 283,
+ 45, 284, 0, 0, 0, 45, 0, 0, 48, 50,
+ 49, 45, 34, 0, 0, 78, 79, 0, 0, -346,
+ 45, 0, 0, 80, 81, 280, 281, 82, 0, 83,
+ 0, 0, 0, 0, 282, 45, 0, 283, 0, 284,
+ 6, 5, 4, 1, 3, 2, 34, 78, 79, 48,
+ 50, 49, 0, -346, 34, 80, 81, 78, 79, 82,
+ 0, 83, 34, 0, 0, 80, 81, 0, 0, 82,
+ 34, 83, 0, 0, 0, 0, 45, 0, 0, 0,
+ 0, 0, 0, 48, 50, 49, 245, 244, 0, 0,
+ 34, 48, 50, 49, 240, 239, 0, 0, 34, 48,
+ 50, 49, 240, 239, 0, 78, 79, 48, 50, 49,
+ 45, 0, 0, 80, 81, 0, 0, 82, 45, 83,
+ 0, 0, 245, 244, 0, 0, 45, 48, 50, 49,
+ 240, 239, 151, 0, 45, 48, 50, 49, 0, 0,
+ 0, 0, 152, 0, 0, 0, 153, 0, 0, 0,
+ 151, 0, 0, 0, 45, 154, 0, 155, 0, 0,
+ 152, 0, 45, 0, 153, 0, 0, 0, 156, 0,
+ 157, 62, 0, 154, 0, 155, 0, 0, 158, 0,
+ 0, 159, 63, 0, 0, 34, 156, 160, 157, 62,
+ 0, 0, 0, 161, 0, 0, 158, 0, 0, 159,
+ 63, 0, 0, 0, 0, 160, 0, 0, 0, 162,
+ 0, 161, 0, 0, 0, 0, 0, 245, 244, 0,
+ 0, 0, 48, 50, 49, 0, 0, 162, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 51, 504, 506, 505, 0,
- 52, 0, 0, 0, 0, 226, 0, 0, 0, 0,
- 0, 43, 54, 32, 210, 0, 0, 40, 0, 0,
- 0, 0, 45, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 502, 0, 30, 31, 0, 0, 0, 0,
- 0, 0, 0, 0, 215, 0, 0, 0, 0, 0,
- 0, 34, 0, 0, 0, 35, 36, 0, 37, 0,
- 0, 0, 0, 0, 0, 503, 0, 0, 0, 44,
- 0, 0, 0, 0, 0, 0, 0, 550, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 51, 504, 506,
- 505, 0, 52, 0, 0, 0, 0, 226, 0, 0,
- 0, 0, 0, 43, 54, 32, 210, 0, 0, 40,
- 0, 0, 0, 0, 45, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 502, 0, 30, 31, 0, 0,
- 0, 0, 0, 0, 0, 0, 215, 0, 0, 0,
- 0, 0, 0, 34, 0, 0, 0, 35, 36, 0,
- 37, 0, 0, 0, 0, 0, 0, 503, 0, 0,
- 0, 44, 0, 0, 0, 0, 0, 0, 0, 547,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 51,
- 504, 506, 505, 0, 52, 0, 0, 0, 0, 226,
- 0, 0, 0, 0, 0, 43, 54, 32, 210, 0,
- 0, 40, 0, 0, 0, 0, 45, 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, 46, 0, 47, 0,
+ 0, 0, 0, 0, 0, 0, 30, 31, 0, 45,
+ 0, 0, 0, 0, 0, 0, 33, 0, 0, 151,
+ 0, 0, 0, 34, 0, 0, 0, 35, 36, 152,
+ 37, 0, 0, 153, 0, 0, 0, 504, 0, 0,
+ 0, 44, 154, 0, 155, 0, 0, 309, 0, 0,
+ 0, 0, 0, 0, 0, 156, 0, 157, 62, 51,
+ 48, 50, 49, 0, 52, 158, 0, 0, 159, 63,
+ 0, 0, 0, 0, 160, 43, 54, 32, 0, 0,
+ 161, 40, 0, 0, 0, 0, 0, 45, 0, 0,
+ 0, 0, 0, 0, 0, 0, 162, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 51, 48, 50, 49, 0, 52, 0, 53, 0, 55,
- 0, 56, 0, 0, 0, 0, 43, 54, 32, 0,
- 0, 0, 40, 0, 0, 0, 0, 45, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, -122, 0, 0,
- 0, 29, 30, 31, 0, 0, 0, 0, 0, 0,
+ 0, 30, 31, 0, 0, 0, 0, 0, 0, 30,
+ 31, 33, 0, 0, 0, 0, 0, 0, 34, 33,
+ 0, 0, 35, 36, 0, 37, 34, 0, 0, 0,
+ 35, 36, 41, 37, 0, 0, 44, 0, 0, 0,
+ 504, 0, 0, 0, 44, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 51, 48, 50, 49, 0, 52,
+ 0, 0, 51, 48, 50, 49, 0, 52, 0, 0,
+ 43, 54, 32, 0, 0, 0, 40, 0, 43, 54,
+ 32, 0, 45, 0, 40, 0, 0, 0, 0, 0,
+ 45, 0, 30, 31, 0, 0, 0, 0, 0, 0,
+ 30, 31, 33, 0, 0, 0, 0, 0, 0, 34,
+ 33, 0, 0, 35, 36, 0, 37, 34, 0, 0,
+ 0, 35, 36, 41, 37, 0, 0, 44, 0, 0,
+ 0, 504, 0, 0, 0, 44, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 51, 48, 50, 49, 0,
+ 52, 0, 0, 51, 48, 50, 49, 0, 52, 0,
+ 0, 43, 54, 32, 0, 0, 0, 40, 0, 43,
+ 54, 32, 0, 45, 0, 40, 0, 0, 0, 0,
+ 0, 45, 0, 30, 31, 0, 0, 0, 0, 0,
+ 0, 30, 31, 33, 0, 0, 0, 0, 0, 0,
+ 34, 33, 0, 0, 35, 36, 0, 37, 34, 0,
+ 0, 0, 35, 36, 41, 37, 0, 0, 44, 0,
+ 0, 0, 504, 0, 0, 0, 44, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 51, 48, 50, 49,
+ 0, 52, 0, 0, 51, 48, 50, 49, 0, 52,
+ 0, 0, 43, 54, 32, 0, 0, 0, 40, 0,
+ 43, 54, 32, 0, 45, 0, 40, 0, 0, 0,
+ 0, 0, 45, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 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, 46, 0, 47, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 504, 0, 0, 0, 44, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 51, 48, 50, 49, 0,
- 52, 0, 53, 0, 55, 0, 56, 0, 0, 0,
+ 52, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 43, 54, 32, 0, 0, 0, 40, 0, 0,
+ 0, 0, 0, 45, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 503, 0, 30, 31, 0, 0, 0,
+ 0, 0, 0, 0, 0, 215, 0, 0, 0, 0,
+ 0, 0, 34, 0, 0, 0, 35, 36, 0, 37,
+ 0, 0, 0, 0, 0, 0, 504, 0, 0, 0,
+ 44, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 51, 505,
+ 507, 506, 0, 52, 0, 0, 0, 0, 226, 0,
+ 0, 0, 0, 0, 43, 54, 32, 210, 0, 0,
+ 40, 0, 0, 0, 0, 0, 45, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 503, 0, 30, 31,
+ 0, 0, 0, 0, 0, 0, 0, 0, 215, 0,
+ 0, 0, 0, 0, 0, 34, 0, 0, 0, 35,
+ 36, 0, 37, 0, 0, 0, 0, 0, 0, 504,
+ 0, 0, 0, 44, 0, 0, 0, 0, 0, 0,
+ 0, 551, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 51, 505, 507, 506, 0, 52, 0, 0, 0,
+ 0, 226, 0, 0, 0, 0, 0, 43, 54, 32,
+ 210, 0, 0, 40, 0, 0, 0, 0, 0, 45,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 503,
+ 0, 30, 31, 0, 0, 0, 0, 0, 0, 0,
+ 0, 215, 0, 0, 0, 0, 0, 0, 34, 0,
+ 0, 0, 35, 36, 0, 37, 0, 0, 0, 0,
+ 0, 0, 504, 0, 0, 0, 44, 0, 0, 0,
+ 0, 0, 0, 0, 548, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 51, 505, 507, 506, 0, 52,
+ 0, 0, 0, 0, 226, 0, 0, 0, 0, 0,
+ 43, 54, 32, 210, 0, 0, 40, 0, 0, 0,
0, 0, 45, 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,
@@ -486,351 +487,392 @@ const short QmlJSGrammar::action_info [] = {
0, 38, 0, 39, 41, 42, 0, 0, 44, 0,
0, 0, 46, 0, 47, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 51, 48, 50, 49,
- 0, 52, 0, 53, 0, 55, 271, 56, 0, 0,
+ 0, 52, 0, 53, 0, 55, 0, 56, 0, 0,
0, 0, 43, 54, 32, 0, 0, 0, 40, 0,
- 0, 0, 0, 45, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 475, 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, 46, 0, 47, 0,
- 0, 476, 0, 0, 0, 0, 0, 0, 0, 0,
- 51, 48, 50, 49, 0, 52, 0, 53, 0, 55,
- 0, 56, 0, 0, 0, 0, 43, 54, 32, 0,
- 0, 0, 40, 0, 0, 0, 0, 45, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 475, 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,
- 46, 0, 47, 0, 0, 481, 0, 0, 0, 0,
- 0, 0, 0, 0, 51, 48, 50, 49, 0, 52,
- 0, 53, 0, 55, 0, 56, 0, 0, 0, 0,
- 43, 54, 32, 0, 0, 0, 40, 0, 0, 0,
- 0, 45, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 483, 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, 46, 0, 47, 0, 0, 484,
- 0, 0, 0, 0, 0, 0, 0, 0, 51, 48,
- 50, 49, 0, 52, 0, 53, 0, 55, 0, 56,
- 0, 0, 0, 0, 43, 54, 32, 0, 0, 0,
- 40, 0, 0, 0, 0, 45, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 483, 0, 0, 29, 30,
+ 0, 0, 0, 0, 45, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, -122, 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, 46, 0,
- 47, 0, 0, 486, 0, 0, 0, 0, 0, 0,
+ 47, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 51, 48, 50, 49, 0, 52, 0, 53,
0, 55, 0, 56, 0, 0, 0, 0, 43, 54,
- 32, 0, 0, 0, 40, 0, 0, 0, 0, 45,
- 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, 217, 0,
- 0, 218, 36, 0, 37, 0, 0, 0, 38, 0,
- 39, 41, 42, 0, 0, 44, 0, 0, 0, 46,
- 0, 47, 0, 0, 0, 0, 0, 0, 0, 221,
- 0, 0, 0, 51, 48, 50, 49, 223, 52, 0,
- 53, 225, 55, 0, 56, 0, 228, 0, 0, 43,
- 54, 32, 0, 0, 0, 40, 0, 0, 0, 0,
+ 32, 0, 0, 0, 40, 0, 0, 0, 0, 0,
45, 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, 217,
- 0, 0, 582, 583, 0, 37, 0, 0, 0, 38,
+ 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,
46, 0, 47, 0, 0, 0, 0, 0, 0, 0,
- 221, 0, 0, 0, 51, 48, 50, 49, 223, 52,
- 0, 53, 225, 55, 0, 56, 0, 228, 0, 0,
+ 0, 0, 0, 0, 51, 48, 50, 49, 0, 52,
+ 0, 53, 0, 55, 272, 56, 0, 0, 0, 0,
43, 54, 32, 0, 0, 0, 40, 0, 0, 0,
- 0, 45, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 109, 110, 111, 0, 0, 113, 115, 116, 0,
- 0, 117, 0, 118, 0, 0, 0, 120, 121, 122,
- 0, 0, 0, 0, 0, 0, 34, 123, 124, 125,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 126, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 129, 0, 0, 0,
- 0, 0, 0, 48, 50, 49, 130, 131, 132, 0,
- 134, 135, 136, 137, 138, 139, 0, 0, 127, 133,
- 119, 112, 114, 128, 0, 0, 0, 0, 0, 45,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 109,
- 110, 111, 0, 0, 113, 115, 116, 0, 0, 117,
- 0, 118, 0, 0, 0, 120, 121, 122, 0, 0,
- 0, 0, 0, 0, 393, 123, 124, 125, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 126, 0,
- 0, 0, 394, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 129, 0, 0, 0, 0, 0,
- 398, 395, 397, 0, 130, 131, 132, 0, 134, 135,
- 136, 137, 138, 139, 0, 0, 127, 133, 119, 112,
- 114, 128, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 109, 110, 111,
- 0, 0, 113, 115, 116, 0, 0, 117, 0, 118,
- 0, 0, 0, 120, 121, 122, 0, 0, 0, 0,
- 0, 0, 393, 123, 124, 125, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 126, 0, 0, 0,
- 394, 0, 0, 0, 0, 0, 0, 0, 396, 0,
- 0, 0, 129, 0, 0, 0, 0, 0, 398, 395,
- 397, 0, 130, 131, 132, 0, 134, 135, 136, 137,
- 138, 139, 0, 0, 127, 133, 119, 112, 114, 128,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 209, 0, 0, 0, 0,
- 211, 0, 29, 30, 31, 213, 0, 0, 0, 0,
- 0, 0, 214, 215, 0, 0, 0, 0, 0, 0,
- 216, 217, 0, 0, 218, 36, 0, 37, 0, 0,
+ 0, 0, 45, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 476, 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, 46, 0, 47, 0, 0,
+ 477, 0, 0, 0, 0, 0, 0, 0, 0, 51,
+ 48, 50, 49, 0, 52, 0, 53, 0, 55, 0,
+ 56, 0, 0, 0, 0, 43, 54, 32, 0, 0,
+ 0, 40, 0, 0, 0, 0, 0, 45, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 476, 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,
+ 46, 0, 47, 0, 0, 482, 0, 0, 0, 0,
+ 0, 0, 0, 0, 51, 48, 50, 49, 0, 52,
+ 0, 53, 0, 55, 0, 56, 0, 0, 0, 0,
+ 43, 54, 32, 0, 0, 0, 40, 0, 0, 0,
+ 0, 0, 45, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 484, 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, 46, 0, 47, 0, 0,
+ 485, 0, 0, 0, 0, 0, 0, 0, 0, 51,
+ 48, 50, 49, 0, 52, 0, 53, 0, 55, 0,
+ 56, 0, 0, 0, 0, 43, 54, 32, 0, 0,
+ 0, 40, 0, 0, 0, 0, 0, 45, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 484, 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,
+ 46, 0, 47, 0, 0, 487, 0, 0, 0, 0,
+ 0, 0, 0, 0, 51, 48, 50, 49, 0, 52,
+ 0, 53, 0, 55, 0, 56, 0, 0, 0, 0,
+ 43, 54, 32, 0, 0, 0, 40, 0, 0, 0,
+ 0, 0, 45, 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, 217, 0, 0, 218, 36, 0, 37, 0, 0,
0, 38, 0, 39, 41, 42, 0, 0, 44, 0,
0, 0, 46, 0, 47, 0, 0, 0, 0, 0,
- 220, 0, 221, 0, 0, 0, 51, 219, 222, 49,
- 223, 52, 224, 53, 225, 55, 226, 56, 227, 228,
- 0, 0, 43, 54, 32, 210, 212, 0, 40, 0,
- 0, 0, 0, 45, 0, 0, 0, 0, 0, 0,
+ 0, 0, 221, 0, 0, 0, 51, 48, 50, 49,
+ 223, 52, 0, 53, 225, 55, 0, 56, 0, 228,
+ 0, 0, 43, 54, 32, 0, 0, 0, 40, 0,
+ 0, 0, 0, 0, 45, 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, 217, 0, 0, 583, 584, 0, 37,
+ 0, 0, 0, 38, 0, 39, 41, 42, 0, 0,
+ 44, 0, 0, 0, 46, 0, 47, 0, 0, 0,
+ 0, 0, 0, 0, 221, 0, 0, 0, 51, 48,
+ 50, 49, 223, 52, 0, 53, 225, 55, 0, 56,
+ 0, 228, 0, 0, 43, 54, 32, 0, 0, 0,
+ 40, 0, 0, 0, 0, 0, 45, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 109, 110, 111, 0,
+ 0, 113, 115, 116, 0, 0, 117, 0, 118, 0,
+ 0, 0, 120, 121, 122, 0, 0, 0, 0, 0,
+ 0, 34, 123, 124, 125, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 126, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 129, 0, 0, 0, 0, 0, 0, 48, 50,
+ 49, 130, 131, 132, 0, 134, 135, 136, 137, 138,
+ 139, 0, 0, 127, 133, 119, 112, 114, 128, 0,
+ 0, 0, 0, 0, 0, 45, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 109, 110, 111, 0, 0,
+ 113, 115, 116, 0, 0, 117, 0, 118, 0, 0,
+ 0, 120, 121, 122, 0, 0, 0, 0, 0, 0,
+ 394, 123, 124, 125, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 126, 0, 0, 0, 395, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 129, 0, 0, 0, 0, 0, 399, 396, 398, 0,
+ 130, 131, 132, 0, 134, 135, 136, 137, 138, 139,
+ 0, 0, 127, 133, 119, 112, 114, 128, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 109, 110, 111, 0, 0, 113,
+ 115, 116, 0, 0, 117, 0, 118, 0, 0, 0,
+ 120, 121, 122, 0, 0, 0, 0, 0, 0, 394,
+ 123, 124, 125, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 126, 0, 0, 0, 395, 0, 0,
+ 0, 0, 0, 0, 0, 397, 0, 0, 0, 129,
+ 0, 0, 0, 0, 0, 399, 396, 398, 0, 130,
+ 131, 132, 0, 134, 135, 136, 137, 138, 139, 0,
+ 0, 127, 133, 119, 112, 114, 128, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 209, 0, 0, 0, 0, 211, 0,
29, 30, 31, 213, 0, 0, 0, 0, 0, 0,
- 214, 33, 0, 0, 0, 0, 0, 0, 216, 217,
+ 214, 215, 0, 0, 0, 0, 0, 0, 216, 217,
0, 0, 218, 36, 0, 37, 0, 0, 0, 38,
0, 39, 41, 42, 0, 0, 44, 0, 0, 0,
46, 0, 47, 0, 0, 0, 0, 0, 220, 0,
221, 0, 0, 0, 51, 219, 222, 49, 223, 52,
224, 53, 225, 55, 226, 56, 227, 228, 0, 0,
43, 54, 32, 210, 212, 0, 40, 0, 0, 0,
+ 0, 0, 45, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 209, 0, 0, 0, 0, 211, 0, 29,
+ 30, 31, 213, 0, 0, 0, 0, 0, 0, 214,
+ 33, 0, 0, 0, 0, 0, 0, 216, 217, 0,
+ 0, 218, 36, 0, 37, 0, 0, 0, 38, 0,
+ 39, 41, 42, 0, 0, 44, 0, 0, 0, 46,
+ 0, 47, 0, 0, 0, 0, 0, 220, 0, 221,
+ 0, 0, 0, 51, 219, 222, 49, 223, 52, 224,
+ 53, 225, 55, 226, 56, 227, 228, 0, 0, 43,
+ 54, 32, 210, 212, 0, 40, 0, 0, 0, 0,
0, 45, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 586, 110, 111, 0, 0, 588, 115, 590, 30,
- 31, 591, 0, 118, 0, 0, 0, 120, 593, 594,
- 0, 0, 0, 0, 0, 0, 595, 596, 124, 125,
+ 0, 587, 110, 111, 0, 0, 589, 115, 591, 30,
+ 31, 592, 0, 118, 0, 0, 0, 120, 594, 595,
+ 0, 0, 0, 0, 0, 0, 596, 597, 124, 125,
218, 36, 0, 37, 0, 0, 0, 38, 0, 39,
- 597, 42, 0, 0, 599, 0, 0, 0, 46, 0,
- 47, 0, 0, 0, 0, 0, 601, 0, 221, 0,
- 0, 0, 603, 600, 602, 49, 604, 605, 606, 53,
- 608, 609, 610, 611, 612, 613, 0, 0, 598, 607,
- 592, 587, 589, 128, 40, 0, 0, 0, 0, 45,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 361,
- 110, 111, 0, 0, 363, 115, 365, 30, 31, 366,
- 0, 118, 0, 0, 0, 120, 368, 369, 0, 0,
- 0, 0, 0, 0, 370, 371, 124, 125, 218, 36,
- 0, 37, 0, 0, 0, 38, 0, 39, 372, 42,
- 0, 0, 374, 0, 0, 0, 46, 0, 47, 0,
- -268, 0, 0, 0, 376, 0, 221, 0, 0, 0,
- 378, 375, 377, 49, 379, 380, 381, 53, 383, 384,
- 385, 386, 387, 388, 0, 0, 373, 382, 367, 362,
- 364, 128, 40, 0, 0, 0, 0, 45, 0, 0,
- 0, 0, 0, 0, 0, 0, 0,
+ 598, 42, 0, 0, 600, 0, 0, 0, 46, 0,
+ 47, 0, 0, 0, 0, 0, 602, 0, 221, 0,
+ 0, 0, 604, 601, 603, 49, 605, 606, 607, 53,
+ 609, 610, 611, 612, 613, 614, 0, 0, 599, 608,
+ 593, 588, 590, 128, 40, 0, 0, 0, 0, 0,
+ 45, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 362, 110, 111, 0, 0, 364, 115, 366, 30, 31,
+ 367, 0, 118, 0, 0, 0, 120, 369, 370, 0,
+ 0, 0, 0, 0, 0, 371, 372, 124, 125, 218,
+ 36, 0, 37, 0, 0, 0, 38, 0, 39, 373,
+ 42, 0, 0, 375, 0, 0, 0, 46, 0, 47,
+ 0, -268, 0, 0, 0, 377, 0, 221, 0, 0,
+ 0, 379, 376, 378, 49, 380, 381, 382, 53, 384,
+ 385, 386, 387, 388, 389, 0, 0, 374, 383, 368,
+ 363, 365, 128, 40, 0, 0, 0, 0, 0, 45,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 534, 311, 497, 309, 532, 461, 498, 499, 516, 515,
- 619, 638, 16, 552, 436, 358, 616, 472, 562, 320,
- 528, 238, 487, 182, 250, 243, 253, 182, 302, 641,
- 627, 632, 150, 485, 143, 454, 439, 402, 445, 559,
- 237, 574, 250, 578, 561, 186, 618, 458, 238, 349,
- 573, 449, 447, 571, 243, 347, 450, 243, 460, 351,
- 238, 353, 358, 410, 415, 439, 176, 188, 436, 250,
- 467, 417, 433, 182, 425, 429, 302, 169, 456, 358,
- 171, 140, 336, 334, 338, 344, 436, 392, 390, 400,
- 163, 302, 307, 148, 146, 339, 439, 404, 302, 358,
- 404, 358, 0, 482, 501, 480, 0, 642, 0, 479,
- 0, 0, 0, 320, 60, 0, 186, 501, 90, 60,
- 60, 489, 302, 60, 617, 93, 0, 88, 0, 405,
- 0, 461, 405, 60, 60, 451, 180, 60, 0, 180,
- 60, 60, 60, 451, 60, 95, 89, 146, 266, 287,
- 60, 146, 407, 270, 60, 288, 178, 60, 106, 452,
- 0, 60, 60, 60, 102, 60, 302, 332, 286, 60,
- 92, 452, 60, 60, 451, 60, 165, 168, 285, 432,
- 284, 435, 60, 60, 108, 501, 329, 94, 540, 96,
- 60, 330, 60, 302, 494, 60, 77, 237, 60, 404,
- 452, 341, 471, 72, 60, 60, 67, 69, 60, 60,
- 68, 0, 70, 60, 60, 60, 61, 180, 60, 60,
- 98, 491, 60, 91, 490, 60, 60, 60, 493, 60,
- 84, 405, 60, 97, 492, 305, 0, 60, 0, 298,
- 0, 100, 270, 298, 270, 298, 106, 298, 270, 0,
- 270, 60, 270, 60, 316, 0, 270, 0, 270, 298,
- 291, 326, 303, 60, 270, 319, 313, 300, 270, 297,
- 60, 60, 108, 175, 295, 270, 270, 290, 60, 501,
- 273, 317, 60, 270, 60, 278, 509, 270, 0, 270,
- 0, 289, 0, 548, 0, 293, 551, 0, 500, 510,
- 501, 501, 0, 544, 501, 0, 0, 0, 509, 0,
- 0, 509, 520, 521, 522, 523, 527, 524, 525, 0,
- 500, 510, 0, 500, 510, 564, 520, 521, 522, 523,
- 527, 524, 525, 581, 0, 0, 0, 0, 0, 0,
- 584, 585, 520, 521, 522, 523, 527, 524, 525, 556,
- 0, 0, 0, 0, 0, 0, 557, 558, 520, 521,
- 522, 523, 527, 524, 525, 0, 0, 0, 0, 0,
+ 639, 310, 529, 533, 516, 535, 517, 499, 500, 462,
+ 498, 620, 553, 312, 243, 16, 562, 440, 437, 633,
+ 238, 250, 473, 182, 253, 182, 617, 488, 359, 563,
+ 303, 321, 619, 642, 150, 575, 560, 250, 628, 163,
+ 426, 348, 250, 579, 186, 350, 182, 574, 468, 340,
+ 430, 345, 572, 434, 359, 457, 448, 446, 238, 450,
+ 455, 459, 243, 243, 461, 352, 238, 451, 354, 148,
+ 403, 483, 486, 176, 437, 143, 440, 401, 411, 335,
+ 188, 437, 440, 169, 237, 171, 237, 140, 359, 393,
+ 337, 303, 308, 416, 391, 146, 418, 303, 405, 359,
+ 359, 0, 0, 146, 0, 0, 0, 60, 178, 60,
+ 0, 452, 288, 0, 303, 60, 405, 60, 405, 180,
+ 285, 60, 60, 60, 491, 186, 286, 60, 287, 60,
+ 406, 453, 502, 502, 303, 643, 545, 60, 321, 453,
+ 60, 165, 180, 60, 60, 490, 180, 60, 406, 60,
+ 406, 452, 267, 146, 60, 60, 60, 271, 408, 289,
+ 60, 84, 69, 168, 60, 60, 60, 100, 106, 60,
+ 97, 98, 96, 502, 481, 0, 541, 72, 480, 436,
+ 433, 60, 60, 333, 60, 60, 91, 92, 90, 60,
+ 93, 60, 60, 89, 108, 60, 94, 339, 77, 88,
+ 60, 502, 462, 331, 60, 95, 303, 61, 618, 106,
+ 342, 330, 60, 60, 453, 452, 60, 60, 494, 495,
+ 60, 60, 493, 60, 60, 492, 60, 70, 68, 60,
+ 60, 102, 67, 60, 271, 108, 175, 299, 271, 0,
+ 299, 0, 271, 0, 314, 271, 294, 299, 60, 60,
+ 60, 0, 271, 271, 271, 271, 60, 279, 274, 320,
+ 0, 271, 318, 60, 0, 317, 0, 296, 271, 327,
+ 292, 60, 60, 472, 0, 304, 271, 271, 291, 290,
+ 557, 299, 299, 541, 549, 615, 271, 271, 502, 0,
+ 552, 0, 502, 0, 0, 510, 0, 0, 502, 510,
+ 0, 0, 303, 298, 301, 510, 473, 501, 511, 0,
+ 0, 501, 511, 0, 0, 0, 0, 501, 511, 521,
+ 522, 523, 524, 528, 525, 526, 582, 0, 0, 0,
+ 0, 0, 0, 585, 586, 521, 522, 523, 524, 528,
+ 525, 526, 557, 0, 0, 0, 0, 0, 0, 558,
+ 559, 521, 522, 523, 524, 528, 525, 526, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 306, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 556, 0, 0, 540, 0, 614,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 565, 521, 522, 523,
+ 524, 528, 525, 526, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 472, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 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 [] = {
- 36, 36, 24, 7, 55, 7, 7, 7, 60, 36,
- 8, 7, 37, 7, 7, 33, 55, 55, 60, 36,
- 36, 33, 33, 55, 8, 33, 7, 7, 34, 36,
- 16, 20, 7, 36, 7, 7, 33, 36, 33, 60,
- 7, 7, 7, 5, 7, 5, 5, 90, 33, 36,
- 7, 33, 7, 36, 7, 33, 66, 36, 7, 36,
- 29, 7, 33, 31, 1, 7, 17, 55, 60, 33,
- 60, 2, 8, 7, 48, 66, 1, 7, 36, 2,
- 8, 7, 36, 2, 60, 2, 8, 7, 17, 1,
- 60, 36, 0, 36, 8, 36, 48, 36, 33, 8,
- 61, 1, 6, 36, 60, 8, -1, 8, -1, 15,
- 48, 10, 7, 8, 61, 8, 20, -1, -1, -1,
- -1, -1, 8, -1, -1, -1, -1, 48, 34, 79,
- 40, 79, 8, 77, 61, 8, 60, 8, 8, 79,
- 8, 51, -1, 40, 42, 61, 62, 8, 61, 62,
- 8, 7, -1, 56, 51, 53, 55, 8, 90, 60,
- 50, 79, 8, 56, 54, 61, 62, 61, 62, 61,
- 62, 40, 61, 62, 60, 40, 61, 62, 61, 62,
- 56, 8, 51, 56, 50, 7, 51, 15, 54, 60,
- 60, 25, 60, 27, 25, 56, 27, 61, 62, 61,
- 62, 36, 60, 29, 38, 29, 34, 38, 36, 25,
- 61, 27, 29, -1, 60, 25, 12, 27, 29, 25,
- 29, 27, 38, 25, 29, 27, 61, 62, 38, 12,
- 7, 12, 38, 60, 8, 25, 38, 27, -1, 61,
- 62, 25, 8, 27, 7, -1, 15, 7, 38, 75,
- 25, 75, 27, 8, 38, 25, 33, 27, 75, -1,
- 86, 57, 86, 38, 75, 34, 75, 63, 38, 86,
- 75, 15, 15, -1, 57, 86, 57, 86, -1, -1,
- 63, 86, 63, 61, 62, -1, -1, 61, 62, 15,
- 34, 34, 36, 36, -1, 61, 62, 47, 61, 62,
- 15, 61, 62, -1, 18, 19, 61, 62, 34, 15,
- 36, 61, 62, 91, -1, 92, 18, 19, 33, 34,
- 29, 36, 18, 19, 18, 19, 29, 33, 34, 29,
- 36, 45, 46, 25, 29, 27, -1, -1, -1, -1,
- -1, 91, -1, 45, 46, -1, 38, -1, -1, 45,
- 46, 45, 46, -1, -1, -1, -1, 66, 67, 68,
- -1, -1, -1, 66, 67, 68, 66, 67, 68, -1,
- -1, 66, 67, 68, -1, -1, 23, 24, -1, -1,
- -1, 29, -1, 92, -1, 32, 23, 24, 35, 92,
- 37, 29, 92, 23, 24, 32, 29, 92, 35, -1,
- 37, 29, 32, 23, 24, 35, -1, 37, -1, -1,
- 29, -1, 32, 23, 24, 35, -1, 37, 66, 67,
- 68, 31, 32, -1, 29, 35, -1, 37, 66, 67,
- 68, 36, -1, 66, 67, 68, -1, -1, 66, 67,
- 68, -1, -1, -1, 92, -1, -1, 66, 67, 68,
- -1, -1, -1, -1, 92, -1, -1, 23, 24, 92,
- -1, 66, 67, 68, 92, 31, 32, 23, 24, 35,
- -1, 37, -1, 92, -1, 31, 32, 23, 24, 35,
- -1, 37, 29, 23, 24, 31, 32, 92, -1, 35,
- 29, 37, 32, 29, -1, 35, -1, 37, 94, 95,
- 96, 97, 98, 99, 29, -1, -1, -1, -1, -1,
- -1, 36, -1, -1, 61, 62, -1, -1, -1, 66,
- 67, 68, 61, 62, -1, 61, 62, 66, 67, 68,
- 66, 67, 68, -1, -1, -1, -1, -1, -1, -1,
- 29, 66, 67, 68, -1, 92, -1, -1, 29, -1,
- -1, 29, -1, 92, -1, -1, 92, -1, -1, -1,
- -1, -1, 23, 24, -1, -1, -1, 92, -1, -1,
- 31, 32, 61, 62, 35, -1, 37, 66, 67, 68,
- 61, 62, 3, 61, 62, 66, 67, 68, 66, 67,
- 68, -1, 13, -1, -1, -1, 17, -1, -1, -1,
- -1, -1, -1, 92, -1, 26, -1, 28, -1, -1,
- 31, 92, -1, -1, 92, -1, -1, -1, 39, -1,
- 41, 42, -1, -1, -1, -1, -1, -1, 49, -1,
- -1, 52, 53, -1, -1, -1, -1, 58, -1, 12,
- 13, 3, -1, 64, -1, -1, -1, -1, -1, 22,
- -1, 13, -1, -1, -1, 17, 29, -1, -1, 80,
- 33, 34, -1, 36, 26, -1, 28, -1, -1, -1,
- 43, -1, -1, -1, 47, -1, -1, 39, -1, 41,
- 42, -1, -1, -1, -1, -1, -1, 49, -1, -1,
- 52, 53, 65, 66, 67, 68, 58, 70, -1, -1,
- -1, -1, 64, -1, -1, -1, -1, -1, 81, 82,
- 83, -1, 12, 13, 87, -1, -1, -1, 80, 92,
- -1, -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, 92, 65, 66, 67, 68, -1, 70, -1,
- -1, -1, 12, 13, -1, -1, -1, -1, -1, 81,
- 82, 83, 22, -1, -1, 87, -1, -1, -1, 29,
- 92, -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, 92, 65, 66, 67, 68, -1, 70, -1,
- -1, -1, 12, 13, -1, -1, -1, -1, -1, 81,
- 82, 83, 22, -1, -1, 87, -1, -1, -1, 29,
- 92, -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, 92, 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,
- 92, -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,
+ 36, 36, 7, 55, 17, 7, 7, 60, 8, 7,
+ 7, 37, 36, 7, 20, 33, 55, 55, 60, 36,
+ 36, 33, 33, 55, 8, 7, 36, 7, 16, 33,
+ 7, 34, 7, 7, 7, 60, 7, 36, 33, 7,
+ 36, 33, 33, 5, 7, 5, 5, 33, 29, 36,
+ 91, 36, 7, 36, 7, 33, 7, 7, 66, 66,
+ 36, 33, 7, 7, 31, 1, 7, 24, 33, 2,
+ 60, 60, 36, 8, 8, 7, 55, 1, 36, 48,
+ 2, 8, 7, 2, 7, 2, 79, 36, 17, 36,
+ 60, 7, 48, 36, 36, 61, 33, 36, 1, 60,
+ 0, 8, 8, 1, 8, 6, 8, -1, -1, 61,
+ 48, 7, 8, 8, 60, 8, 10, -1, 8, 20,
+ 8, -1, 48, -1, 8, 79, 40, 40, 15, 77,
+ -1, 61, 60, 8, 8, 8, 15, 51, 51, 79,
+ 8, 61, 62, 61, 62, 50, 7, 34, 8, 54,
+ 61, 62, 61, 62, 56, 34, 60, 42, 79, 8,
+ 91, 55, 40, 56, 12, 60, 56, 50, 53, 61,
+ 62, 54, 60, 51, 29, 61, 62, 61, 40, 61,
+ 62, 12, 56, 29, 25, 60, 27, 60, 56, 51,
+ 61, 62, 25, 7, 27, 8, 12, 38, -1, 25,
+ 60, 27, 7, -1, 25, 38, 27, 29, 25, 57,
+ 27, 60, 38, 7, 25, 63, 27, 38, 36, 33,
+ 75, 38, 25, 25, 27, 27, 57, 38, 29, 75,
+ -1, 86, 63, 7, 29, 38, 38, 25, 29, 27,
+ 86, 57, 8, 61, 62, 8, -1, 63, 61, 62,
+ 38, 15, 25, 75, 27, 8, 61, 62, 25, -1,
+ 27, 61, 62, -1, 86, 38, -1, 61, 62, -1,
+ 34, 38, 36, 25, 75, 27, 61, 62, -1, 93,
+ 75, 15, -1, -1, 75, 86, 38, 61, 62, 89,
+ 25, 86, 27, -1, 60, 86, 18, 19, 61, 62,
+ 34, -1, 36, 38, 18, 19, -1, 92, 61, 62,
+ -1, -1, -1, 29, 47, 15, 18, 19, -1, -1,
+ 15, 18, 19, 45, 46, 29, -1, -1, 61, 62,
+ 29, 45, 46, 33, 34, 29, 36, 15, 33, 34,
+ -1, 36, 29, 45, 46, 29, -1, -1, 45, 46,
+ 66, 67, 68, 29, -1, -1, 34, -1, 36, 92,
+ -1, -1, 66, 67, 68, 29, -1, 66, 67, 68,
+ -1, -1, 66, 67, 68, -1, 29, 93, -1, 66,
+ 67, 68, 66, 67, 68, 29, 23, 24, -1, 93,
+ 66, 67, 68, 29, 93, 32, -1, -1, 35, 93,
+ 37, -1, 66, 67, 68, 29, 93, -1, 29, 93,
+ -1, -1, -1, 66, 67, 68, 29, 93, -1, -1,
+ -1, 29, 66, 67, 68, 23, 24, 29, -1, 93,
+ 66, 67, 68, -1, 32, -1, 29, 35, -1, 37,
+ 93, -1, 66, 67, 68, 66, 67, 68, -1, 93,
+ -1, 29, -1, 66, 67, 68, -1, 93, 66, 67,
+ 68, -1, -1, -1, 66, 67, 68, 23, 24, 93,
+ -1, -1, 93, 66, 67, 68, 32, -1, -1, 35,
+ 93, 37, -1, -1, -1, 93, -1, -1, 66, 67,
+ 68, 93, 29, -1, -1, 23, 24, -1, -1, 36,
+ 93, -1, -1, 31, 32, 23, 24, 35, -1, 37,
+ -1, -1, -1, -1, 32, 93, -1, 35, -1, 37,
+ 95, 96, 97, 98, 99, 100, 29, 23, 24, 66,
+ 67, 68, -1, 36, 29, 31, 32, 23, 24, 35,
+ -1, 37, 29, -1, -1, 31, 32, -1, -1, 35,
+ 29, 37, -1, -1, -1, -1, 93, -1, -1, -1,
+ -1, -1, -1, 66, 67, 68, 61, 62, -1, -1,
+ 29, 66, 67, 68, 61, 62, -1, -1, 29, 66,
+ 67, 68, 61, 62, -1, 23, 24, 66, 67, 68,
+ 93, -1, -1, 31, 32, -1, -1, 35, 93, 37,
+ -1, -1, 61, 62, -1, -1, 93, 66, 67, 68,
+ 61, 62, 3, -1, 93, 66, 67, 68, -1, -1,
+ -1, -1, 13, -1, -1, -1, 17, -1, -1, -1,
+ 3, -1, -1, -1, 93, 26, -1, 28, -1, -1,
+ 13, -1, 93, -1, 17, -1, -1, -1, 39, -1,
+ 41, 42, -1, 26, -1, 28, -1, -1, 49, -1,
+ -1, 52, 53, -1, -1, 29, 39, 58, 41, 42,
+ -1, -1, -1, 64, -1, -1, 49, -1, -1, 52,
+ 53, -1, -1, -1, -1, 58, -1, -1, -1, 80,
+ -1, 64, -1, -1, -1, -1, -1, 61, 62, -1,
+ -1, -1, 66, 67, 68, -1, -1, 80, -1, -1,
-1, -1, -1, -1, -1, -1, -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, 92, -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, 92, -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, 92, -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, 12, 13, -1, 93,
+ -1, -1, -1, -1, -1, -1, 22, -1, -1, 3,
+ -1, -1, -1, 29, -1, -1, -1, 33, 34, 13,
+ 36, -1, -1, 17, -1, -1, -1, 43, -1, -1,
+ -1, 47, 26, -1, 28, -1, -1, 31, -1, -1,
+ -1, -1, -1, -1, -1, 39, -1, 41, 42, 65,
+ 66, 67, 68, -1, 70, 49, -1, -1, 52, 53,
+ -1, -1, -1, -1, 58, 81, 82, 83, -1, -1,
+ 64, 87, -1, -1, -1, -1, -1, 93, -1, -1,
+ -1, -1, -1, -1, -1, -1, 80, -1, -1, -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, 92, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, 7, -1, -1,
- -1, 11, 12, 13, -1, -1, -1, -1, -1, -1,
+ -1, 12, 13, -1, -1, -1, -1, -1, -1, 12,
+ 13, 22, -1, -1, -1, -1, -1, -1, 29, 22,
+ -1, -1, 33, 34, -1, 36, 29, -1, -1, -1,
+ 33, 34, 43, 36, -1, -1, 47, -1, -1, -1,
+ 43, -1, -1, -1, 47, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, 65, 66, 67, 68, -1, 70,
+ -1, -1, 65, 66, 67, 68, -1, 70, -1, -1,
+ 81, 82, 83, -1, -1, -1, 87, -1, 81, 82,
+ 83, -1, 93, -1, 87, -1, -1, -1, -1, -1,
+ 93, -1, 12, 13, -1, -1, -1, -1, -1, -1,
+ 12, 13, 22, -1, -1, -1, -1, -1, -1, 29,
+ 22, -1, -1, 33, 34, -1, 36, 29, -1, -1,
+ -1, 33, 34, 43, 36, -1, -1, 47, -1, -1,
+ -1, 43, -1, -1, -1, 47, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, 65, 66, 67, 68, -1,
+ 70, -1, -1, 65, 66, 67, 68, -1, 70, -1,
+ -1, 81, 82, 83, -1, -1, -1, 87, -1, 81,
+ 82, 83, -1, 93, -1, 87, -1, -1, -1, -1,
+ -1, 93, -1, 12, 13, -1, -1, -1, -1, -1,
+ -1, 12, 13, 22, -1, -1, -1, -1, -1, -1,
+ 29, 22, -1, -1, 33, 34, -1, 36, 29, -1,
+ -1, -1, 33, 34, 43, 36, -1, -1, 47, -1,
+ -1, -1, 43, -1, -1, -1, 47, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, 65, 66, 67, 68,
+ -1, 70, -1, -1, 65, 66, 67, 68, -1, 70,
+ -1, -1, 81, 82, 83, -1, -1, -1, 87, -1,
+ 81, 82, 83, -1, 93, -1, 87, -1, -1, -1,
+ -1, -1, 93, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 12, 13, -1, -1, -1, -1, -1, -1,
-1, -1, 22, -1, -1, -1, -1, -1, -1, 29,
-1, -1, -1, 33, 34, -1, 36, -1, -1, -1,
- 40, -1, 42, 43, 44, -1, -1, 47, -1, -1,
- -1, 51, -1, 53, -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, -1,
-1, -1, -1, -1, -1, 65, 66, 67, 68, -1,
- 70, -1, 72, -1, 74, -1, 76, -1, -1, -1,
+ 70, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 81, 82, 83, -1, -1, -1, 87, -1, -1,
- -1, -1, 92, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, 93, -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, -1, -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, 93, -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, 93,
+ -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, 93, -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, 70, -1, 72, -1, 74, -1, 76, -1, -1,
-1, -1, 81, 82, 83, -1, -1, -1, 87, -1,
- -1, -1, -1, 92, -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, 92, -1, -1,
+ -1, -1, -1, -1, 93, -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,
+ 93, -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, 93, -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, 93, -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,
@@ -840,83 +882,74 @@ const short QmlJSGrammar::action_check [] = {
-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, 92, -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, 92, -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, 92,
- -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, 69, 70, -1,
- 72, 73, 74, -1, 76, -1, 78, -1, -1, 81,
- 82, 83, -1, -1, -1, 87, -1, -1, -1, -1,
- 92, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 93, -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, 93, -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, 30,
+ -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,
- 61, -1, -1, -1, 65, 66, 67, 68, 69, 70,
- -1, 72, 73, 74, -1, 76, -1, 78, -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, 92, -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, 92,
- -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, -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, -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,
+ -1, -1, 93, -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,
- 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, 92, -1, -1, -1, -1, -1, -1,
+ -1, -1, 61, -1, -1, -1, 65, 66, 67, 68,
+ 69, 70, -1, 72, 73, 74, -1, 76, -1, 78,
+ -1, -1, 81, 82, 83, -1, -1, -1, 87, -1,
+ -1, -1, -1, -1, 93, -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, 69, 70, -1, 72, 73, 74, -1, 76,
+ -1, 78, -1, -1, 81, 82, 83, -1, -1, -1,
+ 87, -1, -1, -1, -1, -1, 93, -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, 93, -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, -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,
-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,
@@ -926,7 +959,17 @@ const short QmlJSGrammar::action_check [] = {
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, 92, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, 93, -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, 93, -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,
@@ -935,67 +978,68 @@ const short QmlJSGrammar::action_check [] = {
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, 92,
- -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, 92, -1, -1,
- -1, -1, -1, -1, -1, -1, -1,
+ 83, 84, 85, 86, 87, -1, -1, -1, -1, -1,
+ 93, -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, 93,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1,
- 15, 2, 105, 3, 29, 15, 4, 2, 15, 29,
- 9, 15, 3, 15, 3, 2, 19, 39, 15, 15,
- 13, 15, 3, 15, 2, 15, 3, 15, 3, 11,
- 13, 15, 71, 39, 39, 3, 22, 2, 99, 19,
- 4, 15, 2, 15, 29, 15, 19, 3, 15, 3,
- 29, 22, 15, 29, 15, 2, 22, 15, 2, 2,
- 15, 2, 2, 2, 2, 22, 3, 15, 3, 2,
- 39, 3, 3, 15, 97, 94, 3, 39, 2, 2,
- 39, 3, 3, 2, 2, 101, 3, 40, 39, 39,
- 39, 3, 2, 39, 39, 15, 22, 13, 3, 2,
- 13, 2, -1, 39, 13, 35, -1, 16, -1, 39,
- -1, -1, -1, 15, 48, -1, 15, 13, 52, 48,
- 48, 50, 3, 48, 20, 53, -1, 52, -1, 45,
- -1, 15, 45, 48, 48, 50, 50, 48, -1, 50,
- 48, 48, 48, 50, 48, 53, 52, 39, 48, 53,
- 48, 39, 44, 53, 48, 53, 44, 48, 15, 50,
- -1, 48, 48, 48, 58, 48, 3, 72, 53, 48,
- 53, 50, 48, 48, 50, 48, 62, 64, 53, 82,
- 53, 82, 48, 48, 41, 13, 88, 53, 16, 54,
- 48, 72, 48, 3, 50, 48, 54, 4, 48, 13,
- 50, 100, 86, 56, 48, 48, 50, 50, 48, 48,
- 50, -1, 51, 48, 48, 48, 51, 50, 48, 48,
- 54, 50, 48, 53, 50, 48, 48, 48, 50, 48,
- 53, 45, 48, 54, 50, 72, -1, 48, -1, 48,
- -1, 60, 53, 48, 53, 48, 15, 48, 53, -1,
- 53, 48, 53, 48, 65, -1, 53, -1, 53, 48,
- 55, 70, 72, 48, 53, 70, 63, 70, 53, 70,
- 48, 48, 41, 42, 59, 53, 53, 55, 48, 13,
- 57, 70, 48, 53, 48, 55, 20, 53, -1, 53,
- -1, 55, -1, 5, -1, 61, 5, -1, 32, 33,
- 13, 13, -1, 16, 13, -1, -1, -1, 20, -1,
- -1, 20, 22, 23, 24, 25, 26, 27, 28, -1,
- 32, 33, -1, 32, 33, 21, 22, 23, 24, 25,
- 26, 27, 28, 13, -1, -1, -1, -1, -1, -1,
- 20, 21, 22, 23, 24, 25, 26, 27, 28, 13,
- -1, -1, -1, -1, -1, -1, 20, 21, 22, 23,
- 24, 25, 26, 27, 28, -1, -1, -1, -1, -1,
+ 15, 3, 13, 29, 29, 15, 15, 4, 2, 15,
+ 105, 9, 15, 2, 15, 3, 29, 22, 3, 15,
+ 15, 2, 39, 15, 3, 15, 19, 3, 2, 15,
+ 3, 15, 19, 11, 71, 15, 19, 2, 13, 39,
+ 97, 2, 2, 15, 15, 3, 15, 29, 39, 15,
+ 94, 101, 29, 3, 2, 2, 15, 99, 15, 22,
+ 3, 3, 15, 15, 2, 2, 15, 22, 2, 39,
+ 2, 39, 39, 3, 3, 39, 22, 39, 2, 2,
+ 15, 3, 22, 39, 4, 39, 4, 3, 2, 40,
+ 3, 3, 2, 2, 39, 39, 3, 3, 13, 2,
+ 2, -1, -1, 39, -1, -1, -1, 48, 44, 48,
+ -1, 50, 53, -1, 3, 48, 13, 48, 13, 50,
+ 53, 48, 48, 48, 50, 15, 53, 48, 53, 48,
+ 45, 50, 13, 13, 3, 16, 16, 48, 15, 50,
+ 48, 62, 50, 48, 48, 50, 50, 48, 45, 48,
+ 45, 50, 48, 39, 48, 48, 48, 53, 44, 53,
+ 48, 53, 50, 64, 48, 48, 48, 60, 15, 48,
+ 54, 54, 54, 13, 35, -1, 16, 56, 39, 82,
+ 82, 48, 48, 72, 48, 48, 53, 53, 52, 48,
+ 53, 48, 48, 52, 41, 48, 53, 2, 54, 52,
+ 48, 13, 15, 72, 48, 53, 3, 51, 20, 15,
+ 100, 88, 48, 48, 50, 50, 48, 48, 50, 50,
+ 48, 48, 50, 48, 48, 50, 48, 51, 50, 48,
+ 48, 58, 50, 48, 53, 41, 42, 48, 53, -1,
+ 48, -1, 53, -1, 63, 53, 61, 48, 48, 48,
+ 48, -1, 53, 53, 53, 53, 48, 55, 57, 70,
+ -1, 53, 70, 48, -1, 65, -1, 59, 53, 70,
+ 55, 48, 48, 86, -1, 72, 53, 53, 55, 55,
+ 13, 48, 48, 16, 5, 18, 53, 53, 13, -1,
+ 5, -1, 13, -1, -1, 20, -1, -1, 13, 20,
+ -1, -1, 3, 70, 70, 20, 39, 32, 33, -1,
+ -1, 32, 33, -1, -1, -1, -1, 32, 33, 22,
+ 23, 24, 25, 26, 27, 28, 13, -1, -1, -1,
+ -1, -1, -1, 20, 21, 22, 23, 24, 25, 26,
+ 27, 28, 13, -1, -1, -1, -1, -1, -1, 20,
+ 21, 22, 23, 24, 25, 26, 27, 28, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 72, -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, 13, -1, -1, 16, -1, 18,
+ -1, -1, -1, -1, -1, -1, 21, 22, 23, 24,
+ 25, 26, 27, 28, -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,
- 39, -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/libs/qmljs/parser/qmljsgrammar_p.h b/src/libs/qmljs/parser/qmljsgrammar_p.h
index 4328eeb0e7..f28711777c 100644
--- a/src/libs/qmljs/parser/qmljsgrammar_p.h
+++ b/src/libs/qmljs/parser/qmljsgrammar_p.h
@@ -52,12 +52,12 @@ class QML_PARSER_EXPORT QmlJSGrammar
public:
enum VariousConstants {
EOF_SYMBOL = 0,
- REDUCE_HERE = 101,
- SHIFT_THERE = 100,
+ REDUCE_HERE = 102,
+ SHIFT_THERE = 101,
T_AND = 1,
T_AND_AND = 2,
T_AND_EQ = 3,
- T_AS = 91,
+ T_AS = 92,
T_AUTOMATIC_SEMICOLON = 62,
T_BREAK = 4,
T_CASE = 5,
@@ -65,6 +65,7 @@ public:
T_COLON = 7,
T_COMMA = 8,
T_COMMENT = 88,
+ T_COMPATIBILITY_SEMICOLON = 89,
T_CONST = 84,
T_CONTINUE = 9,
T_DEBUGGER = 85,
@@ -78,14 +79,14 @@ public:
T_EQ = 17,
T_EQ_EQ = 18,
T_EQ_EQ_EQ = 19,
- T_ERROR = 93,
+ T_ERROR = 94,
T_FALSE = 83,
- T_FEED_JS_EXPRESSION = 97,
- T_FEED_JS_PROGRAM = 99,
- T_FEED_JS_SOURCE_ELEMENT = 98,
- T_FEED_JS_STATEMENT = 96,
- T_FEED_UI_OBJECT_MEMBER = 95,
- T_FEED_UI_PROGRAM = 94,
+ T_FEED_JS_EXPRESSION = 98,
+ T_FEED_JS_PROGRAM = 100,
+ T_FEED_JS_SOURCE_ELEMENT = 99,
+ T_FEED_JS_STATEMENT = 97,
+ T_FEED_UI_OBJECT_MEMBER = 96,
+ T_FEED_UI_PROGRAM = 95,
T_FINALLY = 20,
T_FOR = 21,
T_FUNCTION = 22,
@@ -97,7 +98,7 @@ public:
T_GT_GT_GT_EQ = 28,
T_IDENTIFIER = 29,
T_IF = 30,
- T_IMPORT = 90,
+ T_IMPORT = 91,
T_IN = 31,
T_INSTANCEOF = 32,
T_LBRACE = 33,
@@ -117,7 +118,7 @@ public:
T_NOT_EQ_EQ = 46,
T_NULL = 81,
T_NUMERIC_LITERAL = 47,
- T_ON = 92,
+ T_ON = 93,
T_OR = 48,
T_OR_EQ = 49,
T_OR_OR = 50,
@@ -125,7 +126,7 @@ public:
T_PLUS_EQ = 52,
T_PLUS_PLUS = 53,
T_PROPERTY = 66,
- T_PUBLIC = 89,
+ T_PUBLIC = 90,
T_QUESTION = 54,
T_RBRACE = 55,
T_RBRACKET = 56,
@@ -154,15 +155,15 @@ public:
T_XOR = 79,
T_XOR_EQ = 80,
- ACCEPT_STATE = 644,
- RULE_COUNT = 349,
- STATE_COUNT = 645,
- TERMINAL_COUNT = 102,
+ ACCEPT_STATE = 645,
+ RULE_COUNT = 350,
+ STATE_COUNT = 646,
+ TERMINAL_COUNT = 103,
NON_TERMINAL_COUNT = 107,
- GOTO_INDEX_OFFSET = 645,
- GOTO_INFO_OFFSET = 2807,
- GOTO_CHECK_OFFSET = 2807
+ GOTO_INDEX_OFFSET = 646,
+ GOTO_INFO_OFFSET = 3019,
+ GOTO_CHECK_OFFSET = 3019
};
static const char *const spell [];
diff --git a/src/libs/qmljs/parser/qmljskeywords_p.h b/src/libs/qmljs/parser/qmljskeywords_p.h
index ee4a2b7c41..0c77ff8584 100644
--- a/src/libs/qmljs/parser/qmljskeywords_p.h
+++ b/src/libs/qmljs/parser/qmljskeywords_p.h
@@ -41,10 +41,16 @@
// We mean it.
//
+// Note on the int() casts in the following code:
+// they casts values from Lexer's anonymous enum (aliasing some of the inherited
+// QmlJSGrammar::VariousConstants) to int when used with inherited values of the
+// enum QmlJSGrammar::VariousConstants in a ?: expression to suppress gcc
+// "enumeral mismatch" warning
+
static inline int classify2(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'a') {
if (s[1].unicode() == 's') {
- return qmlMode ? Lexer::T_AS : Lexer::T_RESERVED_WORD;
+ return qmlMode ? Lexer::T_AS : Lexer::T_IDENTIFIER;
}
}
else if (s[0].unicode() == 'd') {
@@ -62,13 +68,13 @@ static inline int classify2(const QChar *s, bool qmlMode) {
}
else if (qmlMode && s[0].unicode() == 'o') {
if (s[1].unicode() == 'n') {
- return Lexer::T_ON;
+ return qmlMode ? Lexer::T_ON : Lexer::T_IDENTIFIER;
}
}
return Lexer::T_IDENTIFIER;
}
-static inline int classify3(const QChar *s, bool /*qmlMode*/) {
+static inline int classify3(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'f') {
if (s[1].unicode() == 'o') {
if (s[2].unicode() == 'r') {
@@ -79,7 +85,7 @@ static inline int classify3(const QChar *s, bool /*qmlMode*/) {
else if (s[0].unicode() == 'i') {
if (s[1].unicode() == 'n') {
if (s[2].unicode() == 't') {
- return Lexer::T_INT;
+ return qmlMode ? int(Lexer::T_INT) : Lexer::T_IDENTIFIER;
}
}
}
@@ -107,12 +113,12 @@ static inline int classify3(const QChar *s, bool /*qmlMode*/) {
return Lexer::T_IDENTIFIER;
}
-static inline int classify4(const QChar *s, bool /*qmlMode*/) {
+static inline int classify4(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'b') {
if (s[1].unicode() == 'y') {
if (s[2].unicode() == 't') {
if (s[3].unicode() == 'e') {
- return Lexer::T_BYTE;
+ return qmlMode ? int(Lexer::T_BYTE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -128,7 +134,7 @@ static inline int classify4(const QChar *s, bool /*qmlMode*/) {
else if (s[1].unicode() == 'h') {
if (s[2].unicode() == 'a') {
if (s[3].unicode() == 'r') {
- return Lexer::T_CHAR;
+ return qmlMode ? int(Lexer::T_CHAR) : Lexer::T_IDENTIFIER;
}
}
}
@@ -153,7 +159,7 @@ static inline int classify4(const QChar *s, bool /*qmlMode*/) {
if (s[1].unicode() == 'o') {
if (s[2].unicode() == 't') {
if (s[3].unicode() == 'o') {
- return Lexer::T_GOTO;
+ return qmlMode ? int(Lexer::T_GOTO) : Lexer::T_IDENTIFIER;
}
}
}
@@ -162,7 +168,7 @@ static inline int classify4(const QChar *s, bool /*qmlMode*/) {
if (s[1].unicode() == 'o') {
if (s[2].unicode() == 'n') {
if (s[3].unicode() == 'g') {
- return Lexer::T_LONG;
+ return qmlMode ? int(Lexer::T_LONG) : Lexer::T_IDENTIFIER;
}
}
}
@@ -213,7 +219,7 @@ static inline int classify4(const QChar *s, bool /*qmlMode*/) {
return Lexer::T_IDENTIFIER;
}
-static inline int classify5(const QChar *s, bool /*qmlMode*/) {
+static inline int classify5(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'b') {
if (s[1].unicode() == 'r') {
if (s[2].unicode() == 'e') {
@@ -248,7 +254,7 @@ static inline int classify5(const QChar *s, bool /*qmlMode*/) {
if (s[2].unicode() == 'n') {
if (s[3].unicode() == 's') {
if (s[4].unicode() == 't') {
- return Lexer::T_CONST;
+ return qmlMode ? Lexer::T_CONST : Lexer::T_RESERVED_WORD;
}
}
}
@@ -268,7 +274,7 @@ static inline int classify5(const QChar *s, bool /*qmlMode*/) {
if (s[2].unicode() == 'n') {
if (s[3].unicode() == 'a') {
if (s[4].unicode() == 'l') {
- return Lexer::T_FINAL;
+ return qmlMode ? int(Lexer::T_FINAL) : Lexer::T_IDENTIFIER;
}
}
}
@@ -277,7 +283,7 @@ static inline int classify5(const QChar *s, bool /*qmlMode*/) {
if (s[2].unicode() == 'o') {
if (s[3].unicode() == 'a') {
if (s[4].unicode() == 't') {
- return Lexer::T_FLOAT;
+ return qmlMode ? int(Lexer::T_FLOAT) : Lexer::T_IDENTIFIER;
}
}
}
@@ -288,7 +294,7 @@ static inline int classify5(const QChar *s, bool /*qmlMode*/) {
if (s[2].unicode() == 'o') {
if (s[3].unicode() == 'r') {
if (s[4].unicode() == 't') {
- return Lexer::T_SHORT;
+ return qmlMode ? int(Lexer::T_SHORT) : Lexer::T_IDENTIFIER;
}
}
}
@@ -297,7 +303,7 @@ static inline int classify5(const QChar *s, bool /*qmlMode*/) {
if (s[2].unicode() == 'p') {
if (s[3].unicode() == 'e') {
if (s[4].unicode() == 'r') {
- return Lexer::T_SUPER;
+ return qmlMode ? int(Lexer::T_SUPER) : Lexer::T_IDENTIFIER;
}
}
}
@@ -346,7 +352,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
if (s[3].unicode() == 'b') {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'e') {
- return Lexer::T_DOUBLE;
+ return qmlMode ? int(Lexer::T_DOUBLE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -385,7 +391,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
if (s[3].unicode() == 'i') {
if (s[4].unicode() == 'v') {
if (s[5].unicode() == 'e') {
- return Lexer::T_NATIVE;
+ return qmlMode ? int(Lexer::T_NATIVE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -398,7 +404,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
if (s[3].unicode() == 'l') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'c') {
- return qmlMode ? Lexer::T_PUBLIC : Lexer::T_RESERVED_WORD;
+ return qmlMode ? Lexer::T_PUBLIC : Lexer::T_IDENTIFIER;
}
}
}
@@ -435,7 +441,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
if (s[3].unicode() == 't') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'c') {
- return Lexer::T_STATIC;
+ return qmlMode ? int(Lexer::T_STATIC) : Lexer::T_IDENTIFIER;
}
}
}
@@ -459,7 +465,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
if (s[3].unicode() == 'o') {
if (s[4].unicode() == 'w') {
if (s[5].unicode() == 's') {
- return Lexer::T_THROWS;
+ return qmlMode ? int(Lexer::T_THROWS) : Lexer::T_IDENTIFIER;
}
}
}
@@ -480,7 +486,7 @@ static inline int classify6(const QChar *s, bool qmlMode) {
return Lexer::T_IDENTIFIER;
}
-static inline int classify7(const QChar *s, bool /*qmlMode*/) {
+static inline int classify7(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'b') {
if (s[1].unicode() == 'o') {
if (s[2].unicode() == 'o') {
@@ -488,7 +494,7 @@ static inline int classify7(const QChar *s, bool /*qmlMode*/) {
if (s[4].unicode() == 'e') {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'n') {
- return Lexer::T_BOOLEAN;
+ return qmlMode ? int(Lexer::T_BOOLEAN) : Lexer::T_IDENTIFIER;
}
}
}
@@ -548,7 +554,7 @@ static inline int classify7(const QChar *s, bool /*qmlMode*/) {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 'g') {
if (s[6].unicode() == 'e') {
- return Lexer::T_PACKAGE;
+ return qmlMode ? int(Lexer::T_PACKAGE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -561,7 +567,7 @@ static inline int classify7(const QChar *s, bool /*qmlMode*/) {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'e') {
- return Lexer::T_PRIVATE;
+ return qmlMode ? int(Lexer::T_PRIVATE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -581,7 +587,7 @@ static inline int classify8(const QChar *s, bool qmlMode) {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'c') {
if (s[7].unicode() == 't') {
- return Lexer::T_ABSTRACT;
+ return qmlMode ? int(Lexer::T_ABSTRACT) : Lexer::T_IDENTIFIER;
}
}
}
@@ -649,7 +655,7 @@ static inline int classify8(const QChar *s, bool qmlMode) {
if (s[5].unicode() == 'r') {
if (s[6].unicode() == 't') {
if (s[7].unicode() == 'y') {
- return Lexer::T_PROPERTY;
+ return qmlMode ? Lexer::T_PROPERTY : Lexer::T_IDENTIFIER;
}
}
}
@@ -683,7 +689,7 @@ static inline int classify8(const QChar *s, bool qmlMode) {
if (s[5].unicode() == 'i') {
if (s[6].unicode() == 'l') {
if (s[7].unicode() == 'e') {
- return Lexer::T_VOLATILE;
+ return qmlMode ? int(Lexer::T_VOLATILE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -695,7 +701,7 @@ static inline int classify8(const QChar *s, bool qmlMode) {
return Lexer::T_IDENTIFIER;
}
-static inline int classify9(const QChar *s, bool /*qmlMode*/) {
+static inline int classify9(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'i') {
if (s[1].unicode() == 'n') {
if (s[2].unicode() == 't') {
@@ -705,7 +711,7 @@ static inline int classify9(const QChar *s, bool /*qmlMode*/) {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'c') {
if (s[8].unicode() == 'e') {
- return Lexer::T_INTERFACE;
+ return qmlMode ? int(Lexer::T_INTERFACE) : Lexer::T_IDENTIFIER;
}
}
}
@@ -724,7 +730,7 @@ static inline int classify9(const QChar *s, bool /*qmlMode*/) {
if (s[6].unicode() == 't') {
if (s[7].unicode() == 'e') {
if (s[8].unicode() == 'd') {
- return Lexer::T_PROTECTED;
+ return qmlMode ? int(Lexer::T_PROTECTED) : Lexer::T_IDENTIFIER;
}
}
}
@@ -743,7 +749,7 @@ static inline int classify9(const QChar *s, bool /*qmlMode*/) {
if (s[6].unicode() == 'e') {
if (s[7].unicode() == 'n') {
if (s[8].unicode() == 't') {
- return Lexer::T_TRANSIENT;
+ return qmlMode ? int(Lexer::T_TRANSIENT) : Lexer::T_IDENTIFIER;
}
}
}
@@ -756,7 +762,7 @@ static inline int classify9(const QChar *s, bool /*qmlMode*/) {
return Lexer::T_IDENTIFIER;
}
-static inline int classify10(const QChar *s, bool /*qmlMode*/) {
+static inline int classify10(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 'i') {
if (s[1].unicode() == 'm') {
if (s[2].unicode() == 'p') {
@@ -767,7 +773,7 @@ static inline int classify10(const QChar *s, bool /*qmlMode*/) {
if (s[7].unicode() == 'n') {
if (s[8].unicode() == 't') {
if (s[9].unicode() == 's') {
- return Lexer::T_IMPLEMENTS;
+ return qmlMode ? int(Lexer::T_IMPLEMENTS) : Lexer::T_IDENTIFIER;
}
}
}
@@ -800,7 +806,7 @@ static inline int classify10(const QChar *s, bool /*qmlMode*/) {
return Lexer::T_IDENTIFIER;
}
-static inline int classify12(const QChar *s, bool /*qmlMode*/) {
+static inline int classify12(const QChar *s, bool qmlMode) {
if (s[0].unicode() == 's') {
if (s[1].unicode() == 'y') {
if (s[2].unicode() == 'n') {
@@ -813,7 +819,7 @@ static inline int classify12(const QChar *s, bool /*qmlMode*/) {
if (s[9].unicode() == 'z') {
if (s[10].unicode() == 'e') {
if (s[11].unicode() == 'd') {
- return Lexer::T_SYNCHRONIZED;
+ return qmlMode ? int(Lexer::T_SYNCHRONIZED) : Lexer::T_IDENTIFIER;
}
}
}
diff --git a/src/libs/qmljs/parser/qmljslexer.cpp b/src/libs/qmljs/parser/qmljslexer.cpp
index 8f9e4eb034..99a800e2ef 100644
--- a/src/libs/qmljs/parser/qmljslexer.cpp
+++ b/src/libs/qmljs/parser/qmljslexer.cpp
@@ -154,10 +154,13 @@ void Lexer::setCode(const QString &code, int lineno, bool qmlMode)
void Lexer::scanChar()
{
+ unsigned sequenceLength = isLineTerminatorSequence();
_char = *_codePtr++;
+ if (sequenceLength == 2)
+ _char = *_codePtr++;
- if (_char == QLatin1Char('\n')) {
- _lastLinePtr = _codePtr; // points to the first character after the newline
+ if (unsigned sequenceLength = isLineTerminatorSequence()) {
+ _lastLinePtr = _codePtr + sequenceLength - 1; // points to the first character after the newline
++_currentLineNumber;
}
}
@@ -275,13 +278,13 @@ again:
_tokenLinePtr = _lastLinePtr;
while (_char.isSpace()) {
- if (_char == QLatin1Char('\n')) {
- _tokenLinePtr = _codePtr;
+ if (unsigned sequenceLength = isLineTerminatorSequence()) {
+ _tokenLinePtr = _codePtr + sequenceLength - 1;
if (_restrictedKeyword) {
// automatic semicolon insertion
_tokenLine = _currentLineNumber;
- _tokenStartPtr = _codePtr - 1; // ### TODO: insert it before the optional \r sequence.
+ _tokenStartPtr = _codePtr - 1;
return T_SEMICOLON;
} else {
_terminator = true;
@@ -398,7 +401,7 @@ again:
}
}
} else if (_char == QLatin1Char('/')) {
- while (!_char.isNull() && _char != QLatin1Char('\n')) {
+ while (!_char.isNull() && !isLineTerminator()) {
scanChar();
}
if (_engine) {
@@ -541,7 +544,7 @@ again:
if (_engine) {
while (!_char.isNull()) {
- if (_char == QLatin1Char('\n') || _char == QLatin1Char('\\')) {
+ if (isLineTerminator() || _char == QLatin1Char('\\')) {
break;
} else if (_char == quote) {
_tokenSpell = _engine->midRef(startCode - _code.unicode() - 1, _codePtr - startCode);
@@ -560,9 +563,11 @@ again:
_tokenText += *startCode++;
while (! _char.isNull()) {
- if (_char == QLatin1Char('\n')) {
+ if (unsigned sequenceLength = isLineTerminatorSequence()) {
multilineStringLiteral = true;
_tokenText += _char;
+ if (sequenceLength == 2)
+ _tokenText += *_codePtr;
scanChar();
} else if (_char == quote) {
scanChar();
@@ -587,7 +592,6 @@ again:
// hex escape sequence
case 'x':
- case 'X':
if (isHexDigit(_codePtr[0]) && isHexDigit(_codePtr[1])) {
scanChar();
@@ -625,23 +629,23 @@ again:
break;
case '\r':
- while (_char == QLatin1Char('\r'))
- scanChar();
-
- if (_char == QLatin1Char('\n')) {
- u = _char;
- scanChar();
- } else {
+ if (isLineTerminatorSequence() == 2) {
+ _tokenText += QLatin1Char('\r');
u = QLatin1Char('\n');
+ } else {
+ u = QLatin1Char('\r');
}
-
+ scanChar();
break;
case '\n':
+ case 0x2028u:
+ case 0x2029u:
u = _char;
scanChar();
break;
+
default:
// non escape character
u = _char;
@@ -860,11 +864,6 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
while (true) {
switch (_char.unicode()) {
- case 0: // eof
- case '\n': case '\r': // line terminator
- _errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression literal");
- return false;
-
case '/':
scanChar();
@@ -934,8 +933,13 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
break;
default:
- _tokenText += _char;
- scanChar();
+ if (_char.isNull() || isLineTerminator()) {
+ _errorMessage = QCoreApplication::translate("QmlParser", "Unterminated regular expression literal");
+ return false;
+ } else {
+ _tokenText += _char;
+ scanChar();
+ }
} // switch
} // while
@@ -944,7 +948,28 @@ bool Lexer::scanRegExp(RegExpBodyPrefix prefix)
bool Lexer::isLineTerminator() const
{
- return (_char == QLatin1Char('\n') || _char == QLatin1Char('\r'));
+ const ushort unicode = _char.unicode();
+ return unicode == 0x000Au
+ || unicode == 0x000Du
+ || unicode == 0x2028u
+ || unicode == 0x2029u;
+}
+
+unsigned Lexer::isLineTerminatorSequence() const
+{
+ switch (_char.unicode()) {
+ case 0x000Au:
+ case 0x2028u:
+ case 0x2029u:
+ return 1;
+ case 0x000Du:
+ if (_codePtr->unicode() == 0x000Au)
+ return 2;
+ else
+ return 1;
+ default:
+ return 0;
+ }
}
bool Lexer::isIdentLetter(QChar ch)
@@ -1112,7 +1137,7 @@ bool Lexer::scanDirectives(Directives *directives)
//
// recognize the mandatory `as' followed by the module name
//
- if (! (lex() == T_RESERVED_WORD && tokenText() == QLatin1String("as")))
+ if (! (lex() == T_IDENTIFIER && tokenText() == QLatin1String("as")))
return false; // expected `as'
if (lex() != T_IDENTIFIER)
diff --git a/src/libs/qmljs/parser/qmljslexer_p.h b/src/libs/qmljs/parser/qmljslexer_p.h
index 12650c2ed6..ae90b9ff32 100644
--- a/src/libs/qmljs/parser/qmljslexer_p.h
+++ b/src/libs/qmljs/parser/qmljslexer_p.h
@@ -92,7 +92,6 @@ public:
T_IMPLEMENTS = T_RESERVED_WORD,
T_INT = T_RESERVED_WORD,
T_INTERFACE = T_RESERVED_WORD,
- T_LET = T_RESERVED_WORD,
T_LONG = T_RESERVED_WORD,
T_NATIVE = T_RESERVED_WORD,
T_PACKAGE = T_RESERVED_WORD,
@@ -104,8 +103,7 @@ public:
T_SYNCHRONIZED = T_RESERVED_WORD,
T_THROWS = T_RESERVED_WORD,
T_TRANSIENT = T_RESERVED_WORD,
- T_VOLATILE = T_RESERVED_WORD,
- T_YIELD = T_RESERVED_WORD
+ T_VOLATILE = T_RESERVED_WORD
};
enum Error {
@@ -182,6 +180,7 @@ private:
int scanNumber(QChar ch);
bool isLineTerminator() const;
+ unsigned isLineTerminatorSequence() const;
static bool isIdentLetter(QChar c);
static bool isDecimalDigit(ushort c);
static bool isHexDigit(QChar c);
diff --git a/src/libs/qmljs/parser/qmljsparser.cpp b/src/libs/qmljs/parser/qmljsparser.cpp
index 5cc04c8b12..5b95f16b25 100644
--- a/src/libs/qmljs/parser/qmljsparser.cpp
+++ b/src/libs/qmljs/parser/qmljsparser.cpp
@@ -27,7 +27,7 @@
**
****************************************************************************/
-#include <QtCore/QDebug>
+#include <QtCore/QtDebug>
#include <QtCore/QCoreApplication>
#include <string.h>
@@ -43,8 +43,15 @@
#include <QVarLengthArray>
//
+// W A R N I N G
+// -------------
+//
// This file is automatically generated from qmljs.g.
-// Changes will be lost.
+// Changes should be made to that file, not here. Any change to this file will
+// be lost!
+//
+// To regenerate this file, run:
+// qlalr --no-debug --no-lines --qt qmljs.g
//
using namespace QmlJS;
@@ -1384,7 +1391,7 @@ case 289: {
sym(1).Node = node;
} break;
-case 291: {
+case 292: {
AST::DoWhileStatement *node = new (pool) AST::DoWhileStatement(sym(2).Statement, sym(5).Expression);
node->doToken = loc(1);
node->whileToken = loc(3);
@@ -1394,7 +1401,7 @@ case 291: {
sym(1).Node = node;
} break;
-case 292: {
+case 293: {
AST::WhileStatement *node = new (pool) AST::WhileStatement(sym(3).Expression, sym(5).Statement);
node->whileToken = loc(1);
node->lparenToken = loc(2);
@@ -1402,7 +1409,7 @@ case 292: {
sym(1).Node = node;
} break;
-case 293: {
+case 294: {
AST::ForStatement *node = new (pool) AST::ForStatement(sym(3).Expression,
sym(5).Expression, sym(7).Expression, sym(9).Statement);
node->forToken = loc(1);
@@ -1413,7 +1420,7 @@ case 293: {
sym(1).Node = node;
} break;
-case 294: {
+case 295: {
AST::LocalForStatement *node = new (pool) AST::LocalForStatement(
sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression,
sym(8).Expression, sym(10).Statement);
@@ -1426,7 +1433,7 @@ case 294: {
sym(1).Node = node;
} break;
-case 295: {
+case 296: {
AST:: ForEachStatement *node = new (pool) AST::ForEachStatement(sym(3).Expression,
sym(5).Expression, sym(7).Statement);
node->forToken = loc(1);
@@ -1436,7 +1443,7 @@ case 295: {
sym(1).Node = node;
} break;
-case 296: {
+case 297: {
AST::LocalForEachStatement *node = new (pool) AST::LocalForEachStatement(
sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement);
node->forToken = loc(1);
@@ -1447,14 +1454,14 @@ case 296: {
sym(1).Node = node;
} break;
-case 298: {
+case 299: {
AST::ContinueStatement *node = new (pool) AST::ContinueStatement();
node->continueToken = loc(1);
node->semicolonToken = loc(2);
sym(1).Node = node;
} break;
-case 300: {
+case 301: {
AST::ContinueStatement *node = new (pool) AST::ContinueStatement(stringRef(2));
node->continueToken = loc(1);
node->identifierToken = loc(2);
@@ -1462,14 +1469,14 @@ case 300: {
sym(1).Node = node;
} break;
-case 302: {
+case 303: {
AST::BreakStatement *node = new (pool) AST::BreakStatement(QStringRef());
node->breakToken = loc(1);
node->semicolonToken = loc(2);
sym(1).Node = node;
} break;
-case 304: {
+case 305: {
AST::BreakStatement *node = new (pool) AST::BreakStatement(stringRef(2));
node->breakToken = loc(1);
node->identifierToken = loc(2);
@@ -1477,14 +1484,14 @@ case 304: {
sym(1).Node = node;
} break;
-case 306: {
+case 307: {
AST::ReturnStatement *node = new (pool) AST::ReturnStatement(sym(2).Expression);
node->returnToken = loc(1);
node->semicolonToken = loc(3);
sym(1).Node = node;
} break;
-case 307: {
+case 308: {
AST::WithStatement *node = new (pool) AST::WithStatement(sym(3).Expression, sym(5).Statement);
node->withToken = loc(1);
node->lparenToken = loc(2);
@@ -1492,7 +1499,7 @@ case 307: {
sym(1).Node = node;
} break;
-case 308: {
+case 309: {
AST::SwitchStatement *node = new (pool) AST::SwitchStatement(sym(3).Expression, sym(5).CaseBlock);
node->switchToken = loc(1);
node->lparenToken = loc(2);
@@ -1500,90 +1507,90 @@ case 308: {
sym(1).Node = node;
} break;
-case 309: {
+case 310: {
AST::CaseBlock *node = new (pool) AST::CaseBlock(sym(2).CaseClauses);
node->lbraceToken = loc(1);
node->rbraceToken = loc(3);
sym(1).Node = node;
} break;
-case 310: {
+case 311: {
AST::CaseBlock *node = new (pool) AST::CaseBlock(sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses);
node->lbraceToken = loc(1);
node->rbraceToken = loc(5);
sym(1).Node = node;
} break;
-case 311: {
+case 312: {
sym(1).Node = new (pool) AST::CaseClauses(sym(1).CaseClause);
} break;
-case 312: {
+case 313: {
sym(1).Node = new (pool) AST::CaseClauses(sym(1).CaseClauses, sym(2).CaseClause);
} break;
-case 313: {
+case 314: {
sym(1).Node = 0;
} break;
-case 314: {
+case 315: {
sym(1).Node = sym(1).CaseClauses->finish ();
} break;
-case 315: {
+case 316: {
AST::CaseClause *node = new (pool) AST::CaseClause(sym(2).Expression, sym(4).StatementList);
node->caseToken = loc(1);
node->colonToken = loc(3);
sym(1).Node = node;
} break;
-case 316: {
+case 317: {
AST::DefaultClause *node = new (pool) AST::DefaultClause(sym(3).StatementList);
node->defaultToken = loc(1);
node->colonToken = loc(2);
sym(1).Node = node;
} break;
-case 317:
-case 318: {
+case 318:
+case 319: {
AST::LabelledStatement *node = new (pool) AST::LabelledStatement(stringRef(1), sym(3).Statement);
node->identifierToken = loc(1);
node->colonToken = loc(2);
sym(1).Node = node;
} break;
-case 319: {
+case 320: {
AST::LabelledStatement *node = new (pool) AST::LabelledStatement(stringRef(1), sym(3).Statement);
node->identifierToken = loc(1);
node->colonToken = loc(2);
sym(1).Node = node;
} break;
-case 321: {
+case 322: {
AST::ThrowStatement *node = new (pool) AST::ThrowStatement(sym(2).Expression);
node->throwToken = loc(1);
node->semicolonToken = loc(3);
sym(1).Node = node;
} break;
-case 322: {
+case 323: {
AST::TryStatement *node = new (pool) AST::TryStatement(sym(2).Statement, sym(3).Catch);
node->tryToken = loc(1);
sym(1).Node = node;
} break;
-case 323: {
+case 324: {
AST::TryStatement *node = new (pool) AST::TryStatement(sym(2).Statement, sym(3).Finally);
node->tryToken = loc(1);
sym(1).Node = node;
} break;
-case 324: {
+case 325: {
AST::TryStatement *node = new (pool) AST::TryStatement(sym(2).Statement, sym(3).Catch, sym(4).Finally);
node->tryToken = loc(1);
sym(1).Node = node;
} break;
-case 325: {
+case 326: {
AST::Catch *node = new (pool) AST::Catch(stringRef(3), sym(5).Block);
node->catchToken = loc(1);
node->lparenToken = loc(2);
@@ -1592,20 +1599,20 @@ case 325: {
sym(1).Node = node;
} break;
-case 326: {
+case 327: {
AST::Finally *node = new (pool) AST::Finally(sym(2).Block);
node->finallyToken = loc(1);
sym(1).Node = node;
} break;
-case 328: {
+case 329: {
AST::DebuggerStatement *node = new (pool) AST::DebuggerStatement();
node->debuggerToken = loc(1);
node->semicolonToken = loc(2);
sym(1).Node = node;
} break;
-case 329: {
+case 330: {
AST::FunctionDeclaration *node = new (pool) AST::FunctionDeclaration(stringRef(2), sym(4).FormalParameterList, sym(7).FunctionBody);
node->functionToken = loc(1);
node->identifierToken = loc(2);
@@ -1616,7 +1623,7 @@ case 329: {
sym(1).Node = node;
} break;
-case 330: {
+case 331: {
AST::FunctionExpression *node = new (pool) AST::FunctionExpression(stringRef(2), sym(4).FormalParameterList, sym(7).FunctionBody);
node->functionToken = loc(1);
if (! stringRef(2).isNull())
@@ -1628,60 +1635,60 @@ case 330: {
sym(1).Node = node;
} break;
-case 331: {
+case 332: {
AST::FormalParameterList *node = new (pool) AST::FormalParameterList(stringRef(1));
node->identifierToken = loc(1);
sym(1).Node = node;
} break;
-case 332: {
+case 333: {
AST::FormalParameterList *node = new (pool) AST::FormalParameterList(sym(1).FormalParameterList, stringRef(3));
node->commaToken = loc(2);
node->identifierToken = loc(3);
sym(1).Node = node;
} break;
-case 333: {
+case 334: {
sym(1).Node = 0;
} break;
-case 334: {
+case 335: {
sym(1).Node = sym(1).FormalParameterList->finish ();
} break;
-case 335: {
+case 336: {
sym(1).Node = 0;
} break;
-case 337: {
+case 338: {
sym(1).Node = new (pool) AST::FunctionBody(sym(1).SourceElements->finish ());
} break;
-case 339: {
+case 340: {
sym(1).Node = new (pool) AST::Program(sym(1).SourceElements->finish ());
} break;
-case 340: {
+case 341: {
sym(1).Node = new (pool) AST::SourceElements(sym(1).SourceElement);
} break;
-case 341: {
+case 342: {
sym(1).Node = new (pool) AST::SourceElements(sym(1).SourceElements, sym(2).SourceElement);
} break;
-case 342: {
+case 343: {
sym(1).Node = new (pool) AST::StatementSourceElement(sym(1).Statement);
} break;
-case 343: {
+case 344: {
sym(1).Node = new (pool) AST::FunctionSourceElement(sym(1).FunctionDeclaration);
} break;
-case 344: {
+case 345: {
stringRef(1) = QStringRef();
} break;
-case 346: {
+case 347: {
sym(1).Node = 0;
} break;
@@ -1694,7 +1701,8 @@ case 346: {
const int errorState = state_stack[tos];
// automatic insertion of `;'
- if (yytoken != -1 && t_action(errorState, T_AUTOMATIC_SEMICOLON) && lexer->canInsertAutomaticSemicolon(yytoken)) {
+ if (yytoken != -1 && ((t_action(errorState, T_AUTOMATIC_SEMICOLON) && lexer->canInsertAutomaticSemicolon(yytoken))
+ || t_action(errorState, T_COMPATIBILITY_SEMICOLON))) {
SavedToken &tk = token_buffer[0];
tk.token = yytoken;
tk.dval = yylval;
diff --git a/src/libs/qmljs/parser/qmljsparser_p.h b/src/libs/qmljs/parser/qmljsparser_p.h
index d46575dcd3..a2aec3d089 100644
--- a/src/libs/qmljs/parser/qmljsparser_p.h
+++ b/src/libs/qmljs/parser/qmljsparser_p.h
@@ -40,8 +40,15 @@
//
//
+// W A R N I N G
+// -------------
+//
// This file is automatically generated from qmljs.g.
-// Changes will be lost.
+// Changes should be made to that file, not here. Any change to this file will
+// be lost!
+//
+// To regenerate this file, run:
+// qlalr --no-debug --no-lines --qt qmljs.g
//
#ifndef QMLJSPARSER_P_H
diff --git a/src/libs/qmljs/persistenttrie.cpp b/src/libs/qmljs/persistenttrie.cpp
new file mode 100644
index 0000000000..271fa69c78
--- /dev/null
+++ b/src/libs/qmljs/persistenttrie.cpp
@@ -0,0 +1,631 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+/*!
+ \class QmlJS::PersistentTrie::Trie
+
+ \brief Implements a trie that is persistent (not on disk but in memory).
+
+ This means that several versions can coexist, as adding an element
+ is non destructive, and as much as possible is shared.
+
+ The trie is only *partially* ordered, it preserves the order
+ of what was inserted as much as possible.
+ This makes some operations a bit slower, but is considered
+ a feature.
+ This means the order in which you insert the elements matters.
+
+ An important use case for this is completions, and several
+ strategies are available.
+ Results order can be improved using the matching strength
+
+ All const operations are threadsafe, and copy is cheap (only a
+ QSharedPointer copy).
+
+ Assigning a shared pointer is *not* threadsafe, so updating the
+ head is *not* thread safe, and should be done only on a local
+ instance (shared pointer used only from a single thread), or
+ protected with locks.
+
+ This is a two level implementation, based on a fully functional
+ implementation (PersistentTrie::Trie), which could be private
+ but was left public because deemed useful.
+
+ Would gain from some memory optimization, or direct string implementation.
+ */
+
+#include "persistenttrie.h"
+
+#include <QDebug>
+#include <QMap>
+#include <QString>
+#include <QStringList>
+
+#include <algorithm>
+#include <utility>
+
+namespace QmlJS {
+namespace PersistentTrie {
+
+TrieNode::TrieNode(const QString &pre, QList<TrieNode::Ptr> post) :
+ prefix(pre), postfixes(post) {}
+
+TrieNode::TrieNode(const TrieNode &o) : prefix(o.prefix),
+ postfixes(o.postfixes) {}
+
+TrieNode::Ptr TrieNode::create(const QString &pre, QList<TrieNode::Ptr> post)
+{
+ return TrieNode::Ptr(new TrieNode(pre,post));
+}
+
+void TrieNode::complete(QStringList &res, const TrieNode::Ptr &trie,
+ const QString &value, const QString &base, LookupFlags flags)
+{
+ // one could also modify this and make it return a TrieNode, instead of a QStringList
+ if (trie.isNull())
+ return;
+ QString::const_iterator i = trie->prefix.constBegin(), iEnd = trie->prefix.constEnd();
+ QString::const_iterator j = value.constBegin(), jEnd = value.constEnd();
+ while (i != iEnd && j != jEnd) {
+ if (i->isSpace()) {
+ if (! j->isSpace() && (flags & SkipSpaces) == 0)
+ return;
+ while (j != jEnd && j->isSpace()) {
+ ++j;
+ } ;
+ do {
+ ++i;
+ } while (i != iEnd && i->isSpace());
+ } else {
+ if (*i != *j && ((flags & CaseInsensitive) == 0 || i->toLower() != j->toLower())) {
+ if ((flags & SkipChars) != 0)
+ --j;
+ else
+ return;
+ }
+ ++i;
+ ++j;
+ }
+ }
+ QString base2 = base + trie->prefix;
+ if (j == jEnd) {
+ if (trie->postfixes.isEmpty())
+ res.append(base2);
+ if (trie->postfixes.size() == 1) {
+ complete(res, trie->postfixes[0],QString(), base2, flags);
+ return;
+ }
+ foreach (TrieNode::Ptr t, trie->postfixes) {
+ if ((flags & Partial) != 0)
+ res.append(base2 + t->prefix);
+ else
+ complete(res, t, QString(), base2, flags);
+ }
+ return;
+ }
+ foreach (const TrieNode::Ptr v, trie->postfixes) {
+ QString::const_iterator vi = v->prefix.constBegin(), vEnd = v->prefix.constEnd();
+ if (vi != vEnd && (*vi == *j || ((flags & CaseInsensitive) != 0
+ && vi->toLower() == j->toLower()) || ((flags & SkipChars) != 0)))
+ complete(res, v, value.right(jEnd-j), base2, flags);
+ }
+}
+
+TrieNode::Ptr TrieNode::insertF(const TrieNode::Ptr &trie,
+ const QString &value)
+{
+ if (trie.isNull()) {
+ if (value.isEmpty())
+ return trie;
+ return TrieNode::create(value);
+ }
+ typedef TrieNode T;
+ QString::const_iterator i = trie->prefix.constBegin(), iEnd = trie->prefix.constEnd();
+ QString::const_iterator j = value.constBegin(), jEnd = value.constEnd();
+ while (i != iEnd && j != jEnd) {
+ if (i->isSpace()) {
+ if (! j->isSpace())
+ break;
+ do {
+ ++j;
+ } while (j != jEnd && j->isSpace());
+ do {
+ ++i;
+ } while (i != iEnd && i->isSpace());
+ } else {
+ if (*i != *j)
+ break;
+ ++i;
+ ++j;
+ }
+ }
+ if (i == iEnd) {
+ if (j == jEnd)
+ return trie;
+ int tSize = trie->postfixes.size();
+ for (int i=0; i < tSize; ++i) {
+ const T::Ptr &v=trie->postfixes[i];
+ QString::const_iterator vi = v->prefix.constBegin(), vEnd = v->prefix.constEnd();
+ if (vi != vEnd && *vi == *j) {
+ T::Ptr res = insertF(v, value.right(jEnd-j));
+ if (res != v) {
+ QList<T::Ptr> post = trie->postfixes;
+ post.replace(i, res);
+ return T::create(trie->prefix,post);
+ } else {
+ return trie;
+ }
+ }
+ }
+ QList<T::Ptr> post = trie->postfixes;
+ if (post.isEmpty())
+ post.append(T::create());
+ post.append(T::create(value.right(jEnd - j)));
+ return T::create(trie->prefix, post);
+ } else {
+ T::Ptr newTrie1 = T::create(trie->prefix.right(iEnd - i), trie->postfixes);
+ T::Ptr newTrie2 = T::create(value.right(jEnd - j));
+ return T::create(trie->prefix.left(i - trie->prefix.constBegin()),
+ QList<T::Ptr>() << newTrie1 << newTrie2);
+ }
+}
+
+bool TrieNode::contains(const TrieNode::Ptr &trie,
+ const QString &value, LookupFlags flags)
+{
+ if (trie.isNull())
+ return false;
+ QString::const_iterator i = trie->prefix.constBegin(), iEnd = trie->prefix.constEnd();
+ QString::const_iterator j = value.constBegin(), jEnd = value.constEnd();
+ while (i != iEnd && j != jEnd) {
+ if (i->isSpace()) {
+ if (! j->isSpace())
+ return false;
+ do {
+ ++j;
+ } while (j != jEnd && j->isSpace());
+ do {
+ ++i;
+ } while (i != iEnd && i->isSpace());
+ } else {
+ if (*i != *j && ((flags & CaseInsensitive) == 0 || i->toLower() != j->toLower()))
+ return false;
+ ++i;
+ ++j;
+ }
+ }
+ if (j == jEnd) {
+ if ((flags & Partial) != 0)
+ return true;
+ if (i == iEnd) {
+ foreach (const TrieNode::Ptr t, trie->postfixes)
+ if (t->prefix.isEmpty())
+ return true;
+ return trie->postfixes.isEmpty();
+ }
+ return false;
+ }
+ if (i != iEnd)
+ return false;
+ bool res = false;
+ foreach (const TrieNode::Ptr v, trie->postfixes) {
+ QString::const_iterator vi = v->prefix.constBegin(), vEnd = v->prefix.constEnd();
+ if (vi != vEnd && (*vi == *j || ((flags & CaseInsensitive) != 0
+ && vi->toLower() == j->toLower())))
+ res = res || contains(v, value.right(jEnd-j), flags);
+ }
+ return res;
+}
+
+namespace {
+class Appender {
+public:
+ Appender() {}
+ QStringList res;
+ void operator()(const QString &s) {
+ res.append(s);
+ }
+};
+}
+
+QStringList TrieNode::stringList(const TrieNode::Ptr &trie)
+{
+ Appender a;
+ enumerateTrieNode<Appender>(trie, a, QString());
+ return a.res;
+}
+
+std::pair<TrieNode::Ptr,int> TrieNode::intersectF(
+ const TrieNode::Ptr &v1, const TrieNode::Ptr &v2, int index1)
+{
+ typedef TrieNode::Ptr P;
+ typedef QMap<QString,int>::const_iterator MapIterator;
+ if (v1.isNull() || v2.isNull())
+ return std::make_pair(P(0), ((v1.isNull()) ? 1 : 0) | ((v2.isNull()) ? 2 : 0));
+ QString::const_iterator i = v1->prefix.constBegin()+index1, iEnd = v1->prefix.constEnd();
+ QString::const_iterator j = v2->prefix.constBegin(), jEnd = v2->prefix.constEnd();
+ while (i != iEnd && j != jEnd) {
+ if (i->isSpace()) {
+ if (! j->isSpace())
+ break;
+ do {
+ ++j;
+ } while (j != jEnd && j->isSpace());
+ do {
+ ++i;
+ } while (i != iEnd && i->isSpace());
+ } else {
+ if (*i != *j)
+ break;
+ ++i;
+ ++j;
+ }
+ }
+ if (i == iEnd) {
+ if (j == jEnd) {
+ if (v1->postfixes.isEmpty() || v2->postfixes.isEmpty()) {
+ if (v1->postfixes.isEmpty() && v2->postfixes.isEmpty())
+ return std::make_pair(v1, 3);
+ foreach (P t1, v1->postfixes)
+ if (t1->prefix.isEmpty()) {
+ if (index1 == 0)
+ return std::make_pair(v2, 2);
+ else
+ return std::make_pair(TrieNode::create(
+ v1->prefix.left(index1).append(v2->prefix), v2->postfixes),0);
+ }
+ foreach (P t2, v2->postfixes)
+ if (t2->prefix.isEmpty())
+ return std::make_pair(v1,1);
+ return std::make_pair(P(0), 0);
+ }
+ QMap<QString,int> p1, p2;
+ QList<P> p3;
+ int ii = 0;
+ foreach (P t1, v1->postfixes)
+ p1[t1->prefix] = ii++;
+ ii = 0;
+ foreach (P t2, v2->postfixes)
+ p2[t2->prefix] = ii++;
+ MapIterator p1Ptr = p1.constBegin(), p2Ptr = p2.constBegin(),
+ p1End = p1.constEnd(), p2End = p2.constEnd();
+ int sameV1V2 = 3;
+ while (p1Ptr != p1End && p2Ptr != p2End) {
+ if (p1Ptr.key().isEmpty()) {
+ if (p2Ptr.key().isEmpty()) {
+ if (sameV1V2 == 0)
+ p3.append(v1->postfixes.at(p1Ptr.value()));
+ ++p1Ptr;
+ ++p2Ptr;
+ } else {
+ if (sameV1V2 == 1)
+ for (MapIterator p1I = p1.constBegin();p1I != p1Ptr; ++p1I)
+ p3.append(v1->postfixes.at(p1I.value()));
+ ++p1Ptr;
+ sameV1V2 &= 2;
+ }
+ } else if (p2Ptr.key().isEmpty()) {
+ if (sameV1V2 == 2)
+ for (MapIterator p2I = p2.constBegin(); p2I != p2Ptr; ++p2I)
+ p3.append(v2->postfixes.at(p2I.value()));
+ ++p2Ptr;
+ sameV1V2 &= 1;
+ } else {
+ QChar c1 = p1Ptr.key().at(0);
+ QChar c2 = p2Ptr.key().at(0);
+ if (c1 < c2) {
+ if (sameV1V2 == 1)
+ for (MapIterator p1I = p1.constBegin(); p1I != p1Ptr; ++p1I)
+ p3.append(v1->postfixes.at(p1I.value()));
+ ++p1Ptr;
+ sameV1V2 &= 2;
+ } else if (c1 > c2) {
+ if (sameV1V2 == 2)
+ for (MapIterator p2I = p2.constBegin(); p2I != p2Ptr; ++p2I)
+ p3.append(v2->postfixes.at(p2I. value()));
+ ++p2Ptr;
+ sameV1V2 &= 1;
+ } else {
+ std::pair<P,int> res = intersectF(v1->postfixes.at(p1Ptr.value()),
+ v2->postfixes.at(p2Ptr.value()));
+ if (sameV1V2 !=0 && (sameV1V2 & res.second) == 0) {
+ if ((sameV1V2 & 1) == 1)
+ for (MapIterator p1I = p1.constBegin(); p1I != p1Ptr; ++p1I)
+ p3.append(v1->postfixes.at(p1I.value()));
+ if (sameV1V2 == 2)
+ for (MapIterator p2I = p2.constBegin(); p2I != p2Ptr; ++p2I)
+ p3.append(v2->postfixes.at(p2I.value()));
+ }
+ sameV1V2 &= res.second;
+ if (sameV1V2 == 0 && !res.first.isNull())
+ p3.append(res.first);
+ ++p1Ptr;
+ ++p2Ptr;
+ }
+ }
+ }
+ if (p1Ptr != p1End) {
+ if (sameV1V2 == 1)
+ for (MapIterator p1I = p1.constBegin(); p1I != p1Ptr; ++p1I)
+ p3.append(v1->postfixes.at(p1I.value()));
+ sameV1V2 &= 2;
+ } else if (p2Ptr != p2End) {
+ if (sameV1V2 == 2) {
+ for (MapIterator p2I = p2.constBegin(); p2I != p2Ptr; ++p2I)
+ p3.append(v2->postfixes.at(p2I. value()));
+ }
+ sameV1V2 &= 1;
+ }
+ switch (sameV1V2) {
+ case 0:
+ if (p3.isEmpty())
+ return std::make_pair(P(0),0);
+ else
+ return std::make_pair(TrieNode::create(v1->prefix,p3),0);
+ case 2:
+ if (index1 == 0)
+ return std::make_pair(v2,2);
+ else
+ return std::make_pair(TrieNode::create(
+ v1->prefix.left(index1).append(v2->prefix), v2->postfixes), 0);
+ default:
+ return std::make_pair(v1,sameV1V2);
+ }
+ }
+ // i == iEnd && j != jEnd
+ foreach (const P &t1, v1->postfixes)
+ if ((!t1->prefix.isEmpty()) && t1->prefix.at(0) == *j) {
+ std::pair<P,int> res = intersectF(v2,t1,j-v2->prefix.constBegin());
+ if (index1 == 0)
+ return std::make_pair(res.first, (((res.second & 1)==1) ? 2 : 0));
+ else
+ return std::make_pair(TrieNode::create(
+ v1->prefix.left(index1).append(res.first->prefix),
+ res.first->postfixes), 0);
+ }
+ return std::make_pair(P(0), 0);
+ } else {
+ // i != iEnd && j == jEnd
+ foreach (P t2, v2->postfixes)
+ if (!t2->prefix.isEmpty() && t2->prefix.at(0) == *i) {
+ std::pair<P,int> res = intersectF(v1,t2,i-v1->prefix.constBegin());
+ return std::make_pair(res.first, (res.second & 1));
+ }
+ return std::make_pair(P(0), 0);
+ }
+}
+
+namespace {
+class InplaceTrie{
+public:
+ TrieNode::Ptr trie;
+
+ void operator()(QString s){
+ trie = TrieNode::insertF(trie,s);
+ }
+};
+}
+
+std::pair<TrieNode::Ptr,int> TrieNode::mergeF(
+ const TrieNode::Ptr &v1, const TrieNode::Ptr &v2)
+{
+ //could be much more efficient if implemented directly on the trie like intersectF
+ InplaceTrie t;
+ t.trie = v1;
+ enumerateTrieNode<InplaceTrie>(v2, t, QString());
+ return std::make_pair(t.trie, ((t.trie == v1) ? 1 : 0));
+}
+
+QDebug &TrieNode::printStrings(QDebug &dbg, const TrieNode::Ptr &trie)
+{
+ if (trie.isNull())
+ return dbg << "Trie{*NULL*}";
+ dbg<<"Trie{ contents:[";
+ bool first = true;
+ foreach (const QString &s, stringList(trie)) {
+ if (!first)
+ dbg << ",";
+ else
+ first = false;
+ dbg << s;
+ }
+ dbg << "]}";
+ return dbg;
+}
+
+QDebug &TrieNode::describe(QDebug &dbg, const TrieNode::Ptr &trie,
+ int indent = 0)
+{
+ dbg.space();
+ dbg.nospace();
+ if (trie.isNull()) {
+ dbg << "NULL";
+ return dbg;
+ }
+ dbg << trie->prefix;
+ int newIndent = indent + trie->prefix.size() + 3;
+ bool newLine = false;
+ foreach (TrieNode::Ptr sub, trie->postfixes) {
+ if (newLine) {
+ dbg << "\n";
+ for (int i=0; i < newIndent; ++i)
+ dbg << " ";
+ } else {
+ newLine = true;
+ }
+ describe(dbg, sub, newIndent);
+ }
+ return dbg;
+}
+
+QDebug &operator<<(QDebug &dbg, const TrieNode::Ptr &trie)
+{
+ dbg.nospace()<<"Trie{\n";
+ TrieNode::describe(dbg,trie,0);
+ dbg << "}";
+ return dbg.space();
+}
+QDebug &operator<<(QDebug &dbg, const Trie &trie)
+{
+ dbg.nospace()<<"Trie{\n";
+ TrieNode::describe(dbg,trie.trie,0);
+ dbg << "}";
+ return dbg.space();
+}
+Trie::Trie() {}
+Trie::Trie(const TrieNode::Ptr &trie) : trie(trie) {}
+Trie::Trie(const Trie &o) : trie(o.trie){}
+
+QStringList Trie::complete(const QString &root, const QString &base,
+ LookupFlags flags) const
+{
+ QStringList res;
+ TrieNode::complete(res, trie, root, base, flags);
+ return res;
+}
+
+bool Trie::contains(const QString &value, LookupFlags flags) const
+{
+ return TrieNode::contains(trie, value, flags);
+}
+
+QStringList Trie::stringList() const
+{
+ return TrieNode::stringList(trie);
+}
+
+/*!
+ \brief inserts into the current trie.
+
+ Non thread safe, only use this on an instance that is used only
+ in a single theread, or that is protected by locks.
+ */
+void Trie::insert(const QString &value)
+{
+ trie = TrieNode::insertF(trie, value);
+}
+
+/*!
+ \brief intesects into the current trie.
+
+ Non thread safe, only use this on an instance that is used only
+ in a single theread, or that is protected by locks.
+ */
+void Trie::intersect(const Trie &v)
+{
+ trie = TrieNode::intersectF(trie, v.trie).first;
+}
+
+/*!
+ \brief merges the given trie into the current one.
+
+ Non thread safe, only use this on an instance that is used only
+ in a single theread, or that is protected by locks.
+ */
+void Trie::merge(const Trie &v)
+{
+ trie = TrieNode::mergeF(trie, v.trie).first;
+}
+
+Trie Trie::insertF(const QString &value) const
+{
+ return Trie(TrieNode::insertF(trie, value));
+}
+
+Trie Trie::intersectF(const Trie &v) const
+{
+ return Trie(TrieNode::intersectF(trie, v.trie).first);
+}
+
+Trie Trie::mergeF(const Trie &v) const
+{
+ return Trie(TrieNode::mergeF(trie, v.trie).first);
+}
+
+/*!
+ \fn int matchStrength(const QString &searchStr, const QString &str)
+
+ Returns a number defining how well the serachStr matches str.
+
+ Quite simplistic, looks only at the first match, and prefers contiguos
+ matches, or matches to ca capitalized or separated word.
+*/
+int matchStrength(const QString &searchStr, const QString &str)
+{
+ QString::const_iterator i = searchStr.constBegin(), iEnd = searchStr.constEnd(),
+ j = str.constBegin(), jEnd = str.constEnd();
+ bool lastWasNotUpper=true, lastWasSpacer=true, lastWasMatch = false;
+ int res = 0;
+ while (i != iEnd && j != jEnd) {
+ bool thisIsUpper = (*j).isUpper();
+ bool thisIsLetterOrNumber = (*j).isLetterOrNumber();
+ if ((*i).toLower() == (*j).toLower()) {
+ if (lastWasMatch || (lastWasNotUpper && thisIsUpper)
+ || (thisIsUpper && (*i).isUpper())
+ || (lastWasSpacer && thisIsLetterOrNumber))
+ ++res;
+ lastWasMatch = true;
+ ++i;
+ } else {
+ lastWasMatch = false;
+ }
+ ++j;
+ lastWasNotUpper = !thisIsUpper;
+ lastWasSpacer = !thisIsLetterOrNumber;
+ }
+ if (i != iEnd)
+ return iEnd - i;
+ return res;
+}
+
+namespace {
+class CompareMatchStrength{
+ QString searchStr;
+public:
+ CompareMatchStrength(const QString& searchStr) : searchStr(searchStr) { }
+ bool operator()(const QString &v1, const QString &v2) {
+ return matchStrength(searchStr,v1) > matchStrength(searchStr,v2);
+ }
+};
+}
+
+/*!
+ \fn QStringList matchingStrengthSort(const QString &searchStr, QStringList &res)
+
+ returns a number defining the matching strength of res to the given searchStr
+*/
+QStringList matchStrengthSort(const QString &searchStr, QStringList &res)
+{
+ CompareMatchStrength compare(searchStr);
+ std::stable_sort(res.begin(), res.end(), compare);
+ return res;
+}
+
+} // end namespace PersistentTrie
+} // end namespace QmlJS
diff --git a/src/libs/qmljs/persistenttrie.h b/src/libs/qmljs/persistenttrie.h
new file mode 100644
index 0000000000..bca8bb1461
--- /dev/null
+++ b/src/libs/qmljs/persistenttrie.h
@@ -0,0 +1,127 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef PERSISTENTTRIE_H
+#define PERSISTENTTRIE_H
+
+#include <qmljs/qmljs_global.h>
+
+#include <QList>
+#include <QSharedPointer>
+
+#include <utility>
+
+QT_FORWARD_DECLARE_CLASS(QString)
+QT_FORWARD_DECLARE_CLASS(QStringList)
+QT_FORWARD_DECLARE_CLASS(QDebug)
+
+namespace QmlJS {
+namespace PersistentTrie {
+
+enum LookupFlags {
+ CaseInsensitive = 0x1,
+ Partial = 0x2,
+ SkipChars = 0x4,
+ SkipSpaces = 0x8
+};
+
+class QMLJS_EXPORT TrieNode
+{
+public:
+ typedef const TrieNode CTrie;
+ typedef QSharedPointer<CTrie> Ptr;
+ QString prefix;
+ QList<Ptr> postfixes;
+
+ TrieNode(const QString &pre = QString(), QList<Ptr> post = QList<Ptr>());
+ TrieNode(const TrieNode &o);
+ static Ptr create(const QString &pre = QString(), QList<Ptr> post = QList<Ptr>());
+
+ static void complete(QStringList &results, const Ptr &trie, const QString &root,
+ const QString &base = QString(), LookupFlags flags = LookupFlags(CaseInsensitive|Partial));
+ static bool contains(const Ptr &trie, const QString &value, LookupFlags flags = LookupFlags(0));
+ static QStringList stringList(const Ptr &trie);
+
+ static Ptr insertF(const Ptr &trie, const QString &value);
+ static std::pair<Ptr,int> intersectF(const Ptr &v1, const Ptr &v2, int index1=0);
+ static std::pair<Ptr,int> mergeF(const Ptr &v1, const Ptr &v2);
+
+ static QDebug &printStrings(QDebug &dbg, const Ptr &trie);
+ static QDebug &describe(QDebug &dbg, const Ptr &trie, int indent);
+};
+
+class QMLJS_EXPORT Trie
+{
+public:
+ Trie();
+ Trie(const TrieNode::Ptr &t);
+ Trie(const Trie &o);
+
+ QStringList complete(const QString &root, const QString &base = QString(),
+ LookupFlags flags = LookupFlags(CaseInsensitive|Partial)) const;
+ bool contains(const QString &value, LookupFlags flags = LookupFlags(0)) const;
+ QStringList stringList() const;
+
+ Trie insertF(const QString &value) const;
+ Trie intersectF(const Trie &v) const;
+ Trie mergeF(const Trie &v) const;
+
+ void insert(const QString &value);
+ void intersect(const Trie &v);
+ void merge(const Trie &v);
+
+ friend QMLJS_EXPORT QDebug &operator<<(QDebug &dbg, const TrieNode::Ptr &trie);
+ friend QMLJS_EXPORT QDebug &operator<<(QDebug &dbg, const Trie &trie);
+
+ TrieNode::Ptr trie;
+};
+
+template <typename T> void enumerateTrieNode(const TrieNode::Ptr &trie, T &t,
+ QString base = QString())
+{
+ if (trie.isNull())
+ return;
+ base.append(trie->prefix);
+ foreach (const TrieNode::Ptr subT, trie->postfixes) {
+ enumerateTrieNode(subT,t,base);
+ }
+ if (trie->postfixes.isEmpty())
+ t(base);
+}
+
+QMLJS_EXPORT int matchStrength(const QString &searchStr, const QString &str);
+QMLJS_EXPORT QStringList matchStrengthSort(const QString &searchString, QStringList &res);
+
+QMLJS_EXPORT QDebug &operator<<(QDebug &dbg, const TrieNode::Ptr &trie);
+QMLJS_EXPORT QDebug &operator<<(QDebug &dbg, const Trie &trie);
+
+} // end namespace PersistentTrie
+} // end namespace QmlJS
+
+#endif // PERSISTENTTRIE_H
diff --git a/src/libs/qmljs/qmljs-lib.pri b/src/libs/qmljs/qmljs-lib.pri
index bbc1d06bda..c5f2c3ba50 100644
--- a/src/libs/qmljs/qmljs-lib.pri
+++ b/src/libs/qmljs/qmljs-lib.pri
@@ -33,7 +33,12 @@ HEADERS += \
$$PWD/qmljsscopechain.h \
$$PWD/qmljsutils.h \
$$PWD/qmljsstaticanalysismessage.h \
- $$PWD/jsoncheck.h
+ $$PWD/jsoncheck.h \
+ $$PWD/consolemanagerinterface.h \
+ $$PWD/consoleitem.h \
+ $$PWD/iscriptevaluator.h \
+ $$PWD/qmljssimplereader.h \
+ $$PWD/persistenttrie.h
SOURCES += \
$$PWD/qmljsbind.cpp \
@@ -58,7 +63,11 @@ SOURCES += \
$$PWD/qmljsscopechain.cpp \
$$PWD/qmljsutils.cpp \
$$PWD/qmljsstaticanalysismessage.cpp \
- $$PWD/jsoncheck.cpp
+ $$PWD/jsoncheck.cpp \
+ $$PWD/consolemanagerinterface.cpp \
+ $$PWD/consoleitem.cpp \
+ $$PWD/qmljssimplereader.cpp \
+ $$PWD/persistenttrie.cpp
RESOURCES += \
$$PWD/qmljs.qrc
diff --git a/src/libs/qmljs/qmljs.qbs b/src/libs/qmljs/qmljs.qbs
index d7b556b06b..f68218fbce 100644
--- a/src/libs/qmljs/qmljs.qbs
+++ b/src/libs/qmljs/qmljs.qbs
@@ -4,11 +4,7 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "QmlJS"
- cpp.includePaths: [
- ".",
- "..",
- "parser"
- ]
+ cpp.includePaths: base.concat("parser")
cpp.defines: base.concat([
"QMLJS_BUILD_DIR",
"QT_CREATOR"
@@ -21,6 +17,8 @@ QtcLibrary {
Depends { name: "Qt"; submodules: ["widgets", "script"] }
files: [
+ "jsoncheck.cpp",
+ "jsoncheck.h",
"qmljs.qrc",
"qmljs_global.h",
"qmljsbind.cpp",
@@ -55,6 +53,7 @@ QtcLibrary {
"qmljspropertyreader.cpp",
"qmljspropertyreader.h",
"qmljsreformatter.cpp",
+ "qmljsreformatter.h",
"qmljsrewriter.cpp",
"qmljsrewriter.h",
"qmljsscanner.cpp",
@@ -73,9 +72,6 @@ QtcLibrary {
"qmljsutils.h",
"qmljsvalueowner.cpp",
"qmljsvalueowner.h",
- "qmljsreformatter.h",
- "jsoncheck.cpp",
- "jsoncheck.h",
"images/element.png",
"images/func.png",
"images/property.png",
@@ -99,16 +95,19 @@ QtcLibrary {
"parser/qmljslexer_p.h",
"parser/qmljsmemorypool_p.h",
"parser/qmljsparser.cpp",
- "parser/qmljsparser_p.h"
+ "parser/qmljsparser_p.h",
+ "persistenttrie.cpp",
+ "persistenttrie.h",
+ "consolemanagerinterface.cpp",
+ "consolemanagerinterface.h",
+ "consoleitem.cpp",
+ "consoleitem.h",
+ "iscriptevaluator.h"
]
ProductModule {
Depends { name: "cpp" }
Depends { name: "LanguageUtils" }
- cpp.includePaths: [
- ".",
- "parser"
- ]
cpp.defines: [
"QT_CREATOR"
]
diff --git a/src/libs/qmljs/qmljscheck.cpp b/src/libs/qmljs/qmljscheck.cpp
index a0b97a7c62..f1c6a7ef03 100644
--- a/src/libs/qmljs/qmljscheck.cpp
+++ b/src/libs/qmljs/qmljscheck.cpp
@@ -82,9 +82,8 @@ public:
if (StringLiteral *stringLiteral = cast<StringLiteral *>(_ast)) {
const QString valueName = stringLiteral->value.toString();
- if (!enumValue->keys().contains(valueName)) {
+ if (!enumValue->keys().contains(valueName))
setMessage(ErrInvalidEnumValue);
- }
} else if (! _rhsValue->asStringValue() && ! _rhsValue->asNumberValue()
&& ! _rhsValue->asUnknownValue()) {
setMessage(ErrEnumValueMustBeStringOrNumber);
@@ -131,9 +130,8 @@ public:
fileName.prepend(QDir::separator());
fileName.prepend(_doc->path());
}
- if (!QFileInfo(fileName).exists()) {
+ if (!QFileInfo(fileName).exists())
setMessage(WarnFileOrDirectoryDoesNotExist);
- }
}
}
}
@@ -421,9 +419,8 @@ protected:
bool visit(VariableStatement *ast)
{
- if (_seenNonDeclarationStatement) {
+ if (_seenNonDeclarationStatement)
addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->declarationKindToken);
- }
return true;
}
@@ -433,13 +430,12 @@ protected:
return true;
const QString &name = ast->name.toString();
- if (_formalParameterNames.contains(name)) {
+ if (_formalParameterNames.contains(name))
addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name);
- } else if (_declaredFunctions.contains(name)) {
+ else if (_declaredFunctions.contains(name))
addMessage(WarnAlreadyFunction, ast->identifierToken, name);
- } else if (_declaredVariables.contains(name)) {
+ else if (_declaredVariables.contains(name))
addMessage(WarnDuplicateDeclaration, ast->identifierToken, name);
- }
if (_possiblyUndeclaredUses.contains(name)) {
foreach (const SourceLocation &loc, _possiblyUndeclaredUses.value(name)) {
@@ -454,9 +450,8 @@ protected:
bool visit(FunctionDeclaration *ast)
{
- if (_seenNonDeclarationStatement) {
+ if (_seenNonDeclarationStatement)
addMessage(HintDeclarationsShouldBeAtStartOfFunction, ast->functionToken);
- }
return visit(static_cast<FunctionExpression *>(ast));
}
@@ -467,13 +462,12 @@ protected:
return false;
const QString &name = ast->name.toString();
- if (_formalParameterNames.contains(name)) {
+ if (_formalParameterNames.contains(name))
addMessage(WarnAlreadyFormalParameter, ast->identifierToken, name);
- } else if (_declaredVariables.contains(name)) {
+ else if (_declaredVariables.contains(name))
addMessage(WarnAlreadyVar, ast->identifierToken, name);
- } else if (_declaredFunctions.contains(name)) {
+ else if (_declaredFunctions.contains(name))
addMessage(WarnDuplicateDeclaration, ast->identifierToken, name);
- }
if (FunctionDeclaration *decl = cast<FunctionDeclaration *>(ast)) {
if (_possiblyUndeclaredUses.contains(name)) {
@@ -502,8 +496,44 @@ private:
bool _seenNonDeclarationStatement;
};
+class VisualAspectsPropertyBlackList : public QStringList
+{
+public:
+ VisualAspectsPropertyBlackList()
+ {
+ (*this) << QLatin1String("x") << QLatin1String("y") << QLatin1String("z")
+ << QLatin1String("width") << QLatin1String("height") << QLatin1String("color")
+ << QLatin1String("opacity") << QLatin1String("scale")
+ << QLatin1String("rotation") << QLatin1String("margins")
+ << QLatin1String("verticalCenterOffset") << QLatin1String("horizontalCenterOffset")
+ << QLatin1String("baselineOffset") << QLatin1String("bottomMargin")
+ << QLatin1String("topMargin") << QLatin1String("leftMargin")
+ << QLatin1String("rightMargin") << QLatin1String("baseline")
+ << QLatin1String("centerIn") << QLatin1String("fill")
+ << QLatin1String("left") << QLatin1String("right")
+ << QLatin1String("mirrored") << QLatin1String("verticalCenter")
+ << QLatin1String("horizontalCenter");
+
+ }
+};
+
+class UnsupportedTypesByVisualDesigner : public QStringList
+{
+public:
+ UnsupportedTypesByVisualDesigner()
+ {
+ (*this) << QLatin1String("Transform") << QLatin1String("Timer")
+ << QLatin1String("Rotation") << QLatin1String("Scale")
+ << QLatin1String("Translate") << QLatin1String("Package")
+ << QLatin1String("Particles");
+ }
+
+};
} // end of anonymous namespace
+Q_GLOBAL_STATIC(VisualAspectsPropertyBlackList, visualAspectsPropertyBlackList)
+Q_GLOBAL_STATIC(UnsupportedTypesByVisualDesigner, unsupportedTypesByVisualDesigner)
+
Check::Check(Document::Ptr doc, const ContextPtr &context)
: _doc(doc)
, _context(context)
@@ -523,6 +553,11 @@ Check::Check(Document::Ptr doc, const ContextPtr &context)
disableMessage(HintBinaryOperatorSpacing);
disableMessage(HintOneStatementPerLine);
disableMessage(HintExtraParentheses);
+ disableMessage(WarnImperativeCodeNotEditableInVisualDesigner);
+ disableMessage(WarnUnsupportedTypeInVisualDesigner);
+ disableMessage(WarnReferenceToParentItemNotSupportedByVisualDesigner);
+ disableMessage(WarnUndefinedValueForVisualDesigner);
+ disableMessage(WarnStatesOnlyInRootItemForVisualDesigner);
}
Check::~Check()
@@ -568,26 +603,32 @@ bool Check::visit(UiProgram *)
bool Check::visit(UiObjectInitializer *)
{
+ QString typeName;
m_propertyStack.push(StringSet());
- UiObjectDefinition *objectDefinition = cast<UiObjectDefinition *>(parent());
- if (objectDefinition && objectDefinition->qualifiedTypeNameId->name == "Component")
- m_idStack.push(StringSet());
- UiObjectBinding *objectBinding = cast<UiObjectBinding *>(parent());
- if (objectBinding && objectBinding->qualifiedTypeNameId->name == "Component")
- m_idStack.push(StringSet());
+ UiQualifiedId *qualifiedTypeId = qualifiedTypeNameId(parent());
+ if (qualifiedTypeId) {
+ typeName = qualifiedTypeId->name.toString();
+ if (typeName == QLatin1String("Component"))
+ m_idStack.push(StringSet());
+ }
+
+ m_typeStack.push(typeName);
+
if (m_idStack.isEmpty())
m_idStack.push(StringSet());
+
return true;
}
void Check::endVisit(UiObjectInitializer *)
{
m_propertyStack.pop();
+ m_typeStack.pop();
UiObjectDefinition *objectDenition = cast<UiObjectDefinition *>(parent());
- if (objectDenition && objectDenition->qualifiedTypeNameId->name == "Component")
+ if (objectDenition && objectDenition->qualifiedTypeNameId->name == QLatin1String("Component"))
m_idStack.pop();
UiObjectBinding *objectBinding = cast<UiObjectBinding *>(parent());
- if (objectBinding && objectBinding->qualifiedTypeNameId->name == "Component")
+ if (objectBinding && objectBinding->qualifiedTypeNameId->name == QLatin1String("Component"))
m_idStack.pop();
}
@@ -595,9 +636,8 @@ void Check::checkProperty(UiQualifiedId *qualifiedId)
{
const QString id = toString(qualifiedId);
if (id.at(0).isLower()) {
- if (m_propertyStack.top().contains(id)) {
+ if (m_propertyStack.top().contains(id))
addMessage(ErrPropertiesCanOnlyHaveOneBinding, fullLocationForQualifiedId(qualifiedId));
- }
m_propertyStack.top().insert(id);
}
}
@@ -618,6 +658,57 @@ bool Check::visit(UiObjectBinding *ast)
return false;
}
+static bool expressionAffectsVisualAspects(BinaryExpression *expression)
+{
+ if (expression->op == QSOperator::Assign
+ || expression->op == QSOperator::InplaceSub
+ || expression->op == QSOperator::InplaceAdd
+ || expression->op == QSOperator::InplaceDiv
+ || expression->op == QSOperator::InplaceMul
+ || expression->op == QSOperator::InplaceOr
+ || expression->op == QSOperator::InplaceXor
+ || expression->op == QSOperator::InplaceAnd) {
+
+ const ExpressionNode *lhsValue = expression->left;
+
+ if (const IdentifierExpression* identifierExpression = cast<const IdentifierExpression *>(lhsValue)) {
+ if (visualAspectsPropertyBlackList()->contains(identifierExpression->name.toString()))
+ return true;
+ } else if (const FieldMemberExpression* fieldMemberExpression = cast<const FieldMemberExpression *>(lhsValue)) {
+ if (visualAspectsPropertyBlackList()->contains(fieldMemberExpression->name.toString()))
+ return true;
+ }
+ }
+ return false;
+}
+
+static UiQualifiedId *getRightMostIdentifier(UiQualifiedId *typeId)
+{
+ if (typeId->next)
+ return getRightMostIdentifier(typeId->next);
+
+ return typeId;
+}
+
+static bool checkTypeForDesignerSupport(UiQualifiedId *typeId)
+{
+ return unsupportedTypesByVisualDesigner()->contains(getRightMostIdentifier(typeId)->name.toString());
+}
+
+static bool checkTopLevelBindingForParentReference(ExpressionStatement *expStmt, const QString &source)
+{
+ if (!expStmt)
+ return false;
+
+ SourceLocation location = locationFromRange(expStmt->firstSourceLocation(), expStmt->lastSourceLocation());
+ QString stmtSource = source.mid(location.begin(), location.length);
+
+ if (stmtSource.contains(QRegExp(QLatin1String("(^|\\W)parent\\."))))
+ return true;
+
+ return false;
+}
+
void Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,
UiObjectInitializer *initializer)
{
@@ -629,9 +720,16 @@ void Check::visitQmlObject(Node *ast, UiQualifiedId *typeId,
return;
}
+ const SourceLocation typeErrorLocation = fullLocationForQualifiedId(typeId);
+
+ if (checkTypeForDesignerSupport(typeId))
+ addMessage(WarnUnsupportedTypeInVisualDesigner, typeErrorLocation);
+
+ if (m_typeStack.count() > 1 && getRightMostIdentifier(typeId)->name.toString() == QLatin1String("State"))
+ addMessage(WarnStatesOnlyInRootItemForVisualDesigner, typeErrorLocation);
+
bool typeError = false;
if (_importsOk) {
- const SourceLocation typeErrorLocation = fullLocationForQualifiedId(typeId);
const ObjectValue *prototype = _context->lookupType(_doc.data(), typeId);
if (!prototype) {
typeError = true;
@@ -699,7 +797,7 @@ bool Check::visit(UiScriptBinding *ast)
return false;
}
- if (id.isEmpty() || (!id.at(0).isLower() && id.at(0) != '_')) {
+ if (id.isEmpty() || (!id.at(0).isLower() && id.at(0) != QLatin1Char('_'))) {
addMessage(ErrInvalidId, loc);
return false;
}
@@ -711,6 +809,13 @@ bool Check::visit(UiScriptBinding *ast)
m_idStack.top().insert(id);
}
+ if (m_typeStack.count() == 1
+ && visualAspectsPropertyBlackList()->contains(ast->qualifiedId->name.toString())
+ && checkTopLevelBindingForParentReference(cast<ExpressionStatement *>(ast->statement), _doc->source())) {
+ addMessage(WarnReferenceToParentItemNotSupportedByVisualDesigner,
+ locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()));
+ }
+
checkProperty(ast->qualifiedId);
if (!ast->statement)
@@ -721,6 +826,12 @@ bool Check::visit(UiScriptBinding *ast)
Evaluate evaluator(&_scopeChain);
const Value *rhsValue = evaluator(ast->statement);
+ if (visualAspectsPropertyBlackList()->contains(ast->qualifiedId->name.toString()) &&
+ rhsValue->asUndefinedValue()) {
+ addMessage(WarnUndefinedValueForVisualDesigner,
+ locationFromRange(ast->firstSourceLocation(), ast->lastSourceLocation()));
+ }
+
const SourceLocation loc = locationFromRange(ast->statement->firstSourceLocation(),
ast->statement->lastSourceLocation());
AssignmentCheck assignmentCheck;
@@ -910,6 +1021,11 @@ bool Check::visit(BinaryExpression *ast)
addMessage(HintBinaryOperatorSpacing, op);
}
+ SourceLocation expressionSourceLocation = locationFromRange(ast->firstSourceLocation(),
+ ast->lastSourceLocation());
+ if (expressionAffectsVisualAspects(ast))
+ addMessage(WarnImperativeCodeNotEditableInVisualDesigner, expressionSourceLocation);
+
// check ==, !=
if (ast->op == QSOperator::Equal || ast->op == QSOperator::NotEqual) {
Evaluate eval(&_scopeChain);
@@ -1032,9 +1148,8 @@ bool Check::visit(ExpressionStatement *ast)
default: break;
}
}
- if (!ok) {
+ if (!ok)
ok = _inStatementBinding;
- }
if (!ok) {
addMessage(WarnConfusingExpressionStatement,
@@ -1119,9 +1234,8 @@ void Check::checkNewExpression(ExpressionNode *ast)
const QString name = functionName(ast, &location);
if (name.isEmpty())
return;
- if (!name.at(0).isUpper()) {
+ if (!name.at(0).isUpper())
addMessage(WarnNewWithLowercaseFunction, location);
- }
}
void Check::checkBindingRhs(Statement *statement)
@@ -1138,9 +1252,8 @@ void Check::checkBindingRhs(Statement *statement)
void Check::checkExtraParentheses(ExpressionNode *expression)
{
- if (NestedExpression *nested = cast<NestedExpression *>(expression)) {
+ if (NestedExpression *nested = cast<NestedExpression *>(expression))
addMessage(HintExtraParentheses, nested->lparenToken);
- }
}
void Check::addMessages(const QList<Message> &messages)
@@ -1188,9 +1301,8 @@ void Check::scanCommentsForAnnotations()
const QString &comment = _doc->source().mid(commentLoc.begin(), commentLoc.length);
// enable all checks annotation
- if (comment.contains(QLatin1String("@enable-all-checks"))) {
+ if (comment.contains(QLatin1String("@enable-all-checks")))
_enabledMessages = Message::allMessageTypes().toSet();
- }
// find all disable annotations
int lastOffset = -1;
diff --git a/src/libs/qmljs/qmljscheck.h b/src/libs/qmljs/qmljscheck.h
index a51d0cb7bb..2f15bdc180 100644
--- a/src/libs/qmljs/qmljscheck.h
+++ b/src/libs/qmljs/qmljscheck.h
@@ -132,6 +132,7 @@ private:
QList<AST::Node *> _chain;
QStack<StringSet> m_idStack;
QStack<StringSet> m_propertyStack;
+ QStack<QString> m_typeStack;
class MessageTypeAndSuppression
{
diff --git a/src/libs/qmljs/qmljscodeformatter.cpp b/src/libs/qmljs/qmljscodeformatter.cpp
index 730cdaff45..6007931104 100644
--- a/src/libs/qmljs/qmljscodeformatter.cpp
+++ b/src/libs/qmljs/qmljscodeformatter.cpp
@@ -407,16 +407,10 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block)
break;
case condition_open:
+ if (tryInsideExpression())
+ break;
switch (kind) {
case RightParenthesis: turnInto(substatement); break;
- case LeftParenthesis: enter(condition_paren_open); break;
- } break;
-
- // paren nesting
- case condition_paren_open:
- switch (kind) {
- case RightParenthesis: leave(); break;
- case LeftParenthesis: enter(condition_paren_open); break;
} break;
case switch_statement:
@@ -839,11 +833,10 @@ int CodeFormatter::column(int index) const
const QChar tab = QLatin1Char('\t');
for (int i = 0; i < index; i++) {
- if (m_currentLine[i] == tab) {
+ if (m_currentLine[i] == tab)
col = ((col / m_tabSize) + 1) * m_tabSize;
- } else {
+ else
col++;
- }
}
return col;
}
@@ -927,23 +920,23 @@ CodeFormatter::TokenKind CodeFormatter::extendedTokenKind(const QmlJS::Token &to
QStringRef text = m_currentLine.midRef(token.begin(), token.length);
if (kind == Identifier) {
- if (text == "as")
+ if (text == QLatin1String("as"))
return As;
- if (text == "import")
+ if (text == QLatin1String("import"))
return Import;
- if (text == "signal")
+ if (text == QLatin1String("signal"))
return Signal;
- if (text == "property")
+ if (text == QLatin1String("property"))
return Property;
- if (text == "on")
+ if (text == QLatin1String("on"))
return On;
- if (text == "list")
+ if (text == QLatin1String("list"))
return List;
} else if (kind == Keyword) {
- const QChar char1 = text.at(0);
- const QChar char2 = text.at(1);
- const QChar char3 = (text.size() > 2 ? text.at(2) : QChar());
- switch (char1.toLatin1()) {
+ const char char1 = text.at(0).toLatin1();
+ const char char2 = text.at(1).toLatin1();
+ const char char3 = (text.size() > 2 ? text.at(2).toLatin1() : 0);
+ switch (char1) {
case 'v':
return Var;
case 'i':
@@ -998,11 +991,11 @@ CodeFormatter::TokenKind CodeFormatter::extendedTokenKind(const QmlJS::Token &to
return Break;
}
} else if (kind == Delimiter) {
- if (text == "?")
+ if (text == QLatin1String("?"))
return Question;
- else if (text == "++")
+ else if (text == QLatin1String("++"))
return PlusPlus;
- else if (text == "--")
+ else if (text == QLatin1String("--"))
return MinusMinus;
}
@@ -1022,7 +1015,7 @@ void CodeFormatter::dump() const
QString CodeFormatter::stateToString(int type) const
{
const QMetaEnum &metaEnum = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("StateType"));
- return metaEnum.valueToKey(type);
+ return QString::fromUtf8(metaEnum.valueToKey(type));
}
QtStyleCodeFormatter::QtStyleCodeFormatter()
@@ -1131,7 +1124,6 @@ void QtStyleCodeFormatter::onEnter(int newState, int *indentDepth, int *savedInd
case signal_arglist_open:
case function_arglist_open:
case paren_open:
- case condition_paren_open:
if (!lastToken)
*indentDepth = tokenPosition + 1;
else
@@ -1325,9 +1317,8 @@ void QtStyleCodeFormatter::adjustIndent(const QList<Token> &tokens, int startLex
break;
case Colon:
- if (topState.type == ternary_op) {
+ if (topState.type == ternary_op)
*indentDepth -= 2;
- }
break;
case Question:
diff --git a/src/libs/qmljs/qmljscodeformatter.h b/src/libs/qmljs/qmljscodeformatter.h
index c38a59a9f1..4c0c7ecc9f 100644
--- a/src/libs/qmljs/qmljscodeformatter.h
+++ b/src/libs/qmljs/qmljscodeformatter.h
@@ -154,7 +154,6 @@ public: // must be public to make Q_GADGET introspection work
else_clause, // The else line of an if-else construct.
condition_open, // Start of a condition in 'if', 'while', entered after opening paren
- condition_paren_open, // After an lparen in a condition
substatement, // The first line after a conditional or loop construct.
substatement_open, // The brace that opens a substatement block.
diff --git a/src/libs/qmljs/qmljscompletioncontextfinder.cpp b/src/libs/qmljs/qmljscompletioncontextfinder.cpp
index 4415aaface..e72cce45ee 100644
--- a/src/libs/qmljs/qmljscompletioncontextfinder.cpp
+++ b/src/libs/qmljs/qmljscompletioncontextfinder.cpp
@@ -238,9 +238,8 @@ void CompletionContextFinder::checkImport()
break;
}
} else if (tokenString == QLatin1String("import")) {
- if (state == Unknown || (state & ExpectImport)) {
+ if (state == Unknown || (state & ExpectImport))
m_inImport = true;
- }
} else {
if (state == Unknown || (state & ExpectAnyTarget)
|| (state & ExpectTargetIdentifier)) {
diff --git a/src/libs/qmljs/qmljsdelta.cpp b/src/libs/qmljs/qmljsdelta.cpp
index 12def15f50..70185ba7e5 100644
--- a/src/libs/qmljs/qmljsdelta.cpp
+++ b/src/libs/qmljs/qmljsdelta.cpp
@@ -61,9 +61,8 @@ private:
bool BuildParentHash::preVisit(Node* ast)
{
- if (ast->uiObjectMemberCast()) {
+ if (ast->uiObjectMemberCast())
stack.append(ast->uiObjectMemberCast());
- }
return true;
}
@@ -71,9 +70,8 @@ void BuildParentHash::postVisit(Node* ast)
{
if (ast->uiObjectMemberCast()) {
stack.removeLast();
- if (!stack.isEmpty()) {
+ if (!stack.isEmpty())
parent.insert(ast->uiObjectMemberCast(), stack.last());
- }
}
}
@@ -99,11 +97,11 @@ static QString label(UiObjectMember *member, Document::Ptr doc)
if (UiObjectDefinition* foo = cast<UiObjectDefinition *>(member)) {
str = label(foo->qualifiedTypeNameId);
- } else if(UiObjectBinding *foo = cast<UiObjectBinding *>(member)) {
+ } else if (UiObjectBinding *foo = cast<UiObjectBinding *>(member)) {
str = label(foo->qualifiedId) + QLatin1Char(' ') + label(foo->qualifiedTypeNameId);
- } else if(UiArrayBinding *foo = cast<UiArrayBinding *>(member)) {
+ } else if (UiArrayBinding *foo = cast<UiArrayBinding *>(member)) {
str = label(foo->qualifiedId) + QLatin1String("[]");
- } else if(UiScriptBinding *foo = cast<UiScriptBinding *>(member)) {
+ } else if (UiScriptBinding *foo = cast<UiScriptBinding *>(member)) {
str = label(foo->qualifiedId) + QLatin1Char(':');
if (foo->statement) {
quint32 start = foo->statement->firstSourceLocation().begin();
@@ -172,7 +170,7 @@ static QList<UiObjectMember *> children(UiObjectMember *ast)
ret.append(list->member);
list = list->next;
}
- } else if(UiArrayBinding *foo = cast<UiArrayBinding *>(ast)) {
+ } else if (UiArrayBinding *foo = cast<UiArrayBinding *>(ast)) {
UiArrayMemberList* list = foo->members;
while (list) {
ret.append(list->member);
@@ -189,7 +187,7 @@ static Map buildMapping_helper(UiObjectMember *x, UiObjectMember *y, const Map &
return M2;
if (M.way2.contains(y))
return M2;
- if(label(x, doc1) != label(y, doc2))
+ if (label(x, doc1) != label(y, doc2))
return M2;
M2.insert(x, y);
QList<UiObjectMember *> list1 = children(x);
@@ -222,7 +220,7 @@ static Map buildMapping(Document::Ptr doc1, Document::Ptr doc2)
Map M;
QList<UiObjectMember *> todo;
todo.append(doc1->qmlProgram()->members->member);
- while(!todo.isEmpty()) {
+ while (!todo.isEmpty()) {
UiObjectMember *x = todo.takeFirst();
todo += children(x);
@@ -291,9 +289,8 @@ static QString _propertyName(UiQualifiedId *id)
static QString _methodName(UiSourceElement *source)
{
if (source) {
- if (FunctionDeclaration *declaration = cast<FunctionDeclaration*>(source->sourceElement)) {
+ if (FunctionDeclaration *declaration = cast<FunctionDeclaration*>(source->sourceElement))
return declaration->name.toString();
- }
}
return QString();
}
@@ -380,7 +377,7 @@ void Delta::insert(UiObjectMember *member, UiObjectMember *parentMember, const Q
// Also, a relative URL is expected (no "file://" prepending!)
QString filename = doc->fileName() + QLatin1Char('_') + QString::number(doc->editorRevision())
+ QLatin1Char(':') + QString::number(startLine-importList.count());
- foreach(DebugId debugId, debugReferences) {
+ foreach (DebugId debugId, debugReferences) {
if (debugId != -1) {
int order = 0;
// skip children which are not objects
@@ -415,9 +412,8 @@ void Delta::update(UiObjectMember* oldObject, const QmlJS::Document::Ptr& oldDoc
const QString scriptCode = _scriptCode(script, newDoc);
UiScriptBinding *previousScript = cast<UiScriptBinding *>(oldMember);
if (!previousScript || _scriptCode(previousScript, oldDoc) != scriptCode) {
- if (debugReferences.count()==0) {
+ if (debugReferences.count()==0)
notifyUnsyncronizableElementChange(newObject);
- }
foreach (DebugId ref, debugReferences) {
if (ref != -1)
updateScriptBinding(ref, newObject, script, property, scriptCode);
@@ -429,9 +425,8 @@ void Delta::update(UiObjectMember* oldObject, const QmlJS::Document::Ptr& oldDoc
UiSourceElement *previousSource = cast<UiSourceElement*>(oldMember);
if (!previousSource || _methodCode(previousSource, oldDoc) != methodCode) {
- if (debugReferences.count()==0) {
+ if (debugReferences.count()==0)
notifyUnsyncronizableElementChange(newObject);
- }
foreach (DebugId ref, debugReferences) {
if (ref != -1)
updateMethodBody(ref, newObject, script, methodName, methodCode);
@@ -492,7 +487,7 @@ Delta::DebugIdMap Delta::operator()(const Document::Ptr &doc1, const Document::P
QList<UiObjectMember *> todo;
todo.append(doc2->qmlProgram()->members->member);
//UiObjectMemberList *list = 0;
- while(!todo.isEmpty()) {
+ while (!todo.isEmpty()) {
UiObjectMember *y = todo.takeFirst();
todo += children(y);
@@ -539,7 +534,7 @@ Delta::DebugIdMap Delta::operator()(const Document::Ptr &doc1, const Document::P
}
todo.append(doc1->qmlProgram()->members->member);
- while(!todo.isEmpty()) {
+ while (!todo.isEmpty()) {
UiObjectMember *x = todo.takeFirst();
todo += children(x);
if (!cast<UiObjectDefinition *>(x))
diff --git a/src/libs/qmljs/qmljsdocument.cpp b/src/libs/qmljs/qmljsdocument.cpp
index 109cee3170..64cd32d80f 100644
--- a/src/libs/qmljs/qmljsdocument.cpp
+++ b/src/libs/qmljs/qmljsdocument.cpp
@@ -83,6 +83,21 @@ using namespace QmlJS::AST;
*/
+bool Document::isQmlLikeLanguage(Document::Language language)
+{
+ switch (language) {
+ case QmlLanguage:
+ case QmlQtQuick1Language:
+ case QmlQtQuick2Language:
+ case QmlQbsLanguage:
+ case QmlProjectLanguage:
+ case QmlTypeInfoLanguage:
+ return true;
+ default:
+ return false;
+ }
+}
+
Document::Document(const QString &fileName, Language language)
: _engine(0)
, _ast(0)
@@ -95,7 +110,7 @@ Document::Document(const QString &fileName, Language language)
QFileInfo fileInfo(fileName);
_path = QDir::cleanPath(fileInfo.absolutePath());
- if (language == QmlLanguage) {
+ if (isQmlLikeLanguage(language)) {
_componentName = fileInfo.baseName();
if (! _componentName.isEmpty()) {
@@ -125,11 +140,13 @@ Document::MutablePtr Document::create(const QString &fileName, Language language
Document::Language Document::guessLanguageFromSuffix(const QString &fileName)
{
- if (fileName.endsWith(".qml", Qt::CaseInsensitive))
+ if (fileName.endsWith(QLatin1String(".qml"), Qt::CaseInsensitive))
return QmlLanguage;
- if (fileName.endsWith(".js", Qt::CaseInsensitive))
+ if (fileName.endsWith(QLatin1String(".qbs"), Qt::CaseInsensitive))
+ return QmlQbsLanguage;
+ if (fileName.endsWith(QLatin1String(".js"), Qt::CaseInsensitive))
return JavaScriptLanguage;
- if (fileName.endsWith(".json", Qt::CaseInsensitive))
+ if (fileName.endsWith(QLatin1String(".json"), Qt::CaseInsensitive))
return JsonLanguage;
return UnknownLanguage;
}
@@ -141,7 +158,7 @@ Document::Ptr Document::ptr() const
bool Document::isQmlDocument() const
{
- return _language == QmlLanguage;
+ return isQmlLikeLanguage(_language);
}
Document::Language Document::language() const
@@ -259,7 +276,7 @@ bool Document::parse_helper(int startToken)
Parser parser(_engine);
QString source = _source;
- lexer.setCode(source, /*line = */ 1, /*qmlMode = */_language == QmlLanguage);
+ lexer.setCode(source, /*line = */ 1, /*qmlMode = */isQmlLikeLanguage(_language));
CollectDirectives collectDirectives(path());
_engine->setDirectives(&collectDirectives);
@@ -378,9 +395,8 @@ Document::MutablePtr Snapshot::documentFromSource(
{
Document::MutablePtr newDoc = Document::create(fileName, language);
- if (Document::Ptr thisDocument = document(fileName)) {
+ if (Document::Ptr thisDocument = document(fileName))
newDoc->_editorRevision = thisDocument->_editorRevision;
- }
newDoc->setSource(code);
return newDoc;
diff --git a/src/libs/qmljs/qmljsdocument.h b/src/libs/qmljs/qmljsdocument.h
index ab88bb48cb..0d529007da 100644
--- a/src/libs/qmljs/qmljsdocument.h
+++ b/src/libs/qmljs/qmljsdocument.h
@@ -51,15 +51,20 @@ public:
typedef QSharedPointer<const Document> Ptr;
typedef QSharedPointer<Document> MutablePtr;
- // used in a 3-bit bitfield
enum Language
{
- QmlLanguage = 0,
+ UnknownLanguage = 0,
JavaScriptLanguage = 1,
JsonLanguage = 2,
- UnknownLanguage = 3
+ QmlLanguage = 3,
+ QmlQtQuick1Language = 4,
+ QmlQtQuick2Language = 5,
+ QmlQbsLanguage = 6,
+ QmlProjectLanguage = 7,
+ QmlTypeInfoLanguage = 8
};
+ static bool isQmlLikeLanguage(Language languge);
protected:
Document(const QString &fileName, Language language);
@@ -117,8 +122,8 @@ private:
QString _source;
QWeakPointer<Document> _ptr;
int _editorRevision;
- Language _language : 3;
- bool _parsedCorrectly : 1;
+ Language _language;
+ bool _parsedCorrectly;
// for documentFromSource
friend class Snapshot;
diff --git a/src/libs/qmljs/qmljsevaluate.cpp b/src/libs/qmljs/qmljsevaluate.cpp
index 32c531c54d..79f6f35e28 100644
--- a/src/libs/qmljs/qmljsevaluate.cpp
+++ b/src/libs/qmljs/qmljsevaluate.cpp
@@ -318,9 +318,8 @@ bool Evaluate::visit(AST::FieldMemberExpression *ast)
return false;
if (const Value *base = _valueOwner->convertToObject(value(ast->base))) {
- if (const ObjectValue *obj = base->asObjectValue()) {
+ if (const ObjectValue *obj = base->asObjectValue())
_result = obj->lookupMember(ast->name.toString(), _context);
- }
}
return false;
@@ -328,26 +327,23 @@ bool Evaluate::visit(AST::FieldMemberExpression *ast)
bool Evaluate::visit(AST::NewMemberExpression *ast)
{
- if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->base))) {
+ if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->base)))
_result = ctor->returnValue();
- }
return false;
}
bool Evaluate::visit(AST::NewExpression *ast)
{
- if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->expression))) {
+ if (const FunctionValue *ctor = value_cast<FunctionValue>(value(ast->expression)))
_result = ctor->returnValue();
- }
return false;
}
bool Evaluate::visit(AST::CallExpression *ast)
{
if (const Value *base = value(ast->base)) {
- if (const FunctionValue *obj = base->asFunctionValue()) {
+ if (const FunctionValue *obj = base->asFunctionValue())
_result = obj->returnValue();
- }
}
return false;
}
diff --git a/src/libs/qmljs/qmljsicons.cpp b/src/libs/qmljs/qmljsicons.cpp
index 88cbbebc25..6235faf783 100644
--- a/src/libs/qmljs/qmljsicons.cpp
+++ b/src/libs/qmljs/qmljsicons.cpp
@@ -119,12 +119,10 @@ QIcon Icons::icon(const QString &packageName, const QString typeName) const
QIcon Icons::icon(Node *node) const
{
- if (dynamic_cast<AST::UiObjectDefinition*>(node)) {
+ if (dynamic_cast<AST::UiObjectDefinition*>(node))
return objectDefinitionIcon();
- }
- if (dynamic_cast<AST::UiScriptBinding*>(node)) {
+ if (dynamic_cast<AST::UiScriptBinding*>(node))
return scriptBindingIcon();
- }
return QIcon();
}
diff --git a/src/libs/qmljs/qmljsindenter.cpp b/src/libs/qmljs/qmljsindenter.cpp
index 3df0bac065..873f4100d6 100644
--- a/src/libs/qmljs/qmljsindenter.cpp
+++ b/src/libs/qmljs/qmljsindenter.cpp
@@ -147,11 +147,10 @@ int QmlJSIndenter::columnForIndex(const QString &t, int index) const
index = t.length();
for (int i = 0; i < index; i++) {
- if (t.at(i) == QLatin1Char('\t')) {
+ if (t.at(i) == QLatin1Char('\t'))
col = ((col / ppHardwareTabSize) + 1) * ppHardwareTabSize;
- } else {
+ else
col++;
- }
}
return col;
}
@@ -186,10 +185,10 @@ QChar QmlJSIndenter::lastParen() const
const Token &token = yyLinizerState.tokens.at(index);
if (token.is(Token::LeftParenthesis))
- return QChar('(');
+ return QLatin1Char('(');
else if (token.is(Token::RightParenthesis))
- return QChar(')');
+ return QLatin1Char(')');
}
return QChar();
@@ -288,11 +287,10 @@ int QmlJSIndenter::indentForContinuationLine()
delimiters.
*/
if (braceDepth == -1) {
- if (j < yyLine->length() - 1) {
+ if (j < yyLine->length() - 1)
hook = j;
- } else {
+ else
return 0; // shouldn't happen
- }
}
break;
case '=':
@@ -324,7 +322,7 @@ int QmlJSIndenter::indentForContinuationLine()
Q_ASSERT(j - 1 >= 0);
if (QString::fromLatin1("!=<>").indexOf(yyLine->at(j - 1)) == -1 &&
- j + 1 < yyLine->length() && yyLine->at(j + 1) != '=') {
+ j + 1 < yyLine->length() && yyLine->at(j + 1) != QLatin1Char('=')) {
if (braceDepth == 0 && delimDepth == 0 &&
j < yyLine->length() - 1 &&
!yyLine->endsWith(QLatin1Char(',')) &&
@@ -587,17 +585,15 @@ int QmlJSIndenter::indentForBottomLine(QTextBlock begin, QTextBlock end, QChar t
smartly, unless the user has already played around with it,
in which case it's better to leave her stuff alone.
*/
- if (isOnlyWhiteSpace(bottomLine)) {
+ if (isOnlyWhiteSpace(bottomLine))
indent = indentWhenBottomLineStartsInMultiLineComment();
- } else {
+ else
indent = indentOfLine(bottomLine);
- }
} else {
- if (isUnfinishedLine()) {
+ if (isUnfinishedLine())
indent = indentForContinuationLine();
- } else {
+ else
indent = indentForStandaloneLine();
- }
if ((okay(typedIn, QLatin1Char('}')) && firstCh == QLatin1Char('}'))
|| (okay(typedIn, QLatin1Char(']')) && firstCh == QLatin1Char(']'))) {
diff --git a/src/libs/qmljs/qmljsinterpreter.cpp b/src/libs/qmljs/qmljsinterpreter.cpp
index b32f48fa52..ce4b8101dc 100644
--- a/src/libs/qmljs/qmljsinterpreter.cpp
+++ b/src/libs/qmljs/qmljsinterpreter.cpp
@@ -357,9 +357,8 @@ const Value *CppComponentValue::valueForCppName(const QString &typeName) const
// might be an enum
const CppComponentValue *base = this;
const QStringList components = typeName.split(QLatin1String("::"));
- if (components.size() == 2) {
+ if (components.size() == 2)
base = valueOwner()->cppQmlTypes().objectByCppName(components.first());
- }
if (base) {
if (const QmlEnumValue *value = base->getEnumValue(components.last()))
return value;
@@ -413,9 +412,8 @@ QString CppComponentValue::propertyType(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName);
- if (propIdx != -1) {
+ if (propIdx != -1)
return iter->property(propIdx).typeName();
- }
}
return QString();
}
@@ -425,9 +423,8 @@ bool CppComponentValue::isListProperty(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName);
- if (propIdx != -1) {
+ if (propIdx != -1)
return iter->property(propIdx).isList();
- }
}
return false;
}
@@ -510,9 +507,8 @@ bool CppComponentValue::isWritable(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName);
- if (propIdx != -1) {
+ if (propIdx != -1)
return iter->property(propIdx).isWritable();
- }
}
return false;
}
@@ -522,9 +518,8 @@ bool CppComponentValue::isPointer(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName);
- if (propIdx != -1) {
+ if (propIdx != -1)
return iter->property(propIdx).isPointer();
- }
}
return false;
}
@@ -542,9 +537,8 @@ bool CppComponentValue::hasProperty(const QString &propertyName) const
foreach (const CppComponentValue *it, prototypes()) {
FakeMetaObject::ConstPtr iter = it->_metaObject;
int propIdx = iter->propertyIndex(propertyName);
- if (propIdx != -1) {
+ if (propIdx != -1)
return true;
- }
}
return false;
}
@@ -956,9 +950,8 @@ const ObjectValue *ObjectValue::prototype(const Context *context) const
{
const ObjectValue *prototypeObject = value_cast<ObjectValue>(_prototype);
if (! prototypeObject) {
- if (const Reference *prototypeReference = value_cast<Reference>(_prototype)) {
+ if (const Reference *prototypeReference = value_cast<Reference>(_prototype))
prototypeObject = value_cast<ObjectValue>(context->lookupReference(prototypeReference));
- }
}
return prototypeObject;
}
@@ -1110,9 +1103,8 @@ const ObjectValue *PrototypeIterator::next()
const ObjectValue *PrototypeIterator::peekNext()
{
- if (hasNext()) {
+ if (hasNext())
return m_next;
- }
return 0;
}
@@ -1131,7 +1123,7 @@ QList<const ObjectValue *> PrototypeIterator::all()
FunctionValue::FunctionValue(ValueOwner *valueOwner)
: ObjectValue(valueOwner)
{
- setClassName("Function");
+ setClassName(QLatin1String("Function"));
setMember(QLatin1String("length"), valueOwner->numberValue());
setPrototype(valueOwner->functionPrototype());
}
@@ -1299,11 +1291,10 @@ void CppQmlTypesLoader::parseQmlTypeDescriptions(const QByteArray &xml,
warningMessage->clear();
TypeDescriptionReader reader(QString::fromUtf8(xml));
if (!reader(newObjects, newModuleApis)) {
- if (reader.errorMessage().isEmpty()) {
+ if (reader.errorMessage().isEmpty())
*errorMessage = QLatin1String("unknown error");
- } else {
+ else
*errorMessage = reader.errorMessage();
- }
}
*warningMessage = reader.warningMessage();
}
@@ -1357,7 +1348,8 @@ template void CppQmlTypes::load< QHash<QString, FakeMetaObject::ConstPtr> >(cons
QList<const CppComponentValue *> CppQmlTypes::createObjectsForImport(const QString &package, ComponentVersion version)
{
- QList<const CppComponentValue *> exportedObjects;
+ QHash<QString, const CppComponentValue *> exportedObjects;
+
QList<const CppComponentValue *> newObjects;
// make new exported objects
@@ -1397,8 +1389,11 @@ QList<const CppComponentValue *> CppQmlTypes::createObjectsForImport(const QStri
// use package.cppname importversion as key
_objectsByQualifiedName.insert(key, newComponent);
- if (exported)
- exportedObjects += newComponent;
+ if (exported) {
+ if (!exportedObjects.contains(name) // we might have the same type in different versions
+ || (newComponent->componentVersion() > exportedObjects.value(name)->componentVersion()))
+ exportedObjects.insert(name, newComponent);
+ }
newObjects += newComponent;
}
}
@@ -1436,7 +1431,7 @@ QList<const CppComponentValue *> CppQmlTypes::createObjectsForImport(const QStri
}
}
- return exportedObjects;
+ return exportedObjects.values();
}
bool CppQmlTypes::hasModule(const QString &module) const
@@ -1446,7 +1441,7 @@ bool CppQmlTypes::hasModule(const QString &module) const
QString CppQmlTypes::qualifiedName(const QString &module, const QString &type, ComponentVersion version)
{
- return QString("%1/%2 %3").arg(
+ return QString::fromLatin1("%1/%2 %3").arg(
module, type,
version.toString());
@@ -1528,14 +1523,16 @@ void ConvertToNumber::visit(const StringValue *)
void ConvertToNumber::visit(const ObjectValue *object)
{
- if (const FunctionValue *valueOfMember = value_cast<FunctionValue>(object->lookupMember("valueOf", ContextPtr()))) {
+ if (const FunctionValue *valueOfMember = value_cast<FunctionValue>(
+ object->lookupMember(QLatin1String("valueOf"), ContextPtr()))) {
_result = value_cast<NumberValue>(valueOfMember->returnValue());
}
}
void ConvertToNumber::visit(const FunctionValue *object)
{
- if (const FunctionValue *valueOfMember = value_cast<FunctionValue>(object->lookupMember("valueOf", ContextPtr()))) {
+ if (const FunctionValue *valueOfMember = value_cast<FunctionValue>(
+ object->lookupMember(QLatin1String("valueOf"), ContextPtr()))) {
_result = value_cast<NumberValue>(valueOfMember->returnValue());
}
}
@@ -1589,14 +1586,16 @@ void ConvertToString::visit(const StringValue *value)
void ConvertToString::visit(const ObjectValue *object)
{
- if (const FunctionValue *toStringMember = value_cast<FunctionValue>(object->lookupMember("toString", ContextPtr()))) {
+ if (const FunctionValue *toStringMember = value_cast<FunctionValue>(
+ object->lookupMember(QLatin1String("toString"), ContextPtr()))) {
_result = value_cast<StringValue>(toStringMember->returnValue());
}
}
void ConvertToString::visit(const FunctionValue *object)
{
- if (const FunctionValue *toStringMember = value_cast<FunctionValue>(object->lookupMember("toString", ContextPtr()))) {
+ if (const FunctionValue *toStringMember = value_cast<FunctionValue>(
+ object->lookupMember(QLatin1String("toString"), ContextPtr()))) {
_result = value_cast<StringValue>(toStringMember->returnValue());
}
}
@@ -2098,18 +2097,16 @@ ImportInfo ImportInfo::pathImport(const QString &docPath, const QString &path,
info._name = path;
QFileInfo importFileInfo(path);
- if (!importFileInfo.isAbsolute()) {
+ if (!importFileInfo.isAbsolute())
importFileInfo = QFileInfo(docPath + QDir::separator() + path);
- }
info._path = importFileInfo.absoluteFilePath();
- if (importFileInfo.isFile()) {
+ if (importFileInfo.isFile())
info._type = FileImport;
- } else if (importFileInfo.isDir()) {
+ else if (importFileInfo.isDir())
info._type = DirectoryImport;
- } else {
+ else
info._type = UnknownFileImport;
- }
info._version = version;
info._as = as;
@@ -2222,11 +2219,10 @@ void TypeScope::processMembers(MemberProcessor *processor) const
if (info.type() == ImportInfo::FileImport)
continue;
- if (!info.as().isEmpty()) {
+ if (!info.as().isEmpty())
processor->processProperty(info.as(), import);
- } else {
+ else
import->processMembers(processor);
- }
}
}
diff --git a/src/libs/qmljs/qmljsinterpreter.h b/src/libs/qmljs/qmljsinterpreter.h
index e088e18bca..9c6df29c8d 100644
--- a/src/libs/qmljs/qmljsinterpreter.h
+++ b/src/libs/qmljs/qmljsinterpreter.h
@@ -751,7 +751,7 @@ public:
AST::UiQualifiedId *qmlTypeName() const;
-private:
+private:
virtual const Value *value(ReferenceContext *referenceContext) const;
AST::UiQualifiedId *_qmlTypeName;
diff --git a/src/libs/qmljs/qmljslineinfo.cpp b/src/libs/qmljs/qmljslineinfo.cpp
index af607d3657..e530183406 100644
--- a/src/libs/qmljs/qmljslineinfo.cpp
+++ b/src/libs/qmljs/qmljslineinfo.cpp
@@ -205,11 +205,10 @@ QString LineInfo::trimmedCodeLine(const QString &t)
while (i >= 2) {
const Token &prev = yyLinizerState.tokens.at(i-1);
const Token &prevPrev = yyLinizerState.tokens.at(i-2);
- if (prev.kind == Token::Dot && prevPrev.kind == Token::Identifier) {
+ if (prev.kind == Token::Dot && prevPrev.kind == Token::Identifier)
i -= 2;
- } else {
+ else
break;
- }
}
// it could also be 'a = \n Foo \n {', but that sounds unlikely
@@ -334,8 +333,8 @@ bool LineInfo::readLine()
the other way around, as we are parsing backwards.
*/
yyLinizerState.braceDepth +=
- yyLinizerState.line.count('}') + yyLinizerState.line.count(']') -
- yyLinizerState.line.count('{') - yyLinizerState.line.count('[');
+ yyLinizerState.line.count(QLatin1Char('}')) + yyLinizerState.line.count(QLatin1Char(']')) -
+ yyLinizerState.line.count(QLatin1Char('{')) - yyLinizerState.line.count(QLatin1Char('['));
/*
We use a dirty trick for
diff --git a/src/libs/qmljs/qmljslink.cpp b/src/libs/qmljs/qmljslink.cpp
index 3606cb63c1..d1a2084ad9 100644
--- a/src/libs/qmljs/qmljslink.cpp
+++ b/src/libs/qmljs/qmljslink.cpp
@@ -342,7 +342,7 @@ Import LinkPrivate::importNonFile(Document::Ptr doc, const ImportInfo &importInf
const QString &packagePath = importInfo.path();
// check the filesystem with full version
foreach (const QString &importPath, importPaths) {
- QString libraryPath = QString("%1/%2.%3").arg(importPath, packagePath, version.toString());
+ QString libraryPath = QString::fromLatin1("%1/%2.%3").arg(importPath, packagePath, version.toString());
if (importLibrary(doc, libraryPath, &import, importPath)) {
importFound = true;
break;
@@ -351,7 +351,7 @@ Import LinkPrivate::importNonFile(Document::Ptr doc, const ImportInfo &importInf
if (!importFound) {
// check the filesystem with major version
foreach (const QString &importPath, importPaths) {
- QString libraryPath = QString("%1/%2.%3").arg(importPath, packagePath,
+ QString libraryPath = QString::fromLatin1("%1/%2.%3").arg(importPath, packagePath,
QString::number(version.majorVersion()));
if (importLibrary(doc, libraryPath, &import, importPath)) {
importFound = true;
@@ -362,7 +362,7 @@ Import LinkPrivate::importNonFile(Document::Ptr doc, const ImportInfo &importInf
if (!importFound) {
// check the filesystem with no version
foreach (const QString &importPath, importPaths) {
- QString libraryPath = QString("%1/%2").arg(importPath, packagePath);
+ QString libraryPath = QString::fromLatin1("%1/%2").arg(importPath, packagePath);
if (importLibrary(doc, libraryPath, &import, importPath)) {
importFound = true;
break;
@@ -460,11 +460,10 @@ bool LinkPrivate::importLibrary(Document::Ptr doc,
// all but no-uri module apis become available for import
QList<ModuleApiInfo> noUriModuleApis;
foreach (const ModuleApiInfo &moduleApi, libraryInfo.moduleApis()) {
- if (moduleApi.uri.isEmpty()) {
+ if (moduleApi.uri.isEmpty())
noUriModuleApis += moduleApi;
- } else {
+ else
importableModuleApis[moduleApi.uri] += moduleApi;
- }
}
// if a module api has no uri, it shares the same name
@@ -501,9 +500,8 @@ void LinkPrivate::loadQmldirComponents(ObjectValue *import, ComponentVersion ver
const LibraryInfo &libraryInfo, const QString &libraryPath)
{
// if the version isn't valid, import the latest
- if (!version.isValid()) {
+ if (!version.isValid())
version = ComponentVersion(ComponentVersion::MaxVersion, ComponentVersion::MaxVersion);
- }
QSet<QString> importedTypes;
@@ -535,9 +533,8 @@ void LinkPrivate::loadImplicitDirectoryImports(Imports *imports, Document::Ptr d
if (directoryImport.object)
importCache.insert(ImportCacheKey(implcitDirectoryImportInfo), directoryImport);
}
- if (directoryImport.object) {
+ if (directoryImport.object)
imports->append(directoryImport);
- }
}
void LinkPrivate::loadImplicitDefaultImports(Imports *imports)
diff --git a/src/libs/qmljs/qmljspropertyreader.cpp b/src/libs/qmljs/qmljspropertyreader.cpp
index ac4c21f825..1942860bfa 100644
--- a/src/libs/qmljs/qmljspropertyreader.cpp
+++ b/src/libs/qmljs/qmljspropertyreader.cpp
@@ -143,9 +143,8 @@ static bool isEnum(AST::Statement *ast)
if (!ast)
return false;
- if (ExpressionStatement *exprStmt = cast<ExpressionStatement*>(ast)) {
+ if (ExpressionStatement *exprStmt = cast<ExpressionStatement*>(ast))
return isEnum(exprStmt->expression);
- }
return false;
}
@@ -194,10 +193,11 @@ PropertyReader::PropertyReader(Document::Ptr doc, AST::UiObjectInitializer *ast)
property->statement->firstSourceLocation(),
property->statement->lastSourceLocation()));
if (isLiteralValue(property)) {
- m_properties.insert(propertyName + '.' + propertyNamePart2, QVariant(deEscape(stripQuotes(astValue))));
+ m_properties.insert(propertyName + QLatin1Char('.') + propertyNamePart2,
+ QVariant(deEscape(stripQuotes(astValue))));
} else if (isEnum(property->statement)) { //enum
- m_properties.insert(propertyName + '.' + propertyNamePart2, QVariant(astValue));
- m_bindingOrEnum.append(propertyName + '.' + propertyNamePart2);
+ m_properties.insert(propertyName + QLatin1Char('.') + propertyNamePart2, QVariant(astValue));
+ m_bindingOrEnum.append(propertyName + QLatin1Char('.') + propertyNamePart2);
}
}
}
@@ -230,7 +230,7 @@ QLinearGradient PropertyReader::parseGradient(const QString &propertyName, bool
initializer->rbraceToken));
const QString objectPropertyName = objectBinding->qualifiedId->name.toString();
const QString typeName = objectBinding->qualifiedTypeNameId->name.toString();
- if (objectPropertyName == propertyName && typeName.contains("Gradient")) {
+ if (objectPropertyName == propertyName && typeName.contains(QLatin1String("Gradient"))) {
QLinearGradient gradient;
QVector<QGradientStop> stops;
@@ -238,10 +238,10 @@ QLinearGradient PropertyReader::parseGradient(const QString &propertyName, bool
UiObjectMember *member = members->member;
if (UiObjectDefinition *objectDefinition = cast<UiObjectDefinition *>(member)) {
PropertyReader localParser(m_doc, objectDefinition->initializer);
- if (localParser.hasProperty("color") && localParser.hasProperty("position")) {
- QColor color = QmlJS::toQColor(localParser.readProperty("color").toString());
- qreal position = localParser.readProperty("position").toReal();
- if (localParser.isBindingOrEnum("color") || localParser.isBindingOrEnum("position"))
+ if (localParser.hasProperty(QLatin1String("color")) && localParser.hasProperty(QLatin1String("position"))) {
+ QColor color = QmlJS::toQColor(localParser.readProperty(QLatin1String("color")).toString());
+ qreal position = localParser.readProperty(QLatin1String("position")).toReal();
+ if (localParser.isBindingOrEnum(QLatin1String("color")) || localParser.isBindingOrEnum(QLatin1String("position")))
*isBound = true;
stops.append( QPair<qreal, QColor>(position, color));
}
diff --git a/src/libs/qmljs/qmljsreformatter.cpp b/src/libs/qmljs/qmljsreformatter.cpp
index b396893282..92822d7f70 100644
--- a/src/libs/qmljs/qmljsreformatter.cpp
+++ b/src/libs/qmljs/qmljsreformatter.cpp
@@ -131,7 +131,7 @@ public:
}
// ensure good ending
- if (!_result.endsWith("\n\n") || !_line.isEmpty())
+ if (!_result.endsWith(QLatin1String("\n\n")) || !_line.isEmpty())
newLine();
return _result;
@@ -166,11 +166,10 @@ protected:
if (precededByEmptyLine(fixedLoc))
newLine();
out(toString(fixedLoc)); // don't use the sourceloc overload here
- if (followedByNewLine(fixedLoc)) {
+ if (followedByNewLine(fixedLoc))
newLine();
- } else {
+ else
out(" ");
- }
}
void out(const QString &str, const SourceLocation &lastLoc = SourceLocation())
@@ -260,9 +259,8 @@ protected:
qreal result = badnessFromSplits;
foreach (const QString &line, lines) {
// really long lines should be avoided at all cost
- if (line.size() > strongMaxLineLength) {
+ if (line.size() > strongMaxLineLength)
result += 50 + (line.size() - strongMaxLineLength);
- }
// having long lines is bad
else if (line.size() > maxLineLength) {
result += 3 + (line.size() - maxLineLength);
@@ -287,7 +285,7 @@ protected:
while (startSpaces < line->size() && line->at(startSpaces).isSpace())
++startSpaces;
- line->replace(0, startSpaces, QString(indent, ' '));
+ line->replace(0, startSpaces, QString(indent, QLatin1Char(' ')));
for (int i = 0; i < splits->size(); ++i) {
(*splits)[i].offset = splits->at(i).offset - startSpaces + indent;
}
@@ -313,7 +311,7 @@ protected:
continue;
// the extra space is to avoid // comments sticking to the 0 offset
- QString indentLine = newContext.join("\n") + QLatin1String("\n ") + restLine;
+ QString indentLine = newContext.join(QLatin1String("\n")) + QLatin1String("\n ") + restLine;
int indent = tryIndent(indentLine);
QList<Split> newSplits = possibleSplits.mid(i + 1);
@@ -446,22 +444,20 @@ protected:
virtual bool preVisit(Node *ast)
{
SourceLocation firstLoc;
- if (ExpressionNode *expr = ast->expressionCast()) {
+ if (ExpressionNode *expr = ast->expressionCast())
firstLoc = expr->firstSourceLocation();
- } else if (Statement *stmt = ast->statementCast()) {
+ else if (Statement *stmt = ast->statementCast())
firstLoc = stmt->firstSourceLocation();
- } else if (UiObjectMember *mem = ast->uiObjectMemberCast()) {
+ else if (UiObjectMember *mem = ast->uiObjectMemberCast())
firstLoc = mem->firstSourceLocation();
- } else if (UiImport *import = cast<UiImport *>(ast)) {
+ else if (UiImport *import = cast<UiImport *>(ast))
firstLoc = import->firstSourceLocation();
- }
if (firstLoc.isValid() && int(firstLoc.offset) != _lastNewlineOffset) {
_lastNewlineOffset = firstLoc.offset;
- if (precededByEmptyLine(firstLoc) && !_result.endsWith(QLatin1String("\n\n"))) {
+ if (precededByEmptyLine(firstLoc) && !_result.endsWith(QLatin1String("\n\n")))
newLine();
- }
}
return true;
@@ -470,15 +466,14 @@ protected:
virtual void postVisit(Node *ast)
{
SourceLocation lastLoc;
- if (ExpressionNode *expr = ast->expressionCast()) {
+ if (ExpressionNode *expr = ast->expressionCast())
lastLoc = expr->lastSourceLocation();
- } else if (Statement *stmt = ast->statementCast()) {
+ else if (Statement *stmt = ast->statementCast())
lastLoc = stmt->lastSourceLocation();
- } else if (UiObjectMember *mem = ast->uiObjectMemberCast()) {
+ else if (UiObjectMember *mem = ast->uiObjectMemberCast())
lastLoc = mem->lastSourceLocation();
- } else if (UiImport *import = cast<UiImport *>(ast)) {
+ else if (UiImport *import = cast<UiImport *>(ast))
lastLoc = import->lastSourceLocation();
- }
if (lastLoc.isValid()) {
const QList<SourceLocation> &comments = _doc->engine()->comments();
@@ -510,11 +505,10 @@ protected:
virtual bool visit(UiImport *ast)
{
out("import ", ast->importToken);
- if (!ast->fileName.isNull()) {
- out(QString("\"%1\"").arg(ast->fileName.toString()));
- } else {
+ if (!ast->fileName.isNull())
+ out(QString::fromLatin1("\"%1\"").arg(ast->fileName.toString()));
+ else
accept(ast->importUri);
- }
if (ast->versionToken.isValid()) {
out(" ");
out(ast->versionToken);
diff --git a/src/libs/qmljs/qmljsrewriter.cpp b/src/libs/qmljs/qmljsrewriter.cpp
index 8e9c641713..dffaf89a87 100644
--- a/src/libs/qmljs/qmljsrewriter.cpp
+++ b/src/libs/qmljs/qmljsrewriter.cpp
@@ -288,9 +288,8 @@ void Rewriter::changeBinding(UiObjectInitializer *ast,
// for grouped properties:
else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
- if (toString(def->qualifiedTypeNameId) == prefix) {
+ if (toString(def->qualifiedTypeNameId) == prefix)
changeBinding(def->initializer, suffix, newValue, binding);
- }
}
}
}
@@ -331,7 +330,7 @@ void Rewriter::replaceMemberValue(UiObjectMember *propertyMember,
}
if (needsSemicolon)
- replacement += ';';
+ replacement += QLatin1Char(';');
m_changeSet->replace(startOffset, endOffset, replacement);
}
@@ -353,11 +352,10 @@ bool Rewriter::isMatchingPropertyMember(const QString &propertyName,
bool Rewriter::nextMemberOnSameLine(UiObjectMemberList *members)
{
- if (members && members->next && members->next->member) {
+ if (members && members->next && members->next->member)
return members->next->member->firstSourceLocation().startLine == members->member->lastSourceLocation().startLine;
- } else {
+ else
return false;
- }
}
void Rewriter::insertIntoArray(UiArrayBinding *ast, const QString &newValue)
@@ -388,15 +386,13 @@ void Rewriter::removeBindingByName(UiObjectInitializer *ast, const QString &prop
UiObjectMember *member = it->member;
// run full name match (for ungrouped properties):
- if (isMatchingPropertyMember(propertyName, member)) {
+ if (isMatchingPropertyMember(propertyName, member))
removeMember(member);
- }
// check for grouped properties:
else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
- if (toString(def->qualifiedTypeNameId) == prefix) {
+ if (toString(def->qualifiedTypeNameId) == prefix)
removeGroupedProperty(def, propertyName);
- }
}
}
}
@@ -417,9 +413,8 @@ void Rewriter::removeGroupedProperty(UiObjectDefinition *ast,
++memberCount;
UiObjectMember *member = it->member;
- if (!wanted && isMatchingPropertyMember(propName, member)) {
+ if (!wanted && isMatchingPropertyMember(propName, member))
wanted = member;
- }
}
if (!wanted)
@@ -517,9 +512,8 @@ void Rewriter::includeEmptyGroupedProperty(UiObjectDefinition *groupedProperty,
// grouped property
UiObjectMemberList *memberIter = groupedProperty->initializer->members;
while (memberIter) {
- if (memberIter->member != memberToBeRemoved) {
+ if (memberIter->member != memberToBeRemoved)
return;
- }
memberIter = memberIter->next;
}
start = groupedProperty->firstSourceLocation().begin();
@@ -670,9 +664,8 @@ void Rewriter::removeObjectMember(UiObjectMember *member, UiObjectMember *parent
if (UiArrayBinding *parentArray = cast<UiArrayBinding *>(parent)) {
extendToLeadingOrTrailingComma(parentArray, member, start, end);
} else {
- if (UiObjectDefinition *parentObjectDefinition = cast<UiObjectDefinition *>(parent)) {
+ if (UiObjectDefinition *parentObjectDefinition = cast<UiObjectDefinition *>(parent))
includeEmptyGroupedProperty(parentObjectDefinition, member, start, end);
- }
includeSurroundingWhitespace(m_originalText, start, end);
}
diff --git a/src/libs/qmljs/qmljsscopeastpath.cpp b/src/libs/qmljs/qmljsscopeastpath.cpp
index a2b13c2cc9..7826fe3b52 100644
--- a/src/libs/qmljs/qmljsscopeastpath.cpp
+++ b/src/libs/qmljs/qmljsscopeastpath.cpp
@@ -55,13 +55,12 @@ void ScopeAstPath::accept(Node *node)
bool ScopeAstPath::preVisit(Node *node)
{
- if (Statement *stmt = node->statementCast()) {
+ if (Statement *stmt = node->statementCast())
return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation());
- } else if (ExpressionNode *exp = node->expressionCast()) {
+ else if (ExpressionNode *exp = node->expressionCast())
return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation());
- } else if (UiObjectMember *ui = node->uiObjectMemberCast()) {
+ else if (UiObjectMember *ui = node->uiObjectMemberCast())
return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation());
- }
return true;
}
diff --git a/src/libs/qmljs/qmljsscopebuilder.cpp b/src/libs/qmljs/qmljsscopebuilder.cpp
index 06ca85a102..7810c9a5d1 100644
--- a/src/libs/qmljs/qmljsscopebuilder.cpp
+++ b/src/libs/qmljs/qmljsscopebuilder.cpp
@@ -81,14 +81,12 @@ void ScopeBuilder::push(AST::Node *node)
break;
}
// signals defined in QML
- if (const ASTSignal *astsig = value_cast<ASTSignal>(value)) {
+ if (const ASTSignal *astsig = value_cast<ASTSignal>(value))
_scopeChain->appendJsScope(astsig->bodyScope());
- }
// signals defined in C++
else if (const CppComponentValue *qmlObject = value_cast<CppComponentValue>(owner)) {
- if (const ObjectValue *scope = qmlObject->signalScope(name)) {
+ if (const ObjectValue *scope = qmlObject->signalScope(name))
_scopeChain->appendJsScope(scope);
- }
}
}
}
@@ -170,11 +168,10 @@ void ScopeBuilder::setQmlScopeObject(Node *node)
}
const ObjectValue *scopeObject = _scopeChain->document()->bind()->findQmlObject(node);
- if (scopeObject) {
+ if (scopeObject)
qmlScopeObjects += scopeObject;
- } else {
+ else
return; // Probably syntax errors, where we're working with a "recovered" AST.
- }
// check if the object has a Qt.ListElement or Qt.Connections ancestor
// ### allow only signal bindings for Connections
@@ -208,11 +205,10 @@ void ScopeBuilder::setQmlScopeObject(Node *node)
Evaluate evaluator(_scopeChain);
const Value *targetValue = evaluator(scriptBinding->statement);
- if (const ObjectValue *target = value_cast<ObjectValue>(targetValue)) {
+ if (const ObjectValue *target = value_cast<ObjectValue>(targetValue))
qmlScopeObjects.prepend(target);
- } else {
+ else
qmlScopeObjects.clear();
- }
}
}
}
diff --git a/src/libs/qmljs/qmljssimplereader.cpp b/src/libs/qmljs/qmljssimplereader.cpp
new file mode 100644
index 0000000000..253ba7017e
--- /dev/null
+++ b/src/libs/qmljs/qmljssimplereader.cpp
@@ -0,0 +1,346 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmljssimplereader.h"
+
+#include "parser/qmljsparser_p.h"
+#include "parser/qmljslexer_p.h"
+#include "parser/qmljsengine_p.h"
+#include "parser/qmljsast_p.h"
+#include "parser/qmljsastvisitor_p.h"
+#include <qmljs/qmljsdocument.h>
+
+#include "qmljsbind.h"
+#include "qmljsinterpreter.h"
+#include "qmljsutils.h"
+
+#include <QFile>
+
+enum {
+ debug = false
+};
+
+
+using namespace QmlJS;
+
+QVariant SimpleReaderNode::property(const QString &name) const
+{
+ return m_properties.value(name);
+}
+
+QStringList SimpleReaderNode::propertyNames() const
+{
+ return m_properties.keys();
+}
+
+SimpleReaderNode::PropertyHash SimpleReaderNode::properties() const
+{
+ return m_properties;
+}
+
+bool SimpleReaderNode::isRoot() const
+{
+ return m_parentNode.isNull();
+}
+
+bool SimpleReaderNode::isValid() const
+{
+ return !m_name.isEmpty();
+}
+
+SimpleReaderNode::Ptr SimpleReaderNode::invalidNode()
+{
+ return Ptr(new SimpleReaderNode);
+}
+
+SimpleReaderNode::WeakPtr SimpleReaderNode::parent() const
+{
+ return m_parentNode;
+}
+
+QString SimpleReaderNode::name() const
+{
+ return m_name;
+}
+
+SimpleReaderNode::SimpleReaderNode()
+{
+}
+
+SimpleReaderNode::SimpleReaderNode(const QString &name, WeakPtr parent)
+ : m_name(name), m_parentNode(parent)
+{
+}
+
+SimpleReaderNode::Ptr SimpleReaderNode::create(const QString &name, WeakPtr parent)
+{
+ Ptr newNode(new SimpleReaderNode(name, parent));
+ newNode->m_weakThis = newNode;
+ if (parent)
+ parent.data()->m_children.append(newNode);
+ return newNode;
+}
+
+const SimpleReaderNode::List SimpleReaderNode::children() const
+{
+ return m_children;
+}
+
+void SimpleReaderNode::setProperty(const QString &name, const QVariant &value)
+{
+ m_properties.insert(name, value);
+}
+
+SimpleAbstractStreamReader::SimpleAbstractStreamReader()
+{
+}
+
+bool SimpleAbstractStreamReader::readFile(const QString &fileName)
+{
+ QFile file(fileName);
+ if (file.open(QIODevice::ReadOnly)) {
+ QByteArray source = file.readAll();
+ file.close();
+ return readFromSource(QString::fromLocal8Bit(source));
+ }
+ addError(tr("Cannot find file %1").arg(fileName));
+ return false;
+}
+
+bool SimpleAbstractStreamReader::readFromSource(const QString &source)
+{
+ m_errors.clear();
+ m_currentSourceLocation = AST::SourceLocation();
+
+ Engine engine;
+ Lexer lexer(&engine);
+ Parser parser(&engine);
+
+ lexer.setCode(source, /*line = */ 1, /*qmlMode = */true);
+
+ if (!parser.parse()) {
+ QString errorMessage = QString::fromLatin1("%1:%2: %3").arg(
+ QString::number(parser.errorLineNumber()),
+ QString::number(parser.errorColumnNumber()),
+ parser.errorMessage());
+ addError(errorMessage);
+ return false;
+ }
+ return readDocument(parser.ast());
+}
+
+QStringList SimpleAbstractStreamReader::errors() const
+{
+ return m_errors;
+}
+
+void SimpleAbstractStreamReader::addError(const QString &error, const AST::SourceLocation &sourceLocation)
+{
+ m_errors << QString::fromLatin1("%1:%2: %3\n").arg(
+ QString::number(sourceLocation.startLine),
+ QString::number(sourceLocation.startColumn),
+ error);
+}
+
+AST::SourceLocation SimpleAbstractStreamReader::currentSourceLocation() const
+{
+ return m_currentSourceLocation;
+}
+
+bool SimpleAbstractStreamReader::readDocument(AST::UiProgram *ast)
+{
+ if (!ast) {
+ addError(tr("Could not parse document"));
+ return false;
+ }
+
+ AST::UiObjectDefinition *uiObjectDefinition = AST::cast<AST::UiObjectDefinition *>(ast->members->member);
+ if (!uiObjectDefinition) {
+ addError(tr("Expected document to contain a single object definition"));
+ return false;
+ }
+ readChild(uiObjectDefinition);
+
+ return errors().isEmpty();
+}
+
+void SimpleAbstractStreamReader::readChildren(AST::UiObjectDefinition *uiObjectDefinition)
+{
+ Q_ASSERT(uiObjectDefinition);
+
+ for (AST::UiObjectMemberList *it = uiObjectDefinition->initializer->members; it; it = it->next) {
+ AST::UiObjectMember *member = it->member;
+ AST::UiObjectDefinition *uiObjectDefinition = AST::cast<AST::UiObjectDefinition *>(member);
+ if (uiObjectDefinition)
+ readChild(uiObjectDefinition);
+ }
+}
+
+void SimpleAbstractStreamReader::readChild(AST::UiObjectDefinition *uiObjectDefinition)
+{
+ Q_ASSERT(uiObjectDefinition);
+
+ setSourceLocation(uiObjectDefinition->firstSourceLocation());
+
+ elementStart(toString(uiObjectDefinition->qualifiedTypeNameId));
+
+ readProperties(uiObjectDefinition);
+ readChildren(uiObjectDefinition);
+
+ elementEnd();
+}
+
+void SimpleAbstractStreamReader::readProperties(AST::UiObjectDefinition *uiObjectDefinition)
+{
+ Q_ASSERT(uiObjectDefinition);
+
+ for (AST::UiObjectMemberList *it = uiObjectDefinition->initializer->members; it; it = it->next) {
+ AST::UiObjectMember *member = it->member;
+ AST::UiScriptBinding *scriptBinding = AST::cast<AST::UiScriptBinding *>(member);
+ if (scriptBinding)
+ readProperty(scriptBinding);
+ }
+}
+
+void SimpleAbstractStreamReader::readProperty(AST::UiScriptBinding *uiScriptBinding)
+{
+ Q_ASSERT(uiScriptBinding);
+
+ setSourceLocation(uiScriptBinding->firstSourceLocation());
+
+ const QString name = toString(uiScriptBinding->qualifiedId);
+ const QVariant value = parsePropertyScriptBinding(uiScriptBinding);
+
+ propertyDefinition(name, value);
+}
+
+QVariant SimpleAbstractStreamReader::parsePropertyScriptBinding(AST::UiScriptBinding *uiScriptBinding)
+{
+ Q_ASSERT(uiScriptBinding);
+
+ AST::ExpressionStatement *expStmt = AST::cast<AST::ExpressionStatement *>(uiScriptBinding->statement);
+ if (!expStmt) {
+ addError(tr("Expected expression statement after colon"), uiScriptBinding->statement->firstSourceLocation());
+ return QVariant();
+ }
+
+ return parsePropertyExpression(expStmt->expression);
+}
+
+QVariant SimpleAbstractStreamReader::parsePropertyExpression(AST::ExpressionNode *expressionNode)
+{
+ Q_ASSERT(expressionNode);
+
+ AST::ArrayLiteral *arrayLiteral = AST::cast<AST::ArrayLiteral *>(expressionNode);
+
+ if (arrayLiteral) {
+ QList<QVariant> variantList;
+ for (AST::ElementList *it = arrayLiteral->elements; it; it = it->next)
+ variantList << parsePropertyExpression(it->expression);
+ return variantList;
+ }
+
+ AST::StringLiteral *stringLiteral = AST::cast<AST::StringLiteral *>(expressionNode);
+ if (stringLiteral)
+ return stringLiteral->value.toString();
+
+ AST::TrueLiteral *trueLiteral = AST::cast<AST::TrueLiteral *>(expressionNode);
+ if (trueLiteral)
+ return true;
+
+ AST::FalseLiteral *falseLiteral = AST::cast<AST::FalseLiteral *>(expressionNode);
+ if (falseLiteral)
+ return false;
+
+ AST::NumericLiteral *numericLiteral = AST::cast<AST::NumericLiteral *>(expressionNode);
+ if (numericLiteral)
+ return numericLiteral->value;
+
+ addError(tr("Expected expression statement to be a literal"), expressionNode->firstSourceLocation());
+ return QVariant();
+}
+
+void SimpleAbstractStreamReader::setSourceLocation(const AST::SourceLocation &sourceLocation)
+{
+ m_currentSourceLocation = sourceLocation;
+}
+
+SimpleReader::SimpleReader()
+{
+}
+
+SimpleReaderNode::Ptr SimpleReader::readFile(const QString &fileName)
+{
+ SimpleAbstractStreamReader::readFile(fileName);
+ return m_rootNode;
+}
+
+SimpleReaderNode::Ptr SimpleReader::readFromSource(const QString &source)
+{
+ SimpleAbstractStreamReader::readFromSource(source);
+ return m_rootNode;
+}
+
+void SimpleReader::elementStart(const QString &name)
+{
+ if (debug)
+ qDebug() << "SimpleReader::elementStart()" << name;
+
+ SimpleReaderNode::Ptr newNode = SimpleReaderNode::create(name, m_currentNode);
+
+ if (newNode->isRoot())
+ m_rootNode = newNode;
+
+ Q_ASSERT(newNode->isValid());
+
+ m_currentNode = newNode;
+}
+
+void SimpleReader::elementEnd()
+{
+ Q_ASSERT(m_currentNode);
+
+ if (debug)
+ qDebug() << "SimpleReader::elementEnd()" << m_currentNode.data()->name();
+
+ m_currentNode = m_currentNode.data()->parent();
+}
+
+void SimpleReader::propertyDefinition(const QString &name, const QVariant &value)
+{
+ Q_ASSERT(m_currentNode);
+
+ if (debug)
+ qDebug() << "SimpleReader::propertyDefinition()" << m_currentNode.data()->name() << name << value;
+
+ if (m_currentNode.data()->propertyNames().contains(name))
+ addError(tr("Property is defined twice"), currentSourceLocation());
+
+ m_currentNode.data()->setProperty(name, value);
+}
diff --git a/src/libs/qmljs/qmljssimplereader.h b/src/libs/qmljs/qmljssimplereader.h
new file mode 100644
index 0000000000..351b590326
--- /dev/null
+++ b/src/libs/qmljs/qmljssimplereader.h
@@ -0,0 +1,134 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLJS_SIMPLEREADER_H
+#define QMLJS_SIMPLEREADER_H
+
+#include <qmljs/qmljs_global.h>
+#include <qmljs/parser/qmljsastfwd_p.h>
+
+#include <QHash>
+#include <QList>
+#include <QStringList>
+#include <QSharedPointer>
+#include <QWeakPointer>
+
+// for Q_DECLARE_TR_FUNCTIONS
+#include <QCoreApplication>
+
+namespace QmlJS {
+
+class QMLJS_EXPORT SimpleReaderNode
+{
+public:
+ typedef QSharedPointer<SimpleReaderNode> Ptr;
+ typedef QWeakPointer<SimpleReaderNode> WeakPtr;
+ typedef QHash<QString, QVariant> PropertyHash;
+ typedef QList<Ptr> List;
+
+ QVariant property(const QString &name) const;
+ QStringList propertyNames() const;
+ PropertyHash properties() const;
+ bool isRoot() const;
+ bool isValid() const;
+ static Ptr invalidNode();
+ WeakPtr parent() const;
+ QString name() const;
+ const List children() const;
+
+protected:
+ SimpleReaderNode();
+ SimpleReaderNode(const QString &name, WeakPtr parent);
+ static Ptr create(const QString &name, WeakPtr parent);
+ void setProperty(const QString &name, const QVariant &value);
+
+private:
+ const QString m_name;
+ PropertyHash m_properties;
+ const WeakPtr m_parentNode;
+ List m_children;
+ WeakPtr m_weakThis;
+
+ friend class SimpleReader;
+};
+
+class QMLJS_EXPORT SimpleAbstractStreamReader
+{
+ Q_DECLARE_TR_FUNCTIONS(QmlJS::SimpleAbstractStreamReader)
+
+public:
+ SimpleAbstractStreamReader();
+ bool readFile(const QString &fileName);
+ bool readFromSource(const QString &source);
+ QStringList errors() const;
+
+protected:
+ void addError(const QString &error, const AST::SourceLocation &sourceLocation = AST::SourceLocation());
+ AST::SourceLocation currentSourceLocation() const;
+
+ virtual void elementStart(const QString &name) = 0;
+ virtual void elementEnd() = 0;
+ virtual void propertyDefinition(const QString &name, const QVariant &value) = 0;
+
+private:
+ bool readDocument(AST::UiProgram *ast);
+ void readChildren(AST::UiObjectDefinition *ast);
+ void readChild(AST::UiObjectDefinition *uiObjectDefinition);
+ void readProperties(AST::UiObjectDefinition *ast);
+ void readProperty(AST::UiScriptBinding *uiScriptBinding);
+ QVariant parsePropertyScriptBinding(AST::UiScriptBinding *ExpressionNode);
+ QVariant parsePropertyExpression(AST::ExpressionNode *expressionNode);
+ void setSourceLocation(const AST::SourceLocation &sourceLocation);
+
+ QStringList m_errors;
+ AST::SourceLocation m_currentSourceLocation;
+};
+
+class QMLJS_EXPORT SimpleReader: public SimpleAbstractStreamReader
+{
+ Q_DECLARE_TR_FUNCTIONS(QmlJS::SimpleReader)
+
+public:
+ SimpleReader();
+ SimpleReaderNode::Ptr readFile(const QString &fileName);
+ SimpleReaderNode::Ptr readFromSource(const QString &source);
+
+protected:
+ virtual void elementStart(const QString &name);
+ virtual void elementEnd();
+ virtual void propertyDefinition(const QString &name, const QVariant &value);
+
+private:
+ SimpleReaderNode::Ptr m_rootNode;
+ SimpleReaderNode::WeakPtr m_currentNode;
+};
+
+} // namespace QmlJS
+
+#endif // QMLJS_SIMPLEREADER_H
diff --git a/src/libs/qmljs/qmljsstaticanalysismessage.cpp b/src/libs/qmljs/qmljsstaticanalysismessage.cpp
index cf4f3dc2d8..7a4831040b 100644
--- a/src/libs/qmljs/qmljsstaticanalysismessage.cpp
+++ b/src/libs/qmljs/qmljsstaticanalysismessage.cpp
@@ -40,7 +40,7 @@ namespace {
class StaticAnalysisMessages
{
- Q_DECLARE_TR_FUNCTIONS(StaticAnalysisMessages)
+ Q_DECLARE_TR_FUNCTIONS(QmlJS::StaticAnalysisMessages)
public:
class PrototypeMessageData {
@@ -214,6 +214,17 @@ StaticAnalysisMessages::StaticAnalysisMessages()
tr("maximum string value length is %1"), 1);
newMsg(ErrInvalidArrayValueLength, Error,
tr("%1 elements expected in array value"), 1);
+ newMsg(WarnImperativeCodeNotEditableInVisualDesigner, Warning,
+ tr("Imperative code is not supported in the Qt Quick Designer"));
+ newMsg(WarnUnsupportedTypeInVisualDesigner, Warning,
+ tr("This type is not supported in the Qt Quick Designer"));
+ newMsg(WarnReferenceToParentItemNotSupportedByVisualDesigner, Warning,
+ tr("Reference to parent item cannot be resolved correctly by the Qt Quick Designer"));
+ newMsg(WarnUndefinedValueForVisualDesigner, Warning,
+ tr("This visual property binding cannot be evaluated in the local context "
+ "and might not show up in Qt Quick Designer as expected"));
+ newMsg(WarnStatesOnlyInRootItemForVisualDesigner, Warning,
+ tr("Qt Quick Designer only supports states in the root item "));
}
} // anonymous namespace
@@ -253,7 +264,7 @@ Message::Message(Type type,
message = message.arg(arg1, arg2);
}
if (appendTypeId)
- message.append(QString(" (M%1)").arg(QString::number(prototype.type)));
+ message.append(QString::fromLatin1(" (M%1)").arg(QString::number(prototype.type)));
}
bool Message::isValid() const
@@ -281,7 +292,7 @@ DiagnosticMessage Message::toDiagnosticMessage() const
QString Message::suppressionString() const
{
- return QString("@disable-check M%1").arg(QString::number(type));
+ return QString::fromLatin1("@disable-check M%1").arg(QString::number(type));
}
QRegExp Message::suppressionPattern()
diff --git a/src/libs/qmljs/qmljsstaticanalysismessage.h b/src/libs/qmljs/qmljsstaticanalysismessage.h
index a7f7720c2a..eb21552d51 100644
--- a/src/libs/qmljs/qmljsstaticanalysismessage.h
+++ b/src/libs/qmljs/qmljsstaticanalysismessage.h
@@ -100,6 +100,11 @@ enum Type
WarnConfusingExpressionStatement = 127,
HintDeclarationsShouldBeAtStartOfFunction = 201,
HintOneStatementPerLine = 202,
+ WarnImperativeCodeNotEditableInVisualDesigner = 203,
+ WarnUnsupportedTypeInVisualDesigner = 204,
+ WarnReferenceToParentItemNotSupportedByVisualDesigner = 205,
+ WarnUndefinedValueForVisualDesigner = 206,
+ WarnStatesOnlyInRootItemForVisualDesigner = 207,
ErrUnknownComponent = 300,
ErrCouldNotResolvePrototypeOf = 301,
ErrCouldNotResolvePrototype = 302,
diff --git a/src/libs/qmljs/qmljstypedescriptionreader.cpp b/src/libs/qmljs/qmljstypedescriptionreader.cpp
index 943104c977..bda3ba09ca 100644
--- a/src/libs/qmljs/qmljstypedescriptionreader.cpp
+++ b/src/libs/qmljs/qmljstypedescriptionreader.cpp
@@ -68,7 +68,7 @@ bool TypeDescriptionReader::operator()(
lexer.setCode(_source, /*line = */ 1, /*qmlMode = */true);
if (!parser.parse()) {
- _errorMessage = QString("%1:%2: %3").arg(
+ _errorMessage = QString::fromLatin1("%1:%2: %3").arg(
QString::number(parser.errorLineNumber()),
QString::number(parser.errorColumnNumber()),
parser.errorMessage());
@@ -95,18 +95,18 @@ QString TypeDescriptionReader::warningMessage() const
void TypeDescriptionReader::readDocument(UiProgram *ast)
{
if (!ast) {
- addError(SourceLocation(), "Could not parse document");
+ addError(SourceLocation(), tr("Could not parse document"));
return;
}
if (!ast->imports || ast->imports->next) {
- addError(SourceLocation(), "Expected a single import");
+ addError(SourceLocation(), tr("Expected a single import"));
return;
}
UiImport *import = ast->imports->import;
if (toString(import->importUri) != QLatin1String("QtQuick.tooling")) {
- addError(import->importToken, "Expected import of QtQuick.tooling");
+ addError(import->importToken, tr("Expected import of QtQuick.tooling"));
return;
}
@@ -118,23 +118,23 @@ void TypeDescriptionReader::readDocument(UiProgram *ast)
versionString.mid(dotIdx + 1).toInt());
}
if (version > ComponentVersion(1, 1)) {
- addError(import->versionToken, "Expected version 1.1 or lower");
+ addError(import->versionToken, tr("Expected version 1.1 or lower"));
return;
}
if (!ast->members || !ast->members->member || ast->members->next) {
- addError(SourceLocation(), "Expected document to contain a single object definition");
+ addError(SourceLocation(), tr("Expected document to contain a single object definition"));
return;
}
UiObjectDefinition *module = dynamic_cast<UiObjectDefinition *>(ast->members->member);
if (!module) {
- addError(SourceLocation(), "Expected document to contain a single object definition");
+ addError(SourceLocation(), tr("Expected document to contain a single object definition"));
return;
}
- if (toString(module->qualifiedTypeNameId) != "Module") {
- addError(SourceLocation(), "Expected document to contain a Module {} member");
+ if (toString(module->qualifiedTypeNameId) != QLatin1String("Module")) {
+ addError(SourceLocation(), tr("Expected document to contain a Module {} member"));
return;
}
@@ -151,22 +151,22 @@ void TypeDescriptionReader::readModule(UiObjectDefinition *ast)
if (component)
typeName = toString(component->qualifiedTypeNameId);
- if (!component || (typeName != "Component" && typeName != "ModuleApi")) {
- addWarning(member->firstSourceLocation(), "Expected only 'Component' and 'ModuleApi' object definitions");
+ if (!component || (typeName != QLatin1String("Component") && typeName != QLatin1String("ModuleApi"))) {
+ addWarning(member->firstSourceLocation(),
+ tr("Expected only 'Component' and 'ModuleApi' object definitions"));
continue;
}
- if (typeName == QLatin1String("Component")) {
+ if (typeName == QLatin1String("Component"))
readComponent(component);
- } else if (typeName == QLatin1String("ModuleApi")) {
+ else if (typeName == QLatin1String("ModuleApi"))
readModuleApi(component);
- }
}
}
void TypeDescriptionReader::addError(const SourceLocation &loc, const QString &message)
{
- _errorMessage += QString("%1:%2: %3\n").arg(
+ _errorMessage += QString::fromLatin1("%1:%2: %3\n").arg(
QString::number(loc.startLine),
QString::number(loc.startColumn),
message);
@@ -174,7 +174,7 @@ void TypeDescriptionReader::addError(const SourceLocation &loc, const QString &m
void TypeDescriptionReader::addWarning(const SourceLocation &loc, const QString &message)
{
- _warningMessage += QString("%1:%2: %3\n").arg(
+ _warningMessage += QString::fromLatin1("%1:%2: %3\n").arg(
QString::number(loc.startLine),
QString::number(loc.startColumn),
message);
@@ -190,41 +190,40 @@ void TypeDescriptionReader::readComponent(UiObjectDefinition *ast)
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) {
QString name = toString(component->qualifiedTypeNameId);
- if (name == "Property") {
+ if (name == QLatin1String("Property"))
readProperty(component, fmo);
- } else if (name == "Method" || name == "Signal") {
- readSignalOrMethod(component, name == "Method", fmo);
- } else if (name == "Enum") {
+ else if (name == QLatin1String("Method") || name == QLatin1String("Signal"))
+ readSignalOrMethod(component, name == QLatin1String("Method"), fmo);
+ else if (name == QLatin1String("Enum"))
readEnum(component, fmo);
- } else {
- addWarning(component->firstSourceLocation(), "Expected only Property, Method, Signal and Enum object definitions");
- }
+ else
+ addWarning(component->firstSourceLocation(), tr("Expected only Property, Method, Signal and Enum object definitions"));
} else if (script) {
QString name = toString(script->qualifiedId);
- if (name == "name") {
+ if (name == QLatin1String("name")) {
fmo->setClassName(readStringBinding(script));
- } else if (name == "prototype") {
+ } else if (name == QLatin1String("prototype")) {
fmo->setSuperclassName(readStringBinding(script));
- } else if (name == "defaultProperty") {
+ } else if (name == QLatin1String("defaultProperty")) {
fmo->setDefaultPropertyName(readStringBinding(script));
- } else if (name == "exports") {
+ } else if (name == QLatin1String("exports")) {
readExports(script, fmo);
- } else if (name == "exportMetaObjectRevisions") {
+ } else if (name == QLatin1String("exportMetaObjectRevisions")) {
readMetaObjectRevisions(script, fmo);
- } else if (name == "attachedType") {
+ } else if (name == QLatin1String("attachedType")) {
fmo->setAttachedTypeName(readStringBinding(script));
} else {
addWarning(script->firstSourceLocation(),
- "Expected only name, prototype, defaultProperty, attachedType, exports "
- "and exportMetaObjectRevisions script bindings");
+ tr("Expected only name, prototype, defaultProperty, attachedType, exports "
+ "and exportMetaObjectRevisions script bindings"));
}
} else {
- addWarning(member->firstSourceLocation(), "Expected only script bindings and object definitions");
+ addWarning(member->firstSourceLocation(), tr("Expected only script bindings and object definitions"));
}
}
if (fmo->className().isEmpty()) {
- addError(ast->firstSourceLocation(), "Component definition is missing a name binding");
+ addError(ast->firstSourceLocation(), tr("Component definition is missing a name binding"));
return;
}
@@ -243,23 +242,23 @@ void TypeDescriptionReader::readModuleApi(UiObjectDefinition *ast)
if (script) {
const QString name = toString(script->qualifiedId);
- if (name == "uri") {
+ if (name == QLatin1String("uri")) {
apiInfo.uri = readStringBinding(script);
- } else if (name == "version") {
+ } else if (name == QLatin1String("version")) {
apiInfo.version = readNumericVersionBinding(script);
- } else if (name == "name") {
+ } else if (name == QLatin1String("name")) {
apiInfo.cppName = readStringBinding(script);
} else {
addWarning(script->firstSourceLocation(),
- "Expected only uri, version and name script bindings");
+ tr("Expected only uri, version and name script bindings"));
}
} else {
- addWarning(member->firstSourceLocation(), "Expected only script bindings");
+ addWarning(member->firstSourceLocation(), tr("Expected only script bindings"));
}
}
if (!apiInfo.version.isValid()) {
- addError(ast->firstSourceLocation(), "ModuleApi definition has no or invalid 'version' binding");
+ addError(ast->firstSourceLocation(), tr("ModuleApi definition has no or invalid 'version' binding"));
return;
}
@@ -282,30 +281,28 @@ void TypeDescriptionReader::readSignalOrMethod(UiObjectDefinition *ast, bool isM
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (component) {
QString name = toString(component->qualifiedTypeNameId);
- if (name == "Parameter") {
+ if (name == QLatin1String("Parameter"))
readParameter(component, &fmm);
- } else {
- addWarning(component->firstSourceLocation(), "Expected only Parameter object definitions");
- }
+ else
+ addWarning(component->firstSourceLocation(), tr("Expected only Parameter object definitions"));
} else if (script) {
QString name = toString(script->qualifiedId);
- if (name == "name") {
+ if (name == QLatin1String("name"))
fmm.setMethodName(readStringBinding(script));
- } else if (name == "type") {
+ else if (name == QLatin1String("type"))
fmm.setReturnType(readStringBinding(script));
- } else if (name == "revision") {
+ else if (name == QLatin1String("revision"))
fmm.setRevision(readIntBinding(script));
- } else {
- addWarning(script->firstSourceLocation(), "Expected only name and type script bindings");
- }
+ else
+ addWarning(script->firstSourceLocation(), tr("Expected only name and type script bindings"));
} else {
- addWarning(member->firstSourceLocation(), "Expected only script bindings and object definitions");
+ addWarning(member->firstSourceLocation(), tr("Expected only script bindings and object definitions"));
}
}
if (fmm.methodName().isEmpty()) {
- addError(ast->firstSourceLocation(), "Method or Signal is missing a name script binding");
+ addError(ast->firstSourceLocation(), tr("Method or Signal is missing a name script binding"));
return;
}
@@ -325,30 +322,29 @@ void TypeDescriptionReader::readProperty(UiObjectDefinition *ast, FakeMetaObject
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
- addWarning(member->firstSourceLocation(), "Expected script binding");
+ addWarning(member->firstSourceLocation(), tr("Expected script binding"));
continue;
}
QString id = toString(script->qualifiedId);
- if (id == "name") {
+ if (id == QLatin1String("name"))
name = readStringBinding(script);
- } else if (id == "type") {
+ else if (id == QLatin1String("type"))
type = readStringBinding(script);
- } else if (id == "isPointer") {
+ else if (id == QLatin1String("isPointer"))
isPointer = readBoolBinding(script);
- } else if (id == "isReadonly") {
+ else if (id == QLatin1String("isReadonly"))
isReadonly = readBoolBinding(script);
- } else if (id == "isList") {
+ else if (id == QLatin1String("isList"))
isList = readBoolBinding(script);
- } else if (id == "revision") {
+ else if (id == QLatin1String("revision"))
revision = readIntBinding(script);
- } else {
- addWarning(script->firstSourceLocation(), "Expected only type, name, revision, isPointer, isReadonly and isList script bindings");
- }
+ else
+ addWarning(script->firstSourceLocation(), tr("Expected only type, name, revision, isPointer, isReadonly and isList script bindings"));
}
if (name.isEmpty() || type.isEmpty()) {
- addError(ast->firstSourceLocation(), "Property object is missing a name or type script binding");
+ addError(ast->firstSourceLocation(), tr("Property object is missing a name or type script binding"));
return;
}
@@ -363,18 +359,17 @@ void TypeDescriptionReader::readEnum(UiObjectDefinition *ast, FakeMetaObject::Pt
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
- addWarning(member->firstSourceLocation(), "Expected script binding");
+ addWarning(member->firstSourceLocation(), tr("Expected script binding"));
continue;
}
QString name = toString(script->qualifiedId);
- if (name == "name") {
+ if (name == QLatin1String("name"))
fme.setName(readStringBinding(script));
- } else if (name == "values") {
+ else if (name == QLatin1String("values"))
readEnumValues(script, &fme);
- } else {
- addWarning(script->firstSourceLocation(), "Expected only name and values script bindings");
- }
+ else
+ addWarning(script->firstSourceLocation(), tr("Expected only name and values script bindings"));
}
fmo->addEnum(fme);
@@ -389,23 +384,23 @@ void TypeDescriptionReader::readParameter(UiObjectDefinition *ast, FakeMetaMetho
UiObjectMember *member = it->member;
UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member);
if (!script) {
- addWarning(member->firstSourceLocation(), "Expected script binding");
+ addWarning(member->firstSourceLocation(), tr("Expected script binding"));
continue;
}
const QString id = toString(script->qualifiedId);
- if (id == "name") {
+ if (id == QLatin1String("name")) {
name = readStringBinding(script);
- } else if (id == "type") {
+ } else if (id == QLatin1String("type")) {
type = readStringBinding(script);
- } else if (id == "isPointer") {
+ } else if (id == QLatin1String("isPointer")) {
// ### unhandled
- } else if (id == "isReadonly") {
+ } else if (id == QLatin1String("isReadonly")) {
// ### unhandled
- } else if (id == "isList") {
+ } else if (id == QLatin1String("isList")) {
// ### unhandled
} else {
- addWarning(script->firstSourceLocation(), "Expected only name and type script bindings");
+ addWarning(script->firstSourceLocation(), tr("Expected only name and type script bindings"));
}
}
@@ -415,19 +410,19 @@ void TypeDescriptionReader::readParameter(UiObjectDefinition *ast, FakeMetaMetho
QString TypeDescriptionReader::readStringBinding(UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected string after colon");
+ addError(ast->colonToken, tr("Expected string after colon"));
return QString();
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected string after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected string after colon"));
return QString();
}
StringLiteral *stringLit = dynamic_cast<StringLiteral *>(expStmt->expression);
if (!stringLit) {
- addError(expStmt->firstSourceLocation(), "Expected string after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected string after colon"));
return QString();
}
@@ -437,20 +432,20 @@ QString TypeDescriptionReader::readStringBinding(UiScriptBinding *ast)
bool TypeDescriptionReader::readBoolBinding(AST::UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected boolean after colon");
+ addError(ast->colonToken, tr("Expected boolean after colon"));
return false;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected boolean after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected boolean after colon"));
return false;
}
TrueLiteral *trueLit = dynamic_cast<TrueLiteral *>(expStmt->expression);
FalseLiteral *falseLit = dynamic_cast<FalseLiteral *>(expStmt->expression);
if (!trueLit && !falseLit) {
- addError(expStmt->firstSourceLocation(), "Expected true or false after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected true or false after colon"));
return false;
}
@@ -460,19 +455,19 @@ bool TypeDescriptionReader::readBoolBinding(AST::UiScriptBinding *ast)
double TypeDescriptionReader::readNumericBinding(AST::UiScriptBinding *ast)
{
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected numeric literal after colon");
+ addError(ast->colonToken, tr("Expected numeric literal after colon"));
return 0;
}
ExpressionStatement *expStmt = AST::cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected numeric literal after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected numeric literal after colon"));
return 0;
}
NumericLiteral *numericLit = AST::cast<NumericLiteral *>(expStmt->expression);
if (!numericLit) {
- addError(expStmt->firstSourceLocation(), "Expected numeric literal after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected numeric literal after colon"));
return 0;
}
@@ -484,19 +479,19 @@ ComponentVersion TypeDescriptionReader::readNumericVersionBinding(UiScriptBindin
ComponentVersion invalidVersion;
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected numeric literal after colon");
+ addError(ast->colonToken, tr("Expected numeric literal after colon"));
return invalidVersion;
}
ExpressionStatement *expStmt = AST::cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected numeric literal after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected numeric literal after colon"));
return invalidVersion;
}
NumericLiteral *numericLit = AST::cast<NumericLiteral *>(expStmt->expression);
if (!numericLit) {
- addError(expStmt->firstSourceLocation(), "Expected numeric literal after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected numeric literal after colon"));
return invalidVersion;
}
@@ -509,7 +504,7 @@ int TypeDescriptionReader::readIntBinding(AST::UiScriptBinding *ast)
int i = static_cast<int>(v);
if (i != v) {
- addError(ast->firstSourceLocation(), "Expected integer after colon");
+ addError(ast->firstSourceLocation(), tr("Expected integer after colon"));
return 0;
}
@@ -519,26 +514,26 @@ int TypeDescriptionReader::readIntBinding(AST::UiScriptBinding *ast)
void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Ptr fmo)
{
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected array of strings after colon");
+ addError(ast->colonToken, tr("Expected array of strings after colon"));
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected array of strings after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected array of strings after colon"));
return;
}
ArrayLiteral *arrayLit = dynamic_cast<ArrayLiteral *>(expStmt->expression);
if (!arrayLit) {
- addError(expStmt->firstSourceLocation(), "Expected array of strings after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected array of strings after colon"));
return;
}
for (ElementList *it = arrayLit->elements; it; it = it->next) {
StringLiteral *stringLit = dynamic_cast<StringLiteral *>(it->expression);
if (!stringLit) {
- addError(arrayLit->firstSourceLocation(), "Expected array literal with only string literal members");
+ addError(arrayLit->firstSourceLocation(), tr("Expected array literal with only string literal members"));
return;
}
QString exp = stringLit->value.toString();
@@ -547,7 +542,7 @@ void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Pt
ComponentVersion version(exp.mid(spaceIdx + 1));
if (spaceIdx == -1 || !version.isValid()) {
- addError(stringLit->firstSourceLocation(), "Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'");
+ addError(stringLit->firstSourceLocation(), tr("Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'"));
continue;
}
QString package;
@@ -563,19 +558,19 @@ void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Pt
void TypeDescriptionReader::readMetaObjectRevisions(UiScriptBinding *ast, FakeMetaObject::Ptr fmo)
{
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected array of numbers after colon");
+ addError(ast->colonToken, tr("Expected array of numbers after colon"));
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected array of numbers after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected array of numbers after colon"));
return;
}
ArrayLiteral *arrayLit = dynamic_cast<ArrayLiteral *>(expStmt->expression);
if (!arrayLit) {
- addError(expStmt->firstSourceLocation(), "Expected array of numbers after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected array of numbers after colon"));
return;
}
@@ -584,19 +579,19 @@ void TypeDescriptionReader::readMetaObjectRevisions(UiScriptBinding *ast, FakeMe
for (ElementList *it = arrayLit->elements; it; it = it->next, ++exportIndex) {
NumericLiteral *numberLit = cast<NumericLiteral *>(it->expression);
if (!numberLit) {
- addError(arrayLit->firstSourceLocation(), "Expected array literal with only number literal members");
+ addError(arrayLit->firstSourceLocation(), tr("Expected array literal with only number literal members"));
return;
}
if (exportIndex >= exportCount) {
- addError(numberLit->firstSourceLocation(), "Meta object revision without matching export");
+ addError(numberLit->firstSourceLocation(), tr("Meta object revision without matching export"));
return;
}
const double v = numberLit->value;
const int metaObjectRevision = static_cast<int>(v);
if (metaObjectRevision != v) {
- addError(numberLit->firstSourceLocation(), "Expected integer");
+ addError(numberLit->firstSourceLocation(), tr("Expected integer"));
return;
}
@@ -607,19 +602,19 @@ void TypeDescriptionReader::readMetaObjectRevisions(UiScriptBinding *ast, FakeMe
void TypeDescriptionReader::readEnumValues(AST::UiScriptBinding *ast, LanguageUtils::FakeMetaEnum *fme)
{
if (!ast || !ast->statement) {
- addError(ast->colonToken, "Expected object literal after colon");
+ addError(ast->colonToken, tr("Expected object literal after colon"));
return;
}
ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement);
if (!expStmt) {
- addError(ast->statement->firstSourceLocation(), "Expected object literal after colon");
+ addError(ast->statement->firstSourceLocation(), tr("Expected object literal after colon"));
return;
}
ObjectLiteral *objectLit = dynamic_cast<ObjectLiteral *>(expStmt->expression);
if (!objectLit) {
- addError(expStmt->firstSourceLocation(), "Expected object literal after colon");
+ addError(expStmt->firstSourceLocation(), tr("Expected object literal after colon"));
return;
}
@@ -630,7 +625,7 @@ void TypeDescriptionReader::readEnumValues(AST::UiScriptBinding *ast, LanguageUt
if (minus)
value = dynamic_cast<NumericLiteral *>(minus->expression);
if (!propName || !value) {
- addError(objectLit->firstSourceLocation(), "Expected object literal to contain only 'string: number' elements");
+ addError(objectLit->firstSourceLocation(), tr("Expected object literal to contain only 'string: number' elements"));
continue;
}
diff --git a/src/libs/qmljs/qmljsvalueowner.cpp b/src/libs/qmljs/qmljsvalueowner.cpp
index 534da85062..2c47a71f45 100644
--- a/src/libs/qmljs/qmljsvalueowner.cpp
+++ b/src/libs/qmljs/qmljsvalueowner.cpp
@@ -125,377 +125,377 @@ SharedValueOwner::SharedValueOwner()
// set up the Global object
_globalObject = newObject();
- _globalObject->setClassName("Global");
+ _globalObject->setClassName(QLatin1String("Global"));
ObjectValue *objectInstance = newObject();
- objectInstance->setClassName("Object");
- objectInstance->setMember("length", numberValue());
+ objectInstance->setClassName(QLatin1String("Object"));
+ objectInstance->setMember(QLatin1String("length"), numberValue());
_objectCtor = new Function(this);
- _objectCtor->setMember("prototype", _objectPrototype);
+ _objectCtor->setMember(QLatin1String("prototype"), _objectPrototype);
_objectCtor->setReturnValue(objectInstance);
- _objectCtor->addArgument(unknownValue(), "value");
+ _objectCtor->addArgument(unknownValue(), QLatin1String("value"));
_objectCtor->setOptionalNamedArgumentCount(1);
FunctionValue *functionInstance = new FunctionValue(this);
_functionCtor = new Function(this);
- _functionCtor->setMember("prototype", _functionPrototype);
+ _functionCtor->setMember(QLatin1String("prototype"), _functionPrototype);
_functionCtor->setReturnValue(functionInstance);
_functionCtor->setVariadic(true);
ObjectValue *arrayInstance = newObject(_arrayPrototype);
- arrayInstance->setClassName("Array");
- arrayInstance->setMember("length", numberValue());
+ arrayInstance->setClassName(QLatin1String("Array"));
+ arrayInstance->setMember(QLatin1String("length"), numberValue());
_arrayCtor = new Function(this);
- _arrayCtor->setMember("prototype", _arrayPrototype);
+ _arrayCtor->setMember(QLatin1String("prototype"), _arrayPrototype);
_arrayCtor->setReturnValue(arrayInstance);
_arrayCtor->setVariadic(true);
ObjectValue *stringInstance = newObject(_stringPrototype);
- stringInstance->setClassName("String");
- stringInstance->setMember("length", numberValue());
+ stringInstance->setClassName(QLatin1String("String"));
+ stringInstance->setMember(QLatin1String("length"), numberValue());
_stringCtor = new Function(this);
- _stringCtor->setMember("prototype", _stringPrototype);
+ _stringCtor->setMember(QLatin1String("prototype"), _stringPrototype);
_stringCtor->setReturnValue(stringInstance);
- _stringCtor->addArgument(unknownValue(), "value");
+ _stringCtor->addArgument(unknownValue(), QLatin1String("value"));
_stringCtor->setOptionalNamedArgumentCount(1);
ObjectValue *booleanInstance = newObject(_booleanPrototype);
- booleanInstance->setClassName("Boolean");
+ booleanInstance->setClassName(QLatin1String("Boolean"));
_booleanCtor = new Function(this);
- _booleanCtor->setMember("prototype", _booleanPrototype);
+ _booleanCtor->setMember(QLatin1String("prototype"), _booleanPrototype);
_booleanCtor->setReturnValue(booleanInstance);
- _booleanCtor->addArgument(unknownValue(), "value");
+ _booleanCtor->addArgument(unknownValue(), QLatin1String("value"));
ObjectValue *numberInstance = newObject(_numberPrototype);
- numberInstance->setClassName("Number");
+ numberInstance->setClassName(QLatin1String("Number"));
_numberCtor = new Function(this);
- _numberCtor->setMember("prototype", _numberPrototype);
+ _numberCtor->setMember(QLatin1String("prototype"), _numberPrototype);
_numberCtor->setReturnValue(numberInstance);
- _numberCtor->addArgument(unknownValue(), "value");
+ _numberCtor->addArgument(unknownValue(), QLatin1String("value"));
_numberCtor->setOptionalNamedArgumentCount(1);
ObjectValue *dateInstance = newObject(_datePrototype);
- dateInstance->setClassName("Date");
+ dateInstance->setClassName(QLatin1String("Date"));
_dateCtor = new Function(this);
- _dateCtor->setMember("prototype", _datePrototype);
+ _dateCtor->setMember(QLatin1String("prototype"), _datePrototype);
_dateCtor->setReturnValue(dateInstance);
_dateCtor->setVariadic(true);
ObjectValue *regexpInstance = newObject(_regexpPrototype);
- regexpInstance->setClassName("RegExp");
- regexpInstance->setMember("source", stringValue());
- regexpInstance->setMember("global", booleanValue());
- regexpInstance->setMember("ignoreCase", booleanValue());
- regexpInstance->setMember("multiline", booleanValue());
- regexpInstance->setMember("lastIndex", numberValue());
+ regexpInstance->setClassName(QLatin1String("RegExp"));
+ regexpInstance->setMember(QLatin1String("source"), stringValue());
+ regexpInstance->setMember(QLatin1String("global"), booleanValue());
+ regexpInstance->setMember(QLatin1String("ignoreCase"), booleanValue());
+ regexpInstance->setMember(QLatin1String("multiline"), booleanValue());
+ regexpInstance->setMember(QLatin1String("lastIndex"), numberValue());
_regexpCtor = new Function(this);
- _regexpCtor->setMember("prototype", _regexpPrototype);
+ _regexpCtor->setMember(QLatin1String("prototype"), _regexpPrototype);
_regexpCtor->setReturnValue(regexpInstance);
- _regexpCtor->addArgument(unknownValue(), "pattern");
- _regexpCtor->addArgument(unknownValue(), "flags");
-
- addFunction(_objectCtor, "getPrototypeOf", 1);
- addFunction(_objectCtor, "getOwnPropertyDescriptor", 2);
- addFunction(_objectCtor, "getOwnPropertyNames", arrayInstance, 1);
- addFunction(_objectCtor, "create", 1, 1);
- addFunction(_objectCtor, "defineProperty", 3);
- addFunction(_objectCtor, "defineProperties", 2);
- addFunction(_objectCtor, "seal", 1);
- addFunction(_objectCtor, "freeze", 1);
- addFunction(_objectCtor, "preventExtensions", 1);
- addFunction(_objectCtor, "isSealed", booleanValue(), 1);
- addFunction(_objectCtor, "isFrozen", booleanValue(), 1);
- addFunction(_objectCtor, "isExtensible", booleanValue(), 1);
- addFunction(_objectCtor, "keys", arrayInstance, 1);
-
- addFunction(_objectPrototype, "toString", stringValue(), 0);
- addFunction(_objectPrototype, "toLocaleString", stringValue(), 0);
- addFunction(_objectPrototype, "valueOf", 0); // ### FIXME it should return thisObject
- addFunction(_objectPrototype, "hasOwnProperty", booleanValue(), 1);
- addFunction(_objectPrototype, "isPrototypeOf", booleanValue(), 1);
- addFunction(_objectPrototype, "propertyIsEnumerable", booleanValue(), 1);
+ _regexpCtor->addArgument(unknownValue(), QLatin1String("pattern"));
+ _regexpCtor->addArgument(unknownValue(), QLatin1String("flags"));
+
+ addFunction(_objectCtor, QLatin1String("getPrototypeOf"), 1);
+ addFunction(_objectCtor, QLatin1String("getOwnPropertyDescriptor"), 2);
+ addFunction(_objectCtor, QLatin1String("getOwnPropertyNames"), arrayInstance, 1);
+ addFunction(_objectCtor, QLatin1String("create"), 1, 1);
+ addFunction(_objectCtor, QLatin1String("defineProperty"), 3);
+ addFunction(_objectCtor, QLatin1String("defineProperties"), 2);
+ addFunction(_objectCtor, QLatin1String("seal"), 1);
+ addFunction(_objectCtor, QLatin1String("freeze"), 1);
+ addFunction(_objectCtor, QLatin1String("preventExtensions"), 1);
+ addFunction(_objectCtor, QLatin1String("isSealed"), booleanValue(), 1);
+ addFunction(_objectCtor, QLatin1String("isFrozen"), booleanValue(), 1);
+ addFunction(_objectCtor, QLatin1String("isExtensible"), booleanValue(), 1);
+ addFunction(_objectCtor, QLatin1String("keys"), arrayInstance, 1);
+
+ addFunction(_objectPrototype, QLatin1String("toString"), stringValue(), 0);
+ addFunction(_objectPrototype, QLatin1String("toLocaleString"), stringValue(), 0);
+ addFunction(_objectPrototype, QLatin1String("valueOf"), 0); // ### FIXME it should return thisObject
+ addFunction(_objectPrototype, QLatin1String("hasOwnProperty"), booleanValue(), 1);
+ addFunction(_objectPrototype, QLatin1String("isPrototypeOf"), booleanValue(), 1);
+ addFunction(_objectPrototype, QLatin1String("propertyIsEnumerable"), booleanValue(), 1);
// set up the default Function prototype
- _functionPrototype->setMember("constructor", _functionCtor);
- addFunction(_functionPrototype, "toString", stringValue(), 0);
- addFunction(_functionPrototype, "apply", 2);
- addFunction(_functionPrototype, "call", 1, 0, true);
- addFunction(_functionPrototype, "bind", 1, 0, true);
+ _functionPrototype->setMember(QLatin1String("constructor"), _functionCtor);
+ addFunction(_functionPrototype, QLatin1String("toString"), stringValue(), 0);
+ addFunction(_functionPrototype, QLatin1String("apply"), 2);
+ addFunction(_functionPrototype, QLatin1String("call"), 1, 0, true);
+ addFunction(_functionPrototype, QLatin1String("bind"), 1, 0, true);
// set up the default Array prototype
- addFunction(_arrayCtor, "isArray", booleanValue(), 1);
-
- _arrayPrototype->setMember("constructor", _arrayCtor);
- addFunction(_arrayPrototype, "toString", stringValue(), 0);
- addFunction(_arrayPrototype, "toLocalString", stringValue(), 0);
- addFunction(_arrayPrototype, "concat", 0, 0, true);
- addFunction(_arrayPrototype, "join", 1);
- addFunction(_arrayPrototype, "pop", 0);
- addFunction(_arrayPrototype, "push", 0, 0, true);
- addFunction(_arrayPrototype, "reverse", 0);
- addFunction(_arrayPrototype, "shift", 0);
- addFunction(_arrayPrototype, "slice", 2);
- addFunction(_arrayPrototype, "sort", 1);
- addFunction(_arrayPrototype, "splice", 2);
- addFunction(_arrayPrototype, "unshift", 0, 0, true);
- addFunction(_arrayPrototype, "indexOf", numberValue(), 2, 1);
- addFunction(_arrayPrototype, "lastIndexOf", numberValue(), 2, 1);
- addFunction(_arrayPrototype, "every", 2, 1);
- addFunction(_arrayPrototype, "some", 2, 1);
- addFunction(_arrayPrototype, "forEach", 2, 1);
- addFunction(_arrayPrototype, "map", 2, 1);
- addFunction(_arrayPrototype, "filter", 2, 1);
- addFunction(_arrayPrototype, "reduce", 2, 1);
- addFunction(_arrayPrototype, "reduceRight", 2, 1);
+ addFunction(_arrayCtor, QLatin1String("isArray"), booleanValue(), 1);
+
+ _arrayPrototype->setMember(QLatin1String("constructor"), _arrayCtor);
+ addFunction(_arrayPrototype, QLatin1String("toString"), stringValue(), 0);
+ addFunction(_arrayPrototype, QLatin1String("toLocalString"), stringValue(), 0);
+ addFunction(_arrayPrototype, QLatin1String("concat"), 0, 0, true);
+ addFunction(_arrayPrototype, QLatin1String("join"), 1);
+ addFunction(_arrayPrototype, QLatin1String("pop"), 0);
+ addFunction(_arrayPrototype, QLatin1String("push"), 0, 0, true);
+ addFunction(_arrayPrototype, QLatin1String("reverse"), 0);
+ addFunction(_arrayPrototype, QLatin1String("shift"), 0);
+ addFunction(_arrayPrototype, QLatin1String("slice"), 2);
+ addFunction(_arrayPrototype, QLatin1String("sort"), 1);
+ addFunction(_arrayPrototype, QLatin1String("splice"), 2);
+ addFunction(_arrayPrototype, QLatin1String("unshift"), 0, 0, true);
+ addFunction(_arrayPrototype, QLatin1String("indexOf"), numberValue(), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("lastIndexOf"), numberValue(), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("every"), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("some"), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("forEach"), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("map"), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("filter"), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("reduce"), 2, 1);
+ addFunction(_arrayPrototype, QLatin1String("reduceRight"), 2, 1);
// set up the default String prototype
- addFunction(_stringCtor, "fromCharCode", stringValue(), 0, 0, true);
-
- _stringPrototype->setMember("constructor", _stringCtor);
- addFunction(_stringPrototype, "toString", stringValue(), 0);
- addFunction(_stringPrototype, "valueOf", stringValue(), 0);
- addFunction(_stringPrototype, "charAt", stringValue(), 1);
- addFunction(_stringPrototype, "charCodeAt", stringValue(), 1);
- addFunction(_stringPrototype, "concat", stringValue(), 0, 0, true);
- addFunction(_stringPrototype, "indexOf", numberValue(), 2);
- addFunction(_stringPrototype, "lastIndexOf", numberValue(), 2);
- addFunction(_stringPrototype, "localeCompare", booleanValue(), 1);
- addFunction(_stringPrototype, "match", arrayInstance, 1);
- addFunction(_stringPrototype, "replace", stringValue(), 2);
- addFunction(_stringPrototype, "search", numberValue(), 1);
- addFunction(_stringPrototype, "slice", stringValue(), 2);
- addFunction(_stringPrototype, "split", arrayInstance, 1);
- addFunction(_stringPrototype, "substring", stringValue(), 2);
- addFunction(_stringPrototype, "toLowerCase", stringValue(), 0);
- addFunction(_stringPrototype, "toLocaleLowerCase", stringValue(), 0);
- addFunction(_stringPrototype, "toUpperCase", stringValue(), 0);
- addFunction(_stringPrototype, "toLocaleUpperCase", stringValue(), 0);
- addFunction(_stringPrototype, "trim", stringValue(), 0);
+ addFunction(_stringCtor, QLatin1String("fromCharCode"), stringValue(), 0, 0, true);
+
+ _stringPrototype->setMember(QLatin1String("constructor"), _stringCtor);
+ addFunction(_stringPrototype, QLatin1String("toString"), stringValue(), 0);
+ addFunction(_stringPrototype, QLatin1String("valueOf"), stringValue(), 0);
+ addFunction(_stringPrototype, QLatin1String("charAt"), stringValue(), 1);
+ addFunction(_stringPrototype, QLatin1String("charCodeAt"), stringValue(), 1);
+ addFunction(_stringPrototype, QLatin1String("concat"), stringValue(), 0, 0, true);
+ addFunction(_stringPrototype, QLatin1String("indexOf"), numberValue(), 2);
+ addFunction(_stringPrototype, QLatin1String("lastIndexOf"), numberValue(), 2);
+ addFunction(_stringPrototype, QLatin1String("localeCompare"), booleanValue(), 1);
+ addFunction(_stringPrototype, QLatin1String("match"), arrayInstance, 1);
+ addFunction(_stringPrototype, QLatin1String("replace"), stringValue(), 2);
+ addFunction(_stringPrototype, QLatin1String("search"), numberValue(), 1);
+ addFunction(_stringPrototype, QLatin1String("slice"), stringValue(), 2);
+ addFunction(_stringPrototype, QLatin1String("split"), arrayInstance, 1);
+ addFunction(_stringPrototype, QLatin1String("substring"), stringValue(), 2);
+ addFunction(_stringPrototype, QLatin1String("toLowerCase"), stringValue(), 0);
+ addFunction(_stringPrototype, QLatin1String("toLocaleLowerCase"), stringValue(), 0);
+ addFunction(_stringPrototype, QLatin1String("toUpperCase"), stringValue(), 0);
+ addFunction(_stringPrototype, QLatin1String("toLocaleUpperCase"), stringValue(), 0);
+ addFunction(_stringPrototype, QLatin1String("trim"), stringValue(), 0);
// set up the default Boolean prototype
- addFunction(_booleanCtor, "fromCharCode", 0);
+ addFunction(_booleanCtor, QLatin1String("fromCharCode"), 0);
- _booleanPrototype->setMember("constructor", _booleanCtor);
- addFunction(_booleanPrototype, "toString", stringValue(), 0);
- addFunction(_booleanPrototype, "valueOf", booleanValue(), 0);
+ _booleanPrototype->setMember(QLatin1String("constructor"), _booleanCtor);
+ addFunction(_booleanPrototype, QLatin1String("toString"), stringValue(), 0);
+ addFunction(_booleanPrototype, QLatin1String("valueOf"), booleanValue(), 0);
// set up the default Number prototype
- _numberCtor->setMember("MAX_VALUE", numberValue());
- _numberCtor->setMember("MIN_VALUE", numberValue());
- _numberCtor->setMember("NaN", numberValue());
- _numberCtor->setMember("NEGATIVE_INFINITY", numberValue());
- _numberCtor->setMember("POSITIVE_INFINITY", numberValue());
-
- addFunction(_numberCtor, "fromCharCode", 0);
-
- _numberPrototype->setMember("constructor", _numberCtor);
- addFunction(_numberPrototype, "toString", stringValue(), 1, 1);
- addFunction(_numberPrototype, "toLocaleString", stringValue(), 0);
- addFunction(_numberPrototype, "valueOf", numberValue(), 0);
- addFunction(_numberPrototype, "toFixed", numberValue(), 1);
- addFunction(_numberPrototype, "toExponential", numberValue(), 1);
- addFunction(_numberPrototype, "toPrecision", numberValue(), 1);
+ _numberCtor->setMember(QLatin1String("MAX_VALUE"), numberValue());
+ _numberCtor->setMember(QLatin1String("MIN_VALUE"), numberValue());
+ _numberCtor->setMember(QLatin1String("NaN"), numberValue());
+ _numberCtor->setMember(QLatin1String("NEGATIVE_INFINITY"), numberValue());
+ _numberCtor->setMember(QLatin1String("POSITIVE_INFINITY"), numberValue());
+
+ addFunction(_numberCtor, QLatin1String("fromCharCode"), 0);
+
+ _numberPrototype->setMember(QLatin1String("constructor"), _numberCtor);
+ addFunction(_numberPrototype, QLatin1String("toString"), stringValue(), 1, 1);
+ addFunction(_numberPrototype, QLatin1String("toLocaleString"), stringValue(), 0);
+ addFunction(_numberPrototype, QLatin1String("valueOf"), numberValue(), 0);
+ addFunction(_numberPrototype, QLatin1String("toFixed"), numberValue(), 1);
+ addFunction(_numberPrototype, QLatin1String("toExponential"), numberValue(), 1);
+ addFunction(_numberPrototype, QLatin1String("toPrecision"), numberValue(), 1);
// set up the Math object
_mathObject = newObject();
- _mathObject->setMember("E", numberValue());
- _mathObject->setMember("LN10", numberValue());
- _mathObject->setMember("LN2", numberValue());
- _mathObject->setMember("LOG2E", numberValue());
- _mathObject->setMember("LOG10E", numberValue());
- _mathObject->setMember("PI", numberValue());
- _mathObject->setMember("SQRT1_2", numberValue());
- _mathObject->setMember("SQRT2", numberValue());
-
- addFunction(_mathObject, "abs", numberValue(), 1);
- addFunction(_mathObject, "acos", numberValue(), 1);
- addFunction(_mathObject, "asin", numberValue(), 1);
- addFunction(_mathObject, "atan", numberValue(), 1);
- addFunction(_mathObject, "atan2", numberValue(), 2);
- addFunction(_mathObject, "ceil", numberValue(), 1);
- addFunction(_mathObject, "cos", numberValue(), 1);
- addFunction(_mathObject, "exp", numberValue(), 1);
- addFunction(_mathObject, "floor", numberValue(), 1);
- addFunction(_mathObject, "log", numberValue(), 1);
- addFunction(_mathObject, "max", numberValue(), 0, 0, true);
- addFunction(_mathObject, "min", numberValue(), 0, 0, true);
- addFunction(_mathObject, "pow", numberValue(), 2);
- addFunction(_mathObject, "random", numberValue(), 1);
- addFunction(_mathObject, "round", numberValue(), 1);
- addFunction(_mathObject, "sin", numberValue(), 1);
- addFunction(_mathObject, "sqrt", numberValue(), 1);
- addFunction(_mathObject, "tan", numberValue(), 1);
+ _mathObject->setMember(QLatin1String("E"), numberValue());
+ _mathObject->setMember(QLatin1String("LN10"), numberValue());
+ _mathObject->setMember(QLatin1String("LN2"), numberValue());
+ _mathObject->setMember(QLatin1String("LOG2E"), numberValue());
+ _mathObject->setMember(QLatin1String("LOG10E"), numberValue());
+ _mathObject->setMember(QLatin1String("PI"), numberValue());
+ _mathObject->setMember(QLatin1String("SQRT1_2"), numberValue());
+ _mathObject->setMember(QLatin1String("SQRT2"), numberValue());
+
+ addFunction(_mathObject, QLatin1String("abs"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("acos"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("asin"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("atan"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("atan2"), numberValue(), 2);
+ addFunction(_mathObject, QLatin1String("ceil"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("cos"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("exp"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("floor"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("log"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("max"), numberValue(), 0, 0, true);
+ addFunction(_mathObject, QLatin1String("min"), numberValue(), 0, 0, true);
+ addFunction(_mathObject, QLatin1String("pow"), numberValue(), 2);
+ addFunction(_mathObject, QLatin1String("random"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("round"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("sin"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("sqrt"), numberValue(), 1);
+ addFunction(_mathObject, QLatin1String("tan"), numberValue(), 1);
// set up the default Boolean prototype
- addFunction(_dateCtor, "parse", numberValue(), 1);
- addFunction(_dateCtor, "UTC", numberValue(), 7, 5);
- addFunction(_dateCtor, "now", numberValue(), 0);
-
- _datePrototype->setMember("constructor", _dateCtor);
- addFunction(_datePrototype, "toString", stringValue(), 0);
- addFunction(_datePrototype, "toDateString", stringValue(), 0);
- addFunction(_datePrototype, "toTimeString", stringValue(), 0);
- addFunction(_datePrototype, "toLocaleString", stringValue(), 0);
- addFunction(_datePrototype, "toLocaleDateString", stringValue(), 0);
- addFunction(_datePrototype, "toLocaleTimeString", stringValue(), 0);
- addFunction(_datePrototype, "valueOf", numberValue(), 0);
- addFunction(_datePrototype, "getTime", numberValue(), 0);
- addFunction(_datePrototype, "getFullYear", numberValue(), 0);
- addFunction(_datePrototype, "getUTCFullYear", numberValue(), 0);
- addFunction(_datePrototype, "getMonth", numberValue(), 0);
- addFunction(_datePrototype, "getUTCMonth", numberValue(), 0);
- addFunction(_datePrototype, "getDate", numberValue(), 0);
- addFunction(_datePrototype, "getUTCDate", numberValue(), 0);
- addFunction(_datePrototype, "getHours", numberValue(), 0);
- addFunction(_datePrototype, "getUTCHours", numberValue(), 0);
- addFunction(_datePrototype, "getMinutes", numberValue(), 0);
- addFunction(_datePrototype, "getUTCMinutes", numberValue(), 0);
- addFunction(_datePrototype, "getSeconds", numberValue(), 0);
- addFunction(_datePrototype, "getUTCSeconds", numberValue(), 0);
- addFunction(_datePrototype, "getMilliseconds", numberValue(), 0);
- addFunction(_datePrototype, "getUTCMilliseconds", numberValue(), 0);
- addFunction(_datePrototype, "getTimezoneOffset", numberValue(), 0);
- addFunction(_datePrototype, "setTime", 1);
- addFunction(_datePrototype, "setMilliseconds", 1);
- addFunction(_datePrototype, "setUTCMilliseconds", 1);
- addFunction(_datePrototype, "setSeconds", 2, 1);
- addFunction(_datePrototype, "setUTCSeconds", 2, 1);
- addFunction(_datePrototype, "setMinutes", 3, 2);
- addFunction(_datePrototype, "setUTCMinutes", 3, 2);
- addFunction(_datePrototype, "setHours", 4, 3);
- addFunction(_datePrototype, "setUTCHours", 4, 3);
- addFunction(_datePrototype, "setDate", 1);
- addFunction(_datePrototype, "setUTCDate", 1);
- addFunction(_datePrototype, "setMonth", 2, 1);
- addFunction(_datePrototype, "setUTCMonth", 2, 1);
- addFunction(_datePrototype, "setFullYear", 3, 2);
- addFunction(_datePrototype, "setUTCFullYear", 3, 2);
- addFunction(_datePrototype, "toUTCString", stringValue(), 0);
- addFunction(_datePrototype, "toISOString", stringValue(), 0);
- addFunction(_datePrototype, "toJSON", stringValue(), 1);
+ addFunction(_dateCtor, QLatin1String("parse"), numberValue(), 1);
+ addFunction(_dateCtor, QLatin1String("UTC"), numberValue(), 7, 5);
+ addFunction(_dateCtor, QLatin1String("now"), numberValue(), 0);
+
+ _datePrototype->setMember(QLatin1String("constructor"), _dateCtor);
+ addFunction(_datePrototype, QLatin1String("toString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toDateString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toTimeString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toLocaleString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toLocaleDateString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toLocaleTimeString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("valueOf"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getTime"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getFullYear"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCFullYear"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getMonth"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCMonth"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getDate"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCDate"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getHours"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCHours"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getMinutes"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCMinutes"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getSeconds"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCSeconds"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getMilliseconds"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getUTCMilliseconds"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("getTimezoneOffset"), numberValue(), 0);
+ addFunction(_datePrototype, QLatin1String("setTime"), 1);
+ addFunction(_datePrototype, QLatin1String("setMilliseconds"), 1);
+ addFunction(_datePrototype, QLatin1String("setUTCMilliseconds"), 1);
+ addFunction(_datePrototype, QLatin1String("setSeconds"), 2, 1);
+ addFunction(_datePrototype, QLatin1String("setUTCSeconds"), 2, 1);
+ addFunction(_datePrototype, QLatin1String("setMinutes"), 3, 2);
+ addFunction(_datePrototype, QLatin1String("setUTCMinutes"), 3, 2);
+ addFunction(_datePrototype, QLatin1String("setHours"), 4, 3);
+ addFunction(_datePrototype, QLatin1String("setUTCHours"), 4, 3);
+ addFunction(_datePrototype, QLatin1String("setDate"), 1);
+ addFunction(_datePrototype, QLatin1String("setUTCDate"), 1);
+ addFunction(_datePrototype, QLatin1String("setMonth"), 2, 1);
+ addFunction(_datePrototype, QLatin1String("setUTCMonth"), 2, 1);
+ addFunction(_datePrototype, QLatin1String("setFullYear"), 3, 2);
+ addFunction(_datePrototype, QLatin1String("setUTCFullYear"), 3, 2);
+ addFunction(_datePrototype, QLatin1String("toUTCString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toISOString"), stringValue(), 0);
+ addFunction(_datePrototype, QLatin1String("toJSON"), stringValue(), 1);
// set up the default Boolean prototype
- _regexpPrototype->setMember("constructor", _regexpCtor);
- addFunction(_regexpPrototype, "exec", arrayInstance, 1);
- addFunction(_regexpPrototype, "test", booleanValue(), 1);
- addFunction(_regexpPrototype, "toString", stringValue(), 0);
+ _regexpPrototype->setMember(QLatin1String("constructor"), _regexpCtor);
+ addFunction(_regexpPrototype, QLatin1String("exec"), arrayInstance, 1);
+ addFunction(_regexpPrototype, QLatin1String("test"), booleanValue(), 1);
+ addFunction(_regexpPrototype, QLatin1String("toString"), stringValue(), 0);
// fill the Global object
- _globalObject->setMember("Math", _mathObject);
- _globalObject->setMember("Object", objectCtor());
- _globalObject->setMember("Function", functionCtor());
- _globalObject->setMember("Array", arrayCtor());
- _globalObject->setMember("String", stringCtor());
- _globalObject->setMember("Boolean", booleanCtor());
- _globalObject->setMember("Number", numberCtor());
- _globalObject->setMember("Date", dateCtor());
- _globalObject->setMember("RegExp", regexpCtor());
+ _globalObject->setMember(QLatin1String("Math"), _mathObject);
+ _globalObject->setMember(QLatin1String("Object"), objectCtor());
+ _globalObject->setMember(QLatin1String("Function"), functionCtor());
+ _globalObject->setMember(QLatin1String("Array"), arrayCtor());
+ _globalObject->setMember(QLatin1String("String"), stringCtor());
+ _globalObject->setMember(QLatin1String("Boolean"), booleanCtor());
+ _globalObject->setMember(QLatin1String("Number"), numberCtor());
+ _globalObject->setMember(QLatin1String("Date"), dateCtor());
+ _globalObject->setMember(QLatin1String("RegExp"), regexpCtor());
Function *f = 0;
// XMLHttpRequest
ObjectValue *xmlHttpRequest = newObject();
- xmlHttpRequest->setMember("onreadystatechange", functionPrototype());
- xmlHttpRequest->setMember("UNSENT", numberValue());
- xmlHttpRequest->setMember("OPENED", numberValue());
- xmlHttpRequest->setMember("HEADERS_RECEIVED", numberValue());
- xmlHttpRequest->setMember("LOADING", numberValue());
- xmlHttpRequest->setMember("DONE", numberValue());
- xmlHttpRequest->setMember("readyState", numberValue());
- f = addFunction(xmlHttpRequest, "open");
- f->addArgument(stringValue(), "method");
- f->addArgument(stringValue(), "url");
- f->addArgument(booleanValue(), "async");
- f->addArgument(stringValue(), "user");
- f->addArgument(stringValue(), "password");
- f = addFunction(xmlHttpRequest, "setRequestHeader");
- f->addArgument(stringValue(), "header");
- f->addArgument(stringValue(), "value");
- f = addFunction(xmlHttpRequest, "send");
- f->addArgument(unknownValue(), "data");
- f = addFunction(xmlHttpRequest, "abort");
- xmlHttpRequest->setMember("status", numberValue());
- xmlHttpRequest->setMember("statusText", stringValue());
- f = addFunction(xmlHttpRequest, "getResponseHeader");
- f->addArgument(stringValue(), "header");
- f = addFunction(xmlHttpRequest, "getAllResponseHeaders");
- xmlHttpRequest->setMember("responseText", stringValue());
- xmlHttpRequest->setMember("responseXML", unknownValue());
-
- f = addFunction(_globalObject, "XMLHttpRequest", xmlHttpRequest);
- f->setMember("prototype", xmlHttpRequest);
- xmlHttpRequest->setMember("constructor", f);
+ xmlHttpRequest->setMember(QLatin1String("onreadystatechange"), functionPrototype());
+ xmlHttpRequest->setMember(QLatin1String("UNSENT"), numberValue());
+ xmlHttpRequest->setMember(QLatin1String("OPENED"), numberValue());
+ xmlHttpRequest->setMember(QLatin1String("HEADERS_RECEIVED"), numberValue());
+ xmlHttpRequest->setMember(QLatin1String("LOADING"), numberValue());
+ xmlHttpRequest->setMember(QLatin1String("DONE"), numberValue());
+ xmlHttpRequest->setMember(QLatin1String("readyState"), numberValue());
+ f = addFunction(xmlHttpRequest, QLatin1String("open"));
+ f->addArgument(stringValue(), QLatin1String("method"));
+ f->addArgument(stringValue(), QLatin1String("url"));
+ f->addArgument(booleanValue(), QLatin1String("async"));
+ f->addArgument(stringValue(), QLatin1String("user"));
+ f->addArgument(stringValue(), QLatin1String("password"));
+ f = addFunction(xmlHttpRequest, QLatin1String("setRequestHeader"));
+ f->addArgument(stringValue(), QLatin1String("header"));
+ f->addArgument(stringValue(), QLatin1String("value"));
+ f = addFunction(xmlHttpRequest, QLatin1String("send"));
+ f->addArgument(unknownValue(), QLatin1String("data"));
+ f = addFunction(xmlHttpRequest, QLatin1String("abort"));
+ xmlHttpRequest->setMember(QLatin1String("status"), numberValue());
+ xmlHttpRequest->setMember(QLatin1String("statusText"), stringValue());
+ f = addFunction(xmlHttpRequest, QLatin1String("getResponseHeader"));
+ f->addArgument(stringValue(), QLatin1String("header"));
+ f = addFunction(xmlHttpRequest, QLatin1String("getAllResponseHeaders"));
+ xmlHttpRequest->setMember(QLatin1String("responseText"), stringValue());
+ xmlHttpRequest->setMember(QLatin1String("responseXML"), unknownValue());
+
+ f = addFunction(_globalObject, QLatin1String("XMLHttpRequest"), xmlHttpRequest);
+ f->setMember(QLatin1String("prototype"), xmlHttpRequest);
+ xmlHttpRequest->setMember(QLatin1String("constructor"), f);
// Database API
ObjectValue *db = newObject();
- f = addFunction(db, "transaction");
- f->addArgument(functionPrototype(), "callback");
- f = addFunction(db, "readTransaction");
- f->addArgument(functionPrototype(), "callback");
- f->setMember("version", stringValue());
- f = addFunction(db, "changeVersion");
- f->addArgument(stringValue(), "oldVersion");
- f->addArgument(stringValue(), "newVersion");
- f->addArgument(functionPrototype(), "callback");
-
- f = addFunction(_globalObject, "openDatabaseSync", db);
- f->addArgument(stringValue(), "name");
- f->addArgument(stringValue(), "version");
- f->addArgument(stringValue(), "displayName");
- f->addArgument(numberValue(), "estimatedSize");
- f->addArgument(functionPrototype(), "callback");
+ f = addFunction(db, QLatin1String("transaction"));
+ f->addArgument(functionPrototype(), QLatin1String("callback"));
+ f = addFunction(db, QLatin1String("readTransaction"));
+ f->addArgument(functionPrototype(), QLatin1String("callback"));
+ f->setMember(QLatin1String("version"), stringValue());
+ f = addFunction(db, QLatin1String("changeVersion"));
+ f->addArgument(stringValue(), QLatin1String("oldVersion"));
+ f->addArgument(stringValue(), QLatin1String("newVersion"));
+ f->addArgument(functionPrototype(), QLatin1String("callback"));
+
+ f = addFunction(_globalObject, QLatin1String("openDatabaseSync"), db);
+ f->addArgument(stringValue(), QLatin1String("name"));
+ f->addArgument(stringValue(), QLatin1String("version"));
+ f->addArgument(stringValue(), QLatin1String("displayName"));
+ f->addArgument(numberValue(), QLatin1String("estimatedSize"));
+ f->addArgument(functionPrototype(), QLatin1String("callback"));
// JSON
ObjectValue *json = newObject();
- f = addFunction(json, "parse", objectPrototype());
- f->addArgument(stringValue(), "text");
- f->addArgument(functionPrototype(), "reviver");
+ f = addFunction(json, QLatin1String("parse"), objectPrototype());
+ f->addArgument(stringValue(), QLatin1String("text"));
+ f->addArgument(functionPrototype(), QLatin1String("reviver"));
f->setOptionalNamedArgumentCount(1);
- f = addFunction(json, "stringify", stringValue());
- f->addArgument(unknownValue(), "value");
- f->addArgument(unknownValue(), "replacer");
- f->addArgument(unknownValue(), "space");
+ f = addFunction(json, QLatin1String("stringify"), stringValue());
+ f->addArgument(unknownValue(), QLatin1String("value"));
+ f->addArgument(unknownValue(), QLatin1String("replacer"));
+ f->addArgument(unknownValue(), QLatin1String("space"));
f->setOptionalNamedArgumentCount(2);
- _globalObject->setMember("JSON", json);
+ _globalObject->setMember(QLatin1String("JSON"), json);
// QML objects
_qmlFontObject = newObject(/*prototype =*/ 0);
_qmlFontObject->setClassName(QLatin1String("Font"));
- _qmlFontObject->setMember("family", stringValue());
- _qmlFontObject->setMember("weight", unknownValue()); // ### make me an object
- _qmlFontObject->setMember("capitalization", unknownValue()); // ### make me an object
- _qmlFontObject->setMember("bold", booleanValue());
- _qmlFontObject->setMember("italic", booleanValue());
- _qmlFontObject->setMember("underline", booleanValue());
- _qmlFontObject->setMember("overline", booleanValue());
- _qmlFontObject->setMember("strikeout", booleanValue());
- _qmlFontObject->setMember("pointSize", intValue());
- _qmlFontObject->setMember("pixelSize", intValue());
- _qmlFontObject->setMember("letterSpacing", realValue());
- _qmlFontObject->setMember("wordSpacing", realValue());
+ _qmlFontObject->setMember(QLatin1String("family"), stringValue());
+ _qmlFontObject->setMember(QLatin1String("weight"), unknownValue()); // ### make me an object
+ _qmlFontObject->setMember(QLatin1String("capitalization"), unknownValue()); // ### make me an object
+ _qmlFontObject->setMember(QLatin1String("bold"), booleanValue());
+ _qmlFontObject->setMember(QLatin1String("italic"), booleanValue());
+ _qmlFontObject->setMember(QLatin1String("underline"), booleanValue());
+ _qmlFontObject->setMember(QLatin1String("overline"), booleanValue());
+ _qmlFontObject->setMember(QLatin1String("strikeout"), booleanValue());
+ _qmlFontObject->setMember(QLatin1String("pointSize"), intValue());
+ _qmlFontObject->setMember(QLatin1String("pixelSize"), intValue());
+ _qmlFontObject->setMember(QLatin1String("letterSpacing"), realValue());
+ _qmlFontObject->setMember(QLatin1String("wordSpacing"), realValue());
_qmlPointObject = newObject(/*prototype =*/ 0);
_qmlPointObject->setClassName(QLatin1String("Point"));
- _qmlPointObject->setMember("x", numberValue());
- _qmlPointObject->setMember("y", numberValue());
+ _qmlPointObject->setMember(QLatin1String("x"), numberValue());
+ _qmlPointObject->setMember(QLatin1String("y"), numberValue());
_qmlSizeObject = newObject(/*prototype =*/ 0);
_qmlSizeObject->setClassName(QLatin1String("Size"));
- _qmlSizeObject->setMember("width", numberValue());
- _qmlSizeObject->setMember("height", numberValue());
+ _qmlSizeObject->setMember(QLatin1String("width"), numberValue());
+ _qmlSizeObject->setMember(QLatin1String("height"), numberValue());
_qmlRectObject = newObject(/*prototype =*/ 0);
- _qmlRectObject->setClassName("Rect");
- _qmlRectObject->setMember("x", numberValue());
- _qmlRectObject->setMember("y", numberValue());
- _qmlRectObject->setMember("width", numberValue());
- _qmlRectObject->setMember("height", numberValue());
+ _qmlRectObject->setClassName(QLatin1String("Rect"));
+ _qmlRectObject->setMember(QLatin1String("x"), numberValue());
+ _qmlRectObject->setMember(QLatin1String("y"), numberValue());
+ _qmlRectObject->setMember(QLatin1String("width"), numberValue());
+ _qmlRectObject->setMember(QLatin1String("height"), numberValue());
_qmlVector3DObject = newObject(/*prototype =*/ 0);
_qmlVector3DObject->setClassName(QLatin1String("Vector3D"));
- _qmlVector3DObject->setMember("x", realValue());
- _qmlVector3DObject->setMember("y", realValue());
- _qmlVector3DObject->setMember("z", realValue());
+ _qmlVector3DObject->setMember(QLatin1String("x"), realValue());
+ _qmlVector3DObject->setMember(QLatin1String("y"), realValue());
+ _qmlVector3DObject->setMember(QLatin1String("z"), realValue());
// global Qt object, in alphabetic order
_qtObject = newObject(new QtObjectPrototypeReference(this));
diff --git a/src/libs/qtcomponents/styleitem/qdeclarativefolderlistmodel.cpp b/src/libs/qtcomponents/styleitem/qdeclarativefolderlistmodel.cpp
index bd4ff948c3..a09f484b1f 100644
--- a/src/libs/qtcomponents/styleitem/qdeclarativefolderlistmodel.cpp
+++ b/src/libs/qtcomponents/styleitem/qdeclarativefolderlistmodel.cpp
@@ -47,7 +47,7 @@ public:
void updateSorting() {
QDir::SortFlags flags = 0;
- switch(sortField) {
+ switch (sortField) {
case QDeclarativeFolderListModel::Unsorted:
flags |= QDir::Unsorted;
break;
diff --git a/src/libs/qtcomponents/styleitem/qstyleitem.cpp b/src/libs/qtcomponents/styleitem/qstyleitem.cpp
index 876aae44ad..21076342f8 100644
--- a/src/libs/qtcomponents/styleitem/qstyleitem.cpp
+++ b/src/libs/qtcomponents/styleitem/qstyleitem.cpp
@@ -115,7 +115,7 @@ void QStyleItem::initStyleOption()
QStyleOptionButton *opt = qstyleoption_cast<QStyleOptionButton*>(m_styleoption);
opt->text = text();
- opt->features = (activeControl() == "default") ?
+ opt->features = (activeControl() == QLatin1String("default")) ?
QStyleOptionButton::DefaultButton :
QStyleOptionButton::None;
}
@@ -126,22 +126,20 @@ void QStyleItem::initStyleOption()
QStyleOptionViewItemV4 *opt = qstyleoption_cast<QStyleOptionViewItemV4*>(m_styleoption);
opt->features = 0;
- if (activeControl() == "alternate")
+ if (activeControl() == QLatin1String("alternate"))
opt->features |= QStyleOptionViewItemV2::Alternate;
}
break;
case Splitter: {
- if (!m_styleoption) {
+ if (!m_styleoption)
m_styleoption = new QStyleOption;
- }
}
break;
case Item: {
- if (!m_styleoption) {
+ if (!m_styleoption)
m_styleoption = new QStyleOptionViewItemV4();
- }
QStyleOptionViewItemV4 *opt = qstyleoption_cast<QStyleOptionViewItemV4*>(m_styleoption);
opt->features = QStyleOptionViewItemV4::HasDisplay;
opt->text = text();
@@ -157,9 +155,9 @@ void QStyleItem::initStyleOption()
QStyleOptionHeader *opt = qstyleoption_cast<QStyleOptionHeader*>(m_styleoption);
opt->text = text();
- opt->sortIndicator = activeControl() == "down" ?
+ opt->sortIndicator = activeControl() == QLatin1String("down") ?
QStyleOptionHeader::SortDown
- : activeControl() == "up" ?
+ : activeControl() == QLatin1String("up") ?
QStyleOptionHeader::SortUp : QStyleOptionHeader::None;
if (activeControl() == QLatin1String("beginning"))
opt->position = QStyleOptionHeader::Beginning;
@@ -195,7 +193,7 @@ void QStyleItem::initStyleOption()
QStyleOptionTabV3 *opt =
qstyleoption_cast<QStyleOptionTabV3*>(m_styleoption);
opt->text = text();
- opt->shape = info() == "South" ? QTabBar::RoundedSouth : QTabBar::RoundedNorth;
+ opt->shape = info() == QLatin1String("South") ? QTabBar::RoundedSouth : QTabBar::RoundedNorth;
if (activeControl() == QLatin1String("beginning"))
opt->position = QStyleOptionTabV3::Beginning;
else if (activeControl() == QLatin1String("end"))
@@ -226,7 +224,7 @@ void QStyleItem::initStyleOption()
if (!m_styleoption)
m_styleoption = new QStyleOptionTabWidgetFrameV2();
QStyleOptionTabWidgetFrameV2 *opt = qstyleoption_cast<QStyleOptionTabWidgetFrameV2*>(m_styleoption);
- opt->shape = (info() == "South") ? QTabBar::RoundedSouth : QTabBar::RoundedNorth;
+ opt->shape = (info() == QLatin1String("South")) ? QTabBar::RoundedSouth : QTabBar::RoundedNorth;
if (minimum())
opt->selectedTabRect = QRect(value(), 0, minimum(), height());
opt->tabBarSize = QSize(minimum() , height());
@@ -322,8 +320,8 @@ void QStyleItem::initStyleOption()
else
opt->sliderValue = value();
opt->subControls = QStyle::SC_SliderGroove | QStyle::SC_SliderHandle;
- opt->tickPosition = (activeControl() == "below") ?
- QSlider::TicksBelow : (activeControl() == "above" ?
+ opt->tickPosition = (activeControl() == QLatin1String("below")) ?
+ QSlider::TicksBelow : (activeControl() == QLatin1String("above") ?
QSlider::TicksAbove:
QSlider::NoTicks);
if (opt->tickPosition != QSlider::NoTicks)
@@ -361,7 +359,7 @@ void QStyleItem::initStyleOption()
opt->subControls |= QStyle::SC_GroupBoxFrame;
else
opt->features |= QStyleOptionFrameV2::Flat;
- if (activeControl() == "checkbox")
+ if (activeControl() == QLatin1String("checkbox"))
opt->subControls |= QStyle::SC_GroupBoxCheckBox;
if (QGroupBox *group= qobject_cast<QGroupBox*>(widget())) {
@@ -433,9 +431,9 @@ void QStyleItem::initStyleOption()
// Some styles actually check the beginning and end position
// using widget geometry, so we have to trick it
widget()->setGeometry(0, 0, width(), height());
- if (activeControl() != "beginning")
+ if (activeControl() != QLatin1String("beginning"))
m_styleoption->rect.translate(1, 0); // Don't position at start of widget
- if (activeControl() != "end")
+ if (activeControl() != QLatin1String("end"))
widget()->resize(200, height());
}
#ifdef Q_WS_WIN
@@ -446,11 +444,10 @@ void QStyleItem::initStyleOption()
m_styleoption->fontMetrics = widget()->fontMetrics();
if (!m_styleoption->palette.resolve())
m_styleoption->palette = widget()->palette();
- if (m_hint.contains("mac.mini")) {
+ if (m_hint.contains(QLatin1String("mac.mini")))
widget()->setAttribute(Qt::WA_MacMiniSize);
- } else if (m_hint.contains("mac.small")) {
+ else if (m_hint.contains(QLatin1String("mac.small")))
widget()->setAttribute(Qt::WA_MacSmallSize);
- }
}
}
@@ -466,15 +463,15 @@ void QStyleItem::initStyleOption()
QString QStyleItem::style() const
{
- QString style = qApp->style()->metaObject()->className();
+ QByteArray style = qApp->style()->metaObject()->className();
style = style.toLower();
- if (style.contains(QLatin1String("oxygen")))
+ if (style.contains("oxygen"))
return QLatin1String("oxygen");
- if (style.startsWith(QLatin1Char('q')))
- style = style.right(style.length() - 1);
+ if (style.startsWith('q'))
+ style.remove(0, 1);
if (style.endsWith("style"))
- style = style.left(style.length() - 5);
- return style.toLower();
+ style.chop(5);
+ return QLatin1String(style);
}
QString QStyleItem::hitTest(int px, int py)
@@ -487,9 +484,9 @@ QString QStyleItem::hitTest(int px, int py)
qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
QPoint(px,py), 0);
if (subcontrol == QStyle::SC_SpinBoxUp)
- return "up";
+ return QLatin1String("up");
else if (subcontrol == QStyle::SC_SpinBoxDown)
- return "down";
+ return QLatin1String("down");
}
break;
@@ -499,7 +496,7 @@ QString QStyleItem::hitTest(int px, int py)
qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
QPoint(px,py), 0);
if (subcontrol == QStyle::SC_SliderHandle)
- return "handle";
+ return QLatin1String("handle");
}
break;
@@ -508,23 +505,23 @@ QString QStyleItem::hitTest(int px, int py)
qstyleoption_cast<QStyleOptionComplex*>(m_styleoption),
QPoint(px,py), 0);
if (subcontrol == QStyle::SC_ScrollBarSlider)
- return "handle";
+ return QLatin1String("handle");
if (subcontrol == QStyle::SC_ScrollBarSubLine)
- return "up";
+ return QLatin1String("up");
else if (subcontrol == QStyle::SC_ScrollBarSubPage)
- return "upPage";
+ return QLatin1String("upPage");
if (subcontrol == QStyle::SC_ScrollBarAddLine)
- return "down";
+ return QLatin1String("down");
else if (subcontrol == QStyle::SC_ScrollBarAddPage)
- return "downPage";
+ return QLatin1String("downPage");
}
break;
default:
break;
}
- return "none";
+ return QLatin1String("none");
}
QSize QStyleItem::sizeFromContents(int width, int height)
@@ -566,7 +563,7 @@ QSize QStyleItem::sizeFromContents(int width, int height)
case Header:
size = qApp->style()->sizeFromContents(QStyle::CT_HeaderSection, m_styleoption, QSize(width,height), widget());
#ifdef Q_OS_MAC
- if (style() =="mac")
+ if (style() == QLatin1String("mac"))
size.setHeight(15);
#endif
break;
@@ -590,37 +587,37 @@ QSize QStyleItem::sizeFromContents(int width, int height)
int QStyleItem::pixelMetric(const QString &metric)
{
- if (metric == "scrollbarExtent")
+ if (metric == QLatin1String("scrollbarExtent"))
return qApp->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, widget());
- else if (metric == "defaultframewidth")
+ else if (metric == QLatin1String("defaultframewidth"))
return qApp->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, widget());
- else if (metric == "taboverlap")
+ else if (metric == QLatin1String("taboverlap"))
return qApp->style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0 , widget());
- else if (metric == "tabbaseoverlap")
+ else if (metric == QLatin1String("tabbaseoverlap"))
#ifdef Q_WS_WIN
// On windows the tabbar paintmargin extends the overlap by one pixels
return 1 + qApp->style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, 0 , widget());
#else
return qApp->style()->pixelMetric(QStyle::PM_TabBarBaseOverlap, 0 , widget());
#endif
- else if (metric == "tabhspace")
+ else if (metric == QLatin1String("tabhspace"))
return qApp->style()->pixelMetric(QStyle::PM_TabBarTabHSpace, 0 , widget());
- else if (metric == "tabvspace")
+ else if (metric == QLatin1String("tabvspace"))
return qApp->style()->pixelMetric(QStyle::PM_TabBarTabVSpace, 0 , widget());
- else if (metric == "tabbaseheight")
+ else if (metric == QLatin1String("tabbaseheight"))
return qApp->style()->pixelMetric(QStyle::PM_TabBarBaseHeight, 0 , widget());
- else if (metric == "tabvshift")
+ else if (metric == QLatin1String("tabvshift"))
return qApp->style()->pixelMetric(QStyle::PM_TabBarTabShiftVertical, 0 , widget());
- else if (metric == "menuhmargin")
+ else if (metric == QLatin1String("menuhmargin"))
return qApp->style()->pixelMetric(QStyle::PM_MenuHMargin, 0 , widget());
- else if (metric == "menuvmargin")
+ else if (metric == QLatin1String("menuvmargin"))
return qApp->style()->pixelMetric(QStyle::PM_MenuVMargin, 0 , widget());
- else if (metric == "menupanelwidth")
+ else if (metric == QLatin1String("menupanelwidth"))
return qApp->style()->pixelMetric(QStyle::PM_MenuPanelWidth, 0 , widget());
- else if (metric == "splitterwidth")
+ else if (metric == QLatin1String("splitterwidth"))
return qApp->style()->pixelMetric(QStyle::PM_SplitterWidth, 0 , widget());
// This metric is incorrectly negative on oxygen
- else if (metric == "scrollbarspacing")
+ else if (metric == QLatin1String("scrollbarspacing"))
return abs(qApp->style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, 0 , widget()));
return 0;
}
@@ -628,26 +625,26 @@ int QStyleItem::pixelMetric(const QString &metric)
QVariant QStyleItem::styleHint(const QString &metric)
{
initStyleOption();
- if (metric == "comboboxpopup") {
+ if (metric == QLatin1String("comboboxpopup")) {
return qApp->style()->styleHint(QStyle::SH_ComboBox_Popup, m_styleoption);
- } else if (metric == "highlightedTextColor") {
+ } else if (metric == QLatin1String("highlightedTextColor")) {
if (widget())
return widget()->palette().highlightedText().color().name();
return qApp->palette().highlightedText().color().name();
- } else if (metric == "textColor") {
+ } else if (metric == QLatin1String("textColor")) {
if (widget())
return widget()->palette().text().color().name();
return qApp->palette().text().color().name();
- } else if (metric == "focuswidget") {
+ } else if (metric == QLatin1String("focuswidget")) {
return qApp->style()->styleHint(QStyle::SH_FocusFrame_AboveWidget);
- } else if (metric == "tabbaralignment") {
+ } else if (metric == QLatin1String("tabbaralignment")) {
int result = qApp->style()->styleHint(QStyle::SH_TabBar_Alignment);
if (result == Qt::AlignCenter)
- return "center";
- return "left";
- } else if (metric == "framearoundcontents") {
+ return QLatin1String("center");
+ return QLatin1String("left");
+ } else if (metric == QLatin1String("framearoundcontents")) {
return qApp->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents);
- } else if (metric == "scrollToClickPosition")
+ } else if (metric == QLatin1String("scrollToClickPosition"))
return qApp->style()->styleHint(QStyle::SH_ScrollBar_LeftClickAbsolutePosition);
return 0;
}
@@ -656,19 +653,19 @@ void QStyleItem::setCursor(const QString &str)
{
if (m_cursor != str) {
m_cursor = str;
- if (m_cursor == "sizehorcursor")
+ if (m_cursor == QLatin1String("sizehorcursor"))
QDeclarativeItem::setCursor(Qt::SizeHorCursor);
- else if (m_cursor == "sizevercursor")
+ else if (m_cursor == QLatin1String("sizevercursor"))
QDeclarativeItem::setCursor(Qt::SizeVerCursor);
- else if (m_cursor == "sizeallcursor")
+ else if (m_cursor == QLatin1String("sizeallcursor"))
QDeclarativeItem::setCursor(Qt::SizeAllCursor);
- else if (m_cursor == "splithcursor")
+ else if (m_cursor == QLatin1String("splithcursor"))
QDeclarativeItem::setCursor(Qt::SplitHCursor);
- else if (m_cursor == "splitvcursor")
+ else if (m_cursor == QLatin1String("splitvcursor"))
QDeclarativeItem::setCursor(Qt::SplitVCursor);
- else if (m_cursor == "wait")
+ else if (m_cursor == QLatin1String("wait"))
QDeclarativeItem::setCursor(Qt::WaitCursor);
- else if (m_cursor == "pointinghandcursor")
+ else if (m_cursor == QLatin1String("pointinghandcursor"))
QDeclarativeItem::setCursor(Qt::PointingHandCursor);
emit cursorChanged();
}
@@ -695,22 +692,22 @@ void QStyleItem::setElementType(const QString &str)
// Only enable visible if the widget can animate
bool visible = false;
- if (str == "menu" || str == "menuitem") {
+ if (str == QLatin1String("menu") || str == QLatin1String("menuitem")) {
// Since these are used by the delegate, it makes no
// sense to re-create them per item
static QWidget *menu = new QMenu();
m_sharedWidget = true;
m_dummywidget = menu;
- m_itemType = (str == "menu") ? Menu : MenuItem;
- } else if (str == "item" || str == "itemrow" || str == "header") {
+ m_itemType = (str == QLatin1String("menu")) ? Menu : MenuItem;
+ } else if (str == QLatin1String("item") || str == QLatin1String("itemrow") || str == QLatin1String("header")) {
// Since these are used by the delegate, it makes no
// sense to re-create them per item
static QTreeView *menu = new QTreeView();
menu->setAttribute(Qt::WA_MacMiniSize);
m_sharedWidget = true;
- if (str == "header") {
+ if (str == QLatin1String("header")) {
m_dummywidget = menu->header();
- if (style() == "mac") { // The default qt font seems to big
+ if (style() == QLatin1String("mac")) { // The default qt font seems to big
QFont font = m_dummywidget->font();
font.setPointSize(11);
m_dummywidget->setFont(font);
@@ -718,26 +715,26 @@ void QStyleItem::setElementType(const QString &str)
m_itemType = Header;
} else {
m_dummywidget = menu;
- m_itemType = (str == "item") ? Item : ItemRow;
+ m_itemType = (str == QLatin1String("item")) ? Item : ItemRow;
}
- } else if (str == "groupbox") {
+ } else if (str == QLatin1String("groupbox")) {
// Since these are used by the delegate, it makes no
// sense to re-create them per item
static QGroupBox *group = new QGroupBox();
m_sharedWidget = true;
m_dummywidget = group;
m_itemType = GroupBox;
- } else if (str == "tabframe" || str == "tab") {
+ } else if (str == QLatin1String("tabframe") || str == QLatin1String("tab")) {
static QTabWidget *tabframe = new QTabWidget();
m_sharedWidget = true;
- if (str == "tab") {
+ if (str == QLatin1String("tab")) {
m_dummywidget = tabframe->findChild<QTabBar*>();
m_itemType = Tab;
} else {
m_dummywidget = tabframe;
m_itemType = TabFrame;
}
- } else if (str == "comboboxitem") {
+ } else if (str == QLatin1String("comboboxitem")) {
// Gtk uses qobject cast, hence we need to separate this from menuitem
// On mac, we temporarily use the menu item because it has more accurate
// palette.
@@ -749,7 +746,7 @@ void QStyleItem::setElementType(const QString &str)
m_sharedWidget = true;
m_dummywidget = combo;
m_itemType = ComboBoxItem;
- } else if (str == "toolbar") {
+ } else if (str == QLatin1String("toolbar")) {
static QToolBar *tb = 0;
if (!tb) {
QMainWindow *mw = new QMainWindow();
@@ -757,7 +754,7 @@ void QStyleItem::setElementType(const QString &str)
}
m_dummywidget = tb;
m_itemType = ToolBar;
- } else if (str == "toolbutton") {
+ } else if (str == QLatin1String("toolbutton")) {
static QToolButton *tb = 0;
static QToolBar *bar = 0;
// KDE animations are too broken with these widgets
@@ -770,58 +767,58 @@ void QStyleItem::setElementType(const QString &str)
m_sharedWidget = true;
m_dummywidget = tb;
m_itemType = ToolButton;
- } else if (str == "slider") {
+ } else if (str == QLatin1String("slider")) {
static QSlider *slider = new QSlider();
m_sharedWidget = true;
m_dummywidget = slider;
m_itemType = Slider;
- } else if (str == "frame") {
+ } else if (str == QLatin1String("frame")) {
static QFrame *frame = new QFrame();
m_sharedWidget = true;
m_dummywidget = frame;
m_itemType = Frame;
- } else if (str == "combobox") {
+ } else if (str == QLatin1String("combobox")) {
m_dummywidget = new QComboBox();
visible = true;
m_itemType = ComboBox;
- } else if (str == "splitter") {
+ } else if (str == QLatin1String("splitter")) {
visible = true;
m_itemType = Splitter;
- } else if (str == "progressbar") {
+ } else if (str == QLatin1String("progressbar")) {
m_dummywidget = new QProgressBar();
visible = true;
m_itemType = ProgressBar;
- } else if (str == "button") {
+ } else if (str == QLatin1String("button")) {
m_dummywidget = new QPushButton();
visible = true;
m_itemType = Button;
- } else if (str == "checkbox") {
+ } else if (str == QLatin1String("checkbox")) {
m_dummywidget = new QCheckBox();
visible = true;
m_itemType = CheckBox;
- } else if (str == "radiobutton") {
+ } else if (str == QLatin1String("radiobutton")) {
m_dummywidget = new QRadioButton();
visible = true;
m_itemType = RadioButton;
- } else if (str == "edit") {
+ } else if (str == QLatin1String("edit")) {
m_dummywidget = new QLineEdit();
visible = true;
m_itemType = Edit;
- } else if (str == "spinbox") {
+ } else if (str == QLatin1String("spinbox")) {
#ifndef Q_WS_WIN // Vista spinbox is currently not working due to grabwidget
m_dummywidget = new QSpinBox();
visible = true;
#endif
m_itemType = SpinBox;
- } else if (str == "scrollbar") {
+ } else if (str == QLatin1String("scrollbar")) {
m_dummywidget = new QScrollBar();
visible = true;
m_itemType = ScrollBar;
- } else if (str == "widget") {
+ } else if (str == QLatin1String("widget")) {
m_itemType = Widget;
- } else if (str == "focusframe") {
+ } else if (str == QLatin1String("focusframe")) {
m_itemType = FocusFrame;
- } else if (str == "dial") {
+ } else if (str == QLatin1String("dial")) {
m_itemType = Dial;
}
if (m_dummywidget) {
@@ -1018,9 +1015,8 @@ void QStyleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWid
qApp->style()->drawComplexControl(QStyle::CC_ScrollBar, qstyleoption_cast<QStyleOptionComplex*>(m_styleoption), painter, widget());
break;
case Menu: {
- if (QMenu *menu = qobject_cast<QMenu*>(widget())) {
+ if (QMenu *menu = qobject_cast<QMenu*>(widget()))
m_styleoption->palette = menu->palette();
- }
QStyleHintReturnMask val;
qApp->style()->styleHint(QStyle::SH_Menu_Mask, m_styleoption, widget(), &val);
painter->save();
diff --git a/src/libs/qtcomponents/styleitem/qstyleplugin.cpp b/src/libs/qtcomponents/styleitem/qstyleplugin.cpp
index 5d83de06cf..bda3b97949 100644
--- a/src/libs/qtcomponents/styleitem/qstyleplugin.cpp
+++ b/src/libs/qtcomponents/styleitem/qstyleplugin.cpp
@@ -36,7 +36,7 @@
** $QT_END_LICENSE$
**
****************************************************************************/
-
+
#include <qdeclarative.h>
#include "qstyleplugin.h"
#include "qstyleitem.h"
@@ -68,7 +68,7 @@ public:
{
Q_UNUSED(requestedSize);
Q_UNUSED(size);
- int pos = id.lastIndexOf('/');
+ int pos = id.lastIndexOf(QLatin1Char('/'));
QString iconName = id.right(id.length() - pos);
int width = qApp->style()->pixelMetric(QStyle::PM_ToolBarIconSize);
return QIcon::fromTheme(iconName).pixmap(width);
@@ -92,7 +92,7 @@ void StylePlugin::registerTypes(const char *uri)
void StylePlugin::initializeEngine(QDeclarativeEngine *engine, const char *uri)
{
Q_UNUSED(uri);
- engine->addImageProvider("desktoptheme", new DesktopIconProvider);
+ engine->addImageProvider(QLatin1String("desktoptheme"), new DesktopIconProvider);
}
#if QT_VERSION < 0x050000
diff --git a/src/libs/qtcomponents/styleitem/qwheelarea.cpp b/src/libs/qtcomponents/styleitem/qwheelarea.cpp
index a5cf2a76ac..d89d14fe73 100644
--- a/src/libs/qtcomponents/styleitem/qwheelarea.cpp
+++ b/src/libs/qtcomponents/styleitem/qwheelarea.cpp
@@ -56,11 +56,11 @@ QWheelArea::QWheelArea(QDeclarativeItem *parent)
QWheelArea::~QWheelArea() {}
bool QWheelArea::event (QEvent * e) {
- switch(e->type()) {
+ switch (e->type()) {
case QEvent::GraphicsSceneWheel: {
QGraphicsSceneWheelEvent *we = static_cast<QGraphicsSceneWheelEvent*>(e);
- if(we) {
- switch(we->orientation()) {
+ if (we) {
+ switch (we->orientation()) {
case Qt::Horizontal:
setHorizontalDelta(we->delta());
break;
@@ -72,8 +72,8 @@ bool QWheelArea::event (QEvent * e) {
}
case QEvent::Wheel: {
QWheelEvent *we = static_cast<QWheelEvent*>(e);
- if(we) {
- switch(we->orientation()) {
+ if (we) {
+ switch (we->orientation()) {
case Qt::Horizontal:
setHorizontalDelta(we->delta());
diff --git a/src/libs/qtcomponents/styleitem/styleitem.qbs b/src/libs/qtcomponents/styleitem/styleitem.qbs
index b5444dcd3a..3577fe4712 100644
--- a/src/libs/qtcomponents/styleitem/styleitem.qbs
+++ b/src/libs/qtcomponents/styleitem/styleitem.qbs
@@ -1,13 +1,13 @@
import qbs.base 1.0
+import "../../../../qbs/defaults.js" as Defaults
DynamicLibrary {
name: "styleplugin"
- destination: "lib/qtcreator/qtcomponents/plugin"
Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["core", "widgets", "declarative", "script"] }
- cpp.defines: project.additionalCppDefines
+ cpp.defines: Defaults.defines(qbs)
files: [
"qdeclarativefolderlistmodel.cpp",
@@ -26,7 +26,12 @@ DynamicLibrary {
"qtmenuitem.cpp",
"qtmenuitem.h",
"qwheelarea.cpp",
- "qwheelarea.h"
+ "qwheelarea.h",
]
-}
+ Group {
+ fileTagsFilter: product.type
+ qbs.install: true
+ qbs.installDir: "lib/qtcreator/qtcomponents/plugin"
+ }
+}
diff --git a/src/libs/qtcreatorcdbext/containers.cpp b/src/libs/qtcreatorcdbext/containers.cpp
index da62cae11b..1ee05daddb 100644
--- a/src/libs/qtcreatorcdbext/containers.cpp
+++ b/src/libs/qtcreatorcdbext/containers.cpp
@@ -360,11 +360,10 @@ AbstractSymbolGroupNodePtrVector
block -= blockArraySize;
const ULONG64 blockOffset = offset % dequeSize;
const ULONG64 address = blockArray[block] + innerTypeSize * blockOffset;
- if (SymbolGroupNode *n = sg->addSymbol(module, SymbolGroupValue::pointedToSymbolName(address, innerType), std::string(), &errorMessage)) {
+ if (SymbolGroupNode *n = sg->addSymbol(module, SymbolGroupValue::pointedToSymbolName(address, innerType), std::string(), &errorMessage))
rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, n));
- } else {
+ else
return AbstractSymbolGroupNodePtrVector();
- }
}
return rc;
}
@@ -842,11 +841,10 @@ SymbolGroupValueVector qHashNodes(const SymbolGroupValue &v,
nodeList.reserve(count);
const SymbolGroupValueVector::const_iterator dcend = dummyNodeList.end();
for (SymbolGroupValueVector::const_iterator it = dummyNodeList.begin(); it != dcend; ++it) {
- if (const SymbolGroupValue n = (*it).typeCast(nodeType.c_str())) {
+ if (const SymbolGroupValue n = (*it).typeCast(nodeType.c_str()))
nodeList.push_back(n);
- } else {
+ else
return SymbolGroupValueVector();
- }
}
return nodeList;
}
@@ -865,11 +863,10 @@ static inline AbstractSymbolGroupNodePtrVector
return rc;
rc.reserve(count);
for (int i = 0; i < count; i++) {
- if (const SymbolGroupValue key = nodes.at(i)["key"]) {
+ if (const SymbolGroupValue key = nodes.at(i)["key"])
rc.push_back(ReferenceSymbolGroupNode::createArrayNode(i, key.node()));
- } else {
+ else
return AbstractSymbolGroupNodePtrVector();
- }
}
return rc;
}
diff --git a/src/libs/qtcreatorcdbext/extensioncontext.cpp b/src/libs/qtcreatorcdbext/extensioncontext.cpp
index 91ccfa6c36..3aab10b07e 100644
--- a/src/libs/qtcreatorcdbext/extensioncontext.cpp
+++ b/src/libs/qtcreatorcdbext/extensioncontext.cpp
@@ -43,6 +43,16 @@ WINDBG_EXTENSION_APIS ExtensionApis = {sizeof(WINDBG_EXTENSION_APIS), 0, 0, 0,
const char *ExtensionContext::stopReasonKeyC = "reason";
const char *ExtensionContext::breakPointStopReasonC = "breakpoint";
+/*! \class Parameters
+
+ Externally configureable parameters.
+ \ingroup qtcreatorcdbext
+*/
+
+Parameters::Parameters() : maxStringLength(10000), maxStackDepth(1000)
+{
+}
+
/*! \class ExtensionContext
Global singleton with context.
@@ -88,11 +98,10 @@ void ExtensionContext::hookCallbacks(CIDebugClient *client)
void ExtensionContext::startRecordingOutput()
{
- if (m_creatorOutputCallback) {
+ if (m_creatorOutputCallback)
m_creatorOutputCallback->startRecording();
- } else {
+ else
report('X', 0, 0, "Error", "ExtensionContext::startRecordingOutput() called with no output hooked.\n");
- }
}
std::wstring ExtensionContext::stopRecordingOutput()
@@ -189,18 +198,17 @@ void ExtensionContext::notifyIdleCommand(CIDebugClient *client)
formatGdbmiHash(str, stopReasons, false);
const std::string threadInfo = gdbmiThreadList(exc.systemObjects(), exc.symbols(),
exc.control(), exc.advanced(), &errorMessage);
- if (threadInfo.empty()) {
+ if (threadInfo.empty())
str << ",threaderror=" << gdbmiStringFormat(errorMessage);
- } else {
+ else
str << ",threads=" << threadInfo;
- }
const std::string stackInfo = gdbmiStack(exc.control(), exc.symbols(),
- maxStackFrames, false, &errorMessage);
- if (stackInfo.empty()) {
+ ExtensionContext::instance().parameters().maxStackDepth,
+ false, &errorMessage);
+ if (stackInfo.empty())
str << ",stackerror=" << gdbmiStringFormat(errorMessage);
- } else {
+ else
str << ",stack=" << stackInfo;
- }
str << '}';
reportLong('E', 0, "session_idle", str.str());
}
diff --git a/src/libs/qtcreatorcdbext/extensioncontext.h b/src/libs/qtcreatorcdbext/extensioncontext.h
index 5a3e398c83..985f6a2ed0 100644
--- a/src/libs/qtcreatorcdbext/extensioncontext.h
+++ b/src/libs/qtcreatorcdbext/extensioncontext.h
@@ -40,6 +40,16 @@ class LocalsSymbolGroup;
class WatchesSymbolGroup;
class OutputCallback;
+// Global parameters
+class Parameters
+{
+public:
+ Parameters();
+
+ unsigned maxStringLength;
+ unsigned maxStackDepth;
+};
+
// Global singleton with context.
// Caches a symbolgroup per frame and thread as long as the session is accessible.
class ExtensionContext {
@@ -48,8 +58,6 @@ class ExtensionContext {
ExtensionContext();
public:
- enum { maxStackFrames = 200 };
-
// Key used to report stop reason in StopReasonMap
static const char *stopReasonKeyC;
static const char *breakPointStopReasonC; // pre-defined stop reasons
@@ -105,6 +113,9 @@ public:
CIDebugClient *hookedClient() const { return m_hookedClient; }
+ const Parameters &parameters() const { return m_parameters; }
+ Parameters &parameters() { return m_parameters; }
+
private:
bool isInitialized() const;
@@ -120,6 +131,7 @@ private:
StopReasonMap m_stopReason;
bool m_stateNotification;
+ Parameters m_parameters;
};
// Context for extension commands to be instantiated on stack in a command handler.
diff --git a/src/libs/qtcreatorcdbext/gdbmihelpers.cpp b/src/libs/qtcreatorcdbext/gdbmihelpers.cpp
index d077a124df..5501051b22 100644
--- a/src/libs/qtcreatorcdbext/gdbmihelpers.cpp
+++ b/src/libs/qtcreatorcdbext/gdbmihelpers.cpp
@@ -107,11 +107,10 @@ void getFrame(CIDebugSymbols *debugSymbols,
WCHAR wBuf[MAX_PATH];
f->address = s.InstructionOffset;
HRESULT hr = debugSymbols->GetNameByOffsetWide(f->address, wBuf, MAX_PATH, 0, 0);
- if (SUCCEEDED(hr)) {
+ if (SUCCEEDED(hr))
f->function = wBuf;
- } else {
+ else
f->function.clear();
- }
ULONG64 ul64Displacement = 0;
hr = debugSymbols->GetLineByOffsetWide(f->address, &(f->line), wBuf, MAX_PATH, 0, &ul64Displacement);
if (SUCCEEDED(hr)) {
@@ -573,19 +572,30 @@ std::wstring memoryToHexW(CIDebugDataSpaces *ds, ULONG64 address, ULONG length,
static StackFrames getStackTrace(CIDebugControl *debugControl,
CIDebugSymbols *debugSymbols,
unsigned maxFrames,
+ bool *incomplete,
std::string *errorMessage)
{
- if (!maxFrames)
+ if (maxFrames) {
+ *incomplete = false;
+ } else {
+ *incomplete = true;
return StackFrames();
- DEBUG_STACK_FRAME *frames = new DEBUG_STACK_FRAME[maxFrames];
+ }
+ // Ask for one more frame to find out whether it is a complete listing.
+ const unsigned askedFrames = maxFrames + 1;
+ DEBUG_STACK_FRAME *frames = new DEBUG_STACK_FRAME[askedFrames];
ULONG frameCount = 0;
- const HRESULT hr = debugControl->GetStackTrace(0, 0, 0, frames, maxFrames, &frameCount);
+ const HRESULT hr = debugControl->GetStackTrace(0, 0, 0, frames, askedFrames, &frameCount);
if (FAILED(hr)) {
delete [] frames;
*errorMessage = msgDebugEngineComFailed("GetStackTrace", hr);
return StackFrames();
}
+ if (askedFrames == frameCount) {
+ --frameCount;
+ *incomplete = true;
+ }
StackFrames rc(frameCount, StackFrame());
for (ULONG f = 0; f < frameCount; ++f)
getFrame(debugSymbols, frames[f], &(rc[f]));
@@ -598,8 +608,9 @@ std::string gdbmiStack(CIDebugControl *debugControl,
unsigned maxFrames,
bool humanReadable, std::string *errorMessage)
{
+ bool incomplete;
const StackFrames frames = getStackTrace(debugControl, debugSymbols,
- maxFrames, errorMessage);
+ maxFrames, &incomplete, errorMessage);
if (frames.empty() && maxFrames > 0)
return std::string();
@@ -613,6 +624,8 @@ std::string gdbmiStack(CIDebugControl *debugControl,
if (humanReadable)
str << '\n';
}
+ if (incomplete) // Empty elements indicates incomplete.
+ str <<",{}";
str << ']';
return str.str();
}
diff --git a/src/libs/qtcreatorcdbext/gdbmihelpers.h b/src/libs/qtcreatorcdbext/gdbmihelpers.h
index 8171c1c0a7..34313b03b7 100644
--- a/src/libs/qtcreatorcdbext/gdbmihelpers.h
+++ b/src/libs/qtcreatorcdbext/gdbmihelpers.h
@@ -165,7 +165,7 @@ std::wstring memoryToHexW(CIDebugDataSpaces *ds, ULONG64 address, ULONG length,
std::string *errorMessage = 0);
// Stack helpers
StackFrames getStackTrace(CIDebugControl *debugControl, CIDebugSymbols *debugSymbols,
- unsigned maxFrames, std::string *errorMessage);
+ unsigned maxFrames, bool *incomplete, std::string *errorMessage);
std::string gdbmiStack(CIDebugControl *debugControl, CIDebugSymbols *debugSymbols,
unsigned maxFrames, bool humanReadable,
diff --git a/src/libs/qtcreatorcdbext/knowntype.h b/src/libs/qtcreatorcdbext/knowntype.h
index 5e58f45b5a..4a8c64d7c5 100644
--- a/src/libs/qtcreatorcdbext/knowntype.h
+++ b/src/libs/qtcreatorcdbext/knowntype.h
@@ -71,6 +71,7 @@ enum KnownType
KT_QVariant = KT_Qt_Type + KT_Qt_MovableType + KT_HasSimpleDumper + KT_HasComplexDumper + 17,
KT_QBasicAtomicInt = KT_Qt_Type + KT_HasSimpleDumper + 18,
KT_QAtomicInt = KT_Qt_Type + KT_HasSimpleDumper + 19,
+ KT_QStringRef = KT_Qt_Type + KT_HasSimpleDumper + 20,
KT_QObject = KT_Qt_Type + KT_HasSimpleDumper + KT_HasComplexDumper + 20,
KT_QWindow = KT_Qt_Type + KT_HasSimpleDumper + KT_HasComplexDumper + 21,
KT_QWidget = KT_Qt_Type + KT_HasSimpleDumper + KT_HasComplexDumper + 22,
@@ -80,7 +81,7 @@ enum KnownType
KT_QUrl = KT_Qt_Type + KT_Qt_MovableType + 31 + KT_HasSimpleDumper,
KT_QIcon = KT_Qt_Type + KT_Qt_MovableType + 32,
KT_QBrush = KT_Qt_Type + KT_Qt_MovableType + 33,
- KT_QImage = KT_Qt_Type + KT_Qt_MovableType + 35,
+ KT_QImage = KT_Qt_Type + KT_HasSimpleDumper + KT_Qt_MovableType + 35,
KT_QLocale = KT_Qt_Type + KT_Qt_MovableType + 36,
KT_QMatrix = KT_Qt_Type + KT_Qt_MovableType + 37,
KT_QRegExp = KT_Qt_Type + KT_Qt_MovableType + KT_HasSimpleDumper + 38,
diff --git a/src/libs/qtcreatorcdbext/qtcreatorcdbext.def b/src/libs/qtcreatorcdbext/qtcreatorcdbext.def
index 798be24b9d..db92e4750f 100644
--- a/src/libs/qtcreatorcdbext/qtcreatorcdbext.def
+++ b/src/libs/qtcreatorcdbext/qtcreatorcdbext.def
@@ -14,6 +14,7 @@ threads
registers
modules
idle
+setparameter
help
memory
expression
diff --git a/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp b/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp
index eb833cd120..ac6db960d1 100644
--- a/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp
+++ b/src/libs/qtcreatorcdbext/qtcreatorcdbextension.cpp
@@ -110,7 +110,8 @@ enum Command {
CmdAddWatch,
CmdWidgetAt,
CmdBreakPoints,
- CmdTest
+ CmdTest,
+ CmdSetParameter
};
static const CommandDescription commandDescriptions[] = {
@@ -167,12 +168,13 @@ static const CommandDescription commandDescriptions[] = {
{"help","Prints help.",""},
{"memory","Prints memory contents in Base64 encoding.","[-t token] <address> <length>"},
{"expression","Prints expression value.","[-t token] <expression>"},
-{"stack","Prints stack in GDBMI format.","[-t token] [max-frames]"},
+{"stack","Prints stack in GDBMI format.","[-t token] [<max-frames>|unlimited]"},
{"shutdownex","Unhooks output callbacks.\nNeeds to be called explicitly only in case of remote debugging.",""},
{"addwatch","Add watch expression","<iname> <expression>"},
{"widgetat","Return address of widget at position","<x> <y>"},
{"breakpoints","List breakpoints with modules","[-h] [-v]"},
-{"test","Testing command","-T type | -w watch-expression"}
+{"test","Testing command","-T type | -w watch-expression"},
+{"setparameter","Set parameter","maxStringLength=value maxStackDepth=value"}
};
typedef std::vector<std::string> StringVector;
@@ -275,13 +277,12 @@ extern "C" HRESULT CALLBACK pid(CIDebugClient *client, PCSTR args)
int token;
commandTokens<StringList>(args, &token);
- dprintf("Qt Creator CDB extension version 2.6.1 (Qt 5 support) %d bit built %s.\n",
+ dprintf("Qt Creator CDB extension version 2.7 (Qt 5 support) %d bit built %s.\n",
sizeof(void *) * 8, __DATE__);
- if (const ULONG pid = currentProcessId(client)) {
+ if (const ULONG pid = currentProcessId(client))
ExtensionContext::instance().report('R', token, 0, "pid", "%u", pid);
- } else {
+ else
ExtensionContext::instance().report('N', token, 0, "pid", "0");
- }
return S_OK;
}
@@ -498,6 +499,8 @@ static std::string commmandLocals(ExtensionCommandContext &commandExtCtx,PCSTR a
symGroup->markUninitialized(uninitializedInames);
SymbolGroupValue::verbose = parameters.verbose;
+ if (SymbolGroupValue::verbose)
+ DebugPrint() << parameters.dumpParameters;
// Synchronize watches if desired.
WatchesSymbolGroup *watchesSymbolGroup = extCtx.watchesSymbolGroup();
@@ -562,11 +565,10 @@ extern "C" HRESULT CALLBACK locals(CIDebugClient *client, PCSTR args)
int token;
const std::string output = commmandLocals(exc, args, &token, &errorMessage);
SymbolGroupValue::verbose = 0;
- if (output.empty()) {
+ if (output.empty())
ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "locals", output);
- }
return S_OK;
}
@@ -617,11 +619,10 @@ extern "C" HRESULT CALLBACK watches(CIDebugClient *client, PCSTR args)
int token = 0;
const std::string output = commmandWatches(exc, args, &token, &errorMessage);
SymbolGroupValue::verbose = 0;
- if (output.empty()) {
+ if (output.empty())
ExtensionContext::instance().report('N', token, 0, "locals", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "locals", output);
- }
return S_OK;
}
@@ -668,11 +669,10 @@ extern "C" HRESULT CALLBACK dumplocal(CIDebugClient *client, PCSTR argsIn)
std::string errorMessage;
int token = 0;
const std::string value = dumplocalHelper(exc,argsIn, &token, &errorMessage);
- if (value.empty()) {
+ if (value.empty())
ExtensionContext::instance().report('N', token, 0, "dumplocal", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "dumplocal", value);
- }
return S_OK;
}
@@ -697,11 +697,10 @@ extern "C" HRESULT CALLBACK typecast(CIDebugClient *client, PCSTR args)
} else {
errorMessage = singleLineUsage(commandDescriptions[CmdTypecast]);
}
- if (symGroup != 0 && symGroup->typeCast(iname, desiredType, &errorMessage)) {
+ if (symGroup != 0 && symGroup->typeCast(iname, desiredType, &errorMessage))
ExtensionContext::instance().report('R', token, 0, "typecast", "OK");
- } else {
+ else
ExtensionContext::instance().report('N', token, 0, "typecast", errorMessage.c_str());
- }
return S_OK;
}
@@ -727,11 +726,10 @@ extern "C" HRESULT CALLBACK addsymbol(CIDebugClient *client, PCSTR args)
} else {
errorMessage = singleLineUsage(commandDescriptions[CmdAddsymbol]);
}
- if (symGroup != 0 && symGroup->addSymbol(std::string(), name, iname, &errorMessage)) {
+ if (symGroup != 0 && symGroup->addSymbol(std::string(), name, iname, &errorMessage))
ExtensionContext::instance().report('R', token, 0, "addsymbol", "OK");
- } else {
+ else
ExtensionContext::instance().report('N', token, 0, "addsymbol", errorMessage.c_str());
- }
return S_OK;
}
@@ -761,11 +759,10 @@ extern "C" HRESULT CALLBACK addwatch(CIDebugClient *client, PCSTR argsIn)
success = watchesSymGroup->addWatch(exc.symbols(), iname, watchExpression, &errorMessage);
} while (false);
- if (success) {
+ if (success)
ExtensionContext::instance().report('R', token, 0, "addwatch", "Ok");
- } else {
+ else
ExtensionContext::instance().report('N', token, 0, "addwatch", errorMessage.c_str());
- }
return S_OK;
}
@@ -822,11 +819,10 @@ extern "C" HRESULT CALLBACK assign(CIDebugClient *client, PCSTR argsIn)
&errorMessage);
} while (false);
- if (success) {
+ if (success)
ExtensionContext::instance().report('R', token, 0, "assign", "Ok");
- } else {
+ else
ExtensionContext::instance().report('N', token, 0, "assign", errorMessage.c_str());
- }
return S_OK;
}
@@ -846,11 +842,10 @@ extern "C" HRESULT CALLBACK threads(CIDebugClient *client, PCSTR argsIn)
exc.control(),
exc.advanced(),
&errorMessage);
- if (gdbmi.empty()) {
+ if (gdbmi.empty())
ExtensionContext::instance().report('N', token, 0, "threads", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "threads", gdbmi);
- }
return S_OK;
}
@@ -866,11 +861,10 @@ extern "C" HRESULT CALLBACK registers(CIDebugClient *Client, PCSTR argsIn)
const StringList tokens = commandTokens<StringList>(argsIn, &token);
const bool humanReadable = !tokens.empty() && tokens.front() == "-h";
const std::string regs = gdbmiRegisters(exc.registers(), exc.control(), humanReadable, IncludePseudoRegisters, &errorMessage);
- if (regs.empty()) {
+ if (regs.empty())
ExtensionContext::instance().report('N', token, 0, "registers", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "registers", regs);
- }
return S_OK;
}
@@ -886,11 +880,10 @@ extern "C" HRESULT CALLBACK modules(CIDebugClient *Client, PCSTR argsIn)
const StringList tokens = commandTokens<StringList>(argsIn, &token);
const bool humanReadable = !tokens.empty() && tokens.front() == "-h";
const std::string modules = gdbmiModules(exc.symbols(), humanReadable, &errorMessage);
- if (modules.empty()) {
+ if (modules.empty())
ExtensionContext::instance().report('N', token, 0, "modules", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "modules", modules);
- }
return S_OK;
}
@@ -902,6 +895,34 @@ extern "C" HRESULT CALLBACK idle(CIDebugClient *client, PCSTR)
return S_OK;
}
+// Extension command 'setparameter':
+// Parse a list of parameters: 'key=value'
+
+extern "C" HRESULT CALLBACK setparameter(CIDebugClient *, PCSTR args)
+{
+ int token;
+ StringVector tokens = commandTokens<StringVector>(args, &token);
+ const size_t count = tokens.size();
+ size_t success = 0;
+ for (size_t i = 0; i < count; ++i) {
+ const std::string &token = tokens.at(i);
+ const std::string::size_type equalsPos = token.find('=');
+ if (equalsPos != std::string::npos) {
+ const std::string value = token.substr(equalsPos + 1, token.size() - 1 - equalsPos);
+ if (!token.compare(0, equalsPos, "maxStringLength")) {
+ if (integerFromString(value, &ExtensionContext::instance().parameters().maxStringLength))
+ ++success;
+ } else if (!token.compare(0, equalsPos, "maxStackDepth")) {
+ if (integerFromString(value, &ExtensionContext::instance().parameters().maxStackDepth))
+ ++success;
+ }
+ }
+ }
+ if (success != count)
+ DebugPrint() << "Errors parsing setparameters command '" << args << '\'';
+ return S_OK;
+}
+
// Extension command 'help':
// Display version
@@ -967,11 +988,10 @@ extern "C" HRESULT CALLBACK expression(CIDebugClient *Client, PCSTR argsIn)
break;
} while (false);
- if (errorMessage.empty()) {
+ if (errorMessage.empty())
ExtensionContext::instance().reportLong('R', token, "expression", toString(value));
- } else {
+ else
ExtensionContext::instance().report('N', token, 0, "expression", errorMessage.c_str());
- }
return S_OK;
}
@@ -985,24 +1005,28 @@ extern "C" HRESULT CALLBACK stack(CIDebugClient *Client, PCSTR argsIn)
int token;
bool humanReadable = false;
- unsigned maxFrames = ExtensionContext::maxStackFrames;
+ unsigned maxFrames = ExtensionContext::instance().parameters().maxStackDepth;
StringList tokens = commandTokens<StringList>(argsIn, &token);
if (!tokens.empty() && tokens.front() == "-h") {
humanReadable = true;
tokens.pop_front();
}
- if (!tokens.empty())
- integerFromString(tokens.front(), &maxFrames);
+ if (!tokens.empty()) {
+ if (tokens.front() == "unlimited") {
+ maxFrames = 1000;
+ } else {
+ integerFromString(tokens.front(), &maxFrames);
+ }
+ }
const std::string stack = gdbmiStack(exc.control(), exc.symbols(),
maxFrames, humanReadable, &errorMessage);
- if (stack.empty()) {
+ if (stack.empty())
ExtensionContext::instance().report('N', token, 0, "stack", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "stack", stack);
- }
return S_OK;
}
@@ -1039,11 +1063,10 @@ extern "C" HRESULT CALLBACK widgetat(CIDebugClient *client, PCSTR argsIn)
x, y, &errorMessage);
} while (false);
- if (widgetAddress.empty()) {
+ if (widgetAddress.empty())
ExtensionContext::instance().report('N', token, 0, "widgetat", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "widgetat", widgetAddress);
- }
return S_OK;
}
@@ -1068,11 +1091,10 @@ extern "C" HRESULT CALLBACK breakpoints(CIDebugClient *client, PCSTR argsIn)
}
const std::string bp = gdbmiBreakpoints(exc.control(), exc.symbols(), exc.dataSpaces(),
humanReadable, verbose, &errorMessage);
- if (bp.empty()) {
+ if (bp.empty())
ExtensionContext::instance().report('N', token, 0, "breakpoints", errorMessage.c_str());
- } else {
+ else
ExtensionContext::instance().reportLong('R', token, "breakpoints", bp);
- }
return S_OK;
}
diff --git a/src/libs/qtcreatorcdbext/stringutils.cpp b/src/libs/qtcreatorcdbext/stringutils.cpp
index f0f2c5cce9..e8801c4a10 100644
--- a/src/libs/qtcreatorcdbext/stringutils.cpp
+++ b/src/libs/qtcreatorcdbext/stringutils.cpp
@@ -27,6 +27,10 @@
**
****************************************************************************/
+#ifndef _SCL_SECURE_NO_WARNINGS // silence std::string::copy
+# define _SCL_SECURE_NO_WARNINGS
+#endif
+
#include "stringutils.h"
#include <cctype>
@@ -205,26 +209,30 @@ inline char toHexDigit(unsigned v)
}
// Strings from raw data.
-std::wstring quotedWStringFromCharData(const unsigned char *data, size_t size)
+std::wstring quotedWStringFromCharData(const unsigned char *data, size_t size, bool truncated)
{
std::wstring rc;
- rc.reserve(size + 2);
+ rc.reserve(size + (truncated ? 5 : 2));
rc.push_back(L'"');
const unsigned char *end = data + size;
for ( ; data < end; data++)
rc.push_back(wchar_t(*data));
+ if (truncated)
+ rc.append(L"...");
rc.push_back(L'"');
return rc;
}
-std::wstring quotedWStringFromWCharData(const unsigned char *dataIn, size_t sizeIn)
+std::wstring quotedWStringFromWCharData(const unsigned char *dataIn, size_t sizeIn, bool truncated)
{
std::wstring rc;
const wchar_t *data = reinterpret_cast<const wchar_t *>(dataIn);
const size_t size = sizeIn / sizeof(wchar_t);
- rc.reserve(size + 2);
+ rc.reserve(size + (truncated ? 5 : 2));
rc.push_back(L'"');
rc.append(data, data + size);
+ if (truncated)
+ rc.append(L"...");
rc.push_back(L'"');
return rc;
}
@@ -264,11 +272,10 @@ std::string dumpMemory(const unsigned char *p, size_t size,
case '\n':
str << "\\n";
default:
- if (u >= 32 && u < 128) {
+ if (u >= 32 && u < 128)
str << (char(u));
- } else {
+ else
str << '\\' << std::setw(3) << unsigned(u);
- }
}
}
if (wantQuotes)
@@ -285,12 +292,29 @@ void decodeHex(const char *p, const char *end, unsigned char *target)
}
}
-std::wstring dataToHexW(const unsigned char *p, const unsigned char *end)
+MemoryHandle *MemoryHandle::fromStdString(const std::string &s)
+{
+ const size_t size = s.size();
+ unsigned char *data = new unsigned char[size];
+ s.copy(reinterpret_cast<char *>(data), size);
+ return new MemoryHandle(data, size);
+}
+
+MemoryHandle *MemoryHandle::fromStdWString(const std::wstring &ws)
+{
+ const size_t size = ws.size();
+ wchar_t *data = new wchar_t[size];
+ ws.copy(data, size);
+ return new MemoryHandle(data, size);
+}
+
+template <class String>
+inline String dataToHexHelper(const unsigned char *p, const unsigned char *end)
{
if (p == end)
- return std::wstring();
+ return String();
- std::wstring rc;
+ String rc;
rc.reserve(2 * (end - p));
for ( ; p < end ; ++p) {
const unsigned c = *p;
@@ -300,6 +324,16 @@ std::wstring dataToHexW(const unsigned char *p, const unsigned char *end)
return rc;
}
+std::wstring dataToHexW(const unsigned char *p, const unsigned char *end)
+{
+ return dataToHexHelper<std::wstring>(p, end);
+}
+
+std::string dataToHex(const unsigned char *p, const unsigned char *end)
+{
+ return dataToHexHelper<std::string>(p, end);
+}
+
// Readable hex: '0xAA 0xBB'..
std::wstring dataToReadableHexW(const unsigned char *begin, const unsigned char *end)
{
diff --git a/src/libs/qtcreatorcdbext/stringutils.h b/src/libs/qtcreatorcdbext/stringutils.h
index 91527864ab..7a7afb2468 100644
--- a/src/libs/qtcreatorcdbext/stringutils.h
+++ b/src/libs/qtcreatorcdbext/stringutils.h
@@ -176,8 +176,8 @@ std::string wStringToString(const std::wstring &w);
std::wstring stringToWString(const std::string &w);
// Strings from raw data.
-std::wstring quotedWStringFromCharData(const unsigned char *data, size_t size);
-std::wstring quotedWStringFromWCharData(const unsigned char *data, size_t size);
+std::wstring quotedWStringFromCharData(const unsigned char *data, size_t size, bool truncated = false);
+std::wstring quotedWStringFromWCharData(const unsigned char *data, size_t size, bool truncated = false);
// Helper for dumping memory
std::string dumpMemory(const unsigned char *data, size_t size, bool wantQuotes = true);
@@ -188,9 +188,41 @@ std::string stringFromHex(const char *begin, const char *end);
void decodeHex(const char *begin, const char *end, unsigned char *target);
std::wstring dataToHexW(const unsigned char *begin, const unsigned char *end);
+std::string dataToHex(const unsigned char *begin, const unsigned char *end);
// Create readable hex: '0xAA 0xBB'..
std::wstring dataToReadableHexW(const unsigned char *begin, const unsigned char *end);
+// Flat memory handle to pass allocated memory around.
+class MemoryHandle {
+ MemoryHandle(const MemoryHandle &);
+ MemoryHandle& operator=(const MemoryHandle &);
+
+public:
+ explicit MemoryHandle(const unsigned char *memory, size_t size) : m_size(size), m_memory(memory) {}
+ explicit MemoryHandle(const wchar_t *wcharData, size_t size) :
+ m_size(size * sizeof(wchar_t)),
+ m_memory(reinterpret_cast<const unsigned char *>(wcharData)) {}
+
+ static MemoryHandle* fromStdString(const std::string &s);
+ static MemoryHandle* fromStdWString(const std::wstring &s);
+
+ ~MemoryHandle() { delete [] m_memory; }
+
+ size_t size() const { return m_size; }
+ const unsigned char *data() const { return m_memory; }
+ const unsigned char *begin() const { return m_memory; }
+ const unsigned char *end() const { return m_memory + m_size; }
+
+ std::string dump(bool wantQuotes) const { return dumpMemory(begin(), m_size, wantQuotes); }
+ std::wstring toHexW() const { return dataToHexW(begin(), end()); }
+ std::string toHex() const { return dataToHex(begin(), end()); }
+ std::wstring toReadableHexW() const { return dataToReadableHexW(begin(), end()); }
+
+private:
+ const size_t m_size;
+ const unsigned char *m_memory;
+};
+
// Format a map as a GDBMI hash {key="value",..}
void formatGdbmiHash(std::ostream &os, const std::map<std::string, std::string> &, bool closeHash = true);
diff --git a/src/libs/qtcreatorcdbext/symbolgroup.cpp b/src/libs/qtcreatorcdbext/symbolgroup.cpp
index 1749d265b0..0a4361147f 100644
--- a/src/libs/qtcreatorcdbext/symbolgroup.cpp
+++ b/src/libs/qtcreatorcdbext/symbolgroup.cpp
@@ -239,11 +239,10 @@ std::string SymbolGroup::debug(const std::string &iname,
if (iname.empty()) {
accept(*visitor);
} else {
- if (AbstractSymbolGroupNode *const node = find(iname)) {
+ if (AbstractSymbolGroupNode *const node = find(iname))
node->accept(*visitor, SymbolGroupNodeVisitor::parentIname(iname), 0, 0);
- } else {
+ else
str << msgNotFound(iname);
- }
}
return str.str();
}
diff --git a/src/libs/qtcreatorcdbext/symbolgroupnode.cpp b/src/libs/qtcreatorcdbext/symbolgroupnode.cpp
index e8e2f5fb06..f2c8ffbe86 100644
--- a/src/libs/qtcreatorcdbext/symbolgroupnode.cpp
+++ b/src/libs/qtcreatorcdbext/symbolgroupnode.cpp
@@ -251,11 +251,10 @@ void BaseSymbolGroupNode::addChild(AbstractSymbolGroupNode *c)
std::ostream &operator<<(std::ostream &str, const DEBUG_SYMBOL_PARAMETERS &parameters)
{
str << "parent=";
- if (parameters.ParentSymbol == DEBUG_ANY_ID) {
+ if (parameters.ParentSymbol == DEBUG_ANY_ID)
str << "DEBUG_ANY_ID";
- } else {
+ else
str << parameters.ParentSymbol ;
- }
if (parameters.Flags != 0 && parameters.Flags != 1)
str << " flags=" << parameters.Flags;
// Detailed flags:
@@ -294,6 +293,10 @@ DumpParameters::DumpParameters() : dumpFlags(0)
DumpParameters::FormatMap DumpParameters::decodeFormatArgument(const std::string &f,
bool isHex)
{
+ extern const char *stdStringTypeC;
+ extern const char *stdWStringTypeC;
+ extern const char *stdWStringWCharTypeC;
+
FormatMap rc;
const std::string::size_type size = f.size();
// Split 'hexname=4,'
@@ -313,7 +316,13 @@ DumpParameters::FormatMap DumpParameters::decodeFormatArgument(const std::string
int format;
if (!integerFromString(f.substr(numberPos, nextPos - numberPos), &format))
return rc;
- rc.insert(FormatMap::value_type(name, format));
+ if (name == "std::basic_string") { // Python dumper naming convention for types
+ rc.insert(FormatMap::value_type(stdStringTypeC, format));
+ rc.insert(FormatMap::value_type(stdWStringTypeC, format));
+ rc.insert(FormatMap::value_type(stdWStringWCharTypeC, format));
+ } else {
+ rc.insert(FormatMap::value_type(name, format));
+ }
pos = nextPos + 1;
}
return rc;
@@ -327,7 +336,12 @@ int DumpParameters::format(const std::string &type, const std::string &iname) co
return iit->second;
}
if (!typeFormats.empty()) {
- const FormatMap::const_iterator tit = typeFormats.find(type);
+ // Strip 'struct' / 'class' prefixes and pointer types
+ // when called with a raw cdb types.
+ std::string stripped = SymbolGroupValue::stripClassPrefixes(type);
+ if (stripped != type)
+ stripped = SymbolGroupValue::stripPointerType(stripped);
+ const FormatMap::const_iterator tit = typeFormats.find(stripped);
if (tit != typeFormats.end())
return tit->second;
}
@@ -589,15 +603,25 @@ SymbolGroupNode::SymbolGroupNode(SymbolGroup *symbolGroup,
ULONG index,
const std::string &module,
const std::string &name,
- const std::string &iname) :
- BaseSymbolGroupNode(name, iname),
- m_symbolGroup(symbolGroup),
- m_module(module), m_index(index), m_dumperType(-1), m_dumperContainerSize(-1), m_dumperSpecialInfo(0)
+ const std::string &iname)
+ : BaseSymbolGroupNode(name, iname)
+ , m_symbolGroup(symbolGroup)
+ , m_module(module)
+ , m_index(index)
+ , m_dumperType(-1)
+ , m_dumperContainerSize(-1)
+ , m_dumperSpecialInfo(0)
+ , m_memory(0)
{
memset(&m_parameters, 0, sizeof(DEBUG_SYMBOL_PARAMETERS));
m_parameters.ParentSymbol = DEBUG_ANY_ID;
}
+SymbolGroupNode::~SymbolGroupNode()
+{
+ delete m_memory;
+}
+
const SymbolGroupNode *SymbolGroupNode::symbolGroupNodeParent() const
{
if (const AbstractSymbolGroupNode *p = parent())
@@ -644,17 +668,15 @@ bool SymbolGroupNode::notifyIndexesMoved(ULONG index, bool inserted, ULONG offse
if (m_index == DEBUG_ANY_ID || m_index < index)
return false;
- if (inserted) {
+ if (inserted)
m_index += offset;
- } else {
+ else
m_index -= offset;
- }
if (m_parameters.ParentSymbol != DEBUG_ANY_ID && m_parameters.ParentSymbol >= index) {
- if (inserted) {
+ if (inserted)
m_parameters.ParentSymbol += offset;
- } else {
+ else
m_parameters.ParentSymbol -= offset;
- }
}
return true;
}
@@ -707,9 +729,8 @@ static inline void fixNames(bool isTopLevel, StringVector *names, StringVector *
* 3) For toplevels: Fix shadowed variables in the order the debugger expects them:
\code
int x; // Occurrence (1), should be reported as name="x <shadowed 1>"/iname="x#1"
- if (true) {
+ if (true)
int x = 5; (2) // Occurrence (2), should be reported as name="x"/iname="x"
- }
\endcode */
StringVector::iterator nameIt = names->begin();
const StringVector::iterator namesEnd = names->end();
@@ -1004,7 +1025,8 @@ bool SymbolGroupNode::runSimpleDumpers(const SymbolGroupValueContext &ctx)
if (testFlags(SimpleDumperMask))
return false;
addFlags(dumpSimpleType(this , ctx, &m_dumperValue,
- &m_dumperType, &m_dumperContainerSize, &m_dumperSpecialInfo));
+ &m_dumperType, &m_dumperContainerSize,
+ &m_dumperSpecialInfo, &m_memory));
if (symbolGroupDebug)
DebugPrint() << "<SymbolGroupNode::runSimpleDumpers " << name() << " '"
<< wStringToString(m_dumperValue) << "' Type="
@@ -1077,11 +1099,10 @@ int SymbolGroupNode::dumpNode(std::ostream &str,
// Emulate gdb's behaviour of returning the referenced address
// for pointers.
str << std::hex << std::showbase;
- if (referencedAddr) {
+ if (referencedAddr)
str << ",addr=\"" << referencedAddr << "\",origaddr=\"" << addr << '"';
- } else {
+ else
str << ",addr=\"" << addr << '"';
- }
str << std::noshowbase << std::dec;
}
const ULONG s = size();
@@ -1105,6 +1126,9 @@ int SymbolGroupNode::dumpNode(std::ostream &str,
base64Encode(str, reinterpret_cast<const unsigned char *>(value.c_str()), value.size() * sizeof(wchar_t));
str << '"';
}
+ const int format = dumpParameters.format(t, aFullIName);
+ if (format > 0)
+ dumpEditValue(this, ctx, format, str);
}
// Children: Dump all known non-obscured or subelements
unsigned childCountGuess = 0;
@@ -1112,11 +1136,10 @@ int SymbolGroupNode::dumpNode(std::ostream &str,
if (m_dumperContainerSize > 0) {
childCountGuess = m_dumperContainerSize; // See Obscured handling
} else {
- if (children().empty()) {
+ if (children().empty())
childCountGuess = m_parameters.SubElements; // Guess
- } else {
+ else
childCountGuess = unsigned(children().size());
- }
}
}
// No children..suppose we are editable and enabled.
@@ -1617,11 +1640,10 @@ SymbolGroupNodeVisitor::VisitResult
if (!realNode->isExpanded() || realNode->testFlags(SymbolGroupNode::Uninitialized|SymbolGroupNode::ExpandedByDumper))
visitChildren = false;
// Comma between same level children given obscured children
- if (depth == m_lastDepth) {
+ if (depth == m_lastDepth)
m_os << ',';
- } else {
+ else
m_lastDepth = depth;
- }
if (m_parameters.humanReadable()) {
m_os << '\n';
indentStream(m_os, depth * 2);
diff --git a/src/libs/qtcreatorcdbext/symbolgroupnode.h b/src/libs/qtcreatorcdbext/symbolgroupnode.h
index 07c4d7c605..9d4cacba51 100644
--- a/src/libs/qtcreatorcdbext/symbolgroupnode.h
+++ b/src/libs/qtcreatorcdbext/symbolgroupnode.h
@@ -45,6 +45,7 @@ class SymbolGroupNodeVisitor;
class SymbolGroup;
struct SymbolGroupValueContext;
class SymbolGroupNode;
+class MemoryHandle;
// Helper struct used for check results when recoding CDB char pointer output.
struct DumpParameterRecodeResult
@@ -214,6 +215,8 @@ public:
WatchNode = 0x100
};
+ ~SymbolGroupNode();
+
typedef std::vector<DEBUG_SYMBOL_PARAMETERS> SymbolParameterVector;
void parseParameters(SymbolParameterVector::size_type index,
@@ -268,6 +271,8 @@ public:
ULONG subElements() const { return m_parameters.SubElements; }
ULONG index() const { return m_index; }
+ MemoryHandle *memory() const { return m_memory; }
+
virtual SymbolGroupNode *asSymbolGroupNode() { return this; }
virtual const SymbolGroupNode *asSymbolGroupNode() const { return this; }
@@ -296,6 +301,7 @@ private:
int m_dumperType;
int m_dumperContainerSize;
void *m_dumperSpecialInfo; // Opaque information passed from simple to complex dumpers
+ MemoryHandle *m_memory; // Memory shared between simple dumper and edit value.
};
class ReferenceSymbolGroupNode : public AbstractSymbolGroupNode
diff --git a/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp b/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp
index 96608bc809..30b99117c6 100644
--- a/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp
+++ b/src/libs/qtcreatorcdbext/symbolgroupvalue.cpp
@@ -30,6 +30,10 @@
// std::copy is perfectly fine, don't let MSVC complain about it being deprecated
#pragma warning (disable: 4996)
+#ifndef NOMINMAX
+# define NOMINMAX
+#endif
+
#include "symbolgroupvalue.h"
#include "symbolgroup.h"
#include "stringutils.h"
@@ -38,6 +42,7 @@
#include <iomanip>
#include <algorithm>
+#include <limits>
#include <ctype.h>
typedef std::vector<int>::size_type VectorIndexType;
@@ -701,11 +706,10 @@ const QtInfo &QtInfo::get(const SymbolGroupValueContext &ctx)
}
rc.libInfix = qualifiedSymbol.substr(libPos + 4, exclPos - libPos - 4);
// 'Qt5Cored!qstrdup' or 'QtCored4!qstrdup'.
- if (isdigit(qualifiedSymbol.at(2))) {
+ if (isdigit(qualifiedSymbol.at(2)))
rc.version = qualifiedSymbol.at(2) - '0';
- } else {
+ else
rc.version = qualifiedSymbol.at(exclPos - 1) - '0';
- }
// Any namespace? 'QtCored4!nsp::qstrdup'
const std::string::size_type nameSpaceStart = exclPos + 1;
const std::string::size_type colonPos = qualifiedSymbol.find(':', nameSpaceStart);
@@ -993,10 +997,10 @@ static inline void formatMilliSeconds(std::wostream &str, int milliSecs)
<< '.' << std::setw(3) << milliSecs;
}
-static const char stdStringTypeC[] = "std::basic_string<char,std::char_traits<char>,std::allocator<char> >";
-static const char stdWStringTypeC[] = "std::basic_string<unsigned short,std::char_traits<unsigned short>,std::allocator<unsigned short> >";
+const char *stdStringTypeC = "std::basic_string<char,std::char_traits<char>,std::allocator<char> >";
+const char *stdWStringTypeC = "std::basic_string<unsigned short,std::char_traits<unsigned short>,std::allocator<unsigned short> >";
// Compiler option: -Zc:wchar_t-:
-static const char stdWStringWCharTypeC[] = "std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >";
+const char *stdWStringWCharTypeC = "std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t> >";
static KnownType knownPODTypeHelper(const std::string &type, std::string::size_type endPos)
{
@@ -1264,6 +1268,8 @@ static KnownType knownClassTypeHelper(const std::string &type,
return KT_QTransform;
if (!type.compare(qPos, 10, "QFixedSize"))
return KT_QFixedSize;
+ if (!type.compare(qPos, 10, "QStringRef"))
+ return KT_QStringRef;
break;
case 11:
if (!type.compare(qPos, 11, "QStringList"))
@@ -1518,35 +1524,40 @@ QtStringAddressData readQtStringAddressData(const SymbolGroupValue &dV,
// Retrieve data from a QByteArrayData(char)/QStringData(wchar_t)
// in desired type. For empty arrays, no data are allocated.
+// All sizes are in CharType units. zeroTerminated means data are 0-terminated
+// in the data type, but "size" does not contain it.
template <typename CharType>
bool readQt5StringData(const SymbolGroupValue &dV, int qtMajorVersion,
- bool zeroTerminated, unsigned sizeLimit,
+ bool zeroTerminated, unsigned position, unsigned sizeLimit,
unsigned *fullSize, unsigned *arraySize,
CharType **array)
{
*array = 0;
- QtStringAddressData data = readQtStringAddressData(dV, qtMajorVersion);
- *arraySize = *fullSize = data.size;
- if (!data.address)
+ const QtStringAddressData data = readQtStringAddressData(dV, qtMajorVersion);
+ if (!data.address || position > data.size)
return false;
+ const ULONG64 address = data.address + sizeof(CharType) * position;
+ *fullSize = data.size - position;
+ *arraySize = std::min(*fullSize, sizeLimit);
if (!*fullSize)
return true;
- const bool truncated = *fullSize > sizeLimit;
- *arraySize = truncated ? sizeLimit : *fullSize;
const unsigned memorySize =
sizeof(CharType) * (*arraySize + (zeroTerminated ? 1 : 0));
unsigned char *memory =
SymbolGroupValue::readMemory(dV.context().dataspaces,
- data.address, memorySize);
+ address, memorySize);
if (!memory)
return false;
*array = reinterpret_cast<CharType *>(memory);
- if (truncated && zeroTerminated)
+ if ((*arraySize < *fullSize) && zeroTerminated)
*(*array + *arraySize) = CharType(0);
return true;
}
-static inline bool dumpQString(const SymbolGroupValue &v, std::wostream &str)
+static inline bool dumpQString(const SymbolGroupValue &v, std::wostream &str,
+ MemoryHandle **memoryHandle = 0,
+ unsigned position = 0,
+ unsigned length = std::numeric_limits<unsigned>::max())
{
const QtInfo &qtInfo = QtInfo::get(v.context());
const SymbolGroupValue dV = v["d"];
@@ -1557,7 +1568,14 @@ static inline bool dumpQString(const SymbolGroupValue &v, std::wostream &str)
if (const SymbolGroupValue sizeValue = dV["size"]) {
const int size = sizeValue.intValue();
if (size >= 0) {
- str << L'"' << dV["data"].wcharPointerData(size) << L'"';
+ std::wstring stringData = dV["data"].wcharPointerData(size);
+ if (position && position < stringData.size())
+ stringData.erase(0, position);
+ if (length < stringData.size())
+ stringData.erase(length, stringData.size() - length);
+ str << L'"' << stringData << L'"';
+ if (memoryHandle)
+ *memoryHandle = MemoryHandle::fromStdWString(stringData);
return true;
}
}
@@ -1571,17 +1589,36 @@ static inline bool dumpQString(const SymbolGroupValue &v, std::wostream &str)
const SymbolGroupValue typeArrayV = dV[unsigned(0)];
if (!typeArrayV)
return false;
- if (!readQt5StringData(typeArrayV, qtInfo.version, true, 10240, &fullSize, &size, &memory))
+ if (!readQt5StringData(typeArrayV, qtInfo.version, true, position,
+ std::min(length, ExtensionContext::instance().parameters().maxStringLength),
+ &fullSize, &size, &memory))
return false;
if (size) {
str << L'"' << memory;
- if (fullSize > size)
+ if (std::min(fullSize, length) > size)
str << L"...";
str << L'"';
} else {
str << L"\"\"";
}
- delete [] memory;
+ if (memoryHandle)
+ *memoryHandle = new MemoryHandle(memory, size);
+ else
+ delete [] memory;
+ return true;
+}
+
+static inline bool dumpQStringRef(const SymbolGroupValue &v, std::wostream &str,
+ MemoryHandle **memoryHandle = 0)
+{
+ const int position = v["m_position"].intValue();
+ const int size = v["m_size"].intValue();
+ if (position < 0 || size < 0)
+ return false;
+ const SymbolGroupValue string = v["m_string"];
+ if (!string || !dumpQString(string, str, memoryHandle, position, size))
+ return false;
+ str << L" (" << position << ',' << size << L')';
return true;
}
@@ -1634,7 +1671,8 @@ static unsigned qAtomicIntSize(const SymbolGroupValueContext &ctx)
}
// Dump a QByteArray
-static inline bool dumpQByteArray(const SymbolGroupValue &v, std::wostream &str)
+static inline bool dumpQByteArray(const SymbolGroupValue &v, std::wostream &str,
+ MemoryHandle **memoryHandle = 0)
{
const QtInfo &qtInfo = QtInfo::get(v.context());
const SymbolGroupValue dV = v["d"];
@@ -1663,7 +1701,7 @@ static inline bool dumpQByteArray(const SymbolGroupValue &v, std::wostream &str)
const SymbolGroupValue typeArrayV = dV[unsigned(0)];
if (!typeArrayV)
return false;
- if (!readQt5StringData(typeArrayV, qtInfo.version, false, 10240, &fullSize, &size, &memory))
+ if (!readQt5StringData(typeArrayV, qtInfo.version, false, 0, 10240, &fullSize, &size, &memory))
return false;
if (size) {
// Emulate CDB's behavior of replacing unprintable characters
@@ -1682,7 +1720,10 @@ static inline bool dumpQByteArray(const SymbolGroupValue &v, std::wostream &str)
} else {
str << L"<empty>";
}
- delete [] memory;
+ if (memoryHandle)
+ *memoryHandle = new MemoryHandle(reinterpret_cast<unsigned char *>(memory), size);
+ else
+ delete [] memory;
return true;
}
@@ -1999,13 +2040,12 @@ static inline bool dumpQFlags(const SymbolGroupValue &v, std::wostream &str)
static bool dumpJulianDate(int julianDay, std::wostream &str)
{
- if (julianDay < 0) {
+ if (julianDay < 0)
return false;
- } else if (!julianDay) {
+ else if (!julianDay)
str << L"<null>";
- } else {
+ else
formatJulianDate(str, julianDay);
- }
return true;
}
@@ -2053,6 +2093,70 @@ static bool dumpQDateTime(const SymbolGroupValue &v, std::wostream &str)
return true;
}
+static bool dumpQImage(const SymbolGroupValue &v, std::wostream &str, MemoryHandle **memoryHandle)
+{
+ struct CreatorImageHeader { // Header for image display as edit format, followed by data.
+ int width;
+ int height;
+ int format;
+ };
+ const QtInfo &qtInfo(QtInfo::get(v.context()));
+ // Fetch data of unexported private class
+ const ULONG64 address = v["d"].pointerValue();
+ if (!address) {
+ str << L"<null>";
+ return true;
+ }
+ const std::string qImageDataType = qtInfo.prependQtGuiModule("QImageData");
+ const unsigned long size = SymbolGroupValue::sizeOf(qImageDataType.c_str());
+ if (!size)
+ return false;
+ unsigned char *qImageData = SymbolGroupValue::readMemory(v.context().dataspaces, address, size);
+ if (!qImageData)
+ return false;
+ // read size data
+ unsigned char *ptr = qImageData + qAtomicIntSize(v.context());
+ CreatorImageHeader header;
+ header.width = *(reinterpret_cast<int *>(ptr));
+ ptr += SymbolGroupValue::intSize();
+ header.height = *(reinterpret_cast<int *>(ptr));
+ ptr += SymbolGroupValue::intSize();
+ const int depth = *(reinterpret_cast<int *>(ptr));
+ ptr += SymbolGroupValue::intSize();
+ const int nbytes = *(reinterpret_cast<int *>(ptr));
+ const unsigned dataOffset = SymbolGroupValue::fieldOffset(qImageDataType.c_str(), "data");
+ // Qt 4 has a Qt 3 support pointer member between 'data' and 'format'.
+ const unsigned formatOffset = SymbolGroupValue::fieldOffset(qImageDataType.c_str(), "format");
+ if (!dataOffset || !formatOffset)
+ return false;
+ ptr = qImageData + dataOffset;
+ // read data pointer
+ ULONG64 data = 0;
+ memcpy(&data, ptr, SymbolGroupValue::pointerSize());
+ // read format
+ ptr = qImageData + formatOffset;
+ header.format = *(reinterpret_cast<int *>(ptr));
+ if (header.width < 0 || header.height < 0 || header.format < 0 || header.format > 255
+ || nbytes < 0 || depth < 0) {
+ return false;
+ }
+ str << header.width << L'x' << header.height << L", depth: " << depth
+ << L", format: " << header.format << L", "
+ << nbytes << L" bytes @0x" << std::hex << data << std::dec;
+ delete [] qImageData;
+ // Create Creator Image data for display if reasonable size
+ if (memoryHandle && data && nbytes > 0 && nbytes < 205824) {
+ if (unsigned char *imageData = SymbolGroupValue::readMemory(v.context().dataspaces, data, nbytes)) {
+ unsigned char *creatorImageData = new unsigned char[sizeof(CreatorImageHeader) + nbytes];
+ memcpy(creatorImageData, &header, sizeof(CreatorImageHeader));
+ memcpy(creatorImageData + sizeof(CreatorImageHeader), imageData, nbytes);
+ delete [] imageData;
+ *memoryHandle = new MemoryHandle(creatorImageData, sizeof(CreatorImageHeader) + nbytes);
+ }
+ }
+ return true;
+}
+
// Dump a rectangle in X11 syntax
template <class T>
inline void dumpRect(std::wostream &str, T x, T y, T width, T height)
@@ -2066,12 +2170,6 @@ inline void dumpRect(std::wostream &str, T x, T y, T width, T height)
str << y;
}
-template <class T>
-inline void dumpRectPoints(std::wostream &str, T x1, T y1, T x2, T y2)
-{
- dumpRect(str, x1, y1, (x2 - x1), (y2 - y1));
-}
-
// Dump Qt's simple geometrical types
static inline bool dumpQSize_F(const SymbolGroupValue &v, std::wostream &str)
{
@@ -2099,7 +2197,11 @@ static inline bool dumpQLine_F(const SymbolGroupValue &v, std::wostream &str)
static inline bool dumpQRect(const SymbolGroupValue &v, std::wostream &str)
{
- dumpRectPoints(str, v["x1"].intValue(), v["y1"].intValue(), v["x2"].intValue(), v["y2"].intValue());
+ const int x1 = v["x1"].intValue();
+ const int y1 = v["y1"].intValue();
+ const int x2 = v["x2"].intValue();
+ const int y2 = v["y2"].intValue();
+ dumpRect(str, x1, y1, (x2 - x1 + 1), (y2 - y1 + 1));
return true;
}
@@ -2193,30 +2295,35 @@ static inline bool dumpQWindow(const SymbolGroupValue &v, std::wostream &str, vo
}
// Dump a std::string.
-static bool dumpStd_W_String(const SymbolGroupValue &v, int type, std::wostream &str)
+static bool dumpStd_W_String(const SymbolGroupValue &v, int type, std::wostream &str,
+ MemoryHandle **memoryHandle = 0)
{
// Find 'bx'. MSVC 2012 has 2 base classes, MSVC 2010 1,
// and MSVC2008 none
const SymbolGroupValue bx = SymbolGroupValue::findMember(v, "_Bx");
const int reserved = bx.parent()["_Myres"].intValue();
- if (!bx || reserved < 0)
+ int size = bx.parent()["_Mysize"].intValue();
+ if (!bx || reserved < 0 || size < 0)
return false;
+ const bool truncated = unsigned(size) > ExtensionContext::instance().parameters().maxStringLength;
+ if (truncated)
+ size = ExtensionContext::instance().parameters().maxStringLength;
// 'Buf' array for small strings, else pointer 'Ptr'.
const int bufSize = type == KT_StdString ? 16 : 8; // see basic_string.
- const SymbolGroupValue string = bufSize <= reserved ? bx["_Ptr"] : bx["_Buf"];
- if (!string)
+ const unsigned long memSize = type == KT_StdString ? size : 2 * size;
+ const ULONG64 address = reserved >= bufSize ? bx["_Ptr"].pointerValue() : bx["_Buf"].address();
+ if (!address)
return false;
- // Potentially re-code char arrays (preferably relying on
- // CDB to initially format the string array).
- const DumpParameterRecodeResult recode = checkCharArrayRecode(string);
- if (recode.buffer) {
- str << (type == KT_StdString ?
- quotedWStringFromCharData(recode.buffer, recode.size) :
- quotedWStringFromWCharData(recode.buffer, recode.size));
- delete [] recode.buffer;
- } else {
- str << string.value();
- }
+ unsigned char *memory = SymbolGroupValue::readMemory(v.context().dataspaces, address, memSize);
+ if (!memory)
+ return false;
+ str << (type == KT_StdString ?
+ quotedWStringFromCharData(memory, memSize, truncated) :
+ quotedWStringFromWCharData(memory, memSize, truncated));
+ if (memoryHandle)
+ *memoryHandle = new MemoryHandle(memory, memSize);
+ else
+ delete [] memory;
return true;
}
@@ -2323,9 +2430,8 @@ static bool dumpQVariant(const SymbolGroupValue &v, std::wostream &str, void **s
break;
case 10: // String
str << L"(QString) ";
- if (const SymbolGroupValue sv = dataV.typeCast(qtInfo.prependQtCoreModule("QString *").c_str())) {
+ if (const SymbolGroupValue sv = dataV.typeCast(qtInfo.prependQtCoreModule("QString *").c_str()))
dumpQString(sv, str);
- }
break;
case 11: //StringList: Dump container size
str << L"(QStringList) ";
@@ -2441,7 +2547,8 @@ static inline bool dumpQSharedPointer(const SymbolGroupValue &v, std::wostream &
unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
std::wstring *s, int *knownTypeIn /* = 0 */,
int *containerSizeIn /* = 0 */,
- void **specialInfoIn /* = 0 */)
+ void **specialInfoIn /* = 0 */,
+ MemoryHandle **memoryHandleIn /* = 0 */)
{
QTC_TRACE_IN
if (containerSizeIn)
@@ -2491,7 +2598,7 @@ unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
rc = dumpQChar(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
case KT_QByteArray:
- rc = dumpQByteArray(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
+ rc = dumpQByteArray(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
case KT_QFileInfo:
rc = dumpQFileInfo(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
@@ -2518,7 +2625,10 @@ unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
rc = dumpQScriptValue(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
case KT_QString:
- rc = dumpQString(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
+ rc = dumpQString(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
+ break;
+ case KT_QStringRef:
+ rc = dumpQStringRef(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
case KT_QColor:
rc = dumpQColor(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
@@ -2547,6 +2657,9 @@ unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
case KT_QLineF:
rc = dumpQLine_F(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
+ case KT_QImage:
+ rc = dumpQImage(v, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
+ break;
case KT_QRect:
rc = dumpQRect(v, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
@@ -2576,7 +2689,7 @@ unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
break;
case KT_StdString:
case KT_StdWString:
- rc = dumpStd_W_String(v, kt, str) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
+ rc = dumpStd_W_String(v, kt, str, memoryHandleIn) ? SymbolGroupNode::SimpleDumperOk : SymbolGroupNode::SimpleDumperFailed;
break;
default:
break;
@@ -2594,6 +2707,58 @@ unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
return rc;
}
+static inline void formatEditValue(int displayFormat, const MemoryHandle *mh, std::ostream &str)
+{
+ str << "editformat=\"" << displayFormat << "\",editvalue=\""
+ << mh->toHex() << "\",";
+}
+
+bool dumpEditValue(const SymbolGroupNode *n, const SymbolGroupValueContext &,
+ int desiredFormat, std::ostream &str)
+{
+ // Keep in sync watchhandler.cpp/showEditValue(), dumper.py.
+ enum DebuggerEditFormats {
+ DisplayImageData = 1,
+ DisplayUtf16String = 2,
+ DisplayImageFile = 3,
+ DisplayProcess = 4,
+ DisplayLatin1String = 5,
+ DisplayUtf8String = 6
+ };
+
+ enum Formats {
+ NormalFormat = 0,
+ StringSeparateWindow = 1 // corresponds to menu index.
+ };
+
+ if (desiredFormat <= 0)
+ return true;
+
+ if (SymbolGroupValue::verbose)
+ DebugPrint() << __FUNCTION__ << ' ' << n->name() << '/' << desiredFormat;
+
+ switch (n->dumperType()) {
+ case KT_QString:
+ case KT_StdWString:
+ if (desiredFormat == StringSeparateWindow)
+ if (const MemoryHandle *mh = n->memory())
+ formatEditValue(DisplayUtf16String, mh, str);
+ break;
+ case KT_QByteArray:
+ case KT_StdString:
+ if (desiredFormat == StringSeparateWindow)
+ if (const MemoryHandle *mh = n->memory())
+ formatEditValue(DisplayLatin1String, mh, str);
+ break;
+ case KT_QImage:
+ if (desiredFormat == 1) // Image.
+ if (const MemoryHandle *mh = n->memory())
+ formatEditValue(DisplayImageData, mh, str);
+ break;
+ }
+ return true;
+}
+
// Dump of QByteArray: Display as an array of unsigned chars.
static inline std::vector<AbstractSymbolGroupNode *>
complexDumpQByteArray(SymbolGroupNode *n, const SymbolGroupValueContext &ctx)
diff --git a/src/libs/qtcreatorcdbext/symbolgroupvalue.h b/src/libs/qtcreatorcdbext/symbolgroupvalue.h
index 3858bb4e26..d441d8a0ef 100644
--- a/src/libs/qtcreatorcdbext/symbolgroupvalue.h
+++ b/src/libs/qtcreatorcdbext/symbolgroupvalue.h
@@ -40,6 +40,7 @@
class AbstractSymbolGroupNode;
class SymbolGroupNode;
class SymbolGroup;
+class MemoryHandle;
struct SymbolGroupValueContext
{
@@ -248,7 +249,11 @@ unsigned dumpSimpleType(SymbolGroupNode *n, const SymbolGroupValueContext &ctx,
std::wstring *s,
int *knownType = 0,
int *containerSizeIn = 0,
- void **specialInfoIn = 0);
+ void **specialInfoIn = 0,
+ MemoryHandle **memoryHandleIn = 0);
+
+bool dumpEditValue(const SymbolGroupNode *n, const SymbolGroupValueContext &,
+ int desiredFormat, std::ostream &str);
enum AssignEncoding
{
diff --git a/src/libs/ssh/sftpchannel_p.h b/src/libs/ssh/sftpchannel_p.h
index ef16fca67c..c210e85870 100644
--- a/src/libs/ssh/sftpchannel_p.h
+++ b/src/libs/ssh/sftpchannel_p.h
@@ -48,14 +48,8 @@ class SftpChannelPrivate : public AbstractSshChannel
Q_OBJECT
friend class QSsh::SftpChannel;
public:
-
enum SftpState { Inactive, SubsystemRequested, InitSent, Initialized };
- virtual void handleChannelSuccess();
- virtual void handleChannelFailure();
-
- virtual void closeHook();
-
signals:
void initialized();
void initializationFailed(const QString &reason);
@@ -71,6 +65,9 @@ private:
SftpChannel *sftp);
SftpJobId createJob(const AbstractSftpOperation::Ptr &job);
+ virtual void handleChannelSuccess();
+ virtual void handleChannelFailure();
+
virtual void handleOpenSuccessInternal();
virtual void handleOpenFailureInternal(const QString &reason);
virtual void handleChannelDataInternal(const QByteArray &data);
@@ -79,6 +76,8 @@ private:
virtual void handleExitStatus(const SshChannelExitStatus &exitStatus);
virtual void handleExitSignal(const SshChannelExitSignal &signal);
+ virtual void closeHook();
+
void handleCurrentPacket();
void handleServerVersion();
void handleHandle();
diff --git a/src/libs/ssh/sftpoutgoingpacket.cpp b/src/libs/ssh/sftpoutgoingpacket.cpp
index d686313343..0ea613f125 100644
--- a/src/libs/ssh/sftpoutgoingpacket.cpp
+++ b/src/libs/ssh/sftpoutgoingpacket.cpp
@@ -154,7 +154,7 @@ SftpOutgoingPacket &SftpOutgoingPacket::generateCreateLink(const QString &filePa
SftpOutgoingPacket &SftpOutgoingPacket::generateOpenFile(const QString &path,
OpenType openType, SftpOverwriteMode mode, const QList<quint32> &attributes, quint32 requestId)
{
- quint32 pFlags;
+ quint32 pFlags = 0;
switch (openType) {
case Read:
pFlags = SSH_FXF_READ;
diff --git a/src/libs/ssh/ssh.pro b/src/libs/ssh/ssh.pro
index d0b90af988..477cf4b91f 100644
--- a/src/libs/ssh/ssh.pro
+++ b/src/libs/ssh/ssh.pro
@@ -29,7 +29,8 @@ SOURCES = $$PWD/sshsendfacility.cpp \
$$PWD/sshconnectionmanager.cpp \
$$PWD/sshkeypasswordretriever.cpp \
$$PWD/sftpfilesystemmodel.cpp \
- $$PWD/sshkeycreationdialog.cpp
+ $$PWD/sshkeycreationdialog.cpp \
+ $$PWD/sshdirecttcpiptunnel.cpp
HEADERS = $$PWD/sshsendfacility_p.h \
$$PWD/sshremoteprocess.h \
@@ -62,7 +63,9 @@ HEADERS = $$PWD/sshsendfacility_p.h \
$$PWD/sshkeypasswordretriever_p.h \
$$PWD/sftpfilesystemmodel.h \
$$PWD/sshkeycreationdialog.h \
- $$PWD/ssh_global.h
+ $$PWD/ssh_global.h \
+ $$PWD/sshdirecttcpiptunnel_p.h \
+ $$PWD/sshdirecttcpiptunnel.h
FORMS = $$PWD/sshkeycreationdialog.ui
diff --git a/src/libs/ssh/ssh.qbs b/src/libs/ssh/ssh.qbs
index 052e80fabc..e6b1b9ba6d 100644
--- a/src/libs/ssh/ssh.qbs
+++ b/src/libs/ssh/ssh.qbs
@@ -5,13 +5,8 @@ QtcLibrary {
name: "QtcSsh"
cpp.defines: base.concat(["QSSH_LIBRARY"]).concat(botanDefines)
+ cpp.includePaths: botanIncludes
cpp.dynamicLibraries: botanLibs
- cpp.includePaths: [
- ".",
- "..",
- "../..",
- buildDirectory
- ].concat(botanIncludes)
Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "network" ] }
@@ -19,33 +14,34 @@ QtcLibrary {
files: [
"sftpchannel.h", "sftpchannel_p.h", "sftpchannel.cpp",
"sftpdefs.cpp", "sftpdefs.h",
+ "sftpfilesystemmodel.cpp", "sftpfilesystemmodel.h",
"sftpincomingpacket.cpp", "sftpincomingpacket_p.h",
"sftpoperation.cpp", "sftpoperation_p.h",
"sftpoutgoingpacket.cpp", "sftpoutgoingpacket_p.h",
"sftppacket.cpp", "sftppacket_p.h",
+ "sshbotanconversions_p.h",
"sshcapabilities_p.h", "sshcapabilities.cpp",
"sshchannel.cpp", "sshchannel_p.h",
"sshchannelmanager.cpp", "sshchannelmanager_p.h",
"sshconnection.h", "sshconnection_p.h", "sshconnection.cpp",
"sshconnectionmanager.cpp", "sshconnectionmanager.h",
"sshcryptofacility.cpp", "sshcryptofacility_p.h",
+ "sshdirecttcpiptunnel.h", "sshdirecttcpiptunnel_p.h", "sshdirecttcpiptunnel.cpp",
+ "ssherrors.h",
+ "sshexception_p.h",
+ "sshincomingpacket_p.h", "sshincomingpacket.cpp",
+ "sshkeycreationdialog.cpp", "sshkeycreationdialog.h", "sshkeycreationdialog.ui",
"sshkeyexchange.cpp", "sshkeyexchange_p.h",
+ "sshkeygenerator.cpp", "sshkeygenerator.h",
+ "sshkeypasswordretriever.cpp",
"sshkeypasswordretriever_p.h",
"sshoutgoingpacket.cpp", "sshoutgoingpacket_p.h",
"sshpacket.cpp", "sshpacket_p.h",
"sshpacketparser.cpp", "sshpacketparser_p.h",
+ "sshpseudoterminal.h",
"sshremoteprocess.cpp", "sshremoteprocess.h", "sshremoteprocess_p.h",
"sshremoteprocessrunner.cpp", "sshremoteprocessrunner.h",
"sshsendfacility.cpp", "sshsendfacility_p.h",
- "sshkeypasswordretriever.cpp",
- "sshkeygenerator.cpp", "sshkeygenerator.h",
- "sshkeycreationdialog.cpp", "sshkeycreationdialog.h", "sshkeycreationdialog.ui",
- "sftpfilesystemmodel.cpp", "sftpfilesystemmodel.h",
- "sshincomingpacket_p.h", "sshincomingpacket.cpp",
- "ssherrors.h",
- "sshexception_p.h",
- "sshpseudoterminal.h",
- "sshbotanconversions_p.h"
].concat(botanFiles)
property var botanIncludes: ["../3rdparty"]
@@ -90,8 +86,6 @@ QtcLibrary {
}
ProductModule {
- Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "network"] }
- cpp.includePaths: [".."]
}
}
diff --git a/src/libs/ssh/sshcapabilities.cpp b/src/libs/ssh/sshcapabilities.cpp
index a989b2264b..c92af1ef63 100644
--- a/src/libs/ssh/sshcapabilities.cpp
+++ b/src/libs/ssh/sshcapabilities.cpp
@@ -41,7 +41,7 @@ namespace {
QByteArray listAsByteArray(const QList<QByteArray> &list)
{
QByteArray array;
- foreach(const QByteArray &elem, list)
+ foreach (const QByteArray &elem, list)
array += elem + ',';
if (!array.isEmpty())
array.remove(array.count() - 1, 1);
diff --git a/src/libs/ssh/sshchannel.cpp b/src/libs/ssh/sshchannel.cpp
index c3413492d4..da28ddc0af 100644
--- a/src/libs/ssh/sshchannel.cpp
+++ b/src/libs/ssh/sshchannel.cpp
@@ -39,18 +39,14 @@
namespace QSsh {
namespace Internal {
-namespace {
- const quint32 MinMaxPacketSize = 32768;
- const quint32 MaxPacketSize = 16 * 1024 * 1024;
- const quint32 InitialWindowSize = MaxPacketSize;
- const quint32 NoChannel = 0xffffffffu;
-} // anonymous namespace
+const quint32 MinMaxPacketSize = 32768;
+const quint32 NoChannel = 0xffffffffu;
AbstractSshChannel::AbstractSshChannel(quint32 channelId,
SshSendFacility &sendFacility)
: m_sendFacility(sendFacility), m_timeoutTimer(new QTimer(this)),
m_localChannel(channelId), m_remoteChannel(NoChannel),
- m_localWindowSize(InitialWindowSize), m_remoteWindowSize(0),
+ m_localWindowSize(initialWindowSize()), m_remoteWindowSize(0),
m_state(Inactive)
{
m_timeoutTimer->setSingleShot(true);
@@ -76,8 +72,7 @@ void AbstractSshChannel::requestSessionStart()
// with our cryptography stuff, it would have hit us before, on
// establishing the connection.
try {
- m_sendFacility.sendSessionPacket(m_localChannel, InitialWindowSize,
- MaxPacketSize);
+ m_sendFacility.sendSessionPacket(m_localChannel, initialWindowSize(), maxPacketSize());
setChannelState(SessionRequested);
m_timeoutTimer->start(ReplyTimeout);
} catch (Botan::Exception &e) {
@@ -97,6 +92,16 @@ void AbstractSshChannel::sendData(const QByteArray &data)
}
}
+quint32 AbstractSshChannel::initialWindowSize()
+{
+ return maxPacketSize();
+}
+
+quint32 AbstractSshChannel::maxPacketSize()
+{
+ return 16 * 1024 * 1024;
+}
+
void AbstractSshChannel::handleWindowAdjust(quint32 bytesToAdd)
{
checkChannelActive();
@@ -173,6 +178,7 @@ void AbstractSshChannel::handleChannelEof()
"Unexpected SSH_MSG_CHANNEL_EOF message.");
}
m_localWindowSize = 0;
+ emit eof();
}
void AbstractSshChannel::handleChannelClose()
@@ -223,10 +229,9 @@ int AbstractSshChannel::handleChannelOrExtendedChannelData(const QByteArray &dat
qWarning("Misbehaving server does not respect local window, clipping.");
m_localWindowSize -= bytesToDeliver;
- if (m_localWindowSize < MaxPacketSize) {
- m_localWindowSize += MaxPacketSize;
- m_sendFacility.sendWindowAdjustPacket(m_remoteChannel,
- MaxPacketSize);
+ if (m_localWindowSize < maxPacketSize()) {
+ m_localWindowSize += maxPacketSize();
+ m_sendFacility.sendWindowAdjustPacket(m_remoteChannel, maxPacketSize());
}
return bytesToDeliver;
}
@@ -255,7 +260,7 @@ void AbstractSshChannel::checkChannelActive()
quint32 AbstractSshChannel::maxDataSize() const
{
- return qMin(m_localWindowSize, MaxPacketSize);
+ return qMin(m_localWindowSize, maxPacketSize());
}
} // namespace Internal
diff --git a/src/libs/ssh/sshchannel_p.h b/src/libs/ssh/sshchannel_p.h
index ddb2570026..83765f94fe 100644
--- a/src/libs/ssh/sshchannel_p.h
+++ b/src/libs/ssh/sshchannel_p.h
@@ -52,17 +52,12 @@ public:
Inactive, SessionRequested, SessionEstablished, CloseRequested, Closed
};
- ChannelState channelState() const { return m_state; }
- void setChannelState(ChannelState state);
-
quint32 localChannelId() const { return m_localChannel; }
quint32 remoteChannel() const { return m_remoteChannel; }
virtual void handleChannelSuccess() = 0;
virtual void handleChannelFailure() = 0;
- virtual void closeHook() = 0;
-
void handleOpenSuccess(quint32 remoteChannelId, quint32 remoteWindowSize,
quint32 remoteMaxPacketSize);
void handleOpenFailure(const QString &reason);
@@ -73,20 +68,28 @@ public:
void handleChannelExtendedData(quint32 type, const QByteArray &data);
void handleChannelRequest(const SshIncomingPacket &packet);
- void requestSessionStart();
- void sendData(const QByteArray &data);
void closeChannel();
virtual ~AbstractSshChannel();
static const int ReplyTimeout = 10000; // milli seconds
+ ChannelState channelState() const { return m_state; }
signals:
void timeout();
+ void eof();
protected:
AbstractSshChannel(quint32 channelId, SshSendFacility &sendFacility);
+ void setChannelState(ChannelState state);
+
+ void requestSessionStart();
+ void sendData(const QByteArray &data);
+
+ static quint32 initialWindowSize();
+ static quint32 maxPacketSize();
+
quint32 maxDataSize() const;
void checkChannelActive();
@@ -102,7 +105,8 @@ private:
virtual void handleExitStatus(const SshChannelExitStatus &exitStatus) = 0;
virtual void handleExitSignal(const SshChannelExitSignal &signal) = 0;
- void setState(ChannelState newState);
+ virtual void closeHook() = 0;
+
void flushSendBuffer();
int handleChannelOrExtendedChannelData(const QByteArray &data);
diff --git a/src/libs/ssh/sshchannelmanager.cpp b/src/libs/ssh/sshchannelmanager.cpp
index b9d955a697..71df3987eb 100644
--- a/src/libs/ssh/sshchannelmanager.cpp
+++ b/src/libs/ssh/sshchannelmanager.cpp
@@ -31,6 +31,8 @@
#include "sftpchannel.h"
#include "sftpchannel_p.h"
+#include "sshdirecttcpiptunnel.h"
+#include "sshdirecttcpiptunnel_p.h"
#include "sshincomingpacket_p.h"
#include "sshremoteprocess.h"
#include "sshremoteprocess_p.h"
@@ -167,6 +169,15 @@ QSsh::SftpChannel::Ptr SshChannelManager::createSftpChannel()
return sftp;
}
+SshDirectTcpIpTunnel::Ptr SshChannelManager::createTunnel(quint16 remotePort,
+ const SshConnectionInfo &connectionInfo)
+{
+ SshDirectTcpIpTunnel::Ptr tunnel(new SshDirectTcpIpTunnel(m_nextLocalChannelId++, remotePort,
+ connectionInfo, m_sendFacility));
+ insertChannel(tunnel->d, tunnel);
+ return tunnel;
+}
+
void SshChannelManager::insertChannel(AbstractSshChannel *priv,
const QSharedPointer<QObject> &pub)
{
diff --git a/src/libs/ssh/sshchannelmanager_p.h b/src/libs/ssh/sshchannelmanager_p.h
index e8dad3ba5b..0b00b7b793 100644
--- a/src/libs/ssh/sshchannelmanager_p.h
+++ b/src/libs/ssh/sshchannelmanager_p.h
@@ -35,8 +35,9 @@
#include <QSharedPointer>
namespace QSsh {
-
class SftpChannel;
+class SshConnectionInfo;
+class SshDirectTcpIpTunnel;
class SshRemoteProcess;
namespace Internal {
@@ -54,8 +55,10 @@ public:
QSharedPointer<SshRemoteProcess> createRemoteProcess(const QByteArray &command);
QSharedPointer<SshRemoteProcess> createRemoteShell();
QSharedPointer<SftpChannel> createSftpChannel();
- int channelCount() const;
+ QSharedPointer<SshDirectTcpIpTunnel> createTunnel(quint16 remotePort,
+ const SshConnectionInfo &connectionInfo);
+ int channelCount() const;
enum CloseAllMode { CloseAllRegular, CloseAllAndReset };
int closeAllChannels(CloseAllMode mode);
diff --git a/src/libs/ssh/sshconnection.cpp b/src/libs/ssh/sshconnection.cpp
index cc654f702e..7d5ca7b584 100644
--- a/src/libs/ssh/sshconnection.cpp
+++ b/src/libs/ssh/sshconnection.cpp
@@ -34,8 +34,10 @@
#include "sshcapabilities_p.h"
#include "sshchannelmanager_p.h"
#include "sshcryptofacility_p.h"
+#include "sshdirecttcpiptunnel.h"
#include "sshexception_p.h"
#include "sshkeyexchange_p.h"
+#include "sshremoteprocess.h"
#include <botan/botan.h>
@@ -79,8 +81,10 @@ namespace {
SshConnectionParameters::SshConnectionParameters() :
- timeout(0), authenticationType(AuthenticationByKey), port(0), proxyType(NoProxy)
+ timeout(0), authenticationType(AuthenticationByKey), port(0)
{
+ options |= SshIgnoreDefaultProxy;
+ options |= SshEnableStrictConformanceChecks;
}
static inline bool equals(const SshConnectionParameters &p1, const SshConnectionParameters &p2)
@@ -191,6 +195,12 @@ QSharedPointer<SftpChannel> SshConnection::createSftpChannel()
return d->createSftpChannel();
}
+SshDirectTcpIpTunnel::Ptr SshConnection::createTunnel(quint16 remotePort)
+{
+ QSSH_ASSERT_AND_RETURN_VALUE(state() == Connected, SshDirectTcpIpTunnel::Ptr());
+ return d->createTunnel(remotePort);
+}
+
int SshConnection::closeAllChannels()
{
try {
@@ -217,8 +227,8 @@ SshConnectionPrivate::SshConnectionPrivate(SshConnection *conn,
m_conn(conn)
{
setupPacketHandlers();
- m_socket->setProxy(m_connParams.proxyType == SshConnectionParameters::DefaultProxy
- ? QNetworkProxy::DefaultProxy : QNetworkProxy::NoProxy);
+ m_socket->setProxy((m_connParams.options & SshIgnoreDefaultProxy)
+ ? QNetworkProxy::NoProxy : QNetworkProxy::DefaultProxy);
m_timeoutTimer.setSingleShot(true);
m_timeoutTimer.setInterval(m_connParams.timeout * 1000);
m_keepAliveTimer.setSingleShot(true);
@@ -331,7 +341,7 @@ void SshConnectionPrivate::handleIncomingData()
e.errorString);
} catch (Botan::Exception &e) {
closeConnection(SSH_DISCONNECT_BY_APPLICATION, SshInternalError, "",
- tr("Botan library exception: %1").arg(QString::fromAscii(e.what())));
+ tr("Botan library exception: %1").arg(QString::fromLatin1(e.what())));
}
}
@@ -390,21 +400,19 @@ void SshConnectionPrivate::handleServerId()
.arg(serverProtoVersion));
}
- // TODO: Remove #if on 2.7
-#if 0
- // Disable this check to accept older OpenSSH servers that do this wrong.
- if (serverProtoVersion == QLatin1String("2.0") && !hasCarriageReturn) {
- throw SshServerException(SSH_DISCONNECT_PROTOCOL_ERROR,
- "Identification string is invalid.",
- tr("Server identification string is invalid (missing carriage return)."));
- }
-#endif
+ if (m_connParams.options & SshEnableStrictConformanceChecks) {
+ if (serverProtoVersion == QLatin1String("2.0") && !hasCarriageReturn) {
+ throw SshServerException(SSH_DISCONNECT_PROTOCOL_ERROR,
+ "Identification string is invalid.",
+ tr("Server identification string is invalid (missing carriage return)."));
+ }
- if (serverProtoVersion == QLatin1String("1.99") && m_serverHasSentDataBeforeId) {
- throw SshServerException(SSH_DISCONNECT_PROTOCOL_ERROR,
- "No extra data preceding identification string allowed for 1.99.",
- tr("Server reports protocol version 1.99, but sends data "
- "before the identification string, which is not allowed."));
+ if (serverProtoVersion == QLatin1String("1.99") && m_serverHasSentDataBeforeId) {
+ throw SshServerException(SSH_DISCONNECT_PROTOCOL_ERROR,
+ "No extra data preceding identification string allowed for 1.99.",
+ tr("Server reports protocol version 1.99, but sends data "
+ "before the identification string, which is not allowed."));
+ }
}
m_keyExchange.reset(new SshKeyExchange(m_sendFacility));
@@ -464,9 +472,8 @@ void SshConnectionPrivate::handleKeyExchangeInitPacket()
// If the server sends a guessed packet, the guess must be wrong,
// because the algorithms we support require us to initiate the
// key exchange.
- if (m_keyExchange->sendDhInitPacket(m_incomingPacket)) {
+ if (m_keyExchange->sendDhInitPacket(m_incomingPacket))
m_ignoreNextPacket = true;
- }
m_keyExchangeState = DhInitSent;
}
@@ -774,6 +781,11 @@ QSharedPointer<SftpChannel> SshConnectionPrivate::createSftpChannel()
return m_channelManager->createSftpChannel();
}
+SshDirectTcpIpTunnel::Ptr SshConnectionPrivate::createTunnel(quint16 remotePort)
+{
+ return m_channelManager->createTunnel(remotePort, m_conn->connectionInfo());
+}
+
const quint64 SshConnectionPrivate::InvalidSeqNr = static_cast<quint64>(-1);
} // namespace Internal
diff --git a/src/libs/ssh/sshconnection.h b/src/libs/ssh/sshconnection.h
index 832b0003fc..9a70a02a0b 100644
--- a/src/libs/ssh/sshconnection.h
+++ b/src/libs/ssh/sshconnection.h
@@ -35,6 +35,7 @@
#include "ssh_global.h"
#include <QByteArray>
+#include <QFlags>
#include <QObject>
#include <QSharedPointer>
#include <QString>
@@ -42,16 +43,23 @@
namespace QSsh {
class SftpChannel;
+class SshDirectTcpIpTunnel;
class SshRemoteProcess;
namespace Internal {
class SshConnectionPrivate;
} // namespace Internal
+enum SshConnectionOption {
+ SshIgnoreDefaultProxy = 0x1,
+ SshEnableStrictConformanceChecks = 0x2
+};
+
+Q_DECLARE_FLAGS(SshConnectionOptions, SshConnectionOption)
+
class QSSH_EXPORT SshConnectionParameters
{
public:
- enum ProxyType { DefaultProxy, NoProxy };
enum AuthenticationType { AuthenticationByPassword, AuthenticationByKey };
SshConnectionParameters();
@@ -62,7 +70,7 @@ public:
int timeout; // In seconds.
AuthenticationType authenticationType;
quint16 port;
- ProxyType proxyType;
+ SshConnectionOptions options;
};
QSSH_EXPORT bool operator==(const SshConnectionParameters &p1, const SshConnectionParameters &p2);
@@ -102,6 +110,7 @@ public:
QSharedPointer<SshRemoteProcess> createRemoteProcess(const QByteArray &command);
QSharedPointer<SshRemoteProcess> createRemoteShell();
QSharedPointer<SftpChannel> createSftpChannel();
+ QSharedPointer<SshDirectTcpIpTunnel> createTunnel(quint16 remotePort);
// -1 if an error occurred, number of channels closed otherwise.
int closeAllChannels();
diff --git a/src/libs/ssh/sshconnection_p.h b/src/libs/ssh/sshconnection_p.h
index d51b60e5bf..2c21a0556c 100644
--- a/src/libs/ssh/sshconnection_p.h
+++ b/src/libs/ssh/sshconnection_p.h
@@ -33,7 +33,6 @@
#include "sshconnection.h"
#include "sshexception_p.h"
#include "sshincomingpacket_p.h"
-#include "sshremoteprocess.h"
#include "sshsendfacility_p.h"
#include <QHash>
@@ -49,6 +48,8 @@ QT_END_NAMESPACE
namespace QSsh {
class SftpChannel;
+class SshRemoteProcess;
+class SshDirectTcpIpTunnel;
namespace Internal {
class SshChannelManager;
@@ -87,6 +88,8 @@ public:
QSharedPointer<SshRemoteProcess> createRemoteProcess(const QByteArray &command);
QSharedPointer<SshRemoteProcess> createRemoteShell();
QSharedPointer<SftpChannel> createSftpChannel();
+ QSharedPointer<SshDirectTcpIpTunnel> createTunnel(quint16 remotePort);
+
SshStateInternal state() const { return m_state; }
SshError error() const { return m_error; }
QString errorString() const { return m_errorString; }
diff --git a/src/libs/ssh/sshcryptofacility.cpp b/src/libs/ssh/sshcryptofacility.cpp
index 7f62018dd7..255ef7ef74 100644
--- a/src/libs/ssh/sshcryptofacility.cpp
+++ b/src/libs/ssh/sshcryptofacility.cpp
@@ -217,14 +217,16 @@ bool SshEncryptionFacility::createAuthenticationKeyFromPKCS8(const QByteArray &p
try {
Pipe pipe;
pipe.process_msg(convertByteArray(privKeyFileContents), privKeyFileContents.size());
- const PrivateKeyPtr authKey = loadPkcs8PrivateKey(pipe, m_rng, SshKeyPasswordRetriever());
- if (DSA_PrivateKey * const dsaKey = dynamic_cast<DSA_PrivateKey *>(authKey.data())) {
+ Private_Key * const key = PKCS8::load_key(pipe, m_rng, SshKeyPasswordRetriever());
+ if (DSA_PrivateKey * const dsaKey = dynamic_cast<DSA_PrivateKey *>(key)) {
m_authKeyAlgoName = SshCapabilities::PubKeyDss;
+ m_authKey.reset(dsaKey);
pubKeyParams << dsaKey->group_p() << dsaKey->group_q()
<< dsaKey->group_g() << dsaKey->get_y();
allKeyParams << pubKeyParams << dsaKey->get_x();
- } else if (RSA_PrivateKey * const rsaKey = dynamic_cast<RSA_PrivateKey *>(authKey.data())) {
+ } else if (RSA_PrivateKey * const rsaKey = dynamic_cast<RSA_PrivateKey *>(key)) {
m_authKeyAlgoName = SshCapabilities::PubKeyRsa;
+ m_authKey.reset(rsaKey);
pubKeyParams << rsaKey->get_e() << rsaKey->get_n();
allKeyParams << pubKeyParams << rsaKey->get_p() << rsaKey->get_q()
<< rsaKey->get_d();
@@ -232,7 +234,6 @@ bool SshEncryptionFacility::createAuthenticationKeyFromPKCS8(const QByteArray &p
qWarning("%s: Unexpected code flow, expected success or exception.", Q_FUNC_INFO);
return false;
}
- m_authKey = authKey;
} catch (const Botan::Exception &ex) {
error = QLatin1String(ex.what());
return false;
@@ -289,13 +290,15 @@ bool SshEncryptionFacility::createAuthenticationKeyFromOpenSSL(const QByteArray
if (m_authKeyAlgoName == SshCapabilities::PubKeyDss) {
BigInt p, q, g, y, x;
sequence.decode (p).decode (q).decode (g).decode (y).decode (x);
- m_authKey = createDsaPrivateKey(m_rng, DL_Group(p, q, g), x);
+ DSA_PrivateKey * const dsaKey = new DSA_PrivateKey(m_rng, DL_Group(p, q, g), x);
+ m_authKey.reset(dsaKey);
pubKeyParams << p << q << g << y;
allKeyParams << pubKeyParams << x;
} else {
BigInt p, q, e, d, n;
sequence.decode(n).decode(e).decode(d).decode(p).decode(q);
- m_authKey = createRsaPrivateKey(m_rng, p, q, e, d, n);
+ RSA_PrivateKey * const rsaKey = new RSA_PrivateKey(m_rng, p, q, e, d, n);
+ m_authKey.reset(rsaKey);
pubKeyParams << e << n;
allKeyParams << pubKeyParams << p << q << d;
}
diff --git a/src/libs/ssh/sshcryptofacility_p.h b/src/libs/ssh/sshcryptofacility_p.h
index 9dc58df060..704a4ee475 100644
--- a/src/libs/ssh/sshcryptofacility_p.h
+++ b/src/libs/ssh/sshcryptofacility_p.h
@@ -116,7 +116,7 @@ private:
QByteArray m_authKeyAlgoName;
QByteArray m_authPubKeyBlob;
QByteArray m_cachedPrivKeyContents;
- QSharedPointer<Botan::Private_Key> m_authKey;
+ QScopedPointer<Botan::Private_Key> m_authKey;
mutable Botan::AutoSeeded_RNG m_rng;
};
diff --git a/src/libs/ssh/sshdirecttcpiptunnel.cpp b/src/libs/ssh/sshdirecttcpiptunnel.cpp
new file mode 100644
index 0000000000..ef0cada653
--- /dev/null
+++ b/src/libs/ssh/sshdirecttcpiptunnel.cpp
@@ -0,0 +1,194 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+#include "sshdirecttcpiptunnel.h"
+#include "sshdirecttcpiptunnel_p.h"
+
+#include "sshincomingpacket_p.h"
+#include "sshsendfacility_p.h"
+
+#include <QTimer>
+
+namespace QSsh {
+namespace Internal {
+
+SshDirectTcpIpTunnelPrivate::SshDirectTcpIpTunnelPrivate(quint32 channelId, quint16 remotePort,
+ const SshConnectionInfo &connectionInfo, SshSendFacility &sendFacility)
+ : AbstractSshChannel(channelId, sendFacility),
+ m_remotePort(remotePort),
+ m_connectionInfo(connectionInfo)
+{
+ connect(this, SIGNAL(eof()), SLOT(handleEof()));
+}
+
+void SshDirectTcpIpTunnelPrivate::handleChannelSuccess()
+{
+ throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
+ "Unexpected SSH_MSG_CHANNEL_SUCCESS message.");
+}
+
+void SshDirectTcpIpTunnelPrivate::handleChannelFailure()
+{
+ throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_PROTOCOL_ERROR,
+ "Unexpected SSH_MSG_CHANNEL_FAILURE message.");
+}
+
+void SshDirectTcpIpTunnelPrivate::handleOpenSuccessInternal()
+{
+ emit initialized();
+}
+
+void SshDirectTcpIpTunnelPrivate::handleOpenFailureInternal(const QString &reason)
+{
+ emit error(reason);
+ closeChannel();
+}
+
+void SshDirectTcpIpTunnelPrivate::handleChannelDataInternal(const QByteArray &data)
+{
+ m_data += data;
+ emit readyRead();
+}
+
+void SshDirectTcpIpTunnelPrivate::handleChannelExtendedDataInternal(quint32 type,
+ const QByteArray &data)
+{
+ qDebug("%s: Unexpected extended channel data. Type is %u, content is '%s'.", Q_FUNC_INFO, type,
+ data.constData());
+}
+
+void SshDirectTcpIpTunnelPrivate::handleExitStatus(const SshChannelExitStatus &exitStatus)
+{
+ qDebug("%s: Unexpected exit status %d.", Q_FUNC_INFO, exitStatus.exitStatus);
+}
+
+void SshDirectTcpIpTunnelPrivate::handleExitSignal(const SshChannelExitSignal &signal)
+{
+ qDebug("%s: Unexpected exit signal %s.", Q_FUNC_INFO, signal.signal.constData());
+}
+
+void SshDirectTcpIpTunnelPrivate::closeHook()
+{
+ emit closed();
+}
+
+void SshDirectTcpIpTunnelPrivate::handleEof()
+{
+ /*
+ * For some reason, the OpenSSH server only sends EOF when the remote port goes away,
+ * but does not close the channel, even though it becomes useless in that case.
+ * So we close it ourselves.
+ */
+ closeChannel();
+}
+
+} // namespace Internal
+
+using namespace Internal;
+
+SshDirectTcpIpTunnel::SshDirectTcpIpTunnel(quint32 channelId, quint16 remotePort,
+ const SshConnectionInfo &connectionInfo, SshSendFacility &sendFacility)
+ : d(new SshDirectTcpIpTunnelPrivate(channelId, remotePort, connectionInfo, sendFacility))
+{
+ connect(d, SIGNAL(initialized()), SIGNAL(initialized()), Qt::QueuedConnection);
+ connect(d, SIGNAL(readyRead()), SIGNAL(readyRead()), Qt::QueuedConnection);
+ connect(d, SIGNAL(closed()), SIGNAL(tunnelClosed()), Qt::QueuedConnection);
+ connect(d, SIGNAL(error(QString)), SLOT(handleError(QString)), Qt::QueuedConnection);
+}
+
+SshDirectTcpIpTunnel::~SshDirectTcpIpTunnel()
+{
+ d->closeChannel();
+ delete d;
+}
+
+bool SshDirectTcpIpTunnel::atEnd() const
+{
+ return QIODevice::atEnd() && d->m_data.isEmpty();
+}
+
+qint64 SshDirectTcpIpTunnel::bytesAvailable() const
+{
+ return QIODevice::bytesAvailable() + d->m_data.count();
+}
+
+bool SshDirectTcpIpTunnel::canReadLine() const
+{
+ return QIODevice::canReadLine() || d->m_data.contains('\n');
+}
+
+void SshDirectTcpIpTunnel::close()
+{
+ d->closeChannel();
+ QIODevice::close();
+}
+
+void SshDirectTcpIpTunnel::initialize()
+{
+ QSSH_ASSERT_AND_RETURN(d->channelState() == AbstractSshChannel::Inactive);
+
+ try {
+ QIODevice::open(QIODevice::ReadWrite);
+ d->m_sendFacility.sendDirectTcpIpPacket(d->localChannelId(), d->initialWindowSize(),
+ d->maxPacketSize(), d->m_connectionInfo.peerAddress.toString().toUtf8(),
+ d->m_remotePort, d->m_connectionInfo.localAddress.toString().toUtf8(),
+ d->m_connectionInfo.localPort);
+ d->setChannelState(AbstractSshChannel::SessionRequested);
+ d->m_timeoutTimer->start(d->ReplyTimeout);
+ } catch (Botan::Exception &e) { // Won't happen, but let's play it safe.
+ qDebug("Botan error: %s", e.what());
+ d->closeChannel();
+ }
+}
+
+qint64 SshDirectTcpIpTunnel::readData(char *data, qint64 maxlen)
+{
+ const qint64 bytesRead = qMin(qint64(d->m_data.count()), maxlen);
+ memcpy(data, d->m_data.constData(), bytesRead);
+ d->m_data.remove(0, bytesRead);
+ return bytesRead;
+}
+
+qint64 SshDirectTcpIpTunnel::writeData(const char *data, qint64 len)
+{
+ QSSH_ASSERT_AND_RETURN_VALUE(d->channelState() == AbstractSshChannel::SessionEstablished, 0);
+
+ d->sendData(QByteArray(data, len));
+ return len;
+}
+
+void SshDirectTcpIpTunnel::handleError(const QString &reason)
+{
+ setErrorString(reason);
+ emit error(reason);
+}
+
+} // namespace QSsh
diff --git a/src/libs/ssh/sshdirecttcpiptunnel.h b/src/libs/ssh/sshdirecttcpiptunnel.h
new file mode 100644
index 0000000000..b451c96afc
--- /dev/null
+++ b/src/libs/ssh/sshdirecttcpiptunnel.h
@@ -0,0 +1,90 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+
+#ifndef SSHDIRECTTCPIPTUNNEL_H
+#define SSHDIRECTTCPIPTUNNEL_H
+
+#include "ssh_global.h"
+
+#include <QIODevice>
+#include <QSharedPointer>
+
+namespace QSsh {
+class SshConnectionInfo;
+
+namespace Internal {
+class SshChannelManager;
+class SshDirectTcpIpTunnelPrivate;
+class SshSendFacility;
+} // namespace Internal
+
+class QSSH_EXPORT SshDirectTcpIpTunnel : public QIODevice
+{
+ Q_OBJECT
+
+ friend class Internal::SshChannelManager;
+
+public:
+ typedef QSharedPointer<SshDirectTcpIpTunnel> Ptr;
+
+ ~SshDirectTcpIpTunnel();
+
+ // QIODevice stuff
+ bool atEnd() const;
+ qint64 bytesAvailable() const;
+ bool canReadLine() const;
+ void close();
+ bool isSequential() const { return true; }
+
+ void initialize();
+
+signals:
+ void initialized();
+ void error(const QString &reason);
+ void tunnelClosed();
+
+private:
+ SshDirectTcpIpTunnel(quint32 channelId, quint16 remotePort,
+ const SshConnectionInfo &connectionInfo, Internal::SshSendFacility &sendFacility);
+
+ // QIODevice stuff
+ qint64 readData(char *data, qint64 maxlen);
+ qint64 writeData(const char *data, qint64 len);
+
+ Q_SLOT void handleError(const QString &reason);
+
+ Internal::SshDirectTcpIpTunnelPrivate * const d;
+};
+
+} // namespace QSsh
+
+#endif // SSHDIRECTTCPIPTUNNEL_H
diff --git a/src/libs/ssh/sshdirecttcpiptunnel_p.h b/src/libs/ssh/sshdirecttcpiptunnel_p.h
new file mode 100644
index 0000000000..7122c4dc2a
--- /dev/null
+++ b/src/libs/ssh/sshdirecttcpiptunnel_p.h
@@ -0,0 +1,84 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+#ifndef DIRECTTCPIPCHANNEL_P_H
+#define DIRECTTCPIPCHANNEL_P_H
+
+#include "sshchannel_p.h"
+
+#include "sshconnection.h"
+
+namespace QSsh {
+class SshDirectTcpIpTunnel;
+
+namespace Internal {
+
+class SshDirectTcpIpTunnelPrivate : public AbstractSshChannel
+{
+ Q_OBJECT
+
+ friend class QSsh::SshDirectTcpIpTunnel;
+
+public:
+ explicit SshDirectTcpIpTunnelPrivate(quint32 channelId, quint16 remotePort,
+ const SshConnectionInfo &connectionInfo, SshSendFacility &sendFacility);
+
+signals:
+ void initialized();
+ void readyRead();
+ void error(const QString &reason);
+ void closed();
+
+private slots:
+ void handleEof();
+
+private:
+ void handleChannelSuccess();
+ void handleChannelFailure();
+
+ void handleOpenSuccessInternal();
+ void handleOpenFailureInternal(const QString &reason);
+ void handleChannelDataInternal(const QByteArray &data);
+ void handleChannelExtendedDataInternal(quint32 type, const QByteArray &data);
+ void handleExitStatus(const SshChannelExitStatus &exitStatus);
+ void handleExitSignal(const SshChannelExitSignal &signal);
+
+ void closeHook();
+
+ const quint16 m_remotePort;
+ const SshConnectionInfo m_connectionInfo;
+ QByteArray m_data;
+};
+
+} // namespace Internal
+} // namespace QSsh
+
+#endif // DIRECTTCPIPCHANNEL_P_H
diff --git a/src/libs/ssh/sshkeycreationdialog.cpp b/src/libs/ssh/sshkeycreationdialog.cpp
index c6eae3b41e..7ffa2c9b4b 100644
--- a/src/libs/ssh/sshkeycreationdialog.cpp
+++ b/src/libs/ssh/sshkeycreationdialog.cpp
@@ -81,11 +81,10 @@ void SshKeyCreationDialog::generateKeys()
m_ui->comboBox->currentText().toUShort());
QApplication::restoreOverrideCursor();
- if (success) {
+ if (success)
saveKeys();
- } else {
+ else
QMessageBox::critical(this, tr("Key Generation Failed"), m_keyGenerator->error());
- }
}
void SshKeyCreationDialog::handleBrowseButtonClicked()
diff --git a/src/libs/ssh/sshkeyexchange.cpp b/src/libs/ssh/sshkeyexchange.cpp
index 1ebbbc45e6..b21f1ab48f 100644
--- a/src/libs/ssh/sshkeyexchange.cpp
+++ b/src/libs/ssh/sshkeyexchange.cpp
@@ -135,7 +135,8 @@ bool SshKeyExchange::sendDhInitPacket(const SshIncomingPacket &serverKexInit)
kexInitParams.compressionAlgorithmsServerToClient.names);
AutoSeeded_RNG rng;
- m_dhKey = createDhPrivateKey(rng, DL_Group(botanKeyExchangeAlgoName(keyAlgo)));
+ m_dhKey.reset(new DH_PrivateKey(rng,
+ DL_Group(botanKeyExchangeAlgoName(keyAlgo))));
m_serverKexInitPayload = serverKexInit.payLoad();
m_sendFacility.sendKeyDhInitPacket(m_dhKey->get_y());
@@ -182,24 +183,28 @@ void SshKeyExchange::sendNewKeysPacket(const SshIncomingPacket &dhReply,
printData("H", m_h);
#endif // CREATOR_SSH_DEBUG
- QSharedPointer<Public_Key> publicKey;
- QByteArray algorithm;
+ QScopedPointer<Public_Key> sigKey;
+ QScopedPointer<PK_Verifier> verifier;
if (m_serverHostKeyAlgo == SshCapabilities::PubKeyDss) {
const DL_Group group(reply.parameters.at(0), reply.parameters.at(1),
reply.parameters.at(2));
- publicKey = createDsaPublicKey(group, reply.parameters.at(3));
- algorithm = SshCapabilities::PubKeyDss;
+ DSA_PublicKey * const dsaKey
+ = new DSA_PublicKey(group, reply.parameters.at(3));
+ sigKey.reset(dsaKey);
+ verifier.reset(new PK_Verifier(*dsaKey, botanEmsaAlgoName(SshCapabilities::PubKeyDss)));
} else if (m_serverHostKeyAlgo == SshCapabilities::PubKeyRsa) {
- publicKey = createRsaPublicKey(reply.parameters.at(1), reply.parameters.at(0));
- algorithm = SshCapabilities::PubKeyRsa;
+ RSA_PublicKey * const rsaKey
+ = new RSA_PublicKey(reply.parameters.at(1), reply.parameters.at(0));
+ sigKey.reset(rsaKey);
+ verifier.reset(new PK_Verifier(*rsaKey, botanEmsaAlgoName(SshCapabilities::PubKeyRsa)));
} else {
Q_ASSERT(!"Impossible: Neither DSS nor RSA!");
}
const byte * const botanH = convertByteArray(m_h);
const Botan::byte * const botanSig
= convertByteArray(reply.signatureBlob);
- if (!PK_Verifier(*publicKey, botanEmsaAlgoName(algorithm)).verify_message(botanH, m_h.size(),
- botanSig, reply.signatureBlob.size())) {
+ if (!verifier->verify_message(botanH, m_h.size(), botanSig,
+ reply.signatureBlob.size())) {
throw SSH_SERVER_EXCEPTION(SSH_DISCONNECT_KEY_EXCHANGE_FAILED,
"Invalid signature in SSH_MSG_KEXDH_REPLY packet.");
}
diff --git a/src/libs/ssh/sshkeyexchange_p.h b/src/libs/ssh/sshkeyexchange_p.h
index 9b99061fcb..019bdc196d 100644
--- a/src/libs/ssh/sshkeyexchange_p.h
+++ b/src/libs/ssh/sshkeyexchange_p.h
@@ -32,7 +32,6 @@
#include <QByteArray>
#include <QScopedPointer>
-#include <QSharedPointer>
namespace Botan {
class DH_PrivateKey;
@@ -71,7 +70,7 @@ private:
QByteArray m_serverId;
QByteArray m_clientKexInitPayload;
QByteArray m_serverKexInitPayload;
- QSharedPointer<Botan::DH_PrivateKey> m_dhKey;
+ QScopedPointer<Botan::DH_PrivateKey> m_dhKey;
QByteArray m_k;
QByteArray m_h;
QByteArray m_serverHostKeyAlgo;
diff --git a/src/libs/ssh/sshkeygenerator.cpp b/src/libs/ssh/sshkeygenerator.cpp
index c81ad4758a..736cc04ff7 100644
--- a/src/libs/ssh/sshkeygenerator.cpp
+++ b/src/libs/ssh/sshkeygenerator.cpp
@@ -59,9 +59,9 @@ bool SshKeyGenerator::generateKeys(KeyType type, PrivateKeyFormat format, int ke
AutoSeeded_RNG rng;
KeyPtr key;
if (m_type == Rsa)
- key = createRsaPrivateKey(rng, keySize);
+ key = KeyPtr(new RSA_PrivateKey(rng, keySize));
else
- key = createDsaPrivateKey(rng, DL_Group(rng, DL_Group::DSA_Kosherizer, keySize));
+ key = KeyPtr(new DSA_PrivateKey(rng, DL_Group(rng, DL_Group::DSA_Kosherizer, keySize)));
switch (format) {
case Pkcs8:
generatePkcs8KeyStrings(key, rng);
@@ -76,7 +76,7 @@ bool SshKeyGenerator::generateKeys(KeyType type, PrivateKeyFormat format, int ke
}
return true;
} catch (Botan::Exception &e) {
- m_error = tr("Error generating key: %1").arg(QString::fromAscii(e.what()));
+ m_error = tr("Error generating key: %1").arg(QString::fromLatin1(e.what()));
return false;
}
}
diff --git a/src/libs/ssh/sshoutgoingpacket.cpp b/src/libs/ssh/sshoutgoingpacket.cpp
index 7e09256c62..d1c654a4a4 100644
--- a/src/libs/ssh/sshoutgoingpacket.cpp
+++ b/src/libs/ssh/sshoutgoingpacket.cpp
@@ -142,7 +142,16 @@ void SshOutgoingPacket::generateSessionPacket(quint32 channelId,
quint32 windowSize, quint32 maxPacketSize)
{
init(SSH_MSG_CHANNEL_OPEN).appendString("session").appendInt(channelId)
- .appendInt(windowSize).appendInt(maxPacketSize).finalize();
+ .appendInt(windowSize).appendInt(maxPacketSize).finalize();
+}
+
+void SshOutgoingPacket::generateDirectTcpIpPacket(quint32 channelId, quint32 windowSize,
+ quint32 maxPacketSize, const QByteArray &remoteHost, quint32 remotePort,
+ const QByteArray &localIpAddress, quint32 localPort)
+{
+ init(SSH_MSG_CHANNEL_OPEN).appendString("direct-tcpip").appendInt(channelId)
+ .appendInt(windowSize).appendInt(maxPacketSize).appendString(remoteHost)
+ .appendInt(remotePort).appendString(localIpAddress).appendInt(localPort).finalize();
}
void SshOutgoingPacket::generateEnvPacket(quint32 remoteChannel,
diff --git a/src/libs/ssh/sshoutgoingpacket_p.h b/src/libs/ssh/sshoutgoingpacket_p.h
index a89fa902dc..03f54cb76d 100644
--- a/src/libs/ssh/sshoutgoingpacket_p.h
+++ b/src/libs/ssh/sshoutgoingpacket_p.h
@@ -61,6 +61,9 @@ public:
void generateInvalidMessagePacket();
void generateSessionPacket(quint32 channelId, quint32 windowSize,
quint32 maxPacketSize);
+ void generateDirectTcpIpPacket(quint32 channelId, quint32 windowSize,
+ quint32 maxPacketSize, const QByteArray &remoteHost, quint32 remotePort,
+ const QByteArray &localIpAddress, quint32 localPort);
void generateEnvPacket(quint32 remoteChannel, const QByteArray &var,
const QByteArray &value);
void generatePtyRequestPacket(quint32 remoteChannel,
diff --git a/src/libs/ssh/sshremoteprocess.cpp b/src/libs/ssh/sshremoteprocess.cpp
index cddec452f2..f3b58df76d 100644
--- a/src/libs/ssh/sshremoteprocess.cpp
+++ b/src/libs/ssh/sshremoteprocess.cpp
@@ -166,6 +166,7 @@ void SshRemoteProcess::init()
connect(d, SIGNAL(readyReadStandardError()), this,
SIGNAL(readyReadStandardError()), Qt::QueuedConnection);
connect(d, SIGNAL(closed(int)), this, SIGNAL(closed(int)), Qt::QueuedConnection);
+ connect(d, SIGNAL(eof()), SIGNAL(readChannelFinished()), Qt::QueuedConnection);
}
void SshRemoteProcess::addToEnvironment(const QByteArray &var, const QByteArray &value)
@@ -205,7 +206,7 @@ void SshRemoteProcess::sendSignal(Signal signal)
d->m_sendFacility.sendChannelSignalPacket(d->remoteChannel(), signalString);
}
} catch (Botan::Exception &e) {
- setErrorString(QString::fromAscii(e.what()));
+ setErrorString(QString::fromLatin1(e.what()));
d->closeChannel();
}
}
diff --git a/src/libs/ssh/sshremoteprocess_p.h b/src/libs/ssh/sshremoteprocess_p.h
index 4022262214..b91fd18c5f 100644
--- a/src/libs/ssh/sshremoteprocess_p.h
+++ b/src/libs/ssh/sshremoteprocess_p.h
@@ -53,13 +53,6 @@ public:
NotYetStarted, ExecRequested, StartFailed, Running, Exited
};
- virtual void handleChannelSuccess();
- virtual void handleChannelFailure();
-
- virtual void closeHook();
-
- QByteArray &data();
-
signals:
void started();
void readyRead();
@@ -73,6 +66,9 @@ private:
SshRemoteProcessPrivate(quint32 channelId, SshSendFacility &sendFacility,
SshRemoteProcess *proc);
+ virtual void handleChannelSuccess();
+ virtual void handleChannelFailure();
+
virtual void handleOpenSuccessInternal();
virtual void handleOpenFailureInternal(const QString &reason);
virtual void handleChannelDataInternal(const QByteArray &data);
@@ -81,8 +77,11 @@ private:
virtual void handleExitStatus(const SshChannelExitStatus &exitStatus);
virtual void handleExitSignal(const SshChannelExitSignal &signal);
+ virtual void closeHook();
+
void init();
void setProcState(ProcessState newState);
+ QByteArray &data();
QProcess::ProcessChannel m_readChannel;
diff --git a/src/libs/ssh/sshsendfacility.cpp b/src/libs/ssh/sshsendfacility.cpp
index cbd0f54703..8b600009e4 100644
--- a/src/libs/ssh/sshsendfacility.cpp
+++ b/src/libs/ssh/sshsendfacility.cpp
@@ -149,6 +149,15 @@ void SshSendFacility::sendSessionPacket(quint32 channelId, quint32 windowSize,
sendPacket();
}
+void SshSendFacility::sendDirectTcpIpPacket(quint32 channelId, quint32 windowSize,
+ quint32 maxPacketSize, const QByteArray &remoteHost, quint32 remotePort,
+ const QByteArray &localIpAddress, quint32 localPort)
+{
+ m_outgoingPacket.generateDirectTcpIpPacket(channelId, windowSize, maxPacketSize, remoteHost,
+ remotePort, localIpAddress, localPort);
+ sendPacket();
+}
+
void SshSendFacility::sendPtyRequestPacket(quint32 remoteChannel,
const SshPseudoTerminal &terminal)
{
diff --git a/src/libs/ssh/sshsendfacility_p.h b/src/libs/ssh/sshsendfacility_p.h
index 9996b50e80..6312b8e50f 100644
--- a/src/libs/ssh/sshsendfacility_p.h
+++ b/src/libs/ssh/sshsendfacility_p.h
@@ -68,6 +68,9 @@ public:
void sendInvalidPacket();
void sendSessionPacket(quint32 channelId, quint32 windowSize,
quint32 maxPacketSize);
+ void sendDirectTcpIpPacket(quint32 channelId, quint32 windowSize, quint32 maxPacketSize,
+ const QByteArray &remoteHost, quint32 remotePort, const QByteArray &localIpAddress,
+ quint32 localPort);
void sendPtyRequestPacket(quint32 remoteChannel,
const SshPseudoTerminal &terminal);
void sendEnvPacket(quint32 remoteChannel, const QByteArray &var,
diff --git a/src/libs/utils/basetreeview.cpp b/src/libs/utils/basetreeview.cpp
index 09ea3dd3ab..fd3f35e35a 100644
--- a/src/libs/utils/basetreeview.cpp
+++ b/src/libs/utils/basetreeview.cpp
@@ -30,11 +30,31 @@
#include "basetreeview.h"
#include <QHeaderView>
+#include <QItemDelegate>
+#include <QLabel>
#include <QMenu>
#include <QMouseEvent>
namespace Utils {
+class BaseTreeViewDelegate : public QItemDelegate
+{
+public:
+ BaseTreeViewDelegate() {}
+
+ QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
+ const QModelIndex &index) const
+ {
+ Q_UNUSED(option);
+ QLabel *label = new QLabel(parent);
+ label->setAutoFillBackground(true);
+ label->setTextInteractionFlags(Qt::TextSelectableByMouse
+ | Qt::LinksAccessibleByMouse);
+ label->setText(index.data().toString());
+ return label;
+ }
+};
+
BaseTreeView::BaseTreeView(QWidget *parent)
: QTreeView(parent)
{
@@ -44,7 +64,7 @@ BaseTreeView::BaseTreeView(QWidget *parent)
setIconSize(QSize(10, 10));
setSelectionMode(QAbstractItemView::ExtendedSelection);
setUniformRowHeights(true);
-
+ setItemDelegate(new BaseTreeViewDelegate);
header()->setDefaultAlignment(Qt::AlignLeft);
header()->setClickable(true);
@@ -133,4 +153,16 @@ void BaseTreeView::reset()
resizeColumnsToContents();
}
+QModelIndexList BaseTreeView::activeRows() const
+{
+ QItemSelectionModel *selection = selectionModel();
+ QModelIndexList indices = selection->selectedRows();
+ if (indices.isEmpty()) {
+ QModelIndex current = selection->currentIndex();
+ if (current.isValid())
+ indices.append(current);
+ }
+ return indices;
+}
+
} // namespace Utils
diff --git a/src/libs/utils/basetreeview.h b/src/libs/utils/basetreeview.h
index d4ae2e1aee..c488e211fe 100644
--- a/src/libs/utils/basetreeview.h
+++ b/src/libs/utils/basetreeview.h
@@ -46,6 +46,7 @@ public:
void setAlwaysAdjustColumnsAction(QAction *action);
virtual void addBaseContextActions(QMenu *menu);
bool handleBaseContextAction(QAction *action);
+ QModelIndexList activeRows() const;
void setModel(QAbstractItemModel *model);
virtual void rowActivated(const QModelIndex &) {}
diff --git a/src/libs/utils/buildablehelperlibrary.cpp b/src/libs/utils/buildablehelperlibrary.cpp
index e1022d16df..3c7a51bc81 100644
--- a/src/libs/utils/buildablehelperlibrary.cpp
+++ b/src/libs/utils/buildablehelperlibrary.cpp
@@ -37,8 +37,9 @@
#include <QDateTime>
#include <utils/environment.h>
-#include <utils/synchronousprocess.h>
#include <utils/fileutils.h>
+#include <utils/hostosinfo.h>
+#include <utils/synchronousprocess.h>
#include <QDesktopServices>
#include <QDebug>
@@ -55,9 +56,8 @@ Utils::FileName BuildableHelperLibrary::findSystemQt(const Utils::Environment &e
foreach (const QString &possibleCommand, possibleQMakeCommands()) {
const QFileInfo qmake(prefix + possibleCommand);
if (qmake.exists()) {
- if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull()) {
+ if (!qtVersionForQMake(qmake.absoluteFilePath()).isNull())
return Utils::FileName(qmake);
- }
}
}
}
@@ -122,15 +122,14 @@ QString BuildableHelperLibrary::qtVersionForQMake(const QString &qmakePath, bool
QStringList BuildableHelperLibrary::possibleQMakeCommands()
{
// On windows no one has renamed qmake, right?
-#ifdef Q_OS_WIN
- return QStringList(QLatin1String("qmake.exe"));
-#else
+ if (HostOsInfo::isWindowsHost())
+ return QStringList(QLatin1String("qmake.exe"));
+
// On unix some distributions renamed qmake to avoid clashes
QStringList result;
result << QLatin1String("qmake-qt4") << QLatin1String("qmake4")
<< QLatin1String("qmake-qt5") << QLatin1String("qmake5") << QLatin1String("qmake");
return result;
-#endif
}
// Copy helper source files to a target directory, replacing older files.
@@ -140,7 +139,7 @@ bool BuildableHelperLibrary::copyFiles(const QString &sourcePath,
QString *errorMessage)
{
// try remove the directory
- if (!FileUtils::removeRecursively(targetDirectory, errorMessage))
+ if (!FileUtils::removeRecursively(FileName::fromString(targetDirectory), errorMessage))
return false;
if (!QDir().mkpath(targetDirectory)) {
*errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The target directory %1 could not be created.").arg(targetDirectory);
@@ -158,9 +157,8 @@ bool BuildableHelperLibrary::copyFiles(const QString &sourcePath,
return false;
}
}
- if (!destInfo.dir().exists()) {
+ if (!destInfo.dir().exists())
QDir().mkpath(destInfo.dir().absolutePath());
- }
if (!QFile::copy(source, dest)) {
*errorMessage = QCoreApplication::translate("ProjectExplorer::DebuggingHelperLibrary", "The file %1 could not be copied to %2.").arg(source, dest);
@@ -299,7 +297,7 @@ bool BuildableHelperLibrary::getHelperFileInfoFor(const QStringList &validBinary
if (!info)
return false;
- foreach(const QString &binaryFilename, validBinaryFilenames) {
+ foreach (const QString &binaryFilename, validBinaryFilenames) {
info->setFile(directory + binaryFilename);
if (info->exists())
return true;
@@ -335,7 +333,7 @@ QString BuildableHelperLibrary::byInstallDataHelper(const QString &sourcePath,
QString newestHelper;
QDateTime newestHelperModified = sourcesModified; // prevent using one that's older than the sources
QFileInfo fileInfo;
- foreach(const QString &installDirectory, installDirectories) {
+ foreach (const QString &installDirectory, installDirectories) {
if (getHelperFileInfoFor(validBinaryFilenames, installDirectory, &fileInfo)) {
if (!newestHelperModified.isValid()
|| (fileInfo.lastModified() > newestHelperModified)) {
diff --git a/src/libs/utils/changeset.cpp b/src/libs/utils/changeset.cpp
index 6bb54fb25b..1b4290eff5 100644
--- a/src/libs/utils/changeset.cpp
+++ b/src/libs/utils/changeset.cpp
@@ -158,6 +158,8 @@ bool ChangeSet::move_helper(int pos, int length, int to)
bool ChangeSet::insert(int pos, const QString &text)
{
+ Q_ASSERT(pos >= 0);
+
if (hasOverlap(pos, 0))
m_error = true;
diff --git a/src/libs/utils/classnamevalidatinglineedit.cpp b/src/libs/utils/classnamevalidatinglineedit.cpp
index 0ed71b3425..88ad817e70 100644
--- a/src/libs/utils/classnamevalidatinglineedit.cpp
+++ b/src/libs/utils/classnamevalidatinglineedit.cpp
@@ -46,8 +46,8 @@ namespace Utils {
struct ClassNameValidatingLineEditPrivate {
ClassNameValidatingLineEditPrivate();
- const QRegExp m_nameRegexp;
- const QString m_namespaceDelimiter;
+ QRegExp m_nameRegexp;
+ QString m_namespaceDelimiter;
bool m_namespacesEnabled;
bool m_lowerCaseFileName;
bool m_forceFirstCapitalLetter;
@@ -67,6 +67,7 @@ ClassNameValidatingLineEdit::ClassNameValidatingLineEdit(QWidget *parent) :
Utils::BaseValidatingLineEdit(parent),
d(new ClassNameValidatingLineEditPrivate)
{
+ updateRegExp();
}
ClassNameValidatingLineEdit::~ClassNameValidatingLineEdit()
@@ -84,11 +85,28 @@ void ClassNameValidatingLineEdit::setNamespacesEnabled(bool b)
d->m_namespacesEnabled = b;
}
+/**
+ * @return Language-specific namespace delimiter, e.g. '::' or '.'
+ */
+QString ClassNameValidatingLineEdit::namespaceDelimiter()
+{
+ return d->m_namespaceDelimiter;
+}
+
+/**
+ * @brief Sets language-specific namespace delimiter, e.g. '::' or '.'
+ * Do not use identifier characters in delimiter
+ */
+void ClassNameValidatingLineEdit::setNamespaceDelimiter(const QString &delimiter)
+{
+ d->m_namespaceDelimiter = delimiter;
+}
+
bool ClassNameValidatingLineEdit::validate(const QString &value, QString *errorMessage) const
{
- static QRegExp nameRegexp(QLatin1String("[a-zA-Z_][a-zA-Z0-9_]*(::[a-zA-Z_][a-zA-Z0-9_]*)*"));
- QTC_ASSERT(nameRegexp.isValid(), return false);
- if (!d->m_namespacesEnabled && value.contains(QLatin1Char(':'))) {
+ QTC_ASSERT(d->m_nameRegexp.isValid(), return false);
+
+ if (!d->m_namespacesEnabled && value.contains(d->m_namespaceDelimiter)) {
if (errorMessage)
*errorMessage = tr("The class name must not contain namespace delimiters.");
return false;
@@ -96,7 +114,7 @@ bool ClassNameValidatingLineEdit::validate(const QString &value, QString *errorM
if (errorMessage)
*errorMessage = tr("Please enter a class name.");
return false;
- } else if (!nameRegexp.exactMatch(value)) {
+ } else if (!d->m_nameRegexp.exactMatch(value)) {
if (errorMessage)
*errorMessage = tr("The class name contains invalid characters.");
return false;
@@ -131,6 +149,13 @@ QString ClassNameValidatingLineEdit::fixInputString(const QString &string)
return fixedString;
}
+void ClassNameValidatingLineEdit::updateRegExp() const
+{
+ QString identifierPatter(QLatin1String("[a-zA-Z_][a-zA-Z0-9_]*"));
+ QString pattern(QLatin1String("%1(%2%1)*"));
+ d->m_nameRegexp.setPattern(pattern.arg(identifierPatter).arg(d->m_namespaceDelimiter));
+}
+
QString ClassNameValidatingLineEdit::createClassName(const QString &name)
{
// Remove spaces and convert the adjacent characters to uppercase
diff --git a/src/libs/utils/classnamevalidatinglineedit.h b/src/libs/utils/classnamevalidatinglineedit.h
index 378e358dc8..0d3298401d 100644
--- a/src/libs/utils/classnamevalidatinglineedit.h
+++ b/src/libs/utils/classnamevalidatinglineedit.h
@@ -51,6 +51,9 @@ public:
bool namespacesEnabled() const;
void setNamespacesEnabled(bool b);
+ QString namespaceDelimiter();
+ void setNamespaceDelimiter(const QString &delimiter);
+
bool lowerCaseFileName() const;
void setLowerCaseFileName(bool v);
@@ -71,6 +74,8 @@ protected:
virtual QString fixInputString(const QString &string);
private:
+ void updateRegExp() const;
+
ClassNameValidatingLineEditPrivate *d;
};
diff --git a/src/libs/utils/consoleprocess.cpp b/src/libs/utils/consoleprocess.cpp
index c5b4f6ccf5..630783fa18 100644
--- a/src/libs/utils/consoleprocess.cpp
+++ b/src/libs/utils/consoleprocess.cpp
@@ -29,6 +29,10 @@
#include "consoleprocess_p.h"
+#include <utils/hostosinfo.h>
+
+#include <QSettings>
+
namespace Utils {
ConsoleProcess::~ConsoleProcess()
@@ -124,7 +128,7 @@ QString ConsoleProcess::msgCannotCreateTempDir(const QString & dir, const QStrin
QString ConsoleProcess::msgUnexpectedOutput(const QByteArray &what)
{
- return tr("Unexpected output from helper program (%1).").arg(QString::fromAscii(what));
+ return tr("Unexpected output from helper program (%1).").arg(QString::fromLatin1(what));
}
QString ConsoleProcess::msgCannotChangeToWorkDir(const QString & dir, const QString &why)
@@ -137,4 +141,19 @@ QString ConsoleProcess::msgCannotExecute(const QString & p, const QString &why)
return tr("Cannot execute '%1': %2").arg(p, why);
}
+QString ConsoleProcess::terminalEmulator(const QSettings *settings)
+{
+ if (settings) {
+ const QString value = settings->value(QLatin1String("General/TerminalEmulator")).toString();
+ if (!value.isEmpty())
+ return value;
+ }
+ return defaultTerminalEmulator();
+}
+
+void ConsoleProcess::setTerminalEmulator(QSettings *settings, const QString &term)
+{
+ return settings->setValue(QLatin1String("General/TerminalEmulator"), term);
+}
+
}
diff --git a/src/libs/utils/consoleprocess.h b/src/libs/utils/consoleprocess.h
index a0ea384de9..8dcff02bf1 100644
--- a/src/libs/utils/consoleprocess.h
+++ b/src/libs/utils/consoleprocess.h
@@ -62,16 +62,23 @@ public:
Environment environment() const;
bool start(const QString &program, const QString &args);
+public slots:
void stop();
+public:
void setMode(Mode m);
Mode mode() const;
bool isRunning() const; // This reflects the state of the console+stub
qint64 applicationPID() const;
+ void killProcess();
+ void killStub();
+
#ifdef Q_OS_WIN
qint64 applicationMainThreadID() const;
+#else
+ void detachStub();
#endif
int exitCode() const;
@@ -85,11 +92,12 @@ public:
static QString createWinCommandline(const QString &program, const QString &args);
#else
void setSettings(QSettings *settings);
+#endif
+
static QString defaultTerminalEmulator();
static QStringList availableTerminalEmulators();
static QString terminalEmulator(const QSettings *settings);
static void setTerminalEmulator(QSettings *settings, const QString &term);
-#endif
signals:
void processError(const QString &error);
@@ -98,8 +106,8 @@ signals:
void processStopped();
// These reflect the state of the console+stub
- void wrapperStarted();
- void wrapperStopped();
+ void stubStarted();
+ void stubStopped();
private slots:
void stubConnectionAvailable();
diff --git a/src/libs/utils/consoleprocess_p.h b/src/libs/utils/consoleprocess_p.h
index be5da4f7cd..2a08b6d933 100644
--- a/src/libs/utils/consoleprocess_p.h
+++ b/src/libs/utils/consoleprocess_p.h
@@ -37,6 +37,10 @@
#include <QLocalSocket>
#include <QLocalServer>
+QT_BEGIN_NAMESPACE
+class QTimer;
+QT_END_NAMESPACE
+
#ifdef Q_OS_WIN
# if QT_VERSION >= 0x050000
# include <QWinEventNotifier>
@@ -51,6 +55,7 @@ namespace Utils {
struct ConsoleProcessPrivate {
ConsoleProcessPrivate();
+ static QString m_defaultConsoleProcess;
ConsoleProcess::Mode m_mode;
QString m_workingDir;
Environment m_environment;
@@ -66,6 +71,9 @@ struct ConsoleProcessPrivate {
QProcess m_process;
QByteArray m_stubServerDir;
QSettings *m_settings;
+ bool m_stubConnected;
+ qint64 m_stubPid;
+ QTimer *m_stubConnectTimer;
#else
qint64 m_appMainThreadId;
PROCESS_INFORMATION *m_pid;
diff --git a/src/libs/utils/consoleprocess_unix.cpp b/src/libs/utils/consoleprocess_unix.cpp
index 06f499009e..367a0abfa6 100644
--- a/src/libs/utils/consoleprocess_unix.cpp
+++ b/src/libs/utils/consoleprocess_unix.cpp
@@ -32,9 +32,12 @@
#include "environment.h"
#include "qtcprocess.h"
+#include <utils/hostosinfo.h>
+
#include <QCoreApplication>
#include <QDir>
#include <QSettings>
+#include <QTimer>
#include <sys/stat.h>
#include <sys/types.h>
@@ -49,7 +52,10 @@ ConsoleProcessPrivate::ConsoleProcessPrivate() :
m_appPid(0),
m_stubSocket(0),
m_tempFile(0),
- m_settings(0)
+ m_settings(0),
+ m_stubConnected(false),
+ m_stubPid(0),
+ m_stubConnectTimer(0)
{
}
@@ -59,8 +65,6 @@ ConsoleProcess::ConsoleProcess(QObject *parent) :
connect(&d->m_stubServer, SIGNAL(newConnection()), SLOT(stubConnectionAvailable()));
d->m_process.setProcessChannelMode(QProcess::ForwardedChannels);
- connect(&d->m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
- SLOT(stubExited()));
}
void ConsoleProcess::setSettings(QSettings *settings)
@@ -133,12 +137,14 @@ bool ConsoleProcess::start(const QString &program, const QString &args)
}
}
+ if (Utils::HostOsInfo::isMacHost()) {
+ xtermArgs << (QCoreApplication::applicationDirPath()
+ + QLatin1String("/../Resources/qtcreator_process_stub"));
+ } else {
+ xtermArgs << (QCoreApplication::applicationDirPath()
+ + QLatin1String("/qtcreator_process_stub"));
+ }
xtermArgs
-#ifdef Q_OS_MAC
- << (QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/qtcreator_process_stub"))
-#else
- << (QCoreApplication::applicationDirPath() + QLatin1String("/qtcreator_process_stub"))
-#endif
<< modeOption(d->m_mode)
<< d->m_stubServer.fullServerName()
<< msgPromptToClose()
@@ -155,21 +161,54 @@ bool ConsoleProcess::start(const QString &program, const QString &args)
d->m_tempFile = 0;
return false;
}
+ d->m_stubConnectTimer = new QTimer(this);
+ connect(d->m_stubConnectTimer, SIGNAL(timeout()), SLOT(stop()));
+ d->m_stubConnectTimer->setSingleShot(true);
+ d->m_stubConnectTimer->start(10000);
d->m_executable = program;
- emit wrapperStarted();
return true;
}
-void ConsoleProcess::stop()
+void ConsoleProcess::killProcess()
{
- if (!isRunning())
- return;
- stubServerShutdown();
+ if (d->m_stubSocket && d->m_stubSocket->isWritable()) {
+ d->m_stubSocket->write("k", 1);
+ d->m_stubSocket->flush();
+ }
d->m_appPid = 0;
- d->m_process.terminate();
- if (!d->m_process.waitForFinished(1000))
- d->m_process.kill();
- d->m_process.waitForFinished();
+}
+
+void ConsoleProcess::killStub()
+{
+ if (d->m_stubSocket && d->m_stubSocket->isWritable()) {
+ d->m_stubSocket->write("s", 1);
+ d->m_stubSocket->flush();
+ }
+ stubServerShutdown();
+ d->m_stubPid = 0;
+}
+
+void ConsoleProcess::detachStub()
+{
+ if (d->m_stubSocket && d->m_stubSocket->isWritable()) {
+ d->m_stubSocket->write("d", 1);
+ d->m_stubSocket->flush();
+ }
+ stubServerShutdown();
+ d->m_stubPid = 0;
+}
+
+void ConsoleProcess::stop()
+{
+ killProcess();
+ killStub();
+ if (isRunning()) {
+ d->m_process.terminate();
+ if (!d->m_process.waitForFinished(1000)) {
+ d->m_process.kill();
+ d->m_process.waitForFinished();
+ }
+ }
}
bool ConsoleProcess::isRunning() const
@@ -206,7 +245,8 @@ QString ConsoleProcess::stubServerListen()
void ConsoleProcess::stubServerShutdown()
{
- delete d->m_stubSocket;
+ if (d->m_stubSocket)
+ d->m_stubSocket->deleteLater(); // we might be called from the disconnected signal of m_stubSocket
d->m_stubSocket = 0;
if (d->m_stubServer.isListening()) {
d->m_stubServer.close();
@@ -216,8 +256,15 @@ void ConsoleProcess::stubServerShutdown()
void ConsoleProcess::stubConnectionAvailable()
{
+ if (d->m_stubConnectTimer) {
+ delete d->m_stubConnectTimer;
+ d->m_stubConnectTimer = 0;
+ }
+ d->m_stubConnected = true;
+ emit stubStarted();
d->m_stubSocket = d->m_stubServer.nextPendingConnection();
connect(d->m_stubSocket, SIGNAL(readyRead()), SLOT(readStubOutput()));
+ connect(d->m_stubSocket, SIGNAL(disconnected()), SLOT(stubExited()));
}
static QString errorMsg(int code)
@@ -234,11 +281,12 @@ void ConsoleProcess::readStubOutput()
emit processError(msgCannotChangeToWorkDir(workingDirectory(), errorMsg(out.mid(10).toInt())));
} else if (out.startsWith("err:exec ")) {
emit processError(msgCannotExecute(d->m_executable, errorMsg(out.mid(9).toInt())));
- } else if (out.startsWith("pid ")) {
- // Will not need it any more
+ } else if (out.startsWith("spid ")) {
delete d->m_tempFile;
d->m_tempFile = 0;
+ d->m_stubPid = out.mid(4).toInt();
+ } else if (out.startsWith("pid ")) {
d->m_appPid = out.mid(4).toInt();
emit processStarted();
} else if (out.startsWith("exit ")) {
@@ -253,6 +301,7 @@ void ConsoleProcess::readStubOutput()
emit processStopped();
} else {
emit processError(msgUnexpectedOutput(out));
+ d->m_stubPid = 0;
d->m_process.terminate();
break;
}
@@ -265,6 +314,7 @@ void ConsoleProcess::stubExited()
if (d->m_stubSocket && d->m_stubSocket->state() == QLocalSocket::ConnectedState)
d->m_stubSocket->waitForDisconnected();
stubServerShutdown();
+ d->m_stubPid = 0;
delete d->m_tempFile;
d->m_tempFile = 0;
if (d->m_appPid) {
@@ -273,7 +323,7 @@ void ConsoleProcess::stubExited()
d->m_appPid = 0;
emit processStopped(); // Maybe it actually did not, but keep state consistent
}
- emit wrapperStopped();
+ emit stubStopped();
}
struct Terminal {
@@ -289,15 +339,18 @@ static const Terminal knownTerminals[] =
{"rxvt", "-e"},
{"urxvt", "-e"},
{"xfce4-terminal", "-x"},
- {"konsole", "--nofork -e"},
+ {"konsole", "-e"},
{"gnome-terminal", "-x"}
};
QString ConsoleProcess::defaultTerminalEmulator()
{
-#ifdef Q_OS_MAC
- return QLatin1String("/usr/X11/bin/xterm -e");
-#else
+ if (Utils::HostOsInfo::isMacHost()) {
+ QString termCmd = QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/scripts/openTerminal.command");
+ if (QFile(termCmd).exists())
+ return termCmd.replace(QLatin1Char(' '), QLatin1String("\\ "));
+ return QLatin1String("/usr/X11/bin/xterm");
+ }
const Environment env = Environment::systemEnvironment();
const int terminalCount = int(sizeof(knownTerminals) / sizeof(knownTerminals[0]));
for (int i = 0; i < terminalCount; ++i) {
@@ -309,14 +362,10 @@ QString ConsoleProcess::defaultTerminalEmulator()
}
}
return QLatin1String("xterm -e");
-#endif
}
QStringList ConsoleProcess::availableTerminalEmulators()
{
-#ifdef Q_OS_MAC
- return QStringList(defaultTerminalEmulator());
-#else
QStringList result;
const Environment env = Environment::systemEnvironment();
const int terminalCount = int(sizeof(knownTerminals) / sizeof(knownTerminals[0]));
@@ -328,23 +377,10 @@ QStringList ConsoleProcess::availableTerminalEmulators()
result.push_back(terminal);
}
}
+ if (!result.contains(defaultTerminalEmulator()))
+ result.append(defaultTerminalEmulator());
result.sort();
return result;
-#endif
-}
-
-QString ConsoleProcess::terminalEmulator(const QSettings *settings)
-{
- if (settings) {
- const QString value = settings->value(QLatin1String("General/TerminalEmulator")).toString();
- if (!value.isEmpty())
- return value;
- }
- return defaultTerminalEmulator();
}
-void ConsoleProcess::setTerminalEmulator(QSettings *settings, const QString &term)
-{
- return settings->setValue(QLatin1String("General/TerminalEmulator"), term);
-}
} // namespace Utils
diff --git a/src/libs/utils/consoleprocess_win.cpp b/src/libs/utils/consoleprocess_win.cpp
index 5c73cfcdf6..dc64dd47f1 100644
--- a/src/libs/utils/consoleprocess_win.cpp
+++ b/src/libs/utils/consoleprocess_win.cpp
@@ -120,14 +120,14 @@ bool ConsoleProcess::start(const QString &program, const QString &args)
ZeroMemory(d->m_pid, sizeof(PROCESS_INFORMATION));
QString workDir = QDir::toNativeSeparators(workingDirectory());
- if (!workDir.isEmpty() && !workDir.endsWith('\\'))
- workDir.append('\\');
+ if (!workDir.isEmpty() && !workDir.endsWith(QLatin1Char('\\')))
+ workDir.append(QLatin1Char('\\'));
QStringList stubArgs;
stubArgs << modeOption(d->m_mode)
<< d->m_stubServer.fullServerName()
<< workDir
- << (d->m_tempFile ? d->m_tempFile->fileName() : 0)
+ << (d->m_tempFile ? d->m_tempFile->fileName() : QString())
<< createWinCommandline(pcmd, pargs)
<< msgPromptToClose();
@@ -151,16 +151,20 @@ bool ConsoleProcess::start(const QString &program, const QString &args)
d->processFinishedNotifier = new QWinEventNotifier(d->m_pid->hProcess, this);
connect(d->processFinishedNotifier, SIGNAL(activated(HANDLE)), SLOT(stubExited()));
- emit wrapperStarted();
return true;
}
-void ConsoleProcess::stop()
+
+void ConsoleProcess::killProcess()
{
if (d->m_hInferior != NULL) {
TerminateProcess(d->m_hInferior, (unsigned)-1);
cleanupInferior();
}
+}
+
+void ConsoleProcess::killStub()
+{
if (d->m_pid) {
TerminateProcess(d->m_pid->hProcess, (unsigned)-1);
WaitForSingleObject(d->m_pid->hProcess, INFINITE);
@@ -168,6 +172,12 @@ void ConsoleProcess::stop()
}
}
+void ConsoleProcess::stop()
+{
+ killProcess();
+ killStub();
+}
+
bool ConsoleProcess::isRunning() const
{
return d->m_pid != 0;
@@ -192,6 +202,7 @@ void ConsoleProcess::stubServerShutdown()
void ConsoleProcess::stubConnectionAvailable()
{
+ emit stubStarted();
d->m_stubSocket = d->m_stubServer.nextPendingConnection();
connect(d->m_stubSocket, SIGNAL(readyRead()), SLOT(readStubOutput()));
}
@@ -281,7 +292,7 @@ void ConsoleProcess::stubExited()
d->m_appCode = -1;
emit processStopped();
}
- emit wrapperStopped();
+ emit stubStopped();
}
QStringList ConsoleProcess::fixWinEnvironment(const QStringList &env)
@@ -358,4 +369,14 @@ QString ConsoleProcess::createWinCommandline(const QString &program, const QStri
return programName;
}
+QString ConsoleProcess::defaultTerminalEmulator()
+{
+ return QString::fromLocal8Bit(qgetenv("COMSPEC"));
+}
+
+QStringList ConsoleProcess::availableTerminalEmulators()
+{
+ return QStringList(ConsoleProcess::defaultTerminalEmulator());
+}
+
} // namespace Utils
diff --git a/src/libs/utils/crumblepath.cpp b/src/libs/utils/crumblepath.cpp
index 7f38a058b6..fca5cc3dc5 100644
--- a/src/libs/utils/crumblepath.cpp
+++ b/src/libs/utils/crumblepath.cpp
@@ -28,6 +28,7 @@
****************************************************************************/
#include "crumblepath.h"
+#include "qtcassert.h"
#include "stylehelper.h"
#include <QList>
@@ -39,8 +40,6 @@
#include <QPainter>
#include <QImage>
-#include <qtcassert.h>
-
namespace Utils {
static const int ArrowBorderSize = 12;
@@ -125,27 +124,24 @@ void CrumblePathButton::paintEvent(QPaintEvent *)
}
if (m_isEnd) {
- if (m_isPressed || m_isSelected) {
+ if (m_isPressed || m_isSelected)
Utils::StyleHelper::drawCornerImage(m_segmentSelectedEnd, &p, geom, 2, 0, 2, 0);
- } else if (m_isHovering) {
+ else if (m_isHovering)
Utils::StyleHelper::drawCornerImage(m_segmentHoverEnd, &p, geom, 2, 0, 2, 0);
- } else {
+ else
Utils::StyleHelper::drawCornerImage(m_segmentEnd, &p, geom, 2, 0, 2, 0);
- }
} else {
- if (m_isPressed || m_isSelected) {
+ if (m_isPressed || m_isSelected)
Utils::StyleHelper::drawCornerImage(m_segmentSelected, &p, geom, 2, 0, 12, 0);
- } else if (m_isHovering) {
+ else if (m_isHovering)
Utils::StyleHelper::drawCornerImage(m_segmentHover, &p, geom, 2, 0, 12, 0);
- } else {
+ else
Utils::StyleHelper::drawCornerImage(m_segment, &p, geom, 2, 0, 12, 0);
- }
}
- if (isEnabled()) {
+ if (isEnabled())
p.setPen(StyleHelper::panelTextColor());
- } else {
+ else
p.setPen(StyleHelper::panelTextColor().darker());
- }
QFontMetrics fm(p.font());
QString textToDraw = fm.elidedText(text(), Qt::ElideRight, geom.width() - m_textPos.x());
diff --git a/src/libs/utils/detailsbutton.cpp b/src/libs/utils/detailsbutton.cpp
index 8bf29b4259..c899950615 100644
--- a/src/libs/utils/detailsbutton.cpp
+++ b/src/libs/utils/detailsbutton.cpp
@@ -29,6 +29,7 @@
#include "detailsbutton.h"
+#include <utils/hostosinfo.h>
#include <utils/stylehelper.h>
#include <QPropertyAnimation>
@@ -82,16 +83,14 @@ QSize DetailsButton::sizeHint() const
{
// TODO: Adjust this when icons become available!
const int w = fontMetrics().width(text()) + 32;
-#ifdef Q_OS_MAC
- return QSize(w, 34);
-#else
+ if (HostOsInfo::isMacHost())
+ return QSize(w, 34);
return QSize(w, 22);
-#endif
}
bool DetailsButton::event(QEvent *e)
{
- switch(e->type()) {
+ switch (e->type()) {
case QEvent::Enter:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
@@ -119,11 +118,10 @@ void DetailsButton::paintEvent(QPaintEvent *e)
QWidget::paintEvent(e);
QPainter p(this);
-#ifndef Q_OS_MAC
+
// draw hover animation
- if (!isDown() && m_fader > 0)
+ if (!HostOsInfo::isMacHost() && !isDown() && m_fader > 0)
p.fillRect(rect().adjusted(1, 1, -2, -2), QColor(255, 255, 255, int(m_fader*180)));
-#endif
if (isChecked()) {
if (m_checkedPixmap.isNull() || m_checkedPixmap.size() != contentsRect().size())
@@ -166,7 +164,7 @@ QPixmap DetailsButton::cacheRendering(const QSize &size, bool checked)
p.drawRoundedRect(1, 1, size.width()-3, size.height()-3, 1, 1);
p.setPen(QPen(QColor(0, 0, 0, 40)));
p.drawLine(0, 1, 0, size.height() - 2);
- if(checked)
+ if (checked)
p.drawLine(1, size.height() - 1, size.width() - 1, size.height() - 1);
p.setPen(palette().color(QPalette::Text));
diff --git a/src/libs/utils/detailswidget.cpp b/src/libs/utils/detailswidget.cpp
index 29b892827c..cf4f89f598 100644
--- a/src/libs/utils/detailswidget.cpp
+++ b/src/libs/utils/detailswidget.cpp
@@ -29,6 +29,7 @@
#include "detailswidget.h"
#include "detailsbutton.h"
+#include "hostosinfo.h"
#include <QStack>
#include <QPropertyAnimation>
@@ -68,7 +69,6 @@ class DetailsWidgetPrivate
public:
DetailsWidgetPrivate(QWidget *parent);
- QPixmap cacheBackground(const QSize &size);
void updateControls();
void changeHoverState(bool hovered);
@@ -130,22 +130,18 @@ DetailsWidgetPrivate::DetailsWidgetPrivate(QWidget *parent) :
m_grid->addWidget(m_additionalSummaryLabel, 1, 0, 1, 3);
}
-QPixmap DetailsWidgetPrivate::cacheBackground(const QSize &size)
+QPixmap DetailsWidget::createBackground(const QSize &size, int topHeight, QWidget *widget)
{
QPixmap pixmap(size);
pixmap.fill(Qt::transparent);
QPainter p(&pixmap);
- int topHeight = m_useCheckBox ? m_summaryCheckBox->height() : m_summaryLabel->height();
- if (m_state == DetailsWidget::Expanded || m_state == DetailsWidget::Collapsed) // Details Button is shown
- topHeight = qMax(m_detailsButton->height(), topHeight);
-
QRect topRect(0, 0, size.width(), topHeight);
QRect fullRect(0, 0, size.width(), size.height());
-#ifdef Q_OS_MAC
- p.fillRect(fullRect, qApp->palette().window().color());
-#endif
- p.fillRect(fullRect, QColor(255, 255, 255, 40));
+ if (HostOsInfo::isMacHost())
+ p.fillRect(fullRect, qApp->palette().window().color());
+ else
+ p.fillRect(fullRect, QColor(255, 255, 255, 40));
QLinearGradient lg(topRect.topLeft(), topRect.bottomLeft());
lg.setColorAt(0, QColor(255, 255, 255, 130));
@@ -159,7 +155,7 @@ QPixmap DetailsWidgetPrivate::cacheBackground(const QSize &size)
p.setBrush(Qt::NoBrush);
p.setPen(QColor(255,255,255,140));
p.drawRoundedRect(fullRect.adjusted(1, 1, -2, -2), 2, 2);
- p.setPen(QPen(q->palette().color(QPalette::Mid)));
+ p.setPen(QPen(widget->palette().color(QPalette::Mid)));
return pixmap;
}
@@ -187,11 +183,10 @@ void DetailsWidgetPrivate::changeHoverState(bool hovered)
{
if (!m_toolWidget)
return;
-#ifdef Q_OS_MAC
- m_toolWidget->setOpacity(hovered ? 1.0 : 0);
-#else
- m_toolWidget->fadeTo(hovered ? 1.0 : 0);
-#endif
+ if (HostOsInfo::isMacHost())
+ m_toolWidget->setOpacity(hovered ? 1.0 : 0);
+ else
+ m_toolWidget->fadeTo(hovered ? 1.0 : 0);
m_hovered = hovered;
}
@@ -263,15 +258,19 @@ void DetailsWidget::paintEvent(QPaintEvent *paintEvent)
QPoint topLeft(topLeftWidget->geometry().left() - MARGIN, contentsRect().top());
const QRect paintArea(topLeft, contentsRect().bottomRight());
+ int topHeight = d->m_useCheckBox ? d->m_summaryCheckBox->height() : d->m_summaryLabel->height();
+ if (d->m_state == DetailsWidget::Expanded || d->m_state == DetailsWidget::Collapsed) // Details Button is shown
+ topHeight = qMax(d->m_detailsButton->height(), topHeight);
+
if (d->m_state == Collapsed) {
if (d->m_collapsedPixmap.isNull() ||
d->m_collapsedPixmap.size() != size())
- d->m_collapsedPixmap = d->cacheBackground(paintArea.size());
+ d->m_collapsedPixmap = createBackground(paintArea.size(), topHeight, this);
p.drawPixmap(paintArea, d->m_collapsedPixmap);
} else {
if (d->m_expandedPixmap.isNull() ||
d->m_expandedPixmap.size() != size())
- d->m_expandedPixmap = d->cacheBackground(paintArea.size());
+ d->m_expandedPixmap = createBackground(paintArea.size(), topHeight, this);
p.drawPixmap(paintArea, d->m_expandedPixmap);
}
}
@@ -380,9 +379,8 @@ void DetailsWidget::setToolWidget(Utils::FadingPanel *widget)
d->m_toolWidget->adjustSize();
d->m_grid->addWidget(d->m_toolWidget, 0, 1, 1, 1, Qt::AlignRight);
-#ifdef Q_OS_MAC
- d->m_toolWidget->setOpacity(1.0);
-#endif
+ if (HostOsInfo::isMacHost())
+ d->m_toolWidget->setOpacity(1.0);
d->changeHoverState(d->m_hovered);
}
diff --git a/src/libs/utils/detailswidget.h b/src/libs/utils/detailswidget.h
index e40bb9bea4..6465ce0ec6 100644
--- a/src/libs/utils/detailswidget.h
+++ b/src/libs/utils/detailswidget.h
@@ -86,6 +86,8 @@ public:
/// Sets an icon, only supported if useCheckBox is true
void setIcon(const QIcon &icon);
+ static QPixmap createBackground(const QSize &size, int topHeight, QWidget *widget);
+
signals:
void checked(bool);
void linkActivated(const QString &link);
diff --git a/src/libs/utils/elfreader.cpp b/src/libs/utils/elfreader.cpp
index 2c0e527a46..c85d261b7f 100644
--- a/src/libs/utils/elfreader.cpp
+++ b/src/libs/utils/elfreader.cpp
@@ -194,7 +194,7 @@ ElfReader::Result ElfReader::readIt()
// Read Endianess.
m_elfData.endian = ElfEndian(mapper.ustart[5]);
if (m_elfData.endian != Elf_ELFDATA2LSB && m_elfData.endian != Elf_ELFDATA2MSB) {
- m_errorString = msgInvalidElfObject(m_binary, tr("odd endianess"));
+ m_errorString = msgInvalidElfObject(m_binary, tr("odd endianness"));
return Corrupt;
}
diff --git a/src/plugins/qmldesigner/components/integration/integrationcore.cpp b/src/libs/utils/elidinglabel.cpp
index 139f4e3d22..e3ec254888 100644
--- a/src/plugins/qmldesigner/components/integration/integrationcore.cpp
+++ b/src/libs/utils/elidinglabel.cpp
@@ -27,68 +27,55 @@
**
****************************************************************************/
-#include "integrationcore.h"
-#include "pluginmanager.h"
-#include "itemlibraryview.h"
-#include "navigatorwidget.h"
-#include "metainfo.h"
+#include "elidinglabel.h"
+#include <QFontMetrics>
+#include <QPainter>
+#include <QStyle>
-#include <QCoreApplication>
-#include <QObject>
-
-namespace QmlDesigner {
-
-class CorePrivate
-{
- public:
- CorePrivate();
- ~CorePrivate();
-
- static IntegrationCore *m_instance;
+/*!
+ \class Utils::ElidingLabel
- PluginManager m_pluginManager;
-};
+ \brief A label suitable for displaying elided text.
+*/
-CorePrivate::CorePrivate()
-{
-}
+namespace Utils {
-CorePrivate::~CorePrivate()
+ElidingLabel::ElidingLabel(QWidget *parent)
+ : QLabel(parent), m_elideMode(Qt::ElideRight)
{
- MetaInfo::clearGlobal();
+ setSizePolicy(QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred, QSizePolicy::Label));
}
-IntegrationCore *CorePrivate::m_instance = 0;
-
-/*!
- \class QmlDesigner::Core
-
- Convenience class to access the plugin manager singleton,
- and manage the lifecycle of static data (e.g. in the metatype system).
-*/
-
-IntegrationCore::IntegrationCore() :
- d(new CorePrivate)
+ElidingLabel::ElidingLabel(const QString &text, QWidget *parent)
+ : QLabel(text, parent), m_elideMode(Qt::ElideRight)
{
- Q_ASSERT(CorePrivate::m_instance == 0);
- CorePrivate::m_instance = this;
+ setSizePolicy(QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred, QSizePolicy::Label));
}
-IntegrationCore::~IntegrationCore()
+Qt::TextElideMode ElidingLabel::elideMode() const
{
- CorePrivate::m_instance = 0;
- delete d;
+ return m_elideMode;
}
-IntegrationCore *IntegrationCore::instance()
+void ElidingLabel::setElideMode(const Qt::TextElideMode &elideMode)
{
- Q_ASSERT(CorePrivate::m_instance);
- return CorePrivate::m_instance;
+ m_elideMode = elideMode;
+ update();
}
-PluginManager *IntegrationCore::pluginManager() const
+void ElidingLabel::paintEvent(QPaintEvent *)
{
- return &d->m_pluginManager;
+ const int m = margin();
+ QRect contents = contentsRect().adjusted(m, m, -m, -m);
+ QFontMetrics fm = fontMetrics();
+ QString txt = text();
+ if (txt.length() > 4 && fm.width(txt) > contents.width())
+ txt = fm.elidedText(txt, m_elideMode, contents.width());
+ int flags = QStyle::visualAlignment(layoutDirection(), alignment()) | Qt::TextSingleLine;
+
+ QPainter painter(this);
+ drawFrame(&painter);
+ painter.drawText(contents, flags, txt);
}
-}
+} // namespace Utils
diff --git a/src/libs/utils/elidinglabel.h b/src/libs/utils/elidinglabel.h
new file mode 100644
index 0000000000..3118f1f594
--- /dev/null
+++ b/src/libs/utils/elidinglabel.h
@@ -0,0 +1,59 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef ELIDINGLABEL_H
+#define ELIDINGLABEL_H
+
+#include "utils_global.h"
+#include <QLabel>
+
+namespace Utils {
+
+class QTCREATOR_UTILS_EXPORT ElidingLabel : public QLabel
+{
+ Q_OBJECT
+ Q_PROPERTY(Qt::TextElideMode elideMode READ elideMode WRITE setElideMode DESIGNABLE true)
+
+public:
+ explicit ElidingLabel(QWidget *parent = 0);
+ explicit ElidingLabel(const QString &text, QWidget *parent = 0);
+
+ Qt::TextElideMode elideMode() const;
+ void setElideMode(const Qt::TextElideMode &elideMode);
+
+protected:
+ void paintEvent(QPaintEvent *event);
+
+private:
+ Qt::TextElideMode m_elideMode;
+};
+
+} // namespace Utils
+
+#endif // ELIDINGLABEL_H
diff --git a/src/libs/utils/environment.cpp b/src/libs/utils/environment.cpp
index ae98210287..9ca27f28bc 100644
--- a/src/libs/utils/environment.cpp
+++ b/src/libs/utils/environment.cpp
@@ -29,8 +29,11 @@
#include "environment.h"
+#include "hostosinfo.h"
+
#include <QDir>
#include <QProcess>
+#include <QProcessEnvironment>
#include <QString>
#include <QCoreApplication>
@@ -38,20 +41,20 @@ class SystemEnvironment : public Utils::Environment
{
public:
SystemEnvironment()
- : Environment(QProcess::systemEnvironment())
+ : Environment(QProcessEnvironment::systemEnvironment().toStringList())
{
-#ifdef Q_OS_LINUX
- QString ldLibraryPath = value(QLatin1String("LD_LIBRARY_PATH"));
- QDir lib(QCoreApplication::applicationDirPath());
- lib.cd("../lib");
- QString toReplace = lib.path();
- lib.cd("qtcreator");
- toReplace.append(QLatin1String(":"));
- toReplace.append(lib.path());
-
- if (ldLibraryPath.startsWith(toReplace))
- set(QLatin1String("LD_LIBRARY_PATH"), ldLibraryPath.remove(0, toReplace.length()));
-#endif
+ if (Utils::HostOsInfo::isLinuxHost()) {
+ QString ldLibraryPath = value(QLatin1String("LD_LIBRARY_PATH"));
+ QDir lib(QCoreApplication::applicationDirPath());
+ lib.cd(QLatin1String("../lib"));
+ QString toReplace = lib.path();
+ lib.cd(QLatin1String("qtcreator"));
+ toReplace.append(QLatin1Char(':'));
+ toReplace.append(lib.path());
+
+ if (ldLibraryPath.startsWith(toReplace))
+ set(QLatin1String("LD_LIBRARY_PATH"), ldLibraryPath.remove(0, toReplace.length()));
+ }
}
};
@@ -103,11 +106,10 @@ Environment::Environment(const QStringList &env)
foreach (const QString &s, env) {
int i = s.indexOf(QLatin1Char('='));
if (i >= 0) {
-#ifdef Q_OS_WIN
- m_values.insert(s.left(i).toUpper(), s.mid(i+1));
-#else
- m_values.insert(s.left(i), s.mid(i+1));
-#endif
+ if (HostOsInfo::isWindowsHost())
+ m_values.insert(s.left(i).toUpper(), s.mid(i+1));
+ else
+ m_values.insert(s.left(i), s.mid(i+1));
}
}
}
@@ -125,34 +127,29 @@ QStringList Environment::toStringList() const
return result;
}
+QProcessEnvironment Environment::toProcessEnvironment() const
+{
+ QProcessEnvironment result;
+ const QMap<QString, QString>::const_iterator end = m_values.constEnd();
+ for (QMap<QString, QString>::const_iterator it = m_values.constBegin(); it != end; ++it)
+ result.insert(it.key(), it.value());
+ return result;
+}
+
void Environment::set(const QString &key, const QString &value)
{
-#ifdef Q_OS_WIN
- QString _key = key.toUpper();
-#else
- const QString &_key = key;
-#endif
- m_values.insert(_key, value);
+ m_values.insert(HostOsInfo::isWindowsHost() ? key.toUpper() : key, value);
}
void Environment::unset(const QString &key)
{
-#ifdef Q_OS_WIN
- QString _key = key.toUpper();
-#else
- const QString &_key = key;
-#endif
- m_values.remove(_key);
+ m_values.remove(HostOsInfo::isWindowsHost() ? key.toUpper() : key);
}
void Environment::appendOrSet(const QString &key, const QString &value, const QString &sep)
{
-#ifdef Q_OS_WIN
- QString _key = key.toUpper();
-#else
- const QString &_key = key;
-#endif
- QMap<QString, QString>::iterator it = m_values.find(key);
+ const QString &_key = HostOsInfo::isWindowsHost() ? key.toUpper() : key;
+ QMap<QString, QString>::iterator it = m_values.find(_key);
if (it == m_values.end()) {
m_values.insert(_key, value);
} else {
@@ -165,12 +162,8 @@ void Environment::appendOrSet(const QString &key, const QString &value, const QS
void Environment::prependOrSet(const QString&key, const QString &value, const QString &sep)
{
-#ifdef Q_OS_WIN
- QString _key = key.toUpper();
-#else
- const QString &_key = key;
-#endif
- QMap<QString, QString>::iterator it = m_values.find(key);
+ const QString &_key = HostOsInfo::isWindowsHost() ? key.toUpper() : key;
+ QMap<QString, QString>::iterator it = m_values.find(_key);
if (it == m_values.end()) {
m_values.insert(_key, value);
} else {
@@ -183,38 +176,35 @@ void Environment::prependOrSet(const QString&key, const QString &value, const QS
void Environment::appendOrSetPath(const QString &value)
{
-#ifdef Q_OS_WIN
- const QChar sep = QLatin1Char(';');
-#else
- const QChar sep = QLatin1Char(':');
-#endif
- appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
+ appendOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value),
+ QString(HostOsInfo::pathListSeparator()));
}
void Environment::prependOrSetPath(const QString &value)
{
-#ifdef Q_OS_WIN
- const QChar sep = QLatin1Char(';');
-#else
- const QChar sep = QLatin1Char(':');
-#endif
- prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value), QString(sep));
+ prependOrSet(QLatin1String("PATH"), QDir::toNativeSeparators(value),
+ QString(HostOsInfo::pathListSeparator()));
}
void Environment::prependOrSetLibrarySearchPath(const QString &value)
{
-#ifdef Q_OS_MAC
- Q_UNUSED(value);
- // we could set DYLD_LIBRARY_PATH on Mac but it is unnecessary in practice
-#elif defined(Q_OS_WIN)
- const QChar sep = QLatin1Char(';');
- const QLatin1String path("PATH");
- prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
-#elif defined(Q_OS_UNIX)
- const QChar sep = QLatin1Char(':');
- const QLatin1String path("LD_LIBRARY_PATH");
- prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
-#endif
+ switch (HostOsInfo::hostOs()) {
+ case HostOsInfo::HostOsWindows: {
+ const QChar sep = QLatin1Char(';');
+ const QLatin1String path("PATH");
+ prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
+ break;
+ }
+ case HostOsInfo::HostOsLinux:
+ case HostOsInfo::HostOsOtherUnix: {
+ const QChar sep = QLatin1Char(':');
+ const QLatin1String path("LD_LIBRARY_PATH");
+ prependOrSet(path, QDir::toNativeSeparators(value), QString(sep));
+ break;
+ }
+ default: // we could set DYLD_LIBRARY_PATH on Mac but it is unnecessary in practice
+ break;
+ }
}
Environment Environment::systemEnvironment()
@@ -257,16 +247,16 @@ QString Environment::searchInPath(const QString &executable,
return QString();
QStringList execs(exec);
-#ifdef Q_OS_WIN
- // Check all the executable extensions on windows:
- // PATHEXT is only used if the executable has no extension
- if (fi.suffix().isEmpty()) {
- QStringList extensions = value(QLatin1String("PATHEXT")).split(QLatin1Char(';'));
-
- foreach (const QString &ext, extensions)
- execs << executable + ext.toLower();
+ if (HostOsInfo::isWindowsHost()) {
+ // Check all the executable extensions on windows:
+ // PATHEXT is only used if the executable has no extension
+ if (fi.suffix().isEmpty()) {
+ QStringList extensions = value(QLatin1String("PATHEXT")).split(QLatin1Char(';'));
+
+ foreach (const QString &ext, extensions)
+ execs << executable + ext.toLower();
+ }
}
-#endif
foreach (QString dir, additionalDirs) {
QString tmp = searchInDirectory(execs, dir);
@@ -287,12 +277,8 @@ QString Environment::searchInPath(const QString &executable,
QStringList Environment::path() const
{
-#ifdef Q_OS_WIN
- const QChar sep = QLatin1Char(';');
-#else
- const QChar sep = QLatin1Char(':');
-#endif
- return m_values.value(QLatin1String("PATH")).split(sep, QString::SkipEmptyParts);
+ return m_values.value(QLatin1String("PATH")).split(HostOsInfo::pathListSeparator(),
+ QString::SkipEmptyParts);
}
QString Environment::value(const QString &key) const
@@ -404,6 +390,11 @@ bool Environment::hasKey(const QString &key)
return m_values.contains(key);
}
+QString Environment::userName() const
+{
+ return value(QLatin1String(HostOsInfo::isWindowsHost() ? "USERNAME" : "USER"));
+}
+
bool Environment::operator!=(const Environment &other) const
{
return !(*this == other);
@@ -425,68 +416,68 @@ QString Environment::expandVariables(const QString &input) const
{
QString result = input;
-#ifdef Q_OS_WIN
- for (int vStart = -1, i = 0; i < result.length(); ) {
- if (result.at(i++) == QLatin1Char('%')) {
- if (vStart > 0) {
- const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1).toUpper());
- if (it != m_values.constEnd()) {
- result.replace(vStart - 1, i - vStart + 1, *it);
- i = vStart - 1 + it->length();
- vStart = -1;
+ if (HostOsInfo::isWindowsHost()) {
+ for (int vStart = -1, i = 0; i < result.length(); ) {
+ if (result.at(i++) == QLatin1Char('%')) {
+ if (vStart > 0) {
+ const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1).toUpper());
+ if (it != m_values.constEnd()) {
+ result.replace(vStart - 1, i - vStart + 1, *it);
+ i = vStart - 1 + it->length();
+ vStart = -1;
+ } else {
+ vStart = i;
+ }
} else {
vStart = i;
}
- } else {
- vStart = i;
}
}
- }
-#else
- enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
- int vStart = -1;
-
- for (int i = 0; i < result.length();) {
- QChar c = result.at(i++);
- if (state == BASE) {
- if (c == QLatin1Char('$'))
- state = OPTIONALVARIABLEBRACE;
- } else if (state == OPTIONALVARIABLEBRACE) {
- if (c == QLatin1Char('{')) {
- state = BRACEDVARIABLE;
- vStart = i;
- } else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
- state = VARIABLE;
- vStart = i - 1;
- } else {
- state = BASE;
- }
- } else if (state == BRACEDVARIABLE) {
- if (c == QLatin1Char('}')) {
- const_iterator it = m_values.constFind(result.mid(vStart, i - 1 - vStart));
- if (it != constEnd()) {
- result.replace(vStart - 2, i - vStart + 2, *it);
- i = vStart - 2 + it->length();
+ } else {
+ enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
+ int vStart = -1;
+
+ for (int i = 0; i < result.length();) {
+ QChar c = result.at(i++);
+ if (state == BASE) {
+ if (c == QLatin1Char('$'))
+ state = OPTIONALVARIABLEBRACE;
+ } else if (state == OPTIONALVARIABLEBRACE) {
+ if (c == QLatin1Char('{')) {
+ state = BRACEDVARIABLE;
+ vStart = i;
+ } else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
+ state = VARIABLE;
+ vStart = i - 1;
+ } else {
+ state = BASE;
}
- state = BASE;
- }
- } else if (state == VARIABLE) {
- if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
- const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1));
- if (it != constEnd()) {
- result.replace(vStart - 1, i - vStart, *it);
- i = vStart - 1 + it->length();
+ } else if (state == BRACEDVARIABLE) {
+ if (c == QLatin1Char('}')) {
+ const_iterator it = m_values.constFind(result.mid(vStart, i - 1 - vStart));
+ if (it != constEnd()) {
+ result.replace(vStart - 2, i - vStart + 2, *it);
+ i = vStart - 2 + it->length();
+ }
+ state = BASE;
+ }
+ } else if (state == VARIABLE) {
+ if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
+ const_iterator it = m_values.constFind(result.mid(vStart, i - vStart - 1));
+ if (it != constEnd()) {
+ result.replace(vStart - 1, i - vStart, *it);
+ i = vStart - 1 + it->length();
+ }
+ state = BASE;
}
- state = BASE;
}
}
+ if (state == VARIABLE) {
+ const_iterator it = m_values.constFind(result.mid(vStart));
+ if (it != constEnd())
+ result.replace(vStart - 1, result.length() - vStart + 1, *it);
+ }
}
- if (state == VARIABLE) {
- const_iterator it = m_values.constFind(result.mid(vStart));
- if (it != constEnd())
- result.replace(vStart - 1, result.length() - vStart + 1, *it);
- }
-#endif
return result;
}
diff --git a/src/libs/utils/environment.h b/src/libs/utils/environment.h
index 214240d63d..dcadb13a77 100644
--- a/src/libs/utils/environment.h
+++ b/src/libs/utils/environment.h
@@ -34,6 +34,7 @@
#include <QList>
#include <QMap>
+#include <QProcessEnvironment>
#include <QString>
#include <QStringList>
@@ -70,6 +71,7 @@ public:
static Environment systemEnvironment();
QStringList toStringList() const;
+ QProcessEnvironment toProcessEnvironment() const;
QString value(const QString &key) const;
void set(const QString &key, const QString &value);
void unset(const QString &key);
@@ -78,6 +80,8 @@ public:
QList<EnvironmentItem> diff(const Environment &other) const;
bool hasKey(const QString &key);
+ QString userName() const;
+
void appendOrSet(const QString &key, const QString &value, const QString &sep = QString());
void prependOrSet(const QString &key, const QString &value, const QString &sep = QString());
diff --git a/src/libs/utils/environmentmodel.cpp b/src/libs/utils/environmentmodel.cpp
index cba1be4f99..1e4424ad60 100644
--- a/src/libs/utils/environmentmodel.cpp
+++ b/src/libs/utils/environmentmodel.cpp
@@ -30,8 +30,10 @@
#include "environmentmodel.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QFont>
+#include <QTextEdit>
namespace Utils {
namespace Internal {
@@ -46,9 +48,8 @@ public:
// Add removed variables again and mark them as "<UNSET>" so
// that the user can actually see those removals:
foreach (const Utils::EnvironmentItem &item, m_items) {
- if (item.unset) {
+ if (item.unset)
m_resultEnvironment.set(item.name, EnvironmentModel::tr("<UNSET>"));
- }
}
}
@@ -147,7 +148,14 @@ QVariant EnvironmentModel::data(const QModelIndex &index, int role) const
if (pos >= 0)
return d->m_items.at(pos).value;
}
- return d->m_resultEnvironment.value(d->m_resultEnvironment.constBegin() + index.row());
+ QString value = d->m_resultEnvironment.value(d->m_resultEnvironment.constBegin() + index.row());
+ if (role == Qt::ToolTipRole && value.length() > 80) {
+ // Use html to enable text wrapping
+ value = Qt::escape(value);
+ value.prepend(QLatin1String("<html><body>"));
+ value.append(QLatin1String("</body></html>"));
+ }
+ return value;
}
}
if (role == Qt::FontRole) {
@@ -201,11 +209,8 @@ bool EnvironmentModel::setData(const QModelIndex &index, const QVariant &value,
if (index.column() == 0) {
//fail if a variable with the same name already exists
-#if defined(Q_OS_WIN)
- const QString &newName = value.toString().toUpper();
-#else
- const QString &newName = value.toString();
-#endif
+ const QString &newName = HostOsInfo::isWindowsHost()
+ ? value.toString().toUpper() : value.toString();
// Does the new name exist already?
if (d->m_resultEnvironment.hasKey(newName) || newName.isEmpty())
return false;
diff --git a/src/libs/utils/fancylineedit.cpp b/src/libs/utils/fancylineedit.cpp
index e185bfb9d8..83802be857 100644
--- a/src/libs/utils/fancylineedit.cpp
+++ b/src/libs/utils/fancylineedit.cpp
@@ -58,18 +58,16 @@ static void execMenuAtWidget(QMenu *menu, QWidget *widget)
QSize sh = menu->sizeHint();
QRect rect = widget->rect();
if (widget->isRightToLeft()) {
- if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
+ if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height())
p = widget->mapToGlobal(rect.bottomRight());
- } else {
+ else
p = widget->mapToGlobal(rect.topRight() - QPoint(0, sh.height()));
- }
p.rx() -= sh.width();
} else {
- if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height()) {
+ if (widget->mapToGlobal(QPoint(0, rect.bottom())).y() + sh.height() <= screen.height())
p = widget->mapToGlobal(rect.bottomLeft());
- } else {
+ else
p = widget->mapToGlobal(rect.topLeft() - QPoint(0, sh.height()));
- }
}
p.rx() = qMax(screen.left(), qMin(p.x(), screen.right() - sh.width()));
p.ry() += 1;
diff --git a/src/libs/utils/fancymainwindow.cpp b/src/libs/utils/fancymainwindow.cpp
index a7de4e1124..0311b18005 100644
--- a/src/libs/utils/fancymainwindow.cpp
+++ b/src/libs/utils/fancymainwindow.cpp
@@ -105,11 +105,10 @@ QDockWidget *FancyMainWindow::addDockForWidget(QWidget *widget)
dockWidget->setWidget(widget);
// Set an object name to be used in settings, derive from widget name
const QString objectName = widget->objectName();
- if (objectName.isEmpty()) {
+ if (objectName.isEmpty())
dockWidget->setObjectName(QLatin1String("dockWidget") + QString::number(dockWidgets().size() + 1));
- } else {
+ else
dockWidget->setObjectName(objectName + QLatin1String("DockWidget"));
- }
connect(dockWidget->toggleViewAction(), SIGNAL(triggered()),
this, SLOT(onDockActionTriggered()), Qt::QueuedConnection);
connect(dockWidget, SIGNAL(visibilityChanged(bool)),
@@ -256,7 +255,7 @@ void FancyMainWindow::restoreSettings(const QHash<QString, QVariant> &settings)
QList<QDockWidget *> FancyMainWindow::dockWidgets() const
{
- return qFindChildren<QDockWidget *>(this);
+ return findChildren<QDockWidget *>();
}
bool FancyMainWindow::isLocked() const
@@ -274,7 +273,7 @@ static bool actionLessThan(const QAction *action1, const QAction *action2)
QMenu *FancyMainWindow::createPopupMenu()
{
QList<QAction *> actions;
- QList<QDockWidget *> dockwidgets = qFindChildren<QDockWidget *>(this);
+ QList<QDockWidget *> dockwidgets = findChildren<QDockWidget *>();
for (int i = 0; i < dockwidgets.size(); ++i) {
QDockWidget *dockWidget = dockwidgets.at(i);
if (dockWidget->property("managed_dockwidget").isNull()
diff --git a/src/libs/utils/filenamevalidatinglineedit.cpp b/src/libs/utils/filenamevalidatinglineedit.cpp
index dedae0c655..6fa95eac74 100644
--- a/src/libs/utils/filenamevalidatinglineedit.cpp
+++ b/src/libs/utils/filenamevalidatinglineedit.cpp
@@ -114,11 +114,10 @@ bool FileNameValidatingLineEdit::validateFileName(const QString &name,
if (name.contains(QLatin1Char(*c))) {
if (errorMessage) {
const QChar qc = QLatin1Char(*c);
- if (qc.isSpace()) {
+ if (qc.isSpace())
*errorMessage = tr("Name contains white space.");
- } else {
+ else
*errorMessage = tr("Invalid character '%1'.").arg(qc);
- }
}
return false;
}
@@ -171,17 +170,15 @@ bool FileNameValidatingLineEdit::validateFileNameExtension(const QString &fileNa
if (!requiredExtensions.isEmpty()) {
foreach (const QString &requiredExtension, requiredExtensions) {
QString extension = QLatin1String(".") + requiredExtension;
- if (fileName.endsWith(extension, Qt::CaseSensitive) && extension.count() < fileName.count()) {
+ if (fileName.endsWith(extension, Qt::CaseSensitive) && extension.count() < fileName.count())
return true;
- }
}
if (errorMessage) {
- if (requiredExtensions.count() == 1) {
+ if (requiredExtensions.count() == 1)
*errorMessage = tr("File extension %1 is required:").arg(requiredExtensions.first());
- } else {
+ else
*errorMessage = tr("File extensions %1 are required:").arg(requiredExtensions.join(QLatin1String(", ")));
- }
}
return false;
diff --git a/src/libs/utils/filesearch.cpp b/src/libs/utils/filesearch.cpp
index 4fd8bdc67e..75b4add40a 100644
--- a/src/libs/utils/filesearch.cpp
+++ b/src/libs/utils/filesearch.cpp
@@ -348,6 +348,72 @@ QString Utils::expandRegExpReplacement(const QString &replaceText, const QString
return result;
}
+namespace Utils {
+namespace Internal {
+QString matchCaseReplacement(const QString &originalText, const QString &replaceText)
+{
+ //Now proceed with actual case matching
+ bool firstIsUpperCase = originalText.at(0).isUpper();
+ bool firstIsLowerCase = originalText.at(0).isLower();
+ bool restIsLowerCase = true; // to be verified
+ bool restIsUpperCase = true; // to be verified
+
+ for (int i = 1; i < originalText.length(); ++i) {
+ if (originalText.at(i).isUpper())
+ restIsLowerCase = false;
+ else if (originalText.at(i).isLower())
+ restIsUpperCase = false;
+
+ if (!restIsLowerCase && !restIsUpperCase)
+ return replaceText; // mixed
+ }
+
+ if (restIsLowerCase) {
+ QString res = replaceText.toLower();
+ if (firstIsUpperCase)
+ res.replace(0, 1, res.at(0).toUpper());
+ return res;
+ }
+
+ if (restIsUpperCase) {
+ QString res = replaceText.toUpper();
+ if (firstIsLowerCase)
+ res.replace(0, 1, res.at(0).toLower());
+ return res;
+ }
+
+ return replaceText; // mixed
+}
+}
+}
+
+QString Utils::matchCaseReplacement(const QString &originalText, const QString &replaceText)
+{
+ if (originalText.isEmpty())
+ return replaceText;
+
+ //Find common prefix & suffix: these will be unaffected
+ const int replaceTextLen = replaceText.length();
+ const int originalTextLen = originalText.length();
+
+ int prefixLen = 0;
+ for (; prefixLen <= replaceTextLen && prefixLen <= originalTextLen; prefixLen++)
+ if (replaceText.at(prefixLen).toLower() != originalText.at(prefixLen).toLower())
+ break;
+
+ int suffixLen = 0;
+ for (; suffixLen < replaceTextLen - prefixLen && suffixLen < originalTextLen - prefixLen; suffixLen++)
+ if (replaceText.at(replaceTextLen - 1 - suffixLen).toLower() != originalText.at(originalTextLen- 1 - suffixLen).toLower())
+ break;
+
+ //keep prefix and suffix, and do actual replacement on the 'middle' of the string
+ return originalText.left(prefixLen)
+ + Internal::matchCaseReplacement(originalText.mid(prefixLen, originalTextLen - prefixLen - suffixLen),
+ replaceText.mid(prefixLen, replaceTextLen - prefixLen - suffixLen))
+ + originalText.right(suffixLen);
+
+}
+
// #pragma mark -- FileIterator
FileIterator::FileIterator()
@@ -427,15 +493,14 @@ bool SubDirFileIterator::hasNext() const
{
if (!m_currentFiles.isEmpty())
return true;
- while(!m_dirs.isEmpty() && m_currentFiles.isEmpty()) {
+ while (!m_dirs.isEmpty() && m_currentFiles.isEmpty()) {
QDir dir = m_dirs.pop();
const qreal dirProgressMax = m_progressValues.pop();
const bool processed = m_processedValues.pop();
if (dir.exists()) {
QStringList subDirs;
- if (!processed) {
+ if (!processed)
subDirs = dir.entryList(QDir::Dirs|QDir::Hidden|QDir::NoDotAndDotDot);
- }
if (subDirs.isEmpty()) {
QStringList fileEntries = dir.entryList(m_filters,
QDir::Files|QDir::Hidden);
diff --git a/src/libs/utils/filesearch.h b/src/libs/utils/filesearch.h
index 887a91231b..bf5bd4a9a6 100644
--- a/src/libs/utils/filesearch.h
+++ b/src/libs/utils/filesearch.h
@@ -118,6 +118,7 @@ QTCREATOR_UTILS_EXPORT QFuture<FileSearchResultList> findInFilesRegExp(const QSt
QTextDocument::FindFlags flags, QMap<QString, QString> fileToContentsMap = QMap<QString, QString>());
QTCREATOR_UTILS_EXPORT QString expandRegExpReplacement(const QString &replaceText, const QStringList &capturedTexts);
+QTCREATOR_UTILS_EXPORT QString matchCaseReplacement(const QString &originalText, const QString &replaceText);
} // namespace Utils
diff --git a/src/libs/utils/filesystemwatcher.cpp b/src/libs/utils/filesystemwatcher.cpp
index 01773fd196..adcdfc19b0 100644
--- a/src/libs/utils/filesystemwatcher.cpp
+++ b/src/libs/utils/filesystemwatcher.cpp
@@ -284,9 +284,8 @@ void FileSystemWatcher::removeFiles(const QStringList &files)
const int count = --(d->m_staticData->m_fileCount[file]);
Q_ASSERT(count >= 0);
- if (!count) {
+ if (!count)
toRemove << file;
- }
}
if (!toRemove.isEmpty())
@@ -362,9 +361,8 @@ void FileSystemWatcher::removeDirectories(const QStringList &directories)
const int count = --d->m_staticData->m_directoryCount[directory];
Q_ASSERT(count >= 0);
- if (!count) {
+ if (!count)
toRemove << directory;
- }
}
if (!toRemove.isEmpty())
d->m_staticData->m_watcher->removePaths(toRemove);
diff --git a/src/libs/utils/fileutils.cpp b/src/libs/utils/fileutils.cpp
index a8598f4b1a..93e09e93e0 100644
--- a/src/libs/utils/fileutils.cpp
+++ b/src/libs/utils/fileutils.cpp
@@ -30,6 +30,7 @@
#include "fileutils.h"
#include "savefile.h"
+#include "hostosinfo.h"
#include "qtcassert.h"
#include <QDir>
@@ -57,14 +58,14 @@ namespace Utils {
\return Whether the operation succeeded.
*/
-bool FileUtils::removeRecursively(const QString &filePath, QString *error)
+bool FileUtils::removeRecursively(const FileName &filePath, QString *error)
{
- QFileInfo fileInfo(filePath);
+ QFileInfo fileInfo = filePath.toFileInfo();
if (!fileInfo.exists() && !fileInfo.isSymLink())
return true;
- QFile::setPermissions(filePath, fileInfo.permissions() | QFile::WriteUser);
+ QFile::setPermissions(filePath.toString(), fileInfo.permissions() | QFile::WriteUser);
if (fileInfo.isDir()) {
- QDir dir(filePath);
+ QDir dir(filePath.toString());
dir = dir.canonicalPath();
if (dir.isRoot()) {
if (error) {
@@ -84,21 +85,21 @@ bool FileUtils::removeRecursively(const QString &filePath, QString *error)
QStringList fileNames = dir.entryList(QDir::Files | QDir::Hidden
| QDir::System | QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &fileName, fileNames) {
- if (!removeRecursively(filePath + QLatin1Char('/') + fileName, error))
+ if (!removeRecursively(FileName(filePath).appendPath(fileName), error))
return false;
}
if (!QDir::root().rmdir(dir.path())) {
if (error) {
*error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove directory '%1'.")
- .arg(QDir::toNativeSeparators(filePath));
+ .arg(filePath.toUserOutput());
}
return false;
}
} else {
- if (!QFile::remove(filePath)) {
+ if (!QFile::remove(filePath.toString())) {
if (error) {
*error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove file '%1'.")
- .arg(QDir::toNativeSeparators(filePath));
+ .arg(filePath.toUserOutput());
}
return false;
}
@@ -123,36 +124,36 @@ bool FileUtils::removeRecursively(const QString &filePath, QString *error)
\return Whether the operation succeeded.
*/
-bool FileUtils::copyRecursively(const QString &srcFilePath,
- const QString &tgtFilePath, QString *error)
+bool FileUtils::copyRecursively(const FileName &srcFilePath, const FileName &tgtFilePath,
+ QString *error)
{
- QFileInfo srcFileInfo(srcFilePath);
+ QFileInfo srcFileInfo = srcFilePath.toFileInfo();
if (srcFileInfo.isDir()) {
- QDir targetDir(tgtFilePath);
+ QDir targetDir(tgtFilePath.toString());
targetDir.cdUp();
- if (!targetDir.mkdir(QFileInfo(tgtFilePath).fileName())) {
+ if (!targetDir.mkdir(tgtFilePath.toFileInfo().fileName())) {
if (error) {
*error = QCoreApplication::translate("Utils::FileUtils", "Failed to create directory '%1'.")
- .arg(QDir::toNativeSeparators(tgtFilePath));
+ .arg(tgtFilePath.toUserOutput());
}
return false;
}
- QDir sourceDir(srcFilePath);
- QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
+ QDir sourceDir(srcFilePath.toString());
+ QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot
+ | QDir::Hidden | QDir::System);
foreach (const QString &fileName, fileNames) {
- const QString newSrcFilePath
- = srcFilePath + QLatin1Char('/') + fileName;
- const QString newTgtFilePath
- = tgtFilePath + QLatin1Char('/') + fileName;
+ FileName newSrcFilePath = srcFilePath;
+ newSrcFilePath.appendPath(fileName);
+ FileName newTgtFilePath = tgtFilePath;
+ newTgtFilePath.appendPath(fileName);
if (!copyRecursively(newSrcFilePath, newTgtFilePath, error))
return false;
}
} else {
- if (!QFile::copy(srcFilePath, tgtFilePath)) {
+ if (!QFile::copy(srcFilePath.toString(), tgtFilePath.toString())) {
if (error) {
*error = QCoreApplication::translate("Utils::FileUtils", "Could not copy file '%1' to '%2'.")
- .arg(QDir::toNativeSeparators(srcFilePath),
- QDir::toNativeSeparators(tgtFilePath));
+ .arg(srcFilePath.toUserOutput(), tgtFilePath.toUserOutput());
}
return false;
}
@@ -167,19 +168,16 @@ bool FileUtils::copyRecursively(const QString &srcFilePath,
\return Whether at least one file in \a filePath has a newer date than \a timeStamp.
*/
-bool FileUtils::isFileNewerThan(const QString &filePath,
- const QDateTime &timeStamp)
+bool FileUtils::isFileNewerThan(const FileName &filePath, const QDateTime &timeStamp)
{
- QFileInfo fileInfo(filePath);
+ QFileInfo fileInfo = filePath.toFileInfo();
if (!fileInfo.exists() || fileInfo.lastModified() >= timeStamp)
return true;
if (fileInfo.isDir()) {
- const QStringList dirContents = QDir(filePath)
+ const QStringList dirContents = QDir(filePath.toString())
.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
foreach (const QString &curFileName, dirContents) {
- const QString curFilePath
- = filePath + QLatin1Char('/') + curFileName;
- if (isFileNewerThan(curFilePath, timeStamp))
+ if (isFileNewerThan(FileName(filePath).appendPath(curFileName), timeStamp))
return true;
}
}
@@ -195,15 +193,33 @@ bool FileUtils::isFileNewerThan(const QString &filePath,
return Symlink target file path.
*/
-QString FileUtils::resolveSymlinks(const QString &path)
+FileName FileUtils::resolveSymlinks(const FileName &path)
{
- QFileInfo f(path);
+ QFileInfo f = path.toFileInfo();
int links = 16;
while (links-- && f.isSymLink())
f.setFile(f.symLinkTarget());
if (links <= 0)
- return QString();
- return f.filePath();
+ return FileName();
+ return FileName::fromString(f.filePath());
+}
+
+/*!
+ Like QDir::toNativeSeparators(), but use prefix '~' instead of $HOME on unix systems when an
+ absolute path is given.
+
+ return Possibly shortened path with native separators.
+*/
+QString FileUtils::shortNativePath(const FileName &path)
+{
+ if (HostOsInfo::isAnyUnixHost()) {
+ const FileName home = FileName::fromString(QDir::cleanPath(QDir::homePath()));
+ if (path.isChildOf(home)) {
+ return QLatin1Char('~') + QDir::separator()
+ + QDir::toNativeSeparators(path.relativeChildPath(home).toString());
+ }
+ }
+ return path.toUserOutput();
}
QByteArray FileReader::fetchQrc(const QString &fileName)
@@ -411,13 +427,6 @@ TempFileSaver::~TempFileSaver()
On windows filenames are compared case insensitively.
*/
-
-#ifdef Q_OS_WIN
-Qt::CaseSensitivity FileName::cs = Qt::CaseInsensitive;
-#else
-Qt::CaseSensitivity FileName::cs = Qt::CaseSensitive;
-#endif
-
FileName::FileName()
: QString()
{
@@ -480,10 +489,9 @@ FileName FileName::fromString(const QString &filename)
/// Constructs a FileName from \a fileName
/// \a fileName is only passed through QDir::cleanPath
-/// and QDir::fromNativeSeparators
FileName FileName::fromUserInput(const QString &filename)
{
- return FileName(QDir::cleanPath(QDir::fromNativeSeparators(filename)));
+ return FileName(QDir::cleanPath(filename));
}
FileName::FileName(const QString &string)
@@ -494,7 +502,7 @@ FileName::FileName(const QString &string)
bool FileName::operator==(const FileName &other) const
{
- return QString::compare(*this, other, cs) == 0;
+ return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) == 0;
}
bool FileName::operator!=(const FileName &other) const
@@ -504,12 +512,12 @@ bool FileName::operator!=(const FileName &other) const
bool FileName::operator<(const FileName &other) const
{
- return QString::compare(*this, other, cs) < 0;
+ return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) < 0;
}
bool FileName::operator<=(const FileName &other) const
{
- return QString::compare(*this, other, cs) <= 0;
+ return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) <= 0;
}
bool FileName::operator>(const FileName &other) const
@@ -527,7 +535,7 @@ bool FileName::isChildOf(const FileName &s) const
{
if (s.isEmpty())
return false;
- if (!QString::startsWith(s, cs))
+ if (!QString::startsWith(s, HostOsInfo::fileNameCaseSensitivity()))
return false;
if (size() <= s.size())
return false;
@@ -547,7 +555,7 @@ bool FileName::isChildOf(const QDir &dir) const
/// \returns whether FileName endsWith \a s
bool FileName::endsWith(const QString &s) const
{
- return QString::endsWith(s, cs);
+ return QString::endsWith(s, HostOsInfo::fileNameCaseSensitivity());
}
/// \returns the relativeChildPath of FileName to parent if FileName is a child of parent
@@ -586,10 +594,8 @@ FileName &FileName::append(QChar str)
QT_BEGIN_NAMESPACE
uint qHash(const Utils::FileName &a)
{
-#ifdef Q_OS_WIN
- return qHash(a.toString().toUpper());
-#else
+ if (Utils::HostOsInfo::isWindowsHost())
+ return qHash(a.toString().toUpper());
return qHash(a.toString());
-#endif
}
QT_END_NAMESPACE
diff --git a/src/libs/utils/fileutils.h b/src/libs/utils/fileutils.h
index 741d937452..6f328d74bb 100644
--- a/src/libs/utils/fileutils.h
+++ b/src/libs/utils/fileutils.h
@@ -49,14 +49,53 @@ QT_END_NAMESPACE
namespace Utils {
+class QTCREATOR_UTILS_EXPORT FileName : private QString
+{
+public:
+ FileName();
+ explicit FileName(const QFileInfo &info);
+ QFileInfo toFileInfo() const;
+ static FileName fromString(const QString &filename);
+ static FileName fromUserInput(const QString &filename);
+ QString toString() const;
+ QString toUserOutput() const;
+
+ FileName parentDir() const;
+
+ bool operator==(const FileName &other) const;
+ bool operator!=(const FileName &other) const;
+ bool operator<(const FileName &other) const;
+ bool operator<=(const FileName &other) const;
+ bool operator>(const FileName &other) const;
+ bool operator>=(const FileName &other) const;
+
+ bool isChildOf(const FileName &s) const;
+ bool isChildOf(const QDir &dir) const;
+ bool endsWith(const QString &s) const;
+
+ Utils::FileName relativeChildPath(const FileName &parent) const;
+ Utils::FileName &appendPath(const QString &s);
+ Utils::FileName &append(const QString &str);
+ Utils::FileName &append(QChar str);
+
+ using QString::size;
+ using QString::count;
+ using QString::length;
+ using QString::isEmpty;
+ using QString::isNull;
+ using QString::clear;
+private:
+ FileName(const QString &string);
+};
+
class QTCREATOR_UTILS_EXPORT FileUtils {
public:
- static bool removeRecursively(const QString &filePath, QString *error = 0);
- static bool copyRecursively(const QString &srcFilePath,
- const QString &tgtFilePath, QString *error = 0);
- static bool isFileNewerThan(const QString &filePath,
- const QDateTime &timeStamp);
- static QString resolveSymlinks(const QString &path);
+ static bool removeRecursively(const FileName &filePath, QString *error = 0);
+ static bool copyRecursively(const FileName &srcFilePath, const FileName &tgtFilePath,
+ QString *error = 0);
+ static bool isFileNewerThan(const FileName &filePath, const QDateTime &timeStamp);
+ static FileName resolveSymlinks(const FileName &path);
+ static QString shortNativePath(const FileName &path);
};
class QTCREATOR_UTILS_EXPORT FileReader
@@ -138,46 +177,6 @@ private:
bool m_autoRemove;
};
-class QTCREATOR_UTILS_EXPORT FileName : private QString
-{
-public:
- FileName();
- explicit FileName(const QFileInfo &info);
- QFileInfo toFileInfo() const;
- static FileName fromString(const QString &filename);
- static FileName fromUserInput(const QString &filename);
- QString toString() const;
- QString toUserOutput() const;
-
- FileName parentDir() const;
-
- bool operator==(const FileName &other) const;
- bool operator!=(const FileName &other) const;
- bool operator<(const FileName &other) const;
- bool operator<=(const FileName &other) const;
- bool operator>(const FileName &other) const;
- bool operator>=(const FileName &other) const;
-
- bool isChildOf(const FileName &s) const;
- bool isChildOf(const QDir &dir) const;
- bool endsWith(const QString &s) const;
-
- Utils::FileName relativeChildPath(const FileName &parent) const;
- Utils::FileName &appendPath(const QString &s);
- Utils::FileName &append(const QString &str);
- Utils::FileName &append(QChar str);
-
- using QString::size;
- using QString::count;
- using QString::length;
- using QString::isEmpty;
- using QString::isNull;
- using QString::clear;
-private:
- static Qt::CaseSensitivity cs;
- FileName(const QString &string);
-};
-
} // namespace Utils
QT_BEGIN_NAMESPACE
diff --git a/src/libs/utils/filewizarddialog.cpp b/src/libs/utils/filewizarddialog.cpp
index ddb2c38da0..72d63c3842 100644
--- a/src/libs/utils/filewizarddialog.cpp
+++ b/src/libs/utils/filewizarddialog.cpp
@@ -30,6 +30,8 @@
#include "filewizarddialog.h"
#include "filewizardpage.h"
+#include "hostosinfo.h"
+
#include <QAbstractButton>
/*!
@@ -48,15 +50,15 @@ FileWizardDialog::FileWizardDialog(QWidget *parent) :
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setOption(QWizard::NoCancelButton, false);
setOption(QWizard::NoDefaultButton, false);
-#ifdef Q_OS_MAC
- setButtonLayout(QList<QWizard::WizardButton>()
- << QWizard::CancelButton
- << QWizard::Stretch
- << QWizard::BackButton
- << QWizard::NextButton
- << QWizard::CommitButton
- << QWizard::FinishButton);
-#endif
+ if (HostOsInfo::isMacHost()) {
+ setButtonLayout(QList<QWizard::WizardButton>()
+ << QWizard::CancelButton
+ << QWizard::Stretch
+ << QWizard::BackButton
+ << QWizard::NextButton
+ << QWizard::CommitButton
+ << QWizard::FinishButton);
+ }
const int filePageId = addPage(m_filePage);
wizardProgress()->item(filePageId)->setTitle(tr("Location"));
connect(m_filePage, SIGNAL(activated()), button(QWizard::FinishButton), SLOT(animateClick()));
diff --git a/src/libs/utils/filewizardpage.ui b/src/libs/utils/filewizardpage.ui
index 17b78cae6d..e8b3ca1b4b 100644
--- a/src/libs/utils/filewizardpage.ui
+++ b/src/libs/utils/filewizardpage.ui
@@ -45,7 +45,7 @@
<customwidget>
<class>Utils::PathChooser</class>
<extends>QWidget</extends>
- <header>pathchooser.h</header>
+ <header location="global">utils/pathchooser.h</header>
<container>1</container>
</customwidget>
</customwidgets>
diff --git a/src/libs/utils/flowlayout.cpp b/src/libs/utils/flowlayout.cpp
index dd06e2eb03..aa5e4bc39d 100644
--- a/src/libs/utils/flowlayout.cpp
+++ b/src/libs/utils/flowlayout.cpp
@@ -61,20 +61,18 @@ void FlowLayout::addItem(QLayoutItem *item)
int FlowLayout::horizontalSpacing() const
{
- if (m_hSpace >= 0) {
+ if (m_hSpace >= 0)
return m_hSpace;
- } else {
+ else
return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
- }
}
int FlowLayout::verticalSpacing() const
{
- if (m_vSpace >= 0) {
+ if (m_vSpace >= 0)
return m_vSpace;
- } else {
+ else
return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
- }
}
int FlowLayout::count() const
diff --git a/src/libs/utils/historycompleter.cpp b/src/libs/utils/historycompleter.cpp
index 4a877880d2..d3a1662e04 100644
--- a/src/libs/utils/historycompleter.cpp
+++ b/src/libs/utils/historycompleter.cpp
@@ -138,17 +138,20 @@ bool HistoryCompleterPrivate::removeRows(int row, int count, const QModelIndex &
void HistoryCompleterPrivate::clearHistory()
{
+ beginResetModel();
list.clear();
- reset();
+ endResetModel();
}
void HistoryCompleterPrivate::saveEntry(const QString &str)
{
QTC_ASSERT(theSettings, return);
- if (str.isEmpty())
- return;
- if (list.contains(str))
- return;
+ int removeIndex = list.indexOf(str);
+ if (removeIndex != -1) {
+ beginRemoveRows(QModelIndex(), removeIndex, removeIndex);
+ list.removeAt(removeIndex);
+ endRemoveRows();
+ }
beginInsertRows (QModelIndex(), list.count(), list.count());
list.prepend(str);
list = list.mid(0, maxLines);
diff --git a/tests/auto/icheckbuild/ichecklib_global.h b/src/libs/utils/hostosinfo.cpp
index 597805bfc2..6e103a6dc8 100644
--- a/tests/auto/icheckbuild/ichecklib_global.h
+++ b/src/libs/utils/hostosinfo.cpp
@@ -1,4 +1,4 @@
-/****************************************************************************
+/**************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
@@ -27,20 +27,32 @@
**
****************************************************************************/
-#ifndef ICHECKLIB_GLOBAL_H
-#define ICHECKLIB_GLOBAL_H
+#include "hostosinfo.h"
-#include <qglobal.h>
+#ifdef Q_OS_WIN
+#include <windows.h>
+#endif
+using namespace Utils;
-#ifdef ICHECK_APP_BUILD
-# define ICHECKLIBSHARED_EXPORT
+HostOsInfo::HostArchitecture HostOsInfo::hostArchitecture()
+{
+#ifdef Q_OS_WIN
+ SYSTEM_INFO info;
+ GetNativeSystemInfo(&info);
+ switch (info.wProcessorArchitecture) {
+ case PROCESSOR_ARCHITECTURE_AMD64:
+ return HostOsInfo::HostArchitectureAMD64;
+ case PROCESSOR_ARCHITECTURE_INTEL:
+ return HostOsInfo::HostArchitectureX86;
+ case PROCESSOR_ARCHITECTURE_IA64:
+ return HostOsInfo::HostArchitectureItanium;
+ case PROCESSOR_ARCHITECTURE_ARM:
+ return HostOsInfo::HostArchitectureArm;
+ default:
+ return HostOsInfo::HostArchitectureUnknown;
+ }
#else
-# if defined(ICHECKLIB_LIBRARY)
-# define ICHECKLIBSHARED_EXPORT Q_DECL_EXPORT
-# else
-# define ICHECKLIBSHARED_EXPORT Q_DECL_IMPORT
-# endif
+ return HostOsInfo::HostArchitectureUnknown;
#endif
-
-#endif // ICHECKLIB_GLOBAL_H
+}
diff --git a/src/libs/utils/hostosinfo.h b/src/libs/utils/hostosinfo.h
new file mode 100644
index 0000000000..1b0919f7c1
--- /dev/null
+++ b/src/libs/utils/hostosinfo.h
@@ -0,0 +1,111 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef HOSTOSINFO_H
+#define HOSTOSINFO_H
+
+#include "utils_global.h"
+
+#include <QString>
+
+#ifdef Q_OS_WIN
+#define QTC_HOST_EXE_SUFFIX ".exe"
+#else
+#define QTC_HOST_EXE_SUFFIX ""
+#endif // Q_OS_WIN
+
+namespace Utils {
+
+class QTCREATOR_UTILS_EXPORT HostOsInfo
+{
+public:
+ // Add more as needed.
+ enum HostOs { HostOsWindows, HostOsLinux, HostOsMac, HostOsOtherUnix, HostOsOther };
+ static inline HostOs hostOs();
+
+ enum HostArchitecture { HostArchitectureX86, HostArchitectureAMD64, HostArchitectureItanium,
+ HostArchitectureArm, HostArchitectureUnknown };
+ static HostArchitecture hostArchitecture();
+
+ static bool isWindowsHost() { return hostOs() == HostOsWindows; }
+ static bool isLinuxHost() { return hostOs() == HostOsLinux; }
+ static bool isMacHost() { return hostOs() == HostOsMac; }
+ static inline bool isAnyUnixHost();
+
+ static QString appendExecutableSuffix(const QString &executable)
+ {
+ QString finalName = executable;
+ if (isWindowsHost())
+ finalName += QLatin1String(QTC_HOST_EXE_SUFFIX);
+ return finalName;
+ }
+
+ static Qt::CaseSensitivity fileNameCaseSensitivity()
+ {
+ return isWindowsHost() ? Qt::CaseInsensitive: Qt::CaseSensitive;
+ }
+
+ static QChar pathListSeparator()
+ {
+ return isWindowsHost() ? QLatin1Char(';') : QLatin1Char(':');
+ }
+
+ static Qt::KeyboardModifier controlModifier()
+ {
+ return isMacHost() ? Qt::MetaModifier : Qt::ControlModifier;
+ }
+};
+
+HostOsInfo::HostOs HostOsInfo::hostOs()
+{
+#if defined(Q_OS_WIN)
+ return HostOsWindows;
+#elif defined(Q_OS_LINUX)
+ return HostOsLinux;
+#elif defined(Q_OS_MAC)
+ return HostOsMac;
+#elif defined(Q_OS_UNIX)
+ return HostOsOtherUnix;
+#else
+ return HostOsOther;
+#endif
+}
+
+bool HostOsInfo::isAnyUnixHost()
+{
+#ifdef Q_OS_UNIX
+ return true;
+#else
+ return false;
+#endif
+}
+
+} // namespace Utils
+
+#endif // HOSTOSINFO_H
diff --git a/src/libs/utils/json.cpp b/src/libs/utils/json.cpp
index fd3f4032de..a173691068 100644
--- a/src/libs/utils/json.cpp
+++ b/src/libs/utils/json.cpp
@@ -353,8 +353,7 @@ int JsonSchema::itemArraySchemaSize() const
*
* The method also marks the context as being inside an array evaluation.
*
- * \param index
- * \return whether it was necessary to "enter" a schema for the supplied array index
+ * \return whether it was necessary to "enter" a schema for the supplied array index, false if index is out of bounds
*/
bool JsonSchema::maybeEnterNestedArraySchema(int index)
{
@@ -730,9 +729,8 @@ JsonSchema *JsonSchemaManager::parseSchema(const QString &schemaFileName) const
if (reader.fetch(schemaFileName, QIODevice::Text)) {
const QString &contents = QString::fromUtf8(reader.data());
JsonValue *json = JsonValue::create(contents);
- if (json && json->kind() == JsonValue::Object) {
+ if (json && json->kind() == JsonValue::Object)
return new JsonSchema(json->toObject(), this);
- }
}
return 0;
diff --git a/src/libs/utils/networkaccessmanager.cpp b/src/libs/utils/networkaccessmanager.cpp
index bb6198e8fc..35c921000d 100644
--- a/src/libs/utils/networkaccessmanager.cpp
+++ b/src/libs/utils/networkaccessmanager.cpp
@@ -29,6 +29,7 @@
#include "networkaccessmanager.h"
+#include <QCoreApplication>
#include <QLocale>
#include <QUrl>
#include <QNetworkReply>
@@ -37,8 +38,6 @@
#include <sys/utsname.h>
#endif
-#include <app/app_version.h>
-
/*!
\class Utils::NetworkManager
@@ -130,8 +129,9 @@ void NetworkAccessManager::getUrl(const QUrl &url)
QNetworkReply* NetworkAccessManager::createRequest(Operation op, const QNetworkRequest &request, QIODevice *outgoingData)
{
- QString agentStr = QString::fromLatin1("Qt-Creator/%1 (QNetworkAccessManager %2; %3; %4; %5 bit)")
- .arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),
+ QString agentStr = QString::fromLatin1("%1/%2 (QNetworkAccessManager %3; %4; %5; %6 bit)")
+ .arg(QCoreApplication::applicationName(),
+ QCoreApplication::applicationVersion(),
QLatin1String(qVersion()),
getOsString(), QLocale::system().name())
.arg(QSysInfo::WordSize);
diff --git a/src/libs/utils/newclasswidget.cpp b/src/libs/utils/newclasswidget.cpp
index 66c2905134..9a66819cd1 100644
--- a/src/libs/utils/newclasswidget.cpp
+++ b/src/libs/utils/newclasswidget.cpp
@@ -419,6 +419,8 @@ static inline NewClassWidget::ClassType classTypeForBaseClass(const QString &bas
// Declarative Items
if (baseClass == QLatin1String("QDeclarativeItem"))
return NewClassWidget::ClassInheritsQDeclarativeItem;
+ if (baseClass == QLatin1String("QQuickItem"))
+ return NewClassWidget::ClassInheritsQQuickItem;
return NewClassWidget::NoClassType;
}
diff --git a/src/libs/utils/newclasswidget.h b/src/libs/utils/newclasswidget.h
index ce450ed57d..422d4ea8af 100644
--- a/src/libs/utils/newclasswidget.h
+++ b/src/libs/utils/newclasswidget.h
@@ -71,9 +71,13 @@ class QTCREATOR_UTILS_EXPORT NewClassWidget : public QWidget
Q_ENUMS(ClassType)
public:
- enum ClassType { NoClassType, ClassInheritsQObject, ClassInheritsQWidget,
+ enum ClassType { NoClassType,
+ ClassInheritsQObject,
+ ClassInheritsQWidget,
ClassInheritsQDeclarativeItem,
- SharedDataClass };
+ ClassInheritsQQuickItem,
+ SharedDataClass
+ };
explicit NewClassWidget(QWidget *parent = 0);
~NewClassWidget();
diff --git a/src/libs/utils/newclasswidget.ui b/src/libs/utils/newclasswidget.ui
index dc3c315e86..7279892c55 100644
--- a/src/libs/utils/newclasswidget.ui
+++ b/src/libs/utils/newclasswidget.ui
@@ -71,7 +71,12 @@
</item>
<item>
<property name="text">
- <string>Inherits QDeclarativeItem</string>
+ <string>Inherits QDeclarativeItem - Qt Quick 1</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Inherits QQuickItem - Qt Quick 2</string>
</property>
</item>
<item>
diff --git a/src/libs/utils/parameteraction.cpp b/src/libs/utils/parameteraction.cpp
index 9bed475a64..340c5ee264 100644
--- a/src/libs/utils/parameteraction.cpp
+++ b/src/libs/utils/parameteraction.cpp
@@ -93,11 +93,10 @@ void ParameterAction::setEnablingMode(EnablingMode m)
void ParameterAction::setParameter(const QString &p)
{
const bool enabled = !p.isEmpty();
- if (enabled) {
+ if (enabled)
setText(m_parameterText.arg(p));
- } else {
+ else
setText(m_emptyText);
- }
if (m_enablingMode == EnabledWithParameter)
setEnabled(enabled);
}
diff --git a/src/libs/utils/pathchooser.cpp b/src/libs/utils/pathchooser.cpp
index 1de404e6de..83dbc51587 100644
--- a/src/libs/utils/pathchooser.cpp
+++ b/src/libs/utils/pathchooser.cpp
@@ -34,19 +34,19 @@
#include "qtcassert.h"
#include "synchronousprocess.h"
+#include "hostosinfo.h"
#include <QDebug>
-#include <QDir>
-#include <QFileInfo>
-#include <QSettings>
-#include <QProcess>
-
-#include <qevent.h>
#include <QDesktopServices>
+#include <QDir>
+#include <QEvent>
#include <QFileDialog>
+#include <QFileInfo>
#include <QHBoxLayout>
#include <QLineEdit>
+#include <QProcess>
#include <QPushButton>
+#include <QSettings>
/*!
\class Utils::PathChooser
@@ -57,7 +57,7 @@
Has some validation logic for embedding into QWizardPage.
*/
-/*static*/ const char * const Utils::PathChooser::browseButtonLabel =
+const char * const Utils::PathChooser::browseButtonLabel =
#ifdef Q_OS_MAC
QT_TRANSLATE_NOOP("Utils::PathChooser", "Choose...");
#else
@@ -426,6 +426,11 @@ QString PathChooser::errorMessage() const
return d->m_lineEdit->errorMessage();
}
+void PathChooser::triggerChanged()
+{
+ d->m_lineEdit->triggerChanged();
+}
+
bool PathChooser::validatePath(const QString &path, QString *errorMessage)
{
QString expandedPath = d->expandedPath(path);
@@ -541,14 +546,12 @@ QString PathChooser::label()
QString PathChooser::homePath()
{
-#ifdef Q_OS_WIN
// Return 'users/<name>/Documents' on Windows, since Windows explorer
// does not let people actually display the contents of their home
// directory. Alternatively, create a QtCreator-specific directory?
- return QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
-#else
+ if (HostOsInfo::isWindowsHost())
+ return QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
return QDir::homePath();
-#endif
}
void PathChooser::setExpectedKind(Kind expected)
diff --git a/src/libs/utils/pathchooser.h b/src/libs/utils/pathchooser.h
index 3ac5c86b76..dcb43ed8c1 100644
--- a/src/libs/utils/pathchooser.h
+++ b/src/libs/utils/pathchooser.h
@@ -131,6 +131,7 @@ public:
bool isReadOnly() const;
void setReadOnly(bool b);
+ void triggerChanged();
private:
// Returns overridden title or the one from <title>
QString makeDialogTitle(const QString &title);
diff --git a/src/libs/utils/pathlisteditor.cpp b/src/libs/utils/pathlisteditor.cpp
index 4f25705315..58ecee520b 100644
--- a/src/libs/utils/pathlisteditor.cpp
+++ b/src/libs/utils/pathlisteditor.cpp
@@ -29,6 +29,8 @@
#include "pathlisteditor.h"
+#include "hostosinfo.h"
+
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QPlainTextEdit>
@@ -91,7 +93,7 @@ void PathListPlainTextEdit::insertFromMimeData(const QMimeData *source)
if (source->hasText()) {
// replace separator
QString text = source->text().trimmed();
- text.replace(PathListEditor::separator(), QLatin1Char('\n'));
+ text.replace(HostOsInfo::pathListSeparator(), QLatin1Char('\n'));
QSharedPointer<QMimeData> fixed(new QMimeData);
fixed->setText(text);
QPlainTextEdit::insertFromMimeData(fixed.data());
@@ -172,11 +174,10 @@ QAction *PathListEditor::insertAction(int index /* -1 */, const QString &text, Q
beforeAction = actions.at(index);
}
QAction *rc = createAction(this, text, receiver, slotFunc);
- if (beforeAction) {
+ if (beforeAction)
d->buttonMenu->insertAction(beforeAction, rc);
- } else {
+ else
d->buttonMenu->addAction(rc);
- }
return rc;
}
@@ -187,7 +188,7 @@ int PathListEditor::lastAddActionIndex()
QString PathListEditor::pathListString() const
{
- return pathList().join(separator());
+ return pathList().join(HostOsInfo::pathListSeparator());
}
QStringList PathListEditor::pathList() const
@@ -213,7 +214,8 @@ void PathListEditor::setPathList(const QString &pathString)
if (pathString.isEmpty()) {
clear();
} else {
- setPathList(pathString.split(separator(), QString::SkipEmptyParts));
+ setPathList(pathString.split(HostOsInfo::pathListSeparator(),
+ QString::SkipEmptyParts));
}
}
@@ -251,16 +253,6 @@ void PathListEditor::slotInsert()
insertPathAtCursor(QDir::toNativeSeparators(dir));
}
-QChar PathListEditor::separator()
-{
-#ifdef Q_OS_WIN
- static const QChar rc(QLatin1Char(';'));
-#else
- static const QChar rc(QLatin1Char(':'));
-#endif
- return rc;
-}
-
// Add a button "Import from 'Path'"
void PathListEditor::addEnvVariableImportAction(const QString &var)
{
diff --git a/src/libs/utils/pathlisteditor.h b/src/libs/utils/pathlisteditor.h
index cad91b3037..b12c5a85cc 100644
--- a/src/libs/utils/pathlisteditor.h
+++ b/src/libs/utils/pathlisteditor.h
@@ -53,8 +53,6 @@ public:
QStringList pathList() const;
QString fileDialogTitle() const;
- static QChar separator();
-
// Add a convenience action "Import from 'Path'" (environment variable)
void addEnvVariableImportAction(const QString &var);
diff --git a/src/libs/utils/persistentsettings.cpp b/src/libs/utils/persistentsettings.cpp
index ad5841bcdc..29d1510e12 100644
--- a/src/libs/utils/persistentsettings.cpp
+++ b/src/libs/utils/persistentsettings.cpp
@@ -29,8 +29,6 @@
#include "persistentsettings.h"
-#include <app/app_version.h>
-
#include <utils/fileutils.h>
#include <QDebug>
@@ -403,8 +401,9 @@ bool PersistentSettingsWriter::write(const QVariantMap &data, QWidget *parent) c
w.setAutoFormattingIndent(1); // Historical, used to be QDom.
w.writeStartDocument();
w.writeDTD(QLatin1String("<!DOCTYPE ") + m_docType + QLatin1Char('>'));
- w.writeComment(QString::fromAscii(" Written by Qt Creator %1, %2. ").
- arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),
+ w.writeComment(QString::fromLatin1(" Written by %1 %2, %3. ").
+ arg(QCoreApplication::applicationName(),
+ QCoreApplication::applicationVersion(),
QDateTime::currentDateTime().toString(Qt::ISODate)));
w.writeStartElement(ctx.qtCreatorElement);
const QVariantMap::const_iterator cend = data.constEnd();
diff --git a/src/libs/utils/portlist.cpp b/src/libs/utils/portlist.cpp
index c00ff978d8..94e376abd1 100644
--- a/src/libs/utils/portlist.cpp
+++ b/src/libs/utils/portlist.cpp
@@ -116,7 +116,7 @@ private:
}
bool atEnd() const { return m_pos == m_portsSpec.length(); }
- char nextChar() const { return m_portsSpec.at(m_pos).toAscii(); }
+ char nextChar() const { return m_portsSpec.at(m_pos).toLatin1(); }
PortList m_portList;
int m_pos;
diff --git a/src/libs/utils/process_stub_unix.c b/src/libs/utils/process_stub_unix.c
index 3fc03d5257..7ab6a3e0bf 100644
--- a/src/libs/utils/process_stub_unix.c
+++ b/src/libs/utils/process_stub_unix.c
@@ -45,6 +45,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
+#include <assert.h>
/* For OpenBSD */
#ifndef EPROTO
@@ -55,6 +56,10 @@ extern char **environ;
static int qtcFd;
static char *sleepMsg;
+static int chldPipe[2];
+static int isDebug;
+static volatile int isDetached;
+static volatile int chldPid;
static void __attribute__((noreturn)) doExit(int code)
{
@@ -71,10 +76,10 @@ static void sendMsg(const char *msg, int num)
char pidStr[64];
pidStrLen = sprintf(pidStr, msg, num);
- if ((ioRet = write(qtcFd, pidStr, pidStrLen)) != pidStrLen) {
+ if (!isDetached && (ioRet = write(qtcFd, pidStr, pidStrLen)) != pidStrLen) {
fprintf(stderr, "Cannot write to creator comm socket: %s\n",
(ioRet < 0) ? strerror(errno) : "short write");
- doExit(3);
+ isDetached = 2;
}
}
@@ -88,16 +93,88 @@ enum {
ArgExe
};
+/* Handle sigchld */
+static void sigchldHandler(int sig)
+{
+ int chldStatus;
+ /* Currently we have only one child, so we exit in case of error. */
+ int waitRes;
+ (void)sig;
+ for (;;) {
+ waitRes = waitpid(-1, &chldStatus, WNOHANG);
+ if (!waitRes)
+ break;
+ if (waitRes < 0) {
+ perror("Cannot obtain exit status of child process");
+ doExit(3);
+ }
+ if (WIFSTOPPED(chldStatus)) {
+ /* The child stopped. This can be only the result of ptrace(TRACE_ME). */
+ /* We won't need the notification pipe any more, as we know that
+ * the exec() succeeded. */
+ close(chldPipe[0]);
+ close(chldPipe[1]);
+ chldPipe[0] = -1;
+ /* If we are not debugging, just skip the "handover enabler".
+ * This is suboptimal, as it makes us ignore setuid/-gid bits. */
+ if (isDebug) {
+ /* Stop the child after we detach from it, so we can hand it over to gdb.
+ * If the signal delivery is not queued, things will go awry. It works on
+ * Linux and MacOSX ... */
+ kill(chldPid, SIGSTOP);
+ }
+#ifdef __linux__
+ ptrace(PTRACE_DETACH, chldPid, 0, 0);
+#else
+ ptrace(PT_DETACH, chldPid, 0, 0);
+#endif
+ sendMsg("pid %d\n", chldPid);
+ if (isDetached == 2 && isDebug) {
+ /* qtcreator was not informed and died while debugging, killing the child */
+ kill(chldPid, SIGKILL);
+ }
+ } else if (WIFEXITED(chldStatus)) {
+ int errNo;
+
+ /* The child exited normally. */
+ if (chldPipe[0] >= 0) {
+ /* The child exited before being stopped by ptrace(). That can only
+ * mean that the exec() failed. */
+ switch (read(chldPipe[0], &errNo, sizeof(errNo))) {
+ default:
+ /* Read of unknown length. Should never happen ... */
+ errno = EPROTO;
+ /* fallthrough */
+ case -1:
+ /* Read failed. Should never happen, either ... */
+ perror("Cannot read status from child process");
+ doExit(3);
+ case sizeof(errNo):
+ /* Child telling us the errno from exec(). */
+ sendMsg("err:exec %d\n", errNo);
+ doExit(3);
+ }
+ }
+ sendMsg("exit %d\n", WEXITSTATUS(chldStatus));
+ doExit(0);
+ } else {
+ sendMsg("crash %d\n", WTERMSIG(chldStatus));
+ doExit(0);
+ }
+ }
+}
+
+
/* syntax: $0 {"run"|"debug"} <pid-socket> <continuation-msg> <workdir> <env-file> <exe> <args...> */
/* exit codes: 0 = ok, 1 = invocation error, 3 = internal error */
int main(int argc, char *argv[])
{
- int errNo;
- int chldPid;
- int chldStatus;
- int chldPipe[2];
+ int errNo, hadInvalidCommand = 0;
char **env = 0;
struct sockaddr_un sau;
+ struct sigaction act;
+
+ memset(&act, 0, sizeof(act));
if (argc < ArgEnv) {
fprintf(stderr, "This is an internal helper of Qt Creator. Do not run it manually.\n");
@@ -118,6 +195,11 @@ int main(int argc, char *argv[])
doExit(1);
}
+ isDebug = !strcmp(argv[ArgAction], "debug");
+ isDetached = 0;
+
+ sendMsg("spid %ld\n", (long)getpid());
+
if (*argv[ArgDir] && chdir(argv[ArgDir])) {
/* Only expected error: no such file or direcotry */
sendMsg("err:chdir %d\n", errno);
@@ -154,10 +236,26 @@ int main(int argc, char *argv[])
}
- /* Ignore SIGTTOU. Without this, calling tcsetpgrp() from a background
- * process group (in which we will be, once as child and once as parent)
- * generates the mentioned signal and stops the concerned process. */
- signal(SIGTTOU, SIG_IGN);
+ /*
+ * set up the signal handlers
+ */
+ {
+ /* Ignore SIGTTOU. Without this, calling tcsetpgrp() from a background
+ * process group (in which we will be, once as child and once as parent)
+ * generates the mentioned signal and stops the concerned process. */
+ act.sa_handler = SIG_IGN;
+ if (sigaction(SIGTTOU, &act, 0)) {
+ perror("sigaction SIGTTOU");
+ doExit(3);
+ }
+
+ /* Handle SIGCHLD to keep track of what the child does without blocking */
+ act.sa_handler = sigchldHandler;
+ if (sigaction(SIGCHLD, &act, 0)) {
+ perror("sigaction SIGCHLD");
+ doExit(3);
+ }
+ }
/* Create execution result notification pipe. */
if (pipe(chldPipe)) {
@@ -175,6 +273,10 @@ int main(int argc, char *argv[])
case 0:
close(qtcFd);
+ /* Remove the SIGCHLD handler from the child */
+ act.sa_handler = SIG_DFL;
+ sigaction(SIGCHLD, &act, 0);
+
/* Put the process into an own process group and make it the foregroud
* group on this terminal, so it will receive ctrl-c events, etc.
* This is the main reason for *all* this stub magic in the first place. */
@@ -200,57 +302,51 @@ int main(int argc, char *argv[])
_exit(0);
default:
for (;;) {
- if (wait(&chldStatus) < 0) {
- perror("Cannot obtain exit status of child process");
- doExit(3);
- }
- if (WIFSTOPPED(chldStatus)) {
- /* The child stopped. This can be only the result of ptrace(TRACE_ME). */
- /* We won't need the notification pipe any more, as we know that
- * the exec() succeeded. */
- close(chldPipe[0]);
- close(chldPipe[1]);
- chldPipe[0] = -1;
- /* If we are not debugging, just skip the "handover enabler".
- * This is suboptimal, as it makes us ignore setuid/-gid bits. */
- if (!strcmp(argv[ArgAction], "debug")) {
- /* Stop the child after we detach from it, so we can hand it over to gdb.
- * If the signal delivery is not queued, things will go awry. It works on
- * Linux and MacOSX ... */
- kill(chldPid, SIGSTOP);
+ char buffer[100];
+ int nbytes;
+
+ nbytes = read(qtcFd, buffer, 100);
+ if (nbytes <= 0) {
+ if (nbytes < 0 && errno == EINTR)
+ continue;
+ if (!isDetached) {
+ isDetached = 2;
+ if (nbytes == 0)
+ fprintf(stderr, "Lost connection to QtCreator, detaching from it.\n");
+ else
+ perror("Lost connection to QtCreator, detaching from it");
}
-#ifdef __linux__
- ptrace(PTRACE_DETACH, chldPid, 0, 0);
-#else
- ptrace(PT_DETACH, chldPid, 0, 0);
-#endif
- sendMsg("pid %d\n", chldPid);
- } else if (WIFEXITED(chldStatus)) {
- /* The child exited normally. */
- if (chldPipe[0] >= 0) {
- /* The child exited before being stopped by ptrace(). That can only
- * mean that the exec() failed. */
- switch (read(chldPipe[0], &errNo, sizeof(errNo))) {
- default:
- /* Read of unknown length. Should never happen ... */
- errno = EPROTO;
- case -1:
- /* Read failed. Should never happen, either ... */
- perror("Cannot read status from child process");
- doExit(3);
- case sizeof(errNo):
- /* Child telling us the errno from exec(). */
- sendMsg("err:exec %d\n", errNo);
- return 3;
+ break;
+ } else {
+ int i;
+ for (i = 0; i < nbytes; ++i) {
+ switch (buffer[i]) {
+ case 'k':
+ if (chldPid > 0) {
+ kill(chldPid, SIGTERM);
+ sleep(1);
+ kill(chldPid, SIGKILL);
+ }
+ break;
+ case 'd':
+ isDetached = 1;
+ break;
+ case 's':
+ exit(0);
+ default:
+ if (!hadInvalidCommand) {
+ fprintf(stderr, "Ignoring invalid commands from QtCreator.\n");
+ hadInvalidCommand = 1;
+ }
}
}
- sendMsg("exit %d\n", WEXITSTATUS(chldStatus));
- doExit(0);
- } else {
- sendMsg("crash %d\n", WTERMSIG(chldStatus));
- doExit(0);
}
}
- break;
+ if (isDetached) {
+ for (;;)
+ pause(); /* will exit in the signal handler... */
+ }
}
+ assert(0);
+ return 0;
}
diff --git a/src/libs/utils/qtcprocess.cpp b/src/libs/utils/qtcprocess.cpp
index b3949fb16d..0d2c7e01a3 100644
--- a/src/libs/utils/qtcprocess.cpp
+++ b/src/libs/utils/qtcprocess.cpp
@@ -278,7 +278,7 @@ QStringList QtcProcess::splitArgs(const QString &_args, bool abortOnMeta, SplitE
inline static bool isQuoteMeta(QChar cUnicode)
{
- char c = cUnicode.toAscii();
+ char c = cUnicode.toLatin1();
return c == '\\' || c == '\'' || c == '"' || c == '$';
}
diff --git a/src/libs/utils/reloadpromptutils.cpp b/src/libs/utils/reloadpromptutils.cpp
index 3c40c937a1..70723112d3 100644
--- a/src/libs/utils/reloadpromptutils.cpp
+++ b/src/libs/utils/reloadpromptutils.cpp
@@ -97,12 +97,11 @@ QTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer
box.setDefaultButton(saveas);
box.exec();
QAbstractButton *clickedbutton = box.clickedButton();
- if (clickedbutton == close) {
+ if (clickedbutton == close)
return FileDeletedClose;
- } else if (clickedbutton == saveas) {
+ else if (clickedbutton == saveas)
return FileDeletedSaveAs;
- } else if (clickedbutton == save) {
+ else if (clickedbutton == save)
return FileDeletedSave;
- }
return FileDeletedClose;
}
diff --git a/src/libs/utils/savefile.cpp b/src/libs/utils/savefile.cpp
index f5dbf618ce..d056a93e9f 100644
--- a/src/libs/utils/savefile.cpp
+++ b/src/libs/utils/savefile.cpp
@@ -34,10 +34,13 @@
# include <windows.h>
#else
# include <unistd.h>
+# include <sys/stat.h>
#endif
namespace Utils {
+QFile::Permissions SaveFile::m_umask = 0;
+
SaveFile::SaveFile(const QString &filename) :
m_finalFileName(filename), m_finalized(true), m_backup(false)
{
@@ -65,8 +68,19 @@ bool SaveFile::open(OpenMode flags)
return false;
m_finalized = false; // needs clean up in the end
- if (ofi.exists())
+ if (ofi.exists()) {
setPermissions(ofi.permissions()); // Ignore errors
+ } else {
+ Permissions permAll = QFile::ReadOwner
+ | QFile::ReadGroup
+ | QFile::ReadOther
+ | QFile::WriteOwner
+ | QFile::WriteGroup
+ | QFile::WriteOther;
+
+ // set permissions with respect to the current umask
+ setPermissions(permAll & ~m_umask);
+ }
return true;
}
@@ -99,7 +113,8 @@ bool SaveFile::commit()
return false;
}
- QString finalFileName = Utils::FileUtils::resolveSymlinks(m_finalFileName);
+ QString finalFileName
+ = FileUtils::resolveSymlinks(FileName::fromString(m_finalFileName)).toString();
QString bakname = finalFileName + QLatin1Char('~');
QFile::remove(bakname); // Kill old backup
QFile::rename(finalFileName, bakname); // Backup current file
@@ -113,4 +128,27 @@ bool SaveFile::commit()
return true;
}
+void SaveFile::initializeUmask()
+{
+#ifdef Q_OS_WIN
+ m_umask = QFile::WriteGroup | QFile::WriteOther;
+#else
+ // Get the current process' file creation mask (umask)
+ // umask() is not thread safe so this has to be done by single threaded
+ // application initialization
+ mode_t mask = umask(0); // get current umask
+ umask(mask); // set it back
+
+ m_umask = ((mask & S_IRUSR) ? QFile::ReadOwner : QFlags<QFile::Permission>(0))
+ | ((mask & S_IWUSR) ? QFile::WriteOwner : QFlags<QFile::Permission>(0))
+ | ((mask & S_IXUSR) ? QFile::ExeOwner : QFlags<QFile::Permission>(0))
+ | ((mask & S_IRGRP) ? QFile::ReadGroup : QFlags<QFile::Permission>(0))
+ | ((mask & S_IWGRP) ? QFile::WriteGroup : QFlags<QFile::Permission>(0))
+ | ((mask & S_IXGRP) ? QFile::ExeGroup : QFlags<QFile::Permission>(0))
+ | ((mask & S_IROTH) ? QFile::ReadOther : QFlags<QFile::Permission>(0))
+ | ((mask & S_IWOTH) ? QFile::WriteOther : QFlags<QFile::Permission>(0))
+ | ((mask & S_IXOTH) ? QFile::ExeOther : QFlags<QFile::Permission>(0));
+#endif
+}
+
} // namespace Utils
diff --git a/src/libs/utils/savefile.h b/src/libs/utils/savefile.h
index d2572f2eb8..718ee7f3ae 100644
--- a/src/libs/utils/savefile.h
+++ b/src/libs/utils/savefile.h
@@ -49,10 +49,13 @@ public:
void setBackup(bool backup) { m_backup = backup; }
+ static void initializeUmask();
+
private:
const QString m_finalFileName;
bool m_finalized;
bool m_backup;
+ static QFile::Permissions m_umask;
};
} // namespace Utils
diff --git a/src/libs/utils/stringutils.cpp b/src/libs/utils/stringutils.cpp
index 6b98d9b3d8..a9d6a3d112 100644
--- a/src/libs/utils/stringutils.cpp
+++ b/src/libs/utils/stringutils.cpp
@@ -29,6 +29,8 @@
#include "stringutils.h"
+#include "hostosinfo.h"
+
#include <QString>
#include <QStringList>
#include <QFileInfo>
@@ -94,19 +96,17 @@ QTCREATOR_UTILS_EXPORT QString commonPath(const QStringList &files)
lastSeparatorPos = common.lastIndexOf(QLatin1Char('\\'));
if (lastSeparatorPos == -1)
return QString();
-#ifdef Q_OS_UNIX
- if (lastSeparatorPos == 0) // Unix: "/a", "/b" -> '/'
+ if (HostOsInfo::isAnyUnixHost() && lastSeparatorPos == 0) // Unix: "/a", "/b" -> '/'
lastSeparatorPos = 1;
-#endif
common.truncate(lastSeparatorPos);
return common;
}
QTCREATOR_UTILS_EXPORT QString withTildeHomePath(const QString &path)
{
-#ifdef Q_OS_WIN
- QString outPath = path;
-#else
+ if (HostOsInfo::isWindowsHost())
+ return path;
+
static const QString homePath = QDir::homePath();
QFileInfo fi(QDir::cleanPath(path));
@@ -115,7 +115,6 @@ QTCREATOR_UTILS_EXPORT QString withTildeHomePath(const QString &path)
outPath = QLatin1Char('~') + outPath.mid(homePath.size());
else
outPath = path;
-#endif
return outPath;
}
diff --git a/src/libs/utils/stylehelper.cpp b/src/libs/utils/stylehelper.cpp
index 7b88fee818..edc5f089bf 100644
--- a/src/libs/utils/stylehelper.cpp
+++ b/src/libs/utils/stylehelper.cpp
@@ -29,6 +29,8 @@
#include "stylehelper.h"
+#include "hostosinfo.h"
+
#include <QPixmapCache>
#include <QWidget>
#include <QRect>
@@ -68,11 +70,7 @@ QColor StyleHelper::mergedColors(const QColor &colorA, const QColor &colorB, int
qreal StyleHelper::sidebarFontSize()
{
-#if defined(Q_OS_MAC)
- return 10;
-#else
- return 7.5;
-#endif
+ return HostOsInfo::isMacHost() ? 10 : 7.5;
}
QPalette StyleHelper::sidebarFontPalette(const QPalette &original)
diff --git a/src/libs/utils/synchronousprocess.cpp b/src/libs/utils/synchronousprocess.cpp
index 51642bd95f..8622f48e33 100644
--- a/src/libs/utils/synchronousprocess.cpp
+++ b/src/libs/utils/synchronousprocess.cpp
@@ -28,7 +28,8 @@
****************************************************************************/
#include "synchronousprocess.h"
-#include <qtcassert.h>
+#include "qtcassert.h"
+#include "hostosinfo.h"
#include <QDebug>
#include <QTimer>
@@ -207,6 +208,7 @@ struct SynchronousProcessPrivate {
int m_maxHangTimerCount;
bool m_startFailure;
bool m_timeOutMessageBoxEnabled;
+ bool m_waitingForUser;
QString m_binary;
ChannelBuffer m_stdOut;
@@ -218,7 +220,8 @@ SynchronousProcessPrivate::SynchronousProcessPrivate() :
m_hangTimerCount(0),
m_maxHangTimerCount(defaultMaxHangTimerCount),
m_startFailure(false),
- m_timeOutMessageBoxEnabled(false)
+ m_timeOutMessageBoxEnabled(false),
+ m_waitingForUser(false)
{
}
@@ -255,11 +258,10 @@ SynchronousProcess::~SynchronousProcess()
void SynchronousProcess::setTimeout(int timeoutMS)
{
- if (timeoutMS >= 0) {
+ if (timeoutMS >= 0)
d->m_maxHangTimerCount = qMax(2, timeoutMS / 1000);
- } else {
+ else
d->m_maxHangTimerCount = INT_MAX;
- }
}
int SynchronousProcess::timeout() const
@@ -412,10 +414,12 @@ static inline bool askToKill(const QString &binary = QString())
void SynchronousProcess::slotTimeout()
{
- if (++d->m_hangTimerCount > d->m_maxHangTimerCount) {
+ if (!d->m_waitingForUser && (++d->m_hangTimerCount > d->m_maxHangTimerCount)) {
if (debug)
qDebug() << Q_FUNC_INFO << "HANG detected, killing";
+ d->m_waitingForUser = true;
const bool terminate = !d->m_timeOutMessageBoxEnabled || askToKill(d->m_binary);
+ d->m_waitingForUser = false;
if (terminate) {
SynchronousProcess::stopProcess(d->m_process);
d->m_result.result = SynchronousProcessResponse::Hang;
@@ -598,18 +602,6 @@ bool SynchronousProcess::stopProcess(QProcess &p)
// Path utilities
-enum OS_Type { OS_Mac, OS_Windows, OS_Unix };
-
-#ifdef Q_OS_WIN
-static const OS_Type pathOS = OS_Windows;
-#else
-# ifdef Q_OS_MAC
-static const OS_Type pathOS = OS_Mac;
-# else
-static const OS_Type pathOS = OS_Unix;
-# endif
-#endif
-
// Locate a binary in a directory, applying all kinds of
// extensions the operating system supports.
static QString checkBinary(const QDir &dir, const QString &binary)
@@ -621,16 +613,18 @@ static QString checkBinary(const QDir &dir, const QString &binary)
// Does the OS have some weird extension concept or does the
// binary have a 3 letter extension?
- if (pathOS == OS_Unix)
+ if (HostOsInfo::isAnyUnixHost() && !HostOsInfo::isMacHost())
return QString();
const int dotIndex = binary.lastIndexOf(QLatin1Char('.'));
if (dotIndex != -1 && dotIndex == binary.size() - 4)
return QString();
- switch (pathOS) {
- case OS_Unix:
+ switch (HostOsInfo::hostOs()) {
+ case HostOsInfo::HostOsLinux:
+ case HostOsInfo::HostOsOtherUnix:
+ case HostOsInfo::HostOsOther:
break;
- case OS_Windows: {
+ case HostOsInfo::HostOsWindows: {
static const char *windowsExtensions[] = {".cmd", ".bat", ".exe", ".com" };
// Check the Windows extensions using the order
const int windowsExtensionCount = sizeof(windowsExtensions)/sizeof(const char*);
@@ -641,7 +635,7 @@ static QString checkBinary(const QDir &dir, const QString &binary)
}
}
break;
- case OS_Mac: {
+ case HostOsInfo::HostOsMac: {
// Check for Mac app folders
const QFileInfo appFolder(dir.filePath(binary + QLatin1String(".app")));
if (appFolder.isDir()) {
@@ -666,13 +660,13 @@ QString SynchronousProcess::locateBinary(const QString &path, const QString &bin
return checkBinary(absInfo.dir(), absInfo.fileName());
// Windows finds binaries in the current directory
- if (pathOS == OS_Windows) {
+ if (HostOsInfo::isWindowsHost()) {
const QString currentDirBinary = checkBinary(QDir::current(), binary);
if (!currentDirBinary.isEmpty())
return currentDirBinary;
}
- const QStringList paths = path.split(pathSeparator());
+ const QStringList paths = path.split(HostOsInfo::pathListSeparator());
if (paths.empty())
return QString();
const QStringList::const_iterator cend = paths.constEnd();
@@ -691,11 +685,4 @@ QString SynchronousProcess::locateBinary(const QString &binary)
return locateBinary(QString::fromLocal8Bit(path), binary);
}
-QChar SynchronousProcess::pathSeparator()
-{
- if (pathOS == OS_Windows)
- return QLatin1Char(';');
- return QLatin1Char(':');
-}
-
} // namespace Utils
diff --git a/src/libs/utils/synchronousprocess.h b/src/libs/utils/synchronousprocess.h
index f582b51150..4563588e3c 100644
--- a/src/libs/utils/synchronousprocess.h
+++ b/src/libs/utils/synchronousprocess.h
@@ -139,7 +139,6 @@ public:
// and file types.
static QString locateBinary(const QString &binary);
static QString locateBinary(const QString &path, const QString &binary);
- static QChar pathSeparator();
signals:
void stdOut(const QByteArray &data, bool firstTime);
diff --git a/src/libs/utils/tcpportsgatherer.cpp b/src/libs/utils/tcpportsgatherer.cpp
index 35c925e529..9c414fcacf 100644
--- a/src/libs/utils/tcpportsgatherer.cpp
+++ b/src/libs/utils/tcpportsgatherer.cpp
@@ -169,7 +169,7 @@ void TcpPortsGathererPrivate::updateLinux(TcpPortsGatherer::ProtocolFlags protoc
));
while (!file.atEnd()) {
QByteArray line = file.readLine();
- if (pattern.indexIn(line) != -1) {
+ if (pattern.indexIn(QLatin1String(line)) != -1) {
bool isNumber;
quint16 port = pattern.cap(1).toUShort(&isNumber, 16);
QTC_ASSERT(isNumber, continue);
@@ -213,12 +213,12 @@ void TcpPortsGathererPrivate::updateNetstat(TcpPortsGatherer::ProtocolFlags prot
"\\s+\\d+" // whitespace, number (Recv-Q)
"\\s+\\d+" // whitespace, number (Send-Q)
"\\s+(\\S+)")); // whitespace, Local Address
- if (pattern.indexIn(line) != -1) {
+ if (pattern.indexIn(QLatin1String(line)) != -1) {
QString localAddress = pattern.cap(1);
// Examples of local addresses:
// '*.56501' , '*.*' 'fe80::1%lo0.123'
- int portDelimiterPos = localAddress.lastIndexOf(".");
+ int portDelimiterPos = localAddress.lastIndexOf(QLatin1Char('.'));
if (portDelimiterPos == -1)
continue;
diff --git a/src/libs/utils/textfileformat.cpp b/src/libs/utils/textfileformat.cpp
index bd6a992616..28a579f824 100644
--- a/src/libs/utils/textfileformat.cpp
+++ b/src/libs/utils/textfileformat.cpp
@@ -103,13 +103,12 @@ TextFileFormat TextFileFormat::detect(const QByteArray &data)
}
// end code taken from qtextstream
const int newLinePos = data.indexOf('\n');
- if (newLinePos == -1) {
+ if (newLinePos == -1)
result.lineTerminationMode = NativeLineTerminator;
- } else if (newLinePos == 0) {
+ else if (newLinePos == 0)
result.lineTerminationMode = LFLineTerminator;
- } else {
+ else
result.lineTerminationMode = data.at(newLinePos - 1) == '\r' ? CRLFLineTerminator : LFLineTerminator;
- }
return result;
}
@@ -286,11 +285,10 @@ bool TextFileFormat::writeFile(const QString &fileName, QString plainText, QStri
// let QFile do the work, else manually add.
QIODevice::OpenMode fileMode = QIODevice::NotOpen;
if (lineTerminationMode == CRLFLineTerminator) {
- if (NativeLineTerminator == CRLFLineTerminator) {
+ if (NativeLineTerminator == CRLFLineTerminator)
fileMode |= QIODevice::Text;
- } else {
+ else
plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
- }
}
Utils::FileSaver saver(fileName, fileMode);
diff --git a/src/plugins/texteditor/tooltip/effects.h b/src/libs/utils/tooltip/effects.h
index f516675ddb..f516675ddb 100644
--- a/src/plugins/texteditor/tooltip/effects.h
+++ b/src/libs/utils/tooltip/effects.h
diff --git a/src/plugins/texteditor/tooltip/reuse.h b/src/libs/utils/tooltip/reuse.h
index f682420714..6ebd38901a 100644
--- a/src/plugins/texteditor/tooltip/reuse.h
+++ b/src/libs/utils/tooltip/reuse.h
@@ -36,7 +36,7 @@
#include <QApplication>
#include <QDesktopWidget>
-namespace TextEditor {
+namespace Utils {
namespace Internal {
inline int screenNumber(const QPoint &pos, QWidget *w)
@@ -57,6 +57,6 @@ inline QRect screenGeometry(const QPoint &pos, QWidget *w)
}
} // namespace Internal
-} // namespace TextEditor
+} // namespace Utils
#endif // TOOLTIPREUSE_H
diff --git a/src/plugins/texteditor/tooltip/tipcontents.cpp b/src/libs/utils/tooltip/tipcontents.cpp
index 70af3da3fa..147a25f610 100644
--- a/src/plugins/texteditor/tooltip/tipcontents.cpp
+++ b/src/libs/utils/tooltip/tipcontents.cpp
@@ -35,7 +35,7 @@
#include <QtGlobal>
-namespace TextEditor {
+namespace Utils {
TipContent::TipContent()
{}
@@ -192,4 +192,4 @@ bool WidgetContent::pinToolTip(QWidget *w)
return false;
}
-} // namespace TextEditor
+} // namespace Utils
diff --git a/src/plugins/texteditor/tooltip/tipcontents.h b/src/libs/utils/tooltip/tipcontents.h
index 302edbd636..4632f65963 100644
--- a/src/plugins/texteditor/tooltip/tipcontents.h
+++ b/src/libs/utils/tooltip/tipcontents.h
@@ -30,14 +30,14 @@
#ifndef TIPCONTENTS_H
#define TIPCONTENTS_H
-#include "texteditor/texteditor_global.h"
+#include "../utils_global.h"
#include <QString>
#include <QColor>
-namespace TextEditor {
+namespace Utils {
-class TEXTEDITOR_EXPORT TipContent
+class QTCREATOR_UTILS_EXPORT TipContent
{
protected:
TipContent();
@@ -53,7 +53,7 @@ public:
virtual bool equals(const TipContent &tipContent) const = 0;
};
-class TEXTEDITOR_EXPORT ColorContent : public TipContent
+class QTCREATOR_UTILS_EXPORT ColorContent : public TipContent
{
public:
ColorContent(const QColor &color);
@@ -74,7 +74,7 @@ private:
QColor m_color;
};
-class TEXTEDITOR_EXPORT TextContent : public TipContent
+class QTCREATOR_UTILS_EXPORT TextContent : public TipContent
{
public:
TextContent(const QString &text);
@@ -96,7 +96,7 @@ private:
};
// A content for displaying any widget (with a layout).
-class TEXTEDITOR_EXPORT WidgetContent : public TipContent
+class QTCREATOR_UTILS_EXPORT WidgetContent : public TipContent
{
public:
explicit WidgetContent(QWidget *w, bool interactive = false);
@@ -123,6 +123,6 @@ private:
bool m_interactive;
};
-} // namespace TextEditor
+} // namespace Utils
#endif // TIPCONTENTS_H
diff --git a/src/plugins/texteditor/tooltip/tips.cpp b/src/libs/utils/tooltip/tips.cpp
index cb16db0c1f..6d3928ac5e 100644
--- a/src/plugins/texteditor/tooltip/tips.cpp
+++ b/src/libs/utils/tooltip/tips.cpp
@@ -47,7 +47,7 @@
#include <QPaintEvent>
#include <QVBoxLayout>
-namespace TextEditor {
+namespace Utils {
namespace Internal {
namespace {
@@ -72,7 +72,7 @@ QTipLabel::QTipLabel(QWidget *parent) :
QTipLabel::~QTipLabel()
{
- TextEditor::TipContent *tmpTipContent = m_tipContent;
+ Utils::TipContent *tmpTipContent = m_tipContent;
m_tipContent = 0;
delete tmpTipContent;
}
@@ -84,7 +84,7 @@ bool QTipLabel::isInteractive() const
void QTipLabel::setContent(const TipContent &content)
{
- TextEditor::TipContent *tmpTipContent = m_tipContent;
+ Utils::TipContent *tmpTipContent = m_tipContent;
m_tipContent = content.clone();
delete tmpTipContent;
}
@@ -268,4 +268,4 @@ bool WidgetTip::canHandleContentReplacement(const TipContent & ) const
#include "moc_tips.cpp"
} // namespace Internal
-} // namespace TextEditor
+} // namespace Utils
diff --git a/src/plugins/texteditor/tooltip/tips.h b/src/libs/utils/tooltip/tips.h
index 0c832c90e4..56e16120f4 100644
--- a/src/plugins/texteditor/tooltip/tips.h
+++ b/src/libs/utils/tooltip/tips.h
@@ -36,12 +36,12 @@
QT_FORWARD_DECLARE_CLASS(QVBoxLayout)
-namespace TextEditor {
+namespace Utils {
class TipContent;
}
#ifndef Q_MOC_RUN
-namespace TextEditor {
+namespace Utils {
namespace Internal {
#endif
@@ -55,16 +55,16 @@ protected:
public:
virtual ~QTipLabel();
- void setContent(const TextEditor::TipContent &content);
- const TextEditor::TipContent &content() const;
+ void setContent(const Utils::TipContent &content);
+ const Utils::TipContent &content() const;
virtual void configure(const QPoint &pos, QWidget *w) = 0;
- virtual bool canHandleContentReplacement(const TextEditor::TipContent &content) const = 0;
+ virtual bool canHandleContentReplacement(const Utils::TipContent &content) const = 0;
bool isInteractive() const;
private:
- TextEditor::TipContent *m_tipContent;
+ Utils::TipContent *m_tipContent;
};
class ColorTip : public QTipLabel
@@ -118,7 +118,7 @@ private:
#ifndef Q_MOC_RUN
} // namespace Internal
-} // namespace TextEditor
+} // namespace Utils
#endif
#endif // TIPS_H
diff --git a/src/plugins/texteditor/tooltip/tooltip.cpp b/src/libs/utils/tooltip/tooltip.cpp
index 14efcd032e..ab2ade2293 100644
--- a/src/plugins/texteditor/tooltip/tooltip.cpp
+++ b/src/libs/utils/tooltip/tooltip.cpp
@@ -30,23 +30,25 @@
#include "tooltip.h"
#include "tips.h"
#include "tipcontents.h"
-#include "tipfactory.h"
#include "effects.h"
#include "reuse.h"
+#include <utils/hostosinfo.h>
+
#include <QString>
#include <QColor>
#include <QApplication>
#include <QKeyEvent>
#include <QMouseEvent>
+#include <QWidget>
#include <QMenu>
#include <QDebug>
-using namespace TextEditor;
+using namespace Utils;
using namespace Internal;
-ToolTip::ToolTip() : m_tipFactory(new TipFactory), m_tip(0), m_widget(0)
+ToolTip::ToolTip() : m_tip(0), m_widget(0)
{
connect(&m_showTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
connect(&m_hideDelayTimer, SIGNAL(timeout()), this, SLOT(hideTipImmediately()));
@@ -55,7 +57,6 @@ ToolTip::ToolTip() : m_tipFactory(new TipFactory), m_tip(0), m_widget(0)
ToolTip::~ToolTip()
{
m_tip = 0;
- delete m_tipFactory;
}
ToolTip *ToolTip::instance()
@@ -67,12 +68,23 @@ ToolTip *ToolTip::instance()
void ToolTip::show(const QPoint &pos, const TipContent &content, QWidget *w, const QRect &rect)
{
if (acceptShow(content, pos, w, rect)) {
-#ifndef Q_OS_WIN
- m_tip = m_tipFactory->createTip(content, w);
-#else
- m_tip = m_tipFactory->createTip(
- content, QApplication::desktop()->screen(Internal::screenNumber(pos, w)));
-#endif
+ QWidget *target = 0;
+ if (HostOsInfo::isWindowsHost())
+ target = QApplication::desktop()->screen(Internal::screenNumber(pos, w));
+ else
+ target = w;
+
+ switch (content.typeId()) {
+ case TextContent::TEXT_CONTENT_ID:
+ m_tip = new TextTip(target);
+ break;
+ case ColorContent::COLOR_CONTENT_ID:
+ m_tip = new ColorTip(target);
+ break;
+ case WidgetContent::WIDGET_CONTENT_ID:
+ m_tip = new WidgetTip(target);
+ break;
+ }
setUp(pos, content, w, rect);
qApp->installEventFilter(this);
showTip();
@@ -204,14 +216,7 @@ void ToolTip::placeTip(const QPoint &pos, QWidget *w)
{
QRect screen = Internal::screenGeometry(pos, w);
QPoint p = pos;
- p += QPoint(2,
-#ifdef Q_OS_WIN
- 21
-#else
- 16
-#endif
- );
-
+ p += QPoint(2, Utils::HostOsInfo::isWindowsHost() ? 21 : 16);
if (p.x() + m_tip->width() > screen.x() + screen.width())
p.rx() -= 4 + m_tip->width();
if (p.y() + m_tip->height() > screen.y() + screen.height())
@@ -247,9 +252,8 @@ bool ToolTip::eventFilter(QObject *o, QEvent *event)
}
#endif
case QEvent::Leave:
- if (o == m_tip) {
+ if (o == m_tip)
hideTipWithDelay();
- }
break;
case QEvent::Enter:
// User moved cursor into tip and wants to interact.
@@ -271,9 +275,8 @@ bool ToolTip::eventFilter(QObject *o, QEvent *event)
case QEvent::Wheel:
if (m_tip) {
if (m_tip->isInteractive()) { // Do not close on interaction with the tooltip
- if (o != m_tip && !m_tip->isAncestorOf(static_cast<QWidget *>(o))) {
+ if (o != m_tip && !m_tip->isAncestorOf(static_cast<QWidget *>(o)))
hideTipImmediately();
- }
} else {
hideTipImmediately();
}
diff --git a/src/plugins/texteditor/tooltip/tooltip.h b/src/libs/utils/tooltip/tooltip.h
index bf763214fa..c8ca4f51a4 100644
--- a/src/plugins/texteditor/tooltip/tooltip.h
+++ b/src/libs/utils/tooltip/tooltip.h
@@ -30,7 +30,7 @@
#ifndef TOOLTIP_H
#define TOOLTIP_H
-#include "texteditor/texteditor_global.h"
+#include "../utils_global.h"
#include <QSharedPointer>
#include <QObject>
@@ -52,16 +52,12 @@ class QPoint;
class QWidget;
QT_END_NAMESPACE
-namespace TextEditor {
-
-namespace Internal {
-class TipFactory;
-class QTipLabel;
-}
+namespace Utils {
+namespace Internal { class QTipLabel; }
class TipContent;
-class TEXTEDITOR_EXPORT ToolTip : public QObject
+class QTCREATOR_UTILS_EXPORT ToolTip : public QObject
{
Q_OBJECT
private:
@@ -95,7 +91,6 @@ private:
void showTip();
void hideTipWithDelay();
- Internal::TipFactory *m_tipFactory;
Internal::QTipLabel *m_tip;
QWidget *m_widget;
QRect m_rect;
@@ -103,6 +98,6 @@ private:
QTimer m_hideDelayTimer;
};
-} // namespace TextEditor
+} // namespace Utils
#endif // TOOLTIP_H
diff --git a/src/libs/utils/uncommentselection.cpp b/src/libs/utils/uncommentselection.cpp
index 2b954f9134..0d7b4974b4 100644
--- a/src/libs/utils/uncommentselection.cpp
+++ b/src/libs/utils/uncommentselection.cpp
@@ -258,7 +258,7 @@ void Utils::unCommentSelection(QPlainTextEdit *edit, const CommentDefinition &de
}
} else {
QString text = block.text();
- foreach(QChar c, text) {
+ foreach (QChar c, text) {
if (!c.isSpace()) {
if (definition.isAfterWhiteSpaces())
cursor.setPosition(block.position() + text.indexOf(c));
diff --git a/src/libs/utils/utils-lib.pri b/src/libs/utils/utils-lib.pri
index a8a6dfe1b7..12feb98984 100644
--- a/src/libs/utils/utils-lib.pri
+++ b/src/libs/utils/utils-lib.pri
@@ -38,12 +38,10 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/fancylineedit.cpp \
$$PWD/qtcolorbutton.cpp \
$$PWD/savedaction.cpp \
- $$PWD/submiteditorwidget.cpp \
$$PWD/synchronousprocess.cpp \
$$PWD/savefile.cpp \
$$PWD/fileutils.cpp \
$$PWD/textfileformat.cpp \
- $$PWD/submitfieldwidget.cpp \
$$PWD/consoleprocess.cpp \
$$PWD/uncommentselection.cpp \
$$PWD/parameteraction.cpp \
@@ -79,7 +77,14 @@ SOURCES += $$PWD/environment.cpp \
$$PWD/basetreeview.cpp \
$$PWD/qtcassert.cpp \
$$PWD/elfreader.cpp \
- $$PWD/bracematcher.cpp
+ $$PWD/bracematcher.cpp \
+ $$PWD/proxyaction.cpp \
+ $$PWD/elidinglabel.cpp \
+ $$PWD/hostosinfo.cpp \
+ $$PWD/tooltip/tooltip.cpp \
+ $$PWD/tooltip/tips.cpp \
+ $$PWD/tooltip/tipcontents.cpp \
+ $$PWD/unixutils.cpp
win32 {
SOURCES += \
@@ -89,10 +94,6 @@ win32 {
}
else:SOURCES += $$PWD/consoleprocess_unix.cpp
-unix:!macx {
- HEADERS += $$PWD/unixutils.h
- SOURCES += $$PWD/unixutils.cpp
-}
HEADERS += \
$$PWD/environment.h \
$$PWD/environmentmodel.h \
@@ -120,14 +121,12 @@ HEADERS += \
$$PWD/fancylineedit.h \
$$PWD/qtcolorbutton.h \
$$PWD/savedaction.h \
- $$PWD/submiteditorwidget.h \
$$PWD/consoleprocess.h \
$$PWD/consoleprocess_p.h \
$$PWD/synchronousprocess.h \
$$PWD/savefile.h \
$$PWD/fileutils.h \
$$PWD/textfileformat.h \
- $$PWD/submitfieldwidget.h \
$$PWD/uncommentselection.h \
$$PWD/parameteraction.h \
$$PWD/treewidgetcolumnstretcher.h \
@@ -165,11 +164,19 @@ HEADERS += \
$$PWD/appmainwindow.h \
$$PWD/basetreeview.h \
$$PWD/elfreader.h \
- $$PWD/bracematcher.h
+ $$PWD/bracematcher.h \
+ $$PWD/proxyaction.h \
+ $$PWD/hostosinfo.h \
+ $$PWD/elidinglabel.h \
+ $$PWD/tooltip/tooltip.h \
+ $$PWD/tooltip/tips.h \
+ $$PWD/tooltip/tipcontents.h \
+ $$PWD/tooltip/reuse.h \
+ $$PWD/tooltip/effects.h \
+ $$PWD/unixutils.h
FORMS += $$PWD/filewizardpage.ui \
$$PWD/projectintropage.ui \
- $$PWD/newclasswidget.ui \
- $$PWD/submiteditorwidget.ui
+ $$PWD/newclasswidget.ui
RESOURCES += $$PWD/utils.qrc
diff --git a/src/libs/utils/utils.pro b/src/libs/utils/utils.pro
index 873eb0c437..9f5d56d644 100644
--- a/src/libs/utils/utils.pro
+++ b/src/libs/utils/utils.pro
@@ -12,12 +12,6 @@ lessThan(QT_MAJOR_VERSION, 5) {
win32:include(../../private_headers.pri)
}
-HEADERS += \
- proxyaction.h
-
-SOURCES += \
- proxyaction.cpp
-
win32: LIBS += -luser32
# PortsGatherer
win32: LIBS += -liphlpapi -lws2_32
diff --git a/src/libs/utils/utils.qbs b/src/libs/utils/utils.qbs
index 292ae6bb68..9a1a6d897b 100644
--- a/src/libs/utils/utils.qbs
+++ b/src/libs/utils/utils.qbs
@@ -4,13 +4,7 @@ import "../QtcLibrary.qbs" as QtcLibrary
QtcLibrary {
name: "Utils"
- cpp.defines: base.concat(["QTCREATOR_UTILS_LIB"])
- cpp.includePaths: [
- ".",
- "..",
- "../..",
- buildDirectory
- ]
+ cpp.defines: base.concat("QTCREATOR_UTILS_LIB")
Properties {
condition: qbs.targetOS == "windows"
@@ -30,21 +24,22 @@ QtcLibrary {
Depends { name: "app_version_header" }
files: [
- "filewizardpage.ui",
- "newclasswidget.ui",
- "projectintropage.ui",
- "utils.qrc",
"annotateditemdelegate.cpp",
"annotateditemdelegate.h",
+ "appmainwindow.cpp",
+ "appmainwindow.h",
"basetreeview.cpp",
"basetreeview.h",
"basevalidatinglineedit.cpp",
"basevalidatinglineedit.h",
"bracematcher.cpp",
"bracematcher.h",
+ "buildablehelperlibrary.cpp",
"buildablehelperlibrary.h",
"changeset.cpp",
"changeset.h",
+ "checkablemessagebox.cpp",
+ "checkablemessagebox.h",
"classnamevalidatinglineedit.cpp",
"classnamevalidatinglineedit.h",
"codegeneration.cpp",
@@ -54,6 +49,7 @@ QtcLibrary {
"consoleprocess.cpp",
"consoleprocess.h",
"consoleprocess_p.h",
+ "crumblepath.cpp",
"crumblepath.h",
"detailsbutton.cpp",
"detailsbutton.h",
@@ -61,6 +57,9 @@ QtcLibrary {
"detailswidget.h",
"elfreader.cpp",
"elfreader.h",
+ "elidinglabel.cpp",
+ "elidinglabel.h",
+ "environment.cpp",
"environment.h",
"environmentmodel.cpp",
"environmentmodel.h",
@@ -70,27 +69,32 @@ QtcLibrary {
"fancylineedit.h",
"fancymainwindow.cpp",
"fancymainwindow.h",
- "appmainwindow.h",
- "appmainwindow.cpp",
"fileinprojectfinder.cpp",
"fileinprojectfinder.h",
+ "filenamevalidatinglineedit.cpp",
"filenamevalidatinglineedit.h",
"filesearch.cpp",
"filesearch.h",
"filesystemwatcher.cpp",
"filesystemwatcher.h",
+ "fileutils.cpp",
"fileutils.h",
"filewizarddialog.cpp",
"filewizarddialog.h",
"filewizardpage.cpp",
"filewizardpage.h",
+ "filewizardpage.ui",
"filterlineedit.cpp",
"filterlineedit.h",
"flowlayout.cpp",
"flowlayout.h",
+ "historycompleter.cpp",
"historycompleter.h",
+ "hostosinfo.h",
+ "hostosinfo.cpp",
"htmldocextractor.cpp",
"htmldocextractor.h",
+ "ipaddresslineedit.cpp",
"ipaddresslineedit.h",
"iwelcomepage.cpp",
"iwelcomepage.h",
@@ -99,11 +103,14 @@ QtcLibrary {
"linecolumnlabel.cpp",
"linecolumnlabel.h",
"listutils.h",
+ "multitask.h",
"navigationtreeview.cpp",
"navigationtreeview.h",
+ "networkaccessmanager.cpp",
"networkaccessmanager.h",
"newclasswidget.cpp",
"newclasswidget.h",
+ "newclasswidget.ui",
"outputformat.h",
"outputformatter.cpp",
"outputformatter.h",
@@ -111,23 +118,34 @@ QtcLibrary {
"parameteraction.h",
"pathchooser.cpp",
"pathchooser.h",
+ "pathlisteditor.cpp",
"pathlisteditor.h",
+ "persistentsettings.cpp",
+ "persistentsettings.h",
+ "portlist.cpp",
+ "portlist.h",
"projectintropage.cpp",
"projectintropage.h",
+ "projectintropage.ui",
"projectnamevalidatinglineedit.cpp",
"projectnamevalidatinglineedit.h",
+ "proxyaction.cpp",
"proxyaction.h",
- "qtcassert.h",
"qtcassert.cpp",
+ "qtcassert.h",
"qtcolorbutton.cpp",
"qtcolorbutton.h",
+ "qtcprocess.cpp",
"qtcprocess.h",
"reloadpromptutils.cpp",
"reloadpromptutils.h",
+ "runextensions.h",
+ "savedaction.cpp",
"savedaction.h",
"savefile.cpp",
"savefile.h",
"settingsselector.cpp",
+ "settingsselector.h",
"settingsutils.h",
"statuslabel.cpp",
"statuslabel.h",
@@ -135,12 +153,8 @@ QtcLibrary {
"stringutils.h",
"styledbar.cpp",
"styledbar.h",
+ "stylehelper.cpp",
"stylehelper.h",
- "submiteditorwidget.cpp",
- "submiteditorwidget.h",
- "submiteditorwidget.ui",
- "submitfieldwidget.cpp",
- "submitfieldwidget.h",
"synchronousprocess.cpp",
"synchronousprocess.h",
"tcpportsgatherer.cpp",
@@ -151,31 +165,12 @@ QtcLibrary {
"treewidgetcolumnstretcher.h",
"uncommentselection.cpp",
"uncommentselection.h",
+ "unixutils.cpp",
+ "unixutils.h",
+ "utils.qrc",
"utils_global.h",
"wizard.cpp",
"wizard.h",
- "persistentsettings.h",
- "settingsselector.h",
- "buildablehelperlibrary.cpp",
- "checkablemessagebox.cpp",
- "checkablemessagebox.h",
- "crumblepath.cpp",
- "environment.cpp",
- "filenamevalidatinglineedit.cpp",
- "fileutils.cpp",
- "historycompleter.cpp",
- "ipaddresslineedit.cpp",
- "networkaccessmanager.cpp",
- "pathlisteditor.cpp",
- "persistentsettings.cpp",
- "portlist.cpp",
- "portlist.h",
- "proxyaction.cpp",
- "qtcprocess.cpp",
- "savedaction.cpp",
- "stylehelper.cpp",
- "multitask.h",
- "runextensions.h",
"images/arrow.png",
"images/crumblepath-segment-end.png",
"images/crumblepath-segment-hover-end.png",
@@ -183,11 +178,24 @@ QtcLibrary {
"images/crumblepath-segment-selected-end.png",
"images/crumblepath-segment-selected.png",
"images/crumblepath-segment.png",
- "images/removesubmitfield.png",
"images/triangle_vert.png",
]
Group {
+ prefix: "tooltip/"
+ files: [
+ "effects.h",
+ "reuse.h",
+ "tipcontents.cpp",
+ "tipcontents.h",
+ "tips.cpp",
+ "tips.h",
+ "tooltip.cpp",
+ "tooltip.h",
+ ]
+ }
+
+ Group {
condition: qbs.targetOS == "windows"
files: [
"consoleprocess_win.cpp",
@@ -203,18 +211,8 @@ QtcLibrary {
]
}
- Group {
- condition: qbs.targetOS == "linux"
- files: [
- "unixutils.h",
- "unixutils.cpp"
- ]
- }
-
ProductModule {
- Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["concurrent", "widgets" ] }
- cpp.includePaths: [".."]
}
}
diff --git a/src/libs/utils/utils.qrc b/src/libs/utils/utils.qrc
index 52ec41382b..2748bccb6c 100644
--- a/src/libs/utils/utils.qrc
+++ b/src/libs/utils/utils.qrc
@@ -1,6 +1,5 @@
<RCC>
<qresource prefix="/utils">
- <file>images/removesubmitfield.png</file>
<file>images/arrow.png</file>
<file>images/crumblepath-segment.png</file>
<file>images/crumblepath-segment-end.png</file>
diff --git a/src/libs/utils/wizard.cpp b/src/libs/utils/wizard.cpp
index 1ca4a3f8bb..fbef9fcd95 100644
--- a/src/libs/utils/wizard.cpp
+++ b/src/libs/utils/wizard.cpp
@@ -553,9 +553,8 @@ QList<WizardProgressItem *> WizardProgressPrivate::singlePathBetween(WizardProgr
if (itItem.value().count() != 1)
return QList<WizardProgressItem *>();
it = itItem.value().constBegin().key();
- if (it == item) {
+ if (it == item)
return path;
- }
itItem = visitedItemsToParents.constFind(it);
}
return QList<WizardProgressItem *>();
diff --git a/src/libs/zeroconf/avahiLib.cpp b/src/libs/zeroconf/avahiLib.cpp
index a8f653333b..5f79901e47 100644
--- a/src/libs/zeroconf/avahiLib.cpp
+++ b/src/libs/zeroconf/avahiLib.cpp
@@ -467,7 +467,7 @@ extern "C" void cAvahiClientReply (AvahiClient * /*s*/, AvahiClientState state,
break;
case (AVAHI_CLIENT_S_RUNNING):
/* Server state: RUNNING */
- lib->setError(false, QString(""));
+ lib->setError(false, QString());
break;
case (AVAHI_CLIENT_S_COLLISION):
/* Server state: COLLISION */
@@ -506,9 +506,8 @@ extern "C" void cAvahiBrowseReply(
}
ServiceBrowserPrivate *browser = reinterpret_cast<ServiceBrowserPrivate *>(context);
- if (browser == 0) {
+ if (browser == 0)
qDebug() << "Error context is null in cAvahiBrowseReply";
- }
switch (event) {
case AVAHI_BROWSER_FAILURE:
browser->browseReply(kDNSServiceFlagsMoreComing, 0, protocol, kDNSServiceErr_Unknown,
diff --git a/src/libs/zeroconf/embed/dnssd_clientstub.c b/src/libs/zeroconf/embed/dnssd_clientstub.c
index eabf084369..d4f75f95c8 100644
--- a/src/libs/zeroconf/embed/dnssd_clientstub.c
+++ b/src/libs/zeroconf/embed/dnssd_clientstub.c
@@ -757,6 +757,7 @@ static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
struct msghdr msg;
struct cmsghdr *cmsg;
char cbuf[CMSG_SPACE(sizeof(dnssd_sock_t))];
+ dnssd_sock_t *sock;
if (sdr->op == send_bpf) // Okay to use sdr->op when checking for op == send_bpf
{
@@ -784,7 +785,8 @@ static DNSServiceErrorType deliver_request(ipc_msg_hdr *hdr, DNSServiceOp *sdr)
cmsg->cmsg_len = CMSG_LEN(sizeof(dnssd_sock_t));
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
- *((dnssd_sock_t *)CMSG_DATA(cmsg)) = listenfd;
+ sock = (dnssd_sock_t *)CMSG_DATA(cmsg);
+ *sock = listenfd;
#if TEST_KQUEUE_CONTROL_MESSAGE_BUG
sleep(1);
diff --git a/src/libs/zeroconf/embeddedLib.cpp b/src/libs/zeroconf/embeddedLib.cpp
index 541adfda0a..b4ae626d49 100644
--- a/src/libs/zeroconf/embeddedLib.cpp
+++ b/src/libs/zeroconf/embeddedLib.cpp
@@ -71,8 +71,8 @@ public:
{
if (daemonPath.isEmpty())
m_maxErrors = 0;
- if (!daemonPath.isEmpty() && daemonPath.at(0) != '/' && daemonPath.at(0) != '.')
- this->daemonPath = QCoreApplication::applicationDirPath() + QChar('/') + daemonPath;
+ if (!daemonPath.isEmpty() && daemonPath.at(0) != QLatin1Char('/') && daemonPath.at(0) != QLatin1Char('.'))
+ this->daemonPath = QCoreApplication::applicationDirPath() + QLatin1Char('/') + daemonPath;
}
~EmbeddedZConfLib()
@@ -114,7 +114,7 @@ public:
QString daemonCmd = daemonPath;
QStringList daemonArgs;
#ifdef Q_OS_LINUX
- if (QFile::exists("/tmp/mdnsd") && logger)
+ if (QFile::exists(QLatin1String("/tmp/mdnsd")) && logger)
logger->appendError(ErrorMessage::WarningLevel,
ZConfLib::tr("%1 detected a file at /tmp/mdnsd, daemon startup will probably fail.")
.arg(name()));
@@ -128,7 +128,7 @@ public:
logger->appendError(ErrorMessage::NoteLevel,
ZConfLib::tr("%1: log of previous daemon run is: '%2'.\n")
.arg(name())
- .arg(QString::fromAscii(logBA.constData(), logBA.size())));
+ .arg(QString::fromLatin1(logBA.constData(), logBA.size())));
qDebug()<<logBA.size()<<oldLog.error()<<oldLog.errorString();
}
oldLog.close();
diff --git a/src/libs/zeroconf/servicebrowser.cpp b/src/libs/zeroconf/servicebrowser.cpp
index 9a75f1a42a..0dd8accf4f 100644
--- a/src/libs/zeroconf/servicebrowser.cpp
+++ b/src/libs/zeroconf/servicebrowser.cpp
@@ -113,9 +113,8 @@ int fromFullNameC(const char * const fullName, QString &service, QString &regtyp
fullNameDecoded[decodedI++] = c;
}
} else if (c == '.') {
- if (iPos < 4) {
+ if (iPos < 4)
oldPos[iPos++] = decodedI;
- }
fullNameDecoded[decodedI++] = c;
} else {
fullNameDecoded[decodedI++] = c;
@@ -387,11 +386,10 @@ QDebug operator<<(QDebug dbg, const Service &service)
}
QDebug operator<<(QDebug dbg, const Service::ConstPtr &service){
- if (service.data() == 0){
+ if (service.data() == 0)
dbg << "Service{*NULL*}";
- } else {
+ else
dbg << *service.data();
- }
return dbg;
}
@@ -663,7 +661,7 @@ extern "C" void DNSSD_API cServiceResolveReply(DNSServiceRef
<< ((size_t)context);
ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
if (ctxGatherer){
- if (ctxGatherer->currentService->fullName() != fullname){
+ if (ctxGatherer->currentService->fullName() != QString::fromLocal8Bit(fullname)) {
qDebug() << "ServiceBrowser " << ctxGatherer->serviceBrowser->serviceType
<< " for service " << ctxGatherer->currentService->name()
<< " ignoring resolve reply for " << fullname << " vs. "
@@ -718,9 +716,8 @@ extern "C" void DNSSD_API cAddrReply(DNSServiceRef sdRef,
<< interfaceIndex << ", " << ((int)errorCode) << ", " << hostname << ", "
<< QHostAddress(address).toString() << ", " << ttl << ", " << ((size_t)context);
ServiceGatherer *ctxGatherer = reinterpret_cast<ServiceGatherer *>(context);
- if (ctxGatherer){
+ if (ctxGatherer)
ctxGatherer->addrReply(flags, errorCode, hostname, address, ttl);
- }
}
/// callback for service browsing
@@ -856,9 +853,8 @@ void ServiceGatherer::restartResolve(ZK_IP_Protocol protocol)
changed = true;
}
}
- if (changed) {
+ if (changed)
currentService->m_host->setAddresses(addrNow);
- }
}
DNSServiceErrorType err = lib()->resolve(
serviceBrowser->mainRef(),
@@ -889,9 +885,8 @@ void ServiceGatherer::restartResolve(ZK_IP_Protocol protocol)
changed = true;
}
}
- if (changed) {
+ if (changed)
currentService->m_host->setAddresses(addrNow);
- }
}
}
DNSServiceErrorType err = lib()->resolve(
@@ -1078,16 +1073,15 @@ void ServiceGatherer::serviceResolveReply(DNSServiceFlags fl
}
currentService->m_interfaceNr = interfaceIndex;
currentService->m_port = port;
- if (hostName != hosttarget) {
+ if (hostName != QString::fromUtf8(hosttarget)) {
hostName = QString::fromUtf8(hosttarget);
if (!currentService->host())
currentService->m_host = new QHostInfo();
else
currentService->m_host->setAddresses(QList<QHostAddress>());
currentService->m_host->setHostName(hostName);
- if (serviceBrowser->autoResolveAddresses){
+ if (serviceBrowser->autoResolveAddresses)
restartHostResolution();
- }
}
if (currentServiceCanBePublished())
serviceBrowser->pendingGathererAdd(gatherer());
@@ -1144,9 +1138,8 @@ void ServiceGatherer::txtRecordReply(DNSServiceFlags flags,
currentService->m_txtRecord.remove(QString::fromUtf8(keyBuf)); // check value???
}
}
- if ((flags & kDNSServiceFlagsAdd) != 0) {
+ if ((flags & kDNSServiceFlagsAdd) != 0)
status |= TxtConnectionSuccess;
- }
if (currentService->m_txtRecord.count() != 0 && currentServiceCanBePublished())
serviceBrowser->pendingGathererAdd(gatherer());
}
@@ -1224,7 +1217,7 @@ void ServiceGatherer::addrReply(DNSServiceFlags flags,
serviceBrowser->updateFlowStatusForFlags(flags);
if (!currentService->host())
currentService->m_host = new QHostInfo();
- if (currentService->host()->hostName() != hostname) {
+ if (currentService->host()->hostName() != QString::fromUtf8(hostname)) {
if ((flags & kDNSServiceFlagsAdd) == 1)
currentService->m_host->setHostName(QString::fromUtf8(hostname));
if (currentService->host()->addresses().isEmpty()) {
@@ -1373,12 +1366,10 @@ ServiceBrowserPrivate::~ServiceBrowserPrivate()
{
if (DEBUG_ZEROCONF)
qDebug() << "destroying ServiceBrowserPrivate " << serviceType;
- if (browsing){
+ if (browsing)
stopBrowsing();
- }
- if (mainConnection){
+ if (mainConnection)
mainConnection->removeBrowser(this);
- }
}
void ServiceBrowserPrivate::insertGatherer(const QString &fullName)
@@ -1475,9 +1466,9 @@ void ServiceBrowserPrivate::browseReply(DNSServiceFlags flag
QString newServiceName = QString::fromUtf8(serviceName);
QString newType = serviceType;
QString newDomain = domain;
- if (serviceType != regtype) // discard? should not happen...
+ if (serviceType != QString::fromUtf8(regtype)) // discard? should not happen...
newType = QString::fromUtf8(regtype);
- if (domain != replyDomain)
+ if (domain != QString::fromUtf8(replyDomain))
domain = QString::fromUtf8(replyDomain);
QString fullName = toFullNameC(serviceName, regtype, replyDomain);
updateFlowStatusForFlags(flags);
@@ -1498,9 +1489,8 @@ void ServiceBrowserPrivate::browseReply(DNSServiceFlags flag
if (pos == knownServices.end() || *pos != fullName)
knownServices.insert(pos, fullName);
} else {
- if (gatherers.contains(fullName)){
+ if (gatherers.contains(fullName))
gatherers[fullName]->maybeRemove();
- }
knownServices.removeOne(fullName);
}
maybeUpdateLists(); // avoid?
diff --git a/src/libs/zeroconf/zeroconf.qbs b/src/libs/zeroconf/zeroconf.qbs
index fcc98878a1..04274fd6f6 100644
--- a/src/libs/zeroconf/zeroconf.qbs
+++ b/src/libs/zeroconf/zeroconf.qbs
@@ -6,8 +6,8 @@ QtcLibrary {
Depends { name: "cpp" }
Depends { name: "Qt.network" }
+ cpp.includePaths: base.concat(".")
- cpp.includePaths: "."
cpp.defines: base.concat("ZEROCONF_LIBRARY")
Properties {
@@ -26,21 +26,16 @@ QtcLibrary {
}
files: [
- "servicebrowser.cpp",
- "servicebrowser.h",
- "servicebrowser_p.h",
- "embeddedLib.cpp",
- "mdnsderived.cpp",
- "mdnsderived.h",
"avahiLib.cpp",
"dnsSdLib.cpp",
"dns_sd_types.h",
+ "embeddedLib.cpp",
+ "mdnsderived.cpp",
+ "mdnsderived.h",
+ "servicebrowser.cpp",
+ "servicebrowser.h",
+ "servicebrowser_p.h",
+ "syssocket.h",
"zeroconf_global.h",
- "syssocket.h"
]
-
- ProductModule {
- Depends { name: "cpp" }
- cpp.includePaths: ["."]
- }
}
diff --git a/src/plugins/QtcPlugin.qbs b/src/plugins/QtcPlugin.qbs
index 8ed4ce13c0..9a2f701f29 100644
--- a/src/plugins/QtcPlugin.qbs
+++ b/src/plugins/QtcPlugin.qbs
@@ -1,11 +1,11 @@
import qbs.base 1.0
import qbs.fileinfo 1.0 as FileInfo
+import "../../qbs/defaults.js" as Defaults
Product {
type: ["dynamiclibrary", "pluginSpec"]
property string provider: 'QtProject'
property var pluginspecreplacements
- destination: "lib/qtcreator/plugins/" + provider
targetName: {
// see PluginSpecPrivate::loadLibrary()
if (qbs.debugInformation) {
@@ -21,16 +21,28 @@ Product {
Depends { name: "pluginspec" }
Depends { name: "cpp" }
- cpp.defines: project.additionalCppDefines.concat([name.toUpperCase() + "_LIBRARY"])
- cpp.rpaths: ["$ORIGIN/../../.."]
+ Depends {
+ condition: Defaults.testsEnabled(qbs)
+ name: "Qt.test"
+ }
+
+ cpp.defines: Defaults.defines(qbs).concat([name.toUpperCase() + "_LIBRARY"])
+ cpp.rpaths: ["$ORIGIN/../.."]
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain == "gcc" || qbs.toolchain == "mingw"))
return ["-Wl,-s"]
}
+ cpp.includePaths: [ ".", ".." ]
Group {
+ name: "PluginSpec"
files: [ product.name + ".pluginspec.in" ]
fileTags: ["pluginSpecIn"]
}
-}
+ Group {
+ fileTagsFilter: product.type
+ qbs.install: true
+ qbs.installDir: "lib/qtcreator/plugins/" + provider
+ }
+}
diff --git a/src/plugins/analyzerbase/analyzerbase.pro b/src/plugins/analyzerbase/analyzerbase.pro
index b3512f66cd..6659c64d23 100644
--- a/src/plugins/analyzerbase/analyzerbase.pro
+++ b/src/plugins/analyzerbase/analyzerbase.pro
@@ -1,7 +1,7 @@
TEMPLATE = lib
TARGET = AnalyzerBase
-DEFINES += ANALYZER_LIBRARY QT_NO_CAST_FROM_ASCII
+DEFINES += ANALYZER_LIBRARY
include(../../qtcreatorplugin.pri)
include(analyzerbase_dependencies.pri)
diff --git a/src/plugins/analyzerbase/analyzerbase.qbs b/src/plugins/analyzerbase/analyzerbase.qbs
index 7fada29a11..621bdd10d7 100644
--- a/src/plugins/analyzerbase/analyzerbase.qbs
+++ b/src/plugins/analyzerbase/analyzerbase.qbs
@@ -13,27 +13,24 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "cpp" }
- cpp.defines: base.concat([
- "ANALYZER_LIBRARY",
- "QT_NO_CAST_FROM_ASCII"
- ])
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
+ cpp.defines: base.concat("ANALYZER_LIBRARY")
files: [
"analyzerbase.qrc",
"analyzerbase_global.h",
"analyzerconstants.h",
+ "analyzermanager.cpp",
+ "analyzermanager.h",
"analyzeroptionspage.cpp",
"analyzeroptionspage.h",
"analyzerplugin.cpp",
"analyzerplugin.h",
"analyzerrunconfigwidget.cpp",
"analyzerrunconfigwidget.h",
+ "analyzerruncontrol.cpp",
"analyzerruncontrol.h",
+ "analyzerruncontrolfactory.cpp",
+ "analyzerruncontrolfactory.h",
"analyzersettings.cpp",
"analyzersettings.h",
"analyzerstartparameters.h",
@@ -42,23 +39,15 @@ QtcPlugin {
"ianalyzerengine.cpp",
"ianalyzerengine.h",
"ianalyzertool.cpp",
+ "ianalyzertool.h",
"startremotedialog.cpp",
"startremotedialog.h",
- "analyzermanager.cpp",
- "analyzermanager.h",
- "analyzerruncontrol.cpp",
- "analyzerruncontrolfactory.cpp",
- "analyzerruncontrolfactory.h",
- "ianalyzertool.h",
"images/analyzer_category.png",
"images/analyzer_mode.png",
- "images/analyzer_start_small.png"
+ "images/analyzer_start_small.png",
]
ProductModule {
- Depends { name: "cpp" }
- cpp.includePaths: ["."]
-
Depends { name: "CPlusPlus" }
}
}
diff --git a/src/plugins/analyzerbase/analyzermanager.cpp b/src/plugins/analyzerbase/analyzermanager.cpp
index e25cd100a8..f8e60a6e13 100644
--- a/src/plugins/analyzerbase/analyzermanager.cpp
+++ b/src/plugins/analyzerbase/analyzermanager.cpp
@@ -88,6 +88,7 @@
#include <QLabel>
#include <QCheckBox>
#include <QDialogButtonBox>
+#include <QPointer>
#include <QPushButton>
using namespace Core;
@@ -211,7 +212,7 @@ public:
MainWindowSettingsMap m_defaultSettings;
// list of dock widgets to prevent memory leak
- typedef QWeakPointer<QDockWidget> DockPtr;
+ typedef QPointer<QDockWidget> DockPtr;
QList<DockPtr> m_dockWidgets;
};
@@ -235,8 +236,6 @@ AnalyzerManagerPrivate::AnalyzerManagerPrivate(AnalyzerManager *qq):
setupActions();
- connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
- this, SLOT(modeChanged(Core::IMode*)));
ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
connect(pe, SIGNAL(updateRunActions()), SLOT(updateRunActions()));
}
@@ -294,6 +293,9 @@ void AnalyzerManagerPrivate::delayedInit()
m_mode = new AnalyzerMode(q);
createModeMainWindow();
+ connect(ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*)),
+ this, SLOT(modeChanged(Core::IMode*)));
+
// Right-side window with editor, output etc.
MiniSplitter *mainWindowSplitter = new MiniSplitter;
mainWindowSplitter->addWidget(m_mainWindow);
diff --git a/src/plugins/analyzerbase/analyzeroptionspage.cpp b/src/plugins/analyzerbase/analyzeroptionspage.cpp
index cb878db197..c36d8a45c9 100644
--- a/src/plugins/analyzerbase/analyzeroptionspage.cpp
+++ b/src/plugins/analyzerbase/analyzeroptionspage.cpp
@@ -48,7 +48,7 @@ AnalyzerOptionsPage::AnalyzerOptionsPage(AbstractAnalyzerSubConfig *config, QObj
{
setId(m_config->id());
setDisplayName(m_config->displayName());
- setCategory(QLatin1String("T.Analyzer"));
+ setCategory("T.Analyzer");
setDisplayCategory(QCoreApplication::translate("Analyzer", "Analyzer"));
setCategoryIcon(QLatin1String(":/images/analyzer_category.png"));
}
diff --git a/src/plugins/analyzerbase/analyzerruncontrol.cpp b/src/plugins/analyzerbase/analyzerruncontrol.cpp
index 73b1d9c7a1..7d695817d8 100644
--- a/src/plugins/analyzerbase/analyzerruncontrol.cpp
+++ b/src/plugins/analyzerbase/analyzerruncontrol.cpp
@@ -35,7 +35,7 @@
#include "analyzermanager.h"
#include "analyzerstartparameters.h"
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/task.h>
diff --git a/src/plugins/analyzerbase/analyzerruncontrolfactory.cpp b/src/plugins/analyzerbase/analyzerruncontrolfactory.cpp
index 9e69b81860..9ee6da8447 100644
--- a/src/plugins/analyzerbase/analyzerruncontrolfactory.cpp
+++ b/src/plugins/analyzerbase/analyzerruncontrolfactory.cpp
@@ -35,7 +35,7 @@
#include "ianalyzertool.h"
#include "analyzerstartparameters.h"
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/projectexplorer.h>
#include <utils/qtcassert.h>
@@ -89,6 +89,14 @@ IRunConfigurationAspect *AnalyzerRunControlFactory::createRunConfigurationAspect
return new AnalyzerRunConfigurationAspect;
}
+IRunConfigurationAspect *AnalyzerRunControlFactory::cloneRunConfigurationAspect(IRunConfigurationAspect *source)
+{
+ AnalyzerRunConfigurationAspect *s = dynamic_cast<AnalyzerRunConfigurationAspect *>(source);
+ if (!s)
+ return 0;
+ return new AnalyzerRunConfigurationAspect(s);
+}
+
RunConfigWidget *AnalyzerRunControlFactory::createConfigurationWidget(RunConfiguration *runConfiguration)
{
AnalyzerRunConfigWidget *ret = new AnalyzerRunConfigWidget;
diff --git a/src/plugins/analyzerbase/analyzerruncontrolfactory.h b/src/plugins/analyzerbase/analyzerruncontrolfactory.h
index fb4293e43d..880b6e3253 100644
--- a/src/plugins/analyzerbase/analyzerruncontrolfactory.h
+++ b/src/plugins/analyzerbase/analyzerruncontrolfactory.h
@@ -51,6 +51,7 @@ public:
ProjectExplorer::RunMode mode,
QString *errorMessage);
ProjectExplorer::IRunConfigurationAspect *createRunConfigurationAspect();
+ ProjectExplorer::IRunConfigurationAspect *cloneRunConfigurationAspect(ProjectExplorer::IRunConfigurationAspect *source);
ProjectExplorer::RunConfigWidget *createConfigurationWidget(RunConfiguration *runConfiguration);
};
diff --git a/src/plugins/analyzerbase/analyzersettings.cpp b/src/plugins/analyzerbase/analyzersettings.cpp
index 620a1c7b7e..5bc1699619 100644
--- a/src/plugins/analyzerbase/analyzersettings.cpp
+++ b/src/plugins/analyzerbase/analyzersettings.cpp
@@ -54,6 +54,11 @@ AnalyzerSettings::AnalyzerSettings(QObject *parent)
{
}
+AnalyzerSettings::AnalyzerSettings(AnalyzerSettings *other)
+{
+ Q_UNUSED(other);
+}
+
QVariantMap AnalyzerSettings::defaults() const
{
QVariantMap map;
@@ -148,8 +153,8 @@ void AnalyzerGlobalSettings::registerTool(IAnalyzerTool *tool)
}
-AnalyzerRunConfigurationAspect::AnalyzerRunConfigurationAspect(QObject *parent)
- : AnalyzerSettings(parent), m_useGlobalSettings(true)
+AnalyzerRunConfigurationAspect::AnalyzerRunConfigurationAspect()
+ : AnalyzerSettings((QObject *)0), m_useGlobalSettings(true)
{
QList<IAnalyzerTool*> tools = AnalyzerManager::tools();
// add sub configs
@@ -163,6 +168,19 @@ AnalyzerRunConfigurationAspect::AnalyzerRunConfigurationAspect(QObject *parent)
resetCustomToGlobalSettings();
}
+AnalyzerRunConfigurationAspect::AnalyzerRunConfigurationAspect(AnalyzerRunConfigurationAspect *other)
+ : AnalyzerSettings(other), m_useGlobalSettings(other->m_useGlobalSettings)
+{
+
+ foreach (AbstractAnalyzerSubConfig *config, other->m_customConfigurations)
+ m_customConfigurations.append(config->clone());
+
+ if (m_useGlobalSettings)
+ m_subConfigs = AnalyzerGlobalSettings::instance()->subConfigs();
+ else
+ m_subConfigs = m_customConfigurations;
+}
+
AnalyzerRunConfigurationAspect::~AnalyzerRunConfigurationAspect()
{
qDeleteAll(m_customConfigurations);
@@ -191,11 +209,10 @@ void AnalyzerRunConfigurationAspect::setUsingGlobalSettings(bool value)
if (value == m_useGlobalSettings)
return;
m_useGlobalSettings = value;
- if (m_useGlobalSettings) {
+ if (m_useGlobalSettings)
m_subConfigs = AnalyzerGlobalSettings::instance()->subConfigs();
- } else {
+ else
m_subConfigs = m_customConfigurations;
- }
}
void AnalyzerRunConfigurationAspect::resetCustomToGlobalSettings()
diff --git a/src/plugins/analyzerbase/analyzersettings.h b/src/plugins/analyzerbase/analyzersettings.h
index 2d1402845e..81503dfb08 100644
--- a/src/plugins/analyzerbase/analyzersettings.h
+++ b/src/plugins/analyzerbase/analyzersettings.h
@@ -36,6 +36,7 @@
#include "analyzerbase_global.h"
+#include <coreplugin/id.h>
#include <projectexplorer/runconfiguration.h>
namespace Analyzer {
@@ -73,11 +74,13 @@ public:
virtual void fromMap(const QVariantMap &map) = 0;
/// unique ID for this configuration
- virtual QString id() const = 0;
+ virtual Core::Id id() const = 0;
/// user readable display name for this configuration
virtual QString displayName() const = 0;
/// create a configuration widget for this configuration
virtual QWidget *createConfigWidget(QWidget *parent) = 0;
+ /// clones s AbstractAnalyzerSubConfig
+ virtual AbstractAnalyzerSubConfig *clone() = 0;
};
/**
@@ -115,6 +118,7 @@ protected:
void fromMap(const QVariantMap &map, QList<AbstractAnalyzerSubConfig *> *subConfigs);
AnalyzerSettings(QObject *parent);
+ AnalyzerSettings(AnalyzerSettings *other);
QList<AbstractAnalyzerSubConfig *> m_subConfigs;
};
@@ -162,7 +166,8 @@ class ANALYZER_EXPORT AnalyzerRunConfigurationAspect
Q_OBJECT
public:
- AnalyzerRunConfigurationAspect(QObject *parent = 0);
+ AnalyzerRunConfigurationAspect();
+ AnalyzerRunConfigurationAspect(AnalyzerRunConfigurationAspect *other);
~AnalyzerRunConfigurationAspect();
QString displayName() const;
diff --git a/src/plugins/analyzerbase/ianalyzertool.cpp b/src/plugins/analyzerbase/ianalyzertool.cpp
index 081ca19e84..218eec88cf 100644
--- a/src/plugins/analyzerbase/ianalyzertool.cpp
+++ b/src/plugins/analyzerbase/ianalyzertool.cpp
@@ -42,8 +42,8 @@ IAnalyzerTool::IAnalyzerTool(QObject *parent)
Id IAnalyzerTool::defaultMenuGroup(StartMode mode)
{
if (mode == StartRemote)
- return Constants::G_ANALYZER_REMOTE_TOOLS;
- return Constants::G_ANALYZER_TOOLS;
+ return Id(Constants::G_ANALYZER_REMOTE_TOOLS);
+ return Id(Constants::G_ANALYZER_TOOLS);
}
Id IAnalyzerTool::defaultActionId(const IAnalyzerTool *tool, StartMode mode)
@@ -51,11 +51,11 @@ Id IAnalyzerTool::defaultActionId(const IAnalyzerTool *tool, StartMode mode)
Id id = tool->id();
switch (mode) {
case StartLocal:
- return Id(QByteArray("Analyzer." + id.name() + ".Local").data());
+ return Id(QByteArray("Analyzer." + id.name() + ".Local"));
case StartRemote:
- return Id(QByteArray("Analyzer." + id.name() + ".Remote").data());
+ return Id(QByteArray("Analyzer." + id.name() + ".Remote"));
case StartQml:
- return Id(QByteArray("Analyzer." + id.name() + ".Qml").data());
+ return Id(QByteArray("Analyzer." + id.name() + ".Qml"));
}
return Id();
}
diff --git a/src/plugins/android/Android.pluginspec.in b/src/plugins/android/Android.pluginspec.in
index f7bf82c4a4..0f5ddc6e5a 100644
--- a/src/plugins/android/Android.pluginspec.in
+++ b/src/plugins/android/Android.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Android\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"$$ANDROID_EXPERIMENTAL_STR\">
+<plugin name=\"Android\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
<vendor>KDE Necessitas</vendor>
<copyright>(C) 2013 BogDan Vatra</copyright>
<license>
@@ -12,7 +12,7 @@ Alternatively, this plugin may be used under the terms of the GNU Lesser General
</license>
<description>Support for deployment to and execution on Android Devices</description>
<category>Device Support</category>
- <url>http://community.kde.org/Necessitas</url>
+ <url>http://necessitas.kde.org</url>
<dependencyList>
<dependency name=\"Core\" version=\"$$QTCREATOR_VERSION\"/>
<dependency name=\"Debugger\" version=\"$$QTCREATOR_VERSION\"/>
diff --git a/src/plugins/android/android.pro b/src/plugins/android/android.pro
index 94e3fd054c..4361a95ab0 100644
--- a/src/plugins/android/android.pro
+++ b/src/plugins/android/android.pro
@@ -76,5 +76,4 @@ FORMS += \
androidcreatekeystorecertificate.ui
RESOURCES = android.qrc
-DEFINES += QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
DEFINES += ANDROID_LIBRARY
diff --git a/src/plugins/android/android.qbs b/src/plugins/android/android.qbs
index d719b78309..62304534b5 100644
--- a/src/plugins/android/android.qbs
+++ b/src/plugins/android/android.qbs
@@ -13,17 +13,13 @@ QtcPlugin {
Depends { name: "Qt"; submodules: ["widgets", "xml", "network"] }
property bool enable: false
- property var pluginspecreplacements: ({"ANDROID_EXPERIMENTAL_STR": (enable ? "false": "true")})
+ pluginspecreplacements: ({"ANDROID_EXPERIMENTAL_STR": (enable ? "false": "true")})
- cpp.includePaths: [
- "..",
- buildDirectory,
- "../../libs",
- "../../shared"
- ]
+ cpp.includePaths: base.concat("../../shared")
files: [
"addnewavddialog.ui",
+ "android.qrc",
"androidconfigurations.cpp",
"androidconfigurations.h",
"androidconstants.h",
@@ -35,9 +31,9 @@ QtcPlugin {
"androiddeployconfiguration.cpp",
"androiddeployconfiguration.h",
"androiddeploystep.cpp",
+ "androiddeploystep.h",
"androiddeploystepfactory.cpp",
"androiddeploystepfactory.h",
- "androiddeploystep.h",
"androiddeploystepwidget.cpp",
"androiddeploystepwidget.h",
"androiddeploystepwidget.ui",
@@ -46,8 +42,8 @@ QtcPlugin {
"androiddevicefactory.cpp",
"androiddevicefactory.h",
"androidglobal.h",
- "androidmanager.h",
"androidmanager.cpp",
+ "androidmanager.h",
"androidpackagecreationfactory.cpp",
"androidpackagecreationfactory.h",
"androidpackagecreationstep.cpp",
@@ -61,11 +57,10 @@ QtcPlugin {
"androidpackageinstallationstep.h",
"androidplugin.cpp",
"androidplugin.h",
- "android.qrc",
"androidqtversion.cpp",
+ "androidqtversion.h",
"androidqtversionfactory.cpp",
"androidqtversionfactory.h",
- "androidqtversion.h",
"androidrunconfiguration.cpp",
"androidrunconfiguration.h",
"androidruncontrol.cpp",
@@ -82,6 +77,6 @@ QtcPlugin {
"androidtoolchain.cpp",
"androidtoolchain.h",
"javaparser.cpp",
- "javaparser.h"
+ "javaparser.h",
]
}
diff --git a/src/plugins/android/androidconfigurations.cpp b/src/plugins/android/androidconfigurations.cpp
index 18e8080f09..737aed1602 100644
--- a/src/plugins/android/androidconfigurations.cpp
+++ b/src/plugins/android/androidconfigurations.cpp
@@ -32,6 +32,7 @@
#include "ui_addnewavddialog.h"
#include <coreplugin/icore.h>
+#include <utils/hostosinfo.h>
#include <utils/persistentsettings.h>
#include <QDateTime>
@@ -82,10 +83,10 @@ namespace {
const QLatin1String jarsignerName("jarsigner");
const QLatin1String changeTimeStamp("ChangeTimeStamp");
- static Utils::FileName settingsFileName()
+ static QString sdkSettingsFileName()
{
- return Utils::FileName::fromString(QString::fromLatin1("%1/qtcreator/android.xml")
- .arg(QFileInfo(Core::ICore::settings(QSettings::SystemScope)->fileName()).absolutePath()));
+ return QString::fromLatin1("%1/android.xml")
+ .arg(QFileInfo(Core::ICore::settings(QSettings::SystemScope)->fileName()).absolutePath());
}
bool androidDevicesLessThan(const AndroidDeviceInfo &dev1, const AndroidDeviceInfo &dev2)
@@ -141,9 +142,8 @@ AndroidConfig::AndroidConfig(const QSettings &settings)
// user settings
PersistentSettingsReader reader;
- Utils::FileName fn = settingsFileName();
- if (reader.load(fn)
- && settings.value(changeTimeStamp).toInt() != fn.toFileInfo().lastModified().toMSecsSinceEpoch() / 1000) {
+ if (reader.load(FileName::fromString(sdkSettingsFileName()))
+ && settings.value(changeTimeStamp).toInt() != QFileInfo(sdkSettingsFileName()).lastModified().toMSecsSinceEpoch() / 1000) {
// persisten settings
sdkLocation = FileName::fromString(reader.restoreValue(SDKLocationKey).toString());
ndkLocation = FileName::fromString(reader.restoreValue(NDKLocationKey).toString());
@@ -181,7 +181,7 @@ AndroidConfig::AndroidConfig()
void AndroidConfig::save(QSettings &settings) const
{
- QFileInfo fileInfo = settingsFileName().toFileInfo();
+ QFileInfo fileInfo(sdkSettingsFileName());
if (fileInfo.exists())
settings.setValue(changeTimeStamp, fileInfo.lastModified().toMSecsSinceEpoch() / 1000);
@@ -262,24 +262,24 @@ QStringList AndroidConfigurations::ndkToolchainVersions() const
FileName AndroidConfigurations::adbToolPath() const
{
FileName path = m_config.sdkLocation;
- return path.appendPath(QLatin1String("platform-tools/adb" ANDROID_EXE_SUFFIX));
+ return path.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX));
}
FileName AndroidConfigurations::androidToolPath() const
{
-#ifdef Q_OS_WIN32
- // I want to switch from using android.bat to using an executable. All it really does is call
- // Java and I've made some progress on it. So if android.exe exists, return that instead.
- FileName path = m_config.sdkLocation;
- path.appendPath(QLatin1String("tools/android"ANDROID_EXE_SUFFIX));
- if (path.toFileInfo().exists())
- return path;
- path = m_config.sdkLocation;
- return path.appendPath(QLatin1String("tools/android"ANDROID_BAT_SUFFIX));
-#else
- FileName path = m_config.sdkLocation;
- return path.appendPath(QLatin1String("tools/android"));
-#endif
+ if (HostOsInfo::isWindowsHost()) {
+ // I want to switch from using android.bat to using an executable. All it really does is call
+ // Java and I've made some progress on it. So if android.exe exists, return that instead.
+ FileName path = m_config.sdkLocation;
+ path.appendPath(QLatin1String("tools/android" QTC_HOST_EXE_SUFFIX));
+ if (path.toFileInfo().exists())
+ return path;
+ path = m_config.sdkLocation;
+ return path.appendPath(QLatin1String("tools/android" ANDROID_BAT_SUFFIX));
+ } else {
+ FileName path = m_config.sdkLocation;
+ return path.appendPath(QLatin1String("tools/android"));
+ }
}
FileName AndroidConfigurations::antToolPath() const
@@ -293,7 +293,7 @@ FileName AndroidConfigurations::antToolPath() const
FileName AndroidConfigurations::emulatorToolPath() const
{
FileName path = m_config.sdkLocation;
- return path.appendPath(QLatin1String("tools/emulator" ANDROID_EXE_SUFFIX));
+ return path.appendPath(QLatin1String("tools/emulator" QTC_HOST_EXE_SUFFIX));
}
FileName AndroidConfigurations::toolPath(Abi::Architecture architecture) const
@@ -308,17 +308,17 @@ FileName AndroidConfigurations::toolPath(Abi::Architecture architecture) const
FileName AndroidConfigurations::stripPath(Abi::Architecture architecture) const
{
- return toolPath(architecture).append(QLatin1String("-strip" ANDROID_EXE_SUFFIX));
+ return toolPath(architecture).append(QLatin1String("-strip" QTC_HOST_EXE_SUFFIX));
}
FileName AndroidConfigurations::readelfPath(Abi::Architecture architecture) const
{
- return toolPath(architecture).append(QLatin1String("-readelf" ANDROID_EXE_SUFFIX));
+ return toolPath(architecture).append(QLatin1String("-readelf" QTC_HOST_EXE_SUFFIX));
}
FileName AndroidConfigurations::gccPath(Abi::Architecture architecture) const
{
- return toolPath(architecture).append(QLatin1String("-gcc" ANDROID_EXE_SUFFIX));
+ return toolPath(architecture).append(QLatin1String("-gcc" QTC_HOST_EXE_SUFFIX));
}
FileName AndroidConfigurations::gdbServerPath(Abi::Architecture architecture) const
@@ -360,7 +360,7 @@ FileName AndroidConfigurations::gdbPath(Abi::Architecture architecture) const
}
if (!gdbPath.isEmpty())
return gdbPath;
- return toolPath(architecture).append(QLatin1String("-gdb" ANDROID_EXE_SUFFIX));
+ return toolPath(architecture).append(QLatin1String("-gdb" QTC_HOST_EXE_SUFFIX));
}
FileName AndroidConfigurations::openJDKPath() const
@@ -389,7 +389,7 @@ FileName AndroidConfigurations::jarsignerPath() const
FileName AndroidConfigurations::zipalignPath() const
{
Utils::FileName path = m_config.sdkLocation;
- return path.appendPath(QLatin1String("tools/zipalign" ANDROID_EXE_SUFFIX));
+ return path.appendPath(QLatin1String("tools/zipalign" QTC_HOST_EXE_SUFFIX));
}
QString AndroidConfigurations::getDeployDeviceSerialNumber(int *apiLevel) const
@@ -411,7 +411,7 @@ QVector<AndroidDeviceInfo> AndroidConfigurations::connectedDevices(int apiLevel)
QProcess adbProc;
adbProc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
if (!adbProc.waitForFinished(-1)) {
- adbProc.terminate();
+ adbProc.kill();
return devices;
}
QList<QByteArray> adbDevs = adbProc.readAll().trimmed().split('\n');
@@ -564,7 +564,7 @@ QString AndroidConfigurations::startAVD(int *apiLevel, const QString &name) cons
proc.start(adbToolPath().toString(), QStringList() << QLatin1String("-e") << QLatin1String("wait-for-device"));
while (!proc.waitForFinished(500)) {
if (avdProcess->waitForFinished(0)) {
- proc.terminate();
+ proc.kill();
proc.waitForFinished(-1);
return QString();
}
@@ -574,7 +574,7 @@ QString AndroidConfigurations::startAVD(int *apiLevel, const QString &name) cons
// workaround for stupid adb bug
proc.start(adbToolPath().toString(), QStringList() << QLatin1String("devices"));
if (!proc.waitForFinished(-1)) {
- proc.terminate();
+ proc.kill();
return QString();
}
@@ -596,7 +596,7 @@ int AndroidConfigurations::getSDKVersion(const QString &device) const
<< QLatin1String("shell") << QLatin1String("getprop")
<< QLatin1String("ro.build.version.sdk"));
if (!adbProc.waitForFinished(-1)) {
- adbProc.terminate();
+ adbProc.kill();
return -1;
}
return adbProc.readAll().trimmed().toInt();
diff --git a/src/plugins/android/androidconstants.h b/src/plugins/android/androidconstants.h
index 4021e62feb..17357471d1 100644
--- a/src/plugins/android/androidconstants.h
+++ b/src/plugins/android/androidconstants.h
@@ -44,10 +44,8 @@ enum AndroidQemuStatus {
};
#ifdef Q_OS_WIN32
-#define ANDROID_EXE_SUFFIX ".exe"
#define ANDROID_BAT_SUFFIX ".bat"
#else
-#define ANDROID_EXE_SUFFIX ""
#define ANDROID_BAT_SUFFIX ""
#endif
@@ -55,7 +53,7 @@ enum AndroidQemuStatus {
namespace Constants {
const char ANDROID_SETTINGS_ID[] = "ZZ.Android Configurations";
-const char ANDROID_SETTINGS_CATEGORY[] = "X.Android";
+const char ANDROID_SETTINGS_CATEGORY[] = "XA.Android";
const char ANDROID_SETTINGS_TR_CATEGORY[] = QT_TRANSLATE_NOOP("Android", "Android");
const char ANDROID_SETTINGS_CATEGORY_ICON[] = ":/android/images/QtAndroid.png";
const char ANDROID_TOOLCHAIN_ID[] = "Qt4ProjectManager.ToolChain.Android";
diff --git a/src/plugins/android/androiddebugsupport.cpp b/src/plugins/android/androiddebugsupport.cpp
index 19543d5424..c5eb00bdf6 100644
--- a/src/plugins/android/androiddebugsupport.cpp
+++ b/src/plugins/android/androiddebugsupport.cpp
@@ -156,9 +156,8 @@ void AndroidDebugSupport::handleRemoteProcessStarted(int gdbServerPort, int qmlP
void AndroidDebugSupport::handleRemoteProcessFinished(const QString &errorMsg)
{
- disconnect(m_runner, SIGNAL(remoteProcessFinished(QString)),
- this,SLOT(handleRemoteProcessFinished(QString)));
- m_runControl->engine()->notifyEngineRemoteSetupFailed(errorMsg);
+ if (m_runControl)
+ m_runControl->showMessage(errorMsg, AppStuff);
}
void AndroidDebugSupport::handleRemoteOutput(const QByteArray &output)
diff --git a/src/plugins/android/androiddeployconfiguration.cpp b/src/plugins/android/androiddeployconfiguration.cpp
index 03008d4630..ae84f247be 100644
--- a/src/plugins/android/androiddeployconfiguration.cpp
+++ b/src/plugins/android/androiddeployconfiguration.cpp
@@ -56,6 +56,7 @@ AndroidDeployConfiguration::AndroidDeployConfiguration(Target *parent, Core::Id
AndroidDeployConfiguration::AndroidDeployConfiguration(Target *parent, DeployConfiguration *source)
: DeployConfiguration(parent, source)
{
+ cloneSteps(source);
}
AndroidDeployConfigurationFactory::AndroidDeployConfigurationFactory(QObject *parent)
diff --git a/src/plugins/android/androiddeploystep.cpp b/src/plugins/android/androiddeploystep.cpp
index 3ead9852ed..72eedc590b 100644
--- a/src/plugins/android/androiddeploystep.cpp
+++ b/src/plugins/android/androiddeploystep.cpp
@@ -36,6 +36,7 @@
#include "androidrunconfiguration.h"
#include "androidmanager.h"
+#include <coreplugin/messagemanager.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
@@ -56,6 +57,7 @@ namespace Android {
namespace Internal {
static const char USE_LOCAL_QT_KEY[] = "Qt4ProjectManager.AndroidDeployStep.UseLocalQtLibs";
+static const char DEPLOY_ACTION_KEY[] = "Qt4ProjectManager.AndroidDeployStep.DeployAction";
const Core::Id AndroidDeployStep::Id("Qt4ProjectManager.AndroidDeployStep");
@@ -138,6 +140,9 @@ bool AndroidDeployStep::useLocalQtLibs()
bool AndroidDeployStep::fromMap(const QVariantMap &map)
{
m_useLocalQtLibs = map.value(QLatin1String(USE_LOCAL_QT_KEY), false).toBool();
+ m_deployAction = AndroidDeployAction(map.value(QLatin1String(DEPLOY_ACTION_KEY), NoDeploy).toInt());
+ if (m_deployAction == InstallQASI)
+ m_deployAction = NoDeploy;
return ProjectExplorer::BuildStep::fromMap(map);
}
@@ -145,9 +150,40 @@ QVariantMap AndroidDeployStep::toMap() const
{
QVariantMap map = ProjectExplorer::BuildStep::toMap();
map.insert(QLatin1String(USE_LOCAL_QT_KEY), m_useLocalQtLibs);
+ map.insert(QLatin1String(DEPLOY_ACTION_KEY), m_deployAction);
return map;
}
+void AndroidDeployStep::cleanLibsOnDevice()
+{
+ const QString targetSDK = AndroidManager::targetSDK(target());
+
+ int deviceAPILevel = targetSDK.mid(targetSDK.indexOf(QLatin1Char('-')) + 1).toInt();
+ QString deviceSerialNumber = AndroidConfigurations::instance().getDeployDeviceSerialNumber(&deviceAPILevel);
+ if (!deviceSerialNumber.length()) {
+ Core::MessageManager::instance()->printToOutputPanePopup(tr("Could not run adb. No device found."));
+ return;
+ }
+ QProcess *process = new QProcess(this);
+ QStringList arguments;
+ arguments << QLatin1String("-s") << deviceSerialNumber
+ << QLatin1String("shell") << QLatin1String("rm") << QLatin1String("-r") << QLatin1String("/data/local/tmp/qt");
+ connect(process, SIGNAL(finished(int)), this, SLOT(cleanLibsFinished()));
+ const QString adb = AndroidConfigurations::instance().adbToolPath().toString();
+ Core::MessageManager::instance()->printToOutputPanePopup(adb + QLatin1String(" ")
+ + arguments.join(QLatin1String(" ")));
+ process->start(adb, arguments);
+}
+
+void AndroidDeployStep::cleanLibsFinished()
+{
+ QProcess *process = qobject_cast<QProcess *>(sender());
+ if (!process)
+ return;
+ Core::MessageManager::instance()->printToOutputPanePopup(QString::fromLocal8Bit(process->readAll()));
+ Core::MessageManager::instance()->printToOutputPane(tr("adb finished with exit code %1.").arg(process->exitCode()));
+}
+
void AndroidDeployStep::setDeployAction(AndroidDeployStep::AndroidDeployAction deploy)
{
m_deployAction = deploy;
@@ -222,24 +258,122 @@ Utils::FileName AndroidDeployStep::localLibsRulesFilePath()
return AndroidManager::localLibsRulesFilePath(target());
}
-void AndroidDeployStep::copyLibs(const QString &srcPath, const QString &destPath, QStringList &copiedLibs, const QStringList &filter)
+unsigned int AndroidDeployStep::remoteModificationTime(const QString &fullDestination, QHash<QString, unsigned int> *cache)
{
- QDir dir;
- dir.mkpath(destPath);
- QDirIterator libsIt(srcPath, filter, QDir::NoFilter, QDirIterator::Subdirectories);
- int pos = srcPath.size();
+ QString destination = QFileInfo(fullDestination).absolutePath();
+ QProcess process;
+ QHash<QString, unsigned int>::const_iterator it = cache->find(fullDestination);
+ if (it != cache->constEnd())
+ return *it;
+ QStringList arguments;
+ arguments << QLatin1String("-s") << m_deviceSerialNumber
+ << QLatin1String("ls") << destination;
+ process.start(AndroidConfigurations::instance().adbToolPath().toString(), arguments);
+ process.waitForFinished(-1);
+ if (process.error() != QProcess::UnknownError
+ || process.exitCode() != 0)
+ return -1;
+ QByteArray output = process.readAll();
+ output.replace("\r\n", "\n");
+ QList<QByteArray> lines = output.split('\n');
+ foreach (const QByteArray &line, lines) {
+ // do some checks if we got what we expected..
+ if (line.count() < (3 * 8 + 3))
+ continue;
+ if (line.at(8) != ' '
+ || line.at(17) != ' '
+ || line.at(26) != ' ')
+ continue;
+ bool ok;
+ int time = line.mid(18, 8).toUInt(&ok, 16);
+ if (!ok)
+ continue;
+ QString fileName = QString::fromLocal8Bit(line.mid(27));
+ cache->insert(destination + QLatin1Char('/') + fileName, time);
+ }
+ it = cache->find(fullDestination);
+ if (it != cache->constEnd())
+ return *it;
+ return 0;
+}
+
+void AndroidDeployStep::collectFiles(QList<DeployItem> *deployList, const QString &localPath, const QString &remotePath,
+ bool strip, const QStringList &filter)
+{
+ QDirIterator libsIt(localPath, filter, QDir::NoFilter, QDirIterator::Subdirectories);
+ int pos = localPath.size();
while (libsIt.hasNext()) {
libsIt.next();
- const QString destFile(destPath + libsIt.filePath().mid(pos));
- if (libsIt.fileInfo().isDir()) {
- dir.mkpath(destFile);
- } else {
- QFile::copy(libsIt.filePath(), destFile);
- copiedLibs.append(destFile);
+ const QString destFile(remotePath + libsIt.filePath().mid(pos));
+ if (!libsIt.fileInfo().isDir()) {
+ deployList->append(DeployItem(libsIt.filePath(),
+ libsIt.fileInfo().lastModified().toTime_t(),
+ destFile, strip));
}
}
}
+void AndroidDeployStep::fetchRemoteModificationTimes(QList<DeployItem> *deployList)
+{
+ QHash<QString, unsigned int> cache;
+ for (int i = 0; i < deployList->count(); ++i) {
+ DeployItem &item = (*deployList)[i];
+ item.remoteTimeStamp
+ = remoteModificationTime(item.remoteFileName, &cache);
+ }
+}
+
+void AndroidDeployStep::filterModificationTimes(QList<DeployItem> *deployList)
+{
+ QList<DeployItem>::iterator it = deployList->begin();
+ while (it != deployList->end()) {
+ int index = it - deployList->begin();
+ Q_UNUSED(index);
+ if ((*it).localTimeStamp <= (*it).remoteTimeStamp)
+ it = deployList->erase(it);
+ else
+ ++it;
+ }
+}
+
+void AndroidDeployStep::copyFilesToTemp(QList<DeployItem> *deployList, const QString &tempDirectory, const QString &sourcePrefix)
+{
+ QDir dir;
+
+ int pos = sourcePrefix.size();
+ for (int i = 0; i < deployList->count(); ++i) {
+ DeployItem &item = (*deployList)[i];
+ if (!item.needsStrip)
+ continue;
+ const QString destFile(tempDirectory + item.localFileName.mid(pos));
+ dir.mkpath(QFileInfo(destFile).absolutePath());
+ QFile::copy(item.localFileName, destFile);
+ item.localFileName = destFile;
+ }
+}
+
+void AndroidDeployStep::stripFiles(const QList<DeployItem> &deployList, Abi::Architecture architecture)
+{
+ QProcess stripProcess;
+ foreach (const DeployItem &item, deployList) {
+ stripProcess.start(AndroidConfigurations::instance().stripPath(architecture).toString(),
+ QStringList()<<QLatin1String("--strip-unneeded") << item.localFileName);
+ stripProcess.waitForStarted();
+ if (!stripProcess.waitForFinished())
+ stripProcess.kill();
+ }
+}
+
+void AndroidDeployStep::deployFiles(QProcess *process, const QList<DeployItem> &deployList)
+{
+ foreach (const DeployItem &item, deployList) {
+ runCommand(process, AndroidConfigurations::instance().adbToolPath().toString(),
+ QStringList() << QLatin1String("-s") << m_deviceSerialNumber
+ << QLatin1String("push") << item.localFileName
+ << item.remoteFileName);
+ }
+}
+
bool AndroidDeployStep::deployPackage()
{
QProcess *const deployProc = new QProcess;
@@ -249,29 +383,41 @@ bool AndroidDeployStep::deployPackage()
SLOT(handleBuildError()));
if (m_runDeployAction == DeployLocal) {
- writeOutput(tr("Clean old Qt libraries"));
- runCommand(deployProc, AndroidConfigurations::instance().adbToolPath().toString(),
- QStringList() << QLatin1String("-s") << m_deviceSerialNumber
- << QLatin1String("shell") << QLatin1String("rm") << QLatin1String("-r") << QLatin1String("/data/local/qt"));
-
writeOutput(tr("Deploy Qt libraries. This may take some time, please wait."));
const QString tempPath = QDir::tempPath() + QLatin1String("/android_qt_libs_") + m_packageName;
AndroidPackageCreationStep::removeDirectory(tempPath);
- QStringList stripFiles;
- copyLibs(m_qtVersionSourcePath + QLatin1String("/lib"),
- tempPath + QLatin1String("/lib"), stripFiles, QStringList() << QLatin1String("*.so"));
- copyLibs(m_qtVersionSourcePath + QLatin1String("/plugins"),
- tempPath + QLatin1String("/plugins"), stripFiles);
- copyLibs(m_qtVersionSourcePath + QLatin1String("/imports"),
- tempPath + QLatin1String("/imports"), stripFiles);
- copyLibs(m_qtVersionSourcePath + QLatin1String("/jar"),
- tempPath + QLatin1String("/jar"), stripFiles);
- AndroidPackageCreationStep::stripAndroidLibs(stripFiles, target()->activeRunConfiguration()->abi().architecture());
- runCommand(deployProc, AndroidConfigurations::instance().adbToolPath().toString(),
- QStringList() << QLatin1String("-s") << m_deviceSerialNumber
- << QLatin1String("push") << tempPath << QLatin1String("/data/local/qt"));
+
+ const QString remoteRoot = QLatin1String("/data/local/tmp/qt");
+ QList<DeployItem> deployList;
+ collectFiles(&deployList,
+ m_qtVersionSourcePath + QLatin1String("/lib"),
+ remoteRoot + QLatin1String("/lib"),
+ true,
+ QStringList() << QLatin1String("*.so"));
+ collectFiles(&deployList,
+ m_qtVersionSourcePath + QLatin1String("/plugins"),
+ remoteRoot + QLatin1String("/plugins"),
+ true);
+ collectFiles(&deployList,
+ m_qtVersionSourcePath + QLatin1String("/imports"),
+ remoteRoot + QLatin1String("/imports"),
+ true);
+ collectFiles(&deployList,
+ m_qtVersionSourcePath + QLatin1String("/qml"),
+ remoteRoot + QLatin1String("/qml"),
+ true);
+ collectFiles(&deployList,
+ m_qtVersionSourcePath + QLatin1String("/jar"),
+ remoteRoot + QLatin1String("/jar"),
+ true);
+
+ fetchRemoteModificationTimes(&deployList);
+ filterModificationTimes(&deployList);
+ copyFilesToTemp(&deployList, tempPath, m_qtVersionSourcePath);
+ stripFiles(deployList, target()->activeRunConfiguration()->abi().architecture());
+ deployFiles(deployProc, deployList);
+
AndroidPackageCreationStep::removeDirectory(tempPath);
- emit (resetDelopyAction());
}
if (m_runDeployAction == InstallQASI) {
@@ -311,6 +457,10 @@ bool AndroidDeployStep::deployPackage()
<< QString::fromLatin1("%1/app_process").arg(m_buildDirectory));
runCommand(deployProc, AndroidConfigurations::instance().adbToolPath().toString(),
QStringList() << QLatin1String("-s") << m_deviceSerialNumber << QLatin1String("pull")
+ << QLatin1String("/system/bin/linker")
+ << QString::fromLatin1("%1/linker").arg(m_buildDirectory));
+ runCommand(deployProc, AndroidConfigurations::instance().adbToolPath().toString(),
+ QStringList() << QLatin1String("-s") << m_deviceSerialNumber << QLatin1String("pull")
<< QLatin1String("/system/lib/libc.so")
<< QString::fromLatin1("%1/libc.so").arg(m_buildDirectory));
disconnect(deployProc, 0, this, 0);
diff --git a/src/plugins/android/androiddeploystep.h b/src/plugins/android/androiddeploystep.h
index 82a4a3d58e..9b0e852649 100644
--- a/src/plugins/android/androiddeploystep.h
+++ b/src/plugins/android/androiddeploystep.h
@@ -47,6 +47,26 @@ namespace Internal {
class AndroidDeviceConfigListModel;
class AndroidPackageCreationStep;
+class DeployItem
+{
+public:
+ DeployItem(const QString &_localFileName,
+ unsigned int _localTimeStamp,
+ const QString &_remoteFileName,
+ bool _needsStrip)
+ : localFileName(_localFileName),
+ remoteFileName(_remoteFileName),
+ localTimeStamp(_localTimeStamp),
+ remoteTimeStamp(0),
+ needsStrip(_needsStrip)
+ {}
+ QString localFileName;
+ QString remoteFileName;
+ unsigned int localTimeStamp;
+ unsigned int remoteTimeStamp;
+ bool needsStrip;
+};
+
class AndroidDeployStep : public ProjectExplorer::BuildStep
{
Q_OBJECT
@@ -75,6 +95,8 @@ public:
bool fromMap(const QVariantMap &map);
QVariantMap toMap() const;
+ void cleanLibsOnDevice();
+
public slots:
void setDeployAction(AndroidDeployAction deploy);
void setDeployQASIPackagePath(const QString &package);
@@ -89,6 +111,7 @@ private slots:
bool deployPackage();
void handleBuildOutput();
void handleBuildError();
+ void cleanLibsFinished();
private:
AndroidDeployStep(ProjectExplorer::BuildStepList *bc,
@@ -98,11 +121,19 @@ private:
virtual ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
virtual bool immutable() const { return true; }
- void copyLibs(const QString &srcPath, const QString &destPath, QStringList &copiedLibs, const QStringList &filter = QStringList());
void ctor();
void raiseError(const QString &error);
void writeOutput(const QString &text, OutputFormat = MessageOutput);
bool runCommand(QProcess *buildProc, const QString &program, const QStringList &arguments);
+ unsigned int remoteModificationTime(const QString &fullDestination,
+ QHash<QString, unsigned int> *cache);
+ void collectFiles(QList<DeployItem> *deployList, const QString &localPath,
+ const QString &remotePath, bool strip, const QStringList &filter = QStringList());
+ void filterModificationTimes(QList<DeployItem> *deployList);
+ void copyFilesToTemp(QList<DeployItem> *deployList, const QString &tempDirectory, const QString &sourcePrefix);
+ void fetchRemoteModificationTimes(QList<DeployItem> *deployList);
+ void stripFiles(const QList<DeployItem> &deployList, ProjectExplorer::Abi::Architecture architecture);
+ void deployFiles(QProcess *process, const QList<DeployItem> &deployList);
private:
QString m_deviceSerialNumber;
diff --git a/src/plugins/android/androiddeploystepwidget.cpp b/src/plugins/android/androiddeploystepwidget.cpp
index 7612e9b339..6c8e351963 100644
--- a/src/plugins/android/androiddeploystepwidget.cpp
+++ b/src/plugins/android/androiddeploystepwidget.cpp
@@ -63,6 +63,7 @@ AndroidDeployStepWidget::AndroidDeployStepWidget(AndroidDeployStep *step) :
connect(ui->chooseButton, SIGNAL(clicked()), SLOT(setQASIPackagePath()));
connect(ui->useLocalQtLibs, SIGNAL(stateChanged(int)), SLOT(useLocalQtLibsStateChanged(int)));
connect(ui->editRulesFilePushButton, SIGNAL(clicked()), SLOT(editRulesFile()));
+ connect(ui->cleanLibsPushButton, SIGNAL(clicked()), SLOT(cleanLibsOnDevice()));
}
AndroidDeployStepWidget::~AndroidDeployStepWidget()
@@ -110,5 +111,10 @@ void AndroidDeployStepWidget::editRulesFile()
Core::ICore::instance()->openFiles(QStringList() << m_step->localLibsRulesFilePath().toString(), Core::ICore::SwitchMode);
}
+void AndroidDeployStepWidget::cleanLibsOnDevice()
+{
+ m_step->cleanLibsOnDevice();
+}
+
} // namespace Internal
} // namespace Qt4ProjectManager
diff --git a/src/plugins/android/androiddeploystepwidget.h b/src/plugins/android/androiddeploystepwidget.h
index b20f9efb89..01fa278c71 100644
--- a/src/plugins/android/androiddeploystepwidget.h
+++ b/src/plugins/android/androiddeploystepwidget.h
@@ -54,6 +54,7 @@ private slots:
void setQASIPackagePath();
void useLocalQtLibsStateChanged(int);
void editRulesFile();
+ void cleanLibsOnDevice();
private:
virtual QString summaryText() const;
diff --git a/src/plugins/android/androiddeploystepwidget.ui b/src/plugins/android/androiddeploystepwidget.ui
index dd7c51e784..3732f7a501 100644
--- a/src/plugins/android/androiddeploystepwidget.ui
+++ b/src/plugins/android/androiddeploystepwidget.ui
@@ -7,7 +7,7 @@
<x>0</x>
<y>0</y>
<width>560</width>
- <height>136</height>
+ <height>145</height>
</rect>
</property>
<property name="sizePolicy">
@@ -57,6 +57,13 @@ You must have Qt libraries compiled for that platform</string>
</widget>
</item>
<item>
+ <widget class="QPushButton" name="cleanLibsPushButton">
+ <property name="text">
+ <string>Clean libs on device</string>
+ </property>
+ </widget>
+ </item>
+ <item>
<widget class="QPushButton" name="editRulesFilePushButton">
<property name="text">
<string>Edit Rules File</string>
diff --git a/src/plugins/android/androidmanager.cpp b/src/plugins/android/androidmanager.cpp
index faa34ba740..cc2e41db2e 100644
--- a/src/plugins/android/androidmanager.cpp
+++ b/src/plugins/android/androidmanager.cpp
@@ -106,7 +106,7 @@ bool AndroidManager::setPackageName(ProjectExplorer::Target *target, const QStri
QString AndroidManager::applicationName(ProjectExplorer::Target *target)
{
QDomDocument doc;
- if (!openXmlFile(target, doc, stringsPath(target)))
+ if (!openXmlFile(doc, stringsPath(target)))
return QString();
QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("string"));
while (!metadataElem.isNull()) {
@@ -121,7 +121,7 @@ bool AndroidManager::setApplicationName(ProjectExplorer::Target *target, const Q
{
QDomDocument doc;
Utils::FileName path = stringsPath(target);
- if (!openXmlFile(target, doc, path))
+ if (!openXmlFile(doc, path))
return false;
QDomElement metadataElem = doc.documentElement().firstChildElement(QLatin1String("string"));
while (!metadataElem.isNull()) {
@@ -403,11 +403,11 @@ bool AndroidManager::createAndroidTemplatesIfNecessary(ProjectExplorer::Target *
QDomDocument srcVersionDoc;
Utils::FileName srcVersionPath = javaSrcPath;
srcVersionPath.appendPath(QLatin1String("version.xml"));
- if (openXmlFile(target, srcVersionDoc, srcVersionPath, false)) {
+ if (openXmlFile(srcVersionDoc, srcVersionPath)) {
QDomDocument dstVersionDoc;
Utils::FileName dstVersionPath=androidPath;
dstVersionPath.appendPath(QLatin1String("version.xml"));
- if (openXmlFile(target, dstVersionDoc, dstVersionPath, false))
+ if (openXmlFile(dstVersionDoc, dstVersionPath))
forceUpdate = (srcVersionDoc.documentElement().attribute(QLatin1String("value")).toDouble()
> dstVersionDoc.documentElement().attribute(QLatin1String("value")).toDouble());
else
@@ -570,6 +570,11 @@ QString AndroidManager::loadLocalJars(ProjectExplorer::Target *target, int apiLe
return loadLocal(target, apiLevel, Jar);
}
+QString AndroidManager::loadLocalJarsInitClasses(ProjectExplorer::Target *target, int apiLevel)
+{
+ return loadLocal(target, apiLevel, Jar, QLatin1String("initClass"));
+}
+
QStringList AndroidManager::availableQtLibs(ProjectExplorer::Target *target)
{
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
@@ -606,11 +611,10 @@ QStringList AndroidManager::availableQtLibs(ProjectExplorer::Target *target)
int it = 0;
while (it < mapLibs[key].dependencies.size()) {
const QString &dependName = mapLibs[key].dependencies[it];
- if (!mapLibs.keys().contains(dependName) && dependName.startsWith(QLatin1String("lib")) && dependName.endsWith(QLatin1String(".so"))) {
+ if (!mapLibs.keys().contains(dependName) && dependName.startsWith(QLatin1String("lib")) && dependName.endsWith(QLatin1String(".so")))
mapLibs[key].dependencies.removeAt(it);
- } else {
+ else
++it;
- }
}
if (!mapLibs[key].dependencies.size())
mapLibs[key].level = 0;
@@ -674,7 +678,7 @@ bool AndroidManager::setPrebundledLibs(ProjectExplorer::Target *target, const QS
bool AndroidManager::openLibsXml(ProjectExplorer::Target *target, QDomDocument &doc)
{
- return openXmlFile(target, doc, libsPath(target));
+ return openXmlFile(doc, libsPath(target));
}
bool AndroidManager::saveLibsXml(ProjectExplorer::Target *target, QDomDocument &doc)
@@ -687,7 +691,7 @@ void AndroidManager::raiseError(const QString &reason)
QMessageBox::critical(0, tr("Error creating Android templates"), reason);
}
-QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel, ItemType item)
+QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel, ItemType item, const QString &attribute)
{
QString itemType;
if (item == Lib)
@@ -698,7 +702,7 @@ QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel,
QString localLibs;
QDomDocument doc;
- if (!openXmlFile(target, doc, localLibsRulesFilePath(target)))
+ if (!openXmlFile(doc, localLibsRulesFilePath(target)))
return localLibs;
QStringList libs;
@@ -718,13 +722,15 @@ QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel,
if (libs.contains(element.attribute(QLatin1String("name")))) {
QDomElement libElement = element.firstChildElement(QLatin1String("depends")).firstChildElement(itemType);
while (!libElement.isNull()) {
- localLibs += libElement.attribute(QLatin1String("file")).arg(apiLevel) + QLatin1Char(':');
+ if (libElement.hasAttribute(attribute))
+ localLibs += libElement.attribute(attribute).arg(apiLevel) + QLatin1Char(':');
libElement = libElement.nextSiblingElement(itemType);
}
libElement = element.firstChildElement(QLatin1String("replaces")).firstChildElement(itemType);
while (!libElement.isNull()) {
- localLibs.replace(libElement.attribute(QLatin1String("file")).arg(apiLevel) + QLatin1Char(':'), QString());
+ if (libElement.hasAttribute(attribute))
+ localLibs.replace(libElement.attribute(attribute).arg(apiLevel) + QLatin1Char(':'), QString());
libElement = libElement.nextSiblingElement(itemType);
}
}
@@ -733,12 +739,8 @@ QString AndroidManager::loadLocal(ProjectExplorer::Target *target, int apiLevel,
return localLibs;
}
-bool AndroidManager::openXmlFile(ProjectExplorer::Target *target, QDomDocument &doc,
- const Utils::FileName &fileName, bool createAndroidTemplates)
+bool AndroidManager::openXmlFile(QDomDocument &doc, const Utils::FileName &fileName)
{
- if (createAndroidTemplates && !createAndroidTemplatesIfNecessary(target))
- return false;
-
QFile f(fileName.toString());
if (!f.open(QIODevice::ReadOnly))
return false;
@@ -765,7 +767,7 @@ bool AndroidManager::saveXmlFile(ProjectExplorer::Target *target, QDomDocument &
bool AndroidManager::openManifest(ProjectExplorer::Target *target, QDomDocument &doc)
{
- return openXmlFile(target, doc, manifestPath(target));
+ return openXmlFile(doc, manifestPath(target));
}
bool AndroidManager::saveManifest(ProjectExplorer::Target *target, QDomDocument &doc)
@@ -856,7 +858,7 @@ QStringList AndroidManager::dependencies(const Utils::FileName &readelfPath, con
readelfProc.start(readelfPath.toString(), QStringList() << QLatin1String("-d") << QLatin1String("-W") << lib);
if (!readelfProc.waitForFinished(-1)) {
- readelfProc.terminate();
+ readelfProc.kill();
return libs;
}
diff --git a/src/plugins/android/androidmanager.h b/src/plugins/android/androidmanager.h
index d24f06ce1c..56a703c652 100644
--- a/src/plugins/android/androidmanager.h
+++ b/src/plugins/android/androidmanager.h
@@ -102,6 +102,7 @@ public:
static Utils::FileName localLibsRulesFilePath(ProjectExplorer::Target *target);
static QString loadLocalLibs(ProjectExplorer::Target *target, int apiLevel);
static QString loadLocalJars(ProjectExplorer::Target *target, int apiLevel);
+ static QString loadLocalJarsInitClasses(ProjectExplorer::Target *target, int apiLevel);
static QStringList availableQtLibs(ProjectExplorer::Target *target);
static QStringList qtLibs(ProjectExplorer::Target *target);
@@ -113,8 +114,7 @@ public:
private:
static void raiseError(const QString &reason);
- static bool openXmlFile(ProjectExplorer::Target *target, QDomDocument &doc,
- const Utils::FileName &fileName, bool createAndroidTemplates = false);
+ static bool openXmlFile(QDomDocument &doc, const Utils::FileName &fileName);
static bool saveXmlFile(ProjectExplorer::Target *target, QDomDocument &doc, const Utils::FileName &fileName);
static bool openManifest(ProjectExplorer::Target *target, QDomDocument &doc);
static bool saveManifest(ProjectExplorer::Target *target, QDomDocument &doc);
@@ -128,7 +128,7 @@ private:
Lib,
Jar
};
- static QString loadLocal(ProjectExplorer::Target *target, int apiLevel, ItemType item);
+ static QString loadLocal(ProjectExplorer::Target *target, int apiLevel, ItemType item, const QString &attribute=QLatin1String("file"));
class Library
{
diff --git a/src/plugins/android/androidpackagecreationstep.cpp b/src/plugins/android/androidpackagecreationstep.cpp
index 3e3c3bf34c..6f2cd3e097 100644
--- a/src/plugins/android/androidpackagecreationstep.cpp
+++ b/src/plugins/android/androidpackagecreationstep.cpp
@@ -192,6 +192,21 @@ static inline QString msgCannotFindExecutable(const QString &appPath)
"built successfully and is selected in Application tab ('Run option').").arg(appPath);
}
+static void parseSharedLibs(const QByteArray &buffer, QStringList *libs)
+{
+#if defined(_WIN32)
+ QList<QByteArray> lines = buffer.trimmed().split('\r');
+#else
+ QList<QByteArray> lines = buffer.trimmed().split('\n');
+#endif
+ foreach (QByteArray line, lines) {
+ if (line.contains("(NEEDED)") && line.contains("Shared library:") ) {
+ const int pos = line.lastIndexOf('[') + 1;
+ (*libs) << QString::fromLatin1(line.mid(pos, line.length() - pos - 1));
+ }
+ }
+}
+
void AndroidPackageCreationStep::checkRequiredLibraries()
{
QProcess readelfProc;
@@ -203,17 +218,11 @@ void AndroidPackageCreationStep::checkRequiredLibraries()
readelfProc.start(AndroidConfigurations::instance().readelfPath(target()->activeRunConfiguration()->abi().architecture()).toString(),
QStringList() << QLatin1String("-d") << QLatin1String("-W") << appPath);
if (!readelfProc.waitForFinished(-1)) {
- readelfProc.terminate();
+ readelfProc.kill();
return;
}
QStringList libs;
- QList<QByteArray> lines = readelfProc.readAll().trimmed().split('\n');
- foreach (const QByteArray &line, lines) {
- if (line.contains("(NEEDED)") && line.contains("Shared library:") ) {
- const int pos = line.lastIndexOf('[') + 1;
- libs << QString::fromLatin1(line.mid(pos, line.length() - pos - 1));
- }
- }
+ parseSharedLibs(readelfProc.readAll(), &libs);
QStringList checkedLibs = AndroidManager::qtLibs(target());
QStringList requiredLibraries;
foreach (const QString &qtLib, AndroidManager::availableQtLibs(target())) {
@@ -250,18 +259,11 @@ void AndroidPackageCreationStep::checkRequiredLibrariesForRun()
}
readelfProc.start(m_readElf.toString(), QStringList() << QLatin1String("-d") << QLatin1String("-W") << m_appPath.toUserOutput());
if (!readelfProc.waitForFinished(-1)) {
- readelfProc.terminate();
+ readelfProc.kill();
return;
}
QStringList libs;
- QList<QByteArray> lines = readelfProc.readAll().trimmed().split('\n');
- foreach (const QByteArray &line, lines) {
- if (line.contains("(NEEDED)") && line.contains("Shared library:") ) {
- const int pos = line.lastIndexOf('[') + 1;
- libs << QString::fromLatin1(line.mid(pos, line.length() - pos - 1));
- }
- }
-
+ parseSharedLibs(readelfProc.readAll(), &libs);
QStringList requiredLibraries;
foreach (const QString &qtLib, m_availableQtLibs) {
if (libs.contains(QLatin1String("lib") + qtLib + QLatin1String(".so")) || m_qtLibs.contains(qtLib))
@@ -467,7 +469,7 @@ void AndroidPackageCreationStep::stripAndroidLibs(const QStringList & files, Abi
QStringList()<<QLatin1String("--strip-unneeded") << file);
stripProcess.waitForStarted();
if (!stripProcess.waitForFinished())
- stripProcess.terminate();
+ stripProcess.kill();
}
}
diff --git a/src/plugins/android/androidpackagecreationstep.h b/src/plugins/android/androidpackagecreationstep.h
index 064d06479e..512c028a43 100644
--- a/src/plugins/android/androidpackagecreationstep.h
+++ b/src/plugins/android/androidpackagecreationstep.h
@@ -41,10 +41,6 @@ QT_BEGIN_NAMESPACE
class QProcess;
QT_END_NAMESPACE
-namespace Qt4ProjectManager {
-class Qt4BuildConfiguration;
-}
-
namespace Android {
namespace Internal {
diff --git a/src/plugins/android/androidpackagecreationwidget.cpp b/src/plugins/android/androidpackagecreationwidget.cpp
index 30f0059624..a22172b57c 100644
--- a/src/plugins/android/androidpackagecreationwidget.cpp
+++ b/src/plugins/android/androidpackagecreationwidget.cpp
@@ -147,8 +147,9 @@ PermissionsModel::PermissionsModel(QObject *parent)
void PermissionsModel::setPermissions(const QStringList &permissions)
{
+ beginResetModel();
m_permissions = permissions;
- reset();
+ endResetModel();
}
const QStringList &PermissionsModel::permissions()
@@ -259,6 +260,15 @@ void AndroidPackageCreationWidget::initGui()
m_ui->prebundledLibsListView->setModel(m_prebundledLibs);
m_ui->permissionsListView->setModel(m_permissionsModel);
m_ui->KeystoreLocationLineEdit->setText(m_step->keystorePath().toUserOutput());
+
+ // Make the buildconfiguration emit a evironmentChanged() signal
+ // TODO find a better way
+ Qt4BuildConfiguration *bc = qobject_cast<Qt4BuildConfiguration *>(m_step->target()->activeBuildConfiguration());
+ if (!bc)
+ return;
+ bool use = bc->useSystemEnvironment();
+ bc->setUseSystemEnvironment(!use);
+ bc->setUseSystemEnvironment(use);
}
void AndroidPackageCreationWidget::updateAndroidProjectInfo()
diff --git a/src/plugins/android/androidqtversion.cpp b/src/plugins/android/androidqtversion.cpp
index 10117fec4e..9dd177da2c 100644
--- a/src/plugins/android/androidqtversion.cpp
+++ b/src/plugins/android/androidqtversion.cpp
@@ -29,11 +29,24 @@
#include "androidqtversion.h"
#include "androidconstants.h"
-#include "qt4projectmanager/qt4projectmanagerconstants.h"
+#include "androidconfigurations.h"
+#include "androidmanager.h"
+#include <utils/environment.h>
+
+#include <qt4projectmanager/qt4project.h>
+#include <qt4projectmanager/qt4projectmanagerconstants.h>
+
+#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
+#include <qtsupport/qtversionmanager.h>
+
+#include <projectexplorer/kit.h>
+#include <projectexplorer/projectexplorer.h>
using namespace Android::Internal;
+using namespace ProjectExplorer;
+using namespace Qt4ProjectManager;
AndroidQtVersion::AndroidQtVersion()
: QtSupport::BaseQtVersion()
@@ -43,6 +56,7 @@ AndroidQtVersion::AndroidQtVersion()
AndroidQtVersion::AndroidQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource)
: QtSupport::BaseQtVersion(path, isAutodetected, autodetectionSource)
{
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
}
AndroidQtVersion *AndroidQtVersion::clone() const
@@ -79,6 +93,31 @@ QList<ProjectExplorer::Abi> AndroidQtVersion::detectQtAbis() const
32);
}
+void AndroidQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const
+{
+ QString ndk_host = QLatin1String(
+#if defined(Q_OS_LINUX)
+ "linux-x86"
+#elif defined(Q_OS_WIN)
+ "windows"
+#elif defined(Q_OS_MAC)
+ "darwin-x86"
+#endif
+ );
+
+ // this env vars are used by qmake mkspecs to generate makefiles (check QTDIR/mkspecs/android-g++/qmake.conf for more info)
+ env.set(QLatin1String("ANDROID_NDK_HOST"), ndk_host);
+ env.set(QLatin1String("ANDROID_NDK_ROOT"), AndroidConfigurations::instance().config().ndkLocation.toUserOutput());
+
+ Qt4Project *qt4pro = qobject_cast<Qt4ProjectManager::Qt4Project *>(ProjectExplorerPlugin::instance()->currentProject());
+ if (!qt4pro || !qt4pro->activeTarget()
+ || QtSupport::QtKitInformation::qtVersion(k)->type() != QLatin1String(Constants::ANDROIDQT))
+ return;
+ env.set(QLatin1String("ANDROID_NDK_PLATFORM"),
+ AndroidConfigurations::instance().bestMatch(AndroidManager::targetSDK(qt4pro->activeTarget())));
+
+}
+
QString AndroidQtVersion::description() const
{
//: Qt Version is meant for Android
diff --git a/src/plugins/android/androidqtversion.h b/src/plugins/android/androidqtversion.h
index e61da63982..a29235d8c0 100644
--- a/src/plugins/android/androidqtversion.h
+++ b/src/plugins/android/androidqtversion.h
@@ -52,6 +52,8 @@ public:
QList<ProjectExplorer::Abi> detectQtAbis() const;
+ void addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const;
+
Core::FeatureSet availableFeatures() const;
QString platformName() const;
QString platformDisplayName() const;
diff --git a/src/plugins/android/androidruncontrol.cpp b/src/plugins/android/androidruncontrol.cpp
index ffdbf1b0b8..aa9e07cc4e 100644
--- a/src/plugins/android/androidruncontrol.cpp
+++ b/src/plugins/android/androidruncontrol.cpp
@@ -71,7 +71,7 @@ void AndroidRunControl::start()
RunControl::StopResult AndroidRunControl::stop()
{
- m_runner->stop(true);
+ m_runner->stop();
return StoppedSynchronously;
}
diff --git a/src/plugins/android/androidrunner.cpp b/src/plugins/android/androidrunner.cpp
index 0ce88fb284..02373108f3 100644
--- a/src/plugins/android/androidrunner.cpp
+++ b/src/plugins/android/androidrunner.cpp
@@ -55,6 +55,7 @@ AndroidRunner::AndroidRunner(QObject *parent, AndroidRunConfiguration *runConfig
if ((m_useLocalQtLibs = ds->useLocalQtLibs())) {
m_localLibs = AndroidManager::loadLocalLibs(target, ds->deviceAPILevel());
m_localJars = AndroidManager::loadLocalJars(target, ds->deviceAPILevel());
+ m_localJarsInitClasses = AndroidManager::loadLocalJarsInitClasses(target, ds->deviceAPILevel());
}
m_intentName = AndroidManager::intentName(target);
m_packageName = m_intentName.left(m_intentName.indexOf(QLatin1Char('/')));
@@ -68,25 +69,42 @@ AndroidRunner::AndroidRunner(QObject *parent, AndroidRunConfiguration *runConfig
AndroidRunner::~AndroidRunner()
{
- stop(false);
+ stop();
}
void AndroidRunner::checkPID()
{
QProcess psProc;
+ QLatin1String psCmd = QLatin1String("ps");
+ QLatin1String psPidRx = QLatin1String("\\d+\\s+(\\d+)");
+
+ // Detect busybox, as we need to pass -w to it to get wide output.
+ psProc.start(AndroidConfigurations::instance().adbToolPath().toString(),
+ QStringList() << QLatin1String("-s") << m_deviceSerialNumber
+ << QLatin1String("shell") << QLatin1String("readlink") << QLatin1String("$(which ps)"));
+ if (!psProc.waitForFinished(-1)) {
+ psProc.kill();
+ return;
+ }
+ QByteArray which = psProc.readAll();
+ if (which.startsWith("busybox")) {
+ psCmd = QLatin1String("ps -w");
+ psPidRx = QLatin1String("(\\d+)");
+ }
+
psProc.start(AndroidConfigurations::instance().adbToolPath().toString(),
QStringList() << QLatin1String("-s") << m_deviceSerialNumber
- << QLatin1String("shell") << QLatin1String("ps"));
+ << QLatin1String("shell") << psCmd);
if (!psProc.waitForFinished(-1)) {
- psProc.terminate();
+ psProc.kill();
return;
}
+ QRegExp rx(psPidRx);
qint64 pid = -1;
QList<QByteArray> procs = psProc.readAll().split('\n');
foreach (const QByteArray &proc, procs) {
- if (proc.trimmed().endsWith(m_packageName.toAscii())) {
- QRegExp rx(QLatin1String("(\\d+)"));
- if (rx.indexIn(QLatin1String(proc), proc.indexOf(' ')) > 0) {
+ if (proc.trimmed().endsWith(m_packageName.toLatin1())) {
+ if (rx.indexIn(QLatin1String(proc)) > -1) {
pid = rx.cap(1).toLongLong();
break;
}
@@ -105,8 +123,7 @@ void AndroidRunner::checkPID()
m_gdbserverPID = -1;
foreach (const QByteArray &proc, procs) {
if (proc.trimmed().endsWith("gdbserver")) {
- QRegExp rx(QLatin1String("(\\d+)"));
- if (rx.indexIn(QLatin1String(proc), proc.indexOf(' ')) > 0) {
+ if (rx.indexIn(QLatin1String(proc)) > -1) {
m_gdbserverPID = rx.cap(1).toLongLong();
break;
}
@@ -179,9 +196,11 @@ void AndroidRunner::asyncStart()
if (m_useLocalQtLibs) {
extraParams += QLatin1String(" -e use_local_qt_libs true");
- extraParams += QLatin1String(" -e libs_prefix /data/local/qt/");
+ extraParams += QLatin1String(" -e libs_prefix /data/local/tmp/qt/");
extraParams += QLatin1String(" -e load_local_libs ") + m_localLibs;
extraParams += QLatin1String(" -e load_local_jars ") + m_localJars;
+ if (!m_localJarsInitClasses.isEmpty())
+ extraParams += QLatin1String(" -e static_init_classes ") + m_localJarsInitClasses;
}
extraParams = extraParams.trimmed();
@@ -232,23 +251,17 @@ void AndroidRunner::startLogcat()
emit remoteProcessStarted(5039);
}
-void AndroidRunner::stop(bool async)
+void AndroidRunner::stop()
{
QMutexLocker locker(&m_mutex);
- m_adbLogcatProcess.terminate();
- m_adbLogcatProcess.waitForFinished(-1);
m_checkPIDTimer.stop();
- if (m_processPID == -1)
+ if (m_processPID == -1) {
+ m_adbLogcatProcess.kill();
return; // don't emit another signal
- if (async)
- QtConcurrent::run(this, &AndroidRunner::asyncStop);
- else
- asyncStop();
-}
-void AndroidRunner::asyncStop()
-{
+ }
killPID();
- emit remoteProcessFinished(tr("\n\n'%1' killed.").arg(m_packageName));
+ m_adbLogcatProcess.kill();
+ m_adbLogcatProcess.waitForFinished(-1);
}
void AndroidRunner::logcatReadStandardError()
@@ -261,7 +274,7 @@ void AndroidRunner::logcatReadStandardOutput()
m_logcat += m_adbLogcatProcess.readAllStandardOutput();
bool keepLastLine = m_logcat.endsWith('\n');
QByteArray line;
- QByteArray pid(QString::fromLatin1("%1):").arg(m_processPID).toAscii());
+ QByteArray pid(QString::fromLatin1("%1):").arg(m_processPID).toLatin1());
foreach (line, m_logcat.split('\n')) {
if (!line.contains(pid))
continue;
@@ -292,7 +305,7 @@ void AndroidRunner::adbKill(qint64 pid, const QString &device, int timeout, cons
process.start(AndroidConfigurations::instance().adbToolPath().toString(), arguments);
if (!process.waitForFinished(timeout))
- process.terminate();
+ process.kill();
}
QString AndroidRunner::displayName() const
diff --git a/src/plugins/android/androidrunner.h b/src/plugins/android/androidrunner.h
index 34537c98c4..9bb654dd8b 100644
--- a/src/plugins/android/androidrunner.h
+++ b/src/plugins/android/androidrunner.h
@@ -55,7 +55,7 @@ public:
public slots:
void start();
- void stop(bool async);
+ void stop();
signals:
void remoteProcessStarted(int gdbServerPort = -1, int qmlPort = -1);
@@ -71,7 +71,6 @@ private slots:
void logcatReadStandardOutput();
void startLogcat();
void asyncStart();
- void asyncStop();
private:
void adbKill(qint64 pid, const QString &device, int timeout = 2000, const QString &runAsPackageName = QString());
@@ -92,6 +91,7 @@ private:
bool m_useLocalQtLibs;
QString m_localLibs;
QString m_localJars;
+ QString m_localJarsInitClasses;
QMutex m_mutex;
};
diff --git a/src/plugins/android/androidsettingspage.cpp b/src/plugins/android/androidsettingspage.cpp
index 0db3afbf9d..f4f8362df4 100644
--- a/src/plugins/android/androidsettingspage.cpp
+++ b/src/plugins/android/androidsettingspage.cpp
@@ -40,9 +40,9 @@ namespace Internal {
AndroidSettingsPage::AndroidSettingsPage(QObject *parent)
: Core::IOptionsPage(parent)
{
- setId(QLatin1String(Constants::ANDROID_SETTINGS_ID));
+ setId(Constants::ANDROID_SETTINGS_ID);
setDisplayName(tr("Android Configurations"));
- setCategory(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY));
+ setCategory(Constants::ANDROID_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Android",
Constants::ANDROID_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON));
diff --git a/src/plugins/android/androidsettingswidget.cpp b/src/plugins/android/androidsettingswidget.cpp
index b0694ff22a..9348a2f608 100644
--- a/src/plugins/android/androidsettingswidget.cpp
+++ b/src/plugins/android/androidsettingswidget.cpp
@@ -35,6 +35,8 @@
#include "androidconstants.h"
+#include <utils/hostosinfo.h>
+
#include <QFile>
#include <QTextStream>
#include <QProcess>
@@ -48,8 +50,9 @@ namespace Internal {
void AvdModel::setAvdList(const QVector<AndroidDeviceInfo> &list)
{
+ beginResetModel();
m_list = list;
- reset();
+ endResetModel();
}
QString AvdModel::avdName(const QModelIndex &index)
@@ -187,10 +190,10 @@ bool AndroidSettingsWidget::checkSDK(const Utils::FileName &location)
Utils::FileName androidExe = location;
Utils::FileName androidBat = location;
Utils::FileName emulator = location;
- if (!adb.appendPath(QLatin1String("platform-tools/adb" ANDROID_EXE_SUFFIX)).toFileInfo().exists()
- || (!androidExe.appendPath(QLatin1String("/tools/android" ANDROID_EXE_SUFFIX)).toFileInfo().exists()
+ if (!adb.appendPath(QLatin1String("platform-tools/adb" QTC_HOST_EXE_SUFFIX)).toFileInfo().exists()
+ || (!androidExe.appendPath(QLatin1String("/tools/android" QTC_HOST_EXE_SUFFIX)).toFileInfo().exists()
&& !androidBat.appendPath(QLatin1String("/tools/android" ANDROID_BAT_SUFFIX)).toFileInfo().exists())
- || !emulator.appendPath(QLatin1String("/tools/emulator" ANDROID_EXE_SUFFIX)).toFileInfo().exists()) {
+ || !emulator.appendPath(QLatin1String("/tools/emulator" QTC_HOST_EXE_SUFFIX)).toFileInfo().exists()) {
QMessageBox::critical(this, tr("Android SDK Folder"), tr("\"%1\" does not seem to be an Android SDK top folder.").arg(location.toUserOutput()));
return false;
}
@@ -212,7 +215,7 @@ bool AndroidSettingsWidget::checkNDK(const Utils::FileName &location)
if (!platformPath.appendPath(QLatin1String("platforms")).toFileInfo().exists()
|| !toolChainPath.appendPath(QLatin1String("toolchains")).toFileInfo().exists()
|| !sourcesPath.appendPath(QLatin1String("sources/cxx-stl")).toFileInfo().exists()) {
- QMessageBox::critical(this, tr("Android SDK Folder"), tr("\"%1\" does not seem to be an Android NDK top folder.").arg(location.toUserOutput()));
+ QMessageBox::critical(this, tr("Android NDK Folder"), tr("\"%1\" does not seem to be an Android NDK top folder.").arg(location.toUserOutput()));
return false;
}
m_androidConfig.ndkLocation = location;
@@ -335,16 +338,15 @@ void AndroidSettingsWidget::browseNDKLocation()
void AndroidSettingsWidget::browseAntLocation()
{
- QString dir = QDir::homePath();
-#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
- dir = QLatin1String("/usr/bin/ant");
- QLatin1String antApp("ant");
-#elif defined(Q_OS_WIN)
- QLatin1String antApp("ant.bat");
-#elif defined(Q_OS_DARWIN)
- dir = QLatin1String("/opt/local/bin/ant");
- QLatin1String antApp("ant");
-#endif
+ QString dir;
+ QString antApp;
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ dir = QDir::homePath();
+ antApp = QLatin1String("ant.bat");
+ } else {
+ dir = QLatin1String("/usr/bin/ant");
+ antApp = QLatin1String("ant");
+ }
const QString file =
QFileDialog::getOpenFileName(this, tr("Select ant Script"), dir, antApp);
if (!file.length())
diff --git a/src/plugins/android/androidtoolchain.cpp b/src/plugins/android/androidtoolchain.cpp
index fde3f8f5bf..ae0657c9a4 100644
--- a/src/plugins/android/androidtoolchain.cpp
+++ b/src/plugins/android/androidtoolchain.cpp
@@ -30,17 +30,19 @@
#include "androidtoolchain.h"
#include "androidconstants.h"
#include "androidconfigurations.h"
-#include "androidmanager.h"
#include "androidqtversion.h"
+
+#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/qtversionmanager.h>
+
#include <projectexplorer/target.h>
#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/projectexplorer.h>
-#include <qt4projectmanager/qt4project.h>
#include <qtsupport/qtkitinformation.h>
-#include <qtsupport/qtversionmanager.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QFormLayout>
@@ -51,7 +53,7 @@ namespace Android {
namespace Internal {
using namespace ProjectExplorer;
-using namespace Qt4ProjectManager;
+using namespace Utils;
static const char ANDROID_QT_VERSION_KEY[] = "Qt4ProjectManager.Android.QtVersion";
@@ -84,35 +86,30 @@ bool AndroidToolChain::isValid() const
return GccToolChain::isValid() && m_qtVersionId >= 0 && targetAbi().isValid();
}
-void AndroidToolChain::addToEnvironment(Utils::Environment &env) const
+void AndroidToolChain::addToEnvironment(Environment &env) const
{
// TODO this vars should be configurable in projects -> build tab
// TODO invalidate all .pro files !!!
- Qt4Project *qt4pro = qobject_cast<Qt4Project *>(ProjectExplorerPlugin::instance()->currentProject());
- if (!qt4pro || !qt4pro->activeTarget()
- || QtSupport::QtKitInformation::qtVersion(qt4pro->activeTarget()->kit())->type() != QLatin1String(Constants::ANDROIDQT))
- return;
-
- QString ndk_host = QLatin1String(
-#if defined(Q_OS_LINUX)
- "linux-x86"
-#elif defined(Q_OS_WIN)
- "windows"
-#elif defined(Q_OS_MAC)
- "darwin-x86"
-#endif
- );
-
- // this env vars are used by qmake mkspecs to generate makefiles (check QTDIR/mkspecs/android-g++/qmake.conf for more info)
- env.set(QLatin1String("ANDROID_NDK_HOST"), ndk_host);
- env.set(QLatin1String("ANDROID_NDK_ROOT"), AndroidConfigurations::instance().config().ndkLocation.toUserOutput());
+ QString ndkHost;
+ switch (HostOsInfo::hostOs()) {
+ case HostOsInfo::HostOsLinux:
+ ndkHost = QLatin1String("linux-x86");
+ break;
+ case HostOsInfo::HostOsWindows:
+ ndkHost = QLatin1String("windows");
+ break;
+ case HostOsInfo::HostOsMac:
+ ndkHost = QLatin1String("darwin-x86");
+ break;
+ default:
+ break;
+ }
+ env.set(QLatin1String("ANDROID_NDK_HOST"), ndkHost);
env.set(QLatin1String("ANDROID_NDK_TOOLCHAIN_PREFIX"), AndroidConfigurations::toolchainPrefix(targetAbi().architecture()));
env.set(QLatin1String("ANDROID_NDK_TOOLS_PREFIX"), AndroidConfigurations::toolsPrefix(targetAbi().architecture()));
env.set(QLatin1String("ANDROID_NDK_TOOLCHAIN_VERSION"), AndroidConfigurations::instance().config().ndkToolchainVersion);
- env.set(QLatin1String("ANDROID_NDK_PLATFORM"),
- AndroidConfigurations::instance().bestMatch(AndroidManager::targetSDK(qt4pro->activeTarget())));
}
bool AndroidToolChain::operator ==(const ToolChain &tc) const
@@ -146,18 +143,15 @@ bool AndroidToolChain::fromMap(const QVariantMap &data)
return isValid();
}
-QList<Utils::FileName> AndroidToolChain::suggestedMkspecList() const
+QList<FileName> AndroidToolChain::suggestedMkspecList() const
{
- return QList<Utils::FileName>()<< Utils::FileName::fromString(QLatin1String("android-g++"));
+ return QList<FileName>()<< FileName::fromString(QLatin1String("android-g++"));
}
QString AndroidToolChain::makeCommand(const Utils::Environment &env) const
{
-#if defined(Q_OS_WIN)
- QString make = QLatin1String("ma-make.exe");
-#else
- QString make = QLatin1String("make");
-#endif
+ QString make = HostOsInfo::isWindowsHost()
+ ? QLatin1String("ma-make.exe") : QLatin1String("make");
QString tmp = env.searchInPath(make);
return tmp.isEmpty() ? make : tmp;
}
diff --git a/src/plugins/android/androidtoolchain.h b/src/plugins/android/androidtoolchain.h
index 464e47ee10..18e573e7b3 100644
--- a/src/plugins/android/androidtoolchain.h
+++ b/src/plugins/android/androidtoolchain.h
@@ -55,7 +55,7 @@ public:
QVariantMap toMap() const;
bool fromMap(const QVariantMap &data);
QList<Utils::FileName> suggestedMkspecList() const;
- QString makeCommand(const Utils::Environment &env) const;
+ QString makeCommand(const Utils::Environment &environment) const;
void setQtVersionId(int);
int qtVersionId() const;
diff --git a/src/plugins/android/images/QtAndroid.png b/src/plugins/android/images/QtAndroid.png
index 85047515a0..0e79b184fc 100644
--- a/src/plugins/android/images/QtAndroid.png
+++ b/src/plugins/android/images/QtAndroid.png
Binary files differ
diff --git a/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in b/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in
index d11f96b270..8d00f182a0 100644
--- a/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in
+++ b/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.pluginspec.in
@@ -1,17 +1,15 @@
<plugin name=\"AutotoolsProjectManager\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"true\">
<vendor>Openismus GmbH</vendor>
<copyright>(C) 2013 Openismus GmbH</copyright>
- <license>GNU Lesser General Public License Usage
- This file may be used under the terms of the GNU Lesser General Public
- License version 2.1 as published by the Free Software Foundation and
- appearing in the file LICENSE.LGPL included in the packaging of this file.
- Please review the following information to ensure the GNU Lesser General
- Public License version 2.1 requirements will be met:
- http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+ <license>
+Commercial Usage
- In addition, as a special exception, Digia gives you certain additional
- rights. These rights are described in the Digia Qt LGPL Exception
- version 1.1, included in the file LGPL_EXCEPTION.txt in this package.</license>
+Licensees holding valid Qt Commercial licenses may use this plugin in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Digia.
+
+GNU Lesser General Public License Usage
+
+Alternatively, this plugin may be used under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. Please review the following information to ensure the GNU Lesser General Public License version 2.1 requirements will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+ </license>
<category>Build Systems</category>
<description>Autotools project integration.</description>
<url>http://www.qt-project.org</url>
diff --git a/src/plugins/autotoolsprojectmanager/autogenstep.cpp b/src/plugins/autotoolsprojectmanager/autogenstep.cpp
index 6414d4c3c7..6dc35f1d12 100644
--- a/src/plugins/autotoolsprojectmanager/autogenstep.cpp
+++ b/src/plugins/autotoolsprojectmanager/autogenstep.cpp
@@ -151,14 +151,9 @@ void AutogenStep::ctor()
setDefaultDisplayName(tr("Autogen"));
}
-AutotoolsBuildConfiguration *AutogenStep::autotoolsBuildConfiguration() const
-{
- return static_cast<AutotoolsBuildConfiguration *>(buildConfiguration());
-}
-
bool AutogenStep::init()
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
@@ -166,13 +161,14 @@ bool AutogenStep::init()
pp->setWorkingDirectory(bc->buildDirectory());
pp->setCommand(QLatin1String("autogen.sh"));
pp->setArguments(additionalArguments());
+ pp->resolveAll();
return AbstractProcessStep::init();
}
void AutogenStep::run(QFutureInterface<bool> &interface)
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
// Check whether we need to run autogen.sh
const QFileInfo configureInfo(bc->buildDirectory() + QLatin1String("/configure"));
@@ -273,7 +269,7 @@ QString AutogenStepConfigWidget::summaryText() const
void AutogenStepConfigWidget::updateDetails()
{
- AutotoolsBuildConfiguration *bc = m_autogenStep->autotoolsBuildConfiguration();
+ BuildConfiguration *bc = m_autogenStep->buildConfiguration();
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
diff --git a/src/plugins/autotoolsprojectmanager/autogenstep.h b/src/plugins/autotoolsprojectmanager/autogenstep.h
index 5c0cc54674..7efddb5b2b 100644
--- a/src/plugins/autotoolsprojectmanager/autogenstep.h
+++ b/src/plugins/autotoolsprojectmanager/autogenstep.h
@@ -42,7 +42,6 @@ namespace AutotoolsProjectManager {
namespace Internal {
class AutotoolsProject;
-class AutotoolsBuildConfiguration;
class AutogenStep;
class AutogenStepConfigWidget;
@@ -96,7 +95,6 @@ class AutogenStep : public ProjectExplorer::AbstractProcessStep
public:
AutogenStep(ProjectExplorer::BuildStepList *bsl);
- AutotoolsBuildConfiguration *autotoolsBuildConfiguration() const;
bool init();
void run(QFutureInterface<bool> &interface);
ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
diff --git a/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp b/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp
index 37023df8f1..d073452baa 100644
--- a/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp
+++ b/src/plugins/autotoolsprojectmanager/autoreconfstep.cpp
@@ -150,14 +150,9 @@ void AutoreconfStep::ctor()
setDefaultDisplayName(tr("Autoreconf"));
}
-AutotoolsBuildConfiguration *AutoreconfStep::autotoolsBuildConfiguration() const
-{
- return static_cast<AutotoolsBuildConfiguration *>(buildConfiguration());
-}
-
bool AutoreconfStep::init()
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
@@ -165,13 +160,14 @@ bool AutoreconfStep::init()
pp->setWorkingDirectory(bc->buildDirectory());
pp->setCommand(QLatin1String("autoreconf"));
pp->setArguments(additionalArguments());
+ pp->resolveAll();
return AbstractProcessStep::init();
}
void AutoreconfStep::run(QFutureInterface<bool> &interface)
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
// Check whether we need to run autoreconf
const QFileInfo configureInfo(bc->buildDirectory() + QLatin1String("/configure"));
@@ -267,7 +263,7 @@ QString AutoreconfStepConfigWidget::summaryText() const
void AutoreconfStepConfigWidget::updateDetails()
{
- AutotoolsBuildConfiguration *bc = m_autoreconfStep->autotoolsBuildConfiguration();
+ BuildConfiguration *bc = m_autoreconfStep->buildConfiguration();
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
diff --git a/src/plugins/autotoolsprojectmanager/autoreconfstep.h b/src/plugins/autotoolsprojectmanager/autoreconfstep.h
index 922f11d616..232fa8b6ec 100644
--- a/src/plugins/autotoolsprojectmanager/autoreconfstep.h
+++ b/src/plugins/autotoolsprojectmanager/autoreconfstep.h
@@ -42,7 +42,6 @@ namespace AutotoolsProjectManager {
namespace Internal {
class AutotoolsProject;
-class AutotoolsBuildConfiguration;
class AutoreconfStep;
////////////////////////////////
@@ -96,7 +95,6 @@ class AutoreconfStep : public ProjectExplorer::AbstractProcessStep
public:
AutoreconfStep(ProjectExplorer::BuildStepList *bsl);
- AutotoolsBuildConfiguration *autotoolsBuildConfiguration() const;
bool init();
void run(QFutureInterface<bool> &interface);
ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
index bb33584da6..bf07d5c593 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp
@@ -65,9 +65,9 @@ AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target
m_buildDirectory = project->defaultBuildDirectory();
}
-BuildConfigWidget *AutotoolsBuildConfiguration::createConfigWidget()
+NamedWidget *AutotoolsBuildConfiguration::createConfigWidget()
{
- return new AutotoolsBuildSettingsWidget;
+ return new AutotoolsBuildSettingsWidget(this);
}
AutotoolsBuildConfiguration::AutotoolsBuildConfiguration(ProjectExplorer::Target *parent, const Core::Id id)
@@ -112,14 +112,6 @@ void AutotoolsBuildConfiguration::setBuildDirectory(const QString &buildDirector
emit buildDirectoryChanged();
}
-IOutputParser *AutotoolsBuildConfiguration::createOutputParser() const
-{
- ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(target()->kit());
- if (tc)
- return tc->outputParser();
- return 0;
-}
-
//////////////////////////////////////
// AutotoolsBuildConfiguration class
//////////////////////////////////////
@@ -158,7 +150,7 @@ AutotoolsBuildConfiguration *AutotoolsBuildConfigurationFactory::create(Target *
bool ok = true;
QString buildConfigurationName = name;
- if (buildConfigurationName.isEmpty())
+ if (buildConfigurationName.isNull())
buildConfigurationName = QInputDialog::getText(0,
tr("New Configuration"),
tr("New configuration name:"),
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h
index 38c1d354d4..639efc305d 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.h
@@ -48,12 +48,11 @@ class AutotoolsBuildConfiguration : public ProjectExplorer::BuildConfiguration
public:
explicit AutotoolsBuildConfiguration(ProjectExplorer::Target *parent);
- ProjectExplorer::BuildConfigWidget *createConfigWidget();
+ ProjectExplorer::NamedWidget *createConfigWidget();
QString buildDirectory() const;
void setBuildDirectory(const QString &buildDirectory);
QVariantMap toMap() const;
- ProjectExplorer::IOutputParser *createOutputParser() const;
BuildType buildType() const;
protected:
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
index fe142a3201..e55079283b 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.cpp
@@ -49,8 +49,8 @@ using namespace AutotoolsProjectManager;
using namespace AutotoolsProjectManager::Internal;
using namespace ProjectExplorer;
-AutotoolsBuildSettingsWidget::AutotoolsBuildSettingsWidget() :
- m_buildConfiguration(0)
+AutotoolsBuildSettingsWidget::AutotoolsBuildSettingsWidget(AutotoolsBuildConfiguration *bc) :
+ m_buildConfiguration(bc)
{
QFormLayout *fl = new QFormLayout(this);
fl->setContentsMargins(0, 0, 0, 0);
@@ -61,18 +61,10 @@ AutotoolsBuildSettingsWidget::AutotoolsBuildSettingsWidget() :
m_pathChooser->setExpectedKind(Utils::PathChooser::Directory);
fl->addRow(tr("Build directory:"), m_pathChooser);
connect(m_pathChooser, SIGNAL(changed(QString)), this, SLOT(buildDirectoryChanged()));
-}
-QString AutotoolsBuildSettingsWidget::displayName() const
-{
- return QLatin1String("Autotools Manager");
-}
-
-void AutotoolsBuildSettingsWidget::init(BuildConfiguration *bc)
-{
- m_buildConfiguration = static_cast<AutotoolsBuildConfiguration *>(bc);
m_pathChooser->setBaseDirectory(bc->target()->project()->projectDirectory());
m_pathChooser->setPath(m_buildConfiguration->buildDirectory());
+ setDisplayName(tr("Autotools Manager"));
}
void AutotoolsBuildSettingsWidget::buildDirectoryChanged()
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h
index ea6808b4b0..459fb2e234 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildsettingswidget.h
@@ -32,7 +32,7 @@
#ifndef AUTOTOOLSBUILDSETTINGSWIDGET_H
#define AUTOTOOLSBUILDSETTINGSWIDGET_H
-#include <projectexplorer/buildstep.h>
+#include <projectexplorer/namedwidget.h>
QT_BEGIN_NAMESPACE
class QComboBox;
@@ -52,15 +52,12 @@ class AutotoolsBuildConfiguration;
*
* Provides an editor to configure the build directory and build steps.
*/
-class AutotoolsBuildSettingsWidget : public ProjectExplorer::BuildConfigWidget
+class AutotoolsBuildSettingsWidget : public ProjectExplorer::NamedWidget
{
Q_OBJECT
public:
- AutotoolsBuildSettingsWidget();
-
- QString displayName() const;
- void init(ProjectExplorer::BuildConfiguration *bc);
+ AutotoolsBuildSettingsWidget(AutotoolsBuildConfiguration *bc);
private slots:
void buildDirectoryChanged();
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp b/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
index bf1cd895b7..a9f7332107 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
+++ b/src/plugins/autotoolsprojectmanager/autotoolsproject.cpp
@@ -40,7 +40,6 @@
#include "makefileparserthread.h"
#include <projectexplorer/abi.h>
-#include <projectexplorer/buildenvironmentwidget.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/buildconfiguration.h>
@@ -126,11 +125,6 @@ QString AutotoolsProject::defaultBuildDirectory() const
return projectDirectory();
}
-QList<BuildConfigWidget *> AutotoolsProject::subConfigWidgets()
-{
- return QList<BuildConfigWidget *>() << new BuildEnvironmentWidget;
-}
-
ProjectNode *AutotoolsProject::rootProjectNode() const
{
return m_rootNode;
@@ -321,11 +315,10 @@ void AutotoolsProject::buildFileNodeTree(const QDir &directory,
// Add file node
const QString filePath = directory.absoluteFilePath(file);
- if (nodeHash.contains(filePath)) {
+ if (nodeHash.contains(filePath))
nodeHash.remove(filePath);
- } else {
+ else
fileNodes.append(new FileNode(filePath, ResourceType, false));
- }
}
if (!fileNodes.isEmpty())
@@ -414,18 +407,21 @@ void AutotoolsProject::updateCppCodeModel()
QStringList allFrameworkPaths;
QByteArray macros;
+ QStringList cxxflags; // FIXME: Autotools should be able to do better than this!
+
if (activeTarget()) {
ProjectExplorer::Kit *k = activeTarget()->kit();
ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
if (tc) {
- const QList<HeaderPath> allHeaderPaths = tc->systemHeaderPaths(SysRootKitInformation::sysRoot(k));
+ const QList<HeaderPath> allHeaderPaths = tc->systemHeaderPaths(cxxflags,
+ SysRootKitInformation::sysRoot(k));
foreach (const HeaderPath &headerPath, allHeaderPaths) {
if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
allFrameworkPaths.append(headerPath.path());
else
allIncludePaths.append(headerPath.path());
}
- macros = tc->predefinedMacros(QStringList());
+ macros = tc->predefinedMacros(cxxflags);
macros += '\n';
}
}
@@ -444,7 +440,7 @@ void AutotoolsProject::updateCppCodeModel()
part->sourceFiles = m_files;
part->defines = macros;
part->frameworkPaths = allFrameworkPaths;
- part->language = CPlusPlus::CppModelManagerInterface::CXX;
+ part->language = CPlusPlus::CppModelManagerInterface::ProjectPart::CXX11;
pinfo.appendProjectPart(part);
modelManager->updateProjectInfo(pinfo);
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsproject.h b/src/plugins/autotoolsprojectmanager/autotoolsproject.h
index 0aee84e25e..9da7c6a1dd 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsproject.h
+++ b/src/plugins/autotoolsprojectmanager/autotoolsproject.h
@@ -74,7 +74,6 @@ public:
Core::Id id() const;
Core::IDocument *document() const;
ProjectExplorer::IProjectManager *projectManager() const;
- QList<ProjectExplorer::BuildConfigWidget*> subConfigWidgets();
ProjectExplorer::ProjectNode *rootProjectNode() const;
QStringList files(FilesMode fileMode) const;
QString defaultBuildDirectory() const;
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro b/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro
index 92cc4bc09c..7503546796 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro
@@ -1,7 +1,6 @@
TEMPLATE = lib
TARGET = AutotoolsProjectManager
#PROVIDER = Openismus
-DEFINES += QT_NO_CAST_FROM_ASCII
include(../../qtcreatorplugin.pri)
include(autotoolsprojectmanager_dependencies.pri)
diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.qbs b/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.qbs
index 78d4a6ab53..4bfba21bbf 100644
--- a/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.qbs
+++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.qbs
@@ -11,15 +11,6 @@ QtcPlugin {
Depends { name: "QtSupport" }
Depends { name: "CppTools" }
- Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_NO_CAST_FROM_ASCII"])
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
"autogenstep.cpp",
"autogenstep.h",
@@ -50,6 +41,6 @@ QtcPlugin {
"makefileparserthread.cpp",
"makefileparserthread.h",
"makestep.cpp",
- "makestep.h"
+ "makestep.h",
]
}
diff --git a/src/plugins/autotoolsprojectmanager/configurestep.cpp b/src/plugins/autotoolsprojectmanager/configurestep.cpp
index b6f52002ce..3fd4d9d483 100644
--- a/src/plugins/autotoolsprojectmanager/configurestep.cpp
+++ b/src/plugins/autotoolsprojectmanager/configurestep.cpp
@@ -151,14 +151,9 @@ void ConfigureStep::ctor()
setDefaultDisplayName(tr("Configure"));
}
-AutotoolsBuildConfiguration *ConfigureStep::autotoolsBuildConfiguration() const
-{
- return static_cast<AutotoolsBuildConfiguration *>(buildConfiguration());
-}
-
bool ConfigureStep::init()
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
ProcessParameters *pp = processParameters();
pp->setMacroExpander(bc->macroExpander());
@@ -166,13 +161,14 @@ bool ConfigureStep::init()
pp->setWorkingDirectory(bc->buildDirectory());
pp->setCommand(QLatin1String("configure"));
pp->setArguments(additionalArguments());
+ pp->resolveAll();
return AbstractProcessStep::init();
}
void ConfigureStep::run(QFutureInterface<bool>& interface)
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
//Check whether we need to run configure
const QFileInfo configureInfo(bc->buildDirectory() + QLatin1String("/configure"));
@@ -271,7 +267,7 @@ QString ConfigureStepConfigWidget::summaryText() const
void ConfigureStepConfigWidget::updateDetails()
{
- AutotoolsBuildConfiguration *bc = m_configureStep->autotoolsBuildConfiguration();
+ BuildConfiguration *bc = m_configureStep->buildConfiguration();
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
diff --git a/src/plugins/autotoolsprojectmanager/configurestep.h b/src/plugins/autotoolsprojectmanager/configurestep.h
index 57dae4723f..cb1793d044 100644
--- a/src/plugins/autotoolsprojectmanager/configurestep.h
+++ b/src/plugins/autotoolsprojectmanager/configurestep.h
@@ -42,7 +42,6 @@ namespace AutotoolsProjectManager {
namespace Internal {
class AutotoolsProject;
-class AutotoolsBuildConfiguration;
class ConfigureStepConfigWidget;
//////////////////////////////////
@@ -95,7 +94,6 @@ class ConfigureStep : public ProjectExplorer::AbstractProcessStep
public:
ConfigureStep(ProjectExplorer::BuildStepList *bsl);
- AutotoolsBuildConfiguration *autotoolsBuildConfiguration() const;
bool init();
void run(QFutureInterface<bool> &interface);
ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
diff --git a/src/plugins/autotoolsprojectmanager/makestep.cpp b/src/plugins/autotoolsprojectmanager/makestep.cpp
index 17905d73aa..f8cc20d669 100644
--- a/src/plugins/autotoolsprojectmanager/makestep.cpp
+++ b/src/plugins/autotoolsprojectmanager/makestep.cpp
@@ -154,11 +154,6 @@ void MakeStep::ctor()
setDefaultDisplayName(tr("Make"));
}
-AutotoolsBuildConfiguration *MakeStep::autotoolsBuildConfiguration() const
-{
- return static_cast<AutotoolsBuildConfiguration *>(buildConfiguration());
-}
-
void MakeStep::setClean(bool clean)
{
m_clean = clean;
@@ -166,9 +161,9 @@ void MakeStep::setClean(bool clean)
bool MakeStep::init()
{
- AutotoolsBuildConfiguration *bc = autotoolsBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
if (!bc)
- bc = static_cast<AutotoolsBuildConfiguration *>(target()->activeBuildConfiguration());
+ bc = target()->activeBuildConfiguration();
m_tasks.clear();
ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit());
@@ -194,13 +189,12 @@ bool MakeStep::init()
pp->setWorkingDirectory(bc->buildDirectory());
pp->setCommand(tc ? tc->makeCommand(bc->environment()) : QLatin1String("make"));
pp->setArguments(arguments);
+ pp->resolveAll();
setOutputParser(new GnuMakeParser());
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- if (version)
- appendOutputParser(new QtSupport::QtParser);
- if (tc)
- appendOutputParser(tc->outputParser());
+ IOutputParser *parser = target()->kit()->createOutputParser();
+ if (parser)
+ appendOutputParser(parser);
outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());
return AbstractProcessStep::init();
@@ -316,7 +310,7 @@ QString MakeStepConfigWidget::summaryText() const
void MakeStepConfigWidget::updateDetails()
{
- AutotoolsBuildConfiguration *bc = m_makeStep->autotoolsBuildConfiguration();
+ BuildConfiguration *bc = m_makeStep->buildConfiguration();
ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(m_makeStep->target()->kit());
if (tc) {
diff --git a/src/plugins/autotoolsprojectmanager/makestep.h b/src/plugins/autotoolsprojectmanager/makestep.h
index 55689b43df..c7a9f70abb 100644
--- a/src/plugins/autotoolsprojectmanager/makestep.h
+++ b/src/plugins/autotoolsprojectmanager/makestep.h
@@ -43,7 +43,6 @@ namespace AutotoolsProjectManager {
namespace Internal {
class AutotoolsProject;
-class AutotoolsBuildConfiguration;
class MakeStep;
///////////////////////////
@@ -94,7 +93,6 @@ class MakeStep : public ProjectExplorer::AbstractProcessStep
public:
MakeStep(ProjectExplorer::BuildStepList *bsl);
- AutotoolsBuildConfiguration *autotoolsBuildConfiguration() const;
bool init();
void run(QFutureInterface<bool> &interface);
ProjectExplorer::BuildStepConfigWidget *createConfigWidget();
diff --git a/src/plugins/bazaar/annotationhighlighter.h b/src/plugins/bazaar/annotationhighlighter.h
index f7020b26fb..ff39440286 100644
--- a/src/plugins/bazaar/annotationhighlighter.h
+++ b/src/plugins/bazaar/annotationhighlighter.h
@@ -42,7 +42,7 @@ public:
QTextDocument *document = 0);
private:
- virtual QString changeNumber(const QString &block) const;
+ QString changeNumber(const QString &block) const;
mutable QRegExp m_changeset;
};
diff --git a/src/plugins/bazaar/bazaar.pro b/src/plugins/bazaar/bazaar.pro
index 5fc6bc8b7d..895f50473d 100644
--- a/src/plugins/bazaar/bazaar.pro
+++ b/src/plugins/bazaar/bazaar.pro
@@ -2,7 +2,6 @@ TARGET = Bazaar
TEMPLATE = lib
include(../../qtcreatorplugin.pri)
include(bazaar_dependencies.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
SOURCES += \
bazaarclient.cpp \
bazaarcontrol.cpp \
diff --git a/src/plugins/bazaar/bazaar.qbs b/src/plugins/bazaar/bazaar.qbs
index 4271a0d0eb..b43ff69dd0 100644
--- a/src/plugins/bazaar/bazaar.qbs
+++ b/src/plugins/bazaar/bazaar.qbs
@@ -13,49 +13,44 @@ QtcPlugin {
Depends { name: "Locator" }
Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
files: [
- "bazaar.qrc",
- "bazaarcommitpanel.ui",
- "cloneoptionspanel.ui",
- "pullorpushdialog.ui",
- "revertdialog.ui",
- "bazaarcommitwidget.cpp",
- "bazaarcommitwidget.h",
- "bazaarsettings.cpp",
- "branchinfo.cpp",
- "branchinfo.h",
- "cloneoptionspanel.cpp",
- "cloneoptionspanel.h",
- "constants.h",
- "optionspage.ui",
- "pullorpushdialog.cpp",
- "pullorpushdialog.h",
"annotationhighlighter.cpp",
"annotationhighlighter.h",
+ "bazaar.qrc",
"bazaarclient.cpp",
"bazaarclient.h",
+ "bazaarcommitpanel.ui",
+ "bazaarcommitwidget.cpp",
+ "bazaarcommitwidget.h",
"bazaarcontrol.cpp",
"bazaarcontrol.h",
"bazaareditor.cpp",
"bazaareditor.h",
"bazaarplugin.cpp",
"bazaarplugin.h",
+ "bazaarsettings.cpp",
"bazaarsettings.h",
+ "branchinfo.cpp",
+ "branchinfo.h",
+ "cloneoptionspanel.cpp",
+ "cloneoptionspanel.h",
+ "cloneoptionspanel.ui",
"clonewizard.cpp",
"clonewizard.h",
"clonewizardpage.cpp",
"clonewizardpage.h",
"commiteditor.cpp",
"commiteditor.h",
+ "constants.h",
"optionspage.cpp",
"optionspage.h",
- "images/bazaar.png"
+ "optionspage.ui",
+ "pullorpushdialog.cpp",
+ "pullorpushdialog.h",
+ "pullorpushdialog.ui",
+ "revertdialog.ui",
+ "images/bazaar.png",
]
}
diff --git a/src/plugins/bazaar/bazaarclient.cpp b/src/plugins/bazaar/bazaarclient.cpp
index ac074f7802..6b930bd4a8 100644
--- a/src/plugins/bazaar/bazaarclient.cpp
+++ b/src/plugins/bazaar/bazaarclient.cpp
@@ -124,7 +124,7 @@ void BazaarClient::view(const QString &source, const QString &id, const QStringL
QString BazaarClient::vcsEditorKind(VcsCommand cmd) const
{
- switch(cmd) {
+ switch (cmd) {
case AnnotateCommand:
return QLatin1String(Constants::ANNOTATELOG);
case DiffCommand:
diff --git a/src/plugins/bazaar/bazaarcommitwidget.cpp b/src/plugins/bazaar/bazaarcommitwidget.cpp
index deb492397e..52bccadf84 100644
--- a/src/plugins/bazaar/bazaarcommitwidget.cpp
+++ b/src/plugins/bazaar/bazaarcommitwidget.cpp
@@ -61,7 +61,7 @@ class BazaarSubmitHighlighter : QSyntaxHighlighter
{
public:
explicit BazaarSubmitHighlighter(QTextEdit *parent);
- virtual void highlightBlock(const QString &text);
+ void highlightBlock(const QString &text);
private:
enum State { Header, Comment, Other };
@@ -114,7 +114,7 @@ void BazaarSubmitHighlighter::highlightBlock(const QString &text)
BazaarCommitWidget::BazaarCommitWidget(QWidget *parent) :
- Utils::SubmitEditorWidget(parent),
+ VcsBase::SubmitEditorWidget(parent),
m_bazaarCommitPanel(new QWidget)
{
m_bazaarCommitPanelUi.setupUi(m_bazaarCommitPanel);
diff --git a/src/plugins/bazaar/bazaarcommitwidget.h b/src/plugins/bazaar/bazaarcommitwidget.h
index d736d18814..82b95663cd 100644
--- a/src/plugins/bazaar/bazaarcommitwidget.h
+++ b/src/plugins/bazaar/bazaarcommitwidget.h
@@ -31,7 +31,7 @@
#include "ui_bazaarcommitpanel.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
namespace Bazaar {
namespace Internal {
@@ -42,7 +42,7 @@ class BranchInfo;
Some extra fields have been added to the standard SubmitEditorWidget,
to help to conform to the commit style that is used by both git and Bazaar*/
-class BazaarCommitWidget : public Utils::SubmitEditorWidget
+class BazaarCommitWidget : public VcsBase::SubmitEditorWidget
{
public:
diff --git a/src/plugins/bazaar/bazaarcontrol.cpp b/src/plugins/bazaar/bazaarcontrol.cpp
index e032773872..80b6be448f 100644
--- a/src/plugins/bazaar/bazaarcontrol.cpp
+++ b/src/plugins/bazaar/bazaarcontrol.cpp
@@ -51,7 +51,7 @@ QString BazaarControl::displayName() const
Core::Id BazaarControl::id() const
{
- return VcsBase::Constants::VCS_ID_BAZAAR;
+ return Core::Id(VcsBase::Constants::VCS_ID_BAZAAR);
}
bool BazaarControl::managesDirectory(const QString &directory, QString *topLevel) const
diff --git a/src/plugins/bazaar/bazaarcontrol.h b/src/plugins/bazaar/bazaarcontrol.h
index 197aeb852f..673b70a524 100644
--- a/src/plugins/bazaar/bazaarcontrol.h
+++ b/src/plugins/bazaar/bazaarcontrol.h
@@ -66,7 +66,7 @@ public:
QStringList vcsSnapshots(const QString &topLevel);
bool vcsRestoreSnapshot(const QString &topLevel, const QString &name);
bool vcsRemoveSnapshot(const QString &topLevel, const QString &name);
- virtual bool vcsAnnotate(const QString &file, int line);
+ bool vcsAnnotate(const QString &file, int line);
public slots:
// To be connected to the VCSTask's success signal to emit the repository/
diff --git a/src/plugins/bazaar/bazaareditor.cpp b/src/plugins/bazaar/bazaareditor.cpp
index 1052e71965..ee190bc374 100644
--- a/src/plugins/bazaar/bazaareditor.cpp
+++ b/src/plugins/bazaar/bazaareditor.cpp
@@ -52,11 +52,14 @@ using namespace Bazaar;
BazaarEditor::BazaarEditor(const VcsBase::VcsBaseEditorParameters *type, QWidget *parent)
: VcsBase::VcsBaseEditorWidget(type, parent),
m_changesetId(QLatin1String(Constants::CHANGESET_ID)),
- m_exactChangesetId(QLatin1String(Constants::CHANGESET_ID_EXACT)),
- m_diffFileId(QLatin1String("^=== [a-z]+ [a-z]+ '(.*)'\\s*"))
+ m_exactChangesetId(QLatin1String(Constants::CHANGESET_ID_EXACT))
{
setAnnotateRevisionTextFormat(tr("Annotate %1"));
setAnnotatePreviousRevisionTextFormat(tr("Annotate parent revision %1"));
+ // Diff format:
+ // === <change> <file|dir> 'mainwindow.cpp'
+ setDiffFilePattern(QRegExp(QLatin1String("^=== [a-z]+ [a-z]+ '(.+)'\\s*")));
+ setLogEntryPattern(QRegExp(QLatin1String("^revno: (\\d+)")));
}
QSet<QString> BazaarEditor::annotationChanges() const
@@ -111,25 +114,8 @@ QString BazaarEditor::changeUnderCursor(const QTextCursor &cursorIn) const
return QString();
}
-VcsBase::DiffHighlighter *BazaarEditor::createDiffHighlighter() const
-{
- return new VcsBase::DiffHighlighter(m_diffFileId);
-}
-
VcsBase::BaseAnnotationHighlighter *BazaarEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new BazaarAnnotationHighlighter(changes, bg);
}
-
-QString BazaarEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
-{
- // Check for:
- // === <change> <file|dir> 'mainwindow.cpp'
- for (QTextBlock block = inBlock; block.isValid(); block = block.previous()) {
- const QString line = block.text();
- if (m_diffFileId.indexIn(line) != -1)
- return findDiffFile(m_diffFileId.cap(1));
- }
- return QString();
-}
diff --git a/src/plugins/bazaar/bazaareditor.h b/src/plugins/bazaar/bazaareditor.h
index 459bbedebc..50dca61e04 100644
--- a/src/plugins/bazaar/bazaareditor.h
+++ b/src/plugins/bazaar/bazaareditor.h
@@ -44,15 +44,12 @@ public:
explicit BazaarEditor(const VcsBase::VcsBaseEditorParameters *type, QWidget *parent);
private:
- virtual QSet<QString> annotationChanges() const;
- virtual QString changeUnderCursor(const QTextCursor &cursor) const;
- virtual VcsBase::DiffHighlighter *createDiffHighlighter() const;
- virtual VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- virtual QString fileNameFromDiffSpecification(const QTextBlock &diffFileSpec) const;
+ QSet<QString> annotationChanges() const;
+ QString changeUnderCursor(const QTextCursor &cursor) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
mutable QRegExp m_changesetId;
mutable QRegExp m_exactChangesetId;
- mutable QRegExp m_diffFileId;
};
} // namespace Internal
diff --git a/src/plugins/bazaar/bazaarplugin.cpp b/src/plugins/bazaar/bazaarplugin.cpp
index 062366c9e1..ff74da8d45 100644
--- a/src/plugins/bazaar/bazaarplugin.cpp
+++ b/src/plugins/bazaar/bazaarplugin.cpp
@@ -108,7 +108,8 @@ static const VcsBase::VcsBaseSubmitEditorParameters submitEditorParameters = {
Constants::COMMITMIMETYPE,
Constants::COMMIT_ID,
Constants::COMMIT_DISPLAY_NAME,
- Constants::COMMIT_ID
+ Constants::COMMIT_ID,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
@@ -163,7 +164,7 @@ bool BazaarPlugin::initialize(const QStringList &arguments, QString *errorMessag
addAutoReleasedObject(new CloneWizard);
const QString prefix = QLatin1String("bzr");
- m_commandLocator = new Locator::CommandLocator(QLatin1String("Bazaar"), prefix, prefix);
+ m_commandLocator = new Locator::CommandLocator("Bazaar", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
createMenu();
@@ -590,6 +591,65 @@ void BazaarPlugin::diffFromEditorSelected(const QStringList &files)
m_client->diff(m_submitRepository, files);
}
+#ifdef WITH_TESTS
+#include <QTest>
+
+void BazaarPlugin::testDiffFileResolving_data()
+{
+ QTest::addColumn<QByteArray>("header");
+ QTest::addColumn<QByteArray>("fileName");
+
+ QTest::newRow("New") << QByteArray(
+ "=== added file 'src/plugins/bazaar/bazaareditor.cpp'\n"
+ "--- src/plugins/bazaar/bazaareditor.cpp\t1970-01-01 00:00:00 +0000\n"
+ "+++ src/plugins/bazaar/bazaareditor.cpp\t2013-01-20 21:39:47 +0000\n"
+ "@@ -0,0 +1,121 @@\n\n")
+ << QByteArray("src/plugins/bazaar/bazaareditor.cpp");
+ QTest::newRow("Deleted") << QByteArray(
+ "=== removed file 'src/plugins/bazaar/bazaareditor.cpp'\n"
+ "--- src/plugins/bazaar/bazaareditor.cpp\t2013-01-20 21:39:47 +0000\n"
+ "+++ src/plugins/bazaar/bazaareditor.cpp\t1970-01-01 00:00:00 +0000\n"
+ "@@ -1,121 +0,0 @@\n\n")
+ << QByteArray("src/plugins/bazaar/bazaareditor.cpp");
+ QTest::newRow("Modified") << QByteArray(
+ "=== modified file 'src/plugins/bazaar/bazaareditor.cpp'\n"
+ "--- src/plugins/bazaar/bazaareditor.cpp\t2010-08-27 14:12:44 +0000\n"
+ "+++ src/plugins/bazaar/bazaareditor.cpp\t2011-02-28 21:24:19 +0000\n"
+ "@@ -727,6 +727,9 @@\n\n")
+ << QByteArray("src/plugins/bazaar/bazaareditor.cpp");
+}
+
+void BazaarPlugin::testDiffFileResolving()
+{
+ BazaarEditor editor(editorParameters + 3, 0);
+ editor.testDiffFileResolving();
+}
+
+void BazaarPlugin::testLogResolving()
+{
+ QByteArray data(
+ "------------------------------------------------------------\n"
+ "revno: 6572 [merge]\n"
+ "committer: Patch Queue Manager <pqm@pqm.ubuntu.com>\n"
+ "branch nick: +trunk\n"
+ "timestamp: Mon 2012-12-10 10:18:33 +0000\n"
+ "message:\n"
+ " (vila) Fix LC_ALL=C test failures related to utf8 stderr encoding (Vincent\n"
+ " Ladeuil)\n"
+ "------------------------------------------------------------\n"
+ "revno: 6571 [merge]\n"
+ "committer: Patch Queue Manager <pqm@pqm.ubuntu.com>\n"
+ "branch nick: +trunk\n"
+ "timestamp: Thu 2012-10-25 11:13:27 +0000\n"
+ "message:\n"
+ " (gz) Set approved revision and vote \"Approve\" when using lp-propose\n"
+ " --approve (Jonathan Lange)\n"
+ );
+ BazaarEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data, "6572", "6571");
+}
+#endif
+
void BazaarPlugin::commitFromEditor()
{
// Close the submit editor
diff --git a/src/plugins/bazaar/bazaarplugin.h b/src/plugins/bazaar/bazaarplugin.h
index 27ef84dbce..0824c30141 100644
--- a/src/plugins/bazaar/bazaarplugin.h
+++ b/src/plugins/bazaar/bazaarplugin.h
@@ -80,7 +80,7 @@ class BazaarPlugin : public VcsBase::VcsBasePlugin
public:
BazaarPlugin();
- virtual ~BazaarPlugin();
+ ~BazaarPlugin();
bool initialize(const QStringList &arguments, QString *errorMessage);
static BazaarPlugin *instance();
@@ -112,6 +112,11 @@ private slots:
void showCommitWidget(const QList<VcsBase::VcsBaseClient::StatusItem> &status);
void commitFromEditor();
void diffFromEditorSelected(const QStringList &files);
+#ifdef WITH_TESTS
+ void testDiffFileResolving_data();
+ void testDiffFileResolving();
+ void testLogResolving();
+#endif
protected:
void updateActions(VcsBase::VcsBasePlugin::ActionState);
diff --git a/src/plugins/bazaar/commiteditor.cpp b/src/plugins/bazaar/commiteditor.cpp
index 9943eeed90..e2a2283366 100644
--- a/src/plugins/bazaar/commiteditor.cpp
+++ b/src/plugins/bazaar/commiteditor.cpp
@@ -69,6 +69,6 @@ void CommitEditor::setFields(const QString &repositoryRoot,
m_fileModel = new VcsBase::SubmitFileModel(this);
foreach (const VcsBase::VcsBaseClient::StatusItem &item, repoStatus)
if (item.flags != QLatin1String("Unknown"))
- m_fileModel->addFile(item.file, item.flags, true);
+ m_fileModel->addFile(item.file, item.flags);
setFileModel(m_fileModel, repositoryRoot);
}
diff --git a/src/plugins/bazaar/optionspage.cpp b/src/plugins/bazaar/optionspage.cpp
index 49cc9e67c4..2e33c5ea06 100644
--- a/src/plugins/bazaar/optionspage.cpp
+++ b/src/plugins/bazaar/optionspage.cpp
@@ -91,7 +91,7 @@ QString OptionsPageWidget::searchKeywords() const
OptionsPage::OptionsPage()
{
- setId(QLatin1String(VcsBase::Constants::VCS_ID_BAZAAR));
+ setId(VcsBase::Constants::VCS_ID_BAZAAR);
setDisplayName(tr("Bazaar"));
}
diff --git a/src/plugins/bineditor/bineditor.cpp b/src/plugins/bineditor/bineditor.cpp
index e55920d827..500807b250 100644
--- a/src/plugins/bineditor/bineditor.cpp
+++ b/src/plugins/bineditor/bineditor.cpp
@@ -73,9 +73,8 @@ static QByteArray calculateHexPattern(const QByteArray &pattern)
int i = 0;
while (i < pattern.size()) {
ushort s = pattern.mid(i, 2).toUShort(&ok, 16);
- if (!ok) {
+ if (!ok)
return QByteArray();
- }
result.append(s);
i += 2;
}
@@ -142,15 +141,15 @@ void BinEditor::init()
++hex;
}
- if (m_isMonospacedFont && fm.width("M M ") != m_charWidth * 4) {
+ if (m_isMonospacedFont && fm.width(QLatin1String("M M ")) != m_charWidth * 4) {
// On Qt/Mac, monospace font widths may have a fractional component
// This breaks the assumption that width("MMM") == width('M') * 3
m_isMonospacedFont = false;
- m_columnWidth = fm.width("MMM");
+ m_columnWidth = fm.width(QLatin1String("MMM"));
m_labelWidth = m_addressBytes == 4
- ? fm.width("MMMM:MMMM")
- : fm.width("MMMM:MMMM:MMMM:MMMM");
+ ? fm.width(QLatin1String("MMMM:MMMM"))
+ : fm.width(QLatin1String("MMMM:MMMM:MMMM:MMMM"));
}
horizontalScrollBar()->setRange(0, 2 * m_margin + m_bytesPerLine * m_columnWidth
@@ -691,9 +690,9 @@ QString BinEditor::addressString(quint64 address)
for (int b = 0; b < m_addressBytes; ++b) {
addressStringData[indices[2*m_addressBytes - 1 - b*2]] =
- hex[(address >> (8*b)) & 0xf];
+ QLatin1Char(hex[(address >> (8*b)) & 0xf]);
addressStringData[indices[2*m_addressBytes - 2 - b*2]] =
- hex[(address >> (8*b + 4)) & 0xf];
+ QLatin1Char(hex[(address >> (8*b + 4)) & 0xf]);
}
return m_addressString;
}
@@ -734,7 +733,7 @@ void BinEditor::paintEvent(QPaintEvent *e)
selEnd = m_cursorPosition;
} else {
selStart = m_cursorPosition;
- selEnd = m_anchorPosition + 1;
+ selEnd = m_anchorPosition;
}
QString itemString(m_bytesPerLine*3, QLatin1Char(' '));
@@ -796,7 +795,7 @@ void BinEditor::paintEvent(QPaintEvent *e)
int pos = line * m_bytesPerLine + c;
if (pos >= m_size) {
while (c < m_bytesPerLine) {
- itemStringData[c*3] = itemStringData[c*3+1] = ' ';
+ itemStringData[c*3] = itemStringData[c*3+1] = QLatin1Char(' ');
++c;
}
break;
@@ -806,8 +805,8 @@ void BinEditor::paintEvent(QPaintEvent *e)
const uchar value = uchar(dataAt(pos, isOld));
- itemStringData[c*3] = hex[value >> 4];
- itemStringData[c*3+1] = hex[value & 0xf];
+ itemStringData[c*3] = QLatin1Char(hex[value >> 4]);
+ itemStringData[c*3+1] = QLatin1Char(hex[value & 0xf]);
if (hasOldData && !isOld && value != uchar(dataAt(pos, true))) {
changedString[c] = true;
somethingChanged = true;
@@ -834,7 +833,7 @@ void BinEditor::paintEvent(QPaintEvent *e)
m_lineHeight, color);
}
- if (selStart < selEnd && !isFullySelected && pos >= selStart && pos < selEnd) {
+ if (selStart < selEnd && !isFullySelected && pos >= selStart && pos <= selEnd) {
selectionRect |= QRect(item_x, y-m_ascent, m_columnWidth, m_lineHeight);
int printable_item_x = -xoffset + m_margin + m_labelWidth + m_bytesPerLine * m_columnWidth + m_charWidth
+ fm.width(printable.left(c));
@@ -940,22 +939,19 @@ void BinEditor::setCursorPosition(int pos, MoveMode moveMode)
pos = qMin(m_size-1, qMax(0, pos));
int oldCursorPosition = m_cursorPosition;
- bool hasSelection = m_anchorPosition != m_cursorPosition;
+ bool hadSelection = hasSelection();
m_lowNibble = false;
- if (!hasSelection)
+ if (!hadSelection)
updateLines();
m_cursorPosition = pos;
if (moveMode == MoveAnchor) {
- if (hasSelection)
+ if (hadSelection)
updateLines(m_anchorPosition, oldCursorPosition);
m_anchorPosition = m_cursorPosition;
}
- hasSelection = m_anchorPosition != m_cursorPosition;
- updateLines(hasSelection ? oldCursorPosition : m_cursorPosition, m_cursorPosition);
+ updateLines(hadSelection || hasSelection() ? oldCursorPosition : m_cursorPosition, m_cursorPosition);
ensureCursorVisible();
- if (hasSelection)
- emit copyAvailable(hasSelection);
emit cursorPositionChanged(m_cursorPosition);
}
@@ -976,7 +972,8 @@ void BinEditor::mousePressEvent(QMouseEvent *e)
{
if (e->button() != Qt::LeftButton)
return;
- setCursorPosition(posAt(e->pos()));
+ MoveMode moveMode = e->modifiers() & Qt::ShiftModifier ? KeepAnchor : MoveAnchor;
+ setCursorPosition(posAt(e->pos()), moveMode);
setBlinkingCursorEnabled(true);
if (m_hexCursor == inTextArea(e->pos())) {
m_hexCursor = !m_hexCursor;
@@ -1063,11 +1060,10 @@ bool BinEditor::event(QEvent *e)
case QEvent::ToolTip: {
const QHelpEvent *helpEvent = static_cast<const QHelpEvent *>(e);
const QString tt = toolTip(helpEvent);
- if (tt.isEmpty()) {
+ if (tt.isEmpty())
QToolTip::hideText();
- } else {
+ else
QToolTip::showText(helpEvent->globalPos(), tt, this);
- }
e->accept();
return true;
}
@@ -1083,20 +1079,19 @@ QString BinEditor::toolTip(const QHelpEvent *helpEvent) const
// Selection if mouse is in, else 1 byte at cursor
int selStart = selectionStart();
int selEnd = selectionEnd();
- int byteCount = selEnd - selStart;
- if (byteCount <= 0) {
+ int byteCount = selEnd - selStart + 1;
+ if (byteCount <= 1) {
selStart = posAt(helpEvent->pos());
- selEnd = selStart + 1;
+ selEnd = selStart;
byteCount = 1;
}
if (m_hexCursor == 0 || byteCount > 8)
return QString();
const QPoint &startPoint = offsetToPos(selStart);
- const QPoint &endPoint = offsetToPos(selEnd);
- const QPoint expandedEndPoint
- = QPoint(endPoint.x(), endPoint.y() + m_lineHeight);
- const QRect selRect(startPoint, expandedEndPoint);
+ const QPoint &endPoint = offsetToPos(selEnd + 1);
+ QRect selRect(startPoint, endPoint);
+ selRect.setHeight(m_lineHeight);
if (!selRect.contains(helpEvent->pos()))
return QString();
@@ -1305,20 +1300,22 @@ void BinEditor::keyPressEvent(QKeyEvent *e)
setCursorPosition((verticalScrollBar()->value() + line) * m_bytesPerLine + m_cursorPosition % m_bytesPerLine, moveMode);
} break;
- case Qt::Key_Home:
- if (e->modifiers() & Qt::ControlModifier) {
- emit startOfFileRequested(editor());
- } else {
- setCursorPosition(m_cursorPosition/m_bytesPerLine * m_bytesPerLine, moveMode);
- }
- break;
- case Qt::Key_End:
- if (e->modifiers() & Qt::ControlModifier) {
- emit endOfFileRequested(editor());
- } else {
- setCursorPosition(m_cursorPosition/m_bytesPerLine * m_bytesPerLine + 15, moveMode);
- }
- break;
+ case Qt::Key_Home: {
+ int pos;
+ if (e->modifiers() & Qt::ControlModifier)
+ pos = 0;
+ else
+ pos = m_cursorPosition/m_bytesPerLine * m_bytesPerLine;
+ setCursorPosition(pos, moveMode);
+ } break;
+ case Qt::Key_End: {
+ int pos;
+ if (e->modifiers() & Qt::ControlModifier)
+ pos = m_size;
+ else
+ pos = m_cursorPosition/m_bytesPerLine * m_bytesPerLine + 15;
+ setCursorPosition(pos, moveMode);
+ } break;
default:
if (m_readOnly)
break;
@@ -1380,7 +1377,7 @@ void BinEditor::copy(bool raw)
if (selStart >= selEnd)
qSwap(selStart, selEnd);
- const int selectionLength = selEnd - selStart;
+ const int selectionLength = selEnd - selStart + 1;
if (selectionLength >> 22) {
QMessageBox::warning(this, tr("Copying Failed"),
tr("You cannot copy more than 4 MB of binary data."));
@@ -1388,7 +1385,7 @@ void BinEditor::copy(bool raw)
}
const QByteArray &data = dataMid(selStart, selectionLength);
if (raw) {
- QApplication::clipboard()->setText(data);
+ QApplication::clipboard()->setText(QString::fromLatin1(data));
return;
}
QString hexString;
@@ -1396,7 +1393,7 @@ void BinEditor::copy(bool raw)
hexString.reserve(3 * data.size());
for (int i = 0; i < data.size(); ++i) {
const uchar val = static_cast<uchar>(data[i]);
- hexString.append(hex[val >> 4]).append(hex[val & 0xf]).append(' ');
+ hexString.append(QLatin1Char(hex[val >> 4])).append(QLatin1Char(hex[val & 0xf])).append(QLatin1Char(' '));
}
hexString.chop(1);
QApplication::clipboard()->setText(hexString);
@@ -1438,9 +1435,8 @@ void BinEditor::changeData(int position, uchar character, bool highNibble)
changeDataAt(position, (char) character);
bool emitModificationChanged = (m_undoStack.size() == m_unmodifiedState);
m_undoStack.push(cmd);
- if (emitModificationChanged) {
+ if (emitModificationChanged)
emit modificationChanged(m_undoStack.size() != m_unmodifiedState);
- }
if (m_undoStack.size() == 1)
emit undoAvailable(true);
@@ -1489,7 +1485,7 @@ void BinEditor::redo()
void BinEditor::contextMenuEvent(QContextMenuEvent *event)
{
const int selStart = selectionStart();
- const int byteCount = selectionEnd() - selStart;
+ const int byteCount = selectionEnd() - selStart + 1;
QMenu contextMenu;
QAction copyAsciiAction(tr("Copy Selection as ASCII Characters"), this);
@@ -1503,12 +1499,6 @@ void BinEditor::contextMenuEvent(QContextMenuEvent *event)
contextMenu.addAction(&copyHexAction);
contextMenu.addAction(&addWatchpointAction);
- copyAsciiAction.setEnabled(byteCount > 0);
- copyHexAction.setEnabled(byteCount > 0);;
- jumpToBeAddressHereAction.setEnabled(byteCount > 0);
- jumpToBeAddressNewWindowAction.setEnabled(byteCount > 0);
- jumpToLeAddressHereAction.setEnabled(byteCount > 0);
- jumpToLeAddressNewWindowAction.setEnabled(byteCount > 0);
addWatchpointAction.setEnabled(byteCount > 0 && byteCount <= 32);
quint64 beAddress = 0;
diff --git a/src/plugins/bineditor/bineditor.h b/src/plugins/bineditor/bineditor.h
index 9bc61b5310..9242a5b00f 100644
--- a/src/plugins/bineditor/bineditor.h
+++ b/src/plugins/bineditor/bineditor.h
@@ -136,15 +136,12 @@ Q_SIGNALS:
void modificationChanged(bool modified);
void undoAvailable(bool);
void redoAvailable(bool);
- void copyAvailable(bool);
void cursorPositionChanged(int position);
void dataRequested(Core::IEditor *editor, quint64 block);
void newWindowRequested(quint64 address);
void newRangeRequested(Core::IEditor *, quint64 address);
void addWatchpointRequested(quint64 address, uint size);
- void startOfFileRequested(Core::IEditor *);
- void endOfFileRequested(Core::IEditor *);
void dataChanged(Core::IEditor *, quint64 address, const QByteArray &data);
protected:
diff --git a/src/plugins/bineditor/bineditor.pro b/src/plugins/bineditor/bineditor.pro
index 71a65fd19a..8633294174 100644
--- a/src/plugins/bineditor/bineditor.pro
+++ b/src/plugins/bineditor/bineditor.pro
@@ -10,5 +10,3 @@ HEADERS += bineditorplugin.h \
SOURCES += bineditorplugin.cpp \
bineditor.cpp
-
-RESOURCES +=
diff --git a/src/plugins/bineditor/bineditor.qbs b/src/plugins/bineditor/bineditor.qbs
index b2fd675be8..f9384838e3 100644
--- a/src/plugins/bineditor/bineditor.qbs
+++ b/src/plugins/bineditor/bineditor.qbs
@@ -10,20 +10,13 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "Find" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "bineditorplugin.h",
+ "bineditor.cpp",
"bineditor.h",
"bineditorconstants.h",
- "markup.h",
"bineditorplugin.cpp",
- "bineditor.cpp"
+ "bineditorplugin.h",
+ "markup.h",
]
}
diff --git a/src/plugins/bineditor/bineditorplugin.cpp b/src/plugins/bineditor/bineditorplugin.cpp
index 9fea934684..7d2903b43e 100644
--- a/src/plugins/bineditor/bineditorplugin.cpp
+++ b/src/plugins/bineditor/bineditorplugin.cpp
@@ -187,10 +187,6 @@ public:
this, SLOT(provideData(Core::IEditor*,quint64)));
connect(m_editor, SIGNAL(newRangeRequested(Core::IEditor*,quint64)),
this, SLOT(provideNewRange(Core::IEditor*,quint64)));
- connect(m_editor, SIGNAL(startOfFileRequested(Core::IEditor*)), this,
- SLOT(handleStartOfFileRequested(Core::IEditor*)));
- connect(m_editor, SIGNAL(endOfFileRequested(Core::IEditor*)), this,
- SLOT(handleEndOfFileRequested(Core::IEditor*)));
}
~BinEditorDocument() {}
@@ -273,14 +269,6 @@ private slots:
open(0, m_fileName, offset);
}
- void handleStartOfFileRequested(Core::IEditor *) {
- open(0, m_fileName, 0);
- }
-
- void handleEndOfFileRequested(Core::IEditor *) {
- open(0, m_fileName, QFileInfo(m_fileName).size() - 1);
- }
-
public:
void setFilename(const QString &filename) {
@@ -373,7 +361,7 @@ public:
return m_file->open(errorString, fileName);
}
Core::IDocument *document() { return m_file; }
- Core::Id id() const { return Core::Constants::K_DEFAULT_BINARY_EDITOR_ID; }
+ Core::Id id() const { return Core::Id(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID); }
QString displayName() const { return m_displayName; }
void setDisplayName(const QString &title) { m_displayName = title; emit changed(); }
@@ -417,7 +405,7 @@ BinEditorFactory::BinEditorFactory(BinEditorPlugin *owner) :
Core::Id BinEditorFactory::id() const
{
- return Core::Constants::K_DEFAULT_BINARY_EDITOR_ID;
+ return Core::Id(Core::Constants::K_DEFAULT_BINARY_EDITOR_ID);
}
QString BinEditorFactory::displayName() const
@@ -508,7 +496,6 @@ void BinEditorPlugin::initializeEditor(BinEditor *editor)
QObject::connect(editor, SIGNAL(undoAvailable(bool)), this, SLOT(updateActions()));
QObject::connect(editor, SIGNAL(redoAvailable(bool)), this, SLOT(updateActions()));
- QObject::connect(editor, SIGNAL(copyAvailable(bool)), this, SLOT(updateActions()));
Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
BinEditorFind *binEditorFind = new BinEditorFind(editor);
@@ -570,8 +557,6 @@ void BinEditorPlugin::updateActions()
m_undoAction->setEnabled(m_currentEditor && m_currentEditor->isUndoAvailable());
if (m_redoAction)
m_redoAction->setEnabled(m_currentEditor && m_currentEditor->isRedoAvailable());
- if (m_copyAction)
- m_copyAction->setEnabled(m_currentEditor && m_currentEditor->hasSelection());
}
void BinEditorPlugin::undoAction()
diff --git a/src/plugins/bookmarks/bookmark.cpp b/src/plugins/bookmarks/bookmark.cpp
index 8dbd54d8e7..91fa100d17 100644
--- a/src/plugins/bookmarks/bookmark.cpp
+++ b/src/plugins/bookmarks/bookmark.cpp
@@ -77,11 +77,27 @@ void Bookmark::updateFileName(const QString &fileName)
BaseTextMark::updateFileName(fileName);
}
+void Bookmark::setNote(const QString &note)
+{
+ m_note = note;
+}
+
+void Bookmark::updateNote(const QString &note)
+{
+ setNote(note);
+ m_manager->updateBookmark(this);
+}
+
QString Bookmark::lineText() const
{
return m_lineText;
}
+QString Bookmark::note() const
+{
+ return m_note;
+}
+
QString Bookmark::filePath() const
{
return m_fileName;
diff --git a/src/plugins/bookmarks/bookmark.h b/src/plugins/bookmarks/bookmark.h
index d6f02a0f96..7f45d29485 100644
--- a/src/plugins/bookmarks/bookmark.h
+++ b/src/plugins/bookmarks/bookmark.h
@@ -52,12 +52,15 @@ public:
void updateLineNumber(int lineNumber);
void updateBlock(const QTextBlock &block);
void updateFileName(const QString &fileName);
+ void setNote(const QString &note);
+ void updateNote(const QString &note);
void removedFromEditor();
QString filePath() const;
QString fileName() const;
QString path() const;
QString lineText() const;
+ QString note() const;
private:
BookmarkManager *m_manager;
@@ -65,6 +68,7 @@ private:
QString m_onlyFile;
QString m_path;
QString m_lineText;
+ QString m_note;
};
} // namespace Internal
diff --git a/src/plugins/bookmarks/bookmarkmanager.cpp b/src/plugins/bookmarks/bookmarkmanager.cpp
index 175083c806..8787fa0db8 100644
--- a/src/plugins/bookmarks/bookmarkmanager.cpp
+++ b/src/plugins/bookmarks/bookmarkmanager.cpp
@@ -40,6 +40,8 @@
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
#include <texteditor/basetexteditor.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -50,6 +52,7 @@
#include <QContextMenuEvent>
#include <QMenu>
#include <QPainter>
+#include <QInputDialog>
Q_DECLARE_METATYPE(Bookmarks::Internal::Bookmark*)
@@ -116,7 +119,7 @@ void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti
painter->save();
QFontMetrics fm(opt.font);
- static int lwidth = fm.width("8888") + 18;
+ static int lwidth = fm.width(QLatin1String("8888")) + 18;
QColor backgroundColor;
QColor textColor;
@@ -194,7 +197,10 @@ void BookmarkDelegate::paint(QPainter *painter, const QStyleOptionViewItem &opti
//
// painter->drawText(3, opt.rect.top() + fm.ascent() + fm.height() + 6, directory);
- QString lineText = index.data(BookmarkManager::LineText).toString().trimmed();
+ QString lineText = index.data(BookmarkManager::Note).toString().trimmed();
+ if (lineText.isEmpty())
+ lineText = index.data(BookmarkManager::LineText).toString().trimmed();
+
painter->drawText(6, opt.rect.top() + fm.ascent() + fm.height() + 6, lineText);
// Separator lines
@@ -233,6 +239,8 @@ void BookmarkView::contextMenuEvent(QContextMenuEvent *event)
QAction *moveDown = menu.addAction(tr("Move Down"));
QAction *remove = menu.addAction(tr("&Remove"));
QAction *removeAll = menu.addAction(tr("Remove All"));
+ QAction *editNote = menu.addAction(tr("Edit note"));
+
m_contextMenuIndex = indexAt(event->pos());
if (!m_contextMenuIndex.isValid()) {
moveUp->setEnabled(false);
@@ -251,6 +259,8 @@ void BookmarkView::contextMenuEvent(QContextMenuEvent *event)
this, SLOT(removeFromContextMenu()));
connect(removeAll, SIGNAL(triggered()),
this, SLOT(removeAll()));
+ connect(editNote, SIGNAL(triggered()),
+ m_manager, SLOT(editNote()));
menu.exec(mapToGlobal(event->pos()));
}
@@ -338,6 +348,12 @@ QItemSelectionModel *BookmarkManager::selectionModel() const
return m_selectionModel;
}
+bool BookmarkManager::hasBookmarkInPosition(const QString &fileName, int lineNumber)
+{
+ QFileInfo fi(fileName);
+ return findBookmark(fi.path(), fi.fileName(), lineNumber);
+}
+
QModelIndex BookmarkManager::index(int row, int column, const QModelIndex &parent) const
{
if (parent.isValid())
@@ -379,6 +395,8 @@ QVariant BookmarkManager::data(const QModelIndex &index, int role) const
return m_bookmarksList.at(index.row())->path();
else if (role == BookmarkManager::LineText)
return m_bookmarksList.at(index.row())->lineText();
+ else if (role == BookmarkManager::Note)
+ return m_bookmarksList.at(index.row())->note();
else if (role == Qt::ToolTipRole)
return QDir::toNativeSeparators(m_bookmarksList.at(index.row())->filePath());
@@ -643,6 +661,8 @@ void BookmarkManager::moveUp()
QModelIndex bottomRight = current.sibling(current.row(), 2);
emit dataChanged(topLeft, bottomRight);
selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear);
+
+ saveBookmarks();
}
void BookmarkManager::moveDown()
@@ -662,6 +682,35 @@ void BookmarkManager::moveDown()
QModelIndex bottomRight = current.sibling(row, 2);
emit dataChanged(topLeft, bottomRight);
selectionModel()->setCurrentIndex(current.sibling(row, 0), QItemSelectionModel::Select | QItemSelectionModel::Clear);
+
+ saveBookmarks();
+}
+
+void BookmarkManager::editNote(const QString &fileName, int lineNumber)
+{
+ QFileInfo fi(fileName);
+ Bookmark *b = findBookmark(fi.path(), fi.fileName(), lineNumber);
+ QModelIndex current = selectionModel()->currentIndex();
+ selectionModel()->setCurrentIndex(current.sibling(m_bookmarksList.indexOf(b), 0),
+ QItemSelectionModel::Select | QItemSelectionModel::Clear);
+
+ editNote();
+}
+
+void BookmarkManager::editNote()
+{
+ QModelIndex current = selectionModel()->currentIndex();
+ Bookmark *b = m_bookmarksList.at(current.row());
+
+ bool inputOk = false;
+ QString noteText = QInputDialog::getText(0, tr("Edit note"),
+ tr("Note text:"), QLineEdit::Normal,
+ b->note(), &inputOk);
+ if (inputOk) {
+ b->updateNote(noteText.replace(QLatin1Char('\t'), QLatin1Char(' ')));
+ emit dataChanged(current, current);
+ saveBookmarks();
+ }
}
/* Returns the bookmark at the given file and line number, or 0 if no such bookmark exists. */
@@ -703,15 +752,22 @@ void BookmarkManager::addBookmark(Bookmark *bookmark, bool userset)
/* Adds a new bookmark based on information parsed from the string. */
void BookmarkManager::addBookmark(const QString &s)
{
- int index2 = s.lastIndexOf(':');
- int index1 = s.indexOf(':');
- if (index2 != -1 || index1 != -1) {
+ // index3 is a frontier beetween note text and other bookmarks data
+ int index3 = s.lastIndexOf(QLatin1Char('\t'));
+ if (index3 < 0)
+ index3 = s.size();
+ int index2 = s.lastIndexOf(QLatin1Char(':'), index3 - 1);
+ int index1 = s.indexOf(QLatin1Char(':'));
+
+ if (index3 != -1 || index2 != -1 || index1 != -1) {
const QString &filePath = s.mid(index1+1, index2-index1-1);
- const int lineNumber = s.mid(index2 + 1).toInt();
+ const QString &note = s.mid(index3 + 1);
+ const int lineNumber = s.mid(index2 + 1, index3 - index2 - 1).toInt();
const QFileInfo fi(filePath);
if (!filePath.isEmpty() && !findBookmark(fi.path(), fi.fileName(), lineNumber)) {
Bookmark *b = new Bookmark(filePath, lineNumber, this);
+ b->setNote(note);
b->init();
addBookmark(b, false);
}
@@ -724,26 +780,40 @@ void BookmarkManager::addBookmark(const QString &s)
QString BookmarkManager::bookmarkToString(const Bookmark *b)
{
const QLatin1Char colon(':');
+ // Using \t as delimiter because any another symbol can be a part of note.
+ const QLatin1Char noteDelimiter('\t');
// Empty string was the name of the bookmark, which now is always ""
- return QLatin1String("") + colon + b->filePath() + colon + QString::number(b->lineNumber());
+ return QLatin1String("") + colon + b->filePath() +
+ colon + QString::number(b->lineNumber()) +
+ noteDelimiter + b->note();
}
/* Saves the bookmarks to the session settings. */
void BookmarkManager::saveBookmarks()
{
QStringList list;
- foreach (const FileNameBookmarksMap *bookmarksMap, m_bookmarksMap)
- foreach (const Bookmark *bookmark, *bookmarksMap)
+ foreach (const Bookmark *bookmark, m_bookmarksList)
list << bookmarkToString(bookmark);
- sessionManager()->setValue("Bookmarks", list);
+ sessionManager()->setValue(QLatin1String("Bookmarks"), list);
+}
+
+void BookmarkManager::operateTooltip(TextEditor::ITextEditor *textEditor, const QPoint &pos, Bookmark *mark)
+{
+ if (!mark)
+ return;
+
+ if (mark->note().isEmpty())
+ Utils::ToolTip::instance()->hide();
+ else
+ Utils::ToolTip::instance()->show(pos, Utils::TextContent(mark->note()), textEditor->widget());
}
/* Loads the bookmarks from the session settings. */
void BookmarkManager::loadBookmarks()
{
removeAllBookmarks();
- const QStringList &list = sessionManager()->value("Bookmarks").toStringList();
+ const QStringList &list = sessionManager()->value(QLatin1String("Bookmarks")).toStringList();
foreach (const QString &bookmarkString, list)
addBookmark(bookmarkString);
@@ -758,6 +828,16 @@ void BookmarkManager::handleBookmarkRequest(TextEditor::ITextEditor *textEditor,
toggleBookmark(textEditor->document()->fileName(), line);
}
+void BookmarkManager::handleBookmarkTooltipRequest(TextEditor::ITextEditor *textEditor, const QPoint &pos,
+ int line)
+{
+ if (textEditor->document()) {
+ const QFileInfo fi(textEditor->document()->fileName());
+ Bookmark *mark = findBookmark(fi.path(), fi.fileName(), line);
+ operateTooltip(textEditor, pos, mark);
+ }
+}
+
// BookmarkViewFactory
BookmarkViewFactory::BookmarkViewFactory(BookmarkManager *bm)
diff --git a/src/plugins/bookmarks/bookmarkmanager.h b/src/plugins/bookmarks/bookmarkmanager.h
index 24df537728..6bf8d6d7c1 100644
--- a/src/plugins/bookmarks/bookmarkmanager.h
+++ b/src/plugins/bookmarks/bookmarkmanager.h
@@ -85,11 +85,14 @@ public:
// this QItemSelectionModel is shared by all views
QItemSelectionModel *selectionModel() const;
+ bool hasBookmarkInPosition(const QString &fileName, int lineNumber);
+
enum Roles {
Filename = Qt::UserRole,
LineNumber = Qt::UserRole + 1,
Directory = Qt::UserRole + 2,
- LineText = Qt::UserRole + 3
+ LineText = Qt::UserRole + 3,
+ Note = Qt::UserRole + 4
};
public slots:
@@ -101,6 +104,8 @@ public slots:
void prev();
void moveUp();
void moveDown();
+ void editNote();
+ void editNote(const QString &fileName, int lineNumber);
bool gotoBookmark(Bookmark *bookmark);
signals:
@@ -113,6 +118,9 @@ private slots:
void handleBookmarkRequest(TextEditor::ITextEditor * textEditor,
int line,
TextEditor::ITextEditor::MarkRequestKind kind);
+ void handleBookmarkTooltipRequest(TextEditor::ITextEditor *textEditor,
+ const QPoint &pos,
+ int line);
private:
TextEditor::ITextEditor *currentTextEditor() const;
@@ -125,6 +133,7 @@ private:
void addBookmark(const QString &s);
static QString bookmarkToString(const Bookmark *b);
void saveBookmarks();
+ void operateTooltip(TextEditor::ITextEditor *textEditor, const QPoint &pos, Bookmark *mark);
typedef QMultiMap<QString, Bookmark *> FileNameBookmarksMap;
typedef QMap<QString, FileNameBookmarksMap *> DirectoryFileBookmarksMap;
diff --git a/src/plugins/bookmarks/bookmarks.qbs b/src/plugins/bookmarks/bookmarks.qbs
index 0fa44b7194..4601f5a50d 100644
--- a/src/plugins/bookmarks/bookmarks.qbs
+++ b/src/plugins/bookmarks/bookmarks.qbs
@@ -12,22 +12,15 @@ QtcPlugin {
Depends { name: "Find" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "bookmarksplugin.h",
+ "bookmark.cpp",
"bookmark.h",
+ "bookmarkmanager.cpp",
"bookmarkmanager.h",
+ "bookmarks.qrc",
"bookmarks_global.h",
"bookmarksplugin.cpp",
- "bookmark.cpp",
- "bookmarkmanager.cpp",
- "bookmarks.qrc",
+ "bookmarksplugin.h",
]
}
diff --git a/src/plugins/bookmarks/bookmarks_global.h b/src/plugins/bookmarks/bookmarks_global.h
index acbf4abd45..6aad21a696 100644
--- a/src/plugins/bookmarks/bookmarks_global.h
+++ b/src/plugins/bookmarks/bookmarks_global.h
@@ -36,6 +36,7 @@ namespace Constants {
const char BOOKMARKS_TOGGLE_ACTION[] = "Bookmarks.Toggle";
const char BOOKMARKS_MOVEUP_ACTION[] = "Bookmarks.MoveUp";
const char BOOKMARKS_MOVEDOWN_ACTION[] = "Bookmarks.MoveDown";
+const char BOOKMARKS_EDITNOTE_ACTION[] = "Bookmarks.EditNote";
const char BOOKMARKS_PREV_ACTION[] = "Bookmarks.Previous";
const char BOOKMARKS_NEXT_ACTION[] = "Bookmarks.Next";
const char BOOKMARKS_PREVDIR_ACTION[] = "Bookmarks.PreviousDirectory";
diff --git a/src/plugins/bookmarks/bookmarksplugin.cpp b/src/plugins/bookmarks/bookmarksplugin.cpp
index 02ea3ae4d6..a98656981e 100644
--- a/src/plugins/bookmarks/bookmarksplugin.cpp
+++ b/src/plugins/bookmarks/bookmarksplugin.cpp
@@ -108,6 +108,8 @@ bool BookmarksPlugin::initialize(const QStringList & /*arguments*/, QString *)
cmd = Core::ActionManager::registerAction(m_docNextAction, BOOKMARKS_NEXTDOC_ACTION, globalcontext);
mbm->addAction(cmd);
+ m_editNoteAction = new QAction(tr("Edit Bookmark Note"), this);
+
m_bookmarkManager = new BookmarkManager;
connect(m_toggleAction, SIGNAL(triggered()), m_bookmarkManager, SLOT(toggleBookmark()));
@@ -115,6 +117,7 @@ bool BookmarksPlugin::initialize(const QStringList & /*arguments*/, QString *)
connect(m_nextAction, SIGNAL(triggered()), m_bookmarkManager, SLOT(next()));
connect(m_docPrevAction, SIGNAL(triggered()), m_bookmarkManager, SLOT(prevInDocument()));
connect(m_docNextAction, SIGNAL(triggered()), m_bookmarkManager, SLOT(nextInDocument()));
+ connect(m_editNoteAction, SIGNAL(triggered()), this, SLOT(bookmarkEditNoteActionTriggered()));
connect(m_bookmarkManager, SIGNAL(updateActions(int)), this, SLOT(updateActions(int)));
updateActions(m_bookmarkManager->state());
addAutoReleasedObject(new BookmarkViewFactory(m_bookmarkManager));
@@ -163,6 +166,10 @@ void BookmarksPlugin::editorOpened(Core::IEditor *editor)
m_bookmarkManager,
SLOT(handleBookmarkRequest(TextEditor::ITextEditor*,int,
TextEditor::ITextEditor::MarkRequestKind)));
+ connect(editor,
+ SIGNAL(markTooltipRequested(TextEditor::ITextEditor*,QPoint,int)),
+ m_bookmarkManager,
+ SLOT(handleBookmarkTooltipRequest(TextEditor::ITextEditor*,QPoint,int)));
}
}
@@ -179,15 +186,21 @@ void BookmarksPlugin::requestContextMenu(TextEditor::ITextEditor *editor,
{
m_bookmarkMarginActionLineNumber = lineNumber;
m_bookmarkMarginActionFileName = editor->document()->fileName();
+
menu->addAction(m_bookmarkMarginAction);
+ if (m_bookmarkManager->hasBookmarkInPosition(m_bookmarkMarginActionFileName, m_bookmarkMarginActionLineNumber))
+ menu->addAction(m_editNoteAction);
}
void BookmarksPlugin::bookmarkMarginActionTriggered()
{
- m_bookmarkManager->toggleBookmark(
- m_bookmarkMarginActionFileName,
- m_bookmarkMarginActionLineNumber
- );
+ m_bookmarkManager->toggleBookmark(m_bookmarkMarginActionFileName,
+ m_bookmarkMarginActionLineNumber);
+}
+
+void BookmarksPlugin::bookmarkEditNoteActionTriggered()
+{
+ m_bookmarkManager->editNote(m_bookmarkMarginActionFileName, m_bookmarkMarginActionLineNumber);
}
Q_EXPORT_PLUGIN(BookmarksPlugin)
diff --git a/src/plugins/bookmarks/bookmarksplugin.h b/src/plugins/bookmarks/bookmarksplugin.h
index 7e48642faa..40ffc6e86e 100644
--- a/src/plugins/bookmarks/bookmarksplugin.h
+++ b/src/plugins/bookmarks/bookmarksplugin.h
@@ -76,6 +76,7 @@ private slots:
void requestContextMenu(TextEditor::ITextEditor *editor,
int lineNumber, QMenu *menu);
void bookmarkMarginActionTriggered();
+ void bookmarkEditNoteActionTriggered();
private:
static BookmarksPlugin *m_instance;
@@ -86,6 +87,7 @@ private:
QAction *m_nextAction;
QAction *m_docPrevAction;
QAction *m_docNextAction;
+ QAction *m_editNoteAction;
QAction *m_bookmarkMarginAction;
int m_bookmarkMarginActionLineNumber;
diff --git a/src/plugins/classview/classview.qbs b/src/plugins/classview/classview.qbs
index a7ad4a23c2..338cec83eb 100644
--- a/src/plugins/classview/classview.qbs
+++ b/src/plugins/classview/classview.qbs
@@ -13,36 +13,31 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
files: [
- "classviewplugin.h",
- "classviewnavigationwidgetfactory.h",
+ "classview.qrc",
"classviewconstants.h",
+ "classviewmanager.cpp",
+ "classviewmanager.h",
+ "classviewnavigationwidget.cpp",
"classviewnavigationwidget.h",
+ "classviewnavigationwidget.ui",
+ "classviewnavigationwidgetfactory.cpp",
+ "classviewnavigationwidgetfactory.h",
+ "classviewparser.cpp",
"classviewparser.h",
- "classviewmanager.h",
- "classviewsymbollocation.h",
- "classviewsymbolinformation.h",
+ "classviewparsertreeitem.cpp",
"classviewparsertreeitem.h",
- "classviewutils.h",
- "classviewtreeitemmodel.h",
"classviewplugin.cpp",
- "classviewnavigationwidgetfactory.cpp",
- "classviewnavigationwidget.cpp",
- "classviewparser.cpp",
- "classviewmanager.cpp",
- "classviewsymbollocation.cpp",
+ "classviewplugin.h",
"classviewsymbolinformation.cpp",
- "classviewparsertreeitem.cpp",
- "classviewutils.cpp",
+ "classviewsymbolinformation.h",
+ "classviewsymbollocation.cpp",
+ "classviewsymbollocation.h",
"classviewtreeitemmodel.cpp",
- "classviewnavigationwidget.ui",
- "classview.qrc",
+ "classviewtreeitemmodel.h",
+ "classviewutils.cpp",
+ "classviewutils.h",
]
}
diff --git a/src/plugins/classview/classviewmanager.cpp b/src/plugins/classview/classviewmanager.cpp
index df32d9e3c1..a5fb7920e5 100644
--- a/src/plugins/classview/classviewmanager.cpp
+++ b/src/plugins/classview/classviewmanager.cpp
@@ -308,8 +308,7 @@ void Manager::gotoLocations(const QList<QVariant> &list)
// what is open now?
if (Core::IEditor *editor = Core::EditorManager::currentEditor()) {
// get current file name
- Core::IDocument *document = editor->document();
- if (document)
+ if (Core::IDocument *document = editor->document())
fileName = document->fileName();
// if text file - what is current position?
diff --git a/src/plugins/classview/classviewmanager.h b/src/plugins/classview/classviewmanager.h
index adff069520..51a922d0a3 100644
--- a/src/plugins/classview/classviewmanager.h
+++ b/src/plugins/classview/classviewmanager.h
@@ -57,7 +57,7 @@ class Manager : public QObject
public:
/*!
- \brief
+ \brief Creates shared instance
\param parent Parent object
*/
explicit Manager(QObject *parent = 0);
@@ -132,8 +132,8 @@ public slots:
/*!
\brief Open text editor for file \a fileName on line \a lineNumber and column \a column.
\param fileName File which has to be open
- \param lineNumber Line
- \param column Column
+ \param line Line number, 1-based
+ \param column Column, 1-based
*/
void gotoLocation(const QString &fileName, int line = 0, int column = 0);
@@ -227,7 +227,7 @@ protected:
/*!
\brief Set internal Manager state.
- \param true if Manager has to be enabled, false otherwise
+ \param state true if Manager has to be enabled, false otherwise
\sa state, stateChanged
*/
void setState(bool state);
diff --git a/src/plugins/classview/classviewnavigationwidget.h b/src/plugins/classview/classviewnavigationwidget.h
index 21f3b624ce..9b64aec103 100644
--- a/src/plugins/classview/classviewnavigationwidget.h
+++ b/src/plugins/classview/classviewnavigationwidget.h
@@ -112,7 +112,7 @@ public slots:
/*!
\brief Receive a new data for the tree
- \param Result - root item
+ \param result Pointer to the Class View model root item, method does nothing if null passed
*/
void onDataUpdate(QSharedPointer<QStandardItem> result);
@@ -125,8 +125,8 @@ public slots:
protected:
/*!
\brief Fetch data for expanded items - to be sure that content will exist
- \param item
- \param target
+ \param item - does nothing if null
+ \param target - does nothing if null
*/
void fetchExpandedItems(QStandardItem *item, const QStandardItem *target) const;
diff --git a/src/plugins/classview/classviewparser.cpp b/src/plugins/classview/classviewparser.cpp
index 2ca486eee2..9023de9449 100644
--- a/src/plugins/classview/classviewparser.cpp
+++ b/src/plugins/classview/classviewparser.cpp
@@ -188,7 +188,7 @@ ParserTreeItem::ConstPtr Parser::findItemByRoot(const QStandardItem *item, bool
// go item by item to the root
QList<const QStandardItem *> uiList;
const QStandardItem *cur = item;
- while(cur) {
+ while (cur) {
uiList.append(cur);
cur = cur->parent();
}
@@ -201,7 +201,7 @@ ParserTreeItem::ConstPtr Parser::findItemByRoot(const QStandardItem *item, bool
// using internal root - search correct item
ParserTreeItem::ConstPtr internal = d->rootItem;
- while(uiList.count() > 0) {
+ while (uiList.count() > 0) {
cur = uiList.last();
uiList.removeLast();
const SymbolInformation &inf = Utils::symbolInformationFromItem(cur);
@@ -223,7 +223,7 @@ ParserTreeItem::ConstPtr Parser::parse()
// check all projects
QList<ProjectExplorer::Project *> projects = getProjectList();
- foreach(const ProjectExplorer::Project *prj, projects) {
+ foreach (const ProjectExplorer::Project *prj, projects) {
if (!prj)
continue;
@@ -355,7 +355,7 @@ ParserTreeItem::Ptr Parser::createFlatTree(const QStringList &projectList)
QReadLocker locker(&d->prjLocker);
ParserTreeItem::Ptr item(new ParserTreeItem());
- foreach(const QString &project, projectList) {
+ foreach (const QString &project, projectList) {
if (!d->cachedPrjTrees.contains(project))
continue;
ParserTreeItem::ConstPtr list = d->cachedPrjTrees[project];
@@ -371,7 +371,7 @@ ParserTreeItem::Ptr Parser::getParseProjectTree(const QStringList &fileList,
//! changed files only (old edition), and add curent editions
ParserTreeItem::Ptr item(new ParserTreeItem());
unsigned revision = 0;
- foreach(const QString &file, fileList) {
+ foreach (const QString &file, fileList) {
// ? locker for document?..
const CPlusPlus::Document::Ptr &doc = d->document(file);
if (doc.isNull())
@@ -406,7 +406,7 @@ ParserTreeItem::Ptr Parser::getCachedOrParseProjectTree(const QStringList &fileL
if (!projectId.isEmpty() && d->cachedPrjTrees.contains(projectId)) {
// calculate project's revision
unsigned revision = 0;
- foreach(const QString &file, fileList) {
+ foreach (const QString &file, fileList) {
const CPlusPlus::Document::Ptr &doc = d->document(file);
if (doc.isNull())
continue;
@@ -610,14 +610,14 @@ QStringList Parser::projectNodeFileList(const ProjectExplorer::FolderNode *node)
QList<ProjectExplorer::FileNode *> fileNodes = node->fileNodes();
QList<ProjectExplorer::FolderNode *> subFolderNodes = node->subFolderNodes();
- foreach(const ProjectExplorer::FileNode *file, fileNodes) {
+ foreach (const ProjectExplorer::FileNode *file, fileNodes) {
if (file->isGenerated())
continue;
list << file->path();
}
- foreach(const ProjectExplorer::FolderNode *folder, subFolderNodes) {
+ foreach (const ProjectExplorer::FolderNode *folder, subFolderNodes) {
if (folder->nodeType() != ProjectExplorer::FolderNodeType
&& folder->nodeType() != ProjectExplorer::VirtualFolderNodeType)
continue;
@@ -654,7 +654,7 @@ QStringList Parser::addProjectNode(const ParserTreeItem::Ptr &item,
// subnodes
QList<ProjectExplorer::ProjectNode *> projectNodes = node->subProjectNodes();
- foreach(const ProjectExplorer::ProjectNode *project, projectNodes) {
+ foreach (const ProjectExplorer::ProjectNode *project, projectNodes) {
ParserTreeItem::Ptr itemPrj(new ParserTreeItem());
SymbolInformation information(project->displayName(), project->path());
diff --git a/src/plugins/classview/classviewparsertreeitem.cpp b/src/plugins/classview/classviewparsertreeitem.cpp
index 52adc77931..5c73e263b4 100644
--- a/src/plugins/classview/classviewparsertreeitem.cpp
+++ b/src/plugins/classview/classviewparsertreeitem.cpp
@@ -198,7 +198,7 @@ void ParserTreeItem::add(const ParserTreeItem::ConstPtr &target)
target->d->symbolInformations.constBegin();
QHash<SymbolInformation, ParserTreeItem::Ptr>::const_iterator end =
target->d->symbolInformations.constEnd();
- while(cur != end) {
+ while (cur != end) {
const SymbolInformation &inf = cur.key();
const ParserTreeItem::Ptr &targetChild = cur.value();
if (d->symbolInformations.contains(inf)) {
@@ -231,7 +231,7 @@ void ParserTreeItem::subtract(const ParserTreeItem::ConstPtr &target)
target->d->symbolInformations.constBegin();
QHash<SymbolInformation, ParserTreeItem::Ptr>::const_iterator end =
target->d->symbolInformations.constEnd();
- while(cur != end) {
+ while (cur != end) {
const SymbolInformation &inf = cur.key();
if (d->symbolInformations.contains(inf)) {
// this item has the same child node
@@ -258,7 +258,7 @@ void ParserTreeItem::convertTo(QStandardItem *item, bool recursive) const
d->symbolInformations.constBegin();
QHash<SymbolInformation, ParserTreeItem::Ptr>::const_iterator endHash =
d->symbolInformations.constEnd();
- while(curHash != endHash) {
+ while (curHash != endHash) {
map.insert(curHash.key(), curHash.value());
++curHash;
}
@@ -266,7 +266,7 @@ void ParserTreeItem::convertTo(QStandardItem *item, bool recursive) const
// add to item
QMap<SymbolInformation, ParserTreeItem::Ptr>::const_iterator cur = map.constBegin();
QMap<SymbolInformation, ParserTreeItem::Ptr>::const_iterator end = map.constEnd();
- while(cur != end) {
+ while (cur != end) {
const SymbolInformation &inf = cur.key();
ParserTreeItem::Ptr ptr = cur.value();
@@ -310,7 +310,7 @@ bool ParserTreeItem::canFetchMore(QStandardItem *item) const
d->symbolInformations.constBegin();
QHash<SymbolInformation, ParserTreeItem::Ptr>::const_iterator endHash =
d->symbolInformations.constEnd();
- while(curHash != endHash) {
+ while (curHash != endHash) {
const ParserTreeItem::Ptr &child = curHash.value();
if (!child.isNull()) {
internalChildren += child->childCount();
@@ -321,7 +321,7 @@ bool ParserTreeItem::canFetchMore(QStandardItem *item) const
++curHash;
}
- if(storedChildren < internalChildren)
+ if (storedChildren < internalChildren)
return true;
return false;
@@ -359,7 +359,7 @@ void ParserTreeItem::debugDump(int ident) const
d->symbolInformations.constBegin();
QHash<SymbolInformation, ParserTreeItem::Ptr>::const_iterator endHash =
d->symbolInformations.constEnd();
- while(curHash != endHash) {
+ while (curHash != endHash) {
const SymbolInformation &inf = curHash.key();
qDebug() << QString(2*ident, QLatin1Char(' ')) << inf.iconType() << inf.name() << inf.type()
<< curHash.value().isNull();
diff --git a/src/plugins/classview/classviewsymbolinformation.h b/src/plugins/classview/classviewsymbolinformation.h
index c3be26c857..77b316320f 100644
--- a/src/plugins/classview/classviewsymbolinformation.h
+++ b/src/plugins/classview/classviewsymbolinformation.h
@@ -40,7 +40,7 @@ namespace Internal {
/*!
\class SymbolInformation
- \brief
+ \brief Provides name, type and icon for single item in Class View tree
*/
class SymbolInformation
diff --git a/src/plugins/classview/classviewutils.cpp b/src/plugins/classview/classviewutils.cpp
index ceb6326139..70d7e12f01 100644
--- a/src/plugins/classview/classviewutils.cpp
+++ b/src/plugins/classview/classviewutils.cpp
@@ -72,7 +72,7 @@ Utils::Utils()
QList<QVariant> Utils::locationsToRole(const QSet<SymbolLocation> &locations)
{
QList<QVariant> locationsVar;
- foreach(const SymbolLocation &loc, locations)
+ foreach (const SymbolLocation &loc, locations)
locationsVar.append(QVariant::fromValue(loc));
return locationsVar;
@@ -81,10 +81,9 @@ QList<QVariant> Utils::locationsToRole(const QSet<SymbolLocation> &locations)
QSet<SymbolLocation> Utils::roleToLocations(const QList<QVariant> &locationsVar)
{
QSet<SymbolLocation> locations;
- foreach(const QVariant &loc, locationsVar) {
- if (loc.canConvert<SymbolLocation>()) {
+ foreach (const QVariant &loc, locationsVar) {
+ if (loc.canConvert<SymbolLocation>())
locations.insert(loc.value<SymbolLocation>());
- }
}
return locations;
diff --git a/src/plugins/classview/classviewutils.h b/src/plugins/classview/classviewutils.h
index 6d216f585e..78bc793a2a 100644
--- a/src/plugins/classview/classviewutils.h
+++ b/src/plugins/classview/classviewutils.h
@@ -82,7 +82,7 @@ public:
/*!
\brief Set symbol information to the \a QStandardItem
- \param information
+ \param information Provides name, type and icon
\param item Item
\return Filled item
*/
diff --git a/src/plugins/clearcase/ClearCase.pluginspec.in b/src/plugins/clearcase/ClearCase.pluginspec.in
index d5babd63ea..f85625da1d 100644
--- a/src/plugins/clearcase/ClearCase.pluginspec.in
+++ b/src/plugins/clearcase/ClearCase.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"ClearCase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" experimental=\"true\">
+<plugin name=\"ClearCase\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
<vendor>AudioCodes</vendor>
<copyright>(C) 2013 AudioCodes Ltd.</copyright>
<license>
diff --git a/src/plugins/clearcase/annotationhighlighter.h b/src/plugins/clearcase/annotationhighlighter.h
index 14b9069f8c..9792e2492e 100644
--- a/src/plugins/clearcase/annotationhighlighter.h
+++ b/src/plugins/clearcase/annotationhighlighter.h
@@ -45,7 +45,7 @@ public:
QTextDocument *document = 0);
private:
- virtual QString changeNumber(const QString &block) const;
+ QString changeNumber(const QString &block) const;
const QChar m_separator;
};
diff --git a/src/plugins/clearcase/clearcase.pro b/src/plugins/clearcase/clearcase.pro
index c40f5475df..d0ead945bf 100644
--- a/src/plugins/clearcase/clearcase.pro
+++ b/src/plugins/clearcase/clearcase.pro
@@ -5,8 +5,6 @@ TARGET = ClearCase
include(../../qtcreatorplugin.pri)
include(clearcase_dependencies.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
-
HEADERS += activityselector.h \
annotationhighlighter.h \
checkoutdialog.h \
diff --git a/src/plugins/clearcase/clearcase.qbs b/src/plugins/clearcase/clearcase.qbs
index 2a3776d6d1..2264d7d47c 100644
--- a/src/plugins/clearcase/clearcase.qbs
+++ b/src/plugins/clearcase/clearcase.qbs
@@ -16,15 +16,6 @@ QtcPlugin {
Depends { name: "VcsBase" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_NO_CAST_FROM_ASCII"])
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
"activityselector.cpp",
"activityselector.h",
diff --git a/src/plugins/clearcase/clearcasecontrol.cpp b/src/plugins/clearcase/clearcasecontrol.cpp
index b6855a00df..785797718f 100644
--- a/src/plugins/clearcase/clearcasecontrol.cpp
+++ b/src/plugins/clearcase/clearcasecontrol.cpp
@@ -52,7 +52,7 @@ QString ClearCaseControl::displayName() const
Core::Id ClearCaseControl::id() const
{
- return ClearCase::Constants::VCS_ID_CLEARCASE;
+ return Core::Id(ClearCase::Constants::VCS_ID_CLEARCASE);
}
bool ClearCaseControl::isConfigured() const
@@ -144,6 +144,11 @@ QString ClearCaseControl::vcsMakeWritableText() const
return tr("&Hijack");
}
+QString ClearCaseControl::vcsTopic(const QString &directory)
+{
+ return m_plugin->ccGetView(directory).name;
+}
+
void ClearCaseControl::emitRepositoryChanged(const QString &s)
{
emit repositoryChanged(s);
diff --git a/src/plugins/clearcase/clearcasecontrol.h b/src/plugins/clearcase/clearcasecontrol.h
index fa81f3918c..f921518464 100644
--- a/src/plugins/clearcase/clearcasecontrol.h
+++ b/src/plugins/clearcase/clearcasecontrol.h
@@ -70,6 +70,7 @@ public:
QString vcsOpenText() const;
QString vcsMakeWritableText() const;
+ QString vcsTopic(const QString &directory);
void emitRepositoryChanged(const QString &);
void emitFilesChanged(const QStringList &);
diff --git a/src/plugins/clearcase/clearcaseeditor.cpp b/src/plugins/clearcase/clearcaseeditor.cpp
index dd03eb9220..42cdebe2f3 100644
--- a/src/plugins/clearcase/clearcaseeditor.cpp
+++ b/src/plugins/clearcase/clearcaseeditor.cpp
@@ -51,6 +51,13 @@ ClearCaseEditor::ClearCaseEditor(const VcsBase::VcsBaseEditorParameters *type,
m_versionNumberPattern(QLatin1String("[\\\\/]main[\\\\/][^ \t\n\"]*"))
{
QTC_ASSERT(m_versionNumberPattern.isValid(), return);
+ // Diff formats:
+ // "+++ D:\depot\...\mainwindow.cpp@@\main\3" (versioned)
+ // "+++ D:\depot\...\mainwindow.cpp[TAB]Sun May 01 14:22:37 2011" (local)
+ QRegExp diffFilePattern(QLatin1String("^[-+]{3} ([^\\t]+)(?:@@|\\t)"));
+ diffFilePattern.setMinimal(true);
+ setDiffFilePattern(diffFilePattern);
+ setLogEntryPattern(QRegExp(QLatin1String("version \"([^\"]+)\"")));
setAnnotateRevisionTextFormat(tr("Annotate version \"%1\""));
}
@@ -87,43 +94,8 @@ QString ClearCaseEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-/*
- Diff header format (on Windows, native separators are used after the @@)
---- main.cpp@@\main\2
-+++ main.cpp@@\main\1
-@@ -6,6 +6,5 @@
-*/
-VcsBase::DiffHighlighter *ClearCaseEditor::createDiffHighlighter() const
-{
- const QRegExp filePattern(QLatin1String("^[-+][-+][-+] "));
- QTC_CHECK(filePattern.isValid());
- return new VcsBase::DiffHighlighter(filePattern);
-}
-
VcsBase::BaseAnnotationHighlighter *ClearCaseEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new ClearCaseAnnotationHighlighter(changes, bg);
}
-
-QString ClearCaseEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
-{
- // "+++ D:\depot\...\mainwindow.cpp@@\main\3"
- // "+++ D:\depot\...\mainwindow.cpp[TAB]Sun May 01 14:22:37 2011"
- // Go back chunks
- const QString diffIndicator = QLatin1String("+++ ");
- for (QTextBlock block = inBlock; block.isValid() ; block = block.previous()) {
- QString diffFileName = block.text();
- if (diffFileName.startsWith(diffIndicator)) {
- diffFileName.remove(0, diffIndicator.size());
- const int tabIndex = diffFileName.indexOf(QRegExp(QLatin1String("@@|\t")));
- if (tabIndex != -1)
- diffFileName.truncate(tabIndex);
- const QString rc = findDiffFile(diffFileName);
- if (ClearCase::Constants::debug)
- qDebug() << Q_FUNC_INFO << diffFileName << rc << source();
- return rc;
- }
- }
- return QString();
-}
diff --git a/src/plugins/clearcase/clearcaseeditor.h b/src/plugins/clearcase/clearcaseeditor.h
index 1699884986..c9dd8c88e3 100644
--- a/src/plugins/clearcase/clearcaseeditor.h
+++ b/src/plugins/clearcase/clearcaseeditor.h
@@ -49,11 +49,9 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::DiffHighlighter *createDiffHighlighter() const;
VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- QString fileNameFromDiffSpecification(const QTextBlock &diffFileName) const;
- mutable QRegExp m_versionNumberPattern;
+ QRegExp m_versionNumberPattern;
};
} // namespace Internal
diff --git a/src/plugins/clearcase/clearcaseplugin.cpp b/src/plugins/clearcase/clearcaseplugin.cpp
index 5122ae8c45..5d71a3698c 100644
--- a/src/plugins/clearcase/clearcaseplugin.cpp
+++ b/src/plugins/clearcase/clearcaseplugin.cpp
@@ -58,6 +58,7 @@
#include <utils/synchronousprocess.h>
#include <utils/parameteraction.h>
#include <utils/fileutils.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/runextensions.h>
#include <vcsbase/basevcseditorfactory.h>
@@ -95,7 +96,9 @@
#include <QVariant>
#include <QVBoxLayout>
#include <QXmlStreamReader>
-
+#ifdef WITH_TESTS
+#include <QTest>
+#endif
namespace ClearCase {
namespace Internal {
@@ -152,16 +155,20 @@ static inline const VcsBase::VcsBaseEditorParameters *findType(int ie)
static inline QString debugCodec(const QTextCodec *c)
{
- return c ? QString::fromAscii(c->name()) : QString::fromAscii("Null codec");
+ return c ? QString::fromLatin1(c->name()) : QString::fromLatin1("Null codec");
}
// ------------- ClearCasePlugin
ClearCasePlugin *ClearCasePlugin::m_clearcasePluginInstance = 0;
+ViewData::ViewData() :
+ isDynamic(false),
+ isUcm(false)
+{
+}
+
ClearCasePlugin::ClearCasePlugin() :
VcsBase::VcsBasePlugin(QLatin1String(ClearCase::Constants::CLEARCASECHECKINEDITOR_ID)),
- m_isDynamic(false),
- m_isUcm(false),
m_commandLocator(0),
m_checkOutAction(0),
m_checkInCurrentAction(0),
@@ -233,9 +240,7 @@ QString ClearCasePlugin::findTopLevel(const QString &directory) const
return topLevel;
// Dynamic view
- bool isDynamic;
- ccGetView(directory, &isDynamic);
- if (isDynamic) {
+ if (ccGetView(directory).isDynamic) {
QDir dir(directory);
// Go up to one level before root
QDir outer = dir;
@@ -244,7 +249,7 @@ QString ClearCasePlugin::findTopLevel(const QString &directory) const
dir.cdUp();
topLevel = dir.path(); // M:/View_Name
dir.cdUp(); // Z:/ (dynamic view with assigned letter)
- if (!ccGetView(dir.path()).isEmpty())
+ if (!ccGetView(dir.path()).name.isEmpty())
topLevel = dir.path();
}
@@ -255,7 +260,8 @@ static const VcsBase::VcsBaseSubmitEditorParameters submitParameters = {
ClearCase::Constants::CLEARCASE_SUBMIT_MIMETYPE,
ClearCase::Constants::CLEARCASECHECKINEDITOR_ID,
ClearCase::Constants::CLEARCASECHECKINEDITOR_DISPLAY_NAME,
- ClearCase::Constants::CLEARCASECHECKINEDITOR
+ ClearCase::Constants::CLEARCASECHECKINEDITOR,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *errorMessage)
@@ -297,7 +303,7 @@ bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *er
const QString description = QLatin1String("ClearCase");
const QString prefix = QLatin1String("cc");
// register cc prefix in Locator
- m_commandLocator = new Locator::CommandLocator(prefix, description, prefix);
+ m_commandLocator = new Locator::CommandLocator("cc", description, prefix);
addAutoReleasedObject(m_commandLocator);
//register actions
@@ -593,12 +599,12 @@ void ClearCasePlugin::updateStatusActions()
m_checkOutAction->setEnabled(hasFile && (fileStatus.status & (FileStatus::CheckedIn | FileStatus::Hijacked)));
m_undoCheckOutAction->setEnabled(hasFile && (fileStatus.status & FileStatus::CheckedOut));
- m_undoHijackAction->setEnabled(!m_isDynamic && hasFile && (fileStatus.status & FileStatus::Hijacked));
+ m_undoHijackAction->setEnabled(!m_viewData.isDynamic && hasFile && (fileStatus.status & FileStatus::Hijacked));
m_checkInCurrentAction->setEnabled(hasFile && (fileStatus.status & FileStatus::CheckedOut));
m_addFileAction->setEnabled(hasFile && (fileStatus.status & FileStatus::NotManaged));
- m_checkInActivityAction->setEnabled(m_isUcm);
- m_diffActivityAction->setEnabled(m_isUcm);
+ m_checkInActivityAction->setEnabled(m_viewData.isUcm);
+ m_diffActivityAction->setEnabled(m_viewData.isUcm);
}
void ClearCasePlugin::updateActions(VcsBase::VcsBasePlugin::ActionState as)
@@ -613,7 +619,7 @@ void ClearCasePlugin::updateActions(VcsBase::VcsBasePlugin::ActionState as)
if (hasTopLevel)
m_topLevel = state.topLevel();
- m_updateViewAction->setParameter(m_isDynamic ? QString() : m_view);
+ m_updateViewAction->setParameter(m_viewData.isDynamic ? QString() : m_viewData.name);
const QString fileName = state.currentFileName();
m_checkOutAction->setParameter(fileName);
@@ -714,11 +720,10 @@ bool ClearCasePlugin::vcsUndoHijack(const QString &workingDir, const QString &fi
QStringList args(QLatin1String("update"));
args << QLatin1String(keep ? "-rename" : "-overwrite");
args << QLatin1String("-log");
-#ifdef Q_OS_WIN32
- args << QLatin1String("NUL");
-#else
+ if (Utils::HostOsInfo::isWindowsHost())
+ args << QLatin1String("NUL");
+ else
args << QLatin1String("/dev/null");
-#endif
args << QDir::toNativeSeparators(fileName);
const ClearCaseResponse response =
@@ -937,6 +942,7 @@ void ClearCasePlugin::startCheckInAll()
if (iterator.value().status == FileStatus::CheckedOut)
files.append(QDir::toNativeSeparators(iterator.key()));
}
+ files.sort();
startCheckIn(topLevel, files);
}
@@ -973,6 +979,7 @@ void ClearCasePlugin::startCheckInActivity()
last = file;
}
}
+ files.sort();
startCheckIn(topLevel, files);
}
@@ -1009,10 +1016,10 @@ void ClearCasePlugin::startCheckIn(const QString &workingDir, const QStringList
m_checkInMessageFileName = saver.fileName();
m_checkInView = workingDir;
// Create a submit editor and set file list
- ClearCaseSubmitEditor *editor = openClearCaseSubmitEditor(m_checkInMessageFileName, m_isUcm);
+ ClearCaseSubmitEditor *editor = openClearCaseSubmitEditor(m_checkInMessageFileName, m_viewData.isUcm);
editor->setStatusList(files);
- if (m_isUcm && (files.size() == 1)) {
+ if (m_viewData.isUcm && (files.size() == 1)) {
QString activity = ccGetFileActivity(workingDir, files.first());
editor->submitEditorWidget()->setActivity(activity);
}
@@ -1072,9 +1079,9 @@ void ClearCasePlugin::history(const QString &workingDir,
void ClearCasePlugin::viewStatus()
{
- if (m_view.isEmpty())
- m_view = ccGetView(m_topLevel);
- QTC_ASSERT(!m_view.isEmpty() && !m_settings.disableIndexer, return);
+ if (m_viewData.name.isEmpty())
+ m_viewData = ccGetView(m_topLevel);
+ QTC_ASSERT(!m_viewData.name.isEmpty() && !m_settings.disableIndexer, return);
VcsBase::VcsBaseOutputWindow *outputwindow = VcsBase::VcsBaseOutputWindow::instance();
outputwindow->appendCommand(QLatin1String("Indexed files status (C=Checked Out, H=Hijacked, ?=Missing)"));
bool anymod = false;
@@ -1261,7 +1268,7 @@ Core::IEditor *ClearCasePlugin::showOutputInEditor(const QString& title, const Q
{
const VcsBase::VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
- const Core::Id id = params->id;
+ const Core::Id id = Core::Id(QByteArray(params->id));
if (ClearCase::Constants::debug)
qDebug() << "ClearCasePlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
@@ -1318,7 +1325,7 @@ bool ClearCasePlugin::vcsOpen(const QString &workingDir, const QString &fileName
const QString file = QDir::toNativeSeparators(relFile);
const QString title = QString::fromLatin1("Checkout %1").arg(file);
- CheckOutDialog coDialog(title, m_isUcm);
+ CheckOutDialog coDialog(title, m_viewData.isUcm);
if (!m_settings.disableIndexer &&
(fi.isWritable() || m_statusMap->value(relFile).status == FileStatus::Unknown))
@@ -1328,11 +1335,11 @@ bool ClearCasePlugin::vcsOpen(const QString &workingDir, const QString &fileName
return true;
}
// Only snapshot views can have hijacked files
- bool isHijacked = (!m_isDynamic && (m_statusMap->value(relFile).status & FileStatus::Hijacked));
+ bool isHijacked = (!m_viewData.isDynamic && (m_statusMap->value(relFile).status & FileStatus::Hijacked));
if (!isHijacked)
coDialog.hideHijack();
if (coDialog.exec() == QDialog::Accepted) {
- if (m_isUcm && !vcsSetActivity(topLevel, title, coDialog.activity()))
+ if (m_viewData.isUcm && !vcsSetActivity(topLevel, title, coDialog.activity()))
return false;
Core::FileChangeBlocker fcb(absPath);
@@ -1475,7 +1482,7 @@ bool ClearCasePlugin::ccFileOp(const QString &workingDir, const QString &title,
fileOpDlg.setWindowTitle(title);
verticalLayout = new QVBoxLayout(&fileOpDlg);
- if (m_isUcm) {
+ if (m_viewData.isUcm) {
actSelector = new ActivitySelector;
verticalLayout->addWidget(actSelector);
}
@@ -1501,7 +1508,7 @@ bool ClearCasePlugin::ccFileOp(const QString &workingDir, const QString &title,
return true;
QString comment = commentEdit->toPlainText();
- if (m_isUcm && actSelector->changed())
+ if (m_viewData.isUcm && actSelector->changed())
vcsSetActivity(workingDir, fileOpDlg.windowTitle(), actSelector->activity());
QString dirName = QDir::toNativeSeparators(QFileInfo(workingDir, fileName).absolutePath());
@@ -1708,25 +1715,22 @@ bool ClearCasePlugin::ccCheckUcm(const QString &viewname, const QString &working
return QRegExp(QLatin1String("(^|\\n)ucm\\n")).indexIn(catcsData) != -1;
}
-QString ClearCasePlugin::ccGetView(const QString &workingDir, bool *isDynamic, bool *isUcm) const
+ViewData ClearCasePlugin::ccGetView(const QString &workingDir) const
{
- QStringList args(QLatin1String("lsview"));
- args << QLatin1String("-cview");
- QString data = runCleartoolSync(workingDir, args);
- if (data.isEmpty()) {
- if (isDynamic)
- *isDynamic = false;
- return QString();
- }
- if (isDynamic)
- *isDynamic = !data.isEmpty() && (data.at(0) == QLatin1Char('*'));
+ static QHash<QString, ViewData> viewCache;
- QString viewname = data.mid(2, data.indexOf(QLatin1Char(' '), 2) - 2);
- if (isUcm)
- *isUcm = ccCheckUcm(viewname, workingDir);
-
- return viewname;
+ bool inCache = viewCache.contains(workingDir);
+ ViewData &res = viewCache[workingDir];
+ if (!inCache) {
+ QStringList args(QLatin1String("lsview"));
+ args << QLatin1String("-cview");
+ QString data = runCleartoolSync(workingDir, args);
+ res.isDynamic = !data.isEmpty() && (data.at(0) == QLatin1Char('*'));
+ res.name = data.mid(2, data.indexOf(QLatin1Char(' '), 2) - 2);
+ res.isUcm = ccCheckUcm(res.name, workingDir);
+ }
+ return res;
}
void ClearCasePlugin::updateStreamAndView()
@@ -1739,15 +1743,15 @@ void ClearCasePlugin::updateStreamAndView()
QRegExp intStreamExp(QLatin1String("stream:([^@]*)"));
if (intStreamExp.indexIn(sresponse.mid(tabPos + 1)) != -1)
m_intStream = intStreamExp.cap(1);
- m_view = ccGetView(m_topLevel, &m_isDynamic, &m_isUcm);
- m_updateViewAction->setParameter(m_isDynamic ? QString() : m_view);
+ m_viewData = ccGetView(m_topLevel);
+ m_updateViewAction->setParameter(m_viewData.isDynamic ? QString() : m_viewData.name);
}
void ClearCasePlugin::projectChanged(ProjectExplorer::Project *project)
{
- if (m_view == ccGetView(m_topLevel)) // New project on same view as old project
+ if (m_viewData.name == ccGetView(m_topLevel).name) // New project on same view as old project
return;
- m_view.clear();
+ m_viewData = ViewData();
m_stream.clear();
m_intStream.clear();
disconnect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
@@ -1760,14 +1764,12 @@ void ClearCasePlugin::projectChanged(ProjectExplorer::Project *project)
return;
connect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(syncSlot()));
updateStreamAndView();
- if (m_view.isEmpty())
+ if (m_viewData.name.isEmpty())
return;
- Core::EditorManager *editorManager = Core::ICore::editorManager();
- editorManager->setWindowTitleAddition(editorManager->windowTitleAddition() + QLatin1String(" - ") + m_view);
updateIndex();
}
if ( ClearCase::Constants::debug )
- qDebug() << "stream: " << m_stream << "; intStream: " << m_intStream << "view: " << m_view;
+ qDebug() << "stream: " << m_stream << "; intStream: " << m_intStream << "view: " << m_viewData.name;
}
void ClearCasePlugin::tasksFinished(const QString &type)
@@ -1943,6 +1945,38 @@ void ClearCasePlugin::sync(QFutureInterface<void> &future, QString topLevel, QSt
ccSync.run(future, topLevel, files);
}
+#ifdef WITH_TESTS
+void ClearCasePlugin::testDiffFileResolving_data()
+{
+ QTest::addColumn<QByteArray>("header");
+ QTest::addColumn<QByteArray>("fileName");
+
+ QTest::newRow("Modified") << QByteArray(
+ "--- src/plugins/clearcase/clearcaseeditor.cpp@@/main/1\t2013-01-20 23:45:48.549615210 +0200\n"
+ "+++ src/plugins/clearcase/clearcaseeditor.cpp@@/main/2\t2013-01-20 23:45:53.217604679 +0200\n"
+ "@@ -58,6 +58,10 @@\n\n")
+ << QByteArray("src/plugins/clearcase/clearcaseeditor.cpp");
+}
+
+void ClearCasePlugin::testDiffFileResolving()
+{
+ ClearCaseEditor editor(editorParameters + 3, 0);
+ editor.testDiffFileResolving();
+}
+
+void ClearCasePlugin::testLogResolving()
+{
+ QByteArray data(
+ "13-Sep.17:41 user1 create version \"src/plugins/clearcase/clearcaseeditor.h@@/main/branch1/branch2/9\" (baseline1, baseline2, ...)\n"
+ "22-Aug.14:13 user2 create version \"src/plugins/clearcase/clearcaseeditor.h@@/main/branch1/branch2/8\" (baseline3, baseline4, ...)\n"
+ );
+ ClearCaseEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data,
+ "src/plugins/clearcase/clearcaseeditor.h@@/main/branch1/branch2/9",
+ "src/plugins/clearcase/clearcaseeditor.h@@/main/branch1/branch2/8");
+}
+#endif
+
} // namespace Internal
} // namespace ClearCase
diff --git a/src/plugins/clearcase/clearcaseplugin.h b/src/plugins/clearcase/clearcaseplugin.h
index 111316f9b7..823f0a103a 100644
--- a/src/plugins/clearcase/clearcaseplugin.h
+++ b/src/plugins/clearcase/clearcaseplugin.h
@@ -99,6 +99,16 @@ public:
typedef QHash<QString, FileStatus> StatusMap;
+class ViewData
+{
+public:
+ ViewData();
+
+ QString name;
+ bool isDynamic;
+ bool isUcm;
+};
+
class ClearCasePlugin : public VcsBase::VcsBasePlugin
{
Q_OBJECT
@@ -141,12 +151,13 @@ public:
QList<QStringPair> activities(int *current = 0) const;
QString ccGetPredecessor(const QString &version) const;
QStringList ccGetActiveVobs() const;
+ ViewData ccGetView(const QString &workingDir) const;
bool ccFileOp(const QString &workingDir, const QString &title, const QStringList &args,
const QString &fileName, const QString &file2 = QString());
FileStatus vcsStatus(const QString &file) const;
- QString currentView() const { return m_view; }
+ QString currentView() const { return m_viewData.name; }
void refreshActivities();
- inline bool isUcm() const { return m_isUcm; }
+ inline bool isUcm() const { return m_viewData.isUcm; }
void setStatus(const QString &file, FileStatus::Status status, bool update = true);
bool ccCheckUcm(const QString &viewname, const QString &workingDir) const;
@@ -181,6 +192,11 @@ private slots:
void syncSlot();
void closing();
void updateStatusActions();
+#ifdef WITH_TESTS
+ void testDiffFileResolving_data();
+ void testDiffFileResolving();
+ void testLogResolving();
+#endif
protected:
void updateActions(VcsBase::VcsBasePlugin::ActionState);
@@ -217,7 +233,6 @@ private:
static void rmdir(const QString &path);
QString runExtDiff(const QString &workingDir, const QStringList &arguments,
int timeOut, QTextCodec *outputCodec = 0);
- QString ccGetView(const QString &workingDir, bool *isDynamic = 0, bool *isUcm = 0) const;
ClearCaseSettings m_settings;
@@ -225,9 +240,7 @@ private:
QString m_checkInView;
QString m_topLevel;
QString m_stream;
- QString m_view;
- bool m_isDynamic;
- bool m_isUcm;
+ ViewData m_viewData;
QString m_intStream;
QString m_activity;
QString m_diffPrefix;
diff --git a/src/plugins/clearcase/clearcasesettings.cpp b/src/plugins/clearcase/clearcasesettings.cpp
index f48cc016f8..7dd0963d21 100644
--- a/src/plugins/clearcase/clearcasesettings.cpp
+++ b/src/plugins/clearcase/clearcasesettings.cpp
@@ -31,6 +31,7 @@
#include "clearcasesettings.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QSettings>
@@ -55,11 +56,7 @@ enum { defaultTimeOutS = 30, defaultHistoryCount = 50 };
static QString defaultCommand()
{
- QString rc(QLatin1String("cleartool"));
-#if defined(Q_OS_WIN32)
- rc.append(QLatin1String(".exe"));
-#endif
- return rc;
+ return QLatin1String("cleartool" QTC_HOST_EXE_SUFFIX);
}
using namespace ClearCase::Internal;
diff --git a/src/plugins/clearcase/clearcasesubmiteditor.cpp b/src/plugins/clearcase/clearcasesubmiteditor.cpp
index 7ddd758526..ac24ec80b0 100644
--- a/src/plugins/clearcase/clearcasesubmiteditor.cpp
+++ b/src/plugins/clearcase/clearcasesubmiteditor.cpp
@@ -31,7 +31,7 @@
#include "clearcasesubmiteditor.h"
#include "clearcasesubmiteditorwidget.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
#include <vcsbase/submitfilemodel.h>
using namespace ClearCase::Internal;
@@ -60,7 +60,7 @@ void ClearCaseSubmitEditor::setStatusList(const QStringList &statusOutput)
const ConstIterator cend = statusOutput.constEnd();
for (ConstIterator it = statusOutput.constBegin(); it != cend; ++it)
- model->addFile(*it, QLatin1String("C"), true);
+ model->addFile(*it, QLatin1String("C"));
setFileModel(model, checkScriptWorkingDirectory());
if (statusOutput.count() > 1)
submitEditorWidget()->addKeep();
diff --git a/src/plugins/clearcase/clearcasesubmiteditor.h b/src/plugins/clearcase/clearcasesubmiteditor.h
index d0c7e1ef07..2d93351899 100644
--- a/src/plugins/clearcase/clearcasesubmiteditor.h
+++ b/src/plugins/clearcase/clearcasesubmiteditor.h
@@ -55,7 +55,7 @@ public:
void setIsUcm(bool isUcm);
protected:
- virtual QByteArray fileContents() const;
+ QByteArray fileContents() const;
};
diff --git a/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp b/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp
index 2f6822b5ee..9a9e531e10 100644
--- a/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp
+++ b/src/plugins/clearcase/clearcasesubmiteditorwidget.cpp
@@ -40,7 +40,7 @@
using namespace ClearCase::Internal;
ClearCaseSubmitEditorWidget::ClearCaseSubmitEditorWidget(QWidget *parent) :
- Utils::SubmitEditorWidget(parent),
+ VcsBase::SubmitEditorWidget(parent),
m_actSelector(0)
{
setDescriptionMandatory(false);
diff --git a/src/plugins/clearcase/clearcasesubmiteditorwidget.h b/src/plugins/clearcase/clearcasesubmiteditorwidget.h
index 57be577f49..2531b1b6c4 100644
--- a/src/plugins/clearcase/clearcasesubmiteditorwidget.h
+++ b/src/plugins/clearcase/clearcasesubmiteditorwidget.h
@@ -31,7 +31,7 @@
#ifndef CLEARCASESUBMITEDITORWIDGET_H
#define CLEARCASESUBMITEDITORWIDGET_H
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
QT_BEGIN_NAMESPACE
class QCheckBox;
@@ -43,7 +43,7 @@ namespace Internal {
class ActivitySelector;
-class ClearCaseSubmitEditorWidget : public Utils::SubmitEditorWidget
+class ClearCaseSubmitEditorWidget : public VcsBase::SubmitEditorWidget
{
Q_OBJECT
diff --git a/src/plugins/clearcase/settingspage.cpp b/src/plugins/clearcase/settingspage.cpp
index 5c3df34d46..ee991a95f3 100644
--- a/src/plugins/clearcase/settingspage.cpp
+++ b/src/plugins/clearcase/settingspage.cpp
@@ -36,6 +36,7 @@
#include <coreplugin/icore.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <QCoreApplication>
@@ -84,11 +85,11 @@ void SettingsPageWidget::setSettings(const ClearCaseSettings &s)
m_ui.diffWarningLabel->setVisible(false);
} else {
QString diffWarning = tr("In order to use External diff, 'diff' command needs to be accessible.");
-#ifdef Q_OS_WIN
- diffWarning.append(tr(" DiffUtils is available for free download "
- "<a href=\"http://gnuwin32.sourceforge.net/packages/diffutils.htm\">here</a>. "
- "Please extract it to a directory in your PATH."));
-#endif
+ if (HostOsInfo::isWindowsHost()) {
+ diffWarning.append(tr(" DiffUtils is available for free download "
+ "<a href=\"http://gnuwin32.sourceforge.net/packages/diffutils.htm\">here</a>. "
+ "Please extract it to a directory in your PATH."));
+ }
m_ui.diffWarningLabel->setText(diffWarning);
m_ui.externalDiffRadioButton->setEnabled(false);
}
@@ -126,7 +127,7 @@ QString SettingsPageWidget::searchKeywords() const
SettingsPage::SettingsPage() :
m_widget(0)
{
- setId(QLatin1String(ClearCase::Constants::VCS_ID_CLEARCASE));
+ setId(ClearCase::Constants::VCS_ID_CLEARCASE);
setDisplayName(tr("ClearCase"));
}
diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
index 1ed71983af..665fbb5e5d 100644
--- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp
@@ -57,7 +57,10 @@ const char USE_NINJA_KEY[] = "CMakeProjectManager.CMakeBuildConfiguration.UseNin
CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent) :
BuildConfiguration(parent, Core::Id(Constants::CMAKE_BC_ID)), m_useNinja(false)
{
- m_buildDirectory = static_cast<CMakeProject *>(parent->project())->defaultBuildDirectory();
+ CMakeProject *project = static_cast<CMakeProject *>(parent->project());
+ m_buildDirectory = project->shadowBuildDirectory(project->document()->fileName(),
+ parent->kit(),
+ displayName());
}
CMakeBuildConfiguration::CMakeBuildConfiguration(ProjectExplorer::Target *parent,
@@ -106,9 +109,9 @@ void CMakeBuildConfiguration::setUseNinja(bool useNninja)
CMakeBuildConfiguration::~CMakeBuildConfiguration()
{ }
-ProjectExplorer::BuildConfigWidget *CMakeBuildConfiguration::createConfigWidget()
+ProjectExplorer::NamedWidget *CMakeBuildConfiguration::createConfigWidget()
{
- return new CMakeBuildSettingsWidget;
+ return new CMakeBuildSettingsWidget(this);
}
QString CMakeBuildConfiguration::buildDirectory() const
@@ -125,26 +128,6 @@ void CMakeBuildConfiguration::setBuildDirectory(const QString &buildDirectory)
emit environmentChanged();
}
-ProjectExplorer::IOutputParser *CMakeBuildConfiguration::createOutputParser() const
-{
- ProjectExplorer::IOutputParser *parserchain = new ProjectExplorer::GnuMakeParser;
-
- int versionId = QtSupport::QtKitInformation::qtVersionId(target()->kit());
- if (versionId >= 0)
- parserchain->appendOutputParser(new QtSupport::QtParser);
-
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(target()->kit());
- if (tc)
- parserchain->appendOutputParser(tc->outputParser());
- return parserchain;
-}
-
-Utils::Environment CMakeBuildConfiguration::baseEnvironment() const
-{
- Utils::Environment env = BuildConfiguration::baseEnvironment();
- return env;
-}
-
/*!
\class CMakeBuildConfigurationFactory
*/
@@ -190,7 +173,7 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer:
bool ok = true;
QString buildConfigurationName = name;
- if (buildConfigurationName.isEmpty())
+ if (buildConfigurationName.isNull())
buildConfigurationName = QInputDialog::getText(0,
tr("New Configuration"),
tr("New configuration name:"),
@@ -204,7 +187,9 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer:
info.sourceDirectory = project->projectDirectory();
info.environment = Utils::Environment::systemEnvironment();
parent->kit()->addToEnvironment(info.environment);
- info.buildDirectory = project->defaultBuildDirectory();
+ info.buildDirectory = project->shadowBuildDirectory(project->document()->fileName(),
+ parent->kit(),
+ buildConfigurationName);
info.kit = parent->kit();
info.useNinja = false; // This is ignored anyway
@@ -223,15 +208,15 @@ CMakeBuildConfiguration *CMakeBuildConfigurationFactory::create(ProjectExplorer:
MakeStep *cleanMakeStep = new MakeStep(cleanSteps);
cleanSteps->insertStep(0, cleanMakeStep);
- cleanMakeStep->setAdditionalArguments("clean");
+ cleanMakeStep->setAdditionalArguments(QLatin1String("clean"));
cleanMakeStep->setClean(true);
bc->setBuildDirectory(copw.buildDirectory());
bc->setUseNinja(copw.useNinja());
// Default to all
- if (project->hasBuildTarget("all"))
- makeStep->setBuildTarget("all", true);
+ if (project->hasBuildTarget(QLatin1String("all")))
+ makeStep->setBuildTarget(QLatin1String("all"), true);
return bc;
}
@@ -275,14 +260,13 @@ bool CMakeBuildConfigurationFactory::canHandle(const ProjectExplorer::Target *t)
ProjectExplorer::BuildConfiguration::BuildType CMakeBuildConfiguration::buildType() const
{
QString cmakeBuildType;
- QFile cmakeCache(buildDirectory() + "/CMakeCache.txt");
+ QFile cmakeCache(buildDirectory() + QLatin1String("/CMakeCache.txt"));
if (cmakeCache.open(QIODevice::ReadOnly)) {
while (!cmakeCache.atEnd()) {
- QString line = cmakeCache.readLine();
+ QByteArray line = cmakeCache.readLine();
if (line.startsWith("CMAKE_BUILD_TYPE")) {
- if (int pos = line.indexOf('=')) {
- cmakeBuildType = line.mid(pos + 1).trimmed();
- }
+ if (int pos = line.indexOf('='))
+ cmakeBuildType = QString::fromLocal8Bit(line.mid(pos + 1).trimmed());
break;
}
}
@@ -290,13 +274,13 @@ ProjectExplorer::BuildConfiguration::BuildType CMakeBuildConfiguration::buildTyp
}
// Cover all common CMake build types
- if (cmakeBuildType.compare("Release", Qt::CaseInsensitive) == 0
- || cmakeBuildType.compare("MinSizeRel", Qt::CaseInsensitive) == 0)
+ if (cmakeBuildType.compare(QLatin1String("Release"), Qt::CaseInsensitive) == 0
+ || cmakeBuildType.compare(QLatin1String("MinSizeRel"), Qt::CaseInsensitive) == 0)
{
return Release;
- } else if (cmakeBuildType.compare("Debug", Qt::CaseInsensitive) == 0
- || cmakeBuildType.compare("debugfull", Qt::CaseInsensitive) == 0
- || cmakeBuildType.compare("RelWithDebInfo", Qt::CaseInsensitive) == 0)
+ } else if (cmakeBuildType.compare(QLatin1String("Debug"), Qt::CaseInsensitive) == 0
+ || cmakeBuildType.compare(QLatin1String("DebugFull"), Qt::CaseInsensitive) == 0
+ || cmakeBuildType.compare(QLatin1String("RelWithDebInfo"), Qt::CaseInsensitive) == 0)
{
return Debug;
}
diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h
index c847687d64..494c28ea2c 100644
--- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h
+++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.h
@@ -51,17 +51,13 @@ public:
CMakeBuildConfiguration(ProjectExplorer::Target *parent);
~CMakeBuildConfiguration();
- ProjectExplorer::BuildConfigWidget *createConfigWidget();
+ ProjectExplorer::NamedWidget *createConfigWidget();
QString buildDirectory() const;
void setBuildDirectory(const QString &buildDirectory);
QVariantMap toMap() const;
- ProjectExplorer::IOutputParser *createOutputParser() const;
-
- Utils::Environment baseEnvironment() const;
-
BuildType buildType() const;
bool useNinja() const;
@@ -72,7 +68,7 @@ signals:
protected:
CMakeBuildConfiguration(ProjectExplorer::Target *parent, CMakeBuildConfiguration *source);
- virtual bool fromMap(const QVariantMap &map);
+ bool fromMap(const QVariantMap &map);
private:
QString m_buildDirectory;
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
index 4ef479d32b..97c1eada8d 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeeditor.cpp
@@ -46,6 +46,7 @@
#include <texteditor/texteditorsettings.h>
#include <QFileInfo>
+#include <QSharedPointer>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
@@ -55,8 +56,7 @@ using namespace CMakeProjectManager::Internal;
//
CMakeEditor::CMakeEditor(CMakeEditorWidget *editor)
- : BaseTextEditor(editor),
- m_infoBarShown(false)
+ : BaseTextEditor(editor)
{
setContext(Core::Context(CMakeProjectManager::Constants::C_CMAKEEDITOR,
TextEditor::Constants::C_TEXTEDITOR));
@@ -74,20 +74,22 @@ Core::IEditor *CMakeEditor::duplicate(QWidget *parent)
Core::Id CMakeEditor::id() const
{
- return CMakeProjectManager::Constants::CMAKE_EDITOR_ID;
+ return Core::Id(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
}
void CMakeEditor::markAsChanged()
{
if (!document()->isModified())
return;
- if (m_infoBarShown)
+ Core::InfoBar *infoBar = document()->infoBar();
+ Core::Id infoRunCmake("CMakeEditor.RunCMake");
+ if (!infoBar->canInfoBeAdded(infoRunCmake))
return;
- m_infoBarShown = true;
- Core::InfoBarEntry info(QLatin1String("CMakeEditor.RunCMake"),
- tr("Changes to cmake files are shown in the project tree after building."));
+ Core::InfoBarEntry info(infoRunCmake,
+ tr("Changes to cmake files are shown in the project tree after building."),
+ Core::InfoBarEntry::GlobalSuppressionEnabled);
info.setCustomButtonInfo(tr("Build now"), this, SLOT(build()));
- document()->infoBar()->addInfo(info);
+ infoBar->addInfo(info);
}
void CMakeEditor::build()
@@ -112,7 +114,7 @@ void CMakeEditor::build()
CMakeEditorWidget::CMakeEditorWidget(QWidget *parent, CMakeEditorFactory *factory, TextEditor::TextEditorActionHandler *ah)
: BaseTextEditorWidget(parent), m_factory(factory), m_ah(ah)
{
- CMakeDocument *doc = new CMakeDocument();
+ QSharedPointer<CMakeDocument> doc(new CMakeDocument);
doc->setMimeType(QLatin1String(CMakeProjectManager::Constants::CMAKEMIMETYPE));
setBaseTextDocument(doc);
@@ -223,7 +225,7 @@ CMakeEditorWidget::Link CMakeEditorWidget::findLinkAt(const QTextCursor &cursor,
if (fi.exists()) {
if (fi.isDir()) {
QDir subDir(fi.absoluteFilePath());
- QString subProject = subDir.filePath("CMakeLists.txt");
+ QString subProject = subDir.filePath(QLatin1String("CMakeLists.txt"));
if (QFileInfo(subProject).exists())
fileName = subProject;
else
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditor.h b/src/plugins/cmakeprojectmanager/cmakeeditor.h
index fd77e89ecf..3a27b9b1cd 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditor.h
+++ b/src/plugins/cmakeprojectmanager/cmakeeditor.h
@@ -63,8 +63,6 @@ public:
private slots:
void markAsChanged();
void build();
-private:
- bool m_infoBarShown;
};
class CMakeEditorWidget : public TextEditor::BaseTextEditorWidget
diff --git a/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp b/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp
index e62769404b..8bebdfaade 100644
--- a/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeeditorfactory.cpp
@@ -69,7 +69,7 @@ CMakeEditorFactory::CMakeEditorFactory(CMakeManager *manager)
Core::Id CMakeEditorFactory::id() const
{
- return CMakeProjectManager::Constants::CMAKE_EDITOR_ID;
+ return Core::Id(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
}
QString CMakeEditorFactory::displayName() const
diff --git a/src/plugins/texteditor/tooltip/tipfactory.cpp b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp
index 12e6a731db..c5d2098625 100644
--- a/src/plugins/texteditor/tooltip/tipfactory.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.cpp
@@ -27,31 +27,31 @@
**
****************************************************************************/
-#include "tipfactory.h"
-#include "tipcontents.h"
-#include "tips.h"
-#include <utils/qtcassert.h>
+#include "cmakefilecompletionassist.h"
+#include "cmakeprojectconstants.h"
+#include "cmakeprojectmanager.h"
-#include <QVBoxLayout>
+#include <texteditor/codeassist/keywordscompletionassist.h>
+using namespace CMakeProjectManager::Internal;
using namespace TextEditor;
-using namespace Internal;
-TipFactory::TipFactory()
+// -------------------------------
+// CMakeFileCompletionAssistProvider
+// -------------------------------
+CMakeFileCompletionAssistProvider::CMakeFileCompletionAssistProvider(CMakeSettingsPage *settingsPage)
+ : m_settingsPage(settingsPage)
{}
-TipFactory::~TipFactory()
+CMakeFileCompletionAssistProvider::~CMakeFileCompletionAssistProvider()
{}
-Internal::QTipLabel *TipFactory::createTip(const TipContent &content, QWidget *w)
+bool CMakeFileCompletionAssistProvider::supportsEditor(const Core::Id &editorId) const
{
- if (content.typeId() == TextContent::TEXT_CONTENT_ID)
- return new TextTip(w);
- if (content.typeId() == ColorContent::COLOR_CONTENT_ID)
- return new ColorTip(w);
- if (content.typeId() == WidgetContent::WIDGET_CONTENT_ID)
- return new WidgetTip(w);
+ return editorId == CMakeProjectManager::Constants::CMAKE_EDITOR_ID;
+}
- QTC_CHECK(false);
- return 0;
+IAssistProcessor *CMakeFileCompletionAssistProvider::createProcessor() const
+{
+ return new KeywordsCompletionAssistProcessor(m_settingsPage->keywords());
}
diff --git a/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h
new file mode 100644
index 0000000000..75b7c4bf93
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakefilecompletionassist.h
@@ -0,0 +1,56 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CMAKEFILECOMPLETIONASSIST_H
+#define CMAKEFILECOMPLETIONASSIST_H
+
+#include <texteditor/codeassist/completionassistprovider.h>
+
+namespace CMakeProjectManager {
+namespace Internal {
+
+class CMakeSettingsPage;
+
+class CMakeFileCompletionAssistProvider : public TextEditor::CompletionAssistProvider
+{
+public:
+ CMakeFileCompletionAssistProvider(CMakeSettingsPage *settingsPage);
+ ~CMakeFileCompletionAssistProvider();
+
+ bool supportsEditor(const Core::Id &editorId) const;
+ TextEditor::IAssistProcessor *createProcessor() const;
+
+private:
+ CMakeSettingsPage *m_settingsPage;
+};
+
+} // Internal
+} // CMakeProjectManager
+
+#endif // CMAKEFILECOMPLETIONASSIST_H
diff --git a/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp b/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp
index 0e8a5b1ec3..0a7c59ad96 100644
--- a/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakehighlighter.cpp
@@ -37,7 +37,7 @@
using namespace CMakeProjectManager::Internal;
-static bool isVariable(const QString &word)
+static bool isVariable(const QByteArray &word)
{
if (word.length() < 4) // must be at least "${.}"
return false;
@@ -53,14 +53,14 @@ CMakeHighlighter::CMakeHighlighter(QTextDocument *document) :
void CMakeHighlighter::highlightBlock(const QString &text)
{
- QString buf;
+ QByteArray buf;
bool inCommentMode = false;
bool inStringMode = (previousBlockState() == 1);
QTextCharFormat emptyFormat;
int i=0;
for (i=0; i < text.length(); i++) {
- const QChar c = text.at(i);
+ char c = text.at(i).toLatin1();
if (inCommentMode) {
setFormat(i, 1, m_formats[CMakeCommentFormat]);
} else {
@@ -80,7 +80,7 @@ void CMakeHighlighter::highlightBlock(const QString &text)
} else {
buf += c;
}
- } else if (c.isSpace()) {
+ } else if (text.at(i).isSpace()) {
if (!inStringMode)
buf.clear();
else
diff --git a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
index f30147b0de..a34b4f545a 100644
--- a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.cpp
@@ -36,13 +36,17 @@
#include <projectexplorer/target.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/buildsteplist.h>
+#include <utils/fileutils.h>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
+using namespace Utils;
CMakeLocatorFilter::CMakeLocatorFilter()
{
+ setId("Build CMake target");
+ setDisplayName(tr("Build CMake target"));
setShortcutString(QLatin1String("cm"));
ProjectExplorer::SessionManager *sm = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
@@ -73,7 +77,8 @@ QList<Locator::FilterEntry> CMakeLocatorFilter::matchesFor(QFutureInterface<Loca
foreach (CMakeBuildTarget ct, cmakeProject->buildTargets()) {
if (ct.title.contains(entry)) {
Locator::FilterEntry entry(this, ct.title, cmakeProject->document()->fileName());
- entry.extraInfo = cmakeProject->document()->fileName();
+ entry.extraInfo = FileUtils::shortNativePath(
+ FileName::fromString(cmakeProject->document()->fileName()));
result.append(entry);
}
}
diff --git a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.h b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.h
index f429540003..471b3a9e26 100644
--- a/src/plugins/cmakeprojectmanager/cmakelocatorfilter.h
+++ b/src/plugins/cmakeprojectmanager/cmakelocatorfilter.h
@@ -45,10 +45,6 @@ public:
CMakeLocatorFilter();
~CMakeLocatorFilter();
- QString displayName() const { return tr("Build CMake target"); }
- QString id() const { return QLatin1String("Build CMake target"); }
- Priority priority() const { return Medium; }
-
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp
index 3eac898e9b..4d284131a1 100644
--- a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.cpp
@@ -32,6 +32,7 @@
#include "cmakebuildconfiguration.h"
#include <coreplugin/icore.h>
+#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <utils/fancylineedit.h>
#include <projectexplorer/kitinformation.h>
@@ -69,6 +70,7 @@ namespace CMakeProjectManager {
namespace Internal {
class GeneratorInfo
{
+ Q_DECLARE_TR_FUNCTIONS(CMakeProjectManager::Internal::GeneratorInfo)
public:
enum Ninja { NoNinja, OfferNinja, ForceNinja };
static QList<GeneratorInfo> generatorInfosFor(ProjectExplorer::Kit *k, Ninja n, bool hasCodeBlocks);
@@ -80,8 +82,8 @@ namespace Internal {
bool isNinja() const;
QString displayName() const;
- QString generatorArgument() const;
- QString generator() const;
+ QByteArray generatorArgument() const;
+ QByteArray generator() const;
private:
ProjectExplorer::Kit *m_kit;
@@ -110,37 +112,36 @@ bool GeneratorInfo::isNinja() const {
return m_isNinja;
}
-QString GeneratorInfo::generator() const
+QByteArray GeneratorInfo::generator() const
{
if (!m_kit)
- return QString();
+ return QByteArray();
ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(m_kit);
ProjectExplorer::Abi targetAbi = tc->targetAbi();
if (m_isNinja) {
- return QLatin1String("Ninja");
+ return "Ninja";
} else if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) {
if (targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2005Flavor
|| targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2008Flavor
|| targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2010Flavor
|| targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2012Flavor) {
- return QLatin1String("NMake Makefiles");
+ return "NMake Makefiles";
} else if (targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor) {
-#ifdef Q_OS_WIN
- return QLatin1String("MinGW Makefiles");
-#else
- return QLatin1String("Unix Makefiles");
-#endif
+ if (Utils::HostOsInfo::isWindowsHost())
+ return "MinGW Makefiles";
+ else
+ return "Unix Makefiles";
}
}
- return QLatin1String("Unix Makefiles");
+ return "Unix Makefiles";
}
-QString GeneratorInfo::generatorArgument() const
+QByteArray GeneratorInfo::generatorArgument() const
{
- QString tmp = generator();
+ QByteArray tmp = generator();
if (tmp.isEmpty())
return tmp;
- return QLatin1String("-GCodeBlocks - ") + tmp;
+ return QByteArray("-GCodeBlocks - ") + tmp;
}
QString GeneratorInfo::displayName() const
@@ -148,7 +149,7 @@ QString GeneratorInfo::displayName() const
if (!m_kit)
return QString();
if (m_isNinja)
- return QApplication::tr("Ninja (%1)").arg(m_kit->displayName());
+ return tr("Ninja (%1)").arg(m_kit->displayName());
ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(m_kit);
ProjectExplorer::Abi targetAbi = tc->targetAbi();
if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) {
@@ -156,17 +157,16 @@ QString GeneratorInfo::displayName() const
|| targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2008Flavor
|| targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2010Flavor
|| targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMsvc2012Flavor) {
- return QApplication::tr("NMake Generator (%1)").arg(m_kit->displayName());
+ return tr("NMake Generator (%1)").arg(m_kit->displayName());
} else if (targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor) {
-#ifdef Q_OS_WIN
- return QApplication::tr("MinGW Generator (%1)").arg(m_kit->displayName());
-#else
- return QApplication::tr("Unix Generator (%1)").arg(m_kit->displayName());
-#endif
+ if (Utils::HostOsInfo::isWindowsHost())
+ return tr("MinGW Generator (%1)").arg(m_kit->displayName());
+ else
+ return tr("Unix Generator (%1)").arg(m_kit->displayName());
}
} else {
// Non windows
- return QApplication::tr("Unix Generator (%1)").arg(m_kit->displayName());
+ return tr("Unix Generator (%1)").arg(m_kit->displayName());
}
return QString();
}
@@ -268,7 +268,7 @@ CMakeManager *CMakeOpenProjectWizard::cmakeManager() const
bool CMakeOpenProjectWizard::hasInSourceBuild() const
{
- QFileInfo fi(m_sourceDirectory + "/CMakeCache.txt");
+ QFileInfo fi(m_sourceDirectory + QLatin1String("/CMakeCache.txt"));
if (fi.exists())
return true;
return false;
@@ -280,7 +280,7 @@ bool CMakeOpenProjectWizard::existsUpToDateXmlFile() const
if (!cbpFile.isEmpty()) {
// We already have a cbp file
QFileInfo cbpFileInfo(cbpFile);
- QFileInfo cmakeListsFileInfo(sourceDirectory() + "/CMakeLists.txt");
+ QFileInfo cmakeListsFileInfo(sourceDirectory() + QLatin1String("/CMakeLists.txt"));
if (cbpFileInfo.lastModified() > cmakeListsFileInfo.lastModified())
return true;
@@ -500,18 +500,18 @@ void CMakeRunPage::initWidgets()
setMinimumSize(600, 400);
}
-QString CMakeRunPage::cachedGeneratorFromFile(const QString &cache)
+QByteArray CMakeRunPage::cachedGeneratorFromFile(const QString &cache)
{
QFile fi(cache);
if (fi.exists()) {
// Cache exists, then read it...
if (fi.open(QIODevice::ReadOnly | QIODevice::Text)) {
while (!fi.atEnd()) {
- QString line = fi.readLine();
+ QByteArray line = fi.readLine();
if (line.startsWith("CMAKE_GENERATOR:INTERNAL=")) {
int splitpos = line.indexOf('=');
if (splitpos != -1) {
- QString cachedGenerator = line.mid(splitpos + 1).trimmed();
+ QByteArray cachedGenerator = line.mid(splitpos + 1).trimmed();
if (!cachedGenerator.isEmpty())
return cachedGenerator;
}
@@ -519,7 +519,7 @@ QString CMakeRunPage::cachedGeneratorFromFile(const QString &cache)
}
}
}
- return QString();
+ return QByteArray();
}
void CMakeRunPage::initializePage()
@@ -570,7 +570,7 @@ void CMakeRunPage::initializePage()
if (m_mode == Initial) {
// Try figuring out generator and toolchain from CMakeCache.txt
- QString cachedGenerator = cachedGeneratorFromFile(m_buildDirectory + "/CMakeCache.txt");
+ QByteArray cachedGenerator = cachedGeneratorFromFile(m_buildDirectory + QLatin1String("/CMakeCache.txt"));
m_generatorComboBox->show();
QList<ProjectExplorer::Kit *> kitList =
@@ -602,7 +602,7 @@ void CMakeRunPage::initializePage()
ninja,
true);
foreach (const GeneratorInfo &info, infos)
- m_generatorComboBox->addItem(info.displayName(), qVariantFromValue(info));
+ m_generatorComboBox->addItem(info.displayName(), qVariantFromValue(info));
}
}
@@ -653,7 +653,7 @@ void CMakeRunPage::runCMake()
connect(m_cmakeProcess, SIGNAL(readyReadStandardError()), this, SLOT(cmakeReadyReadStandardError()));
connect(m_cmakeProcess, SIGNAL(finished(int)), this, SLOT(cmakeFinished()));
cmakeManager->createXmlFile(m_cmakeProcess, m_argumentsLineEdit->text(), m_cmakeWizard->sourceDirectory(),
- m_buildDirectory, env, generatorInfo.generatorArgument());
+ m_buildDirectory, env, QString::fromLatin1(generatorInfo.generatorArgument()));
} else {
m_runCMake->setEnabled(true);
m_argumentsLineEdit->setEnabled(true);
@@ -678,7 +678,7 @@ void CMakeRunPage::cmakeReadyReadStandardOutput()
tf.setFont(font);
tf.setForeground(m_output->palette().color(QPalette::Text));
- cursor.insertText(m_cmakeProcess->readAllStandardOutput(), tf);
+ cursor.insertText(QString::fromLocal8Bit(m_cmakeProcess->readAllStandardOutput()), tf);
}
void CMakeRunPage::cmakeReadyReadStandardError()
@@ -692,7 +692,7 @@ void CMakeRunPage::cmakeReadyReadStandardError()
tf.setFont(boldFont);
tf.setForeground(mix_colors(m_output->palette().color(QPalette::Text), QColor(Qt::red)));
- cursor.insertText(m_cmakeProcess->readAllStandardError(), tf);
+ cursor.insertText(QString::fromLocal8Bit(m_cmakeProcess->readAllStandardError()), tf);
}
void CMakeRunPage::cmakeFinished()
diff --git a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h
index 737db5b300..220966abfd 100644
--- a/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h
+++ b/src/plugins/cmakeprojectmanager/cmakeopenprojectwizard.h
@@ -179,7 +179,7 @@ private slots:
void cmakeReadyReadStandardError();
private:
void initWidgets();
- QString cachedGeneratorFromFile(const QString &cache);
+ QByteArray cachedGeneratorFromFile(const QString &cache);
CMakeOpenProjectWizard *m_cmakeWizard;
QPlainTextEdit *m_output;
QPushButton *m_runCMake;
diff --git a/src/plugins/cmakeprojectmanager/cmakeproject.cpp b/src/plugins/cmakeprojectmanager/cmakeproject.cpp
index 73bea9c930..13085b37ce 100644
--- a/src/plugins/cmakeprojectmanager/cmakeproject.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeproject.cpp
@@ -41,7 +41,6 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/headerpath.h>
-#include <projectexplorer/buildenvironmentwidget.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/kitinformation.h>
@@ -49,13 +48,20 @@
#include <projectexplorer/toolchain.h>
#include <projectexplorer/target.h>
#include <projectexplorer/deployconfiguration.h>
+#include <projectexplorer/projectmacroexpander.h>
#include <qtsupport/customexecutablerunconfiguration.h>
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtkitinformation.h>
#include <cpptools/ModelManagerInterface.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
+#include <utils/stringutils.h>
+#include <utils/hostosinfo.h>
#include <coreplugin/icore.h>
#include <coreplugin/infobar.h>
+#include <coreplugin/documentmanager.h>
#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/variablemanager.h>
#include <QMap>
#include <QDebug>
@@ -193,9 +199,21 @@ void CMakeProject::changeBuildDirectory(CMakeBuildConfiguration *bc, const QStri
parseCMakeLists();
}
-QString CMakeProject::defaultBuildDirectory() const
+QString CMakeProject::shadowBuildDirectory(const QString &projectFilePath, const Kit *k, const QString &bcName)
{
- return projectDirectory() + QLatin1String("-build");
+ if (projectFilePath.isEmpty())
+ return QString();
+ QFileInfo info(projectFilePath);
+
+ QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
+ if (version && !version->supportsShadowBuilds())
+ return info.absolutePath();
+
+ const QString projectName = QFileInfo(info.absolutePath()).fileName();
+ ProjectExplorer::ProjectExpander expander(projectFilePath, projectName, k, bcName);
+ QDir projectDir = QDir(projectDirectory(projectFilePath));
+ QString buildPath = Utils::expandMacros(Core::DocumentManager::buildDirectory(), &expander);
+ return QDir::cleanPath(projectDir.absoluteFilePath(buildPath));
}
bool CMakeProject::parseCMakeLists()
@@ -208,7 +226,7 @@ bool CMakeProject::parseCMakeLists()
CMakeBuildConfiguration *activeBC = static_cast<CMakeBuildConfiguration *>(activeTarget()->activeBuildConfiguration());
foreach (Core::IEditor *editor, Core::EditorManager::instance()->openedEditors())
if (isProjectFile(editor->document()->fileName()))
- editor->document()->infoBar()->removeInfo(QLatin1String("CMakeEditor.RunCMake"));
+ editor->document()->infoBar()->removeInfo(Core::Id("CMakeEditor.RunCMake"));
// Find cbp file
QString cbpFile = CMakeManager::findCbpFile(activeBC->buildDirectory());
@@ -248,7 +266,7 @@ bool CMakeProject::parseCMakeLists()
projectFiles.insert(node->path());
} else {
// Manually add the CMakeLists.txt file
- QString cmakeListTxt = projectDirectory() + "/CMakeLists.txt";
+ QString cmakeListTxt = projectDirectory() + QLatin1String("/CMakeLists.txt");
bool generated = false;
fileList.append(new ProjectExplorer::FileNode(cmakeListTxt, ProjectExplorer::ProjectFileType, generated));
projectFiles.insert(cmakeListTxt);
@@ -276,14 +294,13 @@ bool CMakeProject::parseCMakeLists()
// TOOD this code ain't very pretty ...
m_uicCommand.clear();
- QFile cmakeCache(activeBC->buildDirectory() + "/CMakeCache.txt");
+ QFile cmakeCache(activeBC->buildDirectory() + QLatin1String("/CMakeCache.txt"));
cmakeCache.open(QIODevice::ReadOnly);
while (!cmakeCache.atEnd()) {
- QString line = cmakeCache.readLine();
+ QByteArray line = cmakeCache.readLine();
if (line.startsWith("QT_UIC_EXECUTABLE")) {
- if (int pos = line.indexOf('=')) {
- m_uicCommand = line.mid(pos + 1).trimmed();
- }
+ if (int pos = line.indexOf('='))
+ m_uicCommand = QString::fromLocal8Bit(line.mid(pos + 1).trimmed());
break;
}
}
@@ -304,13 +321,44 @@ bool CMakeProject::parseCMakeLists()
allIncludePaths.append(projectDirectory());
allIncludePaths.append(cbpparser.includeFiles());
+ QStringList cxxflags;
+ foreach (const CMakeBuildTarget &buildTarget, m_buildTargets) {
+ if (buildTarget.title.endsWith(QLatin1String("/fast")))
+ continue;
+ QString makeCommand = QDir::fromNativeSeparators(buildTarget.makeCommand);
+ int startIndex = makeCommand.indexOf(QLatin1Char('\"'));
+ int endIndex = makeCommand.indexOf(QLatin1Char('\"'), startIndex + 1);
+ if (startIndex == -1 || endIndex == -1)
+ continue;
+ startIndex += 1;
+ QString makefile = makeCommand.mid(startIndex, endIndex - startIndex);
+ int slashIndex = makefile.lastIndexOf(QLatin1Char('/'));
+ makefile.truncate(slashIndex);
+ makefile.append(QLatin1String("/CMakeFiles/") + buildTarget.title + QLatin1String(".dir/flags.make"));
+ QFile file(makefile);
+ bool found = false;
+ if (file.exists()) {
+ file.open(QIODevice::ReadOnly | QIODevice::Text);
+ QStringList lines = QString::fromLatin1(file.readAll()).split(QLatin1Char('\n'));
+ foreach (const QString &line, lines) {
+ if (line.startsWith(QLatin1String("CXX_FLAGS ="))) {
+ int index = line.indexOf(QLatin1Char('=')) + 1;
+ cxxflags = line.mid(index).trimmed().split(QLatin1Char(' '));
+ found = true;
+ break;
+ }
+ }
+ }
+ if (found)
+ break;
+ }
+
QByteArray allDefines;
- allDefines.append(tc->predefinedMacros(QStringList()));
- allDefines.append(cbpparser.defines());
+ allDefines.append(tc->predefinedMacros(cxxflags));
QStringList allFrameworkPaths;
QList<ProjectExplorer::HeaderPath> allHeaderPaths;
- allHeaderPaths = tc->systemHeaderPaths(SysRootKitInformation::sysRoot(k));
+ allHeaderPaths = tc->systemHeaderPaths(cxxflags, SysRootKitInformation::sysRoot(k));
foreach (const ProjectExplorer::HeaderPath &headerPath, allHeaderPaths) {
if (headerPath.kind() == ProjectExplorer::HeaderPath::FrameworkHeaderPath)
allFrameworkPaths.append(headerPath.path());
@@ -334,7 +382,12 @@ bool CMakeProject::parseCMakeLists()
part->sourceFiles = m_files;
part->defines = allDefines;
part->frameworkPaths = allFrameworkPaths;
- part->language = CPlusPlus::CppModelManagerInterface::CXX;
+ if (tc)
+ part->language = tc->compilerFlags(cxxflags) == ToolChain::STD_CXX11
+ ? CPlusPlus::CppModelManagerInterface::ProjectPart::CXX11
+ : CPlusPlus::CppModelManagerInterface::ProjectPart::CXX;
+ else
+ part->language = CPlusPlus::CppModelManagerInterface::ProjectPart::CXX11;
pinfo.appendProjectPart(part);
modelmanager->updateProjectInfo(pinfo);
m_codeModelFuture.cancel();
@@ -512,13 +565,6 @@ CMakeManager *CMakeProject::projectManager() const
return m_manager;
}
-QList<ProjectExplorer::BuildConfigWidget*> CMakeProject::subConfigWidgets()
-{
- QList<ProjectExplorer::BuildConfigWidget*> list;
- list << new BuildEnvironmentWidget;
- return list;
-}
-
ProjectExplorer::ProjectNode *CMakeProject::rootProjectNode() const
{
return m_rootNode;
@@ -544,7 +590,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
Kit *k = copw.kit();
Target *t = new Target(this, k);
CMakeBuildConfiguration *bc(new CMakeBuildConfiguration(t));
- bc->setDefaultDisplayName("all");
+ bc->setDefaultDisplayName(QLatin1String("all"));
bc->setUseNinja(copw.useNinja());
bc->setBuildDirectory(copw.buildDirectory());
ProjectExplorer::BuildStepList *buildSteps = bc->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD);
@@ -555,7 +601,7 @@ bool CMakeProject::fromMap(const QVariantMap &map)
MakeStep *cleanMakeStep = new MakeStep(cleanSteps);
cleanSteps->insertStep(0, cleanMakeStep);
- cleanMakeStep->setAdditionalArguments("clean");
+ cleanMakeStep->setAdditionalArguments(QLatin1String("clean"));
cleanMakeStep->setClean(true);
t->addBuildConfiguration(bc);
@@ -596,11 +642,11 @@ bool CMakeProject::fromMap(const QVariantMap &map)
parseCMakeLists();
- if (!hasUserFile && hasBuildTarget("all")) {
+ if (!hasUserFile && hasBuildTarget(QLatin1String("all"))) {
MakeStep *makeStep = qobject_cast<MakeStep *>(
activeTarget()->activeBuildConfiguration()->stepList(ProjectExplorer::Constants::BUILDSTEPS_BUILD)->at(0));
Q_ASSERT(makeStep);
- makeStep->setBuildTarget("all", true);
+ makeStep->setBuildTarget(QLatin1String("all"), true);
}
connect(Core::EditorManager::instance(), SIGNAL(editorAboutToClose(Core::IEditor*)),
@@ -654,16 +700,28 @@ QString CMakeProject::uicCommand() const
QString CMakeProject::uiHeaderFile(const QString &uiFile)
{
- QDir srcDirRoot = QDir(projectDirectory());
- QString relativePath = srcDirRoot.relativeFilePath(uiFile);
+ QFileInfo fi(uiFile);
+ Utils::FileName project = Utils::FileName::fromString(projectDirectory());
+ Utils::FileName baseDirectory = Utils::FileName::fromString(fi.absolutePath());
+
+ while (baseDirectory.isChildOf(project)) {
+ Utils::FileName cmakeListsTxt = baseDirectory;
+ cmakeListsTxt.appendPath(QLatin1String("CMakeLists.txt"));
+ if (cmakeListsTxt.toFileInfo().exists())
+ break;
+ QDir dir(baseDirectory.toString());
+ dir.cdUp();
+ baseDirectory = Utils::FileName::fromString(dir.absolutePath());
+ }
+
+ QDir srcDirRoot = QDir(project.toString());
+ QString relativePath = srcDirRoot.relativeFilePath(baseDirectory.toString());
QDir buildDir = QDir(activeTarget()->activeBuildConfiguration()->buildDirectory());
QString uiHeaderFilePath = buildDir.absoluteFilePath(relativePath);
-
- QFileInfo fi(uiHeaderFilePath);
- uiHeaderFilePath = fi.absolutePath();
uiHeaderFilePath += QLatin1String("/ui_");
uiHeaderFilePath += fi.completeBaseName();
uiHeaderFilePath += QLatin1String(".h");
+
return QDir::cleanPath(uiHeaderFilePath);
}
@@ -693,7 +751,7 @@ void CMakeProject::updateRunConfigurations(Target *t)
continue;
if (ct.executable.isEmpty())
continue;
- if (ct.title.endsWith("/fast"))
+ if (ct.title.endsWith(QLatin1String("/fast")))
continue;
QList<CMakeRunConfiguration *> list = existingRunConfigurations.values(ct.title);
if (!list.isEmpty()) {
@@ -745,7 +803,7 @@ void CMakeProject::createUiCodeModelSupport()
// Find all ui files
foreach (const QString &uiFile, m_files) {
- if (uiFile.endsWith(".ui")) {
+ if (uiFile.endsWith(QLatin1String(".ui"))) {
// UI file, not convert to
QString uiHeaderFilePath = uiHeaderFile(uiFile);
QMap<QString, CMakeUiCodeModelSupport *>::iterator it
@@ -874,7 +932,7 @@ QString CMakeFile::suggestedFileName() const
QString CMakeFile::mimeType() const
{
- return Constants::CMAKEMIMETYPE;
+ return QLatin1String(Constants::CMAKEMIMETYPE);
}
@@ -910,7 +968,7 @@ bool CMakeFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
return true;
}
-CMakeBuildSettingsWidget::CMakeBuildSettingsWidget() : m_buildConfiguration(0)
+CMakeBuildSettingsWidget::CMakeBuildSettingsWidget(CMakeBuildConfiguration *bc) : m_buildConfiguration(0)
{
QFormLayout *fl = new QFormLayout(this);
fl->setContentsMargins(20, -1, 0, -1);
@@ -934,21 +992,15 @@ CMakeBuildSettingsWidget::CMakeBuildSettingsWidget() : m_buildConfiguration(0)
hbox->addWidget(m_changeButton);
fl->addRow(tr("Build directory:"), hbox);
-}
-
-QString CMakeBuildSettingsWidget::displayName() const
-{
- return "CMake";
-}
-void CMakeBuildSettingsWidget::init(BuildConfiguration *bc)
-{
- m_buildConfiguration = static_cast<CMakeBuildConfiguration *>(bc);
+ m_buildConfiguration = bc;
m_pathLineEdit->setText(m_buildConfiguration->buildDirectory());
if (m_buildConfiguration->buildDirectory() == bc->target()->project()->projectDirectory())
m_changeButton->setEnabled(false);
else
m_changeButton->setEnabled(true);
+
+ setDisplayName(tr("CMake"));
}
void CMakeBuildSettingsWidget::openChangeBuildDirectoryDialog()
@@ -985,11 +1037,10 @@ bool CMakeCbpParser::parseCbpFile(const QString &fileName)
while (!atEnd()) {
readNext();
- if (name() == "CodeBlocks_project_file") {
+ if (name() == QLatin1String("CodeBlocks_project_file"))
parseCodeBlocks_project_file();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
fi.close();
m_includeFiles.sort();
@@ -1003,13 +1054,12 @@ void CMakeCbpParser::parseCodeBlocks_project_file()
{
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (name() == "Project") {
+ else if (name() == QLatin1String("Project"))
parseProject();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
@@ -1017,17 +1067,16 @@ void CMakeCbpParser::parseProject()
{
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (name() == "Option") {
+ else if (name() == QLatin1String("Option"))
parseOption();
- } else if (name() == "Unit") {
+ else if (name() == QLatin1String("Unit"))
parseUnit();
- } else if (name() == "Build") {
+ else if (name() == QLatin1String("Build"))
parseBuild();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
@@ -1035,13 +1084,12 @@ void CMakeCbpParser::parseBuild()
{
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (name() == "Target") {
+ else if (name() == QLatin1String("Target"))
parseBuildTarget();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
@@ -1050,19 +1098,20 @@ void CMakeCbpParser::parseBuildTarget()
m_buildTargetType = false;
m_buildTarget.clear();
- if (attributes().hasAttribute("title"))
- m_buildTarget.title = attributes().value("title").toString();
+ if (attributes().hasAttribute(QLatin1String("title")))
+ m_buildTarget.title = attributes().value(QLatin1String("title")).toString();
while (!atEnd()) {
readNext();
if (isEndElement()) {
- if (m_buildTargetType || m_buildTarget.title == "all" || m_buildTarget.title == "install") {
+ if (m_buildTargetType || m_buildTarget.title == QLatin1String("all") || m_buildTarget.title == QLatin1String("install"))
m_buildTargets.append(m_buildTarget);
- }
return;
- } else if (name() == "Compiler") {
+ } else if (name() == QLatin1String("Compiler")) {
parseCompiler();
- } else if (name() == "Option") {
+ } else if (name() == QLatin1String("Option")) {
parseBuildTargetOption();
+ } else if (name() == QLatin1String("MakeCommands")) {
+ parseMakeCommands();
} else if (isStartElement()) {
parseUnknownElement();
}
@@ -1071,25 +1120,26 @@ void CMakeCbpParser::parseBuildTarget()
void CMakeCbpParser::parseBuildTargetOption()
{
- if (attributes().hasAttribute("output")) {
- m_buildTarget.executable = attributes().value("output").toString();
- } else if (attributes().hasAttribute("type") && (attributes().value("type") == "1" || attributes().value("type") == "0")) {
+ if (attributes().hasAttribute(QLatin1String("output"))) {
+ m_buildTarget.executable = attributes().value(QLatin1String("output")).toString();
+ } else if (attributes().hasAttribute(QLatin1String("type"))
+ && (attributes().value(QLatin1String("type")) == QLatin1String("1")
+ || attributes().value(QLatin1String("type")) == QLatin1String("0"))) {
m_buildTargetType = true;
- } else if (attributes().hasAttribute("type") && (attributes().value("type") == "3" || attributes().value("type") == "2")) {
+ } else if (attributes().hasAttribute(QLatin1String("type"))
+ && (attributes().value(QLatin1String("type")) == QLatin1String("3")
+ || attributes().value(QLatin1String("type")) == QLatin1String("2"))) {
m_buildTargetType = true;
m_buildTarget.library = true;
- } else if (attributes().hasAttribute("working_dir")) {
- m_buildTarget.workingDirectory = attributes().value("working_dir").toString();
+ } else if (attributes().hasAttribute(QLatin1String("working_dir"))) {
+ m_buildTarget.workingDirectory = attributes().value(QLatin1String("working_dir")).toString();
}
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (name() == "MakeCommand") {
- parseMakeCommand();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
@@ -1100,63 +1150,59 @@ QString CMakeCbpParser::projectName() const
void CMakeCbpParser::parseOption()
{
- if (attributes().hasAttribute("title"))
- m_projectName = attributes().value("title").toString();
+ if (attributes().hasAttribute(QLatin1String("title")))
+ m_projectName = attributes().value(QLatin1String("title")).toString();
- if (attributes().hasAttribute("compiler"))
- m_compiler = attributes().value("compiler").toString();
+ if (attributes().hasAttribute(QLatin1String("compiler")))
+ m_compiler = attributes().value(QLatin1String("compiler")).toString();
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
-void CMakeCbpParser::parseMakeCommand()
+void CMakeCbpParser::parseMakeCommands()
{
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (name() == "Build") {
+ else if (name() == QLatin1String("Build"))
parseBuildTargetBuild();
- } else if (name() == "Clean") {
+ else if (name() == QLatin1String("Clean"))
parseBuildTargetClean();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
void CMakeCbpParser::parseBuildTargetBuild()
{
- if (attributes().hasAttribute("command"))
- m_buildTarget.makeCommand = attributes().value("command").toString();
+ if (attributes().hasAttribute(QLatin1String("command")))
+ m_buildTarget.makeCommand = attributes().value(QLatin1String("command")).toString();
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
void CMakeCbpParser::parseBuildTargetClean()
{
- if (attributes().hasAttribute("command"))
- m_buildTarget.makeCleanCommand = attributes().value("command").toString();
+ if (attributes().hasAttribute(QLatin1String("command")))
+ m_buildTarget.makeCleanCommand = attributes().value(QLatin1String("command")).toString();
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
@@ -1164,13 +1210,12 @@ void CMakeCbpParser::parseCompiler()
{
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (name() == "Add") {
+ else if (name() == QLatin1String("Add"))
parseAdd();
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
@@ -1179,42 +1224,29 @@ void CMakeCbpParser::parseAdd()
// CMake only supports <Add option=\> and <Add directory=\>
const QXmlStreamAttributes addAttributes = attributes();
- const QString includeDirectory = addAttributes.value("directory").toString();
+ const QString includeDirectory = addAttributes.value(QLatin1String("directory")).toString();
// allow adding multiple times because order happens
- if (!includeDirectory.isEmpty()) {
+ if (!includeDirectory.isEmpty())
m_includeFiles.append(includeDirectory);
- }
- QString compilerOption = addAttributes.value("option").toString();
+ QString compilerOption = addAttributes.value(QLatin1String("option")).toString();
// defining multiple times a macro to the same value makes no sense
- if (!compilerOption.isEmpty() && !m_compilerOptions.contains(compilerOption)) {
+ if (!compilerOption.isEmpty() && !m_compilerOptions.contains(compilerOption))
m_compilerOptions.append(compilerOption);
- int macroNameIndex = compilerOption.indexOf("-D") + 2;
- if (macroNameIndex != 1) {
- int assignIndex = compilerOption.indexOf('=', macroNameIndex);
- if (assignIndex != -1) {
- compilerOption[assignIndex] = ' ';
- }
- m_defines.append("#define ");
- m_defines.append(compilerOption.mid(macroNameIndex).toAscii());
- m_defines.append('\n');
- }
- }
while (!atEnd()) {
readNext();
- if (isEndElement()) {
+ if (isEndElement())
return;
- } else if (isStartElement()) {
+ else if (isStartElement())
parseUnknownElement();
- }
}
}
void CMakeCbpParser::parseUnit()
{
//qDebug()<<stream.attributes().value("filename");
- QString fileName = attributes().value("filename").toString();
+ QString fileName = attributes().value(QLatin1String("filename")).toString();
m_parsingCmakeUnit = false;
while (!atEnd()) {
readNext();
@@ -1226,9 +1258,9 @@ void CMakeCbpParser::parseUnit()
} else {
bool generated = false;
QString onlyFileName = QFileInfo(fileName).fileName();
- if ( (onlyFileName.startsWith("moc_") && onlyFileName.endsWith(".cxx"))
- || (onlyFileName.startsWith("ui_") && onlyFileName.endsWith(".h"))
- || (onlyFileName.startsWith("qrc_") && onlyFileName.endsWith(".cxx")))
+ if ( (onlyFileName.startsWith(QLatin1String("moc_")) && onlyFileName.endsWith(QLatin1String(".cxx")))
+ || (onlyFileName.startsWith(QLatin1String("ui_")) && onlyFileName.endsWith(QLatin1String(".h")))
+ || (onlyFileName.startsWith(QLatin1String("qrc_")) && onlyFileName.endsWith(QLatin1String(".cxx"))))
generated = true;
if (fileName.endsWith(QLatin1String(".qrc")))
@@ -1239,7 +1271,7 @@ void CMakeCbpParser::parseUnit()
m_processedUnits.insert(fileName);
}
return;
- } else if (name() == "Option") {
+ } else if (name() == QLatin1String("Option")) {
parseUnitOption();
} else if (isStartElement()) {
parseUnknownElement();
@@ -1249,7 +1281,7 @@ void CMakeCbpParser::parseUnit()
void CMakeCbpParser::parseUnitOption()
{
- if (attributes().hasAttribute("virtualFolder"))
+ if (attributes().hasAttribute(QLatin1String("virtualFolder")))
m_parsingCmakeUnit = true;
while (!atEnd()) {
@@ -1298,11 +1330,6 @@ QStringList CMakeCbpParser::includeFiles()
return m_includeFiles;
}
-QByteArray CMakeCbpParser::defines() const
-{
- return m_defines;
-}
-
QList<CMakeBuildTarget> CMakeCbpParser::buildTargets()
{
return m_buildTargets;
diff --git a/src/plugins/cmakeprojectmanager/cmakeproject.h b/src/plugins/cmakeprojectmanager/cmakeproject.h
index 970cec3da1..e255e8a3ff 100644
--- a/src/plugins/cmakeprojectmanager/cmakeproject.h
+++ b/src/plugins/cmakeprojectmanager/cmakeproject.h
@@ -37,8 +37,8 @@
#include <projectexplorer/project.h>
#include <projectexplorer/projectnodes.h>
-#include <projectexplorer/buildstep.h>
#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/namedwidget.h>
#include <coreplugin/idocument.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
@@ -85,8 +85,6 @@ public:
Core::IDocument *document() const;
CMakeManager *projectManager() const;
- QList<ProjectExplorer::BuildConfigWidget*> subConfigWidgets();
-
ProjectExplorer::ProjectNode *rootProjectNode() const;
QStringList files(FilesMode fileMode) const;
@@ -96,8 +94,8 @@ public:
CMakeBuildTarget buildTargetForTitle(const QString &title);
- QString defaultBuildDirectory() const;
-
+ QString shadowBuildDirectory(const QString &projectFilePath, const ProjectExplorer::Kit *k,
+ const QString &bcName);
QString uicCommand() const;
@@ -164,7 +162,6 @@ public:
QList<ProjectExplorer::FileNode *> cmakeFileList();
QStringList includeFiles();
QList<CMakeBuildTarget> buildTargets();
- QByteArray defines() const;
QString projectName() const;
QString compilerName() const;
bool hasCMakeFiles();
@@ -176,7 +173,7 @@ private:
void parseOption();
void parseBuildTarget();
void parseBuildTargetOption();
- void parseMakeCommand();
+ void parseMakeCommands();
void parseBuildTargetBuild();
void parseBuildTargetClean();
void parseCompiler();
@@ -191,7 +188,6 @@ private:
bool m_parsingCmakeUnit;
QStringList m_includeFiles;
QStringList m_compilerOptions;
- QByteArray m_defines;
CMakeBuildTarget m_buildTarget;
bool m_buildTargetType;
@@ -226,15 +222,11 @@ private:
QString m_fileName;
};
-class CMakeBuildSettingsWidget : public ProjectExplorer::BuildConfigWidget
+class CMakeBuildSettingsWidget : public ProjectExplorer::NamedWidget
{
Q_OBJECT
public:
- CMakeBuildSettingsWidget();
- QString displayName() const;
-
- // This is called to set up the config widget before showing it
- void init(ProjectExplorer::BuildConfiguration *bc);
+ CMakeBuildSettingsWidget(CMakeBuildConfiguration *bc);
private slots:
void openChangeBuildDirectoryDialog();
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
index 9173a3a1fd..726905c162 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.cpp
@@ -133,7 +133,7 @@ ProjectExplorer::Project *CMakeManager::openProject(const QString &fileName, QSt
QString CMakeManager::mimeType() const
{
- return Constants::CMAKEMIMETYPE;
+ return QLatin1String(Constants::CMAKEMIMETYPE);
}
QString CMakeManager::cmakeExecutable() const
@@ -224,7 +224,7 @@ QString CMakeManager::qtVersionForQMake(const QString &qmakePath)
qWarning("Timeout running '%s'.", qPrintable(qmakePath));
return QString();
}
- QString output = qmake.readAllStandardOutput();
+ QString output = QString::fromLocal8Bit(qmake.readAllStandardOutput());
QRegExp regexp(QLatin1String("(QMake version|Qmake version:)[\\s]*([\\d.]*)"));
regexp.indexIn(output);
if (regexp.cap(2).startsWith(QLatin1String("2."))) {
@@ -243,109 +243,33 @@ QString CMakeManager::qtVersionForQMake(const QString &qmakePath)
CMakeSettingsPage::CMakeSettingsPage()
: m_pathchooser(0)
{
- setId(QLatin1String("Z.CMake"));
+ setId("Z.CMake");
setDisplayName(tr("CMake"));
- setCategory(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY));
+ setCategory(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
- m_userCmake.process = 0;
- m_pathCmake.process = 0;
- m_userCmake.hasCodeBlocksMsvcGenerator = false;
- m_pathCmake.hasCodeBlocksMsvcGenerator = false;
- m_userCmake.hasCodeBlocksNinjaGenerator = false;
- m_pathCmake.hasCodeBlocksNinjaGenerator = false;
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("CMakeSettings"));
- m_userCmake.executable = settings->value(QLatin1String("cmakeExecutable")).toString();
+ m_cmakeValidatorForUser.setCMakeExecutable(settings->value(QLatin1String("cmakeExecutable")).toString());
settings->endGroup();
- updateInfo(&m_userCmake);
- m_pathCmake.executable = findCmakeExecutable();
- updateInfo(&m_pathCmake);
-}
-
-void CMakeSettingsPage::startProcess(CMakeValidator *cmakeValidator)
-{
- cmakeValidator->process = new QProcess();
-
- if (cmakeValidator == &m_pathCmake) // ugly
- connect(cmakeValidator->process, SIGNAL(finished(int)),
- this, SLOT(userCmakeFinished()));
- else
- connect(cmakeValidator->process, SIGNAL(finished(int)),
- this, SLOT(pathCmakeFinished()));
-
- cmakeValidator->process->start(cmakeValidator->executable, QStringList(QLatin1String("--help")));
- cmakeValidator->process->waitForStarted();
-}
-
-void CMakeSettingsPage::userCmakeFinished()
-{
- cmakeFinished(&m_userCmake);
-}
-
-void CMakeSettingsPage::pathCmakeFinished()
-{
- cmakeFinished(&m_pathCmake);
-}
-
-void CMakeSettingsPage::cmakeFinished(CMakeValidator *cmakeValidator) const
-{
- if (cmakeValidator->process) {
- cmakeValidator->process->waitForFinished();
- QString response = cmakeValidator->process->readAll();
- QRegExp versionRegexp(QLatin1String("^cmake version ([\\d\\.]*)"));
- versionRegexp.indexIn(response);
-
- //m_supportsQtCreator = response.contains(QLatin1String("QtCreator"));
- cmakeValidator->hasCodeBlocksNinjaGenerator = response.contains(QLatin1String("CodeBlocks - Ninja"));
- cmakeValidator->hasCodeBlocksMsvcGenerator = response.contains(QLatin1String("CodeBlocks - NMake Makefiles"));
- cmakeValidator->version = versionRegexp.cap(1);
- if (!(versionRegexp.capturedTexts().size() > 3))
- cmakeValidator->version += QLatin1Char('.') + versionRegexp.cap(3);
-
- if (cmakeValidator->version.isEmpty())
- cmakeValidator->state = CMakeValidator::INVALID;
- else
- cmakeValidator->state = CMakeValidator::VALID;
-
- cmakeValidator->process->deleteLater();
- cmakeValidator->process = 0;
- }
+ m_cmakeValidatorForSystem.setCMakeExecutable(findCmakeExecutable());
}
bool CMakeSettingsPage::isCMakeExecutableValid() const
{
- if (m_userCmake.state == CMakeValidator::RUNNING) {
- disconnect(m_userCmake.process, SIGNAL(finished(int)),
- this, SLOT(userCmakeFinished()));
- m_userCmake.process->waitForFinished();
- // Parse the output now
- cmakeFinished(&m_userCmake);
- }
-
- if (m_userCmake.state == CMakeValidator::VALID)
+ if (m_cmakeValidatorForUser.isValid())
return true;
- if (m_pathCmake.state == CMakeValidator::RUNNING) {
- disconnect(m_userCmake.process, SIGNAL(finished(int)),
- this, SLOT(pathCmakeFinished()));
- m_pathCmake.process->waitForFinished();
- // Parse the output now
- cmakeFinished(&m_pathCmake);
- }
- return m_pathCmake.state == CMakeValidator::VALID;
+
+ return m_cmakeValidatorForSystem.isValid();
}
CMakeSettingsPage::~CMakeSettingsPage()
{
- if (m_userCmake.process)
- m_userCmake.process->waitForFinished();
- delete m_userCmake.process;
- if (m_pathCmake.process)
- m_pathCmake.process->waitForFinished();
- delete m_pathCmake.process;
+ m_cmakeValidatorForUser.cancel();
+ m_cmakeValidatorForSystem.cancel();
}
QString CMakeSettingsPage::findCmakeExecutable() const
@@ -363,28 +287,15 @@ QWidget *CMakeSettingsPage::createPage(QWidget *parent)
m_pathchooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
formLayout->addRow(tr("Executable:"), m_pathchooser);
formLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
- m_pathchooser->setPath(m_userCmake.executable);
+ m_pathchooser->setPath(m_cmakeValidatorForUser.cmakeExecutable());
return outerWidget;
}
-void CMakeSettingsPage::updateInfo(CMakeValidator *cmakeValidator)
-{
- QFileInfo fi(cmakeValidator->executable);
- if (fi.exists() && fi.isExecutable()) {
- // Run it to find out more
- cmakeValidator->state = CMakeValidator::RUNNING;
- startProcess(cmakeValidator);
- } else {
- cmakeValidator->state = CMakeValidator::INVALID;
- }
- saveSettings();
-}
-
void CMakeSettingsPage::saveSettings() const
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("CMakeSettings"));
- settings->setValue(QLatin1String("cmakeExecutable"), m_userCmake.executable);
+ settings->setValue(QLatin1String("cmakeExecutable"), m_cmakeValidatorForUser.cmakeExecutable());
settings->endGroup();
}
@@ -392,10 +303,10 @@ void CMakeSettingsPage::apply()
{
if (!m_pathchooser) // page was never shown
return;
- if (m_userCmake.executable == m_pathchooser->path())
+ if (m_cmakeValidatorForUser.cmakeExecutable() == m_pathchooser->path())
return;
- m_userCmake.executable = m_pathchooser->path();
- updateInfo(&m_userCmake);
+ m_cmakeValidatorForUser.setCMakeExecutable(m_pathchooser->path());
+ saveSettings();
}
void CMakeSettingsPage::finish()
@@ -407,36 +318,46 @@ QString CMakeSettingsPage::cmakeExecutable() const
{
if (!isCMakeExecutableValid())
return QString();
- if (m_userCmake.state == CMakeValidator::VALID)
- return m_userCmake.executable;
- else
- return m_pathCmake.executable;
+
+ if (m_cmakeValidatorForUser.isValid())
+ return m_cmakeValidatorForUser.cmakeExecutable();
+ if (m_cmakeValidatorForSystem.isValid())
+ return m_cmakeValidatorForSystem.cmakeExecutable();
+ return QString();
}
void CMakeSettingsPage::setCMakeExecutable(const QString &executable)
{
- if (m_userCmake.executable == executable)
+ if (m_cmakeValidatorForUser.cmakeExecutable() == executable)
return;
- m_userCmake.executable = executable;
- updateInfo(&m_userCmake);
+ m_cmakeValidatorForUser.setCMakeExecutable(executable);
}
bool CMakeSettingsPage::hasCodeBlocksMsvcGenerator() const
{
- if (!isCMakeExecutableValid())
- return false;
- if (m_userCmake.state == CMakeValidator::VALID)
- return m_userCmake.hasCodeBlocksMsvcGenerator;
- else
- return m_pathCmake.hasCodeBlocksMsvcGenerator;
+ if (m_cmakeValidatorForUser.isValid())
+ return m_cmakeValidatorForUser.hasCodeBlocksMsvcGenerator();
+ if (m_cmakeValidatorForSystem.isValid())
+ return m_cmakeValidatorForSystem.hasCodeBlocksMsvcGenerator();
+ return false;
}
bool CMakeSettingsPage::hasCodeBlocksNinjaGenerator() const
{
- if (!isCMakeExecutableValid())
- return false;
- if (m_userCmake.state == CMakeValidator::VALID)
- return m_userCmake.hasCodeBlocksNinjaGenerator;
- else
- return m_pathCmake.hasCodeBlocksNinjaGenerator;
+ if (m_cmakeValidatorForUser.isValid())
+ return m_cmakeValidatorForUser.hasCodeBlocksNinjaGenerator();
+ if (m_cmakeValidatorForSystem.isValid())
+ return m_cmakeValidatorForSystem.hasCodeBlocksNinjaGenerator();
+ return false;
+}
+
+TextEditor::Keywords CMakeSettingsPage::keywords()
+{
+ if (m_cmakeValidatorForUser.isValid())
+ return m_cmakeValidatorForUser.keywords();
+
+ if (m_cmakeValidatorForSystem.isValid())
+ return m_cmakeValidatorForSystem.keywords();
+
+ return TextEditor::Keywords(QStringList(), QStringList(), QMap<QString, QStringList>());
}
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.h b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.h
index 7edec3e1bc..b67c6654bd 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.h
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.h
@@ -35,6 +35,7 @@
#include <projectexplorer/project.h>
#include <projectexplorer/projectnodes.h>
#include <coreplugin/icontext.h>
+#include <texteditor/codeassist/keywordscompletionassist.h>
#include <utils/environment.h>
#include <utils/pathchooser.h>
@@ -42,9 +43,11 @@
#include <QFuture>
#include <QStringList>
#include <QDir>
+#include <QVector>
#include <QAction>
-QT_FORWARD_DECLARE_CLASS(QProcess)
+#include "cmakevalidator.h"
+
QT_FORWARD_DECLARE_CLASS(QLabel)
namespace Utils {
@@ -95,17 +98,6 @@ private:
ProjectExplorer::Project *m_contextProject;
};
-struct CMakeValidator
-{
- enum STATE { VALID, INVALID, RUNNING };
- STATE state;
- QProcess *process;
- bool hasCodeBlocksMsvcGenerator;
- bool hasCodeBlocksNinjaGenerator;
- QString version;
- QString executable;
-};
-
class CMakeSettingsPage : public Core::IOptionsPage
{
Q_OBJECT
@@ -124,20 +116,15 @@ public:
bool hasCodeBlocksMsvcGenerator() const;
bool hasCodeBlocksNinjaGenerator() const;
-private slots:
- void userCmakeFinished();
- void pathCmakeFinished();
+ TextEditor::Keywords keywords();
private:
- void cmakeFinished(CMakeValidator *cmakeValidator) const;
void saveSettings() const;
QString findCmakeExecutable() const;
- void startProcess(CMakeValidator *cmakeValidator);
- void updateInfo(CMakeValidator *cmakeValidator);
Utils::PathChooser *m_pathchooser;
- mutable CMakeValidator m_userCmake;
- mutable CMakeValidator m_pathCmake;
+ CMakeValidator m_cmakeValidatorForUser;
+ CMakeValidator m_cmakeValidatorForSystem;
};
} // namespace Internal
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro
index b0b516944d..e52e9a730c 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.pro
@@ -17,7 +17,9 @@ HEADERS = cmakeproject.h \
cmakeeditor.h \
cmakehighlighter.h \
cmakeuicodemodelsupport.h \
- cmakelocatorfilter.h
+ cmakelocatorfilter.h \
+ cmakefilecompletionassist.h \
+ cmakevalidator.h
SOURCES = cmakeproject.cpp \
cmakeprojectplugin.cpp \
@@ -31,7 +33,9 @@ SOURCES = cmakeproject.cpp \
cmakeeditor.cpp \
cmakehighlighter.cpp \
cmakeuicodemodelsupport.cpp \
- cmakelocatorfilter.cpp
+ cmakelocatorfilter.cpp \
+ cmakefilecompletionassist.cpp \
+ cmakevalidator.cpp
RESOURCES += cmakeproject.qrc
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs
index 541176d66a..9fdfdf9df1 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectmanager.qbs
@@ -7,21 +7,13 @@ QtcPlugin {
Depends { name: "Qt.widgets" }
Depends { name: "Core" }
- Depends { name: "ProjectExplorer" }
Depends { name: "CppTools" }
Depends { name: "CPlusPlus" }
- Depends { name: "TextEditor" }
Depends { name: "Locator" }
+ Depends { name: "ProjectExplorer" }
+ Depends { name: "TextEditor" }
Depends { name: "QtSupport" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
"CMakeProject.mimetypes.xml",
"cmakebuildconfiguration.cpp",
@@ -30,6 +22,8 @@ QtcPlugin {
"cmakeeditor.h",
"cmakeeditorfactory.cpp",
"cmakeeditorfactory.h",
+ "cmakefilecompletionassist.cpp",
+ "cmakefilecompletionassist.h",
"cmakehighlighter.cpp",
"cmakehighlighter.h",
"cmakelocatorfilter.cpp",
@@ -50,8 +44,9 @@ QtcPlugin {
"cmakerunconfiguration.h",
"cmakeuicodemodelsupport.cpp",
"cmakeuicodemodelsupport.h",
+ "cmakevalidator.cpp",
+ "cmakevalidator.h",
"makestep.cpp",
- "makestep.h"
+ "makestep.h",
]
}
-
diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp
index 23901cd023..fb6521d9eb 100644
--- a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp
@@ -35,6 +35,7 @@
#include "makestep.h"
#include "cmakeprojectconstants.h"
#include "cmakelocatorfilter.h"
+#include "cmakefilecompletionassist.h"
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
@@ -68,7 +69,7 @@ bool CMakeProjectPlugin::initialize(const QStringList & /*arguments*/, QString *
addAutoReleasedObject(new CMakeEditorFactory(manager));
addAutoReleasedObject(new CMakeLocatorFilter);
-
+ addAutoReleasedObject(new CMakeFileCompletionAssistProvider(cmp));
return true;
}
diff --git a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
index 42f18c0d40..a49f48b13c 100644
--- a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
+++ b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.cpp
@@ -103,6 +103,8 @@ CMakeRunConfiguration::~CMakeRunConfiguration()
void CMakeRunConfiguration::ctor()
{
setDefaultDisplayName(defaultDisplayName());
+ connect(target(), SIGNAL(environmentChanged()),
+ this, SIGNAL(baseEnvironmentChanged()));
}
QString CMakeRunConfiguration::executable() const
@@ -200,7 +202,7 @@ QString CMakeRunConfiguration::defaultDisplayName() const
{
if (m_title.isEmpty())
return tr("Run CMake kit");
- return m_title + (m_enabled ? "" : tr(" (disabled)"));
+ return m_title + (m_enabled ? QString() : tr(" (disabled)"));
}
QWidget *CMakeRunConfiguration::createConfigurationWidget()
@@ -568,5 +570,5 @@ QString CMakeRunConfigurationFactory::buildTargetFromId(Core::Id id)
Core::Id CMakeRunConfigurationFactory::idFromBuildTarget(const QString &target)
{
QString id = QString::fromLatin1(CMAKE_RC_PREFIX) + target;
- return Core::Id(id.toUtf8().constData());
+ return Core::Id(id.toUtf8());
}
diff --git a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.h b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.h
index 1659b68b3a..65212e3747 100644
--- a/src/plugins/cmakeprojectmanager/cmakerunconfiguration.h
+++ b/src/plugins/cmakeprojectmanager/cmakerunconfiguration.h
@@ -30,7 +30,7 @@
#ifndef CMAKERUNCONFIGURATION_H
#define CMAKERUNCONFIGURATION_H
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <utils/environment.h>
QT_BEGIN_NAMESPACE
@@ -49,7 +49,6 @@ class EnvironmentWidget;
namespace CMakeProjectManager {
namespace Internal {
-class CMakeBuildConfiguration;
class CMakeTarget;
class CMakeRunConfiguration : public ProjectExplorer::LocalApplicationRunConfiguration
diff --git a/src/plugins/cmakeprojectmanager/cmakevalidator.cpp b/src/plugins/cmakeprojectmanager/cmakevalidator.cpp
new file mode 100644
index 0000000000..61f8c7fcbf
--- /dev/null
+++ b/src/plugins/cmakeprojectmanager/cmakevalidator.cpp
@@ -0,0 +1,258 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "cmakevalidator.h"
+
+#include <QProcess>
+#include <QFileInfo>
+#include <QTextDocument>
+
+using namespace CMakeProjectManager::Internal;
+
+///////////////////////////
+// CMakeValidator
+///////////////////////////
+CMakeValidator::CMakeValidator()
+ : m_state(Invalid), m_process(0), m_hasCodeBlocksMsvcGenerator(false), m_hasCodeBlocksNinjaGenerator(false)
+{
+
+}
+
+CMakeValidator::~CMakeValidator()
+{
+ cancel();
+}
+
+void CMakeValidator::cancel()
+{
+ if (m_process) {
+ disconnect(m_process, SIGNAL(finished(int)));
+ m_process->waitForFinished();
+ delete m_process;
+ m_process = 0;
+ }
+}
+
+void CMakeValidator::setCMakeExecutable(const QString &executable)
+{
+ cancel();
+ m_process = new QProcess();
+ connect(m_process, SIGNAL(finished(int)),
+ this, SLOT(finished(int)));
+
+ m_executable = executable;
+ QFileInfo fi(m_executable);
+ if (fi.exists() && fi.isExecutable()) {
+ // Run it to find out more
+ m_state = CMakeValidator::RunningBasic;
+ if (!startProcess(QStringList(QLatin1String("--help"))))
+ m_state = CMakeValidator::Invalid;
+ } else {
+ m_state = CMakeValidator::Invalid;
+ }
+}
+
+void CMakeValidator::finished(int exitCode)
+{
+ if (exitCode) {
+ m_state = CMakeValidator::Invalid;
+ return;
+ }
+ if (m_state == CMakeValidator::RunningBasic) {
+ QByteArray response = m_process->readAll();
+ QRegExp versionRegexp(QLatin1String("^cmake version ([\\d\\.]*)"));
+ versionRegexp.indexIn(QString::fromLocal8Bit(response));
+
+ //m_supportsQtCreator = response.contains(QLatin1String("QtCreator"));
+ m_hasCodeBlocksMsvcGenerator = response.contains("CodeBlocks - NMake Makefiles");
+ m_hasCodeBlocksNinjaGenerator = response.contains("CodeBlocks - Ninja");
+ m_version = versionRegexp.cap(1);
+ if (!(versionRegexp.capturedTexts().size() > 3))
+ m_version += QLatin1Char('.') + versionRegexp.cap(3);
+
+ if (m_version.isEmpty()) {
+ m_state = CMakeValidator::Invalid;
+ } else {
+ m_state = CMakeValidator::RunningFunctionList;
+ if (!startProcess(QStringList(QLatin1String("--help-command-list"))))
+ finished(0); // shoud never happen, just continue
+ }
+ } else if (m_state == CMakeValidator::RunningFunctionList) {
+ parseFunctionOutput(m_process->readAll());
+ m_state = CMakeValidator::RunningFunctionDetails;
+ if (!startProcess(QStringList(QLatin1String("--help-commands"))))
+ finished(0); // shoud never happen, just continue
+ } else if (m_state == CMakeValidator::RunningFunctionDetails) {
+ parseFunctionDetailsOutput(m_process->readAll());
+ m_state = CMakeValidator::ValidFunctionDetails;
+ }
+}
+
+bool CMakeValidator::isValid() const
+{
+ if (m_state == CMakeValidator::Invalid)
+ return false;
+ if (m_state == CMakeValidator::RunningBasic)
+ m_process->waitForFinished();
+ return (m_state != CMakeValidator::Invalid);
+}
+
+bool CMakeValidator::startProcess(const QStringList &args)
+{
+ m_process->start(m_executable, args);
+ return m_process->waitForStarted(2000);
+}
+
+QString CMakeValidator::cmakeExecutable() const
+{
+ return m_executable;
+}
+
+bool CMakeValidator::hasCodeBlocksMsvcGenerator() const
+{
+ if (!isValid())
+ return false;
+ return m_hasCodeBlocksMsvcGenerator;
+}
+
+bool CMakeValidator::hasCodeBlocksNinjaGenerator() const
+{
+ if (!isValid())
+ return false;
+ return m_hasCodeBlocksNinjaGenerator;
+}
+
+
+TextEditor::Keywords CMakeValidator::keywords()
+{
+ while (m_state != ValidFunctionDetails && m_state != CMakeValidator::Invalid) {
+ m_process->waitForFinished();
+ }
+
+ if (m_state == CMakeValidator::Invalid)
+ return TextEditor::Keywords(QStringList(), QStringList(), QMap<QString, QStringList>());
+
+ return TextEditor::Keywords(m_variables, m_functions, m_functionArgs);
+}
+
+static void extractKeywords(const QByteArray &input, QStringList *destination)
+{
+ if (!destination)
+ return;
+
+ QString keyword;
+ int ignoreZone = 0;
+ for (int i = 0; i < input.count(); ++i) {
+ const QChar chr = QLatin1Char(input.at(i));
+ if (chr == QLatin1Char('{'))
+ ++ignoreZone;
+ if (chr == QLatin1Char('}'))
+ --ignoreZone;
+ if (ignoreZone == 0) {
+ if ((chr.isLetterOrNumber() && chr.isUpper())
+ || chr == QLatin1Char('_')) {
+ keyword += chr;
+ } else {
+ if (!keyword.isEmpty()) {
+ if (keyword.size() > 1)
+ *destination << keyword;
+ keyword.clear();
+ }
+ }
+ }
+ }
+ if (keyword.size() > 1)
+ *destination << keyword;
+}
+
+void CMakeValidator::parseFunctionOutput(const QByteArray &output)
+{
+ QList<QByteArray> cmakeFunctionsList = output.split('\n');
+ m_functions.clear();
+ if (!cmakeFunctionsList.isEmpty()) {
+ cmakeFunctionsList.removeFirst(); //remove version string
+ foreach (const QByteArray &function, cmakeFunctionsList)
+ m_functions << QString::fromLocal8Bit(function.trimmed());
+ }
+}
+
+QString CMakeValidator::formatFunctionDetails(const QString &command, const QString &args)
+{
+ return QString::fromLatin1("<table><tr><td><b>%1</b></td><td>%2</td></tr>")
+ .arg(Qt::escape(command)).arg(Qt::escape(args));
+}
+
+void CMakeValidator::parseFunctionDetailsOutput(const QByteArray &output)
+{
+ QStringList cmakeFunctionsList = m_functions;
+ QList<QByteArray> cmakeCommandsHelp = output.split('\n');
+ for (int i = 0; i < cmakeCommandsHelp.count(); ++i) {
+ QByteArray lineTrimmed = cmakeCommandsHelp.at(i).trimmed();
+ if (cmakeFunctionsList.first().toLatin1() == lineTrimmed) {
+ QStringList commandSyntaxes;
+ QString currentCommandSyntax;
+ QString currentCommand = cmakeFunctionsList.takeFirst();
+ ++i;
+ for (; i < cmakeCommandsHelp.count(); ++i) {
+ lineTrimmed = cmakeCommandsHelp.at(i).trimmed();
+
+ if (cmakeFunctionsList.first().toLatin1() == lineTrimmed) {
+ //start of next function in output
+ if (!currentCommandSyntax.isEmpty())
+ commandSyntaxes << currentCommandSyntax.append(QLatin1String("</table>"));
+ --i;
+ break;
+ }
+ if (lineTrimmed.startsWith(currentCommand.toLatin1() + "(")) {
+ if (!currentCommandSyntax.isEmpty())
+ commandSyntaxes << currentCommandSyntax.append(QLatin1String("</table>"));
+
+ QByteArray argLine = lineTrimmed.mid(currentCommand.length());
+ extractKeywords(argLine, &m_variables);
+ currentCommandSyntax = formatFunctionDetails(currentCommand, QString::fromUtf8(argLine));
+ } else {
+ if (!currentCommandSyntax.isEmpty()) {
+ if (lineTrimmed.isEmpty()) {
+ commandSyntaxes << currentCommandSyntax.append(QLatin1String("</table>"));
+ currentCommandSyntax.clear();
+ } else {
+ extractKeywords(lineTrimmed, &m_variables);
+ currentCommandSyntax += QString::fromLatin1("<tr><td>&nbsp;</td><td>%1</td></tr>")
+ .arg(Qt::escape(QString::fromLocal8Bit(lineTrimmed)));
+ }
+ }
+ }
+ }
+ m_functionArgs[currentCommand] = commandSyntaxes;
+ }
+ }
+ m_functions = m_functionArgs.keys();
+ m_variables.sort();
+ m_variables.removeDuplicates();
+}
diff --git a/src/plugins/madde/maemodeployconfigurationwidget.h b/src/plugins/cmakeprojectmanager/cmakevalidator.h
index 68d7abe354..01c4f274fe 100644
--- a/src/plugins/madde/maemodeployconfigurationwidget.h
+++ b/src/plugins/cmakeprojectmanager/cmakevalidator.h
@@ -27,52 +27,59 @@
**
****************************************************************************/
-#ifndef MAEMODEPLOYCONFIGURATIONWIDGET_H
-#define MAEMODEPLOYCONFIGURATIONWIDGET_H
+#ifndef CMAKEVALIDATOR_H
+#define CMAKEVALIDATOR_H
-#include <projectexplorer/deployconfiguration.h>
+#include <QObject>
+#include <QString>
+#include <QStringList>
+#include <texteditor/codeassist/keywordscompletionassist.h>
-namespace RemoteLinux {
-class DeployableFilesPerProFile;
-class RemoteLinuxDeployConfigurationWidget;
-}
+QT_FORWARD_DECLARE_CLASS(QProcess)
-namespace Madde {
+namespace CMakeProjectManager {
namespace Internal {
-class Qt4MaemoDeployConfiguration;
-namespace Ui { class MaemoDeployConfigurationWidget; }
-
-
-class MaemoDeployConfigurationWidget : public ProjectExplorer::DeployConfigurationWidget
+class CMakeValidator : public QObject
{
Q_OBJECT
-
public:
- explicit MaemoDeployConfigurationWidget(QWidget *parent = 0);
- ~MaemoDeployConfigurationWidget();
+ CMakeValidator();
+ ~CMakeValidator();
- void init(ProjectExplorer::DeployConfiguration *dc);
-
- Qt4MaemoDeployConfiguration *deployConfiguration() const;
+ enum State { Invalid, RunningBasic, RunningFunctionList, RunningFunctionDetails, ValidFunctionDetails };
+ void cancel();
+ bool isValid() const;
+ void setCMakeExecutable(const QString &executable);
+ QString cmakeExecutable() const;
+ bool hasCodeBlocksMsvcGenerator() const;
+ bool hasCodeBlocksNinjaGenerator() const;
+ TextEditor::Keywords keywords();
private slots:
- void addDesktopFile();
- void addIcon();
- void handleDeploymentInfoToBeReset();
- void handleCurrentModelChanged(const RemoteLinux::DeployableFilesPerProFile *proFileInfo);
+ void finished(int exitCode);
private:
- bool canAddDesktopFile(const RemoteLinux::DeployableFilesPerProFile *proFileInfo) const;
- bool canAddIcon(const RemoteLinux::DeployableFilesPerProFile *proFileInfo) const;
- QString remoteIconFilePath(const RemoteLinux::DeployableFilesPerProFile *proFileInfo) const;
- QString remoteIconDir() const;
+ void finishStep();
+ void startNextStep();
+ bool startProcess(const QStringList &args);
+ void parseFunctionOutput(const QByteArray &output);
+ void parseFunctionDetailsOutput(const QByteArray &output);
+ QString formatFunctionDetails(const QString &command, const QString &args);
+
+ State m_state;
+ QProcess *m_process;
+ bool m_hasCodeBlocksMsvcGenerator;
+ bool m_hasCodeBlocksNinjaGenerator;
+ QString m_version;
+ QString m_executable;
- Ui::MaemoDeployConfigurationWidget *ui;
- RemoteLinux::RemoteLinuxDeployConfigurationWidget * const m_remoteLinuxWidget;
+ QMap<QString, QStringList> m_functionArgs;
+ QStringList m_variables;
+ QStringList m_functions;
};
} // namespace Internal
-} // namespace Madde
+} // namespace CMakeProjectManager
-#endif // MAEMODEPLOYCONFIGURATIONWIDGET_H
+#endif // CMAKEVALIDATOR_H
diff --git a/src/plugins/cmakeprojectmanager/makestep.cpp b/src/plugins/cmakeprojectmanager/makestep.cpp
index 7c47fcd52a..7806809d67 100644
--- a/src/plugins/cmakeprojectmanager/makestep.cpp
+++ b/src/plugins/cmakeprojectmanager/makestep.cpp
@@ -91,8 +91,8 @@ MakeStep::MakeStep(BuildStepList *bsl, MakeStep *bs) :
void MakeStep::ctor()
{
- m_percentProgress = QRegExp("^\\[\\s*(\\d*)%\\]");
- m_ninjaProgress = QRegExp ("^\\[\\s*(\\d*)/\\s*(\\d*)");
+ m_percentProgress = QRegExp(QLatin1String("^\\[\\s*(\\d*)%\\]"));
+ m_ninjaProgress = QRegExp(QLatin1String("^\\[\\s*(\\d*)/\\s*(\\d*)"));
m_ninjaProgressString = QLatin1String("[%s/%t "); // ninja: [33/100
//: Default display name for the cmake make step.
setDefaultDisplayName(tr("Make"));
@@ -198,14 +198,12 @@ bool MakeStep::init()
pp->setWorkingDirectory(bc->buildDirectory());
pp->setCommand(makeCommand(tc, bc->environment()));
pp->setArguments(arguments);
+ pp->resolveAll();
setOutputParser(new ProjectExplorer::GnuMakeParser());
-
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- if (version)
- appendOutputParser(new QtSupport::QtParser);
- if (tc)
- appendOutputParser(tc->outputParser());
+ IOutputParser *parser = target()->kit()->createOutputParser();
+ if (parser)
+ appendOutputParser(parser);
outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());
return AbstractProcessStep::init();
@@ -398,9 +396,9 @@ void MakeStepConfigWidget::buildTargetsChanged()
void MakeStepConfigWidget::updateDetails()
{
- CMakeBuildConfiguration *bc = m_makeStep->cmakeBuildConfiguration();
+ BuildConfiguration *bc = m_makeStep->buildConfiguration();
if (!bc)
- bc = static_cast<CMakeBuildConfiguration *>(m_makeStep->target()->activeBuildConfiguration());
+ bc = m_makeStep->target()->activeBuildConfiguration();
if (!bc) {
m_summaryText = tr("<b>No build configuration found on this kit.</b>");
updateSummary();
@@ -457,7 +455,7 @@ BuildStep *MakeStepFactory::create(BuildStepList *parent, const Core::Id id)
MakeStep *step = new MakeStep(parent);
if (parent->id() == ProjectExplorer::Constants::BUILDSTEPS_CLEAN) {
step->setClean(true);
- step->setAdditionalArguments("clean");
+ step->setAdditionalArguments(QLatin1String("clean"));
}
return step;
}
diff --git a/src/plugins/coreplugin/actionmanager/actioncontainer.cpp b/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
index 869b25b00d..8c792830a6 100644
--- a/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
+++ b/src/plugins/coreplugin/actionmanager/actioncontainer.cpp
@@ -307,9 +307,8 @@ Command *ActionContainerPrivate::addSeparator(const Context &context, const Id &
static int separatorIdCount = 0;
QAction *separator = new QAction(this);
separator->setSeparator(true);
- Command *cmd = ActionManager::registerAction(separator, Id(QString::fromLatin1("%1.Separator.%2")
- .arg(id().toString()).arg(++separatorIdCount)),
- context);
+ Id sepId = id().withSuffix(".Separator.").withSuffix(++separatorIdCount);
+ Command *cmd = ActionManager::registerAction(separator, sepId, context);
addAction(cmd, group);
if (outSeparator)
*outSeparator = separator;
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager.cpp b/src/plugins/coreplugin/actionmanager/actionmanager.cpp
index b8a79b4783..574b97cf94 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager.cpp
+++ b/src/plugins/coreplugin/actionmanager/actionmanager.cpp
@@ -258,6 +258,7 @@ Command *ActionManager::registerAction(QAction *action, const Id &id, const Cont
*/
Command *ActionManager::registerShortcut(QShortcut *shortcut, const Id &id, const Context &context, bool scriptable)
{
+ QTC_CHECK(!context.isEmpty());
Shortcut *sc = 0;
if (CommandPrivate *c = m_instance->d->m_idCmdMap.value(id, 0)) {
sc = qobject_cast<Shortcut *>(c);
@@ -282,11 +283,7 @@ Command *ActionManager::registerShortcut(QShortcut *shortcut, const Id &id, cons
shortcut->setParent(ICore::mainWindow());
sc->setShortcut(shortcut);
sc->setScriptable(scriptable);
-
- if (context.isEmpty())
- sc->setContext(Context(0));
- else
- sc->setContext(context);
+ sc->setContext(context);
emit m_instance->commandListChanged();
emit m_instance->commandAdded(id.toString());
@@ -445,11 +442,6 @@ bool ActionManager::isPresentationModeEnabled()
return m_instance->d->m_presentationLabel;
}
-bool ActionManager::hasContext(int context)
-{
- return m_instance->d->m_context.contains(context);
-}
-
/*!
\class ActionManagerPrivate
\inheaderfile actionmanager_p.h
@@ -471,12 +463,12 @@ ActionManagerPrivate::~ActionManagerPrivate()
qDeleteAll(m_idCmdMap.values());
}
-QDebug operator<<(QDebug in, const Context &context)
+QDebug operator<<(QDebug d, const Context &context)
{
- in << "CONTEXT: ";
- foreach (int c, context)
- in << " " << c << Id::fromUniqueIdentifier(c).toString();
- return in;
+ d << "CONTEXT: ";
+ foreach (Id id, context)
+ d << " " << id.uniqueIdentifier() << " " << id.toString();
+ return d;
}
void ActionManagerPrivate::setContext(const Context &context)
@@ -571,7 +563,7 @@ void ActionManagerPrivate::initialize()
for (int i = 0; i < shortcuts; ++i) {
settings->setArrayIndex(i);
const QKeySequence key(settings->value(QLatin1String(sequenceKey)).toString());
- const Id id = Id(settings->value(QLatin1String(idKey)).toString());
+ const Id id = Id::fromSetting(settings->value(QLatin1String(idKey)));
Command *cmd = ActionManager::command(id);
if (cmd)
diff --git a/src/plugins/coreplugin/actionmanager/actionmanager.h b/src/plugins/coreplugin/actionmanager/actionmanager.h
index c13af9e106..b9b666a14c 100644
--- a/src/plugins/coreplugin/actionmanager/actionmanager.h
+++ b/src/plugins/coreplugin/actionmanager/actionmanager.h
@@ -76,8 +76,6 @@ public:
static void setPresentationModeEnabled(bool enabled);
static bool isPresentationModeEnabled();
- static bool hasContext(int context);
-
signals:
void commandListChanged();
void commandAdded(const QString &id);
diff --git a/src/plugins/coreplugin/actionmanager/command.cpp b/src/plugins/coreplugin/actionmanager/command.cpp
index fffe203840..87136bb196 100644
--- a/src/plugins/coreplugin/actionmanager/command.cpp
+++ b/src/plugins/coreplugin/actionmanager/command.cpp
@@ -33,6 +33,8 @@
#include "icontext.h"
#include "id.h"
+#include <utils/hostosinfo.h>
+
#include <QDebug>
#include <QTextStream>
@@ -331,8 +333,8 @@ QKeySequence Shortcut::keySequence() const
void Shortcut::setCurrentContext(const Core::Context &context)
{
- foreach (int ctxt, m_context) {
- if (context.contains(ctxt)) {
+ foreach (Id id, m_context) {
+ if (context.contains(id)) {
if (!m_shortcut->isEnabled()) {
m_shortcut->setEnabled(true);
emit activeStateChanged();
@@ -421,7 +423,7 @@ void Action::updateActiveState()
setActive(m_action->isEnabled() && m_action->isVisible() && !m_action->isSeparator());
}
-static QString msgActionWarning(QAction *newAction, int k, QAction *oldAction)
+static QString msgActionWarning(QAction *newAction, Id id, QAction *oldAction)
{
QString msg;
QTextStream str(&msg);
@@ -429,27 +431,25 @@ static QString msgActionWarning(QAction *newAction, int k, QAction *oldAction)
<< ": Action ";
if (oldAction)
str << oldAction->objectName() << '/' << oldAction->text();
- str << " is already registered for context " << k << ' '
- << Core::Id::fromUniqueIdentifier(k).toString()
- << '.';
+ str << " is already registered for context " << id.uniqueIdentifier() << ' '
+ << id.toString() << '.';
return msg;
}
void Action::addOverrideAction(QAction *action, const Core::Context &context, bool scriptable)
{
-#ifdef Q_OS_MAC
- action->setIconVisibleInMenu(false);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ action->setIconVisibleInMenu(false);
if (isEmpty())
m_action->initialize(action);
if (context.isEmpty()) {
m_contextActionMap.insert(0, action);
} else {
for (int i = 0; i < context.size(); ++i) {
- int k = context.at(i);
- if (m_contextActionMap.contains(k))
- qWarning("%s", qPrintable(msgActionWarning(action, k, m_contextActionMap.value(k, 0))));
- m_contextActionMap.insert(k, action);
+ Id id = context.at(i);
+ if (m_contextActionMap.contains(id))
+ qWarning("%s", qPrintable(msgActionWarning(action, id, m_contextActionMap.value(id, 0))));
+ m_contextActionMap.insert(id, action);
}
}
m_scriptableMap[action] = scriptable;
@@ -458,14 +458,13 @@ void Action::addOverrideAction(QAction *action, const Core::Context &context, bo
void Action::removeOverrideAction(QAction *action)
{
- QMutableMapIterator<int, QPointer<QAction> > it(m_contextActionMap);
+ QMutableMapIterator<Id, QPointer<QAction> > it(m_contextActionMap);
while (it.hasNext()) {
it.next();
- if (it.value() == 0) {
+ if (it.value() == 0)
it.remove();
- } else if (it.value() == action) {
+ else if (it.value() == action)
it.remove();
- }
}
setCurrentContext(m_context);
}
diff --git a/src/plugins/coreplugin/actionmanager/command_p.h b/src/plugins/coreplugin/actionmanager/command_p.h
index 6adbca94b2..a2ead8551d 100644
--- a/src/plugins/coreplugin/actionmanager/command_p.h
+++ b/src/plugins/coreplugin/actionmanager/command_p.h
@@ -145,7 +145,7 @@ private:
Utils::ProxyAction *m_action;
QString m_toolTip;
- QMap<int, QPointer<QAction> > m_contextActionMap;
+ QMap<Id, QPointer<QAction> > m_contextActionMap;
QMap<QAction*, bool> m_scriptableMap;
bool m_active;
bool m_contextInitialized;
diff --git a/src/plugins/coreplugin/actionmanager/commandmappings.cpp b/src/plugins/coreplugin/actionmanager/commandmappings.cpp
index 68ca2c63a9..52258a1759 100644
--- a/src/plugins/coreplugin/actionmanager/commandmappings.cpp
+++ b/src/plugins/coreplugin/actionmanager/commandmappings.cpp
@@ -36,6 +36,7 @@
#include "icore.h"
#include "id.h"
+#include <utils/hostosinfo.h>
#include <utils/treewidgetcolumnstretcher.h>
#include <QKeyEvent>
@@ -165,18 +166,18 @@ bool CommandMappings::filter(const QString &filterString, QTreeWidgetItem *item)
int columnCount = item->columnCount();
for (int i = 0; !visible && i < columnCount; ++i) {
QString text = item->text(i);
-#ifdef Q_OS_MAC
- // accept e.g. Cmd+E in the filter. the text shows special fancy characters for Cmd
- if (i == columnCount - 1) {
- QKeySequence key = QKeySequence::fromString(text, QKeySequence::NativeText);
- if (!key.isEmpty()) {
- text = key.toString(QKeySequence::PortableText);
- text.replace(QLatin1String("Ctrl"), QLatin1String("Cmd"));
- text.replace(QLatin1String("Meta"), QLatin1String("Ctrl"));
- text.replace(QLatin1String("Alt"), QLatin1String("Opt"));
+ if (Utils::HostOsInfo::isMacHost()) {
+ // accept e.g. Cmd+E in the filter. the text shows special fancy characters for Cmd
+ if (i == columnCount - 1) {
+ QKeySequence key = QKeySequence::fromString(text, QKeySequence::NativeText);
+ if (!key.isEmpty()) {
+ text = key.toString(QKeySequence::PortableText);
+ text.replace(QLatin1String("Ctrl"), QLatin1String("Cmd"));
+ text.replace(QLatin1String("Meta"), QLatin1String("Ctrl"));
+ text.replace(QLatin1String("Alt"), QLatin1String("Opt"));
+ }
}
}
-#endif
visible |= (bool)text.contains(filterString, Qt::CaseInsensitive);
}
diff --git a/src/plugins/coreplugin/actionmanager/commandsfile.cpp b/src/plugins/coreplugin/actionmanager/commandsfile.cpp
index a9ab7f9a67..46bb4ad5fa 100644
--- a/src/plugins/coreplugin/actionmanager/commandsfile.cpp
+++ b/src/plugins/coreplugin/actionmanager/commandsfile.cpp
@@ -140,7 +140,7 @@ bool CommandsFile::exportCommands(const QList<ShortcutItem *> &items)
w.setAutoFormattingIndent(1); // Historical, used to be QDom.
w.writeStartDocument();
w.writeDTD(QLatin1String("<!DOCTYPE KeyboardMappingScheme>"));
- w.writeComment(QString::fromAscii(" Written by Qt Creator %1, %2. ").
+ w.writeComment(QString::fromLatin1(" Written by Qt Creator %1, %2. ").
arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),
QDateTime::currentDateTime().toString(Qt::ISODate)));
w.writeStartElement(ctx.mappingElement);
diff --git a/src/plugins/coreplugin/basefilewizard.cpp b/src/plugins/coreplugin/basefilewizard.cpp
index 46a70a39b7..bac79c0f78 100644
--- a/src/plugins/coreplugin/basefilewizard.cpp
+++ b/src/plugins/coreplugin/basefilewizard.cpp
@@ -40,6 +40,7 @@
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <utils/fileutils.h>
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QFile>
@@ -546,7 +547,8 @@ void BaseFileWizard::runWizard(const QString &path, QWidget *parent, const QStri
// Post generation handler
if (!postGenerateFiles(wizard.data(), files, &errorMessage))
- QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
+ if (!errorMessage.isEmpty())
+ QMessageBox::critical(0, tr("File Generation Failure"), errorMessage);
}
@@ -603,15 +605,15 @@ void BaseFileWizard::setupWizard(QWizard *w)
w->setOption(QWizard::NoBackButtonOnStartPage, true);
w->setWindowFlags(w->windowFlags() & ~Qt::WindowContextHelpButtonHint);
-#ifdef Q_OS_MAC
- w->setButtonLayout(QList<QWizard::WizardButton>()
- << QWizard::CancelButton
- << QWizard::Stretch
- << QWizard::BackButton
- << QWizard::NextButton
- << QWizard::CommitButton
- << QWizard::FinishButton);
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ w->setButtonLayout(QList<QWizard::WizardButton>()
+ << QWizard::CancelButton
+ << QWizard::Stretch
+ << QWizard::BackButton
+ << QWizard::NextButton
+ << QWizard::CommitButton
+ << QWizard::FinishButton);
+ }
}
/*!
@@ -651,7 +653,7 @@ bool BaseFileWizard::postGenerateFiles(const QWizard *, const GeneratedFiles &l,
bool BaseFileWizard::postGenerateOpenEditors(const GeneratedFiles &l, QString *errorMessage)
{
- foreach(const Core::GeneratedFile &file, l) {
+ foreach (const Core::GeneratedFile &file, l) {
if (file.attributes() & Core::GeneratedFile::OpenEditorAttribute) {
if (!Core::EditorManager::openEditor(file.path(), file.editorId(), Core::EditorManager::ModeSwitch )) {
if (errorMessage)
diff --git a/src/plugins/coreplugin/coreconstants.h b/src/plugins/coreplugin/coreconstants.h
index 4234774058..79b42fc326 100644
--- a/src/plugins/coreplugin/coreconstants.h
+++ b/src/plugins/coreplugin/coreconstants.h
@@ -227,6 +227,8 @@ const char VARIABLE_SUPPORT_PROPERTY[] = "QtCreator.VariableSupport";
const char TR_CLEAR_MENU[] = QT_TRANSLATE_NOOP("Core", "Clear Menu");
+const char DEFAULT_BUILD_DIRECTORY[] = "../build-%{CurrentProject:Name}-%{CurrentKit:FileSystemName}-%{CurrentBuild:Name}";
+
const int TARGET_ICON_SIZE = 32;
} // namespace Constants
diff --git a/src/plugins/coreplugin/coreplugin.cpp b/src/plugins/coreplugin/coreplugin.cpp
index 966153437f..f5ea9aeb70 100644
--- a/src/plugins/coreplugin/coreplugin.cpp
+++ b/src/plugins/coreplugin/coreplugin.cpp
@@ -37,8 +37,10 @@
#include "mainwindow.h"
#include "mimedatabase.h"
#include "modemanager.h"
+#include "infobar.h"
#include <extensionsystem/pluginmanager.h>
+#include <utils/savefile.h>
#include <QtPlugin>
#include <QDebug>
@@ -92,7 +94,12 @@ bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage)
addObject(m_editMode);
ModeManager::activateMode(m_editMode->id());
m_designMode = new DesignMode;
+ InfoBar::initializeGloballySuppressed();
}
+
+ // Make sure we respect the process's umask when creating new files
+ Utils::SaveFile::initializeUmask();
+
return success;
}
diff --git a/src/plugins/coreplugin/coreplugin.pro b/src/plugins/coreplugin/coreplugin.pro
index 381f6a6e57..bb02bfc631 100644
--- a/src/plugins/coreplugin/coreplugin.pro
+++ b/src/plugins/coreplugin/coreplugin.pro
@@ -207,7 +207,6 @@ FORMS += dialogs/newdialog.ui \
actionmanager/commandmappings.ui \
dialogs/saveitemsdialog.ui \
dialogs/openwithdialog.ui \
- editormanager/openeditorsview.ui \
generalsettings.ui \
dialogs/externaltoolconfig.ui \
variablechooser.ui \
diff --git a/src/plugins/coreplugin/coreplugin.qbs b/src/plugins/coreplugin/coreplugin.qbs
index cf50a57299..b8250e8cfb 100644
--- a/src/plugins/coreplugin/coreplugin.qbs
+++ b/src/plugins/coreplugin/coreplugin.qbs
@@ -13,20 +13,17 @@ QtcPlugin {
Depends { name: "Utils" }
Depends { name: "ExtensionSystem" }
Depends { name: "Aggregation" }
+ Depends { name: "app_version_header" }
- cpp.includePaths: [
- ".",
- "..",
+ cpp.includePaths: base.concat([
"../..",
- "../../libs",
- "../../../src/shared/scriptwrapper/",
+ "../../shared/scriptwrapper",
"dialogs",
"editormanager",
"progressmanager",
"scriptmanager",
- "actionmanager",
- buildDirectory
- ]
+ "actionmanager"
+ ])
cpp.dynamicLibraries: {
if (qbs.targetOS == "windows") return [
@@ -36,8 +33,6 @@ QtcPlugin {
}
files: [
- "fancyactionbar.qrc",
- "generalsettings.ui",
"basefilewizard.cpp",
"basefilewizard.h",
"core.qrc",
@@ -47,6 +42,8 @@ QtcPlugin {
"coreplugin.h",
"designmode.cpp",
"designmode.h",
+ "documentmanager.cpp",
+ "documentmanager.h",
"editmode.cpp",
"editmode.h",
"editortoolbar.cpp",
@@ -56,10 +53,11 @@ QtcPlugin {
"externaltoolmanager.h",
"fancyactionbar.cpp",
"fancyactionbar.h",
+ "fancyactionbar.qrc",
"fancytabwidget.cpp",
"fancytabwidget.h",
- "featureprovider.h",
"featureprovider.cpp",
+ "featureprovider.h",
"fileiconprovider.cpp",
"fileiconprovider.h",
"fileutils.cpp",
@@ -68,6 +66,7 @@ QtcPlugin {
"findplaceholder.h",
"generalsettings.cpp",
"generalsettings.h",
+ "generalsettings.ui",
"generatedfile.cpp",
"generatedfile.h",
"helpmanager.cpp",
@@ -77,20 +76,21 @@ QtcPlugin {
"icore.cpp",
"icore.h",
"icorelistener.h",
+ "id.cpp",
"id.h",
- "ifilewizardextension.h",
- "imode.cpp",
- "imode.h",
- "documentmanager.cpp",
- "documentmanager.h",
"idocument.cpp",
"idocument.h",
"idocumentfactory.h",
+ "ifilewizardextension.h",
+ "imode.cpp",
+ "imode.h",
"inavigationwidgetfactory.cpp",
"inavigationwidgetfactory.h",
"infobar.cpp",
"infobar.h",
"ioutputpane.h",
+ "iversioncontrol.cpp",
+ "iversioncontrol.h",
"mainwindow.cpp",
"mainwindow.h",
"manhattanstyle.cpp",
@@ -146,18 +146,15 @@ QtcPlugin {
"textdocument.h",
"toolsettings.cpp",
"toolsettings.h",
+ "variablechooser.cpp",
"variablechooser.h",
"variablechooser.ui",
- "vcsmanager.h",
- "versiondialog.cpp",
- "versiondialog.h",
- "id.cpp",
- "iversioncontrol.cpp",
- "iversioncontrol.h",
- "variablechooser.cpp",
"variablemanager.cpp",
"variablemanager.h",
"vcsmanager.cpp",
+ "vcsmanager.h",
+ "versiondialog.cpp",
+ "versiondialog.h",
"actionmanager/actioncontainer.cpp",
"actionmanager/actioncontainer.h",
"actionmanager/actioncontainer_p.h",
@@ -167,23 +164,23 @@ QtcPlugin {
"actionmanager/command.cpp",
"actionmanager/command.h",
"actionmanager/command_p.h",
- "actionmanager/commandbutton.h",
"actionmanager/commandbutton.cpp",
+ "actionmanager/commandbutton.h",
"actionmanager/commandmappings.cpp",
"actionmanager/commandmappings.h",
"actionmanager/commandmappings.ui",
"actionmanager/commandsfile.cpp",
"actionmanager/commandsfile.h",
- "dialogs/externaltoolconfig.ui",
- "dialogs/newdialog.ui",
"dialogs/externaltoolconfig.cpp",
"dialogs/externaltoolconfig.h",
+ "dialogs/externaltoolconfig.ui",
"dialogs/ioptionspage.cpp",
"dialogs/ioptionspage.h",
"dialogs/iwizard.cpp",
"dialogs/iwizard.h",
"dialogs/newdialog.cpp",
"dialogs/newdialog.h",
+ "dialogs/newdialog.ui",
"dialogs/openwithdialog.cpp",
"dialogs/openwithdialog.h",
"dialogs/openwithdialog.ui",
@@ -197,25 +194,24 @@ QtcPlugin {
"dialogs/shortcutsettings.cpp",
"dialogs/shortcutsettings.h",
"editormanager/BinFiles.mimetypes.xml",
+ "editormanager/editormanager.cpp",
+ "editormanager/editormanager.h",
"editormanager/editorview.cpp",
"editormanager/editorview.h",
"editormanager/ieditor.cpp",
"editormanager/ieditor.h",
- "editormanager/ieditorfactory.h",
"editormanager/ieditorfactory.cpp",
+ "editormanager/ieditorfactory.h",
"editormanager/iexternaleditor.cpp",
"editormanager/iexternaleditor.h",
"editormanager/openeditorsmodel.cpp",
"editormanager/openeditorsmodel.h",
"editormanager/openeditorsview.cpp",
"editormanager/openeditorsview.h",
- "editormanager/openeditorsview.ui",
"editormanager/openeditorswindow.cpp",
"editormanager/openeditorswindow.h",
"editormanager/systemeditor.cpp",
"editormanager/systemeditor.h",
- "editormanager/editormanager.cpp",
- "editormanager/editormanager.h",
"progressmanager/futureprogress.cpp",
"progressmanager/futureprogress.h",
"progressmanager/progressbar.cpp",
@@ -228,27 +224,27 @@ QtcPlugin {
"scriptmanager/metatypedeclarations.h",
"scriptmanager/scriptmanager.cpp",
"scriptmanager/scriptmanager.h",
- "scriptmanager/scriptmanager_p.h"
+ "scriptmanager/scriptmanager_p.h",
]
Group {
condition: qbs.targetOS == "windows"
files: [
- "progressmanager/progressmanager_win.cpp"
+ "progressmanager/progressmanager_win.cpp",
]
}
Group {
condition: qbs.targetOS == "macx"
files: [
- "progressmanager/progressmanager_mac.mm"
+ "progressmanager/progressmanager_mac.mm",
]
}
Group {
condition: qbs.targetOS == "linux"
files: [
- "progressmanager/progressmanager_x11.cpp"
+ "progressmanager/progressmanager_x11.cpp",
]
}
@@ -257,11 +253,5 @@ QtcPlugin {
Depends { name: "Aggregation" }
Depends { name: "ExtensionSystem" }
Depends { name: "Utils" }
- cpp.includePaths: [
- "../..",
- "../../libs",
- product.buildDirectory + "/.obj/Core/actionmanager"
- ]
}
}
-
diff --git a/src/plugins/coreplugin/designmode.cpp b/src/plugins/coreplugin/designmode.cpp
index 3b529704aa..4e7a5cdc80 100644
--- a/src/plugins/coreplugin/designmode.cpp
+++ b/src/plugins/coreplugin/designmode.cpp
@@ -44,6 +44,7 @@
#include <QPair>
#include <QFileInfo>
+#include <QPointer>
#include <QStringList>
#include <QDebug>
@@ -100,7 +101,7 @@ public:
public:
Internal::DesignModeCoreListener *m_coreListener;
- QWeakPointer<Core::IEditor> m_currentEditor;
+ QPointer<Core::IEditor> m_currentEditor;
bool m_isActive;
bool m_isRequired;
QList<DesignEditorInfo*> m_editors;
@@ -166,7 +167,7 @@ bool DesignMode::designModeIsRequired() const
QStringList DesignMode::registeredMimeTypes() const
{
QStringList rc;
- foreach(const DesignEditorInfo *i, d->m_editors)
+ foreach (const DesignEditorInfo *i, d->m_editors)
rc += i->mimeTypes;
return rc;
}
@@ -194,7 +195,7 @@ void DesignMode::registerDesignWidget(QWidget *widget,
void DesignMode::unregisterDesignWidget(QWidget *widget)
{
d->m_stackWidget->removeWidget(widget);
- foreach(DesignEditorInfo *info, d->m_editors) {
+ foreach (DesignEditorInfo *info, d->m_editors) {
if (info->widget == widget) {
d->m_editors.removeAll(info);
break;
@@ -236,10 +237,10 @@ void DesignMode::currentEditorChanged(Core::IEditor *editor)
if (ModeManager::currentMode() == this)
ModeManager::activateMode(Core::Constants::MODE_EDIT);
setEnabled(false);
- d->m_currentEditor = QWeakPointer<Core::IEditor>();
+ d->m_currentEditor = 0;
emit actionsUpdated(d->m_currentEditor.data());
} else {
- d->m_currentEditor = QWeakPointer<Core::IEditor>(editor);
+ d->m_currentEditor = editor;
if (d->m_currentEditor)
connect(d->m_currentEditor.data(), SIGNAL(changed()), this, SLOT(updateActions()));
diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp b/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp
index 329a0bf7cb..d7bfdeb12a 100644
--- a/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp
+++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.cpp
@@ -30,10 +30,13 @@
#include "externaltoolconfig.h"
#include "ui_externaltoolconfig.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/variablechooser.h>
+#include <coreplugin/variablemanager.h>
#include <QTextStream>
#include <QFile>
@@ -180,9 +183,8 @@ QModelIndex ExternalToolModel::index(int row, int column, const QModelIndex &par
QString category = categoryForIndex(parent, &found);
if (found) {
QList<ExternalTool *> items = m_tools.value(category);
- if (row < items.count()) {
+ if (row < items.count())
return createIndex(row, 0, items.at(row));
- }
}
} else if (column == 0 && row < m_tools.keys().count()) {
return createIndex(row, 0);
@@ -209,14 +211,12 @@ int ExternalToolModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
return m_tools.keys().count();
- if (toolForIndex(parent)) {
+ if (toolForIndex(parent))
return 0;
- }
bool found;
QString category = categoryForIndex(parent, &found);
- if (found) {
+ if (found)
return m_tools.value(category).count();
- }
return 0;
}
@@ -350,13 +350,13 @@ QModelIndex ExternalToolModel::addTool(const QModelIndex &atIndex)
tool->setDescription(tr("This tool prints a line of useful text"));
//: Sample external tool text
const QString text = tr("Useful text");
-#ifdef Q_OS_WIN
- tool->setExecutables(QStringList(QLatin1String("cmd")));
- tool->setArguments(QLatin1String("/c echo ") + text);
-#else
- tool->setExecutables(QStringList(QLatin1String("echo")));
- tool->setArguments(text);
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ tool->setExecutables(QStringList(QLatin1String("cmd")));
+ tool->setArguments(QLatin1String("/c echo ") + text);
+ } else {
+ tool->setExecutables(QStringList(QLatin1String("echo")));
+ tool->setArguments(text);
+ }
int pos;
QModelIndex parent;
@@ -419,6 +419,7 @@ ExternalToolConfig::ExternalToolConfig(QWidget *parent) :
connect(ui->executable, SIGNAL(editingFinished()), this, SLOT(updateCurrentItem()));
connect(ui->executable, SIGNAL(browsingFinished()), this, SLOT(updateCurrentItem()));
connect(ui->arguments, SIGNAL(editingFinished()), this, SLOT(updateCurrentItem()));
+ connect(ui->arguments, SIGNAL(editingFinished()), this, SLOT(updateEffectiveArguments()));
connect(ui->workingDirectory, SIGNAL(editingFinished()), this, SLOT(updateCurrentItem()));
connect(ui->workingDirectory, SIGNAL(browsingFinished()), this, SLOT(updateCurrentItem()));
connect(ui->outputBehavior, SIGNAL(activated(int)), this, SLOT(updateCurrentItem()));
@@ -558,6 +559,7 @@ void ExternalToolConfig::showInfoForItem(const QModelIndex &index)
ui->description->setCursorPosition(0);
ui->arguments->setCursorPosition(0);
+ updateEffectiveArguments();
}
QMap<QString, QList<ExternalTool *> > ExternalToolConfig::tools() const
@@ -604,3 +606,9 @@ void ExternalToolConfig::addCategory()
ui->toolTree->selectionModel()->setCurrentIndex(index, QItemSelectionModel::SelectCurrent);
ui->toolTree->edit(index);
}
+
+void ExternalToolConfig::updateEffectiveArguments()
+{
+ ui->effectiveArguments->setText(Utils::QtcProcess::expandMacros(ui->arguments->text(),
+ Core::VariableManager::instance()->macroExpander()));
+}
diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.h b/src/plugins/coreplugin/dialogs/externaltoolconfig.h
index 38ca3e991a..ab75a8a3d3 100644
--- a/src/plugins/coreplugin/dialogs/externaltoolconfig.h
+++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.h
@@ -108,6 +108,7 @@ private slots:
void addTool();
void removeTool();
void addCategory();
+ void updateEffectiveArguments();
private:
Ui::ExternalToolConfig *ui;
diff --git a/src/plugins/coreplugin/dialogs/externaltoolconfig.ui b/src/plugins/coreplugin/dialogs/externaltoolconfig.ui
index 4ae615dbaf..f6d2a0e7bf 100644
--- a/src/plugins/coreplugin/dialogs/externaltoolconfig.ui
+++ b/src/plugins/coreplugin/dialogs/externaltoolconfig.ui
@@ -131,20 +131,37 @@
<widget class="QLineEdit" name="arguments"/>
</item>
<item row="3" column="0">
+ <widget class="QLabel" name="effectiveArgumentsLabel">
+ <property name="text">
+ <string>Effective Arguments:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QLineEdit" name="effectiveArguments">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
<widget class="QLabel" name="workingDirectoryLabel">
<property name="text">
<string>Working directory:</string>
</property>
</widget>
</item>
- <item row="3" column="1">
+ <item row="4" column="1">
<widget class="Utils::PathChooser" name="workingDirectory">
<property name="expectedKind">
<enum>Utils::PathChooser::Directory</enum>
</property>
</widget>
</item>
- <item row="4" column="0">
+ <item row="5" column="0">
<widget class="QLabel" name="outputLabel">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;
@@ -157,7 +174,7 @@
</property>
</widget>
</item>
- <item row="4" column="1">
+ <item row="5" column="1">
<widget class="QComboBox" name="outputBehavior">
<item>
<property name="text">
@@ -176,7 +193,7 @@
</item>
</widget>
</item>
- <item row="5" column="0">
+ <item row="6" column="0">
<widget class="QLabel" name="errorOutputLabel">
<property name="toolTip">
<string>&lt;html&gt;&lt;head&gt;&lt;body&gt;
@@ -191,7 +208,7 @@
</property>
</widget>
</item>
- <item row="5" column="1">
+ <item row="6" column="1">
<widget class="QComboBox" name="errorOutputBehavior">
<item>
<property name="text">
@@ -210,7 +227,17 @@
</item>
</widget>
</item>
- <item row="7" column="0">
+ <item row="7" column="1">
+ <widget class="QCheckBox" name="modifiesDocumentCheckbox">
+ <property name="toolTip">
+ <string>If the tool modifies the current document, set this flag to ensure that the document is saved before running the tool and is reloaded after the tool finished.</string>
+ </property>
+ <property name="text">
+ <string>Modifies current document</string>
+ </property>
+ </widget>
+ </item>
+ <item row="8" column="0">
<widget class="QLabel" name="inputLabel">
<property name="toolTip">
<string>Text to pass to the executable via standard input. Leave empty if the executable should not receive any input.</string>
@@ -220,23 +247,13 @@
</property>
</widget>
</item>
- <item row="7" column="1">
+ <item row="8" column="1">
<widget class="QPlainTextEdit" name="inputText">
<property name="lineWrapMode">
<enum>QPlainTextEdit::NoWrap</enum>
</property>
</widget>
</item>
- <item row="6" column="1">
- <widget class="QCheckBox" name="modifiesDocumentCheckbox">
- <property name="toolTip">
- <string>If the tool modifies the current document, set this flag to ensure that the document is saved before running the tool and is reloaded after the tool finished.</string>
- </property>
- <property name="text">
- <string>Modifies current document</string>
- </property>
- </widget>
- </item>
</layout>
</widget>
</item>
diff --git a/src/plugins/coreplugin/dialogs/ioptionspage.h b/src/plugins/coreplugin/dialogs/ioptionspage.h
index 2ae753267e..178ca4e66c 100644
--- a/src/plugins/coreplugin/dialogs/ioptionspage.h
+++ b/src/plugins/coreplugin/dialogs/ioptionspage.h
@@ -30,7 +30,7 @@
#ifndef IOPTIONSPAGE_H
#define IOPTIONSPAGE_H
-#include <coreplugin/core_global.h>
+#include <coreplugin/id.h>
#include <QIcon>
#include <QObject>
@@ -44,9 +44,9 @@ class CORE_EXPORT IOptionsPage : public QObject
public:
IOptionsPage(QObject *parent = 0) : QObject(parent) {}
- QString id() const { return m_id; }
+ Id id() const { return m_id; }
QString displayName() const { return m_displayName; }
- QString category() const { return m_category; }
+ Id category() const { return m_category; }
QString displayCategory() const { return m_displayCategory; }
QIcon categoryIcon() const { return QIcon(m_categoryIcon); }
@@ -56,15 +56,15 @@ public:
virtual void finish() = 0;
protected:
- void setId(const QString &id) { m_id = id; }
+ void setId(Id id) { m_id = id; }
void setDisplayName(const QString &displayName) { m_displayName = displayName; }
- void setCategory(const QString &category) { m_category = category; }
+ void setCategory(Id category) { m_category = category; }
void setDisplayCategory(const QString &displayCategory) { m_displayCategory = displayCategory; }
void setCategoryIcon(const QString &categoryIcon) { m_categoryIcon = categoryIcon; }
- QString m_id;
+ Id m_id;
QString m_displayName;
- QString m_category;
+ Id m_category;
QString m_displayCategory;
QString m_categoryIcon;
};
@@ -84,18 +84,18 @@ class CORE_EXPORT IOptionsPageProvider : public QObject
public:
IOptionsPageProvider(QObject *parent = 0) : QObject(parent) {}
- QString category() const { return m_category; }
+ Core::Id category() const { return m_category; }
QString displayCategory() const { return m_displayCategory; }
QIcon categoryIcon() const { return QIcon(m_categoryIcon); }
virtual QList<IOptionsPage *> pages() const = 0;
protected:
- void setCategory(const QString &category) { m_category = category; }
+ void setCategory(Core::Id category) { m_category = category; }
void setDisplayCategory(const QString &displayCategory) { m_displayCategory = displayCategory; }
void setCategoryIcon(const QString &categoryIcon) { m_categoryIcon = categoryIcon; }
- QString m_category;
+ Core::Id m_category;
QString m_displayCategory;
QString m_categoryIcon;
};
diff --git a/src/plugins/coreplugin/dialogs/newdialog.cpp b/src/plugins/coreplugin/dialogs/newdialog.cpp
index b14001c517..260aa80525 100644
--- a/src/plugins/coreplugin/dialogs/newdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/newdialog.cpp
@@ -262,9 +262,8 @@ void NewDialog::setWizards(QList<IWizard*> wizards)
parentItem->appendRow(projectKindItem);
parentItem->appendRow(filesClassesKindItem);
- if (m_dummyIcon.isNull()) {
+ if (m_dummyIcon.isNull())
m_dummyIcon = QIcon(QLatin1String(Core::Constants::ICON_NEWFILE));
- }
QStringList availablePlatforms = IWizard::allAvailablePlatforms();
@@ -311,10 +310,9 @@ Core::IWizard *NewDialog::showDialog()
QModelIndex idx;
if (!lastCategory.isEmpty())
- foreach(QStandardItem* item, m_categoryItems) {
- if (item->data(Qt::UserRole) == lastCategory) {
+ foreach (QStandardItem* item, m_categoryItems) {
+ if (item->data(Qt::UserRole) == lastCategory)
idx = m_twoLevelProxyModel->mapToSource(m_model->indexFromItem(item));
- }
}
if (!idx.isValid())
idx = m_twoLevelProxyModel->index(0,0, m_twoLevelProxyModel->index(0,0));
@@ -390,11 +388,10 @@ void NewDialog::addItem(QStandardItem *topLEvelCategoryItem, IWizard *wizard)
QIcon wizardIcon;
// spacing hack. Add proper icons instead
- if (wizard->icon().isNull()) {
+ if (wizard->icon().isNull())
wizardIcon = m_dummyIcon;
- } else {
+ else
wizardIcon = wizard->icon();
- }
wizardItem->setIcon(wizardIcon);
wizardItem->setData(QVariant::fromValue(WizardContainer(wizard, 0)), Qt::UserRole);
wizardItem->setFlags(Qt::ItemIsEnabled|Qt::ItemIsSelectable);
diff --git a/src/plugins/coreplugin/dialogs/promptoverwritedialog.cpp b/src/plugins/coreplugin/dialogs/promptoverwritedialog.cpp
index 643f66f937..9ec8fd9f3d 100644
--- a/src/plugins/coreplugin/dialogs/promptoverwritedialog.cpp
+++ b/src/plugins/coreplugin/dialogs/promptoverwritedialog.cpp
@@ -127,11 +127,10 @@ void PromptOverwriteDialog::setFileEnabled(const QString &f, bool e)
{
if (QStandardItem *item = itemForFile(f)) {
Qt::ItemFlags flags = item->flags();
- if (e) {
+ if (e)
flags |= Qt::ItemIsEnabled;
- } else {
+ else
flags &= ~Qt::ItemIsEnabled;
- }
item->setFlags(flags);
}
}
diff --git a/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp b/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
index b22e92416e..2fdd2a01c3 100644
--- a/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/saveitemsdialog.cpp
@@ -33,6 +33,7 @@
#include <coreplugin/fileiconprovider.h>
#include <coreplugin/idocument.h>
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QFileInfo>
@@ -53,12 +54,10 @@ SaveItemsDialog::SaveItemsDialog(QWidget *parent,
{
m_ui.setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
-#ifdef Q_OS_MAC
+
// QDialogButtonBox's behavior for "destructive" is wrong, the "do not save" should be left-aligned
- QDialogButtonBox::ButtonRole discardButtonRole = QDialogButtonBox::ResetRole;
-#else
- QDialogButtonBox::ButtonRole discardButtonRole = QDialogButtonBox::DestructiveRole;
-#endif
+ const QDialogButtonBox::ButtonRole discardButtonRole = Utils::HostOsInfo::isMacHost()
+ ? QDialogButtonBox::ResetRole : QDialogButtonBox::DestructiveRole;
QPushButton *discardButton = m_ui.buttonBox->addButton(tr("Do not Save"), discardButtonRole);
m_ui.buttonBox->button(QDialogButtonBox::Save)->setDefault(true);
m_ui.treeWidget->setFocus();
@@ -85,9 +84,8 @@ SaveItemsDialog::SaveItemsDialog(QWidget *parent,
m_ui.treeWidget->resizeColumnToContents(0);
m_ui.treeWidget->selectAll();
-#ifdef Q_OS_MAC
- m_ui.treeWidget->setAlternatingRowColors(true);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ m_ui.treeWidget->setAlternatingRowColors(true);
adjustButtonWidths();
updateSaveButton();
@@ -134,13 +132,13 @@ void SaveItemsDialog::adjustButtonWidths()
if (hint > maxTextWidth)
maxTextWidth = hint;
}
-#ifdef Q_OS_MAC
- QPushButton *cancelButton = m_ui.buttonBox->button(QDialogButtonBox::Cancel);
- int cancelButtonWidth = cancelButton->sizeHint().width();
- if (cancelButtonWidth > maxTextWidth)
- maxTextWidth = cancelButtonWidth;
- cancelButton->setMinimumWidth(maxTextWidth);
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ QPushButton *cancelButton = m_ui.buttonBox->button(QDialogButtonBox::Cancel);
+ int cancelButtonWidth = cancelButton->sizeHint().width();
+ if (cancelButtonWidth > maxTextWidth)
+ maxTextWidth = cancelButtonWidth;
+ cancelButton->setMinimumWidth(maxTextWidth);
+ }
saveButton->setMinimumWidth(maxTextWidth);
}
diff --git a/src/plugins/coreplugin/dialogs/settingsdialog.cpp b/src/plugins/coreplugin/dialogs/settingsdialog.cpp
index 0935413c7f..52a1f1aee9 100644
--- a/src/plugins/coreplugin/dialogs/settingsdialog.cpp
+++ b/src/plugins/coreplugin/dialogs/settingsdialog.cpp
@@ -29,32 +29,34 @@
#include "settingsdialog.h"
-#include <extensionsystem/pluginmanager.h>
#include "icore.h"
+#include <extensionsystem/pluginmanager.h>
+#include <utils/hostosinfo.h>
#include <utils/filterlineedit.h>
-#include <QSettings>
-#include <QSortFilterProxyModel>
-#include <QItemSelectionModel>
+#include <QApplication>
+#include <QDialogButtonBox>
+#include <QFrame>
+#include <QGridLayout>
+#include <QGroupBox>
#include <QHBoxLayout>
#include <QIcon>
+#include <QItemSelectionModel>
#include <QLabel>
+#include <QLineEdit>
+#include <QListView>
+#include <QPointer>
#include <QPushButton>
-#include <QToolButton>
-#include <QToolBar>
#include <QScrollBar>
+#include <QSettings>
+#include <QSortFilterProxyModel>
#include <QSpacerItem>
-#include <QStyle>
#include <QStackedLayout>
-#include <QGridLayout>
-#include <QLineEdit>
-#include <QFrame>
-#include <QDialogButtonBox>
-#include <QListView>
-#include <QApplication>
-#include <QGroupBox>
+#include <QStyle>
#include <QStyledItemDelegate>
+#include <QToolBar>
+#include <QToolButton>
static const char categoryKeyC[] = "General/LastPreferenceCategory";
static const char pageKeyC[] = "General/LastPreferencePage";
@@ -63,13 +65,14 @@ const int categoryIconSize = 24;
namespace Core {
namespace Internal {
-QPointer<SettingsDialog> SettingsDialog::m_instance = 0;
+static QPointer<SettingsDialog> m_instance = 0;
// ----------- Category model
-class Category {
+class Category
+{
public:
- QString id;
+ Id id;
QString displayName;
QIcon icon;
QList<IOptionsPage *> pages;
@@ -92,7 +95,7 @@ public:
const QList<Category*> &categories() const { return m_categories; }
private:
- Category *findCategoryById(const QString &id);
+ Category *findCategoryById(Id id);
QList<Category*> m_categories;
QIcon m_emptyIcon;
@@ -135,13 +138,15 @@ QVariant CategoryModel::data(const QModelIndex &index, int role) const
void CategoryModel::setPages(const QList<IOptionsPage*> &pages,
const QList<IOptionsPageProvider *> &providers)
{
+ beginResetModel();
+
// Clear any previous categories
qDeleteAll(m_categories);
m_categories.clear();
// Put the pages in categories
foreach (IOptionsPage *page, pages) {
- const QString &categoryId = page->category();
+ const Id categoryId = page->category();
Category *category = findCategoryById(categoryId);
if (!category) {
category = new Category;
@@ -158,7 +163,7 @@ void CategoryModel::setPages(const QList<IOptionsPage*> &pages,
}
foreach (IOptionsPageProvider *provider, providers) {
- const QString &categoryId = provider->category();
+ const Id categoryId = provider->category();
Category *category = findCategoryById(categoryId);
if (!category) {
category = new Category;
@@ -174,10 +179,10 @@ void CategoryModel::setPages(const QList<IOptionsPage*> &pages,
category->providers.append(provider);
}
- reset();
+ endResetModel();
}
-Category *CategoryModel::findCategoryById(const QString &id)
+Category *CategoryModel::findCategoryById(Id id)
{
for (int i = 0; i < m_categories.size(); ++i) {
Category *category = m_categories.at(i);
@@ -265,9 +270,9 @@ public:
// Helpers to sort by category. id
bool optionsPageLessThan(const IOptionsPage *p1, const IOptionsPage *p2)
{
- if (const int cc = p1->category().compare(p2->category()))
- return cc < 0;
- return p1->id().compare(p2->id()) < 0;
+ if (p1->category() != p2->category())
+ return p1->category().alphabeticallyBefore(p2->category());
+ return p1->id().alphabeticallyBefore(p2->id());
}
static inline QList<Core::IOptionsPage*> sortedOptionsPages()
@@ -294,11 +299,10 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
createGui();
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
-#ifdef Q_OS_MAC
- setWindowTitle(tr("Preferences"));
-#else
- setWindowTitle(tr("Options"));
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ setWindowTitle(tr("Preferences"));
+ else
+ setWindowTitle(tr("Options"));
m_model->setPages(m_pages,
ExtensionSystem::PluginManager::getObjects<IOptionsPageProvider>());
@@ -323,15 +327,15 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
m_categoryList->setFocus();
}
-void SettingsDialog::showPage(const QString &categoryId, const QString &pageId)
+void SettingsDialog::showPage(Id categoryId, Id pageId)
{
// handle the case of "show last page"
- QString initialCategory = categoryId;
- QString initialPage = pageId;
- if (initialCategory.isEmpty() && initialPage.isEmpty()) {
+ Id initialCategory = categoryId;
+ Id initialPage = pageId;
+ if (!initialCategory.isValid() && !initialPage.isValid()) {
QSettings *settings = ICore::settings();
- initialCategory = settings->value(QLatin1String(categoryKeyC), QVariant(QString())).toString();
- initialPage = settings->value(QLatin1String(pageKeyC), QVariant(QString())).toString();
+ initialCategory = Id::fromSetting(settings->value(QLatin1String(categoryKeyC)));
+ initialPage = Id::fromSetting(settings->value(QLatin1String(pageKeyC)));
}
int initialCategoryIndex = -1;
@@ -459,7 +463,7 @@ void SettingsDialog::updateEnabledTabs(Category *category, const QString &search
for (int i = 0; i < category->pages.size(); ++i) {
const IOptionsPage *page = category->pages.at(i);
const bool enabled = searchText.isEmpty()
- || page->category().contains(searchText, Qt::CaseInsensitive)
+ || page->category().toString().contains(searchText, Qt::CaseInsensitive)
|| page->displayName().contains(searchText, Qt::CaseInsensitive)
|| page->matches(searchText);
category->tabWidget->setTabEnabled(i, enabled);
@@ -538,8 +542,8 @@ void SettingsDialog::apply()
void SettingsDialog::done(int val)
{
QSettings *settings = ICore::settings();
- settings->setValue(QLatin1String(categoryKeyC), m_currentCategory);
- settings->setValue(QLatin1String(pageKeyC), m_currentPage);
+ settings->setValue(QLatin1String(categoryKeyC), m_currentCategory.toSetting());
+ settings->setValue(QLatin1String(pageKeyC), m_currentPage.toSetting());
ICore::saveSettings(); // save all settings
@@ -563,12 +567,10 @@ QSize SettingsDialog::sizeHint() const
}
SettingsDialog *SettingsDialog::getSettingsDialog(QWidget *parent,
- const QString &initialCategory,
- const QString &initialPage)
+ Id initialCategory, Id initialPage)
{
- if (!m_instance) {
+ if (!m_instance)
m_instance = new SettingsDialog(parent);
- }
m_instance->showPage(initialCategory, initialPage);
return m_instance;
}
@@ -600,6 +602,5 @@ bool SettingsDialog::execDialog()
return m_applied;
}
-
} // namespace Internal
} // namespace Core
diff --git a/src/plugins/coreplugin/dialogs/settingsdialog.h b/src/plugins/coreplugin/dialogs/settingsdialog.h
index 121453deeb..3fd145c290 100644
--- a/src/plugins/coreplugin/dialogs/settingsdialog.h
+++ b/src/plugins/coreplugin/dialogs/settingsdialog.h
@@ -31,10 +31,10 @@
#define SETTINGSDIALOG_H
#include "coreplugin/dialogs/ioptionspage.h"
+#include "coreplugin/id.h"
#include <QList>
#include <QSet>
-#include <QPointer>
#include <QEventLoop>
#include <QDialog>
@@ -46,9 +46,7 @@ class QLabel;
class QListView;
QT_END_NAMESPACE
-namespace Utils {
- class FilterLineEdit;
-}
+namespace Utils { class FilterLineEdit; }
namespace Core {
namespace Internal {
@@ -61,13 +59,11 @@ class SettingsDialog : public QDialog
Q_OBJECT
public:
-
// Returns a settings dialog. This makes sure that always only
// a single settings dialog instance is running.
// The dialog will be deleted automatically on close.
static SettingsDialog *getSettingsDialog(QWidget *parent,
- const QString &initialCategory = QString(),
- const QString &initialPage = QString());
+ Id initialCategory, Id initialPage);
// Run the dialog and wait for it to finish.
// Returns if the changes have been applied.
bool execDialog();
@@ -92,18 +88,18 @@ private:
void createGui();
void showCategory(int index);
- void showPage(const QString &categoryId, const QString &pageId);
+ void showPage(Id categoryId, Id pageId);
void updateEnabledTabs(Category *category, const QString &searchText);
void ensureCategoryWidget(Category *category);
void disconnectTabWidgets();
- const QList<Core::IOptionsPage*> m_pages;
+ const QList<IOptionsPage *> m_pages;
- QSet<Core::IOptionsPage*> m_visitedPages;
+ QSet<IOptionsPage *> m_visitedPages;
QSortFilterProxyModel *m_proxyModel;
CategoryModel *m_model;
- QString m_currentCategory;
- QString m_currentPage;
+ Id m_currentCategory;
+ Id m_currentPage;
QStackedLayout *m_stackedLayout;
Utils::FilterLineEdit *m_filterLineEdit;
QListView *m_categoryList;
@@ -112,7 +108,6 @@ private:
bool m_applied;
bool m_finished;
QList<QEventLoop *> m_eventLoops;
- static QPointer<SettingsDialog> m_instance;
};
} // namespace Internal
diff --git a/src/plugins/coreplugin/dialogs/shortcutsettings.cpp b/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
index abb5bb3b92..d75dc1d0d4 100644
--- a/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
+++ b/src/plugins/coreplugin/dialogs/shortcutsettings.cpp
@@ -60,9 +60,9 @@ ShortcutSettings::ShortcutSettings(QObject *parent)
{
connect(ActionManager::instance(), SIGNAL(commandListChanged()), this, SLOT(initialize()));
- setId(QLatin1String(Core::Constants::SETTINGS_ID_SHORTCUTS));
+ setId(Core::Constants::SETTINGS_ID_SHORTCUTS);
setDisplayName(tr("Keyboard"));
- setCategory(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE));
+ setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
}
@@ -141,7 +141,7 @@ void ShortcutSettings::commandChanged(QTreeWidgetItem *current)
CommandMappings::commandChanged(current);
if (!current || !current->data(0, Qt::UserRole).isValid())
return;
- ShortcutItem *scitem = qVariantValue<ShortcutItem *>(current->data(0, Qt::UserRole));
+ ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
setKeySequence(scitem->m_key);
}
@@ -149,13 +149,13 @@ void ShortcutSettings::targetIdentifierChanged()
{
QTreeWidgetItem *current = commandList()->currentItem();
if (current && current->data(0, Qt::UserRole).isValid()) {
- ShortcutItem *scitem = qVariantValue<ShortcutItem *>(current->data(0, Qt::UserRole));
+ ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
scitem->m_key = QKeySequence(m_key[0], m_key[1], m_key[2], m_key[3]);
if (scitem->m_cmd->defaultKeySequence() != scitem->m_key)
setModified(current, true);
else
setModified(current, false);
- current->setText(2, scitem->m_key);
+ current->setText(2, scitem->m_key.toString(QKeySequence::NativeText));
resetCollisionMarker(scitem);
markPossibleCollisions(scitem);
}
@@ -168,14 +168,14 @@ void ShortcutSettings::setKeySequence(const QKeySequence &key)
for (int i = 0; i < m_keyNum; ++i) {
m_key[i] = key[i];
}
- targetEdit()->setText(key);
+ targetEdit()->setText(key.toString(QKeySequence::NativeText));
}
void ShortcutSettings::resetTargetIdentifier()
{
QTreeWidgetItem *current = commandList()->currentItem();
if (current && current->data(0, Qt::UserRole).isValid()) {
- ShortcutItem *scitem = qVariantValue<ShortcutItem *>(current->data(0, Qt::UserRole));
+ ShortcutItem *scitem = qvariant_cast<ShortcutItem *>(current->data(0, Qt::UserRole));
setKeySequence(scitem->m_cmd->defaultKeySequence());
}
}
@@ -200,7 +200,7 @@ void ShortcutSettings::importAction()
QString sid = item->m_cmd->id().toString();
if (mapping.contains(sid)) {
item->m_key = mapping.value(sid);
- item->m_item->setText(2, item->m_key);
+ item->m_item->setText(2, item->m_key.toString(QKeySequence::NativeText));
if (item->m_item == commandList()->currentItem())
commandChanged(item->m_item);
@@ -222,7 +222,7 @@ void ShortcutSettings::defaultAction()
{
foreach (ShortcutItem *item, m_scitems) {
item->m_key = item->m_cmd->defaultKeySequence();
- item->m_item->setText(2, item->m_key);
+ item->m_item->setText(2, item->m_key.toString(QKeySequence::NativeText));
setModified(item->m_item, false);
if (item->m_item == commandList()->currentItem())
commandChanged(item->m_item);
@@ -293,7 +293,7 @@ void ShortcutSettings::initialize()
s->m_key = c->keySequence();
item->setText(0, subId);
item->setText(1, c->description());
- item->setText(2, s->m_key);
+ item->setText(2, s->m_key.toString(QKeySequence::NativeText));
if (s->m_cmd->defaultKeySequence() != s->m_key)
setModified(item, true);
@@ -333,7 +333,7 @@ void ShortcutSettings::handleKeyEvent(QKeyEvent *e)
}
m_keyNum++;
QKeySequence ks(m_key[0], m_key[1], m_key[2], m_key[3]);
- targetEdit()->setText(ks);
+ targetEdit()->setText(ks.toString(QKeySequence::NativeText));
e->accept();
}
@@ -362,7 +362,7 @@ void ShortcutSettings::markPossibleCollisions(ShortcutItem *item)
if (item->m_key.isEmpty())
return;
- int globalId = Context(Constants::C_GLOBAL).at(0);
+ Id globalId = Context(Constants::C_GLOBAL).at(0);
foreach (ShortcutItem *currentItem, m_scitems) {
@@ -371,11 +371,10 @@ void ShortcutSettings::markPossibleCollisions(ShortcutItem *item)
continue;
}
- foreach (int context, currentItem->m_cmd->context()) {
-
+ foreach (Id id, currentItem->m_cmd->context()) {
// conflict if context is identical, OR if one
// of the contexts is the global context
- if (item->m_cmd->context().contains(context) ||
+ if (item->m_cmd->context().contains(id) ||
(item->m_cmd->context().contains(globalId) &&
!currentItem->m_cmd->context().isEmpty()) ||
(currentItem->m_cmd->context().contains(globalId) &&
diff --git a/src/plugins/coreplugin/documentmanager.cpp b/src/plugins/coreplugin/documentmanager.cpp
index f90478d938..3beb2ad964 100644
--- a/src/plugins/coreplugin/documentmanager.cpp
+++ b/src/plugins/coreplugin/documentmanager.cpp
@@ -41,6 +41,7 @@
#include "vcsmanager.h"
#include "coreconstants.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>
#include <utils/reloadpromptutils.h>
@@ -96,7 +97,7 @@ static const char editorsKeyC[] = "EditorIds";
static const char directoryGroupC[] = "Directories";
static const char projectDirectoryKeyC[] = "Projects";
static const char useProjectDirectoryKeyC[] = "UseProjectsDirectory";
-
+static const char buildDirectoryKeyC[] = "BuildDirectory.Template";
namespace Core {
@@ -155,6 +156,7 @@ struct DocumentManagerPrivate
QString m_lastVisitedDirectory;
QString m_projectsDirectory;
bool m_useProjectsDirectory;
+ QString m_buildDirectory;
// When we are callling into a IDocument
// we don't want to receive a changed()
// signal
@@ -177,17 +179,17 @@ QFileSystemWatcher *DocumentManagerPrivate::fileWatcher()
QFileSystemWatcher *DocumentManagerPrivate::linkWatcher()
{
-#ifdef Q_OS_UNIX
- if (!m_linkWatcher) {
- m_linkWatcher = new QFileSystemWatcher(m_instance);
- m_linkWatcher->setObjectName(QLatin1String("_qt_autotest_force_engine_poller"));
- QObject::connect(m_linkWatcher, SIGNAL(fileChanged(QString)),
- m_instance, SLOT(changedFile(QString)));
+ if (Utils::HostOsInfo::isAnyUnixHost()) {
+ if (!m_linkWatcher) {
+ m_linkWatcher = new QFileSystemWatcher(m_instance);
+ m_linkWatcher->setObjectName(QLatin1String("_qt_autotest_force_engine_poller"));
+ QObject::connect(m_linkWatcher, SIGNAL(fileChanged(QString)),
+ m_instance, SLOT(changedFile(QString)));
+ }
+ return m_linkWatcher;
}
- return m_linkWatcher;
-#else
+
return fileWatcher();
-#endif
}
DocumentManagerPrivate::DocumentManagerPrivate(QMainWindow *mw) :
@@ -196,11 +198,7 @@ DocumentManagerPrivate::DocumentManagerPrivate(QMainWindow *mw) :
m_linkWatcher(0),
m_blockActivated(false),
m_lastVisitedDirectory(QDir::currentPath()),
-#ifdef Q_OS_MAC // Creator is in bizarre places when launched via finder.
- m_useProjectsDirectory(true),
-#else
- m_useProjectsDirectory(false),
-#endif
+ m_useProjectsDirectory(Utils::HostOsInfo::isMacHost()), // Creator is in bizarre places when launched via finder.
m_blockedIDocument(0)
{
}
@@ -246,10 +244,9 @@ static void addFileInfo(const QString &fileName, IDocument *document, bool isLin
state.modified = fi.lastModified();
state.permissions = fi.permissions();
// Add watcher if we don't have that already
- if (!d->m_states.contains(fileName)) {
+ if (!d->m_states.contains(fileName))
d->m_states.insert(fileName, FileState());
- }
QFileSystemWatcher *watcher = 0;
if (isLink)
watcher = d->linkWatcher();
@@ -488,9 +485,8 @@ QString DocumentManager::fixFileName(const QString &fileName, FixMode fixmode)
s = QDir::cleanPath(s);
}
s = QDir::toNativeSeparators(s);
-#ifdef Q_OS_WIN
- s = s.toLower();
-#endif
+ if (Utils::HostOsInfo::isWindowsHost())
+ s = s.toLower();
return s;
}
@@ -863,9 +859,8 @@ void DocumentManager::changedFile(const QString &fileName)
if (d->m_states.contains(fileName))
d->m_changedFiles.insert(fileName);
- if (wasempty && !d->m_changedFiles.isEmpty()) {
+ if (wasempty && !d->m_changedFiles.isEmpty())
QTimer::singleShot(200, this, SLOT(checkForReload()));
- }
}
void DocumentManager::mainWindowActivated()
@@ -966,11 +961,10 @@ void DocumentManager::checkForReload()
// find out the type
IDocument::ChangeType fileChange = changeTypes.value(fileName);
- if (fileChange == IDocument::TypeRemoved) {
+ if (fileChange == IDocument::TypeRemoved)
type = IDocument::TypeRemoved;
- } else if (fileChange == IDocument::TypeContents && type == IDocument::TypePermissions) {
+ else if (fileChange == IDocument::TypeContents && type == IDocument::TypePermissions)
type = IDocument::TypeContents;
- }
}
if (!changed) // probably because the change was blocked with (un)blockFileChange
@@ -1169,6 +1163,7 @@ void DocumentManager::saveSettings()
s->beginGroup(QLatin1String(directoryGroupC));
s->setValue(QLatin1String(projectDirectoryKeyC), d->m_projectsDirectory);
s->setValue(QLatin1String(useProjectDirectoryKeyC), d->m_useProjectsDirectory);
+ s->setValue(QLatin1String(buildDirectoryKeyC), d->m_buildDirectory);
s->endGroup();
}
@@ -1188,19 +1183,26 @@ void readSettings()
editorId = ids.next();
if (QFileInfo(fileName).isFile())
d->m_recentFiles.append(DocumentManager::RecentFile(QDir::fromNativeSeparators(fileName), // from native to guard against old settings
- Id(editorId)));
+ Id::fromString(editorId)));
}
s->beginGroup(QLatin1String(directoryGroupC));
const QString settingsProjectDir = s->value(QLatin1String(projectDirectoryKeyC),
QString()).toString();
- if (!settingsProjectDir.isEmpty() && QFileInfo(settingsProjectDir).isDir()) {
+ if (!settingsProjectDir.isEmpty() && QFileInfo(settingsProjectDir).isDir())
d->m_projectsDirectory = settingsProjectDir;
- } else {
+ else
d->m_projectsDirectory = Utils::PathChooser::homePath();
- }
d->m_useProjectsDirectory = s->value(QLatin1String(useProjectDirectoryKeyC),
d->m_useProjectsDirectory).toBool();
+
+ const QString settingsShadowDir = s->value(QLatin1String(buildDirectoryKeyC),
+ QString()).toString();
+ if (!settingsShadowDir.isEmpty())
+ d->m_buildDirectory = settingsShadowDir;
+ else
+ d->m_buildDirectory = QLatin1String(Constants::DEFAULT_BUILD_DIRECTORY);
+
s->endGroup();
}
@@ -1272,6 +1274,26 @@ void DocumentManager::setProjectsDirectory(const QString &dir)
}
/*!
+ Returns the default build directory.
+
+ \sa setBuildDirectory
+*/
+QString DocumentManager::buildDirectory()
+{
+ return d->m_buildDirectory;
+}
+
+/*!
+ Sets the shadow build directory to \a directory.
+
+ \sa buildDirectory
+*/
+void DocumentManager::setBuildDirectory(const QString &directory)
+{
+ d->m_buildDirectory = directory;
+}
+
+/*!
Returns whether the directory for projects is to be
used or the user wants the current directory.
@@ -1369,7 +1391,7 @@ void DocumentManager::executeOpenWithMenuAction(QAction *action)
{
QTC_ASSERT(action, return);
const QVariant data = action->data();
- OpenWithEntry entry = qVariantValue<OpenWithEntry>(data);
+ OpenWithEntry entry = qvariant_cast<OpenWithEntry>(data);
if (entry.editorFactory) {
// close any open editors that have this file open, but have a different type.
EditorManager *em = EditorManager::instance();
diff --git a/src/plugins/coreplugin/documentmanager.h b/src/plugins/coreplugin/documentmanager.h
index 48669b7d32..2a46c0897a 100644
--- a/src/plugins/coreplugin/documentmanager.h
+++ b/src/plugins/coreplugin/documentmanager.h
@@ -129,6 +129,9 @@ public:
static QString projectsDirectory();
static void setProjectsDirectory(const QString &);
+ static QString buildDirectory();
+ static void setBuildDirectory(const QString &directory);
+
static void populateOpenWithMenu(QMenu *menu, const QString &fileName);
/* Used to notify e.g. the code model to update the given files. Does *not*
diff --git a/src/plugins/coreplugin/editormanager/editormanager.cpp b/src/plugins/coreplugin/editormanager/editormanager.cpp
index 66d0e27493..d961e59132 100644
--- a/src/plugins/coreplugin/editormanager/editormanager.cpp
+++ b/src/plugins/coreplugin/editormanager/editormanager.cpp
@@ -60,6 +60,7 @@
#include <extensionsystem/pluginmanager.h>
#include <utils/consoleprocess.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDateTime>
@@ -89,6 +90,7 @@ static const char kCurrentDocumentFilePath[] = "CurrentDocument:FilePath";
static const char kCurrentDocumentPath[] = "CurrentDocument:Path";
static const char kCurrentDocumentXPos[] = "CurrentDocument:XPos";
static const char kCurrentDocumentYPos[] = "CurrentDocument:YPos";
+static const char kMakeWritableWarning[] = "Core.EditorManager.MakeWritable";
//===================EditorClosingCoreListener======================
@@ -204,6 +206,10 @@ struct EditorManagerPrivate
QAction *m_removeAllSplitsAction;
QAction *m_gotoOtherSplitAction;
+ QAction *m_saveCurrentEditorContextAction;
+ QAction *m_saveAsCurrentEditorContextAction;
+ QAction *m_revertToSavedCurrentEditorContextAction;
+
QAction *m_closeCurrentEditorContextAction;
QAction *m_closeAllEditorsContextAction;
QAction *m_closeOtherEditorsContextAction;
@@ -242,6 +248,9 @@ EditorManagerPrivate::EditorManagerPrivate(QWidget *parent) :
m_gotoPreviousDocHistoryAction(new QAction(EditorManager::tr("Previous Open Document in History"), parent)),
m_goBackAction(new QAction(QIcon(QLatin1String(Constants::ICON_PREV)), EditorManager::tr("Go Back"), parent)),
m_goForwardAction(new QAction(QIcon(QLatin1String(Constants::ICON_NEXT)), EditorManager::tr("Go Forward"), parent)),
+ m_saveCurrentEditorContextAction(new QAction(EditorManager::tr("&Save"), parent)),
+ m_saveAsCurrentEditorContextAction(new QAction(EditorManager::tr("Save &As..."), parent)),
+ m_revertToSavedCurrentEditorContextAction(new QAction(EditorManager::tr("Revert to Saved"), parent)),
m_closeCurrentEditorContextAction(new QAction(EditorManager::tr("Close"), parent)),
m_closeAllEditorsContextAction(new QAction(EditorManager::tr("Close All"), parent)),
m_closeOtherEditorsContextAction(new QAction(EditorManager::tr("Close Others"), parent)),
@@ -333,6 +342,11 @@ EditorManager::EditorManager(QWidget *parent) :
cmd->setAttribute(Core::Command::CA_UpdateText);
connect(d->m_closeOtherEditorsAction, SIGNAL(triggered()), this, SLOT(closeOtherEditors()));
+ //Save XXX Context Actions
+ connect(d->m_saveCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(saveDocumentFromContextMenu()));
+ connect(d->m_saveAsCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(saveDocumentAsFromContextMenu()));
+ connect(d->m_revertToSavedCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(revertToSavedFromContextMenu()));
+
// Close XXX Context Actions
connect(d->m_closeAllEditorsContextAction, SIGNAL(triggered()), this, SLOT(closeAllEditors()));
connect(d->m_closeCurrentEditorContextAction, SIGNAL(triggered()), this, SLOT(closeEditorFromContextMenu()));
@@ -492,11 +506,10 @@ void EditorManager::handleContextChange(Core::IContext *context)
if (debugEditorManager)
qDebug() << Q_FUNC_INFO;
IEditor *editor = context ? qobject_cast<IEditor*>(context) : 0;
- if (editor) {
+ if (editor)
setCurrentEditor(editor);
- } else {
+ else
updateActions();
- }
}
void EditorManager::setCurrentEditor(IEditor *editor, bool ignoreNavigationHistory)
@@ -631,9 +644,8 @@ void EditorManager::closeView(Core::Internal::EditorView *view)
*/
if (!d->m_editorModel->isDuplicate(e)) {
QList<IEditor *> duplicates = d->m_editorModel->duplicatesFor(e);
- if (!duplicates.isEmpty()) {
+ if (!duplicates.isEmpty())
d->m_editorModel->makeOriginal(duplicates.first());
- }
}
}
@@ -651,11 +663,10 @@ void EditorManager::closeView(Core::Internal::EditorView *view)
SplitterOrView *newCurrent = splitter->findFirstView();
if (newCurrent) {
- if (IEditor *e = newCurrent->editor()) {
+ if (IEditor *e = newCurrent->editor())
activateEditor(newCurrent->view(), e);
- } else {
+ else
setCurrentView(newCurrent);
- }
}
}
@@ -666,9 +677,8 @@ QList<IEditor*>
QSet<IEditor *> found;
foreach (IDocument *document, documents) {
foreach (IEditor *editor, editors) {
- if (editor->document() == document && !found.contains(editor)) {
+ if (editor->document() == document && !found.contains(editor))
found << editor;
- }
}
}
return found.toList();
@@ -721,10 +731,37 @@ void EditorManager::closeEditor()
closeEditor(d->m_currentEditor);
}
-void EditorManager::addCloseEditorActions(QMenu *contextMenu, const QModelIndex &editorIndex)
+static void assignAction(QAction *self, QAction *other)
+{
+ self->setText(other->text());
+ self->setIcon(other->icon());
+ self->setShortcut(other->shortcut());
+ self->setEnabled(other->isEnabled());
+}
+
+void EditorManager::addSaveAndCloseEditorActions(QMenu *contextMenu, const QModelIndex &editorIndex)
{
QTC_ASSERT(contextMenu, return);
d->m_contextMenuEditorIndex = editorIndex;
+
+ assignAction(d->m_saveCurrentEditorContextAction, ActionManager::command(Constants::SAVE)->action());
+ assignAction(d->m_saveAsCurrentEditorContextAction, ActionManager::command(Constants::SAVEAS)->action());
+ assignAction(d->m_revertToSavedCurrentEditorContextAction, ActionManager::command(Constants::REVERTTOSAVED)->action());
+
+ IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
+
+ setupSaveActions(editor,
+ d->m_saveCurrentEditorContextAction,
+ d->m_saveAsCurrentEditorContextAction,
+ d->m_revertToSavedCurrentEditorContextAction);
+
+ contextMenu->addAction(d->m_saveCurrentEditorContextAction);
+ contextMenu->addAction(d->m_saveAsCurrentEditorContextAction);
+ contextMenu->addAction(ActionManager::command(Constants::SAVEALL)->action());
+ contextMenu->addAction(d->m_revertToSavedCurrentEditorContextAction);
+
+ contextMenu->addSeparator();
+
d->m_closeCurrentEditorContextAction->setText(editorIndex.isValid()
? tr("Close \"%1\"").arg(editorIndex.data().toString())
: tr("Close Editor"));
@@ -748,6 +785,27 @@ void EditorManager::addNativeDirActions(QMenu *contextMenu, const QModelIndex &e
contextMenu->addAction(d->m_openTerminalAction);
}
+void EditorManager::saveDocumentFromContextMenu()
+{
+ IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
+ if (editor)
+ saveDocument(editor->document());
+}
+
+void EditorManager::saveDocumentAsFromContextMenu()
+{
+ IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
+ if (editor)
+ saveDocumentAs(editor->document());
+}
+
+void EditorManager::revertToSavedFromContextMenu()
+{
+ IEditor *editor = d->m_contextMenuEditorIndex.data(Qt::UserRole).value<Core::IEditor*>();
+ if (editor)
+ revertToSaved(editor);
+}
+
void EditorManager::closeEditorFromContextMenu()
{
closeEditor(d->m_contextMenuEditorIndex);
@@ -831,7 +889,7 @@ bool EditorManager::closeEditors(const QList<IEditor*> &editorsToClose, bool ask
// add duplicates
QList<IEditor *> duplicates;
- foreach(IEditor *editor, acceptedEditors)
+ foreach (IEditor *editor, acceptedEditors)
duplicates += d->m_editorModel->duplicatesFor(editor);
acceptedEditors += duplicates;
@@ -913,7 +971,7 @@ void EditorManager::closeDuplicate(Core::IEditor *editor)
emit editorAboutToClose(editor);
- if(d->m_splitter->findView(editor)) {
+ if (d->m_splitter->findView(editor)) {
EditorView *view = d->m_splitter->findView(editor)->view();
removeEditor(editor);
view->removeEditor(editor);
@@ -983,9 +1041,8 @@ Core::IEditor *EditorManager::placeEditor(Core::Internal::EditorView *view, Core
view->addEditor(editor);
view->setCurrentEditor(editor);
if (!sourceView->editor()) {
- if (IEditor *replacement = pickUnusedEditor()) {
+ if (IEditor *replacement = pickUnusedEditor())
sourceView->view()->addEditor(replacement);
- }
}
return editor;
} else if (duplicateSupported) {
@@ -1023,9 +1080,8 @@ Core::IEditor *EditorManager::activateEditor(Core::Internal::EditorView *view, C
if (!(flags & NoActivate)) {
setCurrentEditor(editor, (flags & IgnoreNavigationHistory));
- if (flags & ModeSwitch) {
+ if (flags & ModeSwitch)
switchToPreferedMode();
- }
if (isVisible())
editor->widget()->setFocus();
}
@@ -1105,7 +1161,7 @@ template <class EditorFactoryLike>
EditorFactoryLike *findById(const Core::Id &id)
{
const QList<EditorFactoryLike *> factories = ExtensionSystem::PluginManager::getObjects<EditorFactoryLike>();
- foreach(EditorFactoryLike *efl, factories)
+ foreach (EditorFactoryLike *efl, factories)
if (id == efl->id())
return efl;
return 0;
@@ -1176,14 +1232,14 @@ Core::Id EditorManager::getOpenWithEditorId(const QString &fileName,
//Unable to determine mime type of fileName. Falling back to text/plain",
if (!mt)
mt = ICore::mimeDatabase()->findByType(QLatin1String("text/plain"));
- QStringList allEditorIds;
+ QList<Id> allEditorIds;
QStringList allEditorDisplayNames;
QList<Id> externalEditorIds;
// Built-in
const EditorFactoryList editors = editorFactories(mt, false);
const int size = editors.size();
for (int i = 0; i < size; i++) {
- allEditorIds.push_back(editors.at(i)->id().toString());
+ allEditorIds.push_back(editors.at(i)->id());
allEditorDisplayNames.push_back(editors.at(i)->displayName());
}
// External editors
@@ -1191,7 +1247,7 @@ Core::Id EditorManager::getOpenWithEditorId(const QString &fileName,
const int esize = exEditors.size();
for (int i = 0; i < esize; i++) {
externalEditorIds.push_back(exEditors.at(i)->id());
- allEditorIds.push_back(exEditors.at(i)->id().toString());
+ allEditorIds.push_back(exEditors.at(i)->id());
allEditorDisplayNames.push_back(exEditors.at(i)->displayName());
}
if (allEditorIds.empty())
@@ -1203,7 +1259,7 @@ Core::Id EditorManager::getOpenWithEditorId(const QString &fileName,
dialog.setCurrentEditor(0);
if (dialog.exec() != QDialog::Accepted)
return Id();
- const Id selectedId = Id(allEditorIds.at(dialog.editor()));
+ const Id selectedId = allEditorIds.at(dialog.editor());
if (isExternalEditor)
*isExternalEditor = externalEditorIds.contains(selectedId);
return selectedId;
@@ -1394,11 +1450,10 @@ IEditor *EditorManager::openEditorWithContents(const Id &editorId,
QSet<QString> docnames;
foreach (IEditor *editor, m_instance->openedEditors()) {
QString name = editor->document()->fileName();
- if (name.isEmpty()) {
+ if (name.isEmpty())
name = editor->displayName();
- } else {
+ else
name = QFileInfo(name).completeBaseName();
- }
docnames << name;
}
@@ -1485,9 +1540,8 @@ bool EditorManager::saveDocument(IDocument *documentParam)
success = DocumentManager::saveDocument(document);
}
- if (success) {
+ if (success)
addDocumentToRecentFiles(document);
- }
return success;
}
@@ -1567,9 +1621,8 @@ bool EditorManager::saveDocumentAs(IDocument *documentParam)
if (absoluteFilePath != document->fileName()) {
// close existing editors for the new file name
const QList<IEditor *> existList = editorsForFileName(absoluteFilePath);
- if (!existList.isEmpty()) {
+ if (!existList.isEmpty())
closeEditors(existList, false);
- }
}
const bool success = DocumentManager::saveDocument(document, absoluteFilePath);
@@ -1658,9 +1711,8 @@ void EditorManager::updateWindowTitle()
{
QString windowTitle = tr("Qt Creator");
const QString dashSep = QLatin1String(" - ");
- if (!d->m_titleAddition.isEmpty()) {
+ if (!d->m_titleAddition.isEmpty())
windowTitle.prepend(d->m_titleAddition + dashSep);
- }
IEditor *curEditor = currentEditor();
if (curEditor) {
QString editorName = curEditor->displayName();
@@ -1688,80 +1740,101 @@ void EditorManager::handleEditorStateChange()
}
}
-void EditorManager::updateActions()
+void EditorManager::updateMakeWritableWarning()
{
- QString fName;
IEditor *curEditor = currentEditor();
- int openedCount = openedEditors().count() + d->m_editorModel->restoredEditors().count();
-
- if (curEditor) {
+ bool ww = curEditor->document()->isModified() && curEditor->document()->isFileReadOnly();
+ if (ww != curEditor->document()->hasWriteWarning()) {
+ curEditor->document()->setWriteWarning(ww);
+
+ // Do this after setWriteWarning so we don't re-evaluate this part even
+ // if we do not really show a warning.
+ bool promptVCS = false;
+ const QString directory = QFileInfo(curEditor->document()->fileName()).absolutePath();
+ IVersionControl *versionControl = ICore::vcsManager()->findVersionControlForDirectory(directory);
+ if (versionControl && versionControl->supportsOperation(IVersionControl::OpenOperation)) {
+ if (versionControl->settingsFlags() & IVersionControl::AutoOpen) {
+ vcsOpenCurrentEditor();
+ ww = false;
+ } else {
+ promptVCS = true;
+ }
+ }
- if (!curEditor->document()->fileName().isEmpty()) {
- QFileInfo fi(curEditor->document()->fileName());
- fName = fi.fileName();
+ if (ww) {
+ // we are about to change a read-only file, warn user
+ if (promptVCS) {
+ InfoBarEntry info(Id(kMakeWritableWarning),
+ tr("<b>Warning:</b> This file was not opened in %1 yet.")
+ .arg(versionControl->displayName()));
+ info.setCustomButtonInfo(tr("Open"), this, SLOT(vcsOpenCurrentEditor()));
+ curEditor->document()->infoBar()->addInfo(info);
+ } else {
+ InfoBarEntry info(Id(kMakeWritableWarning),
+ tr("<b>Warning:</b> You are changing a read-only file."));
+ info.setCustomButtonInfo(tr("Make Writable"), this, SLOT(makeCurrentEditorWritable()));
+ curEditor->document()->infoBar()->addInfo(info);
+ }
} else {
- fName = curEditor->displayName();
+ curEditor->document()->infoBar()->removeInfo(Id(kMakeWritableWarning));
}
+ }
+}
-#ifdef Q_OS_MAC
- window()->setWindowModified(curEditor->document()->isModified());
-#endif
- bool ww = curEditor->document()->isModified() && curEditor->document()->isFileReadOnly();
- if (ww != curEditor->document()->hasWriteWarning()) {
- curEditor->document()->setWriteWarning(ww);
-
- // Do this after setWriteWarning so we don't re-evaluate this part even
- // if we do not really show a warning.
- bool promptVCS = false;
- const QString directory = QFileInfo(curEditor->document()->fileName()).absolutePath();
- IVersionControl *versionControl = ICore::vcsManager()->findVersionControlForDirectory(directory);
- if (versionControl && versionControl->supportsOperation(IVersionControl::OpenOperation)) {
- if (versionControl->settingsFlags() & IVersionControl::AutoOpen) {
- vcsOpenCurrentEditor();
- ww = false;
- } else {
- promptVCS = true;
- }
- }
+QString EditorManager::fileNameForEditor(IEditor *editor)
+{
+ QString fileName;
- if (ww) {
- // we are about to change a read-only file, warn user
- if (promptVCS) {
- InfoBarEntry info(QLatin1String("Core.EditorManager.MakeWritable"),
- tr("<b>Warning:</b> This file was not opened in %1 yet.")
- .arg(versionControl->displayName()));
- info.setCustomButtonInfo(tr("Open"), this, SLOT(vcsOpenCurrentEditor()));
- curEditor->document()->infoBar()->addInfo(info);
- } else {
- InfoBarEntry info(QLatin1String("Core.EditorManager.MakeWritable"),
- tr("<b>Warning:</b> You are changing a read-only file."));
- info.setCustomButtonInfo(tr("Make Writable"), this, SLOT(makeCurrentEditorWritable()));
- curEditor->document()->infoBar()->addInfo(info);
- }
- } else {
- curEditor->document()->infoBar()->removeInfo(QLatin1String("Core.EditorManager.MakeWritable"));
- }
+ if (editor) {
+ if (!editor->document()->fileName().isEmpty()) {
+ QFileInfo fileInfo(editor->document()->fileName());
+ fileName = fileInfo.fileName();
+ } else {
+ fileName = editor->displayName();
}
-#ifdef Q_OS_MAC
- } else { // curEditor
+ }
+ return fileName;
+}
+
+void EditorManager::setupSaveActions(IEditor *editor, QAction *saveAction, QAction *saveAsAction, QAction *revertToSavedAction)
+{
+ saveAction->setEnabled(editor != 0 && editor->document()->isModified());
+ saveAsAction->setEnabled(editor != 0 && editor->document()->isSaveAsAllowed());
+ revertToSavedAction->setEnabled(editor != 0
+ && !editor->document()->fileName().isEmpty() && editor->document()->isModified());
+
+ const QString fileName = fileNameForEditor(editor);
+ QString quotedName;
+
+ if (!fileName.isEmpty())
+ quotedName = QLatin1Char('"') + fileName + QLatin1Char('"');
+ if (!quotedName.isEmpty()) {
+ saveAction->setText(tr("&Save %1").arg(quotedName));
+ saveAsAction->setText(tr("Save %1 &As...").arg(quotedName));
+ revertToSavedAction->setText(tr("Revert %1 to Saved").arg(quotedName));
+ }
+}
+
+void EditorManager::updateActions()
+{
+ IEditor *curEditor = currentEditor();
+ const QString fileName = fileNameForEditor(curEditor);
+ int openedCount = openedEditors().count() + d->m_editorModel->restoredEditors().count();
+
+ if (curEditor) {
+ if (HostOsInfo::isMacHost())
+ window()->setWindowModified(curEditor->document()->isModified());
+ updateMakeWritableWarning();
+ } else /* curEditor */ if (HostOsInfo::isMacHost()) {
window()->setWindowModified(false);
-#endif
}
setCloseSplitEnabled(d->m_splitter, d->m_splitter->isSplitter());
- d->m_saveAction->setEnabled(curEditor != 0 && curEditor->document()->isModified());
- d->m_saveAsAction->setEnabled(curEditor != 0 && curEditor->document()->isSaveAsAllowed());
- d->m_revertToSavedAction->setEnabled(curEditor != 0
- && !curEditor->document()->fileName().isEmpty() && curEditor->document()->isModified());
-
QString quotedName;
- if (!fName.isEmpty())
- quotedName = QLatin1Char('"') + fName + QLatin1Char('"');
-
- d->m_saveAsAction->setText(tr("Save %1 &As...").arg(quotedName));
- d->m_saveAction->setText(tr("&Save %1").arg(quotedName));
- d->m_revertToSavedAction->setText(tr("Revert %1 to Saved").arg(quotedName));
+ if (!fileName.isEmpty())
+ quotedName = QLatin1Char('"') + fileName + QLatin1Char('"');
+ setupSaveActions(curEditor, d->m_saveAction, d->m_saveAsAction, d->m_revertToSavedAction);
d->m_closeCurrentEditorAction->setEnabled(curEditor != 0);
d->m_closeCurrentEditorAction->setText(tr("Close %1").arg(quotedName));
@@ -1813,9 +1886,8 @@ QList<IEditor*> EditorManager::visibleEditors() const
} while (view && view != firstView);
}
} else {
- if (d->m_splitter->editor()) {
+ if (d->m_splitter->editor())
editors.append(d->m_splitter->editor());
- }
}
return editors;
}
@@ -1946,11 +2018,10 @@ bool EditorManager::restoreState(const QByteArray &state)
if (!fi.exists())
continue;
QFileInfo rfi(autoSaveName(fileName));
- if (rfi.exists() && fi.lastModified() < rfi.lastModified()) {
- openEditor(fileName, Id(QString::fromUtf8(id)));
- } else {
- d->m_editorModel->addRestoredEditor(fileName, displayName, Id(QString::fromUtf8(id)));
- }
+ if (rfi.exists() && fi.lastModified() < rfi.lastModified())
+ openEditor(fileName, Id::fromName(id));
+ else
+ d->m_editorModel->addRestoredEditor(fileName, displayName, Id::fromName(id));
}
}
@@ -2015,13 +2086,17 @@ void EditorManager::readSettings()
void EditorManager::revertToSaved()
{
- IEditor *currEditor = currentEditor();
- if (!currEditor)
+ revertToSaved(currentEditor());
+}
+
+void EditorManager::revertToSaved(Core::IEditor *editor)
+{
+ if (!editor)
return;
- const QString fileName = currEditor->document()->fileName();
+ const QString fileName = editor->document()->fileName();
if (fileName.isEmpty())
return;
- if (currEditor->document()->isModified()) {
+ if (editor->document()->isModified()) {
QMessageBox msgBox(QMessageBox::Question, tr("Revert to Saved"),
tr("You will lose your current changes if you proceed reverting %1.").arg(QDir::toNativeSeparators(fileName)),
QMessageBox::Yes|QMessageBox::No, ICore::mainWindow());
@@ -2034,7 +2109,7 @@ void EditorManager::revertToSaved()
}
QString errorString;
- if (!currEditor->document()->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents))
+ if (!editor->document()->reload(&errorString, IDocument::FlagReload, IDocument::TypeContents))
QMessageBox::critical(ICore::mainWindow(), tr("File Error"), errorString);
}
diff --git a/src/plugins/coreplugin/editormanager/editormanager.h b/src/plugins/coreplugin/editormanager/editormanager.h
index a4cf644548..3a54a38501 100644
--- a/src/plugins/coreplugin/editormanager/editormanager.h
+++ b/src/plugins/coreplugin/editormanager/editormanager.h
@@ -186,7 +186,7 @@ public:
void setWindowTitleAddition(const QString &addition);
QString windowTitleAddition() const;
- void addCloseEditorActions(QMenu *contextMenu, const QModelIndex &editorIndex);
+ void addSaveAndCloseEditorActions(QMenu *contextMenu, const QModelIndex &editorIndex);
void addNativeDirActions(QMenu *contextMenu, const QModelIndex &editorIndex);
signals:
@@ -203,6 +203,7 @@ public slots:
bool saveDocument(Core::IDocument *documentParam = 0);
bool saveDocumentAs(Core::IDocument *documentParam = 0);
void revertToSaved();
+ void revertToSaved(Core::IEditor *editor);
void closeEditor();
void closeOtherEditors();
@@ -218,6 +219,10 @@ private slots:
void updateVariable(const QByteArray &variable);
void autoSave();
+ void saveDocumentFromContextMenu();
+ void saveDocumentAsFromContextMenu();
+ void revertToSavedFromContextMenu();
+
void closeEditorFromContextMenu();
void closeOtherEditorsFromContextMenu();
@@ -263,6 +268,9 @@ private:
void switchToPreferedMode();
void updateAutoSave();
void setCloseSplitEnabled(Internal::SplitterOrView *splitterOrView, bool enable);
+ void updateMakeWritableWarning();
+ QString fileNameForEditor(IEditor *editor);
+ void setupSaveActions(IEditor *editor, QAction *saveAction, QAction *saveAsAction, QAction *revertToSavedAction);
EditorManagerPrivate *d;
diff --git a/src/plugins/coreplugin/editormanager/editorview.cpp b/src/plugins/coreplugin/editormanager/editorview.cpp
index 5a9b84168a..8529541e35 100644
--- a/src/plugins/coreplugin/editormanager/editorview.cpp
+++ b/src/plugins/coreplugin/editormanager/editorview.cpp
@@ -301,7 +301,7 @@ void EditorView::updateEditorHistory(IEditor *editor)
location.id = editor->id();
location.state = QVariant(state);
- for(int i = 0; i < m_editorHistory.size(); ++i) {
+ for (int i = 0; i < m_editorHistory.size(); ++i) {
if (m_editorHistory.at(i).document == 0
|| m_editorHistory.at(i).document == document
){
@@ -320,9 +320,8 @@ QRect EditorView::editorArea() const
void EditorView::addCurrentPositionToNavigationHistory(IEditor *editor, const QByteArray &saveState)
{
- if (editor && editor != currentEditor()) {
+ if (editor && editor != currentEditor())
return; // we only save editor sate for the current editor, when the user interacts
- }
if (!editor)
editor = currentEditor();
@@ -334,11 +333,10 @@ void EditorView::addCurrentPositionToNavigationHistory(IEditor *editor, const QB
return;
QByteArray state;
- if (saveState.isNull()) {
+ if (saveState.isNull())
state = editor->saveState();
- } else {
+ else
state = saveState;
- }
EditLocation location;
location.document = document;
@@ -606,9 +604,8 @@ SplitterOrView *SplitterOrView::findNextView(SplitterOrView *view)
SplitterOrView *SplitterOrView::findNextView_helper(SplitterOrView *view, bool *found)
{
- if (*found && m_view) {
+ if (*found && m_view)
return this;
- }
if (this == view) {
*found = true;
@@ -664,7 +661,7 @@ void SplitterOrView::split(Qt::Orientation orientation)
SplitterOrView *otherView = 0;
if (e) {
- foreach(IEditor *editor, m_view->editors())
+ foreach (IEditor *editor, m_view->editors())
m_view->removeEditor(editor);
m_splitter->addWidget((view = new SplitterOrView(e)));
@@ -721,9 +718,8 @@ void SplitterOrView::unsplitAll_helper()
ICore::editorManager()->emptyView(m_view);
if (m_splitter) {
for (int i = 0; i < m_splitter->count(); ++i) {
- if (SplitterOrView *splitterOrView = qobject_cast<SplitterOrView*>(m_splitter->widget(i))) {
+ if (SplitterOrView *splitterOrView = qobject_cast<SplitterOrView*>(m_splitter->widget(i)))
splitterOrView->unsplitAll_helper();
- }
}
}
}
@@ -762,14 +758,14 @@ void SplitterOrView::unsplit()
if (parentSplitter) { // not the toplevel splitterOrView
if (parentSplitter->orientation() == Qt::Horizontal) {
if (parentSplitter->widget(0) == this)
- m_view->setCloseSplitIcon(QIcon(Constants::ICON_CLOSE_SPLIT_LEFT));
+ m_view->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_LEFT)));
else
- m_view->setCloseSplitIcon(QIcon(Constants::ICON_CLOSE_SPLIT_RIGHT));
+ m_view->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_RIGHT)));
} else {
if (parentSplitter->widget(0) == this)
- m_view->setCloseSplitIcon(QIcon(Constants::ICON_CLOSE_SPLIT_TOP));
+ m_view->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_TOP)));
else
- m_view->setCloseSplitIcon(QIcon(Constants::ICON_CLOSE_SPLIT_BOTTOM));
+ m_view->setCloseSplitIcon(QIcon(QLatin1String(Constants::ICON_CLOSE_SPLIT_BOTTOM)));
}
}
}
@@ -840,7 +836,7 @@ void SplitterOrView::restoreState(const QByteArray &state)
stream >> fileName >> id >> editorState;
if (!QFile::exists(fileName))
return;
- IEditor *e = em->openEditor(view(), fileName, Id(id), Core::EditorManager::IgnoreNavigationHistory
+ IEditor *e = em->openEditor(view(), fileName, Id::fromString(id), Core::EditorManager::IgnoreNavigationHistory
| Core::EditorManager::NoActivate);
if (!e) {
diff --git a/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp b/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp
index 6fc73272e3..a9a3183831 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorsmodel.cpp
@@ -235,9 +235,8 @@ QList<OpenEditorsModel::Entry> OpenEditorsModel::restoredEditors() const
{
QList<Entry> result;
for (int i = d->m_editors.count()-1; i >= 0; --i) {
- if (!d->m_editors.at(i).editor) {
+ if (!d->m_editors.at(i).editor)
result.append(d->m_editors.at(i));
- }
}
return result;
}
@@ -250,7 +249,7 @@ bool OpenEditorsModel::isDuplicate(IEditor *editor) const
IEditor *OpenEditorsModel::originalForDuplicate(IEditor *duplicate) const
{
IDocument *document = duplicate->document();
- foreach(const Entry &e, d->m_editors)
+ foreach (const Entry &e, d->m_editors)
if (e.editor && e.editor->document() == document)
return e.editor;
return 0;
@@ -260,7 +259,7 @@ QList<IEditor *> OpenEditorsModel::duplicatesFor(IEditor *editor) const
{
QList<IEditor *> result;
IDocument *document = editor->document();
- foreach(IEditor *e, d->m_duplicateEditors)
+ foreach (IEditor *e, d->m_duplicateEditors)
if (e->document() == document)
result += e;
return result;
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.cpp b/src/plugins/coreplugin/editormanager/openeditorsview.cpp
index c30ace1f86..b65fe1c25f 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsview.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorsview.cpp
@@ -41,6 +41,8 @@
#include <coreplugin/actionmanager/command.h>
#include <utils/qtcassert.h>
+#include <QApplication>
+#include <QGridLayout>
#include <QTimer>
#include <QMenu>
#include <QPainter>
@@ -48,6 +50,7 @@
#include <QStyleOption>
#include <QHeaderView>
#include <QKeyEvent>
+#include <QTreeView>
using namespace Core;
using namespace Core::Internal;
@@ -93,36 +96,36 @@ void OpenEditorsDelegate::paint(QPainter *painter, const QStyleOptionViewItem &o
OpenEditorsWidget::OpenEditorsWidget()
{
- m_ui.setupUi(this);
setWindowTitle(tr("Open Documents"));
setWindowIcon(QIcon(QLatin1String(Constants::ICON_DIR)));
- setFocusProxy(m_ui.editorList);
- m_ui.editorList->viewport()->setAttribute(Qt::WA_Hover);
- m_ui.editorList->setItemDelegate((m_delegate = new OpenEditorsDelegate(this)));
- m_ui.editorList->header()->hide();
- m_ui.editorList->setIndentation(0);
- m_ui.editorList->setTextElideMode(Qt::ElideMiddle);
- m_ui.editorList->setFrameStyle(QFrame::NoFrame);
- m_ui.editorList->setAttribute(Qt::WA_MacShowFocusRect, false);
+ setUniformRowHeights(true);
+ viewport()->setAttribute(Qt::WA_Hover);
+ setItemDelegate((m_delegate = new OpenEditorsDelegate(this)));
+ header()->hide();
+ setIndentation(0);
+ setTextElideMode(Qt::ElideMiddle);
+ setFrameStyle(QFrame::NoFrame);
+ setAttribute(Qt::WA_MacShowFocusRect, false);
EditorManager *em = EditorManager::instance();
- m_ui.editorList->setModel(em->openedEditorsModel());
- m_ui.editorList->setSelectionMode(QAbstractItemView::SingleSelection);
- m_ui.editorList->setSelectionBehavior(QAbstractItemView::SelectRows);
- m_ui.editorList->header()->setStretchLastSection(false);
- m_ui.editorList->header()->setResizeMode(0, QHeaderView::Stretch);
- m_ui.editorList->header()->setResizeMode(1, QHeaderView::Fixed);
- m_ui.editorList->header()->resizeSection(1, 16);
- m_ui.editorList->setContextMenuPolicy(Qt::CustomContextMenu);
- m_ui.editorList->installEventFilter(this);
+ setModel(em->openedEditorsModel());
+ setSelectionMode(QAbstractItemView::SingleSelection);
+ setSelectionBehavior(QAbstractItemView::SelectRows);
+ header()->setStretchLastSection(false);
+ header()->setResizeMode(0, QHeaderView::Stretch);
+ header()->setResizeMode(1, QHeaderView::Fixed);
+ header()->resizeSection(1, 16);
+ setContextMenuPolicy(Qt::CustomContextMenu);
+ installEventFilter(this);
+ viewport()->installEventFilter(this);
connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(updateCurrentItem(Core::IEditor*)));
- connect(m_ui.editorList, SIGNAL(clicked(QModelIndex)),
+ connect(this, SIGNAL(clicked(QModelIndex)),
this, SLOT(handleClicked(QModelIndex)));
- connect(m_ui.editorList, SIGNAL(pressed(QModelIndex)),
+ connect(this, SIGNAL(pressed(QModelIndex)),
this, SLOT(handlePressed(QModelIndex)));
- connect(m_ui.editorList, SIGNAL(customContextMenuRequested(QPoint)),
+ connect(this, SIGNAL(customContextMenuRequested(QPoint)),
this, SLOT(contextMenuRequested(QPoint)));
}
@@ -133,30 +136,41 @@ OpenEditorsWidget::~OpenEditorsWidget()
void OpenEditorsWidget::updateCurrentItem(Core::IEditor *editor)
{
if (!editor) {
- m_ui.editorList->clearSelection();
+ clearSelection();
return;
}
EditorManager *em = EditorManager::instance();
- m_ui.editorList->setCurrentIndex(em->openedEditorsModel()->indexOf(editor));
- m_ui.editorList->selectionModel()->select(m_ui.editorList->currentIndex(),
+ setCurrentIndex(em->openedEditorsModel()->indexOf(editor));
+ selectionModel()->select(currentIndex(),
QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
- m_ui.editorList->scrollTo(m_ui.editorList->currentIndex());
+ scrollTo(currentIndex());
}
bool OpenEditorsWidget::eventFilter(QObject *obj, QEvent *event)
{
- if (obj == m_ui.editorList && event->type() == QEvent::KeyPress
- && m_ui.editorList->currentIndex().isValid()) {
+ if (obj == this && event->type() == QEvent::KeyPress
+ && currentIndex().isValid()) {
QKeyEvent *ke = static_cast<QKeyEvent*>(event);
if ((ke->key() == Qt::Key_Return
|| ke->key() == Qt::Key_Enter)
&& ke->modifiers() == 0) {
- activateEditor(m_ui.editorList->currentIndex());
+ activateEditor(currentIndex());
return true;
} else if ((ke->key() == Qt::Key_Delete
|| ke->key() == Qt::Key_Backspace)
&& ke->modifiers() == 0) {
- closeEditor(m_ui.editorList->currentIndex());
+ closeEditor(currentIndex());
+ }
+ } else if (obj == viewport()
+ && event->type() == QEvent::MouseButtonRelease) {
+ QMouseEvent * me = static_cast<QMouseEvent*>(event);
+ if (me->button() == Qt::MiddleButton
+ && me->modifiers() == Qt::NoModifier) {
+ QModelIndex index = indexAt(me->pos());
+ if (index.isValid()) {
+ closeEditor(index);
+ return true;
+ }
}
}
return false;
@@ -164,11 +178,10 @@ bool OpenEditorsWidget::eventFilter(QObject *obj, QEvent *event)
void OpenEditorsWidget::handlePressed(const QModelIndex &index)
{
- if (index.column() == 0) {
+ if (index.column() == 0)
activateEditor(index);
- } else if (index.column() == 1) {
+ else if (index.column() == 1)
m_delegate->pressedIndex = index;
- }
}
void OpenEditorsWidget::handleClicked(const QModelIndex &index)
@@ -178,7 +191,7 @@ void OpenEditorsWidget::handleClicked(const QModelIndex &index)
// work around a bug in itemviews where the delegate wouldn't get the QStyle::State_MouseOver
QPoint cursorPos = QCursor::pos();
- QWidget *vp = m_ui.editorList->viewport();
+ QWidget *vp = viewport();
QMouseEvent e(QEvent::MouseMove, vp->mapFromGlobal(cursorPos), cursorPos, Qt::NoButton, 0, 0);
QCoreApplication::sendEvent(vp, &e);
}
@@ -186,7 +199,7 @@ void OpenEditorsWidget::handleClicked(const QModelIndex &index)
void OpenEditorsWidget::activateEditor(const QModelIndex &index)
{
- m_ui.editorList->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
+ selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
EditorManager::instance()->activateEditorForIndex(index, EditorManager::ModeSwitch);
}
@@ -200,11 +213,11 @@ void OpenEditorsWidget::closeEditor(const QModelIndex &index)
void OpenEditorsWidget::contextMenuRequested(QPoint pos)
{
QMenu contextMenu;
- QModelIndex editorIndex = m_ui.editorList->indexAt(pos);
- EditorManager::instance()->addCloseEditorActions(&contextMenu, editorIndex);
+ QModelIndex editorIndex = indexAt(pos);
+ EditorManager::instance()->addSaveAndCloseEditorActions(&contextMenu, editorIndex);
contextMenu.addSeparator();
EditorManager::instance()->addNativeDirActions(&contextMenu, editorIndex);
- contextMenu.exec(m_ui.editorList->mapToGlobal(pos));
+ contextMenu.exec(mapToGlobal(pos));
}
///
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.h b/src/plugins/coreplugin/editormanager/openeditorsview.h
index ca8ab8f92f..ab32829a7e 100644
--- a/src/plugins/coreplugin/editormanager/openeditorsview.h
+++ b/src/plugins/coreplugin/editormanager/openeditorsview.h
@@ -30,11 +30,10 @@
#ifndef OPENEDITORSVIEW_H
#define OPENEDITORSVIEW_H
-#include "ui_openeditorsview.h"
-
#include <coreplugin/inavigationwidgetfactory.h>
#include <QStyledItemDelegate>
+#include <QTreeView>
namespace Core {
class IEditor;
@@ -43,8 +42,6 @@ namespace Internal {
class OpenEditorsDelegate : public QStyledItemDelegate
{
- Q_OBJECT
-
public:
explicit OpenEditorsDelegate(QObject *parent = 0);
@@ -54,7 +51,7 @@ public:
mutable QModelIndex pressedIndex;
};
-class OpenEditorsWidget : public QWidget
+class OpenEditorsWidget : public QTreeView
{
Q_OBJECT
@@ -73,9 +70,8 @@ private slots:
private:
void activateEditor(const QModelIndex &index);
void closeEditor(const QModelIndex &index);
+ using QAbstractItemView::closeEditor;
- Ui::OpenEditorsView m_ui;
- QWidget *m_widget;
OpenEditorsDelegate *m_delegate;
};
diff --git a/src/plugins/coreplugin/editormanager/openeditorsview.ui b/src/plugins/coreplugin/editormanager/openeditorsview.ui
deleted file mode 100644
index 299538e66a..0000000000
--- a/src/plugins/coreplugin/editormanager/openeditorsview.ui
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>Core::Internal::OpenEditorsView</class>
- <widget class="QWidget" name="Core::Internal::OpenEditorsView">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>263</width>
- <height>217</height>
- </rect>
- </property>
- <layout class="QGridLayout">
- <property name="margin">
- <number>0</number>
- </property>
- <property name="spacing">
- <number>0</number>
- </property>
- <item row="0" column="0">
- <widget class="QTreeView" name="editorList">
- <property name="uniformRowHeights">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/plugins/coreplugin/editormanager/openeditorswindow.cpp b/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
index 197c41c4fd..19c230483f 100644
--- a/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
+++ b/src/plugins/coreplugin/editormanager/openeditorswindow.cpp
@@ -33,6 +33,7 @@
#include "editorview.h"
#include "idocument.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QFocusEvent>
@@ -60,16 +61,14 @@ OpenEditorsWindow::OpenEditorsWindow(QWidget *parent) :
m_editorList->setIndentation(0);
m_editorList->setSelectionMode(QAbstractItemView::SingleSelection);
m_editorList->setTextElideMode(Qt::ElideMiddle);
-#ifdef Q_OS_MAC
- m_editorList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ m_editorList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
m_editorList->installEventFilter(this);
// We disable the frame on this list view and use a QFrame around it instead.
// This improves the look with QGTKStyle.
-#ifndef Q_OS_MAC
- setFrameStyle(m_editorList->frameStyle());
-#endif
+ if (!Utils::HostOsInfo::isMacHost())
+ setFrameStyle(m_editorList->frameStyle());
m_editorList->setFrameStyle(QFrame::NoFrame);
QVBoxLayout *layout = new QVBoxLayout(this);
@@ -89,9 +88,8 @@ void OpenEditorsWindow::selectAndHide()
void OpenEditorsWindow::setVisible(bool visible)
{
QWidget::setVisible(visible);
- if (visible) {
+ if (visible)
setFocus();
- }
}
bool OpenEditorsWindow::isCentering()
diff --git a/src/plugins/coreplugin/editortoolbar.cpp b/src/plugins/coreplugin/editortoolbar.cpp
index 554a2d36a5..27b712df2c 100644
--- a/src/plugins/coreplugin/editortoolbar.cpp
+++ b/src/plugins/coreplugin/editortoolbar.cpp
@@ -43,6 +43,7 @@
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
+#include <utils/hostosinfo.h>
#include <utils/parameteraction.h>
#include <utils/qtcassert.h>
#include <utils/styledbar.h>
@@ -133,6 +134,7 @@ EditorToolBar::EditorToolBar(QWidget *parent) :
connect(d->m_goForwardAction, SIGNAL(triggered()), this, SIGNAL(goForwardClicked()));
d->m_editorList->setProperty("hideicon", true);
+ d->m_editorList->setProperty("notelideasterisk", true);
d->m_editorList->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
d->m_editorList->setMinimumContentsLength(20);
d->m_editorList->setModel(d->m_editorsListModel);
@@ -151,10 +153,10 @@ EditorToolBar::EditorToolBar(QWidget *parent) :
d->m_forwardButton= new QToolButton(this);
d->m_forwardButton->setDefaultAction(d->m_goForwardAction);
-#ifdef Q_OS_MAC
- d->m_horizontalSplitAction->setIconVisibleInMenu(false);
- d->m_verticalSplitAction->setIconVisibleInMenu(false);
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ d->m_horizontalSplitAction->setIconVisibleInMenu(false);
+ d->m_verticalSplitAction->setIconVisibleInMenu(false);
+ }
d->m_splitButton->setIcon(QIcon(QLatin1String(Constants::ICON_SPLIT_HORIZONTAL)));
d->m_splitButton->setToolTip(tr("Split"));
@@ -331,13 +333,12 @@ void EditorToolBar::listContextMenu(QPoint pos)
QMenu menu;
QAction *copyPath = menu.addAction(tr("Copy Full Path to Clipboard"));
menu.addSeparator();
- EditorManager::instance()->addCloseEditorActions(&menu, index);
+ EditorManager::instance()->addSaveAndCloseEditorActions(&menu, index);
menu.addSeparator();
EditorManager::instance()->addNativeDirActions(&menu, index);
QAction *result = menu.exec(d->m_editorList->mapToGlobal(pos));
- if (result == copyPath) {
+ if (result == copyPath)
QApplication::clipboard()->setText(QDir::toNativeSeparators(fileName));
- }
}
void EditorToolBar::makeEditorWritable()
diff --git a/src/plugins/coreplugin/externaltool.cpp b/src/plugins/coreplugin/externaltool.cpp
index 9c2f984d10..188b4b895e 100644
--- a/src/plugins/coreplugin/externaltool.cpp
+++ b/src/plugins/coreplugin/externaltool.cpp
@@ -441,9 +441,8 @@ ExternalTool * ExternalTool::createFromFile(const QString &fileName, QString *er
if (!reader.fetch(absFileName, errorMessage))
return 0;
ExternalTool *tool = ExternalTool::createFromXml(reader.data(), errorMessage, locale);
- if (!tool) {
+ if (!tool)
return 0;
- }
tool->m_fileName = absFileName;
return tool;
}
@@ -624,9 +623,8 @@ void ExternalToolRunner::run()
void ExternalToolRunner::started()
{
- if (!m_resolvedInput.isEmpty()) {
+ if (!m_resolvedInput.isEmpty())
m_process->write(m_resolvedInput.toLocal8Bit());
- }
m_process->closeWriteChannel();
}
@@ -637,9 +635,8 @@ void ExternalToolRunner::finished(int exitCode, QProcess::ExitStatus status)
|| m_tool->errorHandling() == ExternalTool::ReplaceSelection) {
emit ExternalToolManager::instance()->replaceSelectionRequested(m_processOutput);
}
- if (m_tool->modifiesCurrentDocument()) {
+ if (m_tool->modifiesCurrentDocument())
DocumentManager::unexpectFileChange(m_expectedFileName);
- }
}
ICore::messageManager()->printToOutputPane(
tr("'%1' finished").arg(m_resolvedExecutable), false);
@@ -661,11 +658,10 @@ void ExternalToolRunner::readStandardOutput()
return;
QByteArray data = m_process->readAllStandardOutput();
QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_outputCodecState);
- if (m_tool->outputHandling() == ExternalTool::ShowInPane) {
+ if (m_tool->outputHandling() == ExternalTool::ShowInPane)
ICore::messageManager()->printToOutputPane(output, true);
- } else if (m_tool->outputHandling() == ExternalTool::ReplaceSelection) {
+ else if (m_tool->outputHandling() == ExternalTool::ReplaceSelection)
m_processOutput.append(output);
- }
}
void ExternalToolRunner::readStandardError()
@@ -674,11 +670,10 @@ void ExternalToolRunner::readStandardError()
return;
QByteArray data = m_process->readAllStandardError();
QString output = m_outputCodec->toUnicode(data.constData(), data.length(), &m_errorCodecState);
- if (m_tool->errorHandling() == ExternalTool::ShowInPane) {
+ if (m_tool->errorHandling() == ExternalTool::ShowInPane)
ICore::messageManager()->printToOutputPane(output, true);
- } else if (m_tool->errorHandling() == ExternalTool::ReplaceSelection) {
+ else if (m_tool->errorHandling() == ExternalTool::ReplaceSelection)
m_processOutput.append(output);
- }
}
// #pragma mark -- ExternalToolManager
@@ -777,9 +772,8 @@ void ExternalToolManager::menuActivated()
ExternalTool *tool = m_tools.value(action->data().toString());
QTC_ASSERT(tool, return);
ExternalToolRunner *runner = new ExternalToolRunner(tool);
- if (runner->hasError()) {
+ if (runner->hasError())
ICore::messageManager()->printToOutputPane(runner->errorString(), true);
- }
}
QMap<QString, QList<Internal::ExternalTool *> > ExternalToolManager::toolsByCategory() const
@@ -820,7 +814,8 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
const QString externalToolsPrefix = QLatin1String("Tools.External.");
while (remainingActions.hasNext()) {
remainingActions.next();
- ActionManager::unregisterAction(remainingActions.value(), Id(externalToolsPrefix + remainingActions.key()));
+ ActionManager::unregisterAction(remainingActions.value(),
+ Id::fromString(externalToolsPrefix + remainingActions.key()));
delete remainingActions.value();
}
m_actions.clear();
@@ -839,11 +834,10 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
if (containerName.isEmpty()) { // no displayCategory, so put into external tools menu directly
container = mexternaltools;
} else {
- if (m_containers.contains(containerName)) {
+ if (m_containers.contains(containerName))
container = m_containers.take(containerName); // remove to avoid deletion below
- } else {
- container = ActionManager::createMenu(Id(QLatin1String("Tools.External.Category.") + containerName));
- }
+ else
+ container = ActionManager::createMenu(Id::fromString(QLatin1String("Tools.External.Category.") + containerName));
newContainers.insert(containerName, container);
mexternaltools->addMenu(container, Constants::G_DEFAULT_ONE);
container->menu()->setTitle(containerName);
@@ -855,13 +849,13 @@ void ExternalToolManager::setToolsByCategory(const QMap<QString, QList<Internal:
Command *command = 0;
if (m_actions.contains(toolId)) {
action = m_actions.value(toolId);
- command = ActionManager::command(Id(externalToolsPrefix + toolId));
+ command = ActionManager::command(Id::fromString(externalToolsPrefix + toolId));
} else {
action = new QAction(tool->displayName(), this);
action->setData(toolId);
m_actions.insert(toolId, action);
connect(action, SIGNAL(triggered()), this, SLOT(menuActivated()));
- command = ActionManager::registerAction(action, Id(externalToolsPrefix + toolId), Context(Constants::C_GLOBAL));
+ command = ActionManager::registerAction(action, Id::fromString(externalToolsPrefix + toolId), Context(Constants::C_GLOBAL));
command->setAttribute(Command::CA_UpdateText);
}
action->setText(tool->displayName());
@@ -944,6 +938,5 @@ void ExternalToolManager::writeSettings()
void ExternalToolManager::openPreferences()
{
- ICore::showOptionsDialog(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE),
- QLatin1String(Core::Constants::SETTINGS_ID_TOOLS));
+ ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::SETTINGS_ID_TOOLS);
}
diff --git a/src/plugins/coreplugin/fancyactionbar.cpp b/src/plugins/coreplugin/fancyactionbar.cpp
index 8105692a0b..651683d4cb 100644
--- a/src/plugins/coreplugin/fancyactionbar.cpp
+++ b/src/plugins/coreplugin/fancyactionbar.cpp
@@ -32,6 +32,8 @@
#include <utils/stylehelper.h>
#include <utils/stringutils.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <coreplugin/icore.h>
#include <coreplugin/imode.h>
@@ -70,7 +72,7 @@ void FancyToolButton::forceVisible(bool visible)
bool FancyToolButton::event(QEvent *e)
{
- switch(e->type()) {
+ switch (e->type()) {
case QEvent::Enter:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
@@ -87,6 +89,12 @@ bool FancyToolButton::event(QEvent *e)
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
+ case QEvent::ToolTip:
+ {
+ QHelpEvent *he = static_cast<QHelpEvent *>(e);
+ Utils::ToolTip::instance()->show(mapToGlobal(he->pos()), Utils::TextContent(toolTip()), this);
+ return true;
+ }
default:
return QToolButton::event(e);
}
@@ -109,11 +117,10 @@ static QVector<QString> splitInTwoLines(const QString &text, const QFontMetrics
nextSplitPos - text.length() - 1);
if (nextSplitPos != -1) {
int splitCandidate = nextSplitPos + rx.matchedLength();
- if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth) {
+ if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth)
splitPos = splitCandidate;
- } else {
+ else
break;
- }
}
} while (nextSplitPos > 0 && fontMetrics.width(text.left(nextSplitPos)) > availableWidth);
// check if we could split at white space at all
diff --git a/src/plugins/coreplugin/fancytabwidget.cpp b/src/plugins/coreplugin/fancytabwidget.cpp
index 898a920cad..dacd8f73e2 100644
--- a/src/plugins/coreplugin/fancytabwidget.cpp
+++ b/src/plugins/coreplugin/fancytabwidget.cpp
@@ -28,6 +28,7 @@
****************************************************************************/
#include "fancytabwidget.h"
+#include <utils/hostosinfo.h>
#include <utils/stylehelper.h>
#include <utils/styledbar.h>
@@ -273,23 +274,23 @@ void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
}
QString tabText(this->tabText(tabIndex));
- QRect tabTextRect(tabRect(tabIndex));
+ QRect tabTextRect(rect);
+ const bool drawIcon = rect.height() > 36;
QRect tabIconRect(tabTextRect);
- tabTextRect.translate(0, -2);
+ tabTextRect.translate(0, drawIcon ? -2 : 1);
QFont boldFont(painter->font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true);
painter->setFont(boldFont);
painter->setPen(selected ? QColor(255, 255, 255, 160) : QColor(0, 0, 0, 110));
- int textFlags = Qt::AlignCenter | Qt::AlignBottom | Qt::TextWordWrap;
+ const int textFlags = Qt::AlignCenter | (drawIcon ? Qt::AlignBottom : Qt::AlignVCenter) | Qt::TextWordWrap;
if (enabled) {
painter->drawText(tabTextRect, textFlags, tabText);
painter->setPen(selected ? QColor(60, 60, 60) : Utils::StyleHelper::panelTextColor());
} else {
painter->setPen(selected ? Utils::StyleHelper::panelTextColor() : QColor(255, 255, 255, 120));
}
-#ifndef Q_OS_MAC
- if (!selected && enabled) {
+ if (!Utils::HostOsInfo::isMacHost() && !selected && enabled) {
painter->save();
int fader = int(m_tabs[tabIndex]->fader());
QLinearGradient grad(rect.topLeft(), rect.topRight());
@@ -302,14 +303,15 @@ void FancyTabBar::paintTab(QPainter *painter, int tabIndex) const
painter->drawLine(rect.bottomLeft(), rect.bottomRight());
painter->restore();
}
-#endif
if (!enabled)
painter->setOpacity(0.7);
- int textHeight = painter->fontMetrics().boundingRect(QRect(0, 0, width(), height()), Qt::TextWordWrap, tabText).height();
- tabIconRect.adjust(0, 4, 0, -textHeight);
- Utils::StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, enabled ? QIcon::Normal : QIcon::Disabled);
+ if (drawIcon) {
+ int textHeight = painter->fontMetrics().boundingRect(QRect(0, 0, width(), height()), Qt::TextWordWrap, tabText).height();
+ tabIconRect.adjust(0, 4, 0, -textHeight);
+ Utils::StyleHelper::drawIconWithShadow(tabIcon(tabIndex), tabIconRect, painter, enabled ? QIcon::Normal : QIcon::Disabled);
+ }
painter->translate(0, -1);
painter->drawText(tabTextRect, textFlags, tabText);
diff --git a/src/plugins/coreplugin/featureprovider.h b/src/plugins/coreplugin/featureprovider.h
index 9895eebb5b..f6672794fe 100644
--- a/src/plugins/coreplugin/featureprovider.h
+++ b/src/plugins/coreplugin/featureprovider.h
@@ -38,11 +38,6 @@
#include <QSet>
#include <QStringList>
-
-namespace Utils {
-class AbstractMacroExpander;
-}
-
namespace Core {
class CORE_EXPORT FeatureSet;
@@ -61,10 +56,8 @@ public:
class CORE_EXPORT Feature : public Id
{
-friend class FeatureSet;
public:
- Feature(const char *name) : Id(name) {}
- explicit Feature(const QString &name) : Id(name) {}
+ Feature(Id id) : Id(id) {}
};
class CORE_EXPORT FeatureSet : private QSet<Feature>
@@ -72,12 +65,10 @@ class CORE_EXPORT FeatureSet : private QSet<Feature>
public:
FeatureSet() {}
- FeatureSet(const Feature &feature)
+ FeatureSet(Core::Id id)
{
- if (feature.toString().isEmpty())
- return;
-
- insert(feature);
+ if (id.isValid())
+ insert(id);
}
FeatureSet(const FeatureSet &other) : QSet<Feature>(other) {}
diff --git a/src/plugins/coreplugin/fileiconprovider.cpp b/src/plugins/coreplugin/fileiconprovider.cpp
index 6025ae1dc3..bab2617569 100644
--- a/src/plugins/coreplugin/fileiconprovider.cpp
+++ b/src/plugins/coreplugin/fileiconprovider.cpp
@@ -30,6 +30,7 @@
#include "fileiconprovider.h"
#include "mimedatabase.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QApplication>
@@ -43,6 +44,8 @@
#include <QIcon>
#include <QStyle>
+using namespace Utils;
+
/*!
\class Core::FileIconProvider
@@ -138,14 +141,13 @@ QIcon FileIconProvider::icon(const QFileInfo &fileInfo) const
}
}
// Get icon from OS.
-#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
- return QFileIconProvider::icon(fileInfo);
-#else
+ if (HostOsInfo::isWindowsHost() || HostOsInfo::isMacHost())
+ return QFileIconProvider::icon(fileInfo);
+
// File icons are unknown on linux systems.
return (fileInfo.isDir()) ?
QFileIconProvider::icon(fileInfo) :
d->m_unknownFileIcon;
-#endif
}
/*!
@@ -178,11 +180,10 @@ void FileIconProvider::registerIconOverlayForSuffix(const QIcon &icon,
const QPixmap fileIconPixmap = overlayIcon(QStyle::SP_FileIcon, icon, QSize(16, 16));
// replace old icon, if it exists
const CacheIterator it = findBySuffix(suffix, d->m_cache.begin(), d->m_cache.end());
- if (it == d->m_cache.end()) {
+ if (it == d->m_cache.end())
d->m_cache.append(StringIconPair(suffix, fileIconPixmap));
- } else {
+ else
(*it).second = fileIconPixmap;
- }
}
/*!
diff --git a/src/plugins/coreplugin/fileutils.cpp b/src/plugins/coreplugin/fileutils.cpp
index 0a8043de42..5f20153c28 100644
--- a/src/plugins/coreplugin/fileutils.cpp
+++ b/src/plugins/coreplugin/fileutils.cpp
@@ -29,41 +29,37 @@
#include "fileutils.h"
+#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
#include <coreplugin/icore.h>
#include <coreplugin/iversioncontrol.h>
#include <coreplugin/removefiledialog.h>
#include <coreplugin/vcsmanager.h>
+#include <utils/consoleprocess.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
+#include <utils/qtcprocess.h>
+#include <utils/unixutils.h>
+#include <QApplication>
#include <QDir>
#include <QFileInfo>
-#include <QProcess>
-#include <QApplication>
#include <QMessageBox>
+#include <QProcess>
+#include <QPushButton>
#include <QWidget>
#if QT_VERSION < 0x050000
#include <QAbstractFileEngine>
#endif
-#ifndef Q_OS_WIN
-#include <utils/consoleprocess.h>
-#include <utils/qtcprocess.h>
-#ifndef Q_OS_MAC
-#include <coreplugin/coreconstants.h>
-#include <utils/unixutils.h>
-#include <QPushButton>
-#endif
-#endif
+using namespace Utils;
-using namespace Core;
+namespace Core {
-#if !defined(Q_OS_WIN) && !defined(Q_OS_MAC)
+#ifndef Q_OS_MAC
// Show error with option to open settings.
-static inline void showGraphicalShellError(QWidget *parent,
- const QString &app,
- const QString &error)
+static void showGraphicalShellError(QWidget *parent, const QString &app, const QString &error)
{
const QString title = QApplication::translate("Core::Internal",
"Launching a file browser failed");
@@ -77,72 +73,71 @@ static inline void showGraphicalShellError(QWidget *parent,
QMessageBox::ActionRole);
mbox.exec();
if (mbox.clickedButton() == settingsButton)
- Core::ICore::showOptionsDialog(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE),
- QLatin1String(Core::Constants::SETTINGS_ID_ENVIRONMENT));
+ ICore::showOptionsDialog(Constants::SETTINGS_CATEGORY_CORE, Constants::SETTINGS_ID_ENVIRONMENT);
}
#endif
void FileUtils::showInGraphicalShell(QWidget *parent, const QString &pathIn)
{
// Mac, Windows support folder or file.
-#if defined(Q_OS_WIN)
- const QString explorer = Utils::Environment::systemEnvironment().searchInPath(QLatin1String("explorer.exe"));
- if (explorer.isEmpty()) {
- QMessageBox::warning(parent,
- QApplication::translate("Core::Internal",
- "Launching Windows Explorer Failed"),
- QApplication::translate("Core::Internal",
- "Could not find explorer.exe in path to launch Windows Explorer."));
- return;
- }
- QStringList param;
- if (!QFileInfo(pathIn).isDir())
- param += QLatin1String("/select,");
- param += QDir::toNativeSeparators(pathIn);
- QProcess::startDetached(explorer, param);
-#elif defined(Q_OS_MAC)
- Q_UNUSED(parent)
- QStringList scriptArgs;
- scriptArgs << QLatin1String("-e")
- << QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
- .arg(pathIn);
- QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
- scriptArgs.clear();
- scriptArgs << QLatin1String("-e")
- << QLatin1String("tell application \"Finder\" to activate");
- QProcess::execute("/usr/bin/osascript", scriptArgs);
-#else
- // we cannot select a file here, because no file browser really supports it...
- const QFileInfo fileInfo(pathIn);
- const QString folder = fileInfo.isDir() ? fileInfo.absoluteFilePath() : fileInfo.filePath();
- const QString app = Utils::UnixUtils::fileBrowser(Core::ICore::settings());
- QProcess browserProc;
- const QString browserArgs = Utils::UnixUtils::substituteFileBrowserParameters(app, folder);
- bool success = browserProc.startDetached(browserArgs);
- const QString error = QString::fromLocal8Bit(browserProc.readAllStandardError());
- success = success && error.isEmpty();
- if (!success)
- showGraphicalShellError(parent, app, error);
+ if (HostOsInfo::isWindowsHost()) {
+ const QString explorer = Environment::systemEnvironment().searchInPath(QLatin1String("explorer.exe"));
+ if (explorer.isEmpty()) {
+ QMessageBox::warning(parent,
+ QApplication::translate("Core::Internal",
+ "Launching Windows Explorer Failed"),
+ QApplication::translate("Core::Internal",
+ "Could not find explorer.exe in path to launch Windows Explorer."));
+ return;
+ }
+ QStringList param;
+ if (!QFileInfo(pathIn).isDir())
+ param += QLatin1String("/select,");
+ param += QDir::toNativeSeparators(pathIn);
+ QProcess::startDetached(explorer, param);
+ } else if (HostOsInfo::isMacHost()) {
+ QStringList scriptArgs;
+ scriptArgs << QLatin1String("-e")
+ << QString::fromLatin1("tell application \"Finder\" to reveal POSIX file \"%1\"")
+ .arg(pathIn);
+ QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
+ scriptArgs.clear();
+ scriptArgs << QLatin1String("-e")
+ << QLatin1String("tell application \"Finder\" to activate");
+ QProcess::execute(QLatin1String("/usr/bin/osascript"), scriptArgs);
+ } else {
+#ifndef Q_OS_MAC
+ // we cannot select a file here, because no file browser really supports it...
+ const QFileInfo fileInfo(pathIn);
+ const QString folder = fileInfo.isDir() ? fileInfo.absoluteFilePath() : fileInfo.filePath();
+ const QString app = UnixUtils::fileBrowser(ICore::settings());
+ QProcess browserProc;
+ const QString browserArgs = UnixUtils::substituteFileBrowserParameters(app, folder);
+ bool success = browserProc.startDetached(browserArgs);
+ const QString error = QString::fromLocal8Bit(browserProc.readAllStandardError());
+ success = success && error.isEmpty();
+ if (!success)
+ showGraphicalShellError(parent, app, error);
#endif
+ }
}
void FileUtils::openTerminal(const QString &path)
{
// Get terminal application
-#ifdef Q_OS_WIN
- const QString terminalEmulator = QString::fromLocal8Bit(qgetenv("COMSPEC"));
- const QStringList args; // none
-#elif defined(Q_OS_MAC)
- const QString terminalEmulator = Core::ICore::resourcePath()
- + QLatin1String("/scripts/openTerminal.command");
+ QString terminalEmulator;
QStringList args;
-#else
- QStringList args = Utils::QtcProcess::splitArgs(
- Utils::ConsoleProcess::terminalEmulator(Core::ICore::settings()));
- const QString terminalEmulator = args.takeFirst();
- const QString shell = QString::fromLocal8Bit(qgetenv("SHELL"));
- args.append(shell);
-#endif
+ if (HostOsInfo::isWindowsHost()) {
+ terminalEmulator = ConsoleProcess::defaultTerminalEmulator();
+ } else if (HostOsInfo::isMacHost()) {
+ terminalEmulator = ICore::resourcePath()
+ + QLatin1String("/scripts/openTerminal.command");
+ } else {
+ args = QtcProcess::splitArgs(ConsoleProcess::terminalEmulator(ICore::settings()));
+ terminalEmulator = args.takeFirst();
+ args.append(QString::fromLocal8Bit(qgetenv("SHELL")));
+ }
+
// Launch terminal with working directory set.
const QFileInfo fileInfo(path);
const QString pwd = QDir::toNativeSeparators(fileInfo.isDir() ?
@@ -153,22 +148,18 @@ void FileUtils::openTerminal(const QString &path)
QString FileUtils::msgGraphicalShellAction()
{
-#if defined(Q_OS_WIN)
- return QApplication::translate("Core::Internal", "Show in Explorer");
-#elif defined(Q_OS_MAC)
- return QApplication::translate("Core::Internal", "Show in Finder");
-#else
+ if (HostOsInfo::isWindowsHost())
+ return QApplication::translate("Core::Internal", "Show in Explorer");
+ if (HostOsInfo::isMacHost())
+ return QApplication::translate("Core::Internal", "Show in Finder");
return QApplication::translate("Core::Internal", "Show Containing Folder");
-#endif
}
QString FileUtils::msgTerminalAction()
{
-#ifdef Q_OS_WIN
- return QApplication::translate("Core::Internal", "Open Command Prompt Here");
-#else
+ if (HostOsInfo::isWindowsHost())
+ return QApplication::translate("Core::Internal", "Open Command Prompt Here");
return QApplication::translate("Core::Internal", "Open Terminal Here");
-#endif
}
void FileUtils::removeFile(const QString &filePath, bool deleteFromFS)
@@ -209,10 +200,10 @@ bool FileUtils::renameFile(const QString &orgFilePath, const QString &newFilePat
return false;
QString dir = QFileInfo(orgFilePath).absolutePath();
- Core::IVersionControl *vc = Core::ICore::vcsManager()->findVersionControlForDirectory(dir);
+ IVersionControl *vc = ICore::vcsManager()->findVersionControlForDirectory(dir);
bool result = false;
- if (vc && vc->supportsOperation(Core::IVersionControl::MoveOperation))
+ if (vc && vc->supportsOperation(IVersionControl::MoveOperation))
result = vc->vcsMove(orgFilePath, newFilePath);
if (!result) // The moving via vcs failed or the vcs does not support moving, fall back
result = fileSystemRenameFile(orgFilePath, newFilePath);
@@ -222,3 +213,5 @@ bool FileUtils::renameFile(const QString &orgFilePath, const QString &newFilePat
}
return result;
}
+
+} // namespace Core
diff --git a/src/plugins/coreplugin/generalsettings.cpp b/src/plugins/coreplugin/generalsettings.cpp
index b57d37be4f..4f3d318bc4 100644
--- a/src/plugins/coreplugin/generalsettings.cpp
+++ b/src/plugins/coreplugin/generalsettings.cpp
@@ -29,13 +29,14 @@
#include "generalsettings.h"
#include "coreconstants.h"
+#include "icore.h"
+#include "infobar.h"
+#include "editormanager/editormanager.h"
#include <utils/stylehelper.h>
#include <utils/qtcolorbutton.h>
#include <utils/consoleprocess.h>
#include <utils/unixutils.h>
-#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/icore.h>
#include <QMessageBox>
@@ -54,9 +55,9 @@ using namespace Core::Internal;
GeneralSettings::GeneralSettings():
m_page(0), m_dialog(0)
{
- setId(QLatin1String(Core::Constants::SETTINGS_ID_ENVIRONMENT));
+ setId(Core::Constants::SETTINGS_ID_ENVIRONMENT);
setDisplayName(tr("General"));
- setCategory(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE));
+ setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
}
@@ -65,9 +66,8 @@ static bool hasQmFilesForLocale(const QString &locale, const QString &creatorTrP
{
static const QString qtTrPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
- const QString trFile = QLatin1String("qt_") + locale + QLatin1String(".qm");
- return QFile::exists(qtTrPath + QLatin1Char('/') + trFile)
- || QFile::exists(creatorTrPath + QLatin1Char('/') + trFile);
+ const QString trFile = QLatin1String("/qt_") + locale + QLatin1String(".qm");
+ return QFile::exists(qtTrPath + trFile) || QFile::exists(creatorTrPath + trFile);
}
void GeneralSettings::fillLanguageBox() const
@@ -137,8 +137,10 @@ QWidget *GeneralSettings::createPage(QWidget *parent)
m_page->autoSaveCheckBox->setChecked(EditorManager::instance()->autoSaveEnabled());
m_page->autoSaveInterval->setValue(EditorManager::instance()->autoSaveInterval());
- connect(m_page->resetButton, SIGNAL(clicked()),
+ connect(m_page->resetColorButton, SIGNAL(clicked()),
this, SLOT(resetInterfaceColor()));
+ connect(m_page->resetWarningsButton, SIGNAL(clicked()),
+ this, SLOT(resetWarnings()));
#ifdef Q_OS_UNIX
connect(m_page->resetTerminalButton, SIGNAL(clicked()),
this, SLOT(resetTerminal()));
@@ -202,6 +204,12 @@ void GeneralSettings::resetInterfaceColor()
m_page->colorButton->setColor(StyleHelper::DEFAULT_BASE_COLOR);
}
+void GeneralSettings::resetWarnings()
+{
+ Core::InfoBar::clearGloballySuppressed();
+ QMessageBox::information(0, tr("Reset warnings"), tr("Done"));
+}
+
void GeneralSettings::resetTerminal()
{
#if defined(Q_OS_UNIX)
diff --git a/src/plugins/coreplugin/generalsettings.h b/src/plugins/coreplugin/generalsettings.h
index a3e1696915..c812ac45af 100644
--- a/src/plugins/coreplugin/generalsettings.h
+++ b/src/plugins/coreplugin/generalsettings.h
@@ -58,6 +58,7 @@ public:
private slots:
void resetInterfaceColor();
+ void resetWarnings();
void resetLanguage();
void showHelpForFileBrowser();
void resetFileBrowser();
diff --git a/src/plugins/coreplugin/generalsettings.ui b/src/plugins/coreplugin/generalsettings.ui
index 08b42c94e0..a36954345c 100644
--- a/src/plugins/coreplugin/generalsettings.ui
+++ b/src/plugins/coreplugin/generalsettings.ui
@@ -17,13 +17,66 @@
<string>User Interface</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
- <item row="0" column="0">
- <widget class="QLabel" name="colorLabel">
+ <item row="0" column="0">
+ <widget class="QLabel" name="colorLabel">
+ <property name="text">
+ <string>Color:</string>
+ </property>
+ <property name="buddy">
+ <cstring>colorButton</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="Utils::QtColorButton" name="colorButton">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>64</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="alphaAllowed" stdset="0">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="resetColorButton">
+ <property name="toolTip">
+ <string comment="Color">Reset to default.</string>
+ </property>
+ <property name="text">
+ <string>Reset</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>285</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="languageLabel">
<property name="text">
- <string>Color:</string>
- </property>
- <property name="buddy">
- <cstring>colorButton</cstring>
+ <string>Language:</string>
</property>
</widget>
</item>
@@ -54,56 +107,10 @@
</item>
</layout>
</item>
- <item row="0" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="Utils::QtColorButton" name="colorButton">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>64</width>
- <height>0</height>
- </size>
- </property>
- <property name="alphaAllowed" stdset="0">
- <bool>false</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="resetButton">
- <property name="toolTip">
- <string comment="Color">Reset to default.</string>
- </property>
- <property name="text">
- <string>Reset</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>285</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="languageLabel">
+ <item row="3" column="0">
+ <widget class="QPushButton" name="resetWarningsButton">
<property name="text">
- <string>Language:</string>
+ <string>Reset warnings</string>
</property>
</widget>
</item>
@@ -130,6 +137,16 @@
</property>
</widget>
</item>
+ <item row="0" column="2">
+ <widget class="QPushButton" name="resetTerminalButton">
+ <property name="toolTip">
+ <string comment="Terminal">Reset to default.</string>
+ </property>
+ <property name="text">
+ <string>Reset</string>
+ </property>
+ </widget>
+ </item>
<item row="1" column="0">
<widget class="QLabel" name="externalFileBrowserLabel">
<property name="text">
@@ -140,6 +157,16 @@
<item row="1" column="1">
<widget class="QLineEdit" name="externalFileBrowserEdit"/>
</item>
+ <item row="1" column="2">
+ <widget class="QPushButton" name="resetFileBrowserButton">
+ <property name="toolTip">
+ <string comment="File Browser">Reset to default.</string>
+ </property>
+ <property name="text">
+ <string>Reset</string>
+ </property>
+ </widget>
+ </item>
<item row="1" column="3">
<widget class="QToolButton" name="helpExternalFileBrowserButton">
<property name="text">
@@ -197,26 +224,6 @@
</item>
</layout>
</item>
- <item row="0" column="2">
- <widget class="QPushButton" name="resetTerminalButton">
- <property name="toolTip">
- <string comment="Terminal">Reset to default.</string>
- </property>
- <property name="text">
- <string>Reset</string>
- </property>
- </widget>
- </item>
- <item row="1" column="2">
- <widget class="QPushButton" name="resetFileBrowserButton">
- <property name="toolTip">
- <string comment="File Browser">Reset to default.</string>
- </property>
- <property name="text">
- <string>Reset</string>
- </property>
- </widget>
- </item>
<item row="3" column="0" colspan="4">
<layout class="QHBoxLayout" name="horizontalLayout_5">
<item>
@@ -305,17 +312,6 @@
<header location="global">utils/qtcolorbutton.h</header>
</customwidget>
</customwidgets>
- <tabstops>
- <tabstop>colorButton</tabstop>
- <tabstop>resetButton</tabstop>
- <tabstop>languageBox</tabstop>
- <tabstop>terminalComboBox</tabstop>
- <tabstop>resetTerminalButton</tabstop>
- <tabstop>externalFileBrowserEdit</tabstop>
- <tabstop>resetFileBrowserButton</tabstop>
- <tabstop>helpExternalFileBrowserButton</tabstop>
- <tabstop>reloadBehavior</tabstop>
- </tabstops>
<resources>
<include location="core.qrc"/>
</resources>
diff --git a/src/plugins/coreplugin/icontext.cpp b/src/plugins/coreplugin/icontext.cpp
index 152503edbe..3883d166dd 100644
--- a/src/plugins/coreplugin/icontext.cpp
+++ b/src/plugins/coreplugin/icontext.cpp
@@ -28,26 +28,3 @@
****************************************************************************/
#include "icontext.h"
-
-#include "id.h"
-
-#include <QString>
-
-namespace Core {
-
-Context::Context(const char *id, int offset)
-{
- d.append(Id(QLatin1String(id) + QString::number(offset)).uniqueIdentifier());
-}
-
-void Context::add(const char *id)
-{
- d.append(Id(id).uniqueIdentifier());
-}
-
-bool Context::contains(const char *id) const
-{
- return d.contains(Id(id).uniqueIdentifier());
-}
-
-} // namespace Core
diff --git a/src/plugins/coreplugin/icontext.h b/src/plugins/coreplugin/icontext.h
index a7d68cdd72..65206bf082 100644
--- a/src/plugins/coreplugin/icontext.h
+++ b/src/plugins/coreplugin/icontext.h
@@ -31,6 +31,7 @@
#define ICONTEXT_H
#include <coreplugin/core_global.h>
+#include <coreplugin/id.h>
#include <QList>
#include <QObject>
@@ -44,30 +45,27 @@ class CORE_EXPORT Context
public:
Context() {}
- explicit Context(const char *c1) { add(c1); }
- Context(const char *c1, const char *c2) { add(c1); add(c2); }
- Context(const char *c1, const char *c2, const char *c3) { add(c1); add(c2); add(c3); }
- Context(const char *base, int offset);
- void add(const char *c);
- bool contains(const char *c) const;
- bool contains(int c) const { return d.contains(c); }
+ explicit Context(Id c1) { add(c1); }
+ Context(Id c1, Id c2) { add(c1); add(c2); }
+ Context(Id c1, Id c2, Id c3) { add(c1); add(c2); add(c3); }
+ bool contains(Id c) const { return d.contains(c); }
int size() const { return d.size(); }
bool isEmpty() const { return d.isEmpty(); }
- int at(int i) const { return d.at(i); }
+ Id at(int i) const { return d.at(i); }
// FIXME: Make interface slimmer.
- typedef QList<int>::const_iterator const_iterator;
+ typedef QList<Id>::const_iterator const_iterator;
const_iterator begin() const { return d.begin(); }
const_iterator end() const { return d.end(); }
- int indexOf(int c) const { return d.indexOf(c); }
+ int indexOf(Id c) const { return d.indexOf(c); }
void removeAt(int i) { d.removeAt(i); }
- void prepend(int c) { d.prepend(c); }
+ void prepend(Id c) { d.prepend(c); }
void add(const Context &c) { d += c.d; }
- void add(int c) { d.append(c); }
+ void add(Id c) { d.append(c); }
bool operator==(const Context &c) const { return d == c.d; }
private:
- QList<int> d;
+ QList<Id> d;
};
class CORE_EXPORT IContext : public QObject
diff --git a/src/plugins/coreplugin/icore.cpp b/src/plugins/coreplugin/icore.cpp
index 329e1a6c1b..fc9f1537a4 100644
--- a/src/plugins/coreplugin/icore.cpp
+++ b/src/plugins/coreplugin/icore.cpp
@@ -393,15 +393,15 @@ void ICore::showNewItemDialog(const QString &title,
m_mainwindow->showNewItemDialog(title, wizards, defaultLocation, extraVariables);
}
-bool ICore::showOptionsDialog(const QString &group, const QString &page, QWidget *parent)
+bool ICore::showOptionsDialog(const Id group, const Id page, QWidget *parent)
{
return m_mainwindow->showOptionsDialog(group, page, parent);
}
bool ICore::showWarningWithOptions(const QString &title, const QString &text,
const QString &details,
- const QString &settingsCategory,
- const QString &settingsId,
+ Id settingsCategory,
+ Id settingsId,
QWidget *parent)
{
return m_mainwindow->showWarningWithOptions(title, text,
@@ -532,11 +532,6 @@ void ICore::updateAdditionalContexts(const Context &remove, const Context &add)
m_mainwindow->updateAdditionalContexts(remove, add);
}
-bool ICore::hasContext(int context)
-{
- return m_mainwindow->hasContext(context);
-}
-
void ICore::addContextObject(IContext *context)
{
m_mainwindow->addContextObject(context);
diff --git a/src/plugins/coreplugin/icore.h b/src/plugins/coreplugin/icore.h
index 8554267064..d886ef025a 100644
--- a/src/plugins/coreplugin/icore.h
+++ b/src/plugins/coreplugin/icore.h
@@ -31,6 +31,7 @@
#define ICORE_H
#include "core_global.h"
+#include "id.h"
#include <QObject>
#include <QSettings>
@@ -81,14 +82,12 @@ public:
const QString &defaultLocation = QString(),
const QVariantMap &extraVariables = QVariantMap());
- static bool showOptionsDialog(const QString &group = QString(),
- const QString &page = QString(),
- QWidget *parent = 0);
+ static bool showOptionsDialog(Id group, Id page, QWidget *parent = 0);
static bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
- const QString &settingsCategory = QString(),
- const QString &settingsId = QString(),
+ Id settingsCategory = Id(),
+ Id settingsId = Id(),
QWidget *parent = 0);
static QT_DEPRECATED ActionManager *actionManager(); // Use Actionmanager::... directly.
@@ -118,7 +117,6 @@ public:
// Adds and removes additional active contexts, these contexts are appended
// to the currently active contexts.
static void updateAdditionalContexts(const Context &remove, const Context &add);
- static bool hasContext(int context);
static void addContextObject(IContext *context);
static void removeContextObject(IContext *context);
diff --git a/src/plugins/coreplugin/id.cpp b/src/plugins/coreplugin/id.cpp
index 9dc93e9665..4fac923891 100644
--- a/src/plugins/coreplugin/id.cpp
+++ b/src/plugins/coreplugin/id.cpp
@@ -43,22 +43,39 @@ namespace Core {
/*!
\class Core::Id
- \brief The class Id encapsulates an identifier. It is used as a type-safe
- helper class instead of a \c QString or \c QByteArray. The internal
- representation of the id is assumed to be plain 7-bit-clean ASCII.
+ \brief The class Id encapsulates an identifier that is unique
+ within a specific running Qt Creator process.
+
+ \c{Core::Id} is used as facility to identify objects of interest
+ in a more typesafe and faster manner than a plain \c QString or
+ \c QByteArray would provide.
+
+ An id is internally represented as a 32 bit integer (its \c UID)
+ and associated with a be plain 7-bit-clean ASCII name used
+ for display and persistency.
+
+ Each plugin that is distributed as part of Qt Creator has a
+ private range of 10000 UIDs that are guaranteed to be unique.
+
+ Third party plugins are advised to construct ids from their
+ string representation.
*/
class StringHolder
{
public:
- explicit StringHolder(const char *s)
- : str(s)
+ StringHolder()
+ : n(0), str(0)
+ {}
+
+ StringHolder(const char *s, int length)
+ : n(length), str(s)
{
- n = strlen(s);
- int m = n;
+ if (!n)
+ length = n = strlen(s);
h = 0;
- while (m--) {
+ while (length--) {
h = (h << 4) + *s++;
h ^= (h & 0xf0000000) >> 23;
h &= 0x0fffffff;
@@ -72,7 +89,7 @@ public:
static bool operator==(const StringHolder &sh1, const StringHolder &sh2)
{
// sh.n is unlikely to discriminate better than the hash.
- return sh1.h == sh2.h && strcmp(sh1.str, sh1.str) == 0;
+ return sh1.h == sh2.h && sh1.str && sh2.str && strcmp(sh1.str, sh2.str) == 0;
}
@@ -93,53 +110,228 @@ struct IdCache : public QHash<StringHolder, int>
};
-static int lastUid = 0;
-static QVector<QByteArray> stringFromId;
+static int firstUnusedId = Id::IdsPerPlugin * Id::ReservedPlugins;
+
+static QHash<int, StringHolder> stringFromId;
static IdCache idFromString;
-static int theId(const char *str)
+static int theId(const char *str, int n = 0)
{
QTC_ASSERT(str && *str, return 0);
- StringHolder sh(str);
+ StringHolder sh(str, n);
int res = idFromString.value(sh, 0);
if (res == 0) {
- if (lastUid == 0)
- stringFromId.append(QByteArray());
- res = ++lastUid;
+ res = firstUnusedId++;
sh.str = qstrdup(sh.str);
idFromString[sh] = res;
- stringFromId.append(QByteArray::fromRawData(sh.str, sh.n));
+ stringFromId[res] = sh;
}
return res;
}
+static int theId(const QByteArray &ba)
+{
+ return theId(ba.constData(), ba.size());
+}
+
+/*!
+ \fn Core::Id(int uid)
+
+ \brief Constructs an id given a UID.
+
+ The UID is an integer value that is unique within the running
+ Qt Creator process.
+
+ It is the callers responsibility to ensure the uniqueness of
+ the passed integer. The recommended approach is to use
+ \c{registerId()} with an value taken from the plugin's
+ private range.
+
+ \sa registerId()
+
+*/
+
+/*!
+ Constructs an id given its associated name. The internal
+ representation will be unspecified, but consistent within a
+ Qt Creator process.
+
+*/
Id::Id(const char *name)
- : m_id(theId(name))
+ : m_id(theId(name, 0))
+{}
+
+/*!
+ \overload
+
+*/
+Id::Id(const QByteArray &name)
+ : m_id(theId(name))
{}
+/*!
+ \overload
+ \deprecated
+*/
Id::Id(const QString &name)
: m_id(theId(name.toUtf8()))
{}
+/*!
+ Returns an internal representation of the id.
+*/
+
QByteArray Id::name() const
{
- return stringFromId.at(m_id);
+ return stringFromId.value(m_id).str;
}
+/*!
+ Returns a string representation of the id suitable
+ for UI display.
+
+ This should not be used to create a persistent version
+ of the Id, use \c{toSetting()} instead.
+
+ \sa fromString(), toSetting()
+*/
+
QString Id::toString() const
{
- return QString::fromUtf8(stringFromId.at(m_id));
+ return QString::fromUtf8(stringFromId.value(m_id).str);
+}
+
+/*!
+ Creates an id from a string representation.
+
+ This should not be used to handle a persistent version
+ of the Id, use \c{fromSetting()} instead.
+
+ \deprecated
+
+ \sa toString(), fromSetting()
+*/
+
+Id Id::fromString(const QString &name)
+{
+ return Id(theId(name.toUtf8()));
+}
+
+/*!
+ Creates an id from a string representation.
+
+ This should not be used to handle a persistent version
+ of the Id, use \c{fromSetting()} instead.
+
+ \deprecated
+
+ \sa toString(), fromSetting()
+*/
+
+Id Id::fromName(const QByteArray &name)
+{
+ return Id(theId(name));
+}
+
+/*!
+ Returns a persistent value representing the id which is
+ suitable to be stored in QSettings.
+
+ \sa fromSetting()
+*/
+
+QVariant Id::toSetting() const
+{
+ return QVariant(QString::fromUtf8(stringFromId.value(m_id).str));
+}
+
+/*!
+ Reconstructs an id from a persistent value.
+
+ \sa toSetting()
+*/
+
+Id Id::fromSetting(const QVariant &variant)
+{
+ const QByteArray ba = variant.toString().toUtf8();
+ if (ba.isEmpty())
+ return Id();
+ return Id(theId(ba));
+}
+
+/*!
+ Constructs a derived id.
+
+ This can be used to construct groups of ids logically
+ belonging together. The associated internal name
+ will be generated by appending \c{suffix}.
+*/
+
+Id Id::withSuffix(int suffix) const
+{
+ const QByteArray ba = name() + QByteArray::number(suffix);
+ return Id(ba.constData());
+}
+
+/*!
+ \overload
+*/
+
+Id Id::withSuffix(const char *suffix) const
+{
+ const QByteArray ba = name() + suffix;
+ return Id(ba.constData());
+}
+
+/*!
+ Constructs a derived id.
+
+ This can be used to construct groups of ids logically
+ belonging together. The associated internal name
+ will be generated by prepending \c{prefix}.
+*/
+
+Id Id::withPrefix(const char *prefix) const
+{
+ const QByteArray ba = prefix + name();
+ return Id(ba.constData());
+}
+
+
+/*!
+ Associates a id with its uid and its string
+ representation.
+
+ The uid should be taken from the plugin's private range.
+
+ \sa fromSetting()
+*/
+
+void Id::registerId(int uid, const char *name)
+{
+ StringHolder sh(name, 0);
+ idFromString[sh] = uid;
+ stringFromId[uid] = sh;
}
bool Id::operator==(const char *name) const
{
- return strcmp(stringFromId.at(m_id).constData(), name) == 0;
+ const char *string = stringFromId.value(m_id).str;
+ if (string && name)
+ return strcmp(string, name) == 0;
+ else
+ return false;
}
// For debugging purposes
CORE_EXPORT const char *nameForId(int id)
{
- return (stringFromId.constData() + id)->constData();
+ return stringFromId.value(id).str;
+}
+
+bool Id::alphabeticallyBefore(Id other) const
+{
+ return toString().compare(other.toString(), Qt::CaseInsensitive) < 0;
}
} // namespace Core
diff --git a/src/plugins/coreplugin/id.h b/src/plugins/coreplugin/id.h
index 0185c0cf04..ca23c7f437 100644
--- a/src/plugins/coreplugin/id.h
+++ b/src/plugins/coreplugin/id.h
@@ -34,6 +34,7 @@
#include <QMetaType>
#include <QString>
+#include <QVariant>
namespace Core {
@@ -41,12 +42,21 @@ namespace Core {
class CORE_EXPORT Id
{
public:
+ enum { IdsPerPlugin = 10000, ReservedPlugins = 1000 };
+
Id() : m_id(0) {}
+ Id(int uid) : m_id(uid) {}
Id(const char *name);
- // FIXME: Replace with QByteArray
explicit Id(const QString &name);
+ explicit Id(const QByteArray &name);
+
+ Id withSuffix(int suffix) const;
+ Id withSuffix(const char *name) const;
+ Id withPrefix(const char *name) const;
+
QByteArray name() const;
- QString toString() const;
+ QString toString() const; // Avoid.
+ QVariant toSetting() const; // Good to use.
bool isValid() const { return m_id; }
bool operator==(Id id) const { return m_id == id.m_id; }
bool operator==(const char *name) const;
@@ -54,11 +64,15 @@ public:
bool operator!=(const char *name) const { return !operator==(name); }
bool operator<(Id id) const { return m_id < id.m_id; }
bool operator>(Id id) const { return m_id > id.m_id; }
+ bool alphabeticallyBefore(Id other) const;
int uniqueIdentifier() const { return m_id; }
- static Id fromUniqueIdentifier(int uid) { return Id(uid, uid); }
+ static Id fromUniqueIdentifier(int uid) { return Id(uid); }
+ static Id fromString(const QString &str); // FIXME: avoid.
+ static Id fromName(const QByteArray &ba); // FIXME: avoid.
+ static Id fromSetting(const QVariant &variant); // Good to use.
+ static void registerId(int uid, const char *name);
private:
- Id(int uid, int) : m_id(uid) {}
// Intentionally unimplemented
Id(const QLatin1String &);
int m_id;
diff --git a/src/plugins/coreplugin/idocument.cpp b/src/plugins/coreplugin/idocument.cpp
index 4c3b7dda78..01ec58af3e 100644
--- a/src/plugins/coreplugin/idocument.cpp
+++ b/src/plugins/coreplugin/idocument.cpp
@@ -85,7 +85,7 @@ void IDocument::setRestoredFrom(const QString &name)
{
m_autoSaveName = name;
m_restored = true;
- InfoBarEntry info(QLatin1String(kRestoredAutoSave),
+ InfoBarEntry info(Id(kRestoredAutoSave),
tr("File was restored from auto-saved copy. "
"Select Save to confirm or Revert to Saved to discard changes."));
infoBar()->addInfo(info);
@@ -98,7 +98,7 @@ void IDocument::removeAutoSaveFile()
m_autoSaveName.clear();
if (m_restored) {
m_restored = false;
- infoBar()->removeInfo(QLatin1String(kRestoredAutoSave));
+ infoBar()->removeInfo(Id(kRestoredAutoSave));
}
}
}
diff --git a/src/plugins/coreplugin/images/logo/logo.qbs b/src/plugins/coreplugin/images/logo/logo.qbs
index 71737dcffc..c0c401a88b 100644
--- a/src/plugins/coreplugin/images/logo/logo.qbs
+++ b/src/plugins/coreplugin/images/logo/logo.qbs
@@ -2,54 +2,53 @@ import qbs.base 1.0
Product {
condition: qbs.targetOS == "linux"
- type: ["installed_content"]
name: "LogoImages"
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/16x16/apps"
- fileTags: ["install"]
files: ["16/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/24x24/apps"
- fileTags: ["install"]
files: ["24/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/32x32/apps"
- fileTags: ["install"]
files: ["32/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/48x48/apps"
- fileTags: ["install"]
files: ["48/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/64x64/apps"
- fileTags: ["install"]
files: ["64/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/128x128/apps"
- fileTags: ["install"]
files: ["128/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/256x256/apps"
- fileTags: ["install"]
files: ["256/QtProject-qtcreator.png"]
}
Group {
+ qbs.install: true
qbs.installDir: "share/icons/hicolor/512x512/apps"
- fileTags: ["install"]
files: ["512/QtProject-qtcreator.png"]
}
}
diff --git a/src/plugins/coreplugin/inavigationwidgetfactory.h b/src/plugins/coreplugin/inavigationwidgetfactory.h
index 3292852aae..1f6430ecc5 100644
--- a/src/plugins/coreplugin/inavigationwidgetfactory.h
+++ b/src/plugins/coreplugin/inavigationwidgetfactory.h
@@ -30,7 +30,7 @@
#ifndef INAVIGATIONWIDGET_H
#define INAVIGATIONWIDGET_H
-#include <coreplugin/id.h>
+#include "id.h"
#include <QObject>
#include <QList>
diff --git a/src/plugins/coreplugin/infobar.cpp b/src/plugins/coreplugin/infobar.cpp
index 93c1a08f58..5c028da9ea 100644
--- a/src/plugins/coreplugin/infobar.cpp
+++ b/src/plugins/coreplugin/infobar.cpp
@@ -29,24 +29,30 @@
#include "infobar.h"
-#include <coreplugin/coreconstants.h>
+#include "coreconstants.h"
+#include "icore.h"
#include <QFrame>
#include <QHBoxLayout>
#include <QLabel>
+#include <QSettings>
#include <QToolButton>
-
#include <QVariant>
+static const char C_SUPPRESSED_WARNINGS[] = "SuppressedWarnings";
+
namespace Core {
-InfoBarEntry::InfoBarEntry(const QString &_id, const QString &_infoText)
+QSet<Id> InfoBar::globallySuppressed;
+
+InfoBarEntry::InfoBarEntry(Id _id, const QString &_infoText, GlobalSuppressionMode _globalSuppression)
: id(_id)
, infoText(_infoText)
, object(0)
, buttonPressMember(0)
, cancelObject(0)
, cancelButtonPressMember(0)
+ , globalSuppression(_globalSuppression)
{
}
@@ -77,7 +83,7 @@ void InfoBar::addInfo(const InfoBarEntry &info)
emit changed();
}
-void InfoBar::removeInfo(const QString &id)
+void InfoBar::removeInfo(Id id)
{
QMutableListIterator<InfoBarEntry> it(m_infoBarEntries);
while (it.hasNext())
@@ -88,7 +94,7 @@ void InfoBar::removeInfo(const QString &id)
}
}
-bool InfoBar::containsInfo(const QString &id) const
+bool InfoBar::containsInfo(Id id) const
{
QListIterator<InfoBarEntry> it(m_infoBarEntries);
while (it.hasNext())
@@ -98,6 +104,24 @@ bool InfoBar::containsInfo(const QString &id) const
return false;
}
+// Remove and suppress id
+void InfoBar::suppressInfo(Id id)
+{
+ removeInfo(id);
+ m_suppressed << id;
+}
+
+// Info can not be added more than once, or if it is suppressed
+bool InfoBar::canInfoBeAdded(Id id) const
+{
+ return !containsInfo(id) && !m_suppressed.contains(id) && !globallySuppressed.contains(id);
+}
+
+void InfoBar::enableInfo(Id id)
+{
+ m_suppressed.remove(id);
+}
+
void InfoBar::clear()
{
if (!m_infoBarEntries.isEmpty()) {
@@ -106,6 +130,28 @@ void InfoBar::clear()
}
}
+void InfoBar::globallySuppressInfo(Id id)
+{
+ globallySuppressed.insert(id);
+ QStringList list;
+ foreach (Id i, globallySuppressed)
+ list << QLatin1String(i.name());
+ ICore::settings()->setValue(QLatin1String(C_SUPPRESSED_WARNINGS), list);
+}
+
+void InfoBar::initializeGloballySuppressed()
+{
+ QStringList list = ICore::settings()->value(QLatin1String(C_SUPPRESSED_WARNINGS)).toStringList();
+ foreach (const QString &id, list)
+ globallySuppressed.insert(Id::fromString(id));
+}
+
+void InfoBar::clearGloballySuppressed()
+{
+ globallySuppressed.clear();
+ ICore::settings()->setValue(QLatin1String(C_SUPPRESSED_WARNINGS), QStringList());
+}
+
InfoBarDisplay::InfoBarDisplay(QObject *parent)
: QObject(parent)
@@ -182,8 +228,16 @@ void InfoBarDisplay::update()
hbox->addWidget(infoWidgetButton);
}
+ QToolButton *infoWidgetSuppressButton = 0;
+ if (info.globalSuppression == InfoBarEntry::GlobalSuppressionEnabled) {
+ infoWidgetSuppressButton = new QToolButton;
+ infoWidgetSuppressButton->setProperty("infoId", info.id.uniqueIdentifier());
+ infoWidgetSuppressButton->setText(tr("Do not show again"));
+ connect(infoWidgetSuppressButton, SIGNAL(clicked()), SLOT(suppressButtonClicked()));
+ }
+
QToolButton *infoWidgetCloseButton = new QToolButton;
- infoWidgetCloseButton->setProperty("infoId", info.id);
+ infoWidgetCloseButton->setProperty("infoId", info.id.uniqueIdentifier());
// need to connect to cancelObjectbefore connecting to cancelButtonClicked,
// because the latter removes the button and with it any connect
@@ -196,12 +250,16 @@ void InfoBarDisplay::update()
infoWidgetCloseButton->setAutoRaise(true);
infoWidgetCloseButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_CLEAR)));
infoWidgetCloseButton->setToolTip(tr("Close"));
+ if (infoWidgetSuppressButton)
+ hbox->addWidget(infoWidgetSuppressButton);
+ hbox->addWidget(infoWidgetCloseButton);
} else {
infoWidgetCloseButton->setText(info.cancelButtonText);
+ hbox->addWidget(infoWidgetCloseButton);
+ if (infoWidgetSuppressButton)
+ hbox->addWidget(infoWidgetSuppressButton);
}
- hbox->addWidget(infoWidgetCloseButton);
-
connect(infoWidget, SIGNAL(destroyed()), SLOT(widgetDestroyed()));
m_boxLayout->insertWidget(m_boxIndex, infoWidget);
m_infoWidgets << infoWidget;
@@ -210,13 +268,19 @@ void InfoBarDisplay::update()
void InfoBarDisplay::widgetDestroyed()
{
- // This means that the parent is being deleted
- m_infoWidgets.clear();
+ m_infoWidgets.removeOne(static_cast<QWidget *>(sender()));
}
void InfoBarDisplay::cancelButtonClicked()
{
- m_infoBar->removeInfo(sender()->property("infoId").toString());
+ m_infoBar->suppressInfo(Id::fromUniqueIdentifier(sender()->property("infoId").toInt()));
+}
+
+void InfoBarDisplay::suppressButtonClicked()
+{
+ Id id = Id::fromUniqueIdentifier(sender()->property("infoId").toInt());
+ m_infoBar->removeInfo(id);
+ InfoBar::globallySuppressInfo(id);
}
} // namespace Core
diff --git a/src/plugins/coreplugin/infobar.h b/src/plugins/coreplugin/infobar.h
index bcc71ebc02..cd1043529d 100644
--- a/src/plugins/coreplugin/infobar.h
+++ b/src/plugins/coreplugin/infobar.h
@@ -31,8 +31,10 @@
#define INFOBAR_H
#include "core_global.h"
+#include <coreplugin/id.h>
#include <QObject>
+#include <QSet>
QT_BEGIN_NAMESPACE
class QBoxLayout;
@@ -46,14 +48,20 @@ class InfoBarDisplay;
class CORE_EXPORT InfoBarEntry
{
public:
- InfoBarEntry(const QString &_id, const QString &_infoText);
+ enum GlobalSuppressionMode
+ {
+ GlobalSuppressionDisabled,
+ GlobalSuppressionEnabled
+ };
+
+ InfoBarEntry(Id _id, const QString &_infoText, GlobalSuppressionMode _globalSuppression = GlobalSuppressionDisabled);
InfoBarEntry(const InfoBarEntry &other) { *this = other; }
void setCustomButtonInfo(const QString &_buttonText, QObject *_object, const char *_member);
void setCancelButtonInfo(QObject *_object, const char *_member);
void setCancelButtonInfo(const QString &_cancelButtonText, QObject *_object, const char *_member);
private:
- QString id;
+ Id id;
QString infoText;
QString buttonText;
QObject *object;
@@ -61,6 +69,7 @@ private:
QString cancelButtonText;
QObject *cancelObject;
const char *cancelButtonPressMember;
+ GlobalSuppressionMode globalSuppression;
friend class InfoBar;
friend class InfoBarDisplay;
};
@@ -71,15 +80,23 @@ class CORE_EXPORT InfoBar : public QObject
public:
void addInfo(const InfoBarEntry &info);
- void removeInfo(const QString &id);
- bool containsInfo(const QString &id) const;
+ void removeInfo(Id id);
+ bool containsInfo(Id id) const;
+ void suppressInfo(Id id);
+ bool canInfoBeAdded(Id id) const;
+ void enableInfo(Id id);
void clear();
+ static void globallySuppressInfo(Id id);
+ static void initializeGloballySuppressed();
+ static void clearGloballySuppressed();
signals:
void changed();
private:
QList<InfoBarEntry> m_infoBarEntries;
+ QSet<Id> m_suppressed;
+ static QSet<Id> globallySuppressed;
friend class InfoBarDisplay;
};
@@ -94,6 +111,7 @@ public:
private slots:
void cancelButtonClicked();
+ void suppressButtonClicked();
void update();
void infoBarDestroyed();
void widgetDestroyed();
diff --git a/src/plugins/coreplugin/iversioncontrol.cpp b/src/plugins/coreplugin/iversioncontrol.cpp
index 170df09053..cfa3033272 100644
--- a/src/plugins/coreplugin/iversioncontrol.cpp
+++ b/src/plugins/coreplugin/iversioncontrol.cpp
@@ -41,4 +41,9 @@ QString IVersionControl::vcsMakeWritableText() const
return QString();
}
+QString IVersionControl::vcsTopic(const QString &)
+{
+ return QString();
+}
+
}
diff --git a/src/plugins/coreplugin/iversioncontrol.h b/src/plugins/coreplugin/iversioncontrol.h
index 9fa86b1b56..acee0f9cb1 100644
--- a/src/plugins/coreplugin/iversioncontrol.h
+++ b/src/plugins/coreplugin/iversioncontrol.h
@@ -137,6 +137,11 @@ public:
virtual QString vcsGetRepositoryURL(const QString &director) = 0;
/*!
+ * Topic (e.g. name of the current branch)
+ */
+ virtual QString vcsTopic(const QString &directory);
+
+ /*!
* Create a snapshot of the current state and return an identifier or
* an empty string in case of failure.
*/
diff --git a/src/plugins/coreplugin/mainwindow.cpp b/src/plugins/coreplugin/mainwindow.cpp
index 7ee1416bca..05160a942c 100644
--- a/src/plugins/coreplugin/mainwindow.cpp
+++ b/src/plugins/coreplugin/mainwindow.cpp
@@ -82,6 +82,7 @@
#include <coreplugin/inavigationwidgetfactory.h>
#include <coreplugin/settingsdatabase.h>
#include <utils/historycompleter.h>
+#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <utils/stylehelper.h>
#include <utils/stringutils.h>
@@ -179,28 +180,27 @@ MainWindow::MainWindow() :
Utils::HistoryCompleter::setSettings(m_settings);
setWindowTitle(tr("Qt Creator"));
-#ifndef Q_OS_MAC
- QApplication::setWindowIcon(QIcon(QLatin1String(Constants::ICON_QTLOGO_128)));
-#endif
+ if (!Utils::HostOsInfo::isMacHost())
+ QApplication::setWindowIcon(QIcon(QLatin1String(Constants::ICON_QTLOGO_128)));
QCoreApplication::setApplicationName(QLatin1String("QtCreator"));
QCoreApplication::setApplicationVersion(QLatin1String(Core::Constants::IDE_VERSION_LONG));
QCoreApplication::setOrganizationName(QLatin1String(Constants::IDE_SETTINGSVARIANT_STR));
QString baseName = QApplication::style()->objectName();
-#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
- if (baseName == QLatin1String("windows")) {
- // Sometimes we get the standard windows 95 style as a fallback
- if (QStyleFactory::keys().contains("Fusion"))
- baseName = QLatin1String("fusion"); // Qt5
- else { // Qt4
- // e.g. if we are running on a KDE4 desktop
- QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
- if (desktopEnvironment == "kde")
- baseName = QLatin1String("plastique");
- else
- baseName = QLatin1String("cleanlooks");
+ if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost()) {
+ if (baseName == QLatin1String("windows")) {
+ // Sometimes we get the standard windows 95 style as a fallback
+ if (QStyleFactory::keys().contains(QLatin1String("Fusion")))
+ baseName = QLatin1String("fusion"); // Qt5
+ else { // Qt4
+ // e.g. if we are running on a KDE4 desktop
+ QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
+ if (desktopEnvironment == "kde")
+ baseName = QLatin1String("plastique");
+ else
+ baseName = QLatin1String("cleanlooks");
+ }
}
}
-#endif
qApp->setStyle(new ManhattanStyle(baseName));
setDockNestingEnabled(true);
@@ -430,11 +430,10 @@ static bool isDesktopFileManagerDrop(const QMimeData *d, QStringList *files = 0)
const QString fileName = it->toLocalFile();
if (!fileName.isEmpty()) {
hasFiles = true;
- if (files) {
+ if (files)
files->push_back(fileName);
- } else {
+ else
break; // No result list, sufficient for checking
- }
}
}
return hasFiles;
@@ -442,11 +441,10 @@ static bool isDesktopFileManagerDrop(const QMimeData *d, QStringList *files = 0)
void MainWindow::dragEnterEvent(QDragEnterEvent *event)
{
- if (isDesktopFileManagerDrop(event->mimeData()) && m_filesToOpenDelayed.isEmpty()) {
+ if (isDesktopFileManagerDrop(event->mimeData()) && m_filesToOpenDelayed.isEmpty())
event->accept();
- } else {
+ else
event->ignore();
- }
}
void MainWindow::dropEvent(QDropEvent *event)
@@ -485,9 +483,8 @@ void MainWindow::registerDefaultContainers()
{
ActionContainer *menubar = ActionManager::createMenuBar(Constants::MENU_BAR);
-#ifndef Q_OS_MAC // System menu bar on Mac
- setMenuBar(menubar->menuBar());
-#endif
+ if (!Utils::HostOsInfo::isMacHost()) // System menu bar on Mac
+ setMenuBar(menubar->menuBar());
menubar->appendGroup(Constants::G_FILE);
menubar->appendGroup(Constants::G_EDIT);
menubar->appendGroup(Constants::G_VIEW);
@@ -745,19 +742,18 @@ void MainWindow::registerDefaultActions()
mwindow->addAction(cmd, Constants::G_WINDOW_VIEWS);
m_toggleSideBarAction->setEnabled(false);
+
#if defined(Q_OS_MAC)
- bool fullScreenCheckable = false;
const QString fullScreenActionText(tr("Enter Full Screen"));
bool supportsFullScreen = MacFullScreen::supportsFullScreen();
#else
- bool fullScreenCheckable = true;
const QString fullScreenActionText(tr("Full Screen"));
bool supportsFullScreen = true;
#endif
if (supportsFullScreen) {
// Full Screen Action
m_toggleFullScreenAction = new QAction(fullScreenActionText, this);
- m_toggleFullScreenAction->setCheckable(fullScreenCheckable);
+ m_toggleFullScreenAction->setCheckable(!Utils::HostOsInfo::isMacHost());
cmd = ActionManager::registerAction(m_toggleFullScreenAction, Constants::TOGGLE_FULLSCREEN, globalContext);
cmd->setDefaultKeySequence(QKeySequence(UseMacShortcuts ? tr("Ctrl+Meta+F") : tr("Ctrl+Shift+F11")));
cmd->setAttribute(Command::CA_UpdateText); /* for Mac */
@@ -772,17 +768,15 @@ void MainWindow::registerDefaultActions()
// About IDE Action
icon = QIcon::fromTheme(QLatin1String("help-about"));
-#ifdef Q_OS_MAC
- tmpaction = new QAction(icon, tr("About &Qt Creator"), this); // it's convention not to add dots to the about menu
-#else
- tmpaction = new QAction(icon, tr("About &Qt Creator..."), this);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ tmpaction = new QAction(icon, tr("About &Qt Creator"), this); // it's convention not to add dots to the about menu
+ else
+ tmpaction = new QAction(icon, tr("About &Qt Creator..."), this);
cmd = ActionManager::registerAction(tmpaction, Constants::ABOUT_QTCREATOR, globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
-#ifdef Q_OS_MAC
- cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutQtCreator()));
//About Plugins Action
@@ -790,9 +784,8 @@ void MainWindow::registerDefaultActions()
cmd = ActionManager::registerAction(tmpaction, Constants::ABOUT_PLUGINS, globalContext);
mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
tmpaction->setEnabled(true);
-#ifdef Q_OS_MAC
- cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ cmd->action()->setMenuRole(QAction::ApplicationSpecificRole);
connect(tmpaction, SIGNAL(triggered()), this, SLOT(aboutPlugins()));
// About Qt Action
// tmpaction = new QAction(tr("About &Qt..."), this);
@@ -801,12 +794,12 @@ void MainWindow::registerDefaultActions()
// tmpaction->setEnabled(true);
// connect(tmpaction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
// About sep
-#ifndef Q_OS_MAC // doesn't have the "About" actions in the Help menu
- tmpaction = new QAction(this);
- tmpaction->setSeparator(true);
- cmd = ActionManager::registerAction(tmpaction, "QtCreator.Help.Sep.About", globalContext);
- mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
-#endif
+ if (!Utils::HostOsInfo::isMacHost()) { // doesn't have the "About" actions in the Help menu
+ tmpaction = new QAction(this);
+ tmpaction->setSeparator(true);
+ cmd = ActionManager::registerAction(tmpaction, "QtCreator.Help.Sep.About", globalContext);
+ mhelp->addAction(cmd, Constants::G_HELP_ABOUT);
+ }
}
void MainWindow::newFile()
@@ -965,9 +958,7 @@ void MainWindow::showNewItemDialog(const QString &title,
wizard->runWizard(path, this, selectedPlatform, extraVariables);
}
-bool MainWindow::showOptionsDialog(const QString &category,
- const QString &page,
- QWidget *parent)
+bool MainWindow::showOptionsDialog(Id category, Id page, QWidget *parent)
{
emit m_coreImpl->optionsDialogRequested();
if (!parent)
@@ -999,11 +990,10 @@ void MainWindow::openFileWith()
const Id editorId = editorManager()->getOpenWithEditorId(fileName, &isExternal);
if (!editorId.isValid())
continue;
- if (isExternal) {
+ if (isExternal)
EditorManager::openExternalEditor(fileName, editorId);
- } else {
+ else
EditorManager::openEditor(fileName, editorId, Core::EditorManager::ModeSwitch);
- }
}
}
@@ -1127,9 +1117,8 @@ void MainWindow::updateFocusWidget(QWidget *old, QWidget *now)
return;
IContext *newContext = 0;
- if (focusWidget()) {
+ if (QWidget *p = qApp->focusWidget()) {
IContext *context = 0;
- QWidget *p = focusWidget();
while (p) {
context = m_contextWidgets.value(p);
if (context) {
@@ -1186,9 +1175,8 @@ void MainWindow::readSettings()
QColor(Utils::StyleHelper::DEFAULT_BASE_COLOR)).value<QColor>());
}
- if (!restoreGeometry(m_settings->value(QLatin1String(windowGeometryKey)).toByteArray())) {
+ if (!restoreGeometry(m_settings->value(QLatin1String(windowGeometryKey)).toByteArray()))
resize(1008, 700); // size without window decoration
- }
restoreState(m_settings->value(QLatin1String(windowStateKey)).toByteArray());
m_settings->endGroup();
@@ -1218,31 +1206,26 @@ void MainWindow::writeSettings()
void MainWindow::updateAdditionalContexts(const Context &remove, const Context &add)
{
- foreach (const int context, remove) {
- if (context == 0)
+ foreach (const Id id, remove) {
+ if (!id.isValid())
continue;
- int index = m_additionalContexts.indexOf(context);
+ int index = m_additionalContexts.indexOf(id);
if (index != -1)
m_additionalContexts.removeAt(index);
}
- foreach (const int context, add) {
- if (context == 0)
+ foreach (const Id id, add) {
+ if (!id.isValid())
continue;
- if (!m_additionalContexts.contains(context))
- m_additionalContexts.prepend(context);
+ if (!m_additionalContexts.contains(id))
+ m_additionalContexts.prepend(id);
}
updateContext();
}
-bool MainWindow::hasContext(int context) const
-{
- return ActionManager::hasContext(context);
-}
-
void MainWindow::updateContext()
{
Context contexts;
@@ -1254,9 +1237,9 @@ void MainWindow::updateContext()
Context uniquecontexts;
for (int i = 0; i < contexts.size(); ++i) {
- const int c = contexts.at(i);
- if (!uniquecontexts.contains(c))
- uniquecontexts.add(c);
+ const Id id = contexts.at(i);
+ if (!uniquecontexts.contains(id))
+ uniquecontexts.add(id);
}
m_actionManager->d->setContext(uniquecontexts);
@@ -1354,8 +1337,8 @@ void MainWindow::setFullScreen(bool on)
bool MainWindow::showWarningWithOptions(const QString &title,
const QString &text,
const QString &details,
- const QString &settingsCategory,
- const QString &settingsId,
+ Id settingsCategory,
+ Id settingsId,
QWidget *parent)
{
if (parent == 0)
@@ -1365,11 +1348,10 @@ bool MainWindow::showWarningWithOptions(const QString &title,
if (!details.isEmpty())
msgBox.setDetailedText(details);
QAbstractButton *settingsButton = 0;
- if (!settingsId.isEmpty() || !settingsCategory.isEmpty())
+ if (settingsId.isValid() || settingsCategory.isValid())
settingsButton = msgBox.addButton(tr("Settings..."), QMessageBox::AcceptRole);
msgBox.exec();
- if (settingsButton && msgBox.clickedButton() == settingsButton) {
+ if (settingsButton && msgBox.clickedButton() == settingsButton)
return showOptionsDialog(settingsCategory, settingsId);
- }
return false;
}
diff --git a/src/plugins/coreplugin/mainwindow.h b/src/plugins/coreplugin/mainwindow.h
index ac519bfd8c..48b17eed02 100644
--- a/src/plugins/coreplugin/mainwindow.h
+++ b/src/plugins/coreplugin/mainwindow.h
@@ -115,7 +115,6 @@ public:
QStatusBar *statusBar() const;
void updateAdditionalContexts(const Context &remove, const Context &add);
- bool hasContext(int context) const;
void setSuppressNavigationWidget(bool suppress);
@@ -138,14 +137,12 @@ public slots:
const QString &defaultLocation = QString(),
const QVariantMap &extraVariables = QVariantMap());
- bool showOptionsDialog(const QString &category = QString(),
- const QString &page = QString(),
- QWidget *parent = 0);
+ bool showOptionsDialog(Id category = Id(), Id page = Id(), QWidget *parent = 0);
bool showWarningWithOptions(const QString &title, const QString &text,
const QString &details = QString(),
- const QString &settingsCategory = QString(),
- const QString &settingsId = QString(),
+ Id settingsCategory = Id(),
+ Id settingsId = Id(),
QWidget *parent = 0);
protected:
diff --git a/src/plugins/coreplugin/manhattanstyle.cpp b/src/plugins/coreplugin/manhattanstyle.cpp
index 8d1a1fbeba..69e6ce4888 100644
--- a/src/plugins/coreplugin/manhattanstyle.cpp
+++ b/src/plugins/coreplugin/manhattanstyle.cpp
@@ -718,7 +718,20 @@ void ManhattanStyle::drawControl(ControlElement element, const QStyleOption *opt
editRect.adjust(0, 0, -13, 0);
}
- QString text = option->fontMetrics.elidedText(cb->currentText, Qt::ElideRight, editRect.width());
+ QLatin1Char asterisk('*');
+ int elideWidth = editRect.width();
+
+ bool notElideAsterisk = widget && widget->property("notelideasterisk").toBool()
+ && cb->currentText.endsWith(asterisk)
+ && option->fontMetrics.width(cb->currentText) > elideWidth;
+
+ QString text;
+ if (notElideAsterisk) {
+ elideWidth -= option->fontMetrics.width(asterisk);
+ text = asterisk;
+ }
+ text.prepend(option->fontMetrics.elidedText(cb->currentText, Qt::ElideRight, elideWidth));
+
if ((option->state & State_Enabled)) {
painter->setPen(QColor(0, 0, 0, 70));
painter->drawText(editRect.adjusted(1, 0, -1, 0), Qt::AlignLeft | Qt::AlignVCenter, text);
@@ -852,9 +865,8 @@ void ManhattanStyle::drawComplexControl(ComplexControl control, const QStyleOpti
State bflags = toolbutton->state;
if (bflags & State_AutoRaise) {
- if (!(bflags & State_MouseOver)) {
+ if (!(bflags & State_MouseOver))
bflags &= ~State_Raised;
- }
}
State mflags = bflags;
diff --git a/src/plugins/coreplugin/mimedatabase.cpp b/src/plugins/coreplugin/mimedatabase.cpp
index 74ae41aab1..3066cb2e03 100644
--- a/src/plugins/coreplugin/mimedatabase.cpp
+++ b/src/plugins/coreplugin/mimedatabase.cpp
@@ -1073,11 +1073,10 @@ bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString
switch (ps) {
case ParseMimeType: { // start parsing a type
const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
- if (type.isEmpty()) {
+ if (type.isEmpty())
reader.raiseError(QString::fromLatin1("Missing 'type'-attribute"));
- } else {
+ else
data.type = type;
- }
}
break;
case ParseGlobPattern:
@@ -1093,12 +1092,11 @@ bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString
case ParseComment: {
// comments have locale attributes. We want the default, English one
QString locale = atts.value(QLatin1String(localeAttributeC)).toString();
- const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toAscii());
- if (locale.isEmpty()) {
+ const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1());
+ if (locale.isEmpty())
data.comment = comment;
- } else {
+ else
data.localeComments.insert(locale, comment);
- }
}
break;
case ParseAlias: {
@@ -1357,14 +1355,13 @@ bool MimeDatabasePrivate::addMimeType(MimeType mt)
}
// insert the type.
m_typeMimeTypeMap.insert(type, MimeMapEntry(mt));
- // Register the children, resolved via alias map. Note that it is still
- // possible that aliases end up in the map if the parent classes are not inserted
- // at this point (thus their aliases not known).
+ // Register the children
+ // Aliases will be resolved later once all mime types are known.
const QStringList subClassesOf = mt.subClassesOf();
if (!subClassesOf.empty()) {
const QStringList::const_iterator socend = subClassesOf.constEnd();
for (QStringList::const_iterator soit = subClassesOf.constBegin(); soit != socend; ++soit)
- m_parentChildrenMap.insert(resolveAlias(*soit), type);
+ m_parentChildrenMap.insert(*soit, type);
}
// register aliasses
const QStringList aliases = mt.aliases();
@@ -1391,7 +1388,9 @@ void MimeDatabasePrivate::raiseLevelRecursion(MimeMapEntry &e, int level)
m_maxLevel = level;
// At all events recurse over children since nodes might have been
// added.
- const QStringList childTypes = m_parentChildrenMap.values(e.type.type());
+ QStringList childTypes = m_parentChildrenMap.values(e.type.type());
+ foreach (const QString &alias, e.type.aliases())
+ childTypes.append(m_parentChildrenMap.values(alias));
if (childTypes.empty())
return;
// look them up in the type->mime type map
@@ -1466,11 +1465,10 @@ MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f) const
qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath();
const MimeType rc = findByFile(f, &priority);
if (debugMimeDB) {
- if (rc) {
+ if (rc)
qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type();
- } else {
+ else
qDebug() << "<MimeDatabase::findByFile: no match";
- }
}
return rc;
}
@@ -1495,8 +1493,8 @@ MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityP
// Pass 1) Try to match on suffix
const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
- for (int level = m_maxLevel; level >= 0 && candidate.isNull(); level--)
- for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
+ for (int level = m_maxLevel; level >= 0 && candidate.isNull(); level--) {
+ for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
if (it.value().level == level) {
const unsigned suffixPriority = it.value().type.matchesFileBySuffix(context);
if (suffixPriority && suffixPriority > *priorityPtr) {
@@ -1506,12 +1504,14 @@ MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityP
return candidate;
}
}
+ }
+ }
// Pass 2) Match on content
if (!f.isReadable())
return candidate;
- for (int level = m_maxLevel; level >= 0; level--)
- for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
+ for (int level = m_maxLevel; level >= 0; level--) {
+ for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
if (it.value().level == level) {
const unsigned contentPriority = it.value().type.matchesFileByContent(context);
if (contentPriority && contentPriority > *priorityPtr) {
@@ -1519,6 +1519,8 @@ MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityP
candidate = it.value().type;
}
}
+ }
+ }
return candidate;
}
@@ -1531,11 +1533,10 @@ MimeType MimeDatabasePrivate::findByData(const QByteArray &data) const
qDebug() << '>' << Q_FUNC_INFO << data.left(20).toHex();
const MimeType rc = findByData(data, &priority);
if (debugMimeDB) {
- if (rc) {
+ if (rc)
qDebug() << "<MimeDatabase::findByData: match prio=" << priority << rc.type();
- } else {
+ else
qDebug() << "<MimeDatabase::findByData: no match";
- }
}
return rc;
}
@@ -1672,11 +1673,11 @@ QList<MimeType> MimeDatabasePrivate::readUserModifiedMimeTypes()
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
atts = reader.attributes();
- if (reader.name() == mimeTypeTagC) {
+ if (reader.name() == QLatin1String(mimeTypeTagC)) {
mimeType.setType(atts.value(mimeTypeAttribute).toString());
const QString &patterns = atts.value(patternAttribute).toString();
mimeType.setGlobPatterns(toGlobPatterns(patterns.split(kSemiColon)));
- } else if (reader.name() == matchTagC) {
+ } else if (reader.name() == QLatin1String(matchTagC)) {
const QString &value = atts.value(matchValueAttribute).toString();
const QString &type = atts.value(matchTypeAttribute).toString();
const QString &offset = atts.value(matchOffsetAttribute).toString();
@@ -1692,7 +1693,7 @@ QList<MimeType> MimeDatabasePrivate::readUserModifiedMimeTypes()
}
break;
case QXmlStreamReader::EndElement:
- if (reader.name() == mimeTypeTagC) {
+ if (reader.name() == QLatin1String(mimeTypeTagC)) {
mimeType.setMagicRuleMatchers(MagicRuleMatcher::createMatchers(rules));
mimeTypes.append(mimeType);
mimeType.clear();
diff --git a/src/plugins/coreplugin/mimetypesettings.cpp b/src/plugins/coreplugin/mimetypesettings.cpp
index 386c524631..11ac480ebb 100644
--- a/src/plugins/coreplugin/mimetypesettings.cpp
+++ b/src/plugins/coreplugin/mimetypesettings.cpp
@@ -232,6 +232,7 @@ public slots:
void removeMagicHeader();
void editMagicHeader();
void resetMimeTypes();
+ void updateMagicHeaderButtons();
public:
static const QChar kSemiColon;
@@ -281,6 +282,11 @@ void MimeTypeSettingsPrivate::configureUi(QWidget *w)
connect(m_ui.removeMagicButton, SIGNAL(clicked()), this, SLOT(removeMagicHeader()));
connect(m_ui.editMagicButton, SIGNAL(clicked()), this, SLOT(editMagicHeader()));
connect(m_ui.resetButton, SIGNAL(clicked()), this, SLOT(resetMimeTypes()));
+ connect(m_ui.magicHeadersTableWidget->selectionModel(),
+ SIGNAL(currentChanged(QModelIndex,QModelIndex)),
+ this,
+ SLOT(updateMagicHeaderButtons()));
+ updateMagicHeaderButtons();
}
void MimeTypeSettingsPrivate::configureTable(QTableView *tableView)
@@ -538,14 +544,23 @@ void MimeTypeSettingsPrivate::resetMimeTypes()
m_reset = true;
}
+void MimeTypeSettingsPrivate::updateMagicHeaderButtons()
+{
+ const QModelIndex &modelIndex = m_ui.magicHeadersTableWidget->selectionModel()->currentIndex();
+ const bool enabled = modelIndex.isValid();
+
+ m_ui.removeMagicButton->setEnabled(enabled);
+ m_ui.editMagicButton->setEnabled(enabled);
+}
+
// MimeTypeSettingsPage
MimeTypeSettings::MimeTypeSettings(QObject *parent)
: IOptionsPage(parent)
, d(new MimeTypeSettingsPrivate)
{
- setId(QLatin1String(Core::Constants::SETTINGS_ID_MIMETYPES));
+ setId(Core::Constants::SETTINGS_ID_MIMETYPES);
setDisplayName(tr("MIME Types"));
- setCategory(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE));
+ setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core",
Core::Constants::SETTINGS_TR_CATEGORY_CORE));
setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
diff --git a/src/plugins/coreplugin/modemanager.cpp b/src/plugins/coreplugin/modemanager.cpp
index 0294c099e5..b0b10fc1cd 100644
--- a/src/plugins/coreplugin/modemanager.cpp
+++ b/src/plugins/coreplugin/modemanager.cpp
@@ -198,7 +198,7 @@ void ModeManager::objectAdded(QObject *obj)
d->m_modeStack->setTabEnabled(index, mode->isEnabled());
// Register mode shortcut
- const Id shortcutId(QLatin1String("QtCreator.Mode.") + mode->id().toString());
+ const Id shortcutId = mode->id().withPrefix("QtCreator.Mode.");
QShortcut *shortcut = new QShortcut(d->m_mainWindow);
shortcut->setWhatsThis(tr("Switch to <b>%1</b> mode").arg(mode->displayName()));
Command *cmd = ActionManager::registerShortcut(shortcut, shortcutId, Context(Constants::C_GLOBAL));
diff --git a/src/plugins/coreplugin/navigationsubwidget.cpp b/src/plugins/coreplugin/navigationsubwidget.cpp
index 9c748f7229..7f2e979532 100644
--- a/src/plugins/coreplugin/navigationsubwidget.cpp
+++ b/src/plugins/coreplugin/navigationsubwidget.cpp
@@ -174,7 +174,7 @@ void NavigationSubWidget::restoreSettings()
Core::Command *NavigationSubWidget::command(const QString &title) const
{
const QHash<Id, Command *> commandMap = m_parentWidget->commandMap();
- QHash<Id, Command *>::const_iterator r = commandMap.find(Id(title));
+ QHash<Id, Command *>::const_iterator r = commandMap.find(Id::fromString(title));
if (r != commandMap.end())
return r.value();
return 0;
diff --git a/src/plugins/coreplugin/navigationwidget.cpp b/src/plugins/coreplugin/navigationwidget.cpp
index 1513a94bfe..70098f0727 100644
--- a/src/plugins/coreplugin/navigationwidget.cpp
+++ b/src/plugins/coreplugin/navigationwidget.cpp
@@ -195,7 +195,7 @@ void NavigationWidget::setFactories(const QList<INavigationWidgetFactory *> fact
d->m_shortcutMap.insert(shortcut, id);
Command *cmd = ActionManager::registerShortcut(shortcut,
- Id(QLatin1String("QtCreator.Sidebar.") + QLatin1String(id.name())), navicontext);
+ id.withPrefix("QtCreator.Sidebar."), navicontext);
cmd->setDefaultKeySequence(factory->activationSequence());
d->m_commandMap.insert(id, cmd);
@@ -339,7 +339,7 @@ void NavigationWidget::restoreSettings(QSettings *settings)
int position = 0;
foreach (const QString &id, viewIds) {
- int index = factoryIndex(Id(id));
+ int index = factoryIndex(Id::fromString(id));
if (index >= 0) {
// Only add if the id was actually found!
insertSubItem(position, index);
@@ -420,9 +420,8 @@ void NavigationWidget::setSuppressed(bool b)
int NavigationWidget::factoryIndex(const Id &id)
{
for (int row = 0; row < d->m_factoryModel->rowCount(); ++row) {
- if (d->m_factoryModel->data(d->m_factoryModel->index(row, 0), FactoryIdRole).value<Core::Id>() == id) {
+ if (d->m_factoryModel->data(d->m_factoryModel->index(row, 0), FactoryIdRole).value<Core::Id>() == id)
return row;
- }
}
return -1;
}
diff --git a/src/plugins/coreplugin/outputpane.cpp b/src/plugins/coreplugin/outputpane.cpp
index 97b90b0fb6..e046878acf 100644
--- a/src/plugins/coreplugin/outputpane.cpp
+++ b/src/plugins/coreplugin/outputpane.cpp
@@ -113,7 +113,7 @@ void OutputPanePlaceHolder::maximizeOrMinimize(bool maximize)
if (maximize) {
d->m_lastNonMaxSize = sizes[idx];
int sum = 0;
- foreach(int s, sizes)
+ foreach (int s, sizes)
sum += s;
for (int i = 0; i < sizes.count(); ++i) {
sizes[i] = 32;
diff --git a/src/plugins/coreplugin/outputpanemanager.cpp b/src/plugins/coreplugin/outputpanemanager.cpp
index c79c05cde6..c9baeb50a5 100644
--- a/src/plugins/coreplugin/outputpanemanager.cpp
+++ b/src/plugins/coreplugin/outputpanemanager.cpp
@@ -47,6 +47,7 @@
#include <extensionsystem/pluginmanager.h>
+#include <utils/hostosinfo.h>
#include <utils/styledbar.h>
#include <utils/qtcassert.h>
@@ -197,11 +198,7 @@ QWidget *OutputPaneManager::buttonsWidget()
// Return shortcut as Ctrl+<number>
static inline int paneShortCut(int number)
{
-#ifdef Q_OS_MAC
- int modifier = Qt::CTRL;
-#else
- int modifier = Qt::ALT;
-#endif
+ const int modifier = Utils::HostOsInfo::isMacHost() ? Qt::CTRL : Qt::ALT;
return modifier | (Qt::Key_0 + number);
}
@@ -278,7 +275,7 @@ void OutputPaneManager::init()
QString actionId = QLatin1String("QtCreator.Pane.") + outPane->displayName().simplified();
actionId.remove(QLatin1Char(' '));
- Id id(actionId);
+ Id id = Id::fromString(actionId);
QAction *action = new QAction(outPane->displayName(), this);
Command *cmd = ActionManager::registerAction(action, id, globalContext);
@@ -320,11 +317,10 @@ void OutputPaneManager::shortcutTriggered()
// then just give it focus.
int current = currentIndex();
if (OutputPanePlaceHolder::isCurrentVisible() && current == idx) {
- if (!outputPane->hasFocus() && outputPane->canFocus()) {
+ if (!outputPane->hasFocus() && outputPane->canFocus())
outputPane->setFocus();
- } else {
+ else
slotHide();
- }
} else {
// Else do the same as clicking on the button does.
buttonTriggered(idx);
@@ -636,7 +632,7 @@ OutputPaneToggleButton::OutputPaneToggleButton(int number, const QString &text,
fnt.setPixelSize(11);
m_label->setFont(fnt);
m_label->setAlignment(Qt::AlignCenter);
- m_label->setStyleSheet("background-color: #818181; color: white; border-radius: 6; padding-left: 4; padding-right: 4;");
+ m_label->setStyleSheet(QLatin1String("background-color: #818181; color: white; border-radius: 6; padding-left: 4; padding-right: 4;"));
m_label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_label->hide();
}
@@ -703,9 +699,11 @@ void OutputPaneToggleButton::checkStateSet()
m_flashTimer->stop();
if (isChecked())
- m_label->setStyleSheet("background-color: #e1e1e1; color: #606060; border-radius: 6; padding-left: 4; padding-right: 4;");
+ m_label->setStyleSheet(QLatin1String("background-color: #e1e1e1; color: #606060; "
+ "border-radius: 6; padding-left: 4; padding-right: 4;"));
else
- m_label->setStyleSheet("background-color: #818181; color: white; border-radius: 6; padding-left: 4; padding-right: 4;");
+ m_label->setStyleSheet(QLatin1String("background-color: #818181; color: white; border-radius: 6; "
+ "padding-left: 4; padding-right: 4;"));
}
void OutputPaneToggleButton::flash(int count)
diff --git a/src/plugins/coreplugin/outputwindow.cpp b/src/plugins/coreplugin/outputwindow.cpp
index 9e94ee3567..1ebada52a1 100644
--- a/src/plugins/coreplugin/outputwindow.cpp
+++ b/src/plugins/coreplugin/outputwindow.cpp
@@ -174,9 +174,8 @@ void OutputWindow::setFormatter(OutputFormatter *formatter)
void OutputWindow::showEvent(QShowEvent *e)
{
QPlainTextEdit::showEvent(e);
- if (m_scrollToBottom) {
+ if (m_scrollToBottom)
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
- }
m_scrollToBottom = false;
}
diff --git a/src/plugins/coreplugin/progressmanager/futureprogress.cpp b/src/plugins/coreplugin/progressmanager/futureprogress.cpp
index 5ee85450a0..f227048db6 100644
--- a/src/plugins/coreplugin/progressmanager/futureprogress.cpp
+++ b/src/plugins/coreplugin/progressmanager/futureprogress.cpp
@@ -164,7 +164,7 @@ FutureProgress::FutureProgress(QWidget *parent) :
connect(&d->m_watcher, SIGNAL(progressValueChanged(int)), this, SLOT(setProgressValue(int)));
connect(&d->m_watcher, SIGNAL(progressTextChanged(QString)),
this, SLOT(setProgressText(QString)));
- connect(d->m_progress, SIGNAL(clicked()), this, SLOT(cancel()));
+ connect(d->m_progress, SIGNAL(clicked()), this, SLOT(cancel()));
}
/*!
@@ -247,11 +247,10 @@ void FutureProgress::setFinished()
d->m_progress->setFinished(true);
- if (d->m_watcher.future().isCanceled()) {
+ if (d->m_watcher.future().isCanceled())
d->m_progress->setError(true);
- } else {
+ else
d->m_progress->setError(false);
- }
emit finished();
d->tryToFadeAway();
}
@@ -363,15 +362,13 @@ QString FutureProgress::type() const
void FutureProgress::setKeepOnFinish(KeepOnFinishType keepType)
{
- if (d->m_keep == keepType) {
+ if (d->m_keep == keepType)
return;
- }
d->m_keep = keepType;
//if it is not finished tryToFadeAway is called by setFinished at the end
- if (d->m_watcher.isFinished()) {
+ if (d->m_watcher.isFinished())
d->tryToFadeAway();
- }
}
bool FutureProgress::keepOnFinish() const
diff --git a/src/plugins/coreplugin/progressmanager/progressbar.cpp b/src/plugins/coreplugin/progressmanager/progressbar.cpp
index 63c54a3ffd..63e75195d9 100644
--- a/src/plugins/coreplugin/progressmanager/progressbar.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressbar.cpp
@@ -57,7 +57,7 @@ ProgressBar::~ProgressBar()
bool ProgressBar::event(QEvent *e)
{
- switch(e->type()) {
+ switch (e->type()) {
case QEvent::Enter:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "cancelButtonFader");
diff --git a/src/plugins/coreplugin/progressmanager/progressmanager.cpp b/src/plugins/coreplugin/progressmanager/progressmanager.cpp
index 2142c828db..5afa119c82 100644
--- a/src/plugins/coreplugin/progressmanager/progressmanager.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressmanager.cpp
@@ -29,8 +29,8 @@
#include "progressmanager_p.h"
#include "progressview.h"
-#include "coreconstants.h"
-#include "icore.h"
+#include "../coreconstants.h"
+#include "../icore.h"
#include <utils/qtcassert.h>
@@ -272,9 +272,8 @@ void ProgressManagerPrivate::cancelTasks(const QString &type)
delete task.key();
task = m_runningTasks.erase(task);
}
- if (found) {
+ if (found)
emit allTasksFinished(type);
- }
}
void ProgressManagerPrivate::cancelAllRunningTasks()
@@ -330,9 +329,8 @@ void ProgressManagerPrivate::taskFinished()
m_runningTasks.remove(task);
delete task;
- if (!m_runningTasks.key(type, 0)) {
+ if (!m_runningTasks.key(type, 0))
emit allTasksFinished(type);
- }
}
void ProgressManagerPrivate::disconnectApplicationTask()
diff --git a/src/plugins/coreplugin/progressmanager/progressview.cpp b/src/plugins/coreplugin/progressmanager/progressview.cpp
index a821c2a110..b4a273d59a 100644
--- a/src/plugins/coreplugin/progressmanager/progressview.cpp
+++ b/src/plugins/coreplugin/progressmanager/progressview.cpp
@@ -69,11 +69,10 @@ FutureProgress *ProgressView::addTask(const QFuture<void> &future,
m_layout->insertWidget(0, progress);
m_taskList.append(progress);
progress->setType(type);
- if (flags.testFlag(ProgressManager::KeepOnFinish)) {
+ if (flags.testFlag(ProgressManager::KeepOnFinish))
progress->setKeepOnFinish(FutureProgress::KeepOnFinishTillUserInteraction);
- } else {
+ else
progress->setKeepOnFinish(FutureProgress::HideOnFinish);
- }
connect(progress, SIGNAL(removeMe()), this, SLOT(slotRemoveTask()));
return progress;
}
diff --git a/src/plugins/coreplugin/rightpane.cpp b/src/plugins/coreplugin/rightpane.cpp
index 4a0cdbaf19..bd90b80c8d 100644
--- a/src/plugins/coreplugin/rightpane.cpp
+++ b/src/plugins/coreplugin/rightpane.cpp
@@ -176,11 +176,10 @@ void RightPaneWidget::saveSettings(QSettings *settings)
void RightPaneWidget::readSettings(QSettings *settings)
{
- if (settings->contains(QLatin1String("RightPane/Visible"))) {
+ if (settings->contains(QLatin1String("RightPane/Visible")))
setShown(settings->value(QLatin1String("RightPane/Visible")).toBool());
- } else {
+ else
setShown(false);
- }
if (settings->contains(QLatin1String("RightPane/Width"))) {
m_width = settings->value(QLatin1String("RightPane/Width")).toInt();
@@ -190,9 +189,8 @@ void RightPaneWidget::readSettings(QSettings *settings)
m_width = 500; //pixel
}
// Apply
- if (RightPanePlaceHolder::m_current) {
+ if (RightPanePlaceHolder::m_current)
RightPanePlaceHolder::m_current->applyStoredSize(m_width);
- }
}
void RightPaneWidget::setShown(bool b)
diff --git a/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp b/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp
index c3af4894eb..71e6465a78 100644
--- a/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp
+++ b/src/plugins/coreplugin/scriptmanager/scriptmanager.cpp
@@ -95,7 +95,7 @@ static QScriptValue inputDialogGetInteger(QScriptContext *context, QScriptEngine
const int maxValue = argumentCount > 5 ? context->argument(5).toInt32() : INT_MAX;
bool ok;
- const int rc = QInputDialog::getInteger(parent, title, label, defaultValue, minValue, maxValue, 1, &ok);
+ const int rc = QInputDialog::getInt(parent, title, label, defaultValue, minValue, maxValue, 1, &ok);
if (!ok)
return QScriptValue(engine, QScriptValue::NullValue);
return QScriptValue(engine, rc);
diff --git a/src/plugins/coreplugin/settingsdatabase.cpp b/src/plugins/coreplugin/settingsdatabase.cpp
index 6756011773..ccfaae9b94 100644
--- a/src/plugins/coreplugin/settingsdatabase.cpp
+++ b/src/plugins/coreplugin/settingsdatabase.cpp
@@ -244,9 +244,8 @@ QStringList SettingsDatabase::childKeys() const
QMapIterator<QString, QVariant> i(d->m_settings);
while (i.hasNext()) {
const QString &key = i.next().key();
- if (key.startsWith(g) && key.indexOf(QLatin1Char('/'), g.length() + 1) == -1) {
+ if (key.startsWith(g) && key.indexOf(QLatin1Char('/'), g.length() + 1) == -1)
children.append(key.mid(g.length() + 1));
- }
}
return children;
diff --git a/src/plugins/coreplugin/sidebar.cpp b/src/plugins/coreplugin/sidebar.cpp
index f73726a8f3..e6b9bd7f7c 100644
--- a/src/plugins/coreplugin/sidebar.cpp
+++ b/src/plugins/coreplugin/sidebar.cpp
@@ -41,6 +41,7 @@
#include <QLayout>
#include <QToolBar>
#include <QAction>
+#include <QPointer>
#include <QToolButton>
namespace Core {
@@ -79,7 +80,7 @@ struct SideBarPrivate {
SideBarPrivate() :m_closeWhenEmpty(false) {}
QList<Internal::SideBarWidget*> m_widgets;
- QMap<QString, QWeakPointer<SideBarItem> > m_itemMap;
+ QMap<QString, QPointer<SideBarItem> > m_itemMap;
QStringList m_availableItemIds;
QStringList m_availableItemTitles;
QStringList m_unavailableItemIds;
@@ -108,7 +109,7 @@ SideBar::SideBar(QList<SideBarItem*> itemList,
SideBar::~SideBar()
{
- foreach (const QWeakPointer<SideBarItem> &i, d->m_itemMap)
+ foreach (const QPointer<SideBarItem> &i, d->m_itemMap)
if (!i.isNull())
delete i.data();
delete d;
@@ -116,8 +117,8 @@ SideBar::~SideBar()
QString SideBar::idForTitle(const QString &title) const
{
- QMapIterator<QString, QWeakPointer<SideBarItem> > iter(d->m_itemMap);
- while(iter.hasNext()) {
+ QMapIterator<QString, QPointer<SideBarItem> > iter(d->m_itemMap);
+ while (iter.hasNext()) {
iter.next();
if (iter.value().data()->title() == title)
return iter.key();
@@ -151,7 +152,7 @@ void SideBar::setCloseWhenEmpty(bool value)
void SideBar::makeItemAvailable(SideBarItem *item)
{
- typedef QMap<QString, QWeakPointer<SideBarItem> >::const_iterator Iterator;
+ typedef QMap<QString, QPointer<SideBarItem> >::const_iterator Iterator;
const Iterator cend = d->m_itemMap.constEnd();
for (Iterator it = d->m_itemMap.constBegin(); it != cend ; ++it) {
@@ -172,7 +173,7 @@ void SideBar::makeItemAvailable(SideBarItem *item)
void SideBar::setUnavailableItemIds(const QStringList &itemIds)
{
// re-enable previous items
- foreach(const QString &id, d->m_unavailableItemIds) {
+ foreach (const QString &id, d->m_unavailableItemIds) {
d->m_availableItemIds.append(id);
d->m_availableItemTitles.append(d->m_itemMap.value(id).data()->title());
}
@@ -265,7 +266,7 @@ void SideBar::saveSettings(QSettings *settings, const QString &name)
views.append(currentItemId);
}
if (views.isEmpty() && d->m_itemMap.size()) {
- QMapIterator<QString, QWeakPointer<SideBarItem> > iter(d->m_itemMap);
+ QMapIterator<QString, QPointer<SideBarItem> > iter(d->m_itemMap);
iter.next();
views.append(iter.key());
}
@@ -321,7 +322,7 @@ void SideBar::readSettings(QSettings *settings, const QString &name)
void SideBar::activateItem(SideBarItem *item)
{
- typedef QMap<QString, QWeakPointer<SideBarItem> >::const_iterator Iterator;
+ typedef QMap<QString, QPointer<SideBarItem> >::const_iterator Iterator;
QString id;
const Iterator cend = d->m_itemMap.constEnd();
diff --git a/src/plugins/coreplugin/sidebarwidget.cpp b/src/plugins/coreplugin/sidebarwidget.cpp
index 3ff6f1c87c..5b3566472c 100644
--- a/src/plugins/coreplugin/sidebarwidget.cpp
+++ b/src/plugins/coreplugin/sidebarwidget.cpp
@@ -94,7 +94,7 @@ SideBarWidget::SideBarWidget(SideBar *sideBar, const QString &id)
qSort(titleList);
QString t = id;
if (titleList.count()) {
- foreach(const QString &itemTitle, titleList)
+ foreach (const QString &itemTitle, titleList)
m_comboBox->addItem(itemTitle, m_sideBar->idForTitle(itemTitle));
m_comboBox->setCurrentIndex(0);
@@ -160,7 +160,7 @@ void SideBarWidget::updateAvailableItems()
titleList.append(currentTitle);
qSort(titleList);
- foreach(const QString &itemTitle, titleList)
+ foreach (const QString &itemTitle, titleList)
m_comboBox->addItem(itemTitle, m_sideBar->idForTitle(itemTitle));
int idx = m_comboBox->findText(currentTitle);
diff --git a/src/plugins/coreplugin/styleanimator.cpp b/src/plugins/coreplugin/styleanimator.cpp
index 8ad1a783f5..bd1a9ae4c1 100644
--- a/src/plugins/coreplugin/styleanimator.cpp
+++ b/src/plugins/coreplugin/styleanimator.cpp
@@ -128,9 +128,8 @@ void StyleAnimator::timerEvent(QTimerEvent *)
delete a;
}
}
- if (animations.size() == 0 && animationTimer.isActive()) {
+ if (animations.size() == 0 && animationTimer.isActive())
animationTimer.stop();
- }
}
void StyleAnimator::stopAnimation(const QWidget *w)
@@ -148,7 +147,6 @@ void StyleAnimator::startAnimation(Animation *t)
{
stopAnimation(t->widget());
animations.append(t);
- if (animations.size() > 0 && !animationTimer.isActive()) {
+ if (animations.size() > 0 && !animationTimer.isActive())
animationTimer.start(35, this);
- }
}
diff --git a/src/plugins/coreplugin/textdocument.h b/src/plugins/coreplugin/textdocument.h
index 0d2a70ffe0..4490880027 100644
--- a/src/plugins/coreplugin/textdocument.h
+++ b/src/plugins/coreplugin/textdocument.h
@@ -53,6 +53,7 @@ public:
const QTextCodec *codec() const;
void setCodec(const QTextCodec *);
void switchUtf8Bom();
+ virtual bool supportsUtf8Bom() { return true; }
ReadResult read(const QString &fileName, QStringList *plainTextList, QString *errorString);
ReadResult read(const QString &fileName, QString *plainText, QString *errorString);
diff --git a/src/plugins/coreplugin/toolsettings.cpp b/src/plugins/coreplugin/toolsettings.cpp
index ea0064e87a..d76af89a1a 100644
--- a/src/plugins/coreplugin/toolsettings.cpp
+++ b/src/plugins/coreplugin/toolsettings.cpp
@@ -50,9 +50,9 @@ using namespace Core::Internal;
ToolSettings::ToolSettings(QObject *parent) :
IOptionsPage(parent)
{
- setId(QLatin1String(Core::Constants::SETTINGS_ID_TOOLS));
+ setId(Core::Constants::SETTINGS_ID_TOOLS);
setDisplayName(tr("External Tools"));
- setCategory(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE));
+ setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core", Constants::SETTINGS_TR_CATEGORY_CORE));
setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
}
@@ -67,9 +67,8 @@ QWidget *ToolSettings::createPage(QWidget *parent)
{
m_widget = new ExternalToolConfig(parent);
m_widget->setTools(ExternalToolManager::instance()->toolsByCategory());
- if (m_searchKeywords.isEmpty()) {
+ if (m_searchKeywords.isEmpty())
m_searchKeywords = m_widget->searchKeywords();
- }
return m_widget;
}
@@ -151,9 +150,8 @@ void ToolSettings::apply()
ExternalTool *toolToAdd = 0;
if (ExternalTool *originalTool = originalTools.take(tool->id())) {
// check if it has different category and is custom tool
- if (tool->displayCategory() != it.key() && !tool->preset()) {
+ if (tool->displayCategory() != it.key() && !tool->preset())
tool->setDisplayCategory(it.key());
- }
// check if the tool has changed
if ((*originalTool) == (*tool)) {
toolToAdd = originalTool;
diff --git a/src/plugins/coreplugin/variablechooser.cpp b/src/plugins/coreplugin/variablechooser.cpp
index 19f7ced697..a96212c681 100644
--- a/src/plugins/coreplugin/variablechooser.cpp
+++ b/src/plugins/coreplugin/variablechooser.cpp
@@ -60,7 +60,7 @@ VariableChooser::VariableChooser(QWidget *parent) :
VariableManager *vm = VariableManager::instance();
foreach (const QByteArray &variable, vm->variables())
- ui->variableList->addItem(variable);
+ ui->variableList->addItem(QString::fromLatin1(variable));
connect(ui->variableList, SIGNAL(currentTextChanged(QString)),
this, SLOT(updateDescription(QString)));
@@ -87,7 +87,8 @@ void VariableChooser::updateDescription(const QString &variable)
void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
{
- Q_UNUSED(old)
+ if (old)
+ old->removeEventFilter(this);
if (!widget) // we might loose focus, but then keep the previous state
return;
// prevent children of the chooser itself, and limit to children of chooser's parent
@@ -104,6 +105,7 @@ void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
}
if (!handle)
return;
+ widget->installEventFilter(this); // for intercepting escape key presses
QLineEdit *previousLineEdit = m_lineEdit;
m_lineEdit = 0;
m_textEdit = 0;
@@ -111,13 +113,12 @@ void VariableChooser::updateCurrentEditor(QWidget *old, QWidget *widget)
QVariant variablesSupportProperty = widget->property(Constants::VARIABLE_SUPPORT_PROPERTY);
bool supportsVariables = (variablesSupportProperty.isValid()
? variablesSupportProperty.toBool() : false);
- if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) {
+ if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget))
m_lineEdit = (supportsVariables ? lineEdit : 0);
- } else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget)) {
+ else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget))
m_textEdit = (supportsVariables ? textEdit : 0);
- } else if (QPlainTextEdit *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget)) {
+ else if (QPlainTextEdit *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget))
m_plainTextEdit = (supportsVariables ? plainTextEdit : 0);
- }
if (!(m_lineEdit || m_textEdit || m_plainTextEdit))
hide();
if (m_lineEdit != previousLineEdit) {
@@ -183,10 +184,26 @@ void VariableChooser::insertVariable(const QString &variable)
}
}
-void VariableChooser::keyPressEvent(QKeyEvent *ke)
+static bool handleEscapePressed(QKeyEvent *ke, QWidget *widget)
{
if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
ke->accept();
- QTimer::singleShot(0, this, SLOT(close()));
+ QTimer::singleShot(0, widget, SLOT(close()));
+ return true;
+ }
+ return false;
+}
+
+void VariableChooser::keyPressEvent(QKeyEvent *ke)
+{
+ handleEscapePressed(ke, this);
+}
+
+bool VariableChooser::eventFilter(QObject *, QEvent *event)
+{
+ if (event->type() == QEvent::KeyPress && isVisible()) {
+ QKeyEvent *ke = static_cast<QKeyEvent *>(event);
+ return handleEscapePressed(ke, this);
}
+ return false;
}
diff --git a/src/plugins/coreplugin/variablechooser.h b/src/plugins/coreplugin/variablechooser.h
index 26ec962537..5fc1d9ac65 100644
--- a/src/plugins/coreplugin/variablechooser.h
+++ b/src/plugins/coreplugin/variablechooser.h
@@ -58,6 +58,7 @@ public:
protected:
void keyPressEvent(QKeyEvent *ke);
+ bool eventFilter(QObject *, QEvent *event);
private slots:
void updateDescription(const QString &variable);
diff --git a/src/plugins/coreplugin/variablemanager.cpp b/src/plugins/coreplugin/variablemanager.cpp
index 00c3e1ed46..59c379ed33 100644
--- a/src/plugins/coreplugin/variablemanager.cpp
+++ b/src/plugins/coreplugin/variablemanager.cpp
@@ -97,18 +97,11 @@ bool VariableManager::remove(const QByteArray &variable)
QString VariableManager::value(const QByteArray &variable, bool *found)
{
emit variableUpdateRequested(variable);
- if (found) {
+ if (found)
*found = d->m_map.contains(variable);
- }
return d->m_map.value(variable);
}
-QString VariableManager::value(const QByteArray &variable, const QString &defaultValue)
-{
- emit variableUpdateRequested(variable);
- return d->m_map.value(variable, defaultValue);
-}
-
Utils::AbstractMacroExpander *VariableManager::macroExpander()
{
return &d->m_macroExpander;
diff --git a/src/plugins/coreplugin/variablemanager.h b/src/plugins/coreplugin/variablemanager.h
index e4c82b7ba5..cddf0b688f 100644
--- a/src/plugins/coreplugin/variablemanager.h
+++ b/src/plugins/coreplugin/variablemanager.h
@@ -56,7 +56,6 @@ public:
void insert(const QByteArray &variable, const QString &value);
bool remove(const QByteArray &variable);
QString value(const QByteArray &variable, bool *found = 0);
- QString value(const QByteArray &variable, const QString &defaultValue);
Utils::AbstractMacroExpander *macroExpander();
void registerVariable(const QByteArray &variable,
diff --git a/src/plugins/coreplugin/vcsmanager.cpp b/src/plugins/coreplugin/vcsmanager.cpp
index 35cf049b8d..0dd926b46f 100644
--- a/src/plugins/coreplugin/vcsmanager.cpp
+++ b/src/plugins/coreplugin/vcsmanager.cpp
@@ -132,7 +132,7 @@ public:
VcsInfo *newInfo = new VcsInfo(vc, topLevel);
bool createdNewInfo(true);
// Do we have a matching VcsInfo already?
- foreach(VcsInfo *i, m_vcsInfoList) {
+ foreach (VcsInfo *i, m_vcsInfoList) {
if (*i == *newInfo) {
delete newInfo;
newInfo = i;
@@ -148,11 +148,10 @@ public:
while (tmpDir.count() >= topLevel.count() && tmpDir.count() > 0) {
m_cachedMatches.insert(tmpDir, newInfo);
const int slashPos = tmpDir.lastIndexOf(slash);
- if (slashPos >= 0) {
+ if (slashPos >= 0)
tmpDir.truncate(slashPos);
- } else {
+ else
tmpDir.clear();
- }
}
}
@@ -208,7 +207,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const QString &input
if (inputDirectory.isEmpty())
return 0;
- // Make sure we a clean absolute path:
+ // Make sure we an absolute path:
const QString directory = QDir(inputDirectory).absolutePath();
VcsManagerPrivate::VcsInfo *cachedData = d->findInCache(directory);
@@ -242,7 +241,7 @@ IVersionControl* VcsManager::findVersionControlForDirectory(const QString &input
}
// Register Vcs(s) with the cache
- QString tmpDir = directory;
+ QString tmpDir = QFileInfo(directory).canonicalFilePath();
const QChar slash = QLatin1Char('/');
const StringVersionControlPairs::const_iterator cend = allThatCanManage.constEnd();
for (StringVersionControlPairs::const_iterator i = allThatCanManage.constBegin(); i != cend; ++i) {
diff --git a/src/plugins/coreplugin/versiondialog.cpp b/src/plugins/coreplugin/versiondialog.cpp
index 4616c79525..fed1031f15 100644
--- a/src/plugins/coreplugin/versiondialog.cpp
+++ b/src/plugins/coreplugin/versiondialog.cpp
@@ -85,7 +85,7 @@ VersionDialog::VersionDialog(QWidget *parent)
"The program is provided AS IS with NO WARRANTY OF ANY KIND, "
"INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A "
"PARTICULAR PURPOSE.<br/>")
- .arg(version,
+ .arg(version,
QLatin1String(qVersion()), QString::number(QSysInfo::WordSize),
QLatin1String(__DATE__), QLatin1String(__TIME__), QLatin1String(Constants::IDE_YEAR),
(QLatin1String(Constants::IDE_AUTHOR)), ideVersionDescription,
diff --git a/src/plugins/cpaster/codepasterprotocol.cpp b/src/plugins/cpaster/codepasterprotocol.cpp
index 8fe6fe93ec..b6e0e02cd0 100644
--- a/src/plugins/cpaster/codepasterprotocol.cpp
+++ b/src/plugins/cpaster/codepasterprotocol.cpp
@@ -37,6 +37,7 @@
#include <coreplugin/messagemanager.h>
#include <coreplugin/messageoutputwindow.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QListWidget>
@@ -76,12 +77,9 @@ bool CodePasterProtocol::checkConfiguration(QString *errorMessage)
const QString hostName = m_page->hostName();
if (hostName.isEmpty()) {
if (errorMessage) {
- *errorMessage =
-#ifdef Q_OS_MAC
- tr("No Server defined in the CodePaster preferences.");
-#else
- tr("No Server defined in the CodePaster options.");
-#endif
+ *errorMessage = Utils::HostOsInfo::isMacHost()
+ ? tr("No Server defined in the CodePaster preferences.")
+ : tr("No Server defined in the CodePaster options.");
}
return false;
}
@@ -159,7 +157,7 @@ void CodePasterProtocol::pasteFinished()
qWarning("Error pasting: %s", qPrintable(m_pasteReply->errorString()));
} else {
// Cut out the href-attribute
- QString contents = QString::fromAscii(m_pasteReply->readAll());
+ QString contents = QString::fromLatin1(m_pasteReply->readAll());
int hrefPos = contents.indexOf(QLatin1String("href=\""));
if (hrefPos != -1) {
hrefPos += 6;
@@ -190,7 +188,7 @@ void CodePasterProtocol::fetchFinished()
if (error) {
content = m_fetchReply->errorString();
} else {
- content = QString::fromAscii(m_fetchReply->readAll()); // Codepaster does not support special characters.
+ content = QString::fromLatin1(m_fetchReply->readAll()); // Codepaster does not support special characters.
if (debug)
qDebug() << content;
if (content.contains(QLatin1String("<B>No such paste!</B>"))) {
@@ -210,7 +208,7 @@ void CodePasterProtocol::listFinished()
Core::ICore::messageManager()->printToOutputPane(m_listReply->errorString(), true);
} else {
const QByteArray data = m_listReply->readAll();
- const QStringList lines = QString::fromAscii(data).split(QLatin1Char('\n'));
+ const QStringList lines = QString::fromLatin1(data).split(QLatin1Char('\n'));
emit listDone(name(), lines);
}
m_listReply->deleteLater();
diff --git a/src/plugins/cpaster/codepastersettings.cpp b/src/plugins/cpaster/codepastersettings.cpp
index 9fc92f4f22..185073fc9b 100644
--- a/src/plugins/cpaster/codepastersettings.cpp
+++ b/src/plugins/cpaster/codepastersettings.cpp
@@ -51,9 +51,9 @@ namespace CodePaster {
CodePasterSettingsPage::CodePasterSettingsPage()
{
- setId(QLatin1String("C.CodePaster"));
+ setId("C.CodePaster");
setDisplayName(tr("CodePaster"));
- setCategory(QLatin1String(Constants::CPASTER_SETTINGS_CATEGORY));
+ setCategory(Constants::CPASTER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("CodePaster",
Constants::CPASTER_SETTINGS_TR_CATEGORY));
diff --git a/src/plugins/cpaster/cpaster.pro b/src/plugins/cpaster/cpaster.pro
index a06c2c74d5..5cb3e3a713 100644
--- a/src/plugins/cpaster/cpaster.pro
+++ b/src/plugins/cpaster/cpaster.pro
@@ -3,7 +3,6 @@ TEMPLATE = lib
TARGET = CodePaster
include(../../qtcreatorplugin.pri)
include(cpaster_dependencies.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
HEADERS += cpasterplugin.h \
settingspage.h \
protocol.h \
diff --git a/src/plugins/cpaster/cpaster.qbs b/src/plugins/cpaster/cpaster.qbs
index 30208fe477..14cf63b416 100644
--- a/src/plugins/cpaster/cpaster.qbs
+++ b/src/plugins/cpaster/cpaster.qbs
@@ -10,13 +10,7 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
- "../../shared/cpaster",
- "..",
- "../../libs",
- buildDirectory
- ]
+ cpp.includePaths: base.concat("../../shared/cpaster")
files: [
"codepasterprotocol.cpp",
@@ -54,7 +48,7 @@ QtcPlugin {
"settingspage.h",
"settingspage.ui",
"urlopenprotocol.cpp",
- "urlopenprotocol.h"
+ "urlopenprotocol.h",
]
Group {
@@ -63,7 +57,7 @@ QtcPlugin {
"cgi.cpp",
"cgi.h",
"splitter.cpp",
- "splitter.h"
+ "splitter.h",
]
}
}
diff --git a/src/plugins/cpaster/cpasterconstants.h b/src/plugins/cpaster/cpasterconstants.h
index ca2811145e..0c2b9d639b 100644
--- a/src/plugins/cpaster/cpasterconstants.h
+++ b/src/plugins/cpaster/cpasterconstants.h
@@ -35,7 +35,7 @@
namespace CodePaster {
namespace Constants {
-const char CPASTER_SETTINGS_CATEGORY[] = "X.CPaster";
+const char CPASTER_SETTINGS_CATEGORY[] = "XZ.CPaster";
const char CPASTER_SETTINGS_TR_CATEGORY[] = QT_TRANSLATE_NOOP("CodePaster", "Code Pasting");
const char SETTINGS_CATEGORY_CPASTER_ICON[] = ":/core/images/category_cpaster.png";
diff --git a/src/plugins/cpaster/cpasterplugin.cpp b/src/plugins/cpaster/cpasterplugin.cpp
index 02fbce1ef4..a86cafbdc7 100644
--- a/src/plugins/cpaster/cpasterplugin.cpp
+++ b/src/plugins/cpaster/cpasterplugin.cpp
@@ -142,7 +142,7 @@ bool CodepasterPlugin::initialize(const QStringList &arguments, QString *errorMe
new FileShareProtocol
};
const int count = sizeof(protos) / sizeof(Protocol *);
- for(int i = 0; i < count; ++i) {
+ for (int i = 0; i < count; ++i) {
connect(protos[i], SIGNAL(pasteDone(QString)), this, SLOT(finishPost(QString)));
connect(protos[i], SIGNAL(fetchDone(QString,QString,bool)),
this, SLOT(finishFetch(QString,QString,bool)));
@@ -202,7 +202,7 @@ void CodepasterPlugin::extensionsInitialized()
ExtensionSystem::IPlugin::ShutdownFlag CodepasterPlugin::aboutToShutdown()
{
// Delete temporary, fetched files
- foreach(const QString &fetchedSnippet, m_fetchedSnippets) {
+ foreach (const QString &fetchedSnippet, m_fetchedSnippets) {
QFile file(fetchedSnippet);
if (file.exists())
file.remove();
diff --git a/src/plugins/cpaster/fileshareprotocol.cpp b/src/plugins/cpaster/fileshareprotocol.cpp
index b5efc62d05..50367c04dc 100644
--- a/src/plugins/cpaster/fileshareprotocol.cpp
+++ b/src/plugins/cpaster/fileshareprotocol.cpp
@@ -116,13 +116,12 @@ static bool parse(const QString &fileName,
}
// Parse elements
elementCount++;
- if (user && elementName == QLatin1String(userElementC)) {
+ if (user && elementName == QLatin1String(userElementC))
*user = reader.readElementText();
- } else if (description && elementName == QLatin1String(descriptionElementC)) {
+ else if (description && elementName == QLatin1String(descriptionElementC))
*description = reader.readElementText();
- } else if (text && elementName == QLatin1String(textElementC)) {
+ else if (text && elementName == QLatin1String(textElementC))
*text = reader.readElementText();
- }
}
}
if (reader.hasError()) {
@@ -151,11 +150,10 @@ void FileShareProtocol::fetch(const QString &id)
fi = QFileInfo(m_settings->path + QLatin1Char('/') + id);
QString errorMessage;
QString text;
- if (parse(fi.absoluteFilePath(), &errorMessage, 0, 0, &text)) {
+ if (parse(fi.absoluteFilePath(), &errorMessage, 0, 0, &text))
emit fetchDone(id, text, false);
- } else {
+ else
emit fetchDone(id, errorMessage, true);
- }
}
void FileShareProtocol::list()
diff --git a/src/plugins/cpaster/fileshareprotocolsettingspage.cpp b/src/plugins/cpaster/fileshareprotocolsettingspage.cpp
index 29df625960..8a7c4c0496 100644
--- a/src/plugins/cpaster/fileshareprotocolsettingspage.cpp
+++ b/src/plugins/cpaster/fileshareprotocolsettingspage.cpp
@@ -98,9 +98,9 @@ FileShareProtocolSettingsPage::FileShareProtocolSettingsPage(const QSharedPointe
QObject *parent) :
Core::IOptionsPage(parent), m_settings(s), m_widget(0)
{
- setId(QLatin1String("X.FileSharePaster"));
+ setId("X.FileSharePaster");
setDisplayName(tr("Fileshare"));
- setCategory(QLatin1String(Constants::CPASTER_SETTINGS_CATEGORY));
+ setCategory(Constants::CPASTER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("CodePaster", Constants::CPASTER_SETTINGS_TR_CATEGORY));
}
diff --git a/src/plugins/cpaster/frontend/argumentscollector.cpp b/src/plugins/cpaster/frontend/argumentscollector.cpp
new file mode 100644
index 0000000000..d6950a1626
--- /dev/null
+++ b/src/plugins/cpaster/frontend/argumentscollector.cpp
@@ -0,0 +1,130 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "argumentscollector.h"
+
+#include <QFileInfo>
+#include <QCoreApplication>
+
+static QString pasteRequestString() { return QLatin1String("paste"); }
+static QString listProtocolsRequestString() { return QLatin1String("list-protocols"); }
+static QString helpRequestString() { return QLatin1String("help"); }
+static QString pasteFileOptionString() { return QLatin1String("-file"); }
+static QString pasteProtocolOptionString() { return QLatin1String("-protocol"); }
+
+namespace {
+struct ArgumentErrorException
+{
+ ArgumentErrorException(const QString &error) : error(error) {}
+ const QString error;
+};
+}
+
+ArgumentsCollector::ArgumentsCollector(const QStringList &availableProtocols)
+ : m_availableProtocols(availableProtocols)
+{
+}
+
+bool ArgumentsCollector::collect(const QStringList &args)
+{
+ m_arguments = args;
+ m_errorString.clear();
+ m_inputFilePath.clear();
+ m_protocol.clear();
+ try {
+ setRequest();
+ if (m_requestType == RequestTypePaste)
+ setPasteOptions();
+ return true;
+ } catch (const ArgumentErrorException &ex) {
+ m_errorString = ex.error;
+ return false;
+ }
+}
+
+QString ArgumentsCollector::usageString() const
+{
+ QString usage = QString::fromLatin1("Usage:\n\t%1 <request> [ <request options>]\n\t")
+ .arg(QFileInfo(QCoreApplication::applicationFilePath()).fileName());
+ usage += QString::fromLatin1("Possible requests: \"%1\", \"%2\", \"%3\"\n\t")
+ .arg(pasteRequestString(), listProtocolsRequestString(), helpRequestString());
+ usage += QString::fromLatin1("Possible options for request \"%1\": \"%2 <file>\" (default: stdin), "
+ "\"%3 <protocol>\"\n")
+ .arg(pasteRequestString(), pasteFileOptionString(), pasteProtocolOptionString());
+ return usage;
+}
+
+void ArgumentsCollector::setRequest()
+{
+ if (m_arguments.isEmpty())
+ throw ArgumentErrorException(QLatin1String("No request given"));
+ const QString requestString = m_arguments.takeFirst();
+ if (requestString == pasteRequestString())
+ m_requestType = RequestTypePaste;
+ else if (requestString == listProtocolsRequestString())
+ m_requestType = RequestTypeListProtocols;
+ else if (requestString == helpRequestString())
+ m_requestType = RequestTypeHelp;
+ else
+ throw ArgumentErrorException(QString::fromLatin1("Unknown request \"%1\"").arg(requestString));
+}
+
+void ArgumentsCollector::setPasteOptions()
+{
+ while (!m_arguments.isEmpty()) {
+ if (checkAndSetOption(pasteFileOptionString(), m_inputFilePath))
+ continue;
+ if (checkAndSetOption(pasteProtocolOptionString(), m_protocol)) {
+ if (!m_availableProtocols.contains(m_protocol))
+ throw ArgumentErrorException(QString::fromLatin1("Unknown protocol \"%1\"").arg(m_protocol));
+ continue;
+ }
+ throw ArgumentErrorException(QString::fromLatin1("Invalid option \"%1\" for request \"%2\"")
+ .arg(m_arguments.first(), pasteRequestString()));
+ }
+
+ if (m_protocol.isEmpty())
+ throw ArgumentErrorException(QLatin1String("No protocol given"));
+}
+
+bool ArgumentsCollector::checkAndSetOption(const QString &optionString, QString &optionValue)
+{
+ if (m_arguments.first() != optionString)
+ return false;
+
+ if (!optionValue.isEmpty())
+ throw ArgumentErrorException(QString::fromLatin1("option \"%1\" was given twice").arg(optionString));
+ m_arguments.removeFirst();
+ if (m_arguments.isEmpty()) {
+ throw ArgumentErrorException(QString::fromLatin1("Option \"%1\" requires an argument")
+ .arg(optionString));
+ }
+ optionValue = m_arguments.takeFirst();
+ return true;
+}
diff --git a/src/plugins/cpaster/frontend/argumentscollector.h b/src/plugins/cpaster/frontend/argumentscollector.h
new file mode 100644
index 0000000000..83ddfb7eab
--- /dev/null
+++ b/src/plugins/cpaster/frontend/argumentscollector.h
@@ -0,0 +1,64 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef ARGUMENTSCOLLECTOR_H
+#define ARGUMENTSCOLLECTOR_H
+
+#include <QStringList>
+
+class ArgumentsCollector
+{
+public:
+ ArgumentsCollector(const QStringList &availableProtocols);
+ bool collect(const QStringList &args); // Application is already removed.
+
+ enum RequestType { RequestTypeHelp, RequestTypeListProtocols, RequestTypePaste };
+ RequestType requestType() const { return m_requestType; }
+
+ QString errorString() const { return m_errorString; }
+ QString usageString() const;
+
+ // These are valid <=> requestType() == RequestTypePaste
+ QString inputFilePath() const { return m_inputFilePath; }
+ QString protocol() const { return m_protocol; }
+
+private:
+ void setRequest();
+ void setPasteOptions();
+ bool checkAndSetOption(const QString &optionString, QString &optionValue);
+
+ const QStringList m_availableProtocols;
+ QStringList m_arguments;
+ RequestType m_requestType;
+ QString m_inputFilePath;
+ QString m_protocol;
+ QString m_errorString;
+};
+
+#endif // ARGUMENTSCOLLECTOR_H
diff --git a/src/plugins/cpaster/frontend/frontend.pro b/src/plugins/cpaster/frontend/frontend.pro
new file mode 100644
index 0000000000..e38780c4da
--- /dev/null
+++ b/src/plugins/cpaster/frontend/frontend.pro
@@ -0,0 +1,30 @@
+TEMPLATE = app
+TARGET=cpaster
+
+include(../../../../qtcreator.pri)
+include(../../../rpath.pri)
+include(../../../plugins/coreplugin/coreplugin.pri)
+
+CONFIG += console
+QT += network
+
+LIBS *= -L$$IDE_PLUGIN_PATH/QtProject
+QMAKE_RPATHDIR *= $$IDE_PLUGIN_PATH/QtProject
+
+DESTDIR=$$IDE_APP_PATH
+
+HEADERS = ../protocol.h \
+ ../cpasterconstants.h \
+ ../pastebindotcomprotocol.h \
+ ../pastebindotcaprotocol.h \
+ ../kdepasteprotocol.h \
+ ../urlopenprotocol.h \
+ argumentscollector.h
+
+SOURCES += ../protocol.cpp \
+ ../pastebindotcomprotocol.cpp \
+ ../pastebindotcaprotocol.cpp \
+ ../kdepasteprotocol.cpp \
+ ../urlopenprotocol.cpp \
+ argumentscollector.cpp \
+ main.cpp
diff --git a/src/plugins/cpaster/frontend/frontend.qbs b/src/plugins/cpaster/frontend/frontend.qbs
new file mode 100644
index 0000000000..100bbbbe5d
--- /dev/null
+++ b/src/plugins/cpaster/frontend/frontend.qbs
@@ -0,0 +1,30 @@
+import qbs.base 1.0
+import "../../../tools/QtcTool.qbs" as QtcTool
+
+QtcTool {
+ name: "cpaster"
+
+ Depends { name: "cpp" }
+ Depends {
+ name: "Qt"
+ submodules: "core", "gui", "network"
+ }
+ Depends { name: "Core" }
+
+ cpp.includePaths: ["../../"]
+ cpp.rpaths: [
+ "$ORIGIN/../lib/qtcreator",
+ "$ORIGIN/../lib/qtcreator/plugins",
+ "$ORIGIN/../lib/qtcreator/plugins/QtProject"
+ ]
+
+ files: [ "main.cpp",
+ "argumentscollector.h", "argumentscollector.cpp",
+ "../cpasterconstants.h",
+ "../kdepasteprotocol.h", "../kdepasteprotocol.cpp",
+ "../pastebindotcaprotocol.h", "../pastebindotcaprotocol.cpp",
+ "../pastebindotcomprotocol.h", "../pastebindotcomprotocol.cpp",
+ "../protocol.h", "../protocol.cpp",
+ "../urlopenprotocol.h", "../urlopenprotocol.cpp",
+ ]
+}
diff --git a/src/plugins/cpaster/frontend/main.cpp b/src/plugins/cpaster/frontend/main.cpp
new file mode 100644
index 0000000000..11b8f8f9f4
--- /dev/null
+++ b/src/plugins/cpaster/frontend/main.cpp
@@ -0,0 +1,128 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "argumentscollector.h"
+#include "../kdepasteprotocol.h"
+#include "../pastebindotcaprotocol.h"
+#include "../pastebindotcomprotocol.h"
+
+#include <QFile>
+#include <QObject>
+#include <QTimer>
+#include <QCoreApplication>
+
+#include <cstdio>
+#include <cstdlib>
+#include <iostream>
+
+using namespace CodePaster;
+
+class PasteReceiver : public QObject
+{
+ Q_OBJECT
+public:
+ PasteReceiver(const QString &protocol, const QString &filePath) : m_filePath(filePath)
+ {
+ const QSharedPointer<NetworkAccessManagerProxy> accessMgr(new NetworkAccessManagerProxy);
+ if (protocol == KdePasteProtocol::protocolName().toLower())
+ m_protocol.reset(new KdePasteProtocol(accessMgr));
+ else if (protocol == PasteBinDotCaProtocol::protocolName().toLower())
+ m_protocol.reset(new PasteBinDotCaProtocol(accessMgr));
+ else if (protocol == PasteBinDotComProtocol::protocolName().toLower())
+ m_protocol.reset(new PasteBinDotComProtocol(accessMgr));
+ else
+ qFatal("Internal error: Invalid protocol.");
+ }
+
+public slots:
+ void paste()
+ {
+ QFile file(m_filePath);
+ const bool success = m_filePath.isEmpty()
+ ? file.open(stdin, QIODevice::ReadOnly) : file.open(QIODevice::ReadOnly);
+ if (!success) {
+ std::cerr << "Error: Failed to open file to paste from." << std::endl;
+ qApp->exit(EXIT_FAILURE);
+ return;
+ }
+ const QString content = QString::fromLocal8Bit(file.readAll());
+ if (content.isEmpty()) {
+ std::cerr << "Empty input, aborting." << std::endl;
+ qApp->exit(EXIT_FAILURE);
+ return;
+ }
+ connect(m_protocol.data(), SIGNAL(pasteDone(QString)), SLOT(handlePasteDone(QString)));
+ m_protocol->paste(content);
+ }
+
+private slots:
+ void handlePasteDone(const QString &link)
+ {
+ std::cout << qPrintable(link) << std::endl;
+ qApp->quit();
+ }
+
+private:
+ const QString m_filePath;
+ QScopedPointer<Protocol> m_protocol;
+};
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication app(argc, argv);
+
+ const QStringList protocols = QStringList() << KdePasteProtocol::protocolName().toLower()
+ << PasteBinDotCaProtocol::protocolName().toLower()
+ << PasteBinDotComProtocol::protocolName().toLower();
+ ArgumentsCollector argsCollector(protocols);
+ QStringList arguments = QCoreApplication::arguments();
+ arguments.removeFirst();
+ if (!argsCollector.collect(arguments)) {
+ std::cerr << "Error: " << qPrintable(argsCollector.errorString()) << '.' << std::endl
+ << qPrintable(argsCollector.usageString()) << std::endl;
+ return EXIT_FAILURE;
+ }
+
+ switch (argsCollector.requestType()) {
+ case ArgumentsCollector::RequestTypeHelp:
+ std::cout << qPrintable(argsCollector.usageString()) << std::endl;
+ return EXIT_SUCCESS;
+ case ArgumentsCollector::RequestTypeListProtocols:
+ foreach (const QString &protocol, protocols)
+ std::cout << qPrintable(protocol) << std::endl;
+ return EXIT_SUCCESS;
+ case ArgumentsCollector::RequestTypePaste: {
+ PasteReceiver pr(argsCollector.protocol(), argsCollector.inputFilePath());
+ QTimer::singleShot(0, &pr, SLOT(paste()));
+ return app.exec();
+ }
+ }
+}
+
+#include "main.moc"
diff --git a/src/plugins/cpaster/kdepasteprotocol.cpp b/src/plugins/cpaster/kdepasteprotocol.cpp
index c0e5f08257..468146de2d 100644
--- a/src/plugins/cpaster/kdepasteprotocol.cpp
+++ b/src/plugins/cpaster/kdepasteprotocol.cpp
@@ -146,11 +146,10 @@ void KdePasteProtocol::pasteFinished()
// Parse id from '<result><id>143204</id><hash></hash></result>'
// No useful error reports have been observed.
const QString id = parseElement(m_pasteReply, QLatin1String("id"));
- if (id.isEmpty()) {
+ if (id.isEmpty())
qWarning("%s protocol error: Could not send entry.", qPrintable(protocolName()));
- } else {
+ else
emit pasteDone(QLatin1String(hostUrlC) + id);
- }
}
m_pasteReply->deleteLater();
diff --git a/src/plugins/cpaster/pastebindotcaprotocol.cpp b/src/plugins/cpaster/pastebindotcaprotocol.cpp
index d510350b70..ac62c7e3d9 100644
--- a/src/plugins/cpaster/pastebindotcaprotocol.cpp
+++ b/src/plugins/cpaster/pastebindotcaprotocol.cpp
@@ -118,7 +118,7 @@ void PasteBinDotCaProtocol::pasteFinished()
} else {
/// returns ""SUCCESS:[id]""
const QByteArray data = m_pasteReply->readAll();
- const QString link = QString::fromLatin1(urlC) + QString::fromAscii(data).remove(QLatin1String("SUCCESS:"));
+ const QString link = QString::fromLatin1(urlC) + QString::fromLatin1(data).remove(QLatin1String("SUCCESS:"));
emit pasteDone(link);
}
m_pasteReply->deleteLater();
@@ -193,7 +193,7 @@ static inline QStringList parseLists(QIODevice *io)
QXmlStreamReader reader(data);
State state = OutsideRecentLink;
while (!reader.atEnd()) {
- switch(reader.readNext()) {
+ switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
// Inside a <div> of an entry: Anchor or description
if (state == InsideRecentLink && reader.name() == anchorElement) { // Anchor
@@ -218,11 +218,10 @@ static inline QStringList parseLists(QIODevice *io)
void PasteBinDotCaProtocol::listFinished()
{
const bool error = m_listReply->error();
- if (error) {
+ if (error)
qWarning("pastebin.ca list failed: %s", qPrintable(m_listReply->errorString()));
- } else {
+ else
emit listDone(name(), parseLists(m_listReply));
- }
m_listReply->deleteLater();
m_listReply = 0;
}
diff --git a/src/plugins/cpaster/pastebindotcaprotocol.h b/src/plugins/cpaster/pastebindotcaprotocol.h
index 37287054f0..9910d32872 100644
--- a/src/plugins/cpaster/pastebindotcaprotocol.h
+++ b/src/plugins/cpaster/pastebindotcaprotocol.h
@@ -38,7 +38,9 @@ class PasteBinDotCaProtocol : public NetworkProtocol
Q_OBJECT
public:
explicit PasteBinDotCaProtocol(const NetworkAccessManagerProxyPtr &nw);
- QString name() const { return QLatin1String("Pastebin.Ca"); }
+
+ static QString protocolName() { return QLatin1String("Pastebin.Ca"); }
+ QString name() const { return protocolName(); }
virtual bool hasSettings() const { return false; }
virtual unsigned capabilities() const;
diff --git a/src/plugins/cpaster/pastebindotcomprotocol.cpp b/src/plugins/cpaster/pastebindotcomprotocol.cpp
index 1dc9fe00ae..32462ea60c 100644
--- a/src/plugins/cpaster/pastebindotcomprotocol.cpp
+++ b/src/plugins/cpaster/pastebindotcomprotocol.cpp
@@ -131,11 +131,10 @@ void PasteBinDotComProtocol::paste(const QString &text,
void PasteBinDotComProtocol::pasteFinished()
{
- if (m_pasteReply->error()) {
+ if (m_pasteReply->error())
qWarning("Pastebin.com protocol error: %s", qPrintable(m_pasteReply->errorString()));
- } else {
- emit pasteDone(QString::fromAscii(m_pasteReply->readAll()));
- }
+ else
+ emit pasteDone(QString::fromLatin1(m_pasteReply->readAll()));
m_pasteReply->deleteLater();
m_pasteReply = 0;
@@ -171,7 +170,7 @@ void PasteBinDotComProtocol::fetchFinished()
qDebug() << "fetchFinished: error" << m_fetchId << content;
} else {
title = QString::fromLatin1("Pastebin.com: %1").arg(m_fetchId);
- content = QString::fromAscii(m_fetchReply->readAll());
+ content = QString::fromLatin1(m_fetchReply->readAll());
// Cut out from '<pre>' formatting
const int preEnd = content.lastIndexOf(QLatin1String("</pre>"));
if (preEnd != -1)
@@ -325,7 +324,7 @@ static inline QStringList parseLists(QIODevice *io)
QString age;
while (!reader.atEnd()) {
- switch(reader.readNext()) {
+ switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
state = nextOpeningState(state, reader);
switch (state) {
diff --git a/src/plugins/cpaster/pasteselectdialog.cpp b/src/plugins/cpaster/pasteselectdialog.cpp
index 0e7b63e09d..0dae03e853 100644
--- a/src/plugins/cpaster/pasteselectdialog.cpp
+++ b/src/plugins/cpaster/pasteselectdialog.cpp
@@ -30,6 +30,7 @@
#include "pasteselectdialog.h"
#include "protocol.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -43,7 +44,7 @@ PasteSelectDialog::PasteSelectDialog(const QList<Protocol*> &protocols,
m_protocols(protocols)
{
m_ui.setupUi(this);
- foreach(const Protocol *protocol, protocols) {
+ foreach (const Protocol *protocol, protocols) {
m_ui.protocolBox->addItem(protocol->name());
connect(protocol, SIGNAL(listDone(QString,QStringList)),
this, SLOT(listDone(QString,QStringList)));
@@ -55,9 +56,8 @@ PasteSelectDialog::PasteSelectDialog(const QList<Protocol*> &protocols,
connect(m_refreshButton, SIGNAL(clicked()), this, SLOT(list()));
m_ui.listWidget->setSelectionMode(QAbstractItemView::SingleSelection);
-#ifndef Q_OS_MACX
- m_ui.listWidget->setFrameStyle(QFrame::NoFrame);
-#endif // Q_OS_MACX
+ if (!Utils::HostOsInfo::isMacHost())
+ m_ui.listWidget->setFrameStyle(QFrame::NoFrame);
// Proportional formatting of columns for CodePaster
QFont listFont = m_ui.listWidget->font();
listFont.setFamily(QLatin1String("Courier"));
diff --git a/src/plugins/cpaster/pasteview.cpp b/src/plugins/cpaster/pasteview.cpp
index f004b5ac85..13d0d874a9 100644
--- a/src/plugins/cpaster/pasteview.cpp
+++ b/src/plugins/cpaster/pasteview.cpp
@@ -59,7 +59,7 @@ PasteView::PasteView(const QList<Protocol *> protocols,
m_ui.buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Paste"));
connect(m_ui.uiPatchList, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(contentChanged()));
- foreach(const Protocol *p, protocols)
+ foreach (const Protocol *p, protocols)
m_ui.protocolBox->addItem(p->name());
connect(m_ui.protocolBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(protocolChanged(int)));
@@ -207,11 +207,10 @@ void PasteView::setProtocol(const QString &protocol)
{
const int index = m_ui.protocolBox->findText(protocol);
m_ui.protocolBox->setCurrentIndex(index);
- if (index == m_ui.protocolBox->currentIndex()) {
+ if (index == m_ui.protocolBox->currentIndex())
protocolChanged(index); // Force enabling
- } else {
+ else
m_ui.protocolBox->setCurrentIndex(index);
- }
}
} //namespace CodePaster
diff --git a/src/plugins/cpaster/protocol.cpp b/src/plugins/cpaster/protocol.cpp
index c9d5eb3e85..48e7044b07 100644
--- a/src/plugins/cpaster/protocol.cpp
+++ b/src/plugins/cpaster/protocol.cpp
@@ -96,6 +96,8 @@ Protocol::ContentType Protocol::contentType(const QString &mt)
|| mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
return Cpp;
if (mt == QLatin1String(QmlJSTools::Constants::QML_MIMETYPE)
+ || mt == QLatin1String(QmlJSTools::Constants::QMLPROJECT_MIMETYPE)
+ || mt == QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE)
|| mt == QLatin1String(QmlJSTools::Constants::JS_MIMETYPE)
|| mt == QLatin1String(QmlJSTools::Constants::JSON_MIMETYPE))
return JavaScript;
@@ -169,8 +171,7 @@ bool Protocol::showConfigurationError(const Protocol *p,
bool rc = false;
if (mb.clickedButton() == settingsButton)
rc = Core::ICore::showOptionsDialog(p->settingsPage()->category(),
- p->settingsPage()->id(),
- parent);
+ p->settingsPage()->id(), parent);
return rc;
}
diff --git a/src/plugins/cpaster/settings.cpp b/src/plugins/cpaster/settings.cpp
index 906e5d848e..e9c228308c 100644
--- a/src/plugins/cpaster/settings.cpp
+++ b/src/plugins/cpaster/settings.cpp
@@ -30,6 +30,8 @@
#include "settings.h"
#include "pastebindotcomprotocol.h"
+#include <utils/environment.h>
+
#include <QVariant>
#include <QSettings>
@@ -64,11 +66,7 @@ void Settings::toSettings(QSettings *settings) const
void Settings::fromSettings(const QSettings *settings)
{
const QString rootKey = QLatin1String(groupC) + QLatin1Char('/');
-#ifdef Q_OS_WIN
- const QString defaultUser = QString::fromLocal8Bit(qgetenv("USERNAME"));
-#else
- const QString defaultUser = QString::fromLocal8Bit(qgetenv("USER"));
-#endif
+ const QString defaultUser = Utils::Environment::systemEnvironment().userName();
username = settings->value(rootKey + QLatin1String(userNameKeyC), defaultUser).toString();
protocol = settings->value(rootKey + QLatin1String(defaultProtocolKeyC), PasteBinDotComProtocol::protocolName()).toString();
copyToClipboard = settings->value(rootKey + QLatin1String(copyToClipboardKeyC), true).toBool();
diff --git a/src/plugins/cpaster/settingspage.cpp b/src/plugins/cpaster/settingspage.cpp
index e3d1f9fe15..983646a5cd 100644
--- a/src/plugins/cpaster/settingspage.cpp
+++ b/src/plugins/cpaster/settingspage.cpp
@@ -78,9 +78,9 @@ Settings SettingsWidget::settings()
SettingsPage::SettingsPage(const QSharedPointer<Settings> &settings) :
m_settings(settings), m_widget(0)
{
- setId(QLatin1String("A.General"));
+ setId("A.General");
setDisplayName(tr("General"));
- setCategory(QLatin1String(Constants::CPASTER_SETTINGS_CATEGORY));
+ setCategory(Constants::CPASTER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("CodePaster",
Constants::CPASTER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CPASTER_ICON));
diff --git a/src/plugins/cpaster/urlopenprotocol.cpp b/src/plugins/cpaster/urlopenprotocol.cpp
index 5b7a2958a6..f06a7afb7a 100644
--- a/src/plugins/cpaster/urlopenprotocol.cpp
+++ b/src/plugins/cpaster/urlopenprotocol.cpp
@@ -63,11 +63,10 @@ void UrlOpenProtocol::fetchFinished()
const QString title = m_fetchReply->url().toString();
QString content;
const bool error = m_fetchReply->error();
- if (error) {
+ if (error)
content = m_fetchReply->errorString();
- } else {
+ else
content = QString::fromUtf8(m_fetchReply->readAll());
- }
m_fetchReply->deleteLater();
m_fetchReply = 0;
emit fetchDone(title, content, error);
diff --git a/src/plugins/cppeditor/cppclasswizard.cpp b/src/plugins/cppeditor/cppclasswizard.cpp
index f1a8acee15..0893ed4595 100644
--- a/src/plugins/cppeditor/cppclasswizard.cpp
+++ b/src/plugins/cppeditor/cppclasswizard.cpp
@@ -70,7 +70,8 @@ ClassNamePage::ClassNamePage(QWidget *parent) :
<< QLatin1String("QObject")
<< QLatin1String("QWidget")
<< QLatin1String("QMainWindow")
- << QLatin1String("QDeclarativeItem"));
+ << QLatin1String("QDeclarativeItem")
+ << QLatin1String("QQuickItem"));
m_newClassWidget->setBaseClassEditable(true);
m_newClassWidget->setFormInputVisible(false);
m_newClassWidget->setNamespacesEnabled(true);
@@ -237,7 +238,7 @@ bool CppClassWizard::generateHeaderAndSource(const CppClassWizardParameters &par
// class in case the user did not specify one.
QString parentQObjectClass;
bool defineQObjectMacro = false;
- switch(params.classType) {
+ switch (params.classType) {
case Utils::NewClassWidget::ClassInheritsQObject:
parentQObjectClass = QLatin1String("QObject");
defineQObjectMacro = true;
@@ -250,6 +251,10 @@ bool CppClassWizard::generateHeaderAndSource(const CppClassWizardParameters &par
parentQObjectClass = QLatin1String("QDeclarativeItem");
defineQObjectMacro = true;
break;
+ case Utils::NewClassWidget::ClassInheritsQQuickItem:
+ parentQObjectClass = QLatin1String("QQuickItem");
+ defineQObjectMacro = true;
+ break;
case Utils::NewClassWidget::NoClassType:
case Utils::NewClassWidget::SharedDataClass:
break;
diff --git a/src/plugins/cppeditor/cppcompleteswitch.cpp b/src/plugins/cppeditor/cppcompleteswitch.cpp
index 82c01c067c..c2d1ca1310 100644
--- a/src/plugins/cppeditor/cppcompleteswitch.cpp
+++ b/src/plugins/cppeditor/cppcompleteswitch.cpp
@@ -46,6 +46,7 @@ using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
+using namespace TextEditor;
using namespace Utils;
namespace {
@@ -79,7 +80,7 @@ public:
scope);
if (!candidates .isEmpty() && candidates.first().declaration()) {
Symbol *decl = candidates.first().declaration();
- values << prettyPrint(LookupContext::fullyQualifiedName(decl));
+ values << prettyPrint.prettyName(LookupContext::fullyQualifiedName(decl));
}
}
return true;
@@ -112,10 +113,11 @@ public:
"Complete Switch Statement"));
}
-
- virtual void performChanges(const CppRefactoringFilePtr &currentFile,
- const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
int start = currentFile->endOf(compoundStatement->lbrace_token);
changes.insert(start, QLatin1String("\ncase ")
@@ -130,8 +132,9 @@ public:
QStringList values;
};
-static Enum *findEnum(const QList<LookupItem> &results,
- const LookupContext &ctxt)
+} // end of anonymous namespace
+
+static Enum *findEnum(const QList<LookupItem> &results, const LookupContext &ctxt)
{
foreach (const LookupItem &result, results) {
const FullySpecifiedType fst = result.type();
@@ -153,8 +156,7 @@ static Enum *findEnum(const QList<LookupItem> &results,
return 0;
}
-static Enum *conditionEnum(const QSharedPointer<const CppEditor::Internal::CppQuickFixAssistInterface> &interface,
- SwitchStatementAST *statement)
+static Enum *conditionEnum(const CppQuickFixInterface &interface, SwitchStatementAST *statement)
{
Block *block = statement->symbol;
Scope *scope = interface->semanticInfo().doc->scopeAt(block->line(), block->column());
@@ -167,15 +169,12 @@ static Enum *conditionEnum(const QSharedPointer<const CppEditor::Internal::CppQu
return findEnum(results, typeOfExpression.context());
}
-} // end of anonymous namespace
-
-QList<CppQuickFixOperation::Ptr> CompleteSwitchCaseStatement::match(
- const QSharedPointer<const CppEditor::Internal::CppQuickFixAssistInterface> &interface)
+void CompleteSwitchCaseStatement::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
if (path.isEmpty())
- return noResult(); // nothing to do
+ return;
// look for switch statement
for (int depth = path.size() - 1; depth >= 0; --depth) {
@@ -183,19 +182,18 @@ QList<CppQuickFixOperation::Ptr> CompleteSwitchCaseStatement::match(
SwitchStatementAST *switchStatement = ast->asSwitchStatement();
if (switchStatement) {
if (!interface->isCursorOn(switchStatement->switch_token) || !switchStatement->statement)
- return noResult();
+ return;
CompoundStatementAST *compoundStatement = switchStatement->statement->asCompoundStatement();
if (!compoundStatement) // we ignore pathologic case "switch (t) case A: ;"
- return noResult();
+ return;
// look if the condition's type is an enum
if (Enum *e = conditionEnum(interface, switchStatement)) {
// check the possible enum values
QStringList values;
Overview prettyPrint;
for (unsigned i = 0; i < e->memberCount(); ++i) {
- if (Declaration *decl = e->memberAt(i)->asDeclaration()) {
- values << prettyPrint(LookupContext::fullyQualifiedName(decl));
- }
+ if (Declaration *decl = e->memberAt(i)->asDeclaration())
+ values << prettyPrint.prettyName(LookupContext::fullyQualifiedName(decl));
}
// Get the used values
Block *block = switchStatement->symbol;
@@ -205,15 +203,12 @@ QList<CppQuickFixOperation::Ptr> CompleteSwitchCaseStatement::match(
// save the values that would be added
foreach (const QString &usedValue, usedValues)
values.removeAll(usedValue);
- if (values.isEmpty())
- return noResult();
- else
- return singleResult(new Operation(interface, depth, compoundStatement, values));
+ if (!values.isEmpty())
+ result.append(CppQuickFixOperation::Ptr(new Operation(interface, depth, compoundStatement, values)));
+ return;
}
- return noResult();
+ return;
}
}
-
- return noResult();
}
diff --git a/src/plugins/cppeditor/cppcompleteswitch.h b/src/plugins/cppeditor/cppcompleteswitch.h
index 258c7bfd06..9fca8a0d16 100644
--- a/src/plugins/cppeditor/cppcompleteswitch.h
+++ b/src/plugins/cppeditor/cppcompleteswitch.h
@@ -32,8 +32,6 @@
#include "cppquickfix.h"
-#include <CPlusPlusForwardDeclarations.h>
-
namespace CppEditor {
namespace Internal {
@@ -43,8 +41,7 @@ namespace Internal {
class CompleteSwitchCaseStatement: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(
- const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface);
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppeditor.cpp b/src/plugins/cppeditor/cppeditor.cpp
index 6a34b66b6a..dd02128e16 100644
--- a/src/plugins/cppeditor/cppeditor.cpp
+++ b/src/plugins/cppeditor/cppeditor.cpp
@@ -819,9 +819,10 @@ static QList<int> lazyFindReferences(Scope *scope, QString code, Document::Ptr d
TypeOfExpression typeOfExpression;
snapshot.insert(doc);
typeOfExpression.init(doc, snapshot);
- if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression)) {
+ // make possible to instantiate templates
+ typeOfExpression.setExpandTemplates(true);
+ if (Symbol *canonicalSymbol = CanonicalSymbol::canonicalSymbol(scope, code, typeOfExpression))
return CppModelManagerInterface::instance()->references(canonicalSymbol, typeOfExpression.context());
- }
return QList<int>();
}
@@ -832,19 +833,55 @@ void CPPEditorWidget::markSymbols(const QTextCursor &tc, const SemanticInfo &inf
if (! info.doc)
return;
- CanonicalSymbol cs(this, info);
- QString expression;
- if (Scope *scope = cs.getScopeAndExpression(this, info, tc, &expression)) {
- m_references.cancel();
- m_referencesRevision = info.revision;
- m_referencesCursorPosition = position();
- m_references = QtConcurrent::run(&lazyFindReferences, scope, expression, info.doc, info.snapshot);
- m_referencesWatcher.setFuture(m_references);
- } else {
- const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection);
+ if (const Macro *macro = findCanonicalMacro(textCursor(), info.doc)) {
+ QList<QTextEdit::ExtraSelection> selections;
+
+ //Macro definition
+ if (macro->fileName() == info.doc->fileName()) {
+ QTextCursor cursor(document());
+ cursor.setPosition(macro->offset());
+ cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, macro->name().length());
+
+ QTextEdit::ExtraSelection sel;
+ sel.format = m_occurrencesFormat;
+ sel.cursor = cursor;
+ selections.append(sel);
+ }
+
+ //Other macro uses
+ foreach (Document::MacroUse use, info.doc->macroUses()) {
+ if (use.macro().line() != macro->line()
+ || use.macro().offset() != macro->offset()
+ || use.macro().length() != macro->length()
+ || use.macro().fileName() != macro->fileName())
+ continue;
- if (! selections.isEmpty())
- setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>());
+ QTextCursor cursor(document());
+ cursor.setPosition(use.begin());
+ cursor.setPosition(use.end(), QTextCursor::KeepAnchor);
+
+ QTextEdit::ExtraSelection sel;
+ sel.format = m_occurrencesFormat;
+ sel.cursor = cursor;
+ selections.append(sel);
+ }
+
+ setExtraSelections(CodeSemanticsSelection, selections);
+ } else {
+ CanonicalSymbol cs(this, info);
+ QString expression;
+ if (Scope *scope = cs.getScopeAndExpression(this, info, tc, &expression)) {
+ m_references.cancel();
+ m_referencesRevision = info.revision;
+ m_referencesCursorPosition = position();
+ m_references = QtConcurrent::run(&lazyFindReferences, scope, expression, info.doc, info.snapshot);
+ m_referencesWatcher.setFuture(m_references);
+ } else {
+ const QList<QTextEdit::ExtraSelection> selections = extraSelections(CodeSemanticsSelection);
+
+ if (! selections.isEmpty())
+ setExtraSelections(CodeSemanticsSelection, QList<QTextEdit::ExtraSelection>());
+ }
}
}
@@ -1109,6 +1146,8 @@ void CPPEditorWidget::switchDeclarationDefinition()
if (! function)
function = lastVisibleSymbol->enclosingFunction();
+ Core::EditorManager* editorManager = Core::EditorManager::instance();
+
if (function) {
LookupContext context(thisDocument, snapshot);
@@ -1129,12 +1168,61 @@ void CPPEditorWidget::switchDeclarationDefinition()
}
}
}
- if (! best.isEmpty())
- openCppEditorAt(linkToSymbol(best.first()));
+ if (! best.isEmpty()) {
+ Core::IEditor *editor = editorManager->currentEditor();
+ CPPEditorWidget::Link symbolLink = linkToSymbol(best.first());
+ if (editorManager->hasSplitter()) {
+ if (forceOpenLinksInNextSplit()) {
+ editorManager->gotoOtherSplit();
+ } else if (openLinksInNextSplit()) {
+ bool isVisible = false;
+ foreach (Core::IEditor *visEditor, editorManager->visibleEditors()) {
+ if (visEditor->document() &&
+ (symbolLink.fileName == visEditor->document()->fileName()) &&
+ (visEditor != editor)) {
+ isVisible = true;
+ editorManager->activateEditor(visEditor);
+ break;
+ }
+ }
+
+ if (!isVisible)
+ editorManager->gotoOtherSplit();
+ } else {
+ editorManager->addCurrentPositionToNavigationHistory();
+ }
+ }
+ openCppEditorAt(symbolLink);
+ }
} else if (lastVisibleSymbol && lastVisibleSymbol->isDeclaration() && lastVisibleSymbol->type()->isFunctionType()) {
- if (Symbol *def = symbolFinder()->findMatchingDefinition(lastVisibleSymbol, snapshot, true))
- openCppEditorAt(linkToSymbol(def));
+ if (Symbol *def = symbolFinder()->findMatchingDefinition(lastVisibleSymbol, snapshot)) {
+ Core::IEditor *editor = editorManager->currentEditor();
+ CPPEditorWidget::Link symbolLink = linkToSymbol(def);
+ if (editorManager->hasSplitter() && (editor->document()->fileName() != symbolLink.fileName)) {
+ if (forceOpenLinksInNextSplit()) {
+ editorManager->gotoOtherSplit();
+ } else if (openLinksInNextSplit()) {
+ bool isVisible = false;
+ foreach (Core::IEditor *visEditor, editorManager->visibleEditors()) {
+ if (visEditor->document() &&
+ (symbolLink.fileName == visEditor->document()->fileName()) &&
+ (visEditor != editor)) {
+ isVisible = true;
+ editorManager->activateEditor(visEditor);
+ break;
+ }
+ }
+
+ if (!isVisible)
+ editorManager->gotoOtherSplit();
+ } else {
+ editorManager->addCurrentPositionToNavigationHistory();
+ }
+ }
+
+ openCppEditorAt(symbolLink);
+ }
}
}
}
@@ -1436,7 +1524,7 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor,
return link; //already on definition!
} else {
const Document::MacroUse *use = doc->findMacroUseAt(endOfToken - 1);
- if (use && use->macro().fileName() != QLatin1String("<configuration>")) {
+ if (use && use->macro().fileName() != CppModelManagerInterface::configurationFileName()) {
const Macro &macro = use->macro();
link.fileName = macro.fileName();
link.line = macro.line();
@@ -1462,9 +1550,8 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor,
else {
if (ch == QLatin1Char('(') && ! expression.isEmpty()) {
tc.setPosition(pos);
- if (TextEditor::TextBlockUserData::findNextClosingParenthesis(&tc, true)) {
+ if (TextEditor::TextBlockUserData::findNextClosingParenthesis(&tc, true))
expression.append(tc.selectedText());
- }
}
break;
@@ -1473,6 +1560,8 @@ CPPEditorWidget::Link CPPEditorWidget::findLinkAt(const QTextCursor &cursor,
TypeOfExpression typeOfExpression;
typeOfExpression.init(doc, snapshot);
+ // make possible to instantiate templates
+ typeOfExpression.setExpandTemplates(true);
const QList<LookupItem> resolvedSymbols =
typeOfExpression.reference(expression.toUtf8(), scope, TypeOfExpression::Preprocess);
@@ -1745,7 +1834,7 @@ Core::IEditor *CPPEditor::duplicate(QWidget *parent)
Core::Id CPPEditor::id() const
{
- return CppEditor::Constants::CPPEDITOR_ID;
+ return Core::Id(CppEditor::Constants::CPPEDITOR_ID);
}
bool CPPEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
@@ -2124,7 +2213,7 @@ void SemanticHighlighter::run()
SemanticInfo SemanticHighlighter::semanticInfo(const Source &source)
{
SemanticInfo semanticInfo;
- semanticInfo.revision = source.revision;
+ semanticInfo.revision = m_lastSemanticInfo.revision;
semanticInfo.forced = source.force;
m_mutex.lock();
@@ -2164,6 +2253,7 @@ SemanticInfo SemanticHighlighter::semanticInfo(const Source &source)
DeclarationAST *currentFunctionDefinition = functionDefinitionUnderCursor(ast, source.line, source.column);
const LocalSymbols useTable(semanticInfo.doc, currentFunctionDefinition);
+ semanticInfo.revision = source.revision;
semanticInfo.localUses = useTable.uses;
semanticInfo.hasQ = useTable.hasQ;
semanticInfo.hasD = useTable.hasD;
@@ -2245,10 +2335,12 @@ void CPPEditorWidget::updateFunctionDeclDefLink()
const int pos = textCursor().selectionStart();
// if there's already a link, abort it if the cursor is outside or the name changed
+ // (adding a prefix is an exception since the user might type a return type)
if (m_declDefLink
&& (pos < m_declDefLink->linkSelection.selectionStart()
|| pos > m_declDefLink->linkSelection.selectionEnd()
- || m_declDefLink->nameSelection.selectedText() != m_declDefLink->nameInitial)) {
+ || !m_declDefLink->nameSelection.selectedText().trimmed()
+ .endsWith(m_declDefLink->nameInitial))) {
abortDeclDefLink();
return;
}
diff --git a/src/plugins/cppeditor/cppeditor.pro b/src/plugins/cppeditor/cppeditor.pro
index 5fc351a3b6..604246173b 100644
--- a/src/plugins/cppeditor/cppeditor.pro
+++ b/src/plugins/cppeditor/cppeditor.pro
@@ -46,4 +46,9 @@ SOURCES += cppplugin.cpp \
RESOURCES += cppeditor.qrc
OTHER_FILES += CppEditor.mimetypes.xml
+equals(TEST, 1) {
+ SOURCES += \
+ cppquickfix_test.cpp
+ DEFINES += SRCDIR=\\\"$$PWD\\\"
+}
diff --git a/src/plugins/cppeditor/cppeditor.qbs b/src/plugins/cppeditor/cppeditor.qbs
index 8b9295c940..7f92612944 100644
--- a/src/plugins/cppeditor/cppeditor.qbs
+++ b/src/plugins/cppeditor/cppeditor.qbs
@@ -1,6 +1,8 @@
import qbs.base 1.0
+import qbs.fileinfo as FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
+import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "CppEditor"
@@ -12,16 +14,11 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "ProjectExplorer" }
Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- "../../libs/3rdparty",
- buildDirectory
- ]
+
+ cpp.includePaths: base.concat("../../libs/3rdparty")
files: [
"CppEditor.mimetypes.xml",
- "cppeditor.qrc",
"cppautocompleter.cpp",
"cppautocompleter.h",
"cppclasswizard.cpp",
@@ -30,6 +27,7 @@ QtcPlugin {
"cppcompleteswitch.h",
"cppeditor.cpp",
"cppeditor.h",
+ "cppeditor.qrc",
"cppeditor_global.h",
"cppeditorconstants.h",
"cppeditorenums.h",
@@ -59,7 +57,15 @@ QtcPlugin {
"cppsnippetprovider.cpp",
"cppsnippetprovider.h",
"cpptypehierarchy.cpp",
- "cpptypehierarchy.h"
+ "cpptypehierarchy.h",
]
-}
+ Group {
+ condition: Defaults.testsEnabled(qbs)
+ files: [
+ "cppquickfix_test.cpp"
+ ]
+
+ cpp.defines: outer.concat(['SRCDIR="' + FileInfo.path(filePath) + '"'])
+ }
+}
diff --git a/src/plugins/cppeditor/cppelementevaluator.cpp b/src/plugins/cppeditor/cppelementevaluator.cpp
index f9bead433a..0d715584b1 100644
--- a/src/plugins/cppeditor/cppelementevaluator.cpp
+++ b/src/plugins/cppeditor/cppelementevaluator.cpp
@@ -118,6 +118,8 @@ void CppElementEvaluator::execute()
TypeOfExpression typeOfExpression;
typeOfExpression.init(doc, snapshot);
+ // make possible to instantiate templates
+ typeOfExpression.setExpandTemplates(true);
const QList<LookupItem> &lookupItems = typeOfExpression(expression.toUtf8(), scope);
if (lookupItems.isEmpty())
return;
@@ -237,171 +239,82 @@ void CppEditor::Internal::CppElementEvaluator::clear()
}
// CppElement
-CppElement::CppElement() : m_helpCategory(TextEditor::HelpItem::Unknown)
+CppElement::CppElement() : helpCategory(TextEditor::HelpItem::Unknown)
{}
CppElement::~CppElement()
{}
-void CppElement::setHelpCategory(const TextEditor::HelpItem::Category &cat)
-{ m_helpCategory = cat; }
-
-const TextEditor::HelpItem::Category &CppElement::helpCategory() const
-{ return m_helpCategory; }
-
-void CppElement::setHelpIdCandidates(const QStringList &candidates)
-{ m_helpIdCandidates = candidates; }
-
-void CppElement::addHelpIdCandidate(const QString &candidate)
-{ m_helpIdCandidates.append(candidate); }
-
-const QStringList &CppElement::helpIdCandidates() const
-{ return m_helpIdCandidates; }
-
-void CppElement::setHelpMark(const QString &mark)
-{ m_helpMark = mark; }
-
-const QString &CppElement::helpMark() const
-{ return m_helpMark; }
-
-void CppElement::setLink(const CPPEditorWidget::Link &link)
-{ m_link = link; }
-
-const CPPEditorWidget::Link &CppElement::link() const
-{ return m_link; }
-
-void CppElement::setTooltip(const QString &tooltip)
-{ m_tooltip = tooltip; }
-
-const QString &CppElement::tooltip() const
-{ return m_tooltip; }
-
-
// Unknown
-Unknown::Unknown(const QString &type) : CppElement(), m_type(type)
+Unknown::Unknown(const QString &type) : type(type)
{
- setTooltip(m_type);
+ tooltip = type;
}
-Unknown::~Unknown()
-{}
-
-const QString &Unknown::type() const
-{ return m_type; }
// CppInclude
-CppInclude::~CppInclude()
-{}
CppInclude::CppInclude(const Document::Include &includeFile) :
- CppElement(),
- m_path(QDir::toNativeSeparators(includeFile.fileName())),
- m_fileName(QFileInfo(includeFile.fileName()).fileName())
+ path(QDir::toNativeSeparators(includeFile.fileName())),
+ fileName(QFileInfo(includeFile.fileName()).fileName())
{
- setHelpCategory(TextEditor::HelpItem::Brief);
- setHelpIdCandidates(QStringList(m_fileName));
- setHelpMark(m_fileName);
- setLink(CPPEditorWidget::Link(m_path));
- setTooltip(m_path);
+ helpCategory = TextEditor::HelpItem::Brief;
+ helpIdCandidates = QStringList(fileName);
+ helpMark = fileName;
+ link = CPPEditorWidget::Link(path);
+ tooltip = path;
}
-const QString &CppInclude::path() const
-{ return m_path; }
-
-const QString &CppInclude::fileName() const
-{ return m_fileName; }
-
// CppMacro
-CppMacro::CppMacro(const Macro &macro) : CppElement()
+CppMacro::CppMacro(const Macro &macro)
{
- setHelpCategory(TextEditor::HelpItem::Macro);
+ helpCategory = TextEditor::HelpItem::Macro;
const QString macroName = QLatin1String(macro.name());
- setHelpIdCandidates(QStringList(macroName));
- setHelpMark(macroName);
- setLink(CPPEditorWidget::Link(macro.fileName(), macro.line()));
- setTooltip(macro.toStringWithLineBreaks());
+ helpIdCandidates = QStringList(macroName);
+ helpMark = macroName;
+ link = CPPEditorWidget::Link(macro.fileName(), macro.line());
+ tooltip = macro.toStringWithLineBreaks();
}
-CppMacro::~CppMacro()
-{}
-
// CppDeclarableElement
-CppDeclarableElement::CppDeclarableElement()
-{}
CppDeclarableElement::CppDeclarableElement(Symbol *declaration) : CppElement()
{
- m_icon = Icons().iconForSymbol(declaration);
+ icon = Icons().iconForSymbol(declaration);
Overview overview;
- overview.setShowArgumentNames(true);
- overview.setShowReturnTypes(true);
- m_name = overview.prettyName(declaration->name());
+ overview.showArgumentNames = true;
+ overview.showReturnTypes = true;
+ name = overview.prettyName(declaration->name());
if (declaration->enclosingScope()->isClass() ||
declaration->enclosingScope()->isNamespace() ||
declaration->enclosingScope()->isEnum()) {
- m_qualifiedName = overview.prettyName(LookupContext::fullyQualifiedName(declaration));
- setHelpIdCandidates(stripName(m_qualifiedName));
+ qualifiedName = overview.prettyName(LookupContext::fullyQualifiedName(declaration));
+ helpIdCandidates = stripName(qualifiedName);
} else {
- m_qualifiedName = m_name;
- setHelpIdCandidates(QStringList(m_name));
+ qualifiedName = name;
+ helpIdCandidates.append(name);
}
- setTooltip(overview.prettyType(declaration->type(), m_qualifiedName));
- setLink(CPPEditorWidget::linkToSymbol(declaration));
- setHelpMark(m_name);
+ tooltip = overview.prettyType(declaration->type(), qualifiedName);
+ link = CPPEditorWidget::linkToSymbol(declaration);
+ helpMark = name;
}
-CppDeclarableElement::~CppDeclarableElement()
-{}
-
-void CppDeclarableElement::setName(const QString &name)
-{ m_name = name; }
-
-const QString &CppDeclarableElement::name() const
-{ return m_name; }
-
-void CppDeclarableElement::setQualifiedName(const QString &name)
-{ m_qualifiedName = name; }
-
-const QString &CppDeclarableElement::qualifiedName() const
-{ return m_qualifiedName; }
-
-void CppDeclarableElement::setType(const QString &type)
-{ m_type = type; }
-
-const QString &CppDeclarableElement::type() const
-{ return m_type; }
-
-void CppDeclarableElement::setIcon(const QIcon &icon)
-{ m_icon = icon; }
-
-const QIcon &CppDeclarableElement::icon() const
-{ return m_icon; }
-
// CppNamespace
CppNamespace::CppNamespace(Symbol *declaration) : CppDeclarableElement(declaration)
{
- setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
- setTooltip(qualifiedName());
+ helpCategory = TextEditor::HelpItem::ClassOrNamespace;
+ tooltip = qualifiedName;
}
-CppNamespace::~CppNamespace()
-{}
-
// CppClass
-CppClass::CppClass()
-{}
-
CppClass::CppClass(Symbol *declaration) : CppDeclarableElement(declaration)
{
- setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
- setTooltip(qualifiedName());
+ helpCategory = TextEditor::HelpItem::ClassOrNamespace;
+ tooltip = qualifiedName;
}
-CppClass::~CppClass()
-{}
-
void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &context)
{
typedef QPair<ClassOrNamespace *, CppClass *> Data;
@@ -424,8 +337,8 @@ void CppClass::lookupBases(Symbol *declaration, const CPlusPlus::LookupContext &
!visited.contains(clazz)) {
CppClass baseCppClass(symbol);
CppClass *cppClass = current.second;
- cppClass->m_bases.append(baseCppClass);
- q.enqueue(qMakePair(clazz, &cppClass->m_bases.last()));
+ cppClass->bases.append(baseCppClass);
+ q.enqueue(qMakePair(clazz, &cppClass->bases.last()));
}
}
}
@@ -447,59 +360,45 @@ void CppClass::lookupDerived(CPlusPlus::Symbol *declaration, const CPlusPlus::Sn
CppClass *clazz = current.first;
const TypeHierarchy &classHierarchy = current.second;
foreach (const TypeHierarchy &derivedHierarchy, classHierarchy.hierarchy()) {
- clazz->m_derived.append(CppClass(derivedHierarchy.symbol()));
- q.enqueue(qMakePair(&clazz->m_derived.last(), derivedHierarchy));
+ clazz->derived.append(CppClass(derivedHierarchy.symbol()));
+ q.enqueue(qMakePair(&clazz->derived.last(), derivedHierarchy));
}
}
}
-const QList<CppClass> &CppClass::bases() const
-{ return m_bases; }
-
-const QList<CppClass> &CppClass::derived() const
-{ return m_derived; }
-
// CppFunction
-CppFunction::CppFunction(Symbol *declaration) : CppDeclarableElement(declaration)
+CppFunction::CppFunction(Symbol *declaration)
+ : CppDeclarableElement(declaration)
{
- setHelpCategory(TextEditor::HelpItem::Function);
+ helpCategory = TextEditor::HelpItem::Function;
const FullySpecifiedType &type = declaration->type();
// Functions marks can be found either by the main overload or signature based
// (with no argument names and no return). Help ids have no signature at all.
Overview overview;
- overview.setShowDefaultArguments(false);
- setHelpMark(overview.prettyType(type, name()));
+ overview.showDefaultArguments = false;
+ helpMark = overview.prettyType(type, name);
- overview.setShowFunctionSignatures(false);
- addHelpIdCandidate(overview.prettyName(declaration->name()));
+ overview.showFunctionSignatures = false;
+ helpIdCandidates.append(overview.prettyName(declaration->name()));
}
-CppFunction::~CppFunction()
-{}
-
// CppEnum
CppEnum::CppEnum(Enum *declaration)
: CppDeclarableElement(declaration)
{
- setHelpCategory(TextEditor::HelpItem::Enum);
- setTooltip(qualifiedName());
+ helpCategory = TextEditor::HelpItem::Enum;
+ tooltip = qualifiedName;
}
-CppEnum::~CppEnum()
-{}
-
// CppTypedef
CppTypedef::CppTypedef(Symbol *declaration) : CppDeclarableElement(declaration)
{
- setHelpCategory(TextEditor::HelpItem::Typedef);
- setTooltip(Overview().prettyType(declaration->type(), qualifiedName()));
+ helpCategory = TextEditor::HelpItem::Typedef;
+ tooltip = Overview().prettyType(declaration->type(), qualifiedName);
}
-CppTypedef::~CppTypedef()
-{}
-
// CppVariable
CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scope *scope) :
CppDeclarableElement(declaration)
@@ -527,12 +426,12 @@ CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scop
const QString &name =
overview.prettyName(LookupContext::fullyQualifiedName(symbol));
if (!name.isEmpty()) {
- setTooltip(name);
- setHelpCategory(TextEditor::HelpItem::ClassOrNamespace);
+ tooltip = name;
+ helpCategory = TextEditor::HelpItem::ClassOrNamespace;
const QStringList &allNames = stripName(name);
if (!allNames.isEmpty()) {
- setHelpMark(allNames.last());
- setHelpIdCandidates(allNames);
+ helpMark = allNames.last();
+ helpIdCandidates = allNames;
}
}
}
@@ -540,13 +439,10 @@ CppVariable::CppVariable(Symbol *declaration, const LookupContext &context, Scop
}
}
-CppVariable::~CppVariable()
-{}
-
CppEnumerator::CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration)
: CppDeclarableElement(declaration)
{
- setHelpCategory(TextEditor::HelpItem::Enum);
+ helpCategory = TextEditor::HelpItem::Enum;
Overview overview;
@@ -554,19 +450,14 @@ CppEnumerator::CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration)
const QString enumName = overview.prettyName(LookupContext::fullyQualifiedName(enumSymbol));
const QString enumeratorName = overview.prettyName(declaration->name());
QString enumeratorValue;
- if (const StringLiteral *value = declaration->constantValue()) {
+ if (const StringLiteral *value = declaration->constantValue())
enumeratorValue = QString::fromUtf8(value->chars(), value->size());
- }
- setHelpMark(overview.prettyName(enumSymbol->name()));
+ helpMark = overview.prettyName(enumSymbol->name());
- QString tooltip = enumeratorName;
+ tooltip = enumeratorName;
if (!enumName.isEmpty())
tooltip.prepend(enumName + QLatin1Char(' '));
if (!enumeratorValue.isEmpty())
tooltip.append(QLatin1String(" = ") + enumeratorValue);
- setTooltip(tooltip);
}
-
-CppEnumerator::~CppEnumerator()
-{}
diff --git a/src/plugins/cppeditor/cppelementevaluator.h b/src/plugins/cppeditor/cppelementevaluator.h
index b5b18ce071..1a7527bd6b 100644
--- a/src/plugins/cppeditor/cppelementevaluator.h
+++ b/src/plugins/cppeditor/cppelementevaluator.h
@@ -94,96 +94,60 @@ private:
class CppElement
{
-public:
- virtual ~CppElement();
-
- const TextEditor::HelpItem::Category &helpCategory() const;
- const QStringList &helpIdCandidates() const;
- const QString &helpMark() const;
- const CPPEditorWidget::Link &link() const;
- const QString &tooltip() const;
-
protected:
CppElement();
- void setHelpCategory(const TextEditor::HelpItem::Category &category);
- void setLink(const CPPEditorWidget::Link &link);
- void setTooltip(const QString &tooltip);
- void setHelpIdCandidates(const QStringList &candidates);
- void addHelpIdCandidate(const QString &candidate);
- void setHelpMark(const QString &mark);
+public:
+ virtual ~CppElement();
-private:
- TextEditor::HelpItem::Category m_helpCategory;
- QStringList m_helpIdCandidates;
- QString m_helpMark;
- CPPEditorWidget::Link m_link;
- QString m_tooltip;
+ TextEditor::HelpItem::Category helpCategory;
+ QStringList helpIdCandidates;
+ QString helpMark;
+ CPPEditorWidget::Link link;
+ QString tooltip;
};
class Unknown : public CppElement
{
public:
explicit Unknown(const QString &type);
- virtual ~Unknown();
-
- const QString &type() const;
-private:
- QString m_type;
+public:
+ QString type;
};
class CppInclude : public CppElement
{
public:
explicit CppInclude(const CPlusPlus::Document::Include &includeFile);
- virtual ~CppInclude();
-
- const QString &path() const;
- const QString &fileName() const;
-private:
- QString m_path;
- QString m_fileName;
+public:
+ QString path;
+ QString fileName;
};
class CppMacro : public CppElement
{
public:
explicit CppMacro(const CPlusPlus::Macro &macro);
- virtual ~CppMacro();
};
class CppDeclarableElement : public CppElement
{
public:
- CppDeclarableElement();
explicit CppDeclarableElement(CPlusPlus::Symbol *declaration);
- virtual ~CppDeclarableElement();
-
- const QString &name() const;
- const QString &qualifiedName() const;
- const QString &type() const;
- const QIcon &icon() const;
-
-protected:
- void setName(const QString &name);
- void setQualifiedName(const QString &name);
- void setType(const QString &type);
- void setIcon(const QIcon &icon);
-private:
- QString m_name;
- QString m_qualifiedName;
- QString m_type;
- QIcon m_icon;
+public:
+ QString name;
+ QString qualifiedName;
+ QString type;
+ QIcon icon;
};
class CppNamespace : public CppDeclarableElement
{
public:
explicit CppNamespace(CPlusPlus::Symbol *declaration);
- virtual ~CppNamespace();
};
class CppClass : public CppDeclarableElement
@@ -191,38 +155,31 @@ class CppClass : public CppDeclarableElement
public:
CppClass();
explicit CppClass(CPlusPlus::Symbol *declaration);
- virtual ~CppClass();
void lookupBases(CPlusPlus::Symbol *declaration, const CPlusPlus::LookupContext &context);
void lookupDerived(CPlusPlus::Symbol *declaration, const CPlusPlus::Snapshot &snapshot);
- const QList<CppClass> &bases() const;
- const QList<CppClass> &derived() const;
-
-private:
- QList<CppClass> m_bases;
- QList<CppClass> m_derived;
+public:
+ QList<CppClass> bases;
+ QList<CppClass> derived;
};
class CppFunction : public CppDeclarableElement
{
public:
explicit CppFunction(CPlusPlus::Symbol *declaration);
- virtual ~CppFunction();
};
class CppEnum : public CppDeclarableElement
{
public:
explicit CppEnum(CPlusPlus::Enum *declaration);
- virtual ~CppEnum();
};
class CppTypedef : public CppDeclarableElement
{
public:
explicit CppTypedef(CPlusPlus::Symbol *declaration);
- virtual ~CppTypedef();
};
class CppVariable : public CppDeclarableElement
@@ -231,14 +188,12 @@ public:
CppVariable(CPlusPlus::Symbol *declaration,
const CPlusPlus::LookupContext &context,
CPlusPlus::Scope *scope);
- virtual ~CppVariable();
};
class CppEnumerator : public CppDeclarableElement
{
public:
explicit CppEnumerator(CPlusPlus::EnumeratorDeclaration *declaration);
- virtual ~CppEnumerator();
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cppfunctiondecldeflink.cpp b/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
index 68cede71ba..0a17c83053 100644
--- a/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
+++ b/src/plugins/cppeditor/cppfunctiondecldeflink.cpp
@@ -40,12 +40,13 @@
#include <cplusplus/TranslationUnit.h>
#include <cplusplus/LookupContext.h>
#include <cplusplus/Overview.h>
+#include <cpptools/cppcodestylesettings.h>
#include <cpptools/cpplocalsymbols.h>
#include <cpptools/cpprefactoringchanges.h>
#include <cpptools/symbolfinder.h>
#include <texteditor/refactoroverlay.h>
-#include <texteditor/tooltip/tooltip.h>
-#include <texteditor/tooltip/tipcontents.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <utils/qtcassert.h>
#include <utils/proxyaction.h>
#include <coreplugin/actionmanager/actionmanager.h>
@@ -59,6 +60,7 @@ using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
+using namespace TextEditor;
FunctionDeclDefLinkFinder::FunctionDeclDefLinkFinder(QObject *parent)
: QObject(parent)
@@ -146,12 +148,10 @@ static DeclaratorIdAST *getDeclaratorId(DeclaratorAST *declarator)
{
if (!declarator || !declarator->core_declarator)
return 0;
- if (DeclaratorIdAST *id = declarator->core_declarator->asDeclaratorId()) {
+ if (DeclaratorIdAST *id = declarator->core_declarator->asDeclaratorId())
return id;
- }
- if (NestedDeclaratorAST *nested = declarator->core_declarator->asNestedDeclarator()) {
+ if (NestedDeclaratorAST *nested = declarator->core_declarator->asNestedDeclarator())
return getDeclaratorId(nested->declarator);
- }
return 0;
}
@@ -173,9 +173,8 @@ static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<Functio
} else if (link->sourceDeclaration->asSimpleDeclaration()) {
target = finder.findMatchingDefinition(link->sourceFunctionDeclarator->symbol, snapshot, true);
}
- if (!target) {
+ if (!target)
return noResult;
- }
// parse the target file to get the linked decl/def
const QString targetFileName = QString::fromUtf8(
@@ -315,9 +314,9 @@ void FunctionDeclDefLink::apply(CPPEditorWidget *editor, bool jumpToMatch)
}
newTargetFile->apply();
} else {
- TextEditor::ToolTip::instance()->show(
+ Utils::ToolTip::instance()->show(
editor->toolTipPosition(linkSelection),
- TextEditor::TextContent(
+ Utils::TextContent(
tr("Target file was changed, could not apply changes")));
}
}
@@ -419,9 +418,8 @@ static bool hasCommentedName(
return false;
ParameterDeclarationAST *param = list->value;
- if (param->symbol && param->symbol->name()) {
+ if (param->symbol && param->symbol->name())
return false;
- }
// maybe in a comment but in the right spot?
int nameStart = 0;
@@ -440,9 +438,8 @@ static bool hasCommentedName(
QString text = source.mid(nameStart, nameEnd - nameStart);
- if (commentArgNameRegexp()->isEmpty()) {
+ if (commentArgNameRegexp()->isEmpty())
*commentArgNameRegexp() = QRegExp(QLatin1String("/\\*\\s*(\\w*)\\s*\\*/"));
- }
return commentArgNameRegexp()->indexIn(text) != -1;
}
@@ -537,9 +534,8 @@ static QString ensureCorrectParameterSpacing(const QString &text, bool isFirstPa
++firstNonSpace;
return text.mid(firstNonSpace);
} else { // ensure one leading space
- if (text.isEmpty() || !text.at(0).isSpace()) {
+ if (text.isEmpty() || !text.at(0).isSpace())
return QLatin1Char(' ') + text;
- }
}
return text;
}
@@ -573,7 +569,7 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
QString newDeclText = linkSelection.selectedText();
for (int i = 0; i < newDeclText.size(); ++i) {
- if (newDeclText.at(i).toAscii() == 0)
+ if (newDeclText.at(i).toLatin1() == 0)
newDeclText[i] = QLatin1Char('\n');
}
newDeclText.append(QLatin1String("{}"));
@@ -595,16 +591,19 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
if (!newFunction)
return changes;
- Overview overview;
- overview.setShowReturnTypes(true);
- overview.setShowTemplateParameters(true);
- overview.setShowArgumentNames(true);
- overview.setShowFunctionSignatures(true);
+ const Overview overviewFromCurrentProjectStyle
+ = CppCodeStyleSettings::currentProjectCodeStyleOverview();
+
+ Overview overview = overviewFromCurrentProjectStyle;
+ overview.showReturnTypes = true;
+ overview.showTemplateParameters = true;
+ overview.showArgumentNames = true;
+ overview.showFunctionSignatures = true;
// abort if the name of the newly parsed function is not the expected one
DeclaratorIdAST *newDeclId = getDeclaratorId(newDef->declarator);
if (!newDeclId || !newDeclId->name || !newDeclId->name->name
- || overview(newDeclId->name->name) != nameInitial) {
+ || overview.prettyName(newDeclId->name->name) != nameInitial) {
return changes;
}
@@ -650,7 +649,7 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
if (!newFunction->returnType().isEqualTo(sourceFunction->returnType())
&& !newFunction->returnType().isEqualTo(targetFunction->returnType())) {
FullySpecifiedType type = rewriteType(newFunction->returnType(), &env, control);
- const QString replacement = overview(type, targetFunction->name());
+ const QString replacement = overview.prettyType(type, targetFunction->name());
changes.replace(returnTypeStart,
targetFile->startOf(targetFunctionDeclarator->lparen_token),
replacement);
@@ -669,7 +668,7 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
UseMinimalNames q(targetCoN);
env.enter(&q);
Control *control = sourceContext.control().data();
- Overview overview;
+ Overview overview = overviewFromCurrentProjectStyle;
// make a easy to access list of the target parameter declarations
QVarLengthArray<ParameterDeclarationAST *, 10> targetParameterDecls;
@@ -706,19 +705,19 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
QMultiHash<QString, int> sourceParamNameToIndex;
for (int i = 0; i < existingParamCount; ++i) {
Symbol *sourceParam = sourceFunction->argumentAt(i);
- sourceParamNameToIndex.insert(overview(sourceParam->name()), i);
+ sourceParamNameToIndex.insert(overview.prettyName(sourceParam->name()), i);
}
QMultiHash<QString, int> newParamNameToIndex;
for (int i = 0; i < newParamCount; ++i) {
Symbol *newParam = newFunction->argumentAt(i);
- newParamNameToIndex.insert(overview(newParam->name()), i);
+ newParamNameToIndex.insert(overview.prettyName(newParam->name()), i);
}
// name-based binds (possibly disambiguated by type)
for (int sourceParamIndex = 0; sourceParamIndex < existingParamCount; ++sourceParamIndex) {
Symbol *sourceParam = sourceFunction->argumentAt(sourceParamIndex);
- const QString &name = overview(sourceParam->name());
+ const QString &name = overview.prettyName(sourceParam->name());
QList<int> newParams = newParamNameToIndex.values(name);
QList<int> sourceParams = sourceParamNameToIndex.values(name);
@@ -783,7 +782,7 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
// if it's genuinely new, add it
if (existingParamIndex == -1) {
FullySpecifiedType type = rewriteType(newParam->type(), &env, control);
- newTargetParam = overview(type, newParam->name());
+ newTargetParam = overview.prettyType(type, newParam->name());
hadChanges = true;
}
// otherwise preserve as much as possible from the existing parameter
@@ -821,7 +820,7 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
// track renames
if (replacementName != targetParam->name() && replacementName)
- renamedTargetParameters[targetParam] = overview(replacementName);
+ renamedTargetParameters[targetParam] = overview.prettyName(replacementName);
// need to change the type (and name)?
if (!newParam->type().isEqualTo(sourceParam->type())
@@ -837,14 +836,14 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
FullySpecifiedType replacementType = rewriteType(newParam->type(), &env, control);
newTargetParam = targetFile->textOf(parameterStart, parameterTypeStart);
- newTargetParam += overview(replacementType, replacementName);
+ newTargetParam += overview.prettyType(replacementType, replacementName);
newTargetParam += targetFile->textOf(parameterTypeEnd, parameterEnd);
hadChanges = true;
}
// change the name only?
else if (!namesEqual(targetParam->name(), replacementName)) {
DeclaratorIdAST *id = getDeclaratorId(targetParamAst->declarator);
- const QString &replacementNameStr = overview(replacementName);
+ const QString &replacementNameStr = overview.prettyName(replacementName);
if (id) {
newTargetParam += targetFile->textOf(parameterStart, targetFile->startOf(id));
QString rest = targetFile->textOf(targetFile->endOf(id), parameterEnd);
@@ -965,11 +964,10 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
SimpleSpecifierAST *specifier = constSpecifier ? constSpecifier : volatileSpecifier;
QTC_ASSERT(specifier, return changes);
- if (!newFunction->isConst() && !newFunction->isVolatile()) {
+ if (!newFunction->isConst() && !newFunction->isVolatile())
changes.remove(targetFile->endOf(specifier->specifier_token - 1), targetFile->endOf(specifier));
- } else {
+ else
changes.replace(targetFile->range(specifier), cvString);
- }
}
}
}
@@ -991,21 +989,18 @@ Utils::ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targ
class ApplyDeclDefLinkOperation : public CppQuickFixOperation
{
public:
- explicit ApplyDeclDefLinkOperation(
- const QSharedPointer<const CppEditor::Internal::CppQuickFixAssistInterface> &interface,
+ explicit ApplyDeclDefLinkOperation(const CppQuickFixInterface &interface,
const QSharedPointer<FunctionDeclDefLink> &link)
: CppQuickFixOperation(interface, 10)
, m_link(link)
{}
- virtual void perform()
+ void perform()
{
CPPEditorWidget *editor = assistInterface()->editor();
QSharedPointer<FunctionDeclDefLink> link = editor->declDefLink();
- if (link != m_link)
- return;
-
- return editor->applyDeclDefLinkChanges(/*don't jump*/false);
+ if (link == m_link)
+ editor->applyDeclDefLinkChanges(/*don't jump*/false);
}
protected:
@@ -1016,17 +1011,13 @@ private:
QSharedPointer<FunctionDeclDefLink> m_link;
};
-QList<CppQuickFixOperation::Ptr> ApplyDeclDefLinkChanges::match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+void ApplyDeclDefLinkChanges::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
- QList<CppQuickFixOperation::Ptr> results;
-
QSharedPointer<FunctionDeclDefLink> link = interface->editor()->declDefLink();
if (!link || !link->isMarkerVisible())
- return results;
+ return;
QSharedPointer<ApplyDeclDefLinkOperation> op(new ApplyDeclDefLinkOperation(interface, link));
op->setDescription(FunctionDeclDefLink::tr("Apply Function Signature Changes"));
- results += op;
-
- return results;
+ result += op;
}
diff --git a/src/plugins/cppeditor/cppfunctiondecldeflink.h b/src/plugins/cppeditor/cppfunctiondecldeflink.h
index 7928c735fc..9db9ba2ca3 100644
--- a/src/plugins/cppeditor/cppfunctiondecldeflink.h
+++ b/src/plugins/cppeditor/cppfunctiondecldeflink.h
@@ -127,8 +127,7 @@ private:
class ApplyDeclDefLinkChanges: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr>
- match(const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface);
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
};
} // namespace Internal
diff --git a/src/plugins/cppeditor/cpphighlighter.cpp b/src/plugins/cppeditor/cpphighlighter.cpp
index aef99accb1..8ebd0dcd06 100644
--- a/src/plugins/cppeditor/cpphighlighter.cpp
+++ b/src/plugins/cppeditor/cpphighlighter.cpp
@@ -28,10 +28,11 @@
****************************************************************************/
#include "cpphighlighter.h"
-#include <cpptools/cppdoxygen.h>
#include <Token.h>
#include <cplusplus/SimpleLexer.h>
+#include <cplusplus/Lexer.h>
+#include <cpptools/cppdoxygen.h>
#include <cpptools/cpptoolsreuse.h>
#include <texteditor/basetextdocumentlayout.h>
@@ -78,10 +79,12 @@ void CppHighlighter::highlightBlock(const QString &text)
setCurrentBlockState(previousState);
BaseTextDocumentLayout::clearParentheses(currentBlock());
if (text.length()) {// the empty line can still contain whitespace
- if (!initialState)
- setFormat(0, text.length(), m_formats[CppVisualWhitespace]);
+ if (initialState == Lexer::State_MultiLineComment)
+ highlightLine(text, 0, text.length(), m_formats[CppCommentFormat]);
+ else if (initialState == Lexer::State_MultiLineDoxyComment)
+ highlightLine(text, 0, text.length(), m_formats[CppDoxygenCommentFormat]);
else
- setFormat(0, text.length(), m_formats[CppCommentFormat]);
+ setFormat(0, text.length(), m_formats[CppVisualWhitespace]);
}
BaseTextDocumentLayout::setFoldingIndent(currentBlock(), foldingIndent);
return;
@@ -105,12 +108,8 @@ void CppHighlighter::highlightBlock(const QString &text)
tokens.at(i - 1).length();
}
- if (previousTokenEnd != tk.begin()) {
- if (initialState && tk.isComment())
- setFormat(previousTokenEnd, tk.begin() - previousTokenEnd, m_formats[CppCommentFormat]);
- else
- setFormat(previousTokenEnd, tk.begin() - previousTokenEnd, m_formats[CppVisualWhitespace]);
- }
+ if (previousTokenEnd != tk.begin())
+ setFormat(previousTokenEnd, tk.begin() - previousTokenEnd, m_formats[CppVisualWhitespace]);
if (tk.is(T_LPAREN) || tk.is(T_LBRACE) || tk.is(T_LBRACKET)) {
const QChar c = text.at(tk.begin());
@@ -165,14 +164,15 @@ void CppHighlighter::highlightBlock(const QString &text)
setFormat(tk.begin(), tk.length(), m_formats[CppNumberFormat]);
else if (tk.isStringLiteral() || tk.isCharLiteral())
- setFormat(tk.begin(), tk.length(), m_formats[CppStringFormat]);
+ highlightLine(text, tk.begin(), tk.length(), m_formats[CppStringFormat]);
else if (tk.isComment()) {
+ const int startPosition = initialState ? previousTokenEnd : tk.begin();
if (tk.is(T_COMMENT) || tk.is(T_CPP_COMMENT))
- setFormat(tk.begin(), tk.length(), m_formats[CppCommentFormat]);
+ highlightLine(text, startPosition, tk.end() - startPosition, m_formats[CppCommentFormat]);
else // a doxygen comment
- highlightDoxygenComment(text, tk.begin(), tk.length());
+ highlightDoxygenComment(text, startPosition, tk.end() - startPosition);
// we need to insert a close comment parenthesis, if
// - the line starts in a C Comment (initalState != 0)
@@ -207,12 +207,9 @@ void CppHighlighter::highlightBlock(const QString &text)
}
// mark the trailing white spaces
- {
- const Token tk = tokens.last();
- const int lastTokenEnd = tk.begin() + tk.length();
- if (text.length() > lastTokenEnd)
- highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, QTextCharFormat());
- }
+ const int lastTokenEnd = tokens.last().end();
+ if (text.length() > lastTokenEnd)
+ highlightLine(text, lastTokenEnd, text.length() - lastTokenEnd, m_formats[CppVisualWhitespace]);
if (! initialState && state && ! tokens.isEmpty()) {
parentheses.append(Parenthesis(Parenthesis::Opened, QLatin1Char('+'),
@@ -334,7 +331,8 @@ bool CppHighlighter::isPPKeyword(const QStringRef &text) const
void CppHighlighter::highlightLine(const QString &text, int position, int length,
const QTextCharFormat &format)
{
- const QTextCharFormat visualSpaceFormat = m_formats[CppVisualWhitespace];
+ QTextCharFormat visualSpaceFormat = m_formats[CppVisualWhitespace];
+ visualSpaceFormat.setBackground(format.background());
const int end = position + length;
int index = position;
diff --git a/src/plugins/cppeditor/cpphoverhandler.cpp b/src/plugins/cppeditor/cpphoverhandler.cpp
index 4c8c339f4b..a99254fb12 100644
--- a/src/plugins/cppeditor/cpphoverhandler.cpp
+++ b/src/plugins/cppeditor/cpphoverhandler.cpp
@@ -82,12 +82,12 @@ void CppHoverHandler::identifyMatch(TextEditor::ITextEditor *editor, int pos)
if (evaluator.identifiedCppElement()) {
const QSharedPointer<CppElement> &cppElement = evaluator.cppElement();
if (!isDiagnosticTooltip())
- setToolTip(cppElement->tooltip());
- foreach (const QString &helpId, cppElement->helpIdCandidates()) {
+ setToolTip(cppElement->tooltip);
+ foreach (const QString &helpId, cppElement->helpIdCandidates) {
if (!Core::HelpManager::instance()->linksForIdentifier(helpId).isEmpty()) {
setLastHelpItemIdentified(TextEditor::HelpItem(helpId,
- cppElement->helpMark(),
- cppElement->helpCategory()));
+ cppElement->helpMark,
+ cppElement->helpCategory));
break;
}
}
diff --git a/src/plugins/cppeditor/cppinsertdecldef.cpp b/src/plugins/cppeditor/cppinsertdecldef.cpp
index 2ba0c3de6a..508c9a3359 100644
--- a/src/plugins/cppeditor/cppinsertdecldef.cpp
+++ b/src/plugins/cppeditor/cppinsertdecldef.cpp
@@ -37,6 +37,7 @@
#include <cplusplus/Overview.h>
#include <cplusplus/ASTVisitor.h>
#include <cpptools/insertionpointlocator.h>
+#include <cpptools/cppcodestylesettings.h>
#include <cpptools/cpprefactoringchanges.h>
#include <cpptools/cpptoolsreuse.h>
@@ -55,6 +56,8 @@ using namespace CPlusPlus;
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
+using namespace TextEditor;
+using namespace Utils;
namespace {
@@ -86,9 +89,10 @@ public:
"Add %1 Declaration").arg(type));
}
- void performChanges(const CppRefactoringFilePtr &,
- const CppRefactoringChanges &refactoring)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+
InsertionPointLocator locator(refactoring);
const InsertionLocation loc = locator.methodDeclarationInClass(
m_targetFileName, m_targetSymbol, m_xsSpec);
@@ -147,8 +151,7 @@ Class *isMemberFunction(const LookupContext &context, Function *function)
} // anonymous namespace
-QList<CppQuickFixOperation::Ptr> DeclFromDef::match(
- const QSharedPointer<const CppEditor::Internal::CppQuickFixAssistInterface> &interface)
+void DeclFromDef::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
CppRefactoringFilePtr file = interface->currentFile();
@@ -161,24 +164,21 @@ QList<CppQuickFixOperation::Ptr> DeclFromDef::match(
if (DeclaratorIdAST *declId = node->asDeclaratorId()) {
if (file->isCursorOn(declId)) {
if (FunctionDefinitionAST *candidate = path.at(idx - 2)->asFunctionDefinition()) {
- if (funDef) {
- return noResult();
- } else {
- funDef = candidate;
- break;
- }
+ if (funDef)
+ return;
+ funDef = candidate;
+ break;
}
}
}
}
- if (node->asClassSpecifier()) {
- return noResult();
- }
+ if (node->asClassSpecifier())
+ return;
}
if (!funDef || !funDef->symbol)
- return noResult();
+ return;
Function *fun = funDef->symbol;
if (Class *matchingClass = isMemberFunction(interface->context(), fun)) {
@@ -191,28 +191,26 @@ QList<CppQuickFixOperation::Ptr> DeclFromDef::match(
if (s->type().isEqualTo(fun->type())) {
// Declaration exists.
- return noResult();
+ return;
}
}
QString fileName = QString::fromUtf8(matchingClass->fileName(),
matchingClass->fileNameLength());
const QString decl = InsertDeclOperation::generateDeclaration(fun);
- return singleResult(new InsertDeclOperation(interface, fileName, matchingClass,
- InsertionPointLocator::Public, decl));
+ result.append(TextEditor::QuickFixOperation::Ptr(new InsertDeclOperation(interface, fileName, matchingClass,
+ InsertionPointLocator::Public, decl)));
}
-
- return noResult();
}
QString InsertDeclOperation::generateDeclaration(Function *function)
{
- Overview oo;
- oo.setShowFunctionSignatures(true);
- oo.setShowReturnTypes(true);
- oo.setShowArgumentNames(true);
+ Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
+ oo.showFunctionSignatures = true;
+ oo.showReturnTypes = true;
+ oo.showArgumentNames = true;
QString decl;
- decl += oo(function->type(), function->unqualifiedName());
+ decl += oo.prettyType(function->type(), function->unqualifiedName());
decl += QLatin1String(";\n");
return decl;
@@ -220,9 +218,6 @@ QString InsertDeclOperation::generateDeclaration(Function *function)
namespace {
-
-
-
class InsertDefOperation: public CppQuickFixOperation
{
public:
@@ -239,17 +234,16 @@ public:
.arg(dir.relativeFilePath(m_loc.fileName())));
}
- void performChanges(const CppRefactoringFilePtr &,
- const CppRefactoringChanges &refactoring)
+ void perform()
{
QTC_ASSERT(m_loc.isValid(), return);
-
+ CppRefactoringChanges refactoring(snapshot());
CppRefactoringFilePtr targetFile = refactoring.file(m_loc.fileName());
- Overview oo;
- oo.setShowFunctionSignatures(true);
- oo.setShowReturnTypes(true);
- oo.setShowArgumentNames(true);
+ Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
+ oo.showFunctionSignatures = true;
+ oo.showReturnTypes = true;
+ oo.showArgumentNames = true;
// make target lookup context
Document::Ptr targetDoc = targetFile->cppDocument();
@@ -271,7 +265,7 @@ public:
FullySpecifiedType tn = rewriteType(m_decl->type(), &env, control);
// rewrite the function name
- QString name = oo(LookupContext::minimalName(m_decl, targetCoN, control));
+ QString name = oo.prettyName(LookupContext::minimalName(m_decl, targetCoN, control));
QString defText = oo.prettyType(tn, name) + QLatin1String("\n{\n}");
@@ -293,8 +287,7 @@ private:
} // anonymous namespace
-QList<CppQuickFixOperation::Ptr> DefFromDecl::match(
- const QSharedPointer<const CppEditor::Internal::CppQuickFixAssistInterface> &interface)
+void DefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
@@ -310,22 +303,197 @@ QList<CppQuickFixOperation::Ptr> DefFromDecl::match(
&& decl->enclosingScope()->isClass()) {
CppRefactoringChanges refactoring(interface->snapshot());
InsertionPointLocator locator(refactoring);
- QList<CppQuickFixOperation::Ptr> results;
foreach (const InsertionLocation &loc, locator.methodDefinition(decl)) {
if (loc.isValid())
- results.append(CppQuickFixOperation::Ptr(new InsertDefOperation(interface, decl, loc)));
+ result.append(CppQuickFixOperation::Ptr(new InsertDefOperation(interface, decl, loc)));
}
- return results;
+ return;
}
}
}
}
-
break;
}
}
+}
+
+namespace {
+
+class GetterSetterOperation : public CppQuickFixOperation
+{
+public:
+ GetterSetterOperation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ : CppQuickFixOperation(interface)
+ {
+ setDescription(TextEditor::QuickFixFactory::tr("Create Getter and Setter Member Functions"));
+
+ m_variableName = 0;
+ m_declaratorId = 0;
+ m_declarator = 0;
+ m_variableDecl = 0;
+ m_classSpecifier = 0;
+ m_classDecl = 0;
+
+ const QList<AST *> &path = interface->path();
+ // We expect something like
+ // [0] TranslationUnitAST
+ // [1] NamespaceAST
+ // [2] LinkageBodyAST
+ // [3] SimpleDeclarationAST
+ // [4] ClassSpecifierAST
+ // [5] SimpleDeclarationAST
+ // [6] DeclaratorAST
+ // [7] DeclaratorIdAST
+ // [8] SimpleNameAST
+
+ const int n = path.size();
+ if (n < 6)
+ return;
+
+ m_variableName = path.at(n - 1)->asSimpleName();
+ m_declaratorId = path.at(n - 2)->asDeclaratorId();
+ m_declarator = path.at(n - 3)->asDeclarator();
+ m_variableDecl = path.at(n - 4)->asSimpleDeclaration();
+ m_classSpecifier = path.at(n - 5)->asClassSpecifier();
+ m_classDecl = path.at(n - 6)->asSimpleDeclaration();
+ }
+
+ bool isValid() const
+ {
+ return m_variableName
+ && m_declaratorId
+ && m_declarator
+ && m_variableDecl
+ && m_classSpecifier
+ && m_classDecl;
+ }
+
+ void perform()
+ {
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
+ const Name *variableName = m_variableName->name;
+ QTC_ASSERT(variableName, return);
+ const Identifier *variableId = variableName->identifier();
+ QTC_ASSERT(variableId, return);
+ QString variableString = QString::fromLatin1(variableId->chars(), variableId->size());
+
+ const List<Symbol *> *symbols = m_variableDecl->symbols;
+ QTC_ASSERT(symbols, return);
+ Symbol *symbol = symbols->value;
+ QTC_ASSERT(symbol, return);
+ FullySpecifiedType fullySpecifiedType = symbol->type();
+ Type *type = fullySpecifiedType.type();
+ QTC_ASSERT(type, return);
+ Overview oo;
+ oo.showFunctionSignatures = true;
+ oo.showReturnTypes = true;
+ oo.showArgumentNames = true;
+ QString typeString = oo.prettyType(fullySpecifiedType);
+
+ const NameAST *classNameAST = m_classSpecifier->name;
+ QTC_ASSERT(classNameAST, return);
+ const Name *className = classNameAST->name;
+ QTC_ASSERT(className, return);
+ const Identifier *classId = className->identifier();
+ QTC_ASSERT(classId, return);
+ QString classString = QString::fromLatin1(classId->chars(), classId->size());
+
+ bool wasHeader = true;
+ QString declFileName = currentFile->fileName();
+ QString implFileName = CppTools::correspondingHeaderOrSource(declFileName, &wasHeader);
+ const bool sameFile = !wasHeader || !QFile::exists(implFileName);
+ if (sameFile)
+ implFileName = declFileName;
+
+ InsertionPointLocator locator(refactoring);
+ InsertionLocation declLocation = locator.methodDeclarationInClass
+ (declFileName, m_classSpecifier->symbol->asClass(), InsertionPointLocator::Public);
+
+ QString baseName = variableString;
+ if (baseName.startsWith(QLatin1String("m_")))
+ baseName.remove(0, 2);
+ else if (baseName.startsWith(QLatin1Char('_')))
+ baseName.remove(0, 1);
+ else if (baseName.endsWith(QLatin1Char('_')))
+ baseName.chop(1);
+
+ QString getterName = QString::fromLatin1("%1").arg(baseName);
+ QString setterName = QString::fromLatin1("set%1%2")
+ .arg(baseName.left(1).toUpper()).arg(baseName.mid(1));
+
+ const bool passByValue = type->isIntegerType() || type->isFloatType()
+ || type->isPointerType() || type->isEnumType();
+ const char *param = passByValue ? "%1" : "const %1 &";
+ QString paramString = QString::fromLatin1(param).arg(typeString);
+
+ QString declaration = declLocation.prefix();
+ declaration += QString::fromLatin1(
+ "%3 %1() const;\n" "void %2(%4 value);\n")
+ .arg(getterName).arg(setterName)
+ .arg(typeString).arg(paramString);
+ declaration += declLocation.suffix();
+
+ QString implementation = QString::fromLatin1(
+ "\n%5 %3::%1() const\n"
+ "{\n"
+ "return %4;\n"
+ "}\n"
+ "\nvoid %3::%2(%6 value)\n"
+ "{\n"
+ "%4 = value;\n"
+ "}\n")
+ .arg(getterName).arg(setterName)
+ .arg(classString).arg(variableString)
+ .arg(typeString).arg(paramString);
+
+ ChangeSet currChanges;
+
+ int declInsertPos = currentFile->position(qMax(1u, declLocation.line()),
+ declLocation.column());
+ currChanges.insert(declInsertPos, declaration);
+
+ if (sameFile) {
+ const int pos = currentFile->endOf(m_classDecl) + 1;
+ unsigned line, column;
+ currentFile->lineAndColumn(pos, &line, &column);
+ const int insertPos = currentFile->position(line + 1, 1) - 1;
+ currChanges.insert(insertPos < 0 ? pos : insertPos, implementation);
+ } else {
+ CppRefactoringChanges implRefactoring(snapshot());
+ CppRefactoringFilePtr implFile = implRefactoring.file(implFileName);
+ ChangeSet implChanges;
+ const int implInsertPos = QFileInfo(implFileName).size();
+ implChanges.insert(implInsertPos, implementation);
+ implFile->setChangeSet(implChanges);
+ implFile->appendIndentRange(
+ ChangeSet::Range(implInsertPos, implInsertPos + implementation.size()));
+ implFile->apply();
+ }
+ currentFile->setChangeSet(currChanges);
+ currentFile->appendIndentRange(
+ ChangeSet::Range(declInsertPos, declInsertPos + declaration.size()));
+ currentFile->apply();
+ }
- return noResult();
+ SimpleNameAST *m_variableName;
+ DeclaratorIdAST *m_declaratorId;
+ DeclaratorAST *m_declarator;
+ SimpleDeclarationAST *m_variableDecl;
+ ClassSpecifierAST *m_classSpecifier;
+ SimpleDeclarationAST *m_classDecl;
+};
+
+} // namespace
+
+void GetterSetter::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
+{
+ GetterSetterOperation *op = new GetterSetterOperation(interface);
+ if (op->isValid())
+ result.append(CppQuickFixOperation::Ptr(op));
+ else
+ delete op;
}
namespace {
@@ -333,7 +501,7 @@ namespace {
class ExtractFunctionOperation : public CppQuickFixOperation
{
public:
- ExtractFunctionOperation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
+ ExtractFunctionOperation(const CppQuickFixInterface &interface,
int extractionStart,
int extractionEnd,
FunctionDefinitionAST *refFuncDef,
@@ -349,10 +517,11 @@ public:
setDescription(QCoreApplication::translate("QuickFix::ExtractFunction", "Extract Function"));
}
- void performChanges(const CppTools::CppRefactoringFilePtr &currentFile,
- const CppTools::CppRefactoringChanges &refactoring)
+ void perform()
{
QTC_ASSERT(!m_funcReturn || !m_relevantDecls.isEmpty(), return);
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
const QString &funcName = getFunctionName();
if (funcName.isEmpty())
@@ -373,7 +542,7 @@ public:
UseMinimalNames subs(targetCoN);
env.enter(&subs);
- Overview printer;
+ Overview printer = CppCodeStyleSettings::currentProjectCodeStyleOverview();
Control *control = assistInterface()->context().control().data();
QString funcDef;
QString funcDecl; // We generate a declaration only in the case of a member function.
@@ -728,14 +897,13 @@ public:
} // anonymous namespace
-QList<CppQuickFixOperation::Ptr> ExtractFunction::match(
- const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+void ExtractFunction::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
CppRefactoringFilePtr file = interface->currentFile();
QTextCursor cursor = file->cursor();
if (!cursor.hasSelection())
- return noResult();
+ return;
const QList<AST *> &path = interface->path();
FunctionDefinitionAST *refFuncDef = 0; // The "reference" function, which we will extract from.
@@ -752,7 +920,7 @@ QList<CppQuickFixOperation::Ptr> ExtractFunction::match(
|| !refFuncDef->symbol
|| !refFuncDef->symbol->name()
|| refFuncDef->symbol->enclosingScope()->isTemplate() /* TODO: Templates... */) {
- return noResult();
+ return;
}
// Adjust selection ends.
@@ -770,7 +938,7 @@ QList<CppQuickFixOperation::Ptr> ExtractFunction::match(
file,
printer);
if (!analyser(refFuncDef))
- return noResult();
+ return;
// We also need to collect the declarations of the parameters from the reference function.
QSet<QString> refFuncParams;
@@ -826,20 +994,20 @@ QList<CppQuickFixOperation::Ptr> ExtractFunction::match(
if ((usedBeforeExtraction && usedInsideExtraction)
|| (usedInsideExtraction && refFuncParams.contains(name))) {
- QTC_ASSERT(analyser.m_knownDecls.contains(name), return noResult());
+ QTC_ASSERT(analyser.m_knownDecls.contains(name), return);
relevantDecls.append(qMakePair(name, analyser.m_knownDecls.value(name)));
}
// We assume that the first use of a local corresponds to its declaration.
if (usedInsideExtraction && usedAfterExtraction && !usedBeforeExtraction) {
if (!funcReturn) {
- QTC_ASSERT(analyser.m_knownDecls.contains(name), return noResult());
+ QTC_ASSERT(analyser.m_knownDecls.contains(name), return);
// The return, if any, is stored as the first item in the list.
relevantDecls.prepend(qMakePair(name, analyser.m_knownDecls.value(name)));
funcReturn = it.key();
} else {
// Would require multiple returns. (Unless we do fancy things, as pointed below.)
- return noResult();
+ return;
}
}
}
@@ -847,10 +1015,10 @@ QList<CppQuickFixOperation::Ptr> ExtractFunction::match(
// The current implementation doesn't try to be too smart since it preserves the original form
// of the declarations. This might be or not the desired effect. An improvement would be to
// let the user somehow customize the function interface.
- return singleResult(new ExtractFunctionOperation(interface,
+ result.append(CppQuickFixOperation::Ptr(new ExtractFunctionOperation(interface,
analyser.m_extractionStart,
analyser.m_extractionEnd,
refFuncDef,
funcReturn,
- relevantDecls));
+ relevantDecls)));
}
diff --git a/src/plugins/cppeditor/cppinsertdecldef.h b/src/plugins/cppeditor/cppinsertdecldef.h
index 63c7825258..f40ab0f185 100644
--- a/src/plugins/cppeditor/cppinsertdecldef.h
+++ b/src/plugins/cppeditor/cppinsertdecldef.h
@@ -38,23 +38,26 @@ namespace Internal {
class DeclFromDef: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr>
- match(const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface);
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
};
class DefFromDecl: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr>
- match(const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface);
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
};
class ExtractFunction : public CppQuickFixFactory
{
- virtual QList<CppQuickFixOperation::Ptr>
- match(const QSharedPointer<const CppQuickFixAssistInterface> &interface);
+public:
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
};
+class GetterSetter : public CppQuickFixFactory
+{
+public:
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
+};
} // namespace Internal
} // namespace CppEditor
diff --git a/src/plugins/cppeditor/cppinsertqtpropertymembers.cpp b/src/plugins/cppeditor/cppinsertqtpropertymembers.cpp
index 92abf0f442..230f6ef2e4 100644
--- a/src/plugins/cppeditor/cppinsertqtpropertymembers.cpp
+++ b/src/plugins/cppeditor/cppinsertqtpropertymembers.cpp
@@ -50,18 +50,18 @@ using namespace Utils;
using namespace CppEditor;
using namespace CppEditor::Internal;
-QList<CppQuickFixOperation::Ptr> InsertQtPropertyMembers::match(
- const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+void InsertQtPropertyMembers::match(const CppQuickFixInterface &interface,
+ QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
if (path.isEmpty())
- return noResult();
+ return;
AST * const ast = path.last();
QtPropertyDeclarationAST *qtPropertyDeclaration = ast->asQtPropertyDeclaration();
if (!qtPropertyDeclaration)
- return noResult();
+ return;
ClassSpecifierAST *klass = 0;
for (int i = path.size() - 2; i >= 0; --i) {
@@ -70,7 +70,7 @@ QList<CppQuickFixOperation::Ptr> InsertQtPropertyMembers::match(
break;
}
if (!klass)
- return noResult();
+ return;
CppRefactoringFilePtr file = interface->currentFile();
const QString propertyName = file->textOf(qtPropertyDeclaration->property_name);
@@ -102,31 +102,30 @@ QList<CppQuickFixOperation::Ptr> InsertQtPropertyMembers::match(
Symbol *member = c->memberAt(i);
FullySpecifiedType type = member->type();
if (member->asFunction() || (type.isValid() && type->asFunctionType())) {
- const QString name = overview(member->name());
- if (name == getterName) {
+ const QString name = overview.prettyName(member->name());
+ if (name == getterName)
generateFlags &= ~GenerateGetter;
- } else if (name == setterName) {
+ else if (name == setterName)
generateFlags &= ~GenerateSetter;
- } else if (name == signalName) {
+ else if (name == signalName)
generateFlags &= ~GenerateSignal;
- }
} else if (member->asDeclaration()) {
- const QString name = overview(member->name());
+ const QString name = overview.prettyName(member->name());
if (name == storageName)
generateFlags &= ~GenerateStorage;
}
}
if (getterName.isEmpty() && setterName.isEmpty() && signalName.isEmpty())
- return noResult();
+ return;
- return singleResult(new Operation(interface, path.size() - 1, qtPropertyDeclaration, c,
- generateFlags,
- getterName, setterName, signalName, storageName));
+ result.append(QuickFixOperation::Ptr(
+ new Operation(interface, path.size() - 1, qtPropertyDeclaration, c,
+ generateFlags, getterName, setterName, signalName, storageName)));
}
InsertQtPropertyMembers::Operation::Operation(
- const QSharedPointer<const CppQuickFixAssistInterface> &interface,
+ const CppQuickFixInterface &interface,
int priority, QtPropertyDeclarationAST *declaration, Class *klass,
int generateFlags, const QString &getterName, const QString &setterName, const QString &signalName,
const QString &storageName)
@@ -143,9 +142,11 @@ InsertQtPropertyMembers::Operation::Operation(
setDescription(desc);
}
-void InsertQtPropertyMembers::Operation::performChanges(const CppRefactoringFilePtr &file,
- const CppRefactoringChanges &refactoring)
+void InsertQtPropertyMembers::Operation::perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr file = refactoring.file(fileName());
+
InsertionPointLocator locator(refactoring);
Utils::ChangeSet declarations;
@@ -154,7 +155,6 @@ void InsertQtPropertyMembers::Operation::performChanges(const CppRefactoringFile
// getter declaration
if (m_generateFlags & GenerateGetter) {
- // const QString getterDeclaration = QString("%1 %2() const;").arg(typeName, getterName);
const QString getterDeclaration = typeName + QLatin1Char(' ') + m_getterName +
QLatin1String("() const\n{\nreturn ") + m_storageName + QLatin1String(";\n}\n");
InsertionLocation getterLoc = locator.methodDeclarationInClass(file->fileName(), m_class, InsertionPointLocator::Public);
@@ -164,7 +164,6 @@ void InsertQtPropertyMembers::Operation::performChanges(const CppRefactoringFile
// setter declaration
if (m_generateFlags & GenerateSetter) {
- // const QString setterDeclaration = QString("void %1(%2 arg);").arg(setterName, typeName);
QString setterDeclaration;
QTextStream setter(&setterDeclaration);
setter << "void " << m_setterName << '(' << typeName << " arg)\n{\n";
diff --git a/src/plugins/cppeditor/cppinsertqtpropertymembers.h b/src/plugins/cppeditor/cppinsertqtpropertymembers.h
index 0ccb34b56a..d7890e6e85 100644
--- a/src/plugins/cppeditor/cppinsertqtpropertymembers.h
+++ b/src/plugins/cppeditor/cppinsertqtpropertymembers.h
@@ -60,8 +60,7 @@ class InsertQtPropertyMembers : public CppQuickFixFactory
Q_OBJECT
public:
- virtual QList<CppQuickFixOperation::Ptr>
- match(const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface);
+ void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result);
private:
enum GenerateFlag {
@@ -81,8 +80,7 @@ private:
const QString &getterName, const QString &setterName, const QString &signalName,
const QString &storageName);
- virtual void performChanges(const CppTools::CppRefactoringFilePtr &file,
- const CppTools::CppRefactoringChanges &refactoring);
+ void perform();
private:
void insertAndIndent(const TextEditor::RefactoringFilePtr &file, Utils::ChangeSet *changeSet,
diff --git a/src/plugins/cppeditor/cppoutline.cpp b/src/plugins/cppeditor/cppoutline.cpp
index c856cc1782..7e9e75cb4f 100644
--- a/src/plugins/cppeditor/cppoutline.cpp
+++ b/src/plugins/cppeditor/cppoutline.cpp
@@ -82,9 +82,8 @@ bool CppOutlineFilterModel::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const
{
// ignore artifical "<Select Symbol>" entry
- if (!sourceParent.isValid() && sourceRow == 0) {
+ if (!sourceParent.isValid() && sourceRow == 0)
return false;
- }
// ignore generated symbols, e.g. by macro expansion (Q_OBJECT)
const QModelIndex sourceIndex = m_sourceModel->index(sourceRow, 0, sourceParent);
CPlusPlus::Symbol *symbol = m_sourceModel->symbolFromIndex(sourceIndex);
diff --git a/src/plugins/cppeditor/cppplugin.cpp b/src/plugins/cppeditor/cppplugin.cpp
index 8de4ec09d1..b0cfea6c72 100644
--- a/src/plugins/cppeditor/cppplugin.cpp
+++ b/src/plugins/cppeditor/cppplugin.cpp
@@ -54,6 +54,7 @@
#include <texteditor/texteditorplugin.h>
#include <texteditor/texteditorsettings.h>
#include <texteditor/texteditorconstants.h>
+#include <utils/hostosinfo.h>
#include <cpptools/ModelManagerInterface.h>
#include <cpptools/cpptoolsconstants.h>
#include <cpptools/cpptoolssettings.h>
@@ -83,21 +84,21 @@ CppEditorFactory::CppEditorFactory(CppPlugin *owner) :
<< QLatin1String(CppEditor::Constants::CPP_SOURCE_MIMETYPE)
<< QLatin1String(CppEditor::Constants::CPP_HEADER_MIMETYPE);
-#if !defined(Q_OS_MAC) && !defined(Q_OS_WIN)
- Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
- iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/cppeditor/images/qt_cpp.png")),
- mimeDatabase->findByType(QLatin1String(CppEditor::Constants::CPP_SOURCE_MIMETYPE)));
- iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/cppeditor/images/qt_c.png")),
- mimeDatabase->findByType(QLatin1String(CppEditor::Constants::C_SOURCE_MIMETYPE)));
- iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/cppeditor/images/qt_h.png")),
- mimeDatabase->findByType(QLatin1String(CppEditor::Constants::CPP_HEADER_MIMETYPE)));
-#endif
+ if (!Utils::HostOsInfo::isMacHost() && !Utils::HostOsInfo::isWindowsHost()) {
+ Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
+ Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
+ iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/cppeditor/images/qt_cpp.png")),
+ mimeDatabase->findByType(QLatin1String(CppEditor::Constants::CPP_SOURCE_MIMETYPE)));
+ iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/cppeditor/images/qt_c.png")),
+ mimeDatabase->findByType(QLatin1String(CppEditor::Constants::C_SOURCE_MIMETYPE)));
+ iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/cppeditor/images/qt_h.png")),
+ mimeDatabase->findByType(QLatin1String(CppEditor::Constants::CPP_HEADER_MIMETYPE)));
+ }
}
Core::Id CppEditorFactory::id() const
{
- return CppEditor::Constants::CPPEDITOR_ID;
+ return Core::Id(CppEditor::Constants::CPPEDITOR_ID);
}
QString CppEditorFactory::displayName() const
@@ -149,7 +150,7 @@ void CppPlugin::initializeEditor(CPPEditorWidget *editor)
{
m_actionHandler->setupActions(editor);
- editor->setLanguageSettingsId(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID));
+ editor->setLanguageSettingsId(CppTools::Constants::CPP_SETTINGS_ID);
TextEditor::TextEditorSettings::instance()->initializeEditor(editor);
// method combo box sorting
diff --git a/src/plugins/cppeditor/cppplugin.h b/src/plugins/cppeditor/cppplugin.h
index 1d3a0bb52e..c163cd27c6 100644
--- a/src/plugins/cppeditor/cppplugin.h
+++ b/src/plugins/cppeditor/cppplugin.h
@@ -87,6 +87,11 @@ private slots:
void currentEditorChanged(Core::IEditor *editor);
void openTypeHierarchy();
+#ifdef WITH_TESTS
+private slots: // quickfix tests
+ void test_quickfix_GetterSetter();
+#endif // WITH_TESTS
+
private:
Core::IEditor *createEditor(QWidget *parent);
void writeSettings();
diff --git a/src/plugins/cppeditor/cppquickfix.cpp b/src/plugins/cppeditor/cppquickfix.cpp
index 60216ed1b6..efe46a9515 100644
--- a/src/plugins/cppeditor/cppquickfix.cpp
+++ b/src/plugins/cppeditor/cppquickfix.cpp
@@ -53,10 +53,8 @@ using namespace CppEditor::Internal;
using namespace CppTools;
using namespace TextEditor;
using namespace CPlusPlus;
-using namespace Utils;
-CppQuickFixOperation::CppQuickFixOperation(
- const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority)
+CppQuickFixOperation::CppQuickFixOperation(const CppQuickFixInterface &interface, int priority)
: QuickFixOperation(priority)
, m_interface(interface)
{}
@@ -64,12 +62,9 @@ CppQuickFixOperation::CppQuickFixOperation(
CppQuickFixOperation::~CppQuickFixOperation()
{}
-void CppQuickFixOperation::perform()
+Snapshot CppQuickFixOperation::snapshot() const
{
- CppRefactoringChanges refactoring(m_interface->snapshot());
- CppRefactoringFilePtr current = refactoring.file(fileName());
-
- performChanges(current, refactoring);
+ return m_interface->snapshot();
}
const CppQuickFixAssistInterface *CppQuickFixOperation::assistInterface() const
@@ -82,32 +77,10 @@ QString CppQuickFixOperation::fileName() const
return m_interface->document()->fileName();
}
-CppQuickFixFactory::CppQuickFixFactory()
-{
-}
-
-CppQuickFixFactory::~CppQuickFixFactory()
-{
-}
-
-QList<QuickFixOperation::Ptr> CppQuickFixFactory::matchingOperations(
- const QSharedPointer<const TextEditor::IAssistInterface> &interface)
+void CppQuickFixFactory::matchingOperations(const QuickFixInterface &interface, QuickFixOperations &result)
{
- QSharedPointer<const CppQuickFixAssistInterface> cppInterface =
- interface.staticCast<const CppQuickFixAssistInterface>();
+ CppQuickFixInterface cppInterface = interface.staticCast<const CppQuickFixAssistInterface>();
if (cppInterface->path().isEmpty())
- return QList<QuickFixOperation::Ptr>();
- return match(cppInterface);
-}
-
-QList<CppQuickFixOperation::Ptr> CppQuickFixFactory::singleResult(CppQuickFixOperation *operation)
-{
- QList<CppQuickFixOperation::Ptr> result;
- result.append(CppQuickFixOperation::Ptr(operation));
- return result;
-}
-
-QList<CppQuickFixOperation::Ptr> CppQuickFixFactory::noResult()
-{
- return QList<CppQuickFixOperation::Ptr>();
+ return;
+ match(cppInterface, result);
}
diff --git a/src/plugins/cppeditor/cppquickfix.h b/src/plugins/cppeditor/cppquickfix.h
index 9ade56c783..beb893dd20 100644
--- a/src/plugins/cppeditor/cppquickfix.h
+++ b/src/plugins/cppeditor/cppquickfix.h
@@ -35,44 +35,27 @@
namespace CPlusPlus {
class CppModelManagerInterface;
-}
-
-namespace CppTools {
- class CppRefactoringFile;
- class CppRefactoringChanges;
- typedef QSharedPointer<CppRefactoringFile> CppRefactoringFilePtr;
-} // namespace CppTools
-
-namespace ExtensionSystem {
-class IPlugin;
+class Snapshot;
}
namespace CppEditor {
+namespace Internal { class CppQuickFixAssistInterface; }
-namespace Internal {
-class CppQuickFixAssistInterface;
-}
+typedef QSharedPointer<const Internal::CppQuickFixAssistInterface> CppQuickFixInterface;
class CPPEDITOR_EXPORT CppQuickFixOperation: public TextEditor::QuickFixOperation
{
public:
- explicit CppQuickFixOperation(
- const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface,
- int priority = -1);
- virtual ~CppQuickFixOperation();
-
- virtual void perform();
+ explicit CppQuickFixOperation(const CppQuickFixInterface &interface, int priority = -1);
+ ~CppQuickFixOperation();
protected:
- virtual void performChanges(const CppTools::CppRefactoringFilePtr &currentFile,
- const CppTools::CppRefactoringChanges &refactoring) = 0;
-
QString fileName() const;
-
+ CPlusPlus::Snapshot snapshot() const;
const Internal::CppQuickFixAssistInterface *assistInterface() const;
private:
- QSharedPointer<const Internal::CppQuickFixAssistInterface> m_interface;
+ CppQuickFixInterface m_interface;
};
class CPPEDITOR_EXPORT CppQuickFixFactory: public TextEditor::QuickFixFactory
@@ -80,29 +63,17 @@ class CPPEDITOR_EXPORT CppQuickFixFactory: public TextEditor::QuickFixFactory
Q_OBJECT
public:
- CppQuickFixFactory();
- virtual ~CppQuickFixFactory();
+ CppQuickFixFactory() {}
- virtual QList<TextEditor::QuickFixOperation::Ptr>
- matchingOperations(const QSharedPointer<const TextEditor::IAssistInterface> &interface);
+ void matchingOperations(const TextEditor::QuickFixInterface &interface,
+ TextEditor::QuickFixOperations &result);
/*!
Implement this method to match and create the appropriate
CppQuickFixOperation objects.
*/
- virtual QList<CppQuickFixOperation::Ptr> match(
- const QSharedPointer<const Internal::CppQuickFixAssistInterface> &interface) = 0;
-
-protected:
- /*!
- Creates a list of 1 single element: the shared-pointer to the given
- operation. This shared-pointer takes over the ownership (meaning the
- responsibility to delete the operation).
- */
- static QList<CppQuickFixOperation::Ptr> singleResult(CppQuickFixOperation *operation);
-
- /// Utility method which creates an empty list.
- static QList<CppQuickFixOperation::Ptr> noResult();
+ virtual void match(const CppQuickFixInterface &interface,
+ TextEditor::QuickFixOperations &result) = 0;
};
} // namespace CppEditor
diff --git a/src/plugins/cppeditor/cppquickfix_test.cpp b/src/plugins/cppeditor/cppquickfix_test.cpp
new file mode 100644
index 0000000000..25218061ce
--- /dev/null
+++ b/src/plugins/cppeditor/cppquickfix_test.cpp
@@ -0,0 +1,217 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <AST.h>
+#include <Control.h>
+#include <CppDocument.h>
+#include <DiagnosticClient.h>
+#include <Scope.h>
+#include <TranslationUnit.h>
+#include <Literals.h>
+#include <Bind.h>
+#include <Symbols.h>
+#include <utils/changeset.h>
+#include <texteditor/basetextdocument.h>
+#include <texteditor/plaintexteditor.h>
+#include <texteditor/codeassist/iassistproposal.h>
+#include <texteditor/codeassist/iassistproposalmodel.h>
+#include <texteditor/codeassist/basicproposalitemlistmodel.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <cppeditor/cppeditor.h>
+#include <cppeditor/cppplugin.h>
+#include <cppeditor/cppquickfix.h>
+#include <cppeditor/cppquickfixassistant.h>
+#include <cppeditor/cppinsertdecldef.h>
+#include <extensionsystem/pluginmanager.h>
+#include <utils/fileutils.h>
+
+#include <QtTest>
+#include <QDebug>
+#include <QTextDocument>
+#include <QDir>
+
+/*!
+ Tests for quick-fixes.
+ */
+using namespace CPlusPlus;
+using namespace CppEditor;
+using namespace CppEditor::Internal;
+using namespace CppTools;
+using namespace TextEditor;
+using namespace Core;
+
+namespace {
+/**
+ * Encapsulates the whole process of setting up an editor, getting the
+ * quick-fix, applying it, and checking the result.
+ */
+struct TestCase
+{
+ QByteArray originalText;
+ int pos;
+ CPPEditor *editor;
+ CPPEditorWidget *editorWidget;
+
+ TestCase(const QByteArray &input);
+ ~TestCase();
+
+ QuickFixOperation::Ptr getFix(CppQuickFixFactory *factory);
+
+ void run(CppQuickFixFactory *factory, const QByteArray &expected, int undoCount = 1);
+
+private:
+ TestCase(const TestCase &);
+ TestCase &operator=(const TestCase &);
+};
+
+/// apply the factory on the source, and get back the first result.
+QuickFixOperation::Ptr TestCase::getFix(CppQuickFixFactory *factory)
+{
+ CppQuickFixInterface qfi(new CppQuickFixAssistInterface(editorWidget, ExplicitlyInvoked));
+ TextEditor::QuickFixOperations results;
+ factory->match(qfi, results);
+ Q_ASSERT(!results.isEmpty());
+ return results.first();
+}
+
+/// The '@' in the input is the position from where the quick-fix discovery is triggered.
+TestCase::TestCase(const QByteArray &input)
+ : originalText(input)
+{
+ pos = originalText.indexOf('@');
+ QVERIFY(pos != -1);
+ originalText.remove(pos, 1);
+ QString fileName(QDir::tempPath() + QLatin1String("/file.cpp"));
+ Utils::FileSaver srcSaver(fileName);
+ srcSaver.write(originalText);
+ srcSaver.finalize();
+ CPlusPlus::CppModelManagerInterface::instance()->updateSourceFiles(QStringList()<<fileName);
+
+ // wait for the parser in the future to give us the document:
+ while (true) {
+ Snapshot s = CPlusPlus::CppModelManagerInterface::instance()->snapshot();
+ if (s.contains(fileName))
+ break;
+ QCoreApplication::processEvents();
+ }
+
+ editor = dynamic_cast<CPPEditor *>(EditorManager::openEditor(fileName));
+ QVERIFY(editor);
+ editor->setCursorPosition(pos);
+ editorWidget = dynamic_cast<CPPEditorWidget *>(editor->editorWidget());
+ QVERIFY(editorWidget);
+ editorWidget->semanticRehighlight(true);
+
+ // wait for the semantic info from the future:
+ while (editorWidget->semanticInfo().doc.isNull())
+ QCoreApplication::processEvents();
+}
+
+TestCase::~TestCase()
+{
+ EditorManager::instance()->closeEditors(QList<Core::IEditor *>() << editor,
+ false);
+ QCoreApplication::processEvents(); // process any pending events
+
+ // Remove the test file from the code-model:
+ CppModelManagerInterface *mmi = CPlusPlus::CppModelManagerInterface::instance();
+ mmi->GC();
+ QCOMPARE(mmi->snapshot().size(), 0);
+}
+
+/// Leading whitespace is not removed, so we can check if the indetation ranges
+/// have been set correctly by the quick-fix.
+QByteArray &removeTrailingWhitespace(QByteArray &input)
+{
+ QList<QByteArray> lines = input.split('\n');
+ input.resize(0);
+ foreach (QByteArray line, lines) {
+ while (line.length() > 0) {
+ char lastChar = line[line.length() - 1];
+ if (lastChar == ' ' || lastChar == '\t')
+ line = line.left(line.length() - 1);
+ else
+ break;
+ }
+ input.append(line);
+ input.append('\n');
+ }
+ return input;
+}
+
+void TestCase::run(CppQuickFixFactory *factory, const QByteArray &expected, int undoCount)
+{
+ QuickFixOperation::Ptr fix = getFix(factory);
+ fix->perform();
+ QByteArray result = editorWidget->document()->toPlainText().toUtf8();
+ removeTrailingWhitespace(result);
+
+ QCOMPARE(result, expected);
+
+ for (int i = 0; i < undoCount; ++i)
+ editorWidget->undo();
+
+ result = editorWidget->document()->toPlainText().toUtf8();
+ QCOMPARE(result, originalText);
+}
+} // anonymous namespace
+
+void CppPlugin::test_quickfix_GetterSetter()
+{
+ TestCase data("\n"
+ "class Something\n"
+ "{\n"
+ " int @it;\n"
+ "};\n"
+ );
+ QByteArray expected = "\n"
+ "class Something\n"
+ "{\n"
+ " int it;\n"
+ "\n"
+ "public:\n"
+ " int it() const;\n"
+ " void setIt(int value);\n"
+ "};\n"
+ "\n"
+ "int Something::it() const\n"
+ "{\n"
+ " return it;\n"
+ "}\n"
+ "\n"
+ "void Something::setIt(int value)\n"
+ "{\n"
+ " it = value;\n"
+ "}\n"
+ "\n"
+ ;
+
+ GetterSetter factory;
+ data.run(&factory, expected);
+}
diff --git a/src/plugins/cppeditor/cppquickfixassistant.cpp b/src/plugins/cppeditor/cppquickfixassistant.cpp
index 41c090051b..c6d9c3dc2f 100644
--- a/src/plugins/cppeditor/cppquickfixassistant.cpp
+++ b/src/plugins/cppeditor/cppquickfixassistant.cpp
@@ -104,6 +104,7 @@ CppQuickFixAssistInterface::CppQuickFixAssistInterface(CPPEditorWidget *editor,
, m_currentFile(CppRefactoringChanges::file(editor, m_semanticInfo.doc))
, m_context(m_semanticInfo.doc, m_snapshot)
{
+ Q_ASSERT(!m_semanticInfo.doc.isNull());
CPlusPlus::ASTPath astPath(m_semanticInfo.doc);
m_path = astPath(editor->textCursor());
}
diff --git a/src/plugins/cppeditor/cppquickfixes.cpp b/src/plugins/cppeditor/cppquickfixes.cpp
index a0b058c8b4..cfdc0a5887 100644
--- a/src/plugins/cppeditor/cppquickfixes.cpp
+++ b/src/plugins/cppeditor/cppquickfixes.cpp
@@ -28,18 +28,18 @@
****************************************************************************/
#include "cppcompleteswitch.h"
+#include "cppcompleteswitch.h"
#include "cppeditor.h"
-#include "cppquickfix.h"
+#include "cppfunctiondecldeflink.h"
#include "cppinsertdecldef.h"
#include "cppinsertqtpropertymembers.h"
#include "cppquickfixassistant.h"
-#include "cppcompleteswitch.h"
-#include "cppfunctiondecldeflink.h"
+#include "cppquickfix.h"
-#include <ASTVisitor.h>
#include <AST.h>
#include <ASTMatcher.h>
#include <ASTPatternBuilder.h>
+#include <ASTVisitor.h>
#include <CoreTypes.h>
#include <Literals.h>
#include <Name.h>
@@ -50,34 +50,35 @@
#include <TranslationUnit.h>
#include <Type.h>
+#include <cplusplus/CppRewriter.h>
#include <cplusplus/DependencyTable.h>
#include <cplusplus/Overview.h>
#include <cplusplus/TypeOfExpression.h>
-#include <cpptools/ModelManagerInterface.h>
-#include <cplusplus/CppRewriter.h>
-#include <cpptools/cpptoolsconstants.h>
+#include <cpptools/cppclassesfilter.h>
+#include <cpptools/cppcodestylesettings.h>
+#include <cpptools/cpppointerdeclarationformatter.h>
#include <cpptools/cpprefactoringchanges.h>
-#include <cpptools/insertionpointlocator.h>
+#include <cpptools/cpptoolsconstants.h>
#include <cpptools/cpptoolsreuse.h>
-#include <cpptools/cppclassesfilter.h>
+#include <cpptools/insertionpointlocator.h>
+#include <cpptools/ModelManagerInterface.h>
#include <cpptools/searchsymbols.h>
#include <cpptools/symbolfinder.h>
#include <extensionsystem/iplugin.h>
#include <extensionsystem/pluginmanager.h>
-
#include <utils/qtcassert.h>
-#include <QFileInfo>
+#include <cctype>
#include <QApplication>
+#include <QFileInfo>
#include <QTextBlock>
#include <QTextCursor>
-#include <cctype>
using namespace CppEditor;
using namespace CppEditor::Internal;
using namespace CppTools;
-using namespace TextEditor;
using namespace CPlusPlus;
+using namespace TextEditor;
using namespace Utils;
static inline bool isQtStringLiteral(const QByteArray &id)
@@ -103,18 +104,17 @@ namespace {
class UseInverseOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
- QList<CppQuickFixOperation::Ptr> result;
CppRefactoringFilePtr file = interface->currentFile();
const QList<AST *> &path = interface->path();
int index = path.size() - 1;
BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
if (! binary)
- return result;
+ return;
if (! interface->isCursorOn(binary->binary_op_token))
- return result;
+ return;
Kind invertToken;
switch (file->tokenAt(binary->binary_op_token).kind()) {
@@ -137,11 +137,10 @@ public:
invertToken = T_EQUAL_EQUAL;
break;
default:
- return result;
+ return;
}
result.append(CppQuickFixOperation::Ptr(new Operation(interface, index, binary, invertToken)));
- return result;
}
private:
@@ -154,7 +153,7 @@ private:
QString replacement;
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
+ Operation(const CppQuickFixInterface &interface,
int priority, BinaryExpressionAST *binary, Kind invertToken)
: CppQuickFixOperation(interface, priority)
, binary(binary), nested(0), negation(0)
@@ -180,8 +179,11 @@ private:
return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
if (negation) {
// can't remove parentheses since that might break precedence
@@ -211,18 +213,17 @@ private:
class FlipBinaryOp: public CppQuickFixFactory
{
public:
- virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
- QList<QuickFixOperation::Ptr> result;
const QList<AST *> &path = interface->path();
CppRefactoringFilePtr file = interface->currentFile();
int index = path.size() - 1;
BinaryExpressionAST *binary = path.at(index)->asBinaryExpression();
if (! binary)
- return result;
+ return;
if (! interface->isCursorOn(binary->binary_op_token))
- return result;
+ return;
Kind flipToken;
switch (file->tokenAt(binary->binary_op_token).kind()) {
@@ -245,7 +246,7 @@ public:
flipToken = T_EOF_SYMBOL;
break;
default:
- return result;
+ return;
}
QString replacement;
@@ -256,14 +257,13 @@ public:
}
result.append(QuickFixOperation::Ptr(new Operation(interface, index, binary, replacement)));
- return result;
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
+ Operation(const CppQuickFixInterface &interface,
int priority, BinaryExpressionAST *binary, QString replacement)
: CppQuickFixOperation(interface)
, binary(binary)
@@ -280,10 +280,12 @@ private:
return QApplication::translate("CppTools::QuickFix", "Rewrite Using %1").arg(replacement);
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
- ChangeSet changes;
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+ ChangeSet changes;
changes.flip(currentFile->range(binary->left_expression), currentFile->range(binary->right_expression));
if (! replacement.isEmpty())
changes.replace(currentFile->range(binary->binary_op_token), replacement);
@@ -310,9 +312,8 @@ private:
class RewriteLogicalAndOp: public CppQuickFixFactory
{
public:
- virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
- QList<QuickFixOperation::Ptr> result;
BinaryExpressionAST *expression = 0;
const QList<AST *> &path = interface->path();
CppRefactoringFilePtr file = interface->currentFile();
@@ -325,10 +326,10 @@ public:
}
if (! expression)
- return result;
+ return;
if (! interface->isCursorOn(expression->binary_op_token))
- return result;
+ return;
QSharedPointer<Operation> op(new Operation(interface));
@@ -340,8 +341,6 @@ public:
op->setPriority(index);
result.append(op);
}
-
- return result;
}
private:
@@ -353,7 +352,7 @@ private:
UnaryExpressionAST *right;
BinaryExpressionAST *pattern;
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ Operation(const CppQuickFixInterface &interface)
: CppQuickFixOperation(interface)
, mk(new ASTPatternBuilder)
{
@@ -362,8 +361,11 @@ private:
pattern = mk->BinaryExpression(left, right);
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
changes.replace(currentFile->range(pattern->binary_op_token), QLatin1String("||"));
changes.remove(currentFile->range(left->unary_op_token));
@@ -423,12 +425,12 @@ class SplitSimpleDeclarationOp: public CppQuickFixFactory
}
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
- QList<CppQuickFixOperation::Ptr> result;
CoreDeclaratorAST *core_declarator = 0;
const QList<AST *> &path = interface->path();
CppRefactoringFilePtr file = interface->currentFile();
+ const int cursorPosition = file->cursor().selectionStart();
for (int index = path.size() - 1; index != -1; --index) {
AST *node = path.at(index);
@@ -440,34 +442,32 @@ public:
if (checkDeclaration(simpleDecl)) {
SimpleDeclarationAST *declaration = simpleDecl;
- const int cursorPosition = file->cursor().selectionStart();
-
const int startOfDeclSpecifier = file->startOf(declaration->decl_specifier_list->firstToken());
const int endOfDeclSpecifier = file->endOf(declaration->decl_specifier_list->lastToken() - 1);
if (cursorPosition >= startOfDeclSpecifier && cursorPosition <= endOfDeclSpecifier) {
// the AST node under cursor is a specifier.
- return singleResult(new Operation(interface, index, declaration));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, declaration)));
+ return;
}
if (core_declarator && interface->isCursorOn(core_declarator)) {
// got a core-declarator under the text cursor.
- return singleResult(new Operation(interface, index, declaration));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, declaration)));
+ return;
}
}
- break;
+ return;
}
}
-
- return result;
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, SimpleDeclarationAST *decl)
+ Operation(const CppQuickFixInterface &interface, int priority, SimpleDeclarationAST *decl)
: CppQuickFixOperation(interface, priority)
, declaration(decl)
{
@@ -475,8 +475,11 @@ private:
"Split Declaration"));
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
SpecifierListAST *specifiers = declaration->decl_specifier_list;
@@ -518,16 +521,15 @@ private:
if (a)
b;
becomes
- if (a) {
+ if (a)
b;
- }
Activates on: the if
*/
class AddBracesToIfOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
@@ -536,7 +538,8 @@ public:
IfStatementAST *ifStatement = path.at(index)->asIfStatement();
if (ifStatement && interface->isCursorOn(ifStatement->if_token) && ifStatement->statement
&& ! ifStatement->statement->asCompoundStatement()) {
- return singleResult(new Operation(interface, index, ifStatement->statement));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, ifStatement->statement)));
+ return;
}
// or if we're on the statement contained in the if
@@ -546,21 +549,20 @@ public:
if (ifStatement && ifStatement->statement
&& interface->isCursorOn(ifStatement->statement)
&& ! ifStatement->statement->asCompoundStatement()) {
- return singleResult(new Operation(interface, index, ifStatement->statement));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, ifStatement->statement)));
+ return;
}
}
// ### This could very well be extended to the else branch
// and other nodes entirely.
-
- return noResult();
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, StatementAST *statement)
+ Operation(const CppQuickFixInterface &interface, int priority, StatementAST *statement)
: CppQuickFixOperation(interface, priority)
, _statement(statement)
{
@@ -568,8 +570,11 @@ private:
"Add Curly Braces"));
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
const int start = currentFile->endOf(_statement->firstToken() - 1);
@@ -601,7 +606,7 @@ private:
class MoveDeclarationOutOfIfOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
QSharedPointer<Operation> op(new Operation(interface));
@@ -613,26 +618,23 @@ public:
DeclaratorAST *declarator = op->condition->declarator;
op->core = declarator->core_declarator;
if (! op->core)
- return noResult();
+ return;
if (interface->isCursorOn(op->core)) {
- QList<CppQuickFixOperation::Ptr> result;
op->setPriority(index);
result.append(op);
- return result;
+ return;
}
}
}
}
-
- return noResult();
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ Operation(const CppQuickFixInterface &interface)
: CppQuickFixOperation(interface)
{
setDescription(QApplication::translate("CppTools::QuickFix",
@@ -642,8 +644,11 @@ private:
pattern = mk.IfStatement(condition);
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
changes.copy(currentFile->range(core), currentFile->startOf(condition));
@@ -679,7 +684,7 @@ private:
class MoveDeclarationOutOfWhileOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
QSharedPointer<Operation> op(new Operation(interface));
@@ -692,32 +697,29 @@ public:
op->core = declarator->core_declarator;
if (! op->core)
- return noResult();
+ return;
- else if (! declarator->equal_token)
- return noResult();
+ if (! declarator->equal_token)
+ return;
- else if (! declarator->initializer)
- return noResult();
+ if (! declarator->initializer)
+ return;
if (interface->isCursorOn(op->core)) {
- QList<CppQuickFixOperation::Ptr> result;
op->setPriority(index);
result.append(op);
- return result;
+ return;
}
}
}
}
-
- return noResult();
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ Operation(const CppQuickFixInterface &interface)
: CppQuickFixOperation(interface)
{
setDescription(QApplication::translate("CppTools::QuickFix",
@@ -727,8 +729,11 @@ private:
pattern = mk.WhileStatement(condition);
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
changes.insert(currentFile->startOf(condition), QLatin1String("("));
@@ -760,9 +765,8 @@ private:
}
with
- if (something) {
- if (something_else) {
- }
+ if (something)
+ if (something_else)
}
and
@@ -780,7 +784,7 @@ private:
class SplitIfStatementOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
IfStatementAST *pattern = 0;
const QList<AST *> &path = interface->path();
@@ -795,14 +799,14 @@ public:
}
if (! pattern || ! pattern->statement)
- return noResult();
+ return;
unsigned splitKind = 0;
for (++index; index < path.size(); ++index) {
AST *node = path.at(index);
BinaryExpressionAST *condition = node->asBinaryExpression();
if (! condition)
- return noResult();
+ return;
Token binaryToken = interface->currentFile()->tokenAt(condition->binary_op_token);
@@ -810,26 +814,26 @@ public:
if (! splitKind) {
splitKind = binaryToken.kind();
if (splitKind != T_AMPER_AMPER && splitKind != T_PIPE_PIPE)
- return noResult();
+ return;
// we can't reliably split &&s in ifs with an else branch
if (splitKind == T_AMPER_AMPER && pattern->else_statement)
- return noResult();
+ return;
} else if (splitKind != binaryToken.kind()) {
- return noResult();
+ return;
}
- if (interface->isCursorOn(condition->binary_op_token))
- return singleResult(new Operation(interface, index, pattern, condition));
+ if (interface->isCursorOn(condition->binary_op_token)) {
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, pattern, condition)));
+ return;
+ }
}
-
- return noResult();
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority,
+ Operation(const CppQuickFixInterface &interface, int priority,
IfStatementAST *pattern, BinaryExpressionAST *condition)
: CppQuickFixOperation(interface, priority)
, pattern(pattern)
@@ -839,8 +843,11 @@ private:
"Split if Statement"));
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
const Token binaryToken = currentFile->tokenAt(condition->binary_op_token);
if (binaryToken.is(T_AMPER_AMPER))
@@ -931,7 +938,7 @@ static inline QString msgQtStringLiteralDescription(const QString &replacement)
class WrapStringLiteral: public CppQuickFixFactory
{
public:
- typedef const QSharedPointer<const CppQuickFixAssistInterface> AssistInterfacePtr;
+ typedef const CppQuickFixInterface AssistInterfacePtr;
enum ActionFlags
{
@@ -946,7 +953,8 @@ public:
enum Type { TypeString, TypeObjCString, TypeChar, TypeNone };
- virtual QList<CppQuickFixOperation::Ptr> match(const AssistInterfacePtr &interface);
+ //void match(const AssistInterfacePtr &interface, QuickFixOperations &result);
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result);
static QString replacement(unsigned actions);
static QByteArray stringToCharEscapeSequences(const QByteArray &content);
static QByteArray charToStringEscapeSequences(const QByteArray &content);
@@ -964,7 +972,8 @@ public:
unsigned actions, const QString &description, ExpressionAST *literal,
const QString &translationContext = QString());
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &);
+ void perform();
+
private:
const unsigned m_actions;
ExpressionAST *m_literal;
@@ -1020,7 +1029,7 @@ ExpressionAST *WrapStringLiteral::analyze(const QList<AST *> &path,
return literal;
}
-QList<CppQuickFixOperation::Ptr> WrapStringLiteral::match(const AssistInterfacePtr &interface)
+void WrapStringLiteral::match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
typedef CppQuickFixOperation::Ptr OperationPtr;
@@ -1030,18 +1039,16 @@ QList<CppQuickFixOperation::Ptr> WrapStringLiteral::match(const AssistInterfaceP
CppRefactoringFilePtr file = interface->currentFile();
ExpressionAST *literal = WrapStringLiteral::analyze(path, file, &type, &enclosingFunction);
if (!literal || type == TypeNone)
- return noResult();
+ return;
if ((type == TypeChar && enclosingFunction == "QLatin1Char")
|| isQtStringLiteral(enclosingFunction)
|| isQtStringTranslation(enclosingFunction))
- return noResult();
+ return;
- QList<CppQuickFixOperation::Ptr> result;
const int priority = path.size() - 1; // very high priority
if (type == TypeChar) {
unsigned actions = EncloseInQLatin1CharAction;
- QString description =
- msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions));
+ QString description = msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions));
result << OperationPtr(new Operation(interface, priority, actions,
description, literal));
if (NumericLiteralAST *charLiteral = literal->asNumericLiteral()) {
@@ -1083,7 +1090,6 @@ QList<CppQuickFixOperation::Ptr> WrapStringLiteral::match(const AssistInterfaceP
msgQtStringLiteralDescription(WrapStringLiteral::replacement(actions), 5),
literal));
}
- return result;
}
QString WrapStringLiteral::replacement(unsigned actions)
@@ -1134,8 +1140,11 @@ WrapStringLiteral::Operation::Operation(const AssistInterfacePtr &interface, int
setDescription(description);
}
-void WrapStringLiteral::Operation::performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+void WrapStringLiteral::Operation::perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
const int startPos = currentFile->startOf(m_literal);
@@ -1205,7 +1214,7 @@ void WrapStringLiteral::Operation::performChanges(const CppRefactoringFilePtr &c
class TranslateStringLiteral: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
// Initialize
WrapStringLiteral::Type type = WrapStringLiteral::TypeNone;
@@ -1215,7 +1224,7 @@ public:
ExpressionAST *literal = WrapStringLiteral::analyze(path, file, &type, &enclosingFunction);
if (!literal || type != WrapStringLiteral::TypeString
|| isQtStringLiteral(enclosingFunction) || isQtStringTranslation(enclosingFunction))
- return noResult();
+ return;
QString trContext;
@@ -1224,21 +1233,20 @@ public:
// Check whether we are in a method:
const QString description = QApplication::translate("CppTools::QuickFix", "Mark as Translatable");
- QList<CppQuickFixOperation::Ptr> result;
- for (int i = path.size() - 1; i >= 0; --i)
- {
+ for (int i = path.size() - 1; i >= 0; --i) {
if (FunctionDefinitionAST *definition = path.at(i)->asFunctionDefinition()) {
Function *function = definition->symbol;
ClassOrNamespace *b = interface->context().lookupType(function);
if (b) {
// Do we have a tr method?
- foreach(const LookupItem &r, b->find(trName)) {
+ foreach (const LookupItem &r, b->find(trName)) {
Symbol *s = r.declaration();
if (s->type()->isFunctionType()) {
// no context required for tr
- return singleResult(new WrapStringLiteral::Operation(interface, path.size() - 1,
+ result.append(QuickFixOperation::Ptr(new WrapStringLiteral::Operation(interface, path.size() - 1,
WrapStringLiteral::TranslateTrAction,
- description, literal));
+ description, literal)));
+ return;
}
}
}
@@ -1253,16 +1261,17 @@ public:
// ... or global if none available!
if (trContext.isEmpty())
trContext = QLatin1String("GLOBAL");
- return singleResult(new WrapStringLiteral::Operation(interface, path.size() - 1,
+ result.append(QuickFixOperation::Ptr(new WrapStringLiteral::Operation(interface, path.size() - 1,
WrapStringLiteral::TranslateQCoreApplicationAction,
- description, literal, trContext));
+ description, literal, trContext)));
+ return;
}
}
// We need to use Q_TRANSLATE_NOOP
- return singleResult(new WrapStringLiteral::Operation(interface, path.size() - 1,
+ result.append(QuickFixOperation::Ptr(new WrapStringLiteral::Operation(interface, path.size() - 1,
WrapStringLiteral::TranslateNoopAction,
- description, literal, trContext));
+ description, literal, trContext)));
}
};
@@ -1279,12 +1288,12 @@ public:
class CStringToNSString: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
CppRefactoringFilePtr file = interface->currentFile();
if (interface->editor()->mimeType() != QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE))
- return noResult();
+ return;
WrapStringLiteral::Type type = WrapStringLiteral::TypeNone;
QByteArray enclosingFunction;
@@ -1292,18 +1301,18 @@ public:
const QList<AST *> &path = interface->path();
ExpressionAST *literal = WrapStringLiteral::analyze(path, file, &type, &enclosingFunction, &qlatin1Call);
if (!literal || type != WrapStringLiteral::TypeString)
- return noResult();
+ return;
if (!isQtStringLiteral(enclosingFunction))
qlatin1Call = 0;
- return singleResult(new Operation(interface, path.size() - 1, literal->asStringLiteral(), qlatin1Call));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, path.size() - 1, literal->asStringLiteral(), qlatin1Call)));
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, StringLiteralAST *stringLiteral, CallAST *qlatin1Call)
+ Operation(const CppQuickFixInterface &interface, int priority, StringLiteralAST *stringLiteral, CallAST *qlatin1Call)
: CppQuickFixOperation(interface, priority)
, stringLiteral(stringLiteral)
, qlatin1Call(qlatin1Call)
@@ -1312,8 +1321,11 @@ private:
"Convert to Objective-C String Literal"));
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
if (qlatin1Call) {
@@ -1354,27 +1366,25 @@ private:
class ConvertNumericLiteral: public CppQuickFixFactory
{
public:
- virtual QList<QuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
- QList<QuickFixOperation::Ptr> result;
-
const QList<AST *> &path = interface->path();
CppRefactoringFilePtr file = interface->currentFile();
if (path.isEmpty())
- return result; // nothing to do
+ return;
NumericLiteralAST *literal = path.last()->asNumericLiteral();
if (! literal)
- return result;
+ return;
Token token = file->tokenAt(literal->asNumericLiteral()->literal_token);
if (!token.is(T_NUMERIC_LITERAL))
- return result;
+ return;
const NumericLiteral *numeric = token.number;
if (numeric->isDouble() || numeric->isFloat())
- return result;
+ return;
// remove trailing L or U and stuff
const char * const spell = numeric->chars();
@@ -1382,13 +1392,13 @@ public:
while (numberLength > 0 && !std::isxdigit(spell[numberLength - 1]))
--numberLength;
if (numberLength < 1)
- return result;
+ return;
// convert to number
bool valid;
ulong value = QString::fromUtf8(spell).left(numberLength).toULong(&valid, 0);
if (!valid) // e.g. octal with digit > 7
- return result;
+ return;
const int priority = path.size() - 1; // very high priority
const int start = file->startOf(literal);
@@ -1449,15 +1459,13 @@ public:
result.append(op);
}
}
-
- return result;
}
private:
class ConvertNumeric: public CppQuickFixOperation
{
public:
- ConvertNumeric(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
+ ConvertNumeric(const CppQuickFixInterface &interface,
int start, int end, const QString &replacement)
: CppQuickFixOperation(interface)
, start(start)
@@ -1465,8 +1473,11 @@ private:
, replacement(replacement)
{}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile, const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
ChangeSet changes;
changes.replace(start, end, replacement);
currentFile->setChangeSet(changes);
@@ -1487,26 +1498,28 @@ private:
class FixForwardDeclarationOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
for (int index = path.size() - 1; index != -1; --index) {
AST *ast = path.at(index);
if (NamedTypeSpecifierAST *namedTy = ast->asNamedTypeSpecifier()) {
- if (Symbol *fwdClass = checkName(interface, namedTy->name))
- return singleResult(new Operation(interface, index, fwdClass));
+ if (Symbol *fwdClass = checkName(interface, namedTy->name)) {
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, fwdClass)));
+ return;
+ }
} else if (ElaboratedTypeSpecifierAST *eTy = ast->asElaboratedTypeSpecifier()) {
- if (Symbol *fwdClass = checkName(interface, eTy->name))
- return singleResult(new Operation(interface, index, fwdClass));
+ if (Symbol *fwdClass = checkName(interface, eTy->name)) {
+ result.append(QuickFixOperation::Ptr(new Operation(interface, index, fwdClass)));
+ return;
+ }
}
}
-
- return noResult();
}
protected:
- static Symbol *checkName(const QSharedPointer<const CppQuickFixAssistInterface> &interface, NameAST *ast)
+ static Symbol *checkName(const CppQuickFixInterface &interface, NameAST *ast)
{
if (ast && interface->isCursorOn(ast)) {
if (const Name *name = ast->name) {
@@ -1537,7 +1550,7 @@ private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, Symbol *fwdClass)
+ Operation(const CppQuickFixInterface &interface, int priority, Symbol *fwdClass)
: CppQuickFixOperation(interface, priority)
, fwdClass(fwdClass)
{
@@ -1545,21 +1558,20 @@ private:
"#include Header File"));
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile,
- const CppRefactoringChanges &)
+ void perform()
{
QTC_ASSERT(fwdClass != 0, return);
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
CppTools::SymbolFinder symbolFinder;
- if (Class *k =
- symbolFinder.findMatchingClassDeclaration(fwdClass,
- assistInterface()->snapshot())) {
+ if (Class *k = symbolFinder.findMatchingClassDeclaration(fwdClass, snapshot())) {
const QString headerFile = QString::fromUtf8(k->fileName(), k->fileNameLength());
// collect the fwd headers
Snapshot fwdHeaders;
- fwdHeaders.insert(assistInterface()->snapshot().document(headerFile));
- foreach (Document::Ptr doc, assistInterface()->snapshot()) {
+ fwdHeaders.insert(snapshot().document(headerFile));
+ foreach (Document::Ptr doc, snapshot()) {
QFileInfo headerFileInfo(doc->fileName());
if (doc->globalSymbolCount() == 0 && doc->includes().size() == 1)
fwdHeaders.insert(doc);
@@ -1629,7 +1641,7 @@ private:
class AddLocalDeclarationOp: public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
CppRefactoringFilePtr file = interface->currentFile();
@@ -1654,33 +1666,39 @@ public:
}
if (! decl) {
- return singleResult(new Operation(interface, index, binary));
+ result.append(QuickFixOperation::Ptr(
+ new Operation(interface, index, binary, nameAST)));
+ return;
}
}
}
}
}
-
- return noResult();
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, BinaryExpressionAST *binaryAST)
+ Operation(const CppQuickFixInterface &interface,
+ int priority,
+ const BinaryExpressionAST *binaryAST,
+ const SimpleNameAST *simpleNameAST)
: CppQuickFixOperation(interface, priority)
, binaryAST(binaryAST)
+ , simpleNameAST(simpleNameAST)
{
setDescription(QApplication::translate("CppTools::QuickFix", "Add Local Declaration"));
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile,
- const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
TypeOfExpression typeOfExpression;
typeOfExpression.init(assistInterface()->semanticInfo().doc,
- assistInterface()->snapshot(), assistInterface()->context().bindings());
+ snapshot(), assistInterface()->context().bindings());
Scope *scope = currentFile->scopeAt(binaryAST->firstToken());
const QList<LookupItem> result =
typeOfExpression(currentFile->textOf(binaryAST->right_expression).toUtf8(),
@@ -1688,7 +1706,6 @@ private:
TypeOfExpression::Preprocess);
if (! result.isEmpty()) {
-
SubstitutionEnvironment env;
env.setContext(assistInterface()->context());
env.switchScope(result.first().scope());
@@ -1701,16 +1718,13 @@ private:
Control *control = assistInterface()->context().control().data();
FullySpecifiedType tn = rewriteType(result.first().type(), &env, control);
- Overview oo;
- QString ty = oo(tn);
+ Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
+ QString ty = oo.prettyType(tn, simpleNameAST->name);
if (! ty.isEmpty()) {
- const QChar ch = ty.at(ty.size() - 1);
-
- if (ch.isLetterOrNumber() || ch == QLatin1Char(' ') || ch == QLatin1Char('>'))
- ty += QLatin1Char(' ');
-
Utils::ChangeSet changes;
- changes.insert(currentFile->startOf(binaryAST), ty);
+ changes.replace(currentFile->startOf(binaryAST),
+ currentFile->endOf(simpleNameAST),
+ ty);
currentFile->setChangeSet(changes);
currentFile->apply();
}
@@ -1718,7 +1732,8 @@ private:
}
private:
- BinaryExpressionAST *binaryAST;
+ const BinaryExpressionAST *binaryAST;
+ const SimpleNameAST *simpleNameAST;
};
};
@@ -1731,12 +1746,12 @@ private:
class ToCamelCaseConverter : public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> &path = interface->path();
if (path.isEmpty())
- return noResult();
+ return;
AST * const ast = path.last();
const Name *name = 0;
@@ -1748,24 +1763,24 @@ public:
}
if (!name)
- return noResult();
+ return;
QString newName = QString::fromUtf8(name->identifier()->chars());
if (newName.length() < 3)
- return noResult();
+ return;
for (int i = 1; i < newName.length() - 1; ++i) {
- if (Operation::isConvertibleUnderscore(newName, i))
- return singleResult(new Operation(interface, path.size() - 1, newName));
+ if (Operation::isConvertibleUnderscore(newName, i)) {
+ result.append(QuickFixOperation::Ptr(new Operation(interface, path.size() - 1, newName)));
+ return;
+ }
}
-
- return noResult();
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, const QString &newName)
+ Operation(const CppQuickFixInterface &interface, int priority, const QString &newName)
: CppQuickFixOperation(interface, priority)
, m_name(newName)
{
@@ -1773,9 +1788,11 @@ private:
"Convert to Camel Case"));
}
- virtual void performChanges(const CppRefactoringFilePtr &,
- const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
for (int i = 1; i < m_name.length(); ++i) {
QCharRef c = m_name[i];
if (c.isUpper()) {
@@ -1806,16 +1823,16 @@ private:
class IncludeAdder : public CppQuickFixFactory
{
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
CppClassesFilter *classesFilter = ExtensionSystem::PluginManager::getObject<CppClassesFilter>();
if (!classesFilter)
- return noResult();
+ return;
const QList<AST *> &path = interface->path();
if (path.isEmpty())
- return noResult();
+ return;
// find the largest enclosing Name
const NameAST *enclosingName = 0;
@@ -1826,14 +1843,14 @@ public:
if (!innermostName) {
innermostName = nameAst->asSimpleName();
if (!innermostName)
- return noResult();
+ return;
}
} else {
break;
}
}
if (!enclosingName || !enclosingName->name)
- return noResult();
+ return;
// find the enclosing scope
unsigned line, column;
@@ -1841,18 +1858,16 @@ public:
doc->translationUnit()->getTokenStartPosition(enclosingName->firstToken(), &line, &column);
Scope *scope = doc->scopeAt(line, column);
if (!scope)
- return noResult();
+ return;
// check if the name resolves to something
QList<LookupItem> existingResults = interface->context().lookup(enclosingName->name, scope);
if (!existingResults.isEmpty())
- return noResult();
+ return;
- const QString &className = Overview()(innermostName->name);
+ const QString &className = Overview().prettyName(innermostName->name);
if (className.isEmpty())
- return noResult();
-
- QList<CppQuickFixOperation::Ptr> results;
+ return;
// find the include paths
QStringList includePaths;
@@ -1861,7 +1876,7 @@ public:
bool inProject = false;
foreach (const CppModelManagerInterface::ProjectInfo &info, projectInfos) {
foreach (CppModelManagerInterface::ProjectPart::Ptr part, info.projectParts()) {
- if (part->sourceFiles.contains(doc->fileName())) {
+ if (part->sourceFiles.contains(doc->fileName()) || part->objcSourceFiles.contains(doc->fileName()) || part->headerFiles.contains(doc->fileName())) {
inProject = true;
includePaths += part->includePaths;
}
@@ -1905,7 +1920,7 @@ public:
}
if (!shortestInclude.isEmpty())
- results += CppQuickFixOperation::Ptr(new Operation(interface, 0, shortestInclude));
+ result += CppQuickFixOperation::Ptr(new Operation(interface, 0, shortestInclude));
}
// for QSomething, propose a <QSomething> include -- if such a class was in the locator
@@ -1914,17 +1929,15 @@ public:
&& className.at(0) == QLatin1Char('Q')
&& className.at(1).isUpper()) {
const QString include = QLatin1Char('<') + className + QLatin1Char('>');
- results += CppQuickFixOperation::Ptr(new Operation(interface, 1, include));
+ result += CppQuickFixOperation::Ptr(new Operation(interface, 1, include));
}
-
- return results;
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface, int priority, const QString &include)
+ Operation(const CppQuickFixInterface &interface, int priority, const QString &include)
: CppQuickFixOperation(interface, priority)
, m_include(include)
{
@@ -1932,9 +1945,11 @@ private:
"Add #include %1").arg(m_include));
}
- virtual void performChanges(const CppRefactoringFilePtr &file,
- const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr file = refactoring.file(fileName());
+
// find location of last include in file
QList<Document::Include> includes = file->cppDocument()->includes();
unsigned lastIncludeLine = 0;
@@ -1973,10 +1988,9 @@ public:
};
public:
- virtual QList<CppQuickFixOperation::Ptr> match(const QSharedPointer<const CppQuickFixAssistInterface> &interface)
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<AST *> path = interface->path();
- QList<CppQuickFixOperation::Ptr> result;
ParameterDeclarationAST *paramDecl = 0;
int index = path.size() - 1;
@@ -1987,10 +2001,10 @@ public:
}
if (index < 1)
- return result;
+ return;
ParameterDeclarationClauseAST *paramDeclClause = path.at(index-1)->asParameterDeclarationClause();
- QTC_ASSERT(paramDeclClause && paramDeclClause->parameter_declaration_list, return result);
+ QTC_ASSERT(paramDeclClause && paramDeclClause->parameter_declaration_list, return);
ParameterDeclarationListAST *paramListNode = paramDeclClause->parameter_declaration_list;
ParameterDeclarationListAST *prevParamListNode = 0;
@@ -2002,7 +2016,7 @@ public:
}
if (!paramListNode)
- return result;
+ return;
if (prevParamListNode)
result.append(CppQuickFixOperation::Ptr(new Operation(interface, paramListNode->value,
@@ -2010,15 +2024,13 @@ public:
if (paramListNode->next)
result.append(CppQuickFixOperation::Ptr(new Operation(interface, paramListNode->value,
paramListNode->next->value, TargetNext)));
-
- return result;
}
private:
class Operation: public CppQuickFixOperation
{
public:
- Operation(const QSharedPointer<const CppQuickFixAssistInterface> &interface,
+ Operation(const CppQuickFixInterface &interface,
AST *currentParam, AST *targetParam,
Target target)
: CppQuickFixOperation(interface)
@@ -2027,24 +2039,21 @@ private:
{
QString targetString;
if (target == TargetPrevious)
- {
targetString = QApplication::translate("CppTools::QuickFix",
"Switch with Previous Parameter");
- }
else
- {
targetString = QApplication::translate("CppTools::QuickFix",
"Switch with Next Parameter");
- }
-
setDescription(targetString);
}
- virtual void performChanges(const CppRefactoringFilePtr &currentFile,
- const CppRefactoringChanges &)
+ void perform()
{
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+
int targetEndPos = currentFile->endOf(m_targetParam);
- Utils::ChangeSet changes;
+ ChangeSet changes;
changes.flip(currentFile->startOf(m_currentParam), currentFile->endOf(m_currentParam),
currentFile->startOf(m_targetParam), targetEndPos);
currentFile->setChangeSet(changes);
@@ -2058,6 +2067,87 @@ private:
};
};
+/**
+ * Reformats a pointer, reference or rvalue reference type/declaration.
+ *
+ * Works also with selections (except when the cursor is not on any AST).
+ *
+ * Activates on: simple declarations, parameters and return types of function
+ * declarations and definitions, control flow statements (if,
+ * while, for, foreach) with declarations.
+ */
+class PointerDeclarationFormatterOp : public CppQuickFixFactory
+{
+public:
+ typedef Utils::ChangeSet ChangeSet;
+
+ void match(const CppQuickFixInterface &interface, QuickFixOperations &result)
+ {
+ const QList<AST *> &path = interface->path();
+ CppRefactoringFilePtr file = interface->currentFile();
+
+ Overview overview = CppCodeStyleSettings::currentProjectCodeStyleOverview();
+ overview.showArgumentNames = true;
+ overview.showReturnTypes = true;
+
+ const QTextCursor cursor = file->cursor();
+ ChangeSet change;
+ PointerDeclarationFormatter formatter(file, overview,
+ PointerDeclarationFormatter::RespectCursor);
+
+ if (cursor.hasSelection()) {
+ // This will no work always as expected since this method is only called if
+ // interface-path() is not empty. If the user selects the whole document via
+ // ctrl-a and there is an empty line in the end, then the cursor is not on
+ // any AST and therefore no quick fix will be triggered.
+ change = formatter.format(file->cppDocument()->translationUnit()->ast());
+ if (! change.isEmpty())
+ result.append(QuickFixOperation::Ptr(new Operation(interface, change)));
+ } else {
+ for (int index = path.size() - 1; index >= 0; --index) {
+ AST *ast = path.at(index);
+
+ change = formatter.format(ast);
+ if (! change.isEmpty()) {
+ result.append(QuickFixOperation::Ptr(new Operation(interface, change)));
+ return;
+ }
+ }
+ }
+ }
+
+private:
+ class Operation: public CppQuickFixOperation
+ {
+ public:
+ Operation(const CppQuickFixInterface &interface, const ChangeSet change)
+ : CppQuickFixOperation(interface)
+ , m_change(change)
+ {
+ QString description;
+ if (m_change.operationList().size() == 1) {
+ description = QApplication::translate("CppTools::QuickFix",
+ "Reformat to \"%1\"").arg(m_change.operationList().first().text);
+ } else { // > 1
+ description = QApplication::translate("CppTools::QuickFix",
+ "Reformat pointers/references");
+ }
+ setDescription(description);
+ }
+
+ void perform()
+ {
+ CppRefactoringChanges refactoring(snapshot());
+ CppRefactoringFilePtr currentFile = refactoring.file(fileName());
+ currentFile->setChangeSet(m_change);
+ currentFile->apply();
+ }
+
+ private:
+ ChangeSet m_change;
+ };
+};
+
} // end of anonymous namespace
void registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
@@ -2084,5 +2174,7 @@ void registerQuickFixes(ExtensionSystem::IPlugin *plugIn)
plugIn->addAutoReleasedObject(new ApplyDeclDefLinkChanges);
plugIn->addAutoReleasedObject(new IncludeAdder);
plugIn->addAutoReleasedObject(new ExtractFunction);
+ plugIn->addAutoReleasedObject(new GetterSetter);
plugIn->addAutoReleasedObject(new RearrangeParamDeclList);
+ plugIn->addAutoReleasedObject(new PointerDeclarationFormatterOp);
}
diff --git a/src/plugins/cppeditor/cpptypehierarchy.cpp b/src/plugins/cppeditor/cpptypehierarchy.cpp
index d6e2dbd52e..d640b38943 100644
--- a/src/plugins/cppeditor/cpptypehierarchy.cpp
+++ b/src/plugins/cppeditor/cpptypehierarchy.cpp
@@ -60,20 +60,20 @@ enum ItemRole {
QStandardItem *itemForClass(const CppClass &cppClass)
{
QStandardItem *item = new QStandardItem;
- item->setData(cppClass.name(), Qt::DisplayRole);
- if (cppClass.name() != cppClass.qualifiedName())
- item->setData(cppClass.qualifiedName(), AnnotationRole);
- item->setData(cppClass.icon(), Qt::DecorationRole);
+ item->setData(cppClass.name, Qt::DisplayRole);
+ if (cppClass.name != cppClass.qualifiedName)
+ item->setData(cppClass.qualifiedName, AnnotationRole);
+ item->setData(cppClass.icon, Qt::DecorationRole);
QVariant link;
- link.setValue(CPPEditorWidget::Link(cppClass.link()));
+ link.setValue(CPPEditorWidget::Link(cppClass.link));
item->setData(link, LinkRole);
return item;
}
bool compareCppClassNames(const CppClass &c1, const CppClass &c2)
{
- const QString key1 = c1.name() + QLatin1String("::") + c1.qualifiedName();
- const QString key2 = c2.name() + QLatin1String("::") + c2.qualifiedName();
+ const QString key1 = c1.name + QLatin1String("::") + c1.qualifiedName;
+ const QString key2 = c2.name + QLatin1String("::") + c2.qualifiedName;
return key1 < key2;
}
@@ -98,8 +98,8 @@ public:
void setup(CppClass *cppClass)
{
- setText(cppClass->name());
- m_link = cppClass->link();
+ setText(cppClass->name);
+ m_link = cppClass->link;
}
private:
@@ -192,15 +192,15 @@ void CppTypeHierarchyWidget::perform()
}
}
-void CppTypeHierarchyWidget::buildHierarchy(const CppClass &cppClass, QStandardItem *parent, bool isRoot, HierarchyFunc func)
+void CppTypeHierarchyWidget::buildHierarchy(const CppClass &cppClass, QStandardItem *parent, bool isRoot, const HierarchyMember member)
{
if (!isRoot) {
QStandardItem *item = itemForClass(cppClass);
parent->appendRow(item);
parent = item;
}
- foreach (const CppClass &klass, sortClasses((cppClass.*func)()))
- buildHierarchy(klass, parent, false, func);
+ foreach (const CppClass &klass, sortClasses(cppClass.*member))
+ buildHierarchy(klass, parent, false, member);
}
void CppTypeHierarchyWidget::onItemClicked(const QModelIndex &index)
diff --git a/src/plugins/cppeditor/cpptypehierarchy.h b/src/plugins/cppeditor/cpptypehierarchy.h
index 026633f72e..eb8f426925 100644
--- a/src/plugins/cppeditor/cpptypehierarchy.h
+++ b/src/plugins/cppeditor/cpptypehierarchy.h
@@ -75,8 +75,8 @@ private slots:
void onItemClicked(const QModelIndex &index);
private:
- typedef const QList<CppClass> &(CppClass::* HierarchyFunc)() const;
- void buildHierarchy(const CppClass &cppClass, QStandardItem *parent, bool isRoot, HierarchyFunc func);
+ typedef QList<CppClass> CppClass::*HierarchyMember;
+ void buildHierarchy(const CppClass &cppClass, QStandardItem *parent, bool isRoot, HierarchyMember member);
CPPEditorWidget *m_cppEditor;
Utils::NavigationTreeView *m_treeView;
diff --git a/src/plugins/cpptools/ModelManagerInterface.cpp b/src/plugins/cpptools/ModelManagerInterface.cpp
index 41f60f0940..c7d52785da 100644
--- a/src/plugins/cpptools/ModelManagerInterface.cpp
+++ b/src/plugins/cpptools/ModelManagerInterface.cpp
@@ -28,13 +28,31 @@
****************************************************************************/
#include "ModelManagerInterface.h"
+#include "pp-engine.h"
#include <QtCore/QSet>
+/*!
+ \enum CPlusPlus::CppModelManagerInterface::QtVersion
+ Allows C++ parser engine to inject headers or change inner settings as
+ needed to parse Qt language extensions for concrete major Qt version
+ \value UnknownQt
+ Parser may choose any policy
+ \value NoQt
+ Parser must not use special tricks, because it parses non-qt project
+ \value Qt4
+ Parser may enable tricks for Qt v4.x
+ \value Qt5
+ Parser may enable tricks for Qt v5.x
+*/
+
using namespace CPlusPlus;
static CppModelManagerInterface *g_instance = 0;
+const QString CppModelManagerInterface::configurationFileName()
+{ return Preprocessor::configurationFileName; }
+
CppModelManagerInterface::CppModelManagerInterface(QObject *parent)
: QObject(parent)
{
@@ -85,8 +103,12 @@ void CppModelManagerInterface::ProjectInfo::appendProjectPart(
// update source files
QSet<QString> srcs = QSet<QString>::fromList(m_sourceFiles);
+ foreach (const QString &src, part->headerFiles)
+ srcs.insert(src);
foreach (const QString &src, part->sourceFiles)
srcs.insert(src);
+ foreach (const QString &src, part->objcSourceFiles)
+ srcs.insert(src);
m_sourceFiles = srcs.toList();
// update defines
diff --git a/src/plugins/cpptools/ModelManagerInterface.h b/src/plugins/cpptools/ModelManagerInterface.h
index 189b7e7b83..f57b038778 100644
--- a/src/plugins/cpptools/ModelManagerInterface.h
+++ b/src/plugins/cpptools/ModelManagerInterface.h
@@ -58,6 +58,7 @@ namespace CppTools {
class CppCompletionAssistProvider;
class CppHighlightingSupport;
class CppHighlightingSupportFactory;
+ class CppIndexingSupport;
}
namespace CPlusPlus {
@@ -67,37 +68,41 @@ class CPPTOOLS_EXPORT CppModelManagerInterface : public QObject
Q_OBJECT
public:
- enum Language { CXX, OBJC };
class CPPTOOLS_EXPORT ProjectPart
{
public:
ProjectPart()
- : language(CXX)
- , cxx11Enabled(false)
+ : language(CXX11)
, qtVersion(UnknownQt)
{}
- public: //attributes
- QStringList sourceFiles;
- QByteArray defines;
- QStringList includePaths;
- QStringList frameworkPaths;
- QStringList precompiledHeaders;
- Language language;
- bool cxx11Enabled;
+ public: // enums and types
+ enum Language {
+ C89 = 1,
+ C99 = 2,
+ CXX = 3,
+ CXX11 = 4
+ };
enum QtVersion {
UnknownQt = -1,
NoQt = 0,
Qt4 = 1,
Qt5 = 2
};
- QtVersion qtVersion;
-
- bool objcEnabled() const
- { return language == CppModelManagerInterface::OBJC; }
typedef QSharedPointer<ProjectPart> Ptr;
+
+ public: //attributes
+ QStringList headerFiles;
+ QStringList sourceFiles;
+ QStringList objcSourceFiles;
+ QByteArray defines;
+ QStringList includePaths;
+ QStringList frameworkPaths;
+ QStringList precompiledHeaders;
+ Language language;
+ QtVersion qtVersion;
};
class CPPTOOLS_EXPORT ProjectInfo
@@ -106,7 +111,7 @@ public:
ProjectInfo()
{ }
- ProjectInfo(QWeakPointer<ProjectExplorer::Project> project)
+ ProjectInfo(QPointer<ProjectExplorer::Project> project)
: m_project(project)
{ }
@@ -119,7 +124,7 @@ public:
bool isNull() const
{ return m_project.isNull(); }
- QWeakPointer<ProjectExplorer::Project> project() const
+ QPointer<ProjectExplorer::Project> project() const
{ return m_project; }
const QList<ProjectPart::Ptr> projectParts() const
@@ -141,7 +146,7 @@ public:
{ return m_defines; }
private: // attributes
- QWeakPointer<ProjectExplorer::Project> m_project;
+ QPointer<ProjectExplorer::Project> m_project;
QList<ProjectPart::Ptr> m_projectParts;
// the attributes below are calculated from the project parts.
QStringList m_includePaths;
@@ -168,6 +173,9 @@ public:
QHashIterator<QString, QPair<QString, unsigned> > iterator() const
{ return QHashIterator<QString, QPair<QString, unsigned> >(_elements); }
+ int size() const
+ { return _elements.size(); }
+
private:
typedef QHash<QString, QPair<QString, unsigned> > Table;
Table _elements;
@@ -181,6 +189,9 @@ public:
};
public:
+ static const QString configurationFileName();
+
+public:
CppModelManagerInterface(QObject *parent = 0);
virtual ~CppModelManagerInterface();
@@ -220,11 +231,19 @@ public:
virtual CppTools::CppHighlightingSupport *highlightingSupport(Core::IEditor *editor) const = 0;
virtual void setHighlightingSupportFactory(CppTools::CppHighlightingSupportFactory *highlightingFactory) = 0;
+ virtual void setIndexingSupport(CppTools::CppIndexingSupport *indexingSupport) = 0;
+ virtual CppTools::CppIndexingSupport *indexingSupport() = 0;
+
Q_SIGNALS:
void documentUpdated(CPlusPlus::Document::Ptr doc);
void sourceFilesRefreshed(const QStringList &files);
void extraDiagnosticsUpdated(QString fileName);
+ /// \brief Emitted after updateProjectInfo method is called on the model-manager.
+ ///
+ /// Other classes can use this to get notified when the \c ProjectExplorer has updated the parts.
+ void projectPartsUpdated(ProjectExplorer::Project *project);
+
public Q_SLOTS:
virtual void updateModifiedSourceFiles() = 0;
virtual QFuture<void> updateSourceFiles(const QStringList &sourceFiles) = 0;
diff --git a/src/plugins/cpptools/builtinindexingsupport.cpp b/src/plugins/cpptools/builtinindexingsupport.cpp
new file mode 100644
index 0000000000..1c98d6cb03
--- /dev/null
+++ b/src/plugins/cpptools/builtinindexingsupport.cpp
@@ -0,0 +1,213 @@
+#include "builtinindexingsupport.h"
+#include "cppmodelmanager.h"
+#include "searchsymbols.h"
+
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
+#include <coreplugin/progressmanager/progressmanager.h>
+#include <utils/runextensions.h>
+
+#include <QCoreApplication>
+
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+namespace {
+
+static void parse(QFutureInterface<void> &future,
+ CppPreprocessor *preproc,
+ QStringList files)
+{
+ if (files.isEmpty())
+ return;
+
+ const Core::MimeDatabase *mimeDb = Core::ICore::mimeDatabase();
+ Core::MimeType cSourceTy = mimeDb->findByType(QLatin1String("text/x-csrc"));
+ Core::MimeType cppSourceTy = mimeDb->findByType(QLatin1String("text/x-c++src"));
+ Core::MimeType mSourceTy = mimeDb->findByType(QLatin1String("text/x-objcsrc"));
+
+ QStringList sources;
+ QStringList headers;
+
+ QStringList suffixes = cSourceTy.suffixes();
+ suffixes += cppSourceTy.suffixes();
+ suffixes += mSourceTy.suffixes();
+
+ foreach (const QString &file, files) {
+ QFileInfo info(file);
+
+ preproc->m_snapshot.remove(file);
+
+ if (suffixes.contains(info.suffix()))
+ sources.append(file);
+ else
+ headers.append(file);
+ }
+
+ const int sourceCount = sources.size();
+ files = sources;
+ files += headers;
+
+ preproc->setTodo(files);
+
+ future.setProgressRange(0, files.size());
+
+ const QString conf = CPlusPlus::CppModelManagerInterface::configurationFileName();
+ bool processingHeaders = false;
+
+ for (int i = 0; i < files.size(); ++i) {
+ if (future.isPaused())
+ future.waitForResume();
+
+ if (future.isCanceled())
+ break;
+
+ const QString fileName = files.at(i);
+
+ const bool isSourceFile = i < sourceCount;
+ if (isSourceFile)
+ (void) preproc->run(conf);
+
+ else if (! processingHeaders) {
+ (void) preproc->run(conf);
+
+ processingHeaders = true;
+ }
+
+ preproc->run(fileName);
+
+ future.setProgressValue(files.size() - preproc->todo().size());
+
+ if (isSourceFile)
+ preproc->resetEnvironment();
+ }
+
+ future.setProgressValue(files.size());
+ preproc->modelManager()->finishedRefreshingSourceFiles(files);
+
+ delete preproc;
+}
+
+class BuiltinSymbolSearcher: public SymbolSearcher
+{
+public:
+ BuiltinSymbolSearcher(const CPlusPlus::Snapshot &snapshot,
+ Parameters parameters, QSet<QString> fileNames)
+ : m_snapshot(snapshot)
+ , m_parameters(parameters)
+ , m_fileNames(fileNames)
+ {}
+
+ ~BuiltinSymbolSearcher()
+ {}
+
+ void runSearch(QFutureInterface<Find::SearchResultItem> &future)
+ {
+ future.setProgressRange(0, m_snapshot.size());
+ future.setProgressValue(0);
+ int progress = 0;
+
+ SearchSymbols search;
+ search.setSymbolsToSearchFor(m_parameters.types);
+ search.setSeparateScope(true);
+ CPlusPlus::Snapshot::const_iterator it = m_snapshot.begin();
+
+ QString findString = (m_parameters.flags & Find::FindRegularExpression
+ ? m_parameters.text : QRegExp::escape(m_parameters.text));
+ if (m_parameters.flags & Find::FindWholeWords)
+ findString = QString::fromLatin1("\\b%1\\b").arg(findString);
+ QRegExp matcher(findString, (m_parameters.flags & Find::FindCaseSensitively
+ ? Qt::CaseSensitive : Qt::CaseInsensitive));
+ while (it != m_snapshot.end()) {
+ if (future.isPaused())
+ future.waitForResume();
+ if (future.isCanceled())
+ break;
+ if (m_fileNames.isEmpty() || m_fileNames.contains(it.value()->fileName())) {
+ QVector<Find::SearchResultItem> resultItems;
+ QList<ModelItemInfo> modelInfos = search(it.value());
+ foreach (const ModelItemInfo &info, modelInfos) {
+ int index = matcher.indexIn(info.symbolName);
+ if (index != -1) {
+ QStringList path = info.fullyQualifiedName.mid(0,
+ info.fullyQualifiedName.size() - 1);
+ Find::SearchResultItem item;
+ item.path = path;
+ item.text = info.symbolName;
+ item.textMarkPos = -1;
+ item.textMarkLength = 0;
+ item.icon = info.icon;
+ item.lineNumber = -1;
+ item.userData = qVariantFromValue(info);
+ resultItems << item;
+ }
+ }
+ if (!resultItems.isEmpty())
+ future.reportResults(resultItems);
+ }
+ ++it;
+ ++progress;
+ future.setProgressValue(progress);
+ }
+ if (future.isPaused())
+ future.waitForResume();
+ }
+
+private:
+ const CPlusPlus::Snapshot m_snapshot;
+ const Parameters m_parameters;
+ const QSet<QString> m_fileNames;
+};
+
+} // anonymous namespace
+
+BuiltinIndexingSupport::BuiltinIndexingSupport()
+ : m_revision(0)
+{
+ m_synchronizer.setCancelOnWait(true);
+ m_dumpFileNameWhileParsing = !qgetenv("QTCREATOR_DUMP_FILENAME_WHILE_PARSING").isNull();
+}
+
+BuiltinIndexingSupport::~BuiltinIndexingSupport()
+{}
+
+QFuture<void> BuiltinIndexingSupport::refreshSourceFiles(const QStringList &sourceFiles)
+{
+ CppModelManager *mgr = CppModelManager::instance();
+ const WorkingCopy workingCopy = mgr->workingCopy();
+
+ CppPreprocessor *preproc = new CppPreprocessor(mgr, m_dumpFileNameWhileParsing);
+ preproc->setRevision(++m_revision);
+ preproc->setProjectFiles(mgr->projectFiles());
+ preproc->setIncludePaths(mgr->includePaths());
+ preproc->setFrameworkPaths(mgr->frameworkPaths());
+ preproc->setWorkingCopy(workingCopy);
+
+ QFuture<void> result = QtConcurrent::run(&parse, preproc, sourceFiles);
+
+ if (m_synchronizer.futures().size() > 10) {
+ QList<QFuture<void> > futures = m_synchronizer.futures();
+
+ m_synchronizer.clearFutures();
+
+ foreach (const QFuture<void> &future, futures) {
+ if (! (future.isFinished() || future.isCanceled()))
+ m_synchronizer.addFuture(future);
+ }
+ }
+
+ m_synchronizer.addFuture(result);
+
+ if (sourceFiles.count() > 1) {
+ Core::ICore::progressManager()->addTask(result,
+ QCoreApplication::translate("CppTools::Internal::BuiltinIndexingSupport", "Parsing"),
+ QLatin1String(CppTools::Constants::TASK_INDEX));
+ }
+
+ return result;
+}
+
+SymbolSearcher *BuiltinIndexingSupport::createSymbolSearcher(SymbolSearcher::Parameters parameters, QSet<QString> fileNames)
+{
+ return new BuiltinSymbolSearcher(CppModelManager::instance()->snapshot(), parameters, fileNames);
+}
diff --git a/src/plugins/cpptools/builtinindexingsupport.h b/src/plugins/cpptools/builtinindexingsupport.h
new file mode 100644
index 0000000000..7d4c7ff849
--- /dev/null
+++ b/src/plugins/cpptools/builtinindexingsupport.h
@@ -0,0 +1,32 @@
+#ifndef BUILTININDEXINGSUPPORT_H
+#define BUILTININDEXINGSUPPORT_H
+
+#include "cppindexingsupport.h"
+#include "ModelManagerInterface.h"
+
+#include <QFutureSynchronizer>
+
+namespace CppTools {
+namespace Internal {
+
+class BuiltinIndexingSupport: public CppIndexingSupport {
+public:
+ typedef CPlusPlus::CppModelManagerInterface::WorkingCopy WorkingCopy;
+
+public:
+ BuiltinIndexingSupport();
+ ~BuiltinIndexingSupport();
+
+ virtual QFuture<void> refreshSourceFiles(const QStringList &sourceFiles);
+ virtual SymbolSearcher *createSymbolSearcher(SymbolSearcher::Parameters parameters, QSet<QString> fileNames);
+
+private:
+ QFutureSynchronizer<void> m_synchronizer;
+ unsigned m_revision;
+ bool m_dumpFileNameWhileParsing;
+};
+
+} // namespace Internal
+} // namespace CppTools
+
+#endif // BUILTININDEXINGSUPPORT_H
diff --git a/src/plugins/cpptools/completionsettingspage.cpp b/src/plugins/cpptools/completionsettingspage.cpp
index d790e50d31..a1f787f4f6 100644
--- a/src/plugins/cpptools/completionsettingspage.cpp
+++ b/src/plugins/cpptools/completionsettingspage.cpp
@@ -48,7 +48,7 @@ CompletionSettingsPage::CompletionSettingsPage(QObject *parent)
{
m_commentsSettings.fromSettings(QLatin1String(CPPTOOLS_SETTINGSGROUP), Core::ICore::settings());
- setId(QLatin1String("P.Completion"));
+ setId("P.Completion");
setDisplayName(tr("Completion"));
}
diff --git a/src/plugins/cpptools/cppchecksymbols.cpp b/src/plugins/cpptools/cppchecksymbols.cpp
index 55d1a6ac85..afd77fc795 100644
--- a/src/plugins/cpptools/cppchecksymbols.cpp
+++ b/src/plugins/cpptools/cppchecksymbols.cpp
@@ -324,6 +324,8 @@ CheckSymbols::CheckSymbols(Document::Ptr doc, const LookupContext &context, cons
_potentialStatics = collectTypes.statics();
typeOfExpression.init(_doc, _context.snapshot(), _context.bindings());
+ // make possible to instantiate templates
+ typeOfExpression.setExpandTemplates(true);
}
CheckSymbols::~CheckSymbols()
@@ -513,7 +515,7 @@ bool CheckSymbols::visit(SimpleDeclarationAST *ast)
"CPlusplus::CheckSymbols", "Only virtual methods can be marked `override'"));
else if (funTy->isFinal())
warning(declrIdNameAST, QCoreApplication::translate(
- "CPlusplus::CheckSymbols", "Only virtual methods can be marked `final'"));
+ "CPlusPlus::CheckSymbols", "Only virtual methods can be marked `final'"));
}
}
}
@@ -664,13 +666,13 @@ bool CheckSymbols::visit(NewExpressionAST *ast)
if (binding && nameAST) {
int arguments = 0;
if (ast->new_initializer) {
- if (ExpressionAST *expr = ast->new_initializer->expression) {
- while (BinaryExpressionAST *binExpr = expr->asBinaryExpression()) {
- expr = binExpr->right_expression;
- ++arguments;
- }
- }
-
+ ExpressionListAST *list = 0;
+ if (ExpressionListParenAST *exprListParen = ast->new_initializer->asExpressionListParen())
+ list = exprListParen->expression_list;
+ else if (BracedInitializerAST *braceInit = ast->new_initializer->asBracedInitializer())
+ list = braceInit->expression_list;
+ for (ExpressionListAST *it = list; it; it = it->next)
+ ++arguments;
}
Scope *scope = enclosingScope();
@@ -785,7 +787,11 @@ void CheckSymbols::checkName(NameAST *ast, Scope *scope)
}
}
} else if (maybeType(ast->name) || maybeStatic(ast->name)) {
- maybeAddTypeOrStatic(_context.lookup(ast->name, scope), ast);
+ if (! maybeAddTypeOrStatic(_context.lookup(ast->name, scope), ast)) {
+ // it can be a local variable
+ if (maybeField(ast->name))
+ maybeAddField(_context.lookup(ast->name, scope), ast);
+ }
} else if (maybeField(ast->name)) {
maybeAddField(_context.lookup(ast->name, scope), ast);
}
@@ -925,10 +931,17 @@ bool CheckSymbols::visit(MemInitializerAST *ast)
} else if (maybeField(nameAST->name)) {
maybeAddField(_context.lookup(nameAST->name, klass), nameAST);
} else {
- // It's a constructor
+ // It's a constructor, count the number of arguments
unsigned arguments = 0;
- for (ExpressionListAST *it = ast->expression_list; it; it = it->next)
- ++arguments;
+ if (ast->expression) {
+ ExpressionListAST *expr_list = 0;
+ if (ExpressionListParenAST *parenExprList = ast->expression->asExpressionListParen())
+ expr_list = parenExprList->expression_list;
+ else if (BracedInitializerAST *bracedInitList = ast->expression->asBracedInitializer())
+ expr_list = bracedInitList->expression_list;
+ for (ExpressionListAST *it = expr_list; it; it = it->next)
+ ++arguments;
+ }
maybeAddFunction(_context.lookup(nameAST->name, klass), nameAST, arguments);
}
@@ -938,7 +951,7 @@ bool CheckSymbols::visit(MemInitializerAST *ast)
}
}
- accept(ast->expression_list);
+ accept(ast->expression);
}
return false;
@@ -1155,6 +1168,7 @@ bool CheckSymbols::maybeAddTypeOrStatic(const QList<LookupItem> &candidates, Nam
else if (c->isUsingNamespaceDirective()) // ... and using namespace directives.
continue;
else if (c->isTypedef() || c->isNamespace() ||
+ c->isStatic() || //consider also static variable
c->isClass() || c->isEnum() || isTemplateClass(c) ||
c->isForwardClassDeclaration() || c->isTypenameArgument() || c->enclosingEnum() != 0) {
@@ -1165,6 +1179,9 @@ bool CheckSymbols::maybeAddTypeOrStatic(const QList<LookupItem> &candidates, Nam
UseKind kind = SemanticInfo::TypeUse;
if (c->enclosingEnum() != 0)
kind = SemanticInfo::EnumerationUse;
+ else if (c->isStatic())
+ // treat static variable as a field(highlighting)
+ kind = SemanticInfo::FieldUse;
const Use use(line, column, length, kind);
addUse(use);
@@ -1194,7 +1211,7 @@ bool CheckSymbols::maybeAddField(const QList<LookupItem> &candidates, NameAST *a
return false;
else if (! (c->enclosingScope() && c->enclosingScope()->isClass()))
return false; // shadowed
- else if (c->isTypedef() || c->type()->isFunctionType())
+ else if (c->isTypedef() || (c->type() && c->type()->isFunctionType()))
return false; // shadowed
unsigned line, column;
@@ -1282,9 +1299,9 @@ bool CheckSymbols::maybeAddFunction(const QList<LookupItem> &candidates, NameAST
// Add a diagnostic message if argument count does not match
if (matchType == Match_TooFewArgs)
- warning(line, column, QCoreApplication::translate("CPlusplus::CheckSymbols", "Too few arguments"), length);
+ warning(line, column, QCoreApplication::translate("CplusPlus::CheckSymbols", "Too few arguments"), length);
else if (matchType == Match_TooManyArgs)
- warning(line, column, QCoreApplication::translate("CPlusplus::CheckSymbols", "Too many arguments"), length);
+ warning(line, column, QCoreApplication::translate("CPlusPlus::CheckSymbols", "Too many arguments"), length);
const Use use(line, column, length, kind);
addUse(use);
diff --git a/src/plugins/cpptools/cppchecksymbols.h b/src/plugins/cpptools/cppchecksymbols.h
index 22f11d6eac..ce8e9fecb0 100644
--- a/src/plugins/cpptools/cppchecksymbols.h
+++ b/src/plugins/cpptools/cppchecksymbols.h
@@ -30,6 +30,8 @@
#ifndef CPLUSPLUS_CHECKSYMBOLS_H
#define CPLUSPLUS_CHECKSYMBOLS_H
+#include "cpptools_global.h"
+
#include "cppsemanticinfo.h"
#include <cplusplus/CppDocument.h>
@@ -45,7 +47,7 @@
namespace CPlusPlus {
-class CheckSymbols:
+class CPPTOOLS_EXPORT CheckSymbols:
protected ASTVisitor,
public QRunnable,
public QFutureInterface<TextEditor::SemanticHighlighter::Result>
diff --git a/src/plugins/cpptools/cppclassesfilter.cpp b/src/plugins/cpptools/cppclassesfilter.cpp
index 08a1aa9db4..3c656d3fc6 100644
--- a/src/plugins/cpptools/cppclassesfilter.cpp
+++ b/src/plugins/cpptools/cppclassesfilter.cpp
@@ -35,10 +35,12 @@ using namespace CppTools::Internal;
CppClassesFilter::CppClassesFilter(CppModelManager *manager)
: CppLocatorFilter(manager)
{
- setShortcutString("c");
+ setId("Classes");
+ setShortcutString(QLatin1String("c"));
setIncludedByDefault(false);
+ setDisplayName(tr("C++ Classes"));
- search.setSymbolsToSearchFor(SearchSymbols::Classes);
+ search.setSymbolsToSearchFor(SymbolSearcher::Classes);
search.setSeparateScope(true);
}
diff --git a/src/plugins/cpptools/cppclassesfilter.h b/src/plugins/cpptools/cppclassesfilter.h
index 594bd6a077..52038d3638 100644
--- a/src/plugins/cpptools/cppclassesfilter.h
+++ b/src/plugins/cpptools/cppclassesfilter.h
@@ -42,10 +42,6 @@ class CPPTOOLS_EXPORT CppClassesFilter : public Internal::CppLocatorFilter
public:
CppClassesFilter(Internal::CppModelManager *manager);
~CppClassesFilter();
-
- QString displayName() const { return tr("Classes"); }
- QString id() const { return QLatin1String("Classes"); }
- Priority priority() const { return Medium; }
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/cppcodeformatter.cpp b/src/plugins/cpptools/cppcodeformatter.cpp
index f1c55b7347..342b426fef 100644
--- a/src/plugins/cpptools/cppcodeformatter.cpp
+++ b/src/plugins/cpptools/cppcodeformatter.cpp
@@ -299,6 +299,13 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block)
default: tryExpression(); break;
} break;
+ case braceinit_open:
+ switch (kind) {
+ case T_RBRACE: leave(); break;
+ case T_RPAREN: leave(); continue; // recover?
+ default: tryExpression(); break;
+ } break;
+
case ternary_op:
switch (kind) {
case T_RPAREN:
@@ -339,14 +346,16 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block)
case member_init:
switch (kind) {
- case T_LPAREN: enter(member_init_paren_open); break;
- case T_RPAREN: leave(); break;
case T_LBRACE:
+ case T_LPAREN: enter(member_init_nest_open); break;
+ case T_RBRACE:
+ case T_RPAREN: leave(); break;
case T_SEMICOLON: leave(); continue; // try to recover
} break;
- case member_init_paren_open:
+ case member_init_nest_open:
switch (kind) {
+ case T_RBRACE:
case T_RPAREN: leave(); continue;
case T_SEMICOLON: leave(); continue; // try to recover
default: tryExpression(); break;
@@ -468,7 +477,7 @@ void CodeFormatter::recalculateStateAfter(const QTextBlock &block)
case block_open:
if (tryStatement())
break;
- switch(kind) {
+ switch (kind) {
case T_RBRACE: leave(true); break;
} break;
@@ -757,13 +766,14 @@ void CodeFormatter::correctIndentation(const QTextBlock &block)
}
bool CodeFormatter::tryExpression(bool alsoExpression)
-{
+{
int newState = -1;
const int kind = m_currentToken.kind();
switch (kind) {
case T_LPAREN: newState = arglist_open; break;
case T_QUESTION: newState = ternary_op; break;
+ case T_LBRACE: newState = braceinit_open; break;
case T_EQUAL:
case T_AMPER_EQUAL:
@@ -979,11 +989,10 @@ int CodeFormatter::column(int index) const
const QChar tab = QLatin1Char('\t');
for (int i = 0; i < index; i++) {
- if (m_currentLine[i] == tab) {
+ if (m_currentLine[i] == tab)
col = ((col / m_tabSize) + 1) * m_tabSize;
- } else {
+ else
col++;
- }
}
return col;
}
@@ -1017,7 +1026,7 @@ void CodeFormatter::saveCurrentState(const QTextBlock &block)
void CodeFormatter::restoreCurrentState(const QTextBlock &block)
{
- if (block.isValid()) {
+ if (block.isValid()) {
BlockData blockData;
if (loadBlockData(block, &blockData)) {
m_indentDepth = blockData.m_indentDepth;
@@ -1234,7 +1243,7 @@ void QtStyleCodeFormatter::onEnter(int newState, int *indentDepth, int *savedInd
case arglist_open:
case condition_paren_open:
- case member_init_paren_open:
+ case member_init_nest_open:
if (!lastToken)
*paddingDepth = nextTokenPosition-*indentDepth;
else
@@ -1318,9 +1327,8 @@ void QtStyleCodeFormatter::onEnter(int newState, int *indentDepth, int *savedInd
*indentDepth += m_tabSettings.m_indentSize;
}
- if (followedByData) {
+ if (followedByData)
*paddingDepth = nextTokenPosition-*indentDepth;
- }
break;
}
@@ -1473,11 +1481,10 @@ void QtStyleCodeFormatter::adjustIndent(const QList<CPlusPlus::Token> &tokens, i
} else if ((topState.type == expression && previousState.type == declaration_start)
|| topState.type == member_init || topState.type == member_init_open) {
// the declaration_start indent is the base
- if (topState.type == member_init) {
+ if (topState.type == member_init)
*indentDepth = state(2).savedIndentDepth;
- } else {
+ else
*indentDepth = previousState.savedIndentDepth;
- }
if (m_styleSettings.indentFunctionBraces)
*indentDepth += m_tabSettings.m_indentSize;
*paddingDepth = 0;
diff --git a/src/plugins/cpptools/cppcodeformatter.h b/src/plugins/cpptools/cppcodeformatter.h
index c30785bcbf..c175734f2b 100644
--- a/src/plugins/cpptools/cppcodeformatter.h
+++ b/src/plugins/cpptools/cppcodeformatter.h
@@ -123,7 +123,7 @@ public: // must be public to make Q_GADGET introspection work
member_init_open, // After ':' that starts a member initialization list.
member_init_expected, // At the start and after every ',' in member_init_open
member_init, // After an identifier in member_init_expected
- member_init_paren_open, // After '(' in member_init.
+ member_init_nest_open, // After '(' or '{' in member_init.
enum_start, // After 'enum'
enum_open, // Brace that opens a enum declaration.
@@ -167,6 +167,7 @@ public: // must be public to make Q_GADGET introspection work
stream_op, // After a '<<' or '>>' in a context where it's likely a stream operator.
stream_op_cont, // When finding another stream operator in stream_op
ternary_op, // The ? : operator
+ braceinit_open, // after '{' in an expression context
condition_open, // Start of a condition in 'if', 'while', entered after opening paren
condition_paren_open, // After an lparen in a condition
diff --git a/src/plugins/cpptools/cppcodegen_test.cpp b/src/plugins/cpptools/cppcodegen_test.cpp
index 574b9ded48..6bc8fb89e5 100644
--- a/src/plugins/cpptools/cppcodegen_test.cpp
+++ b/src/plugins/cpptools/cppcodegen_test.cpp
@@ -68,7 +68,7 @@ void CppToolsPlugin::test_codegen_public_in_empty_class()
"};\n"
"\n";
- Document::Ptr doc = Document::create("public_in_empty_class");
+ Document::Ptr doc = Document::create(QLatin1String("public_in_empty_class"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -108,7 +108,7 @@ void CppToolsPlugin::test_codegen_public_in_nonempty_class()
"};\n" // line 4
"\n";
- Document::Ptr doc = Document::create("public_in_nonempty_class");
+ Document::Ptr doc = Document::create(QLatin1String("public_in_nonempty_class"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -148,7 +148,7 @@ void CppToolsPlugin::test_codegen_public_before_protected()
"};\n"
"\n";
- Document::Ptr doc = Document::create("public_before_protected");
+ Document::Ptr doc = Document::create(QLatin1String("public_before_protected"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -189,7 +189,7 @@ void CppToolsPlugin::test_codegen_private_after_protected()
"};\n"
"\n";
- Document::Ptr doc = Document::create("private_after_protected");
+ Document::Ptr doc = Document::create(QLatin1String("private_after_protected"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -230,7 +230,7 @@ void CppToolsPlugin::test_codegen_protected_in_nonempty_class()
"};\n" // line 4
"\n";
- Document::Ptr doc = Document::create("protected_in_nonempty_class");
+ Document::Ptr doc = Document::create(QLatin1String("protected_in_nonempty_class"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -271,7 +271,7 @@ void CppToolsPlugin::test_codegen_protected_between_public_and_private()
"};\n" // line 5
"\n";
- Document::Ptr doc = Document::create("protected_betwee_public_and_private");
+ Document::Ptr doc = Document::create(QLatin1String("protected_betwee_public_and_private"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -332,7 +332,7 @@ void CppToolsPlugin::test_codegen_qtdesigner_integration()
"\n"
"#endif // MAINWINDOW_H\n";
- Document::Ptr doc = Document::create("qtdesigner_integration");
+ Document::Ptr doc = Document::create(QLatin1String("qtdesigner_integration"));
doc->setUtf8Source(src);
doc->parse();
doc->check();
@@ -429,7 +429,7 @@ void CppToolsPlugin::test_codegen_definition_first_member()
"};\n"
"\n";
- const QByteArray dstText = QString(
+ const QByteArray dstText = QString::fromLatin1(
"\n"
"#include \"%1/file.h\"\n" // line 1
"int x;\n"
@@ -498,7 +498,7 @@ void CppToolsPlugin::test_codegen_definition_last_member()
"};\n"
"\n";
- const QByteArray dstText = QString(
+ const QByteArray dstText = QString::fromLatin1(
"\n"
"#include \"%1/file.h\"\n" // line 1
"int x;\n"
@@ -568,7 +568,7 @@ void CppToolsPlugin::test_codegen_definition_middle_member()
"};\n"
"\n";
- const QByteArray dstText = QString(
+ const QByteArray dstText = QString::fromLatin1(
"\n"
"#include \"%1/file.h\"\n" // line 1
"int x;\n"
diff --git a/src/plugins/cpptools/cppcodestylepreferences.cpp b/src/plugins/cpptools/cppcodestylepreferences.cpp
index 7013bd41a1..cfe6af734c 100644
--- a/src/plugins/cpptools/cppcodestylepreferences.cpp
+++ b/src/plugins/cpptools/cppcodestylepreferences.cpp
@@ -31,7 +31,7 @@
using namespace CppTools;
-static const char *settingsSuffixKey = "CodeStyleSettings";
+static const char settingsSuffixKey[] = "CodeStyleSettings";
CppCodeStylePreferences::CppCodeStylePreferences(QObject *parent) :
ICodeStylePreferences(parent)
@@ -71,9 +71,8 @@ void CppCodeStylePreferences::setCodeStyleSettings(const CppCodeStyleSettings &d
v.setValue(data);
emit valueChanged(v);
emit codeStyleSettingsChanged(m_data);
- if (!currentDelegate()) {
+ if (!currentDelegate())
emit currentValueChanged(v);
- }
}
CppCodeStyleSettings CppCodeStylePreferences::currentCodeStyleSettings() const
@@ -96,7 +95,7 @@ void CppCodeStylePreferences::slotCurrentValueChanged(const QVariant &value)
QString CppCodeStylePreferences::settingsSuffix() const
{
- return settingsSuffixKey;
+ return QLatin1String(settingsSuffixKey);
}
void CppCodeStylePreferences::toMap(const QString &prefix, QVariantMap *map) const
diff --git a/src/plugins/cpptools/cppcodestylepreferencesfactory.cpp b/src/plugins/cpptools/cppcodestylepreferencesfactory.cpp
index 13941a783d..50936a2f34 100644
--- a/src/plugins/cpptools/cppcodestylepreferencesfactory.cpp
+++ b/src/plugins/cpptools/cppcodestylepreferencesfactory.cpp
@@ -91,14 +91,14 @@ CppCodeStylePreferencesFactory::CppCodeStylePreferencesFactory()
{
}
-QString CppCodeStylePreferencesFactory::languageId()
+Core::Id CppCodeStylePreferencesFactory::languageId()
{
return Constants::CPP_SETTINGS_ID;
}
QString CppCodeStylePreferencesFactory::displayName()
{
- return Constants::CPP_SETTINGS_NAME;
+ return QString::fromUtf8(Constants::CPP_SETTINGS_NAME);
}
TextEditor::ICodeStylePreferences *CppCodeStylePreferencesFactory::createCodeStyle() const
diff --git a/src/plugins/cpptools/cppcodestylepreferencesfactory.h b/src/plugins/cpptools/cppcodestylepreferencesfactory.h
index bc02afdb17..5b303ab873 100644
--- a/src/plugins/cpptools/cppcodestylepreferencesfactory.h
+++ b/src/plugins/cpptools/cppcodestylepreferencesfactory.h
@@ -39,14 +39,14 @@ class CppCodeStylePreferencesFactory : public TextEditor::ICodeStylePreferencesF
public:
CppCodeStylePreferencesFactory();
- virtual QString languageId();
- virtual QString displayName();
- virtual TextEditor::ICodeStylePreferences *createCodeStyle() const;
- virtual QWidget *createEditor(TextEditor::ICodeStylePreferences *settings,
- QWidget *parent) const;
- virtual TextEditor::Indenter *createIndenter() const;
- virtual TextEditor::ISnippetProvider *snippetProvider() const;
- virtual QString previewText() const;
+ Core::Id languageId();
+ QString displayName();
+ TextEditor::ICodeStylePreferences *createCodeStyle() const;
+ QWidget *createEditor(TextEditor::ICodeStylePreferences *settings,
+ QWidget *parent) const;
+ TextEditor::Indenter *createIndenter() const;
+ TextEditor::ISnippetProvider *snippetProvider() const;
+ QString previewText() const;
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/cppcodestylesettings.cpp b/src/plugins/cpptools/cppcodestylesettings.cpp
index 6d9478ee06..17a140ad0e 100644
--- a/src/plugins/cpptools/cppcodestylesettings.cpp
+++ b/src/plugins/cpptools/cppcodestylesettings.cpp
@@ -28,26 +28,42 @@
****************************************************************************/
#include "cppcodestylesettings.h"
+#include "cppcodestylepreferencesfactory.h"
+
+#include <cpptools/cppcodestylepreferences.h>
+#include <cpptools/cppcodestylesettings.h>
+#include <cpptools/cpptoolsconstants.h>
+#include <cpptools/cpptoolssettings.h>
+
+#include <projectexplorer/editorconfiguration.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/projectexplorer.h>
+
+#include <utils/qtcassert.h>
#include <utils/settingsutils.h>
-static const char *groupPostfix = "IndentSettings";
-static const char *indentBlockBracesKey = "IndentBlockBraces";
-static const char *indentBlockBodyKey = "IndentBlockBody";
-static const char *indentClassBracesKey = "IndentClassBraces";
-static const char *indentEnumBracesKey = "IndentEnumBraces";
-static const char *indentNamespaceBracesKey = "IndentNamespaceBraces";
-static const char *indentNamespaceBodyKey = "IndentNamespaceBody";
-static const char *indentAccessSpecifiersKey = "IndentAccessSpecifiers";
-static const char *indentDeclarationsRelativeToAccessSpecifiersKey = "IndentDeclarationsRelativeToAccessSpecifiers";
-static const char *indentFunctionBodyKey = "IndentFunctionBody";
-static const char *indentFunctionBracesKey = "IndentFunctionBraces";
-static const char *indentSwitchLabelsKey = "IndentSwitchLabels";
-static const char *indentStatementsRelativeToSwitchLabelsKey = "IndentStatementsRelativeToSwitchLabels";
-static const char *indentBlocksRelativeToSwitchLabelsKey = "IndentBlocksRelativeToSwitchLabels";
-static const char *indentControlFlowRelativeToSwitchLabelsKey = "IndentControlFlowRelativeToSwitchLabels";
-static const char *extraPaddingForConditionsIfConfusingAlignKey = "ExtraPaddingForConditionsIfConfusingAlign";
-static const char *alignAssignmentsKey = "AlignAssignments";
+static const char groupPostfix[] = "IndentSettings";
+static const char indentBlockBracesKey[] = "IndentBlockBraces";
+static const char indentBlockBodyKey[] = "IndentBlockBody";
+static const char indentClassBracesKey[] = "IndentClassBraces";
+static const char indentEnumBracesKey[] = "IndentEnumBraces";
+static const char indentNamespaceBracesKey[] = "IndentNamespaceBraces";
+static const char indentNamespaceBodyKey[] = "IndentNamespaceBody";
+static const char indentAccessSpecifiersKey[] = "IndentAccessSpecifiers";
+static const char indentDeclarationsRelativeToAccessSpecifiersKey[] = "IndentDeclarationsRelativeToAccessSpecifiers";
+static const char indentFunctionBodyKey[] = "IndentFunctionBody";
+static const char indentFunctionBracesKey[] = "IndentFunctionBraces";
+static const char indentSwitchLabelsKey[] = "IndentSwitchLabels";
+static const char indentStatementsRelativeToSwitchLabelsKey[] = "IndentStatementsRelativeToSwitchLabels";
+static const char indentBlocksRelativeToSwitchLabelsKey[] = "IndentBlocksRelativeToSwitchLabels";
+static const char indentControlFlowRelativeToSwitchLabelsKey[] = "IndentControlFlowRelativeToSwitchLabels";
+static const char bindStarToIdentifierKey[] = "BindStarToIdentifier";
+static const char bindStarToTypeNameKey[] = "BindStarToTypeName";
+static const char bindStarToLeftSpecifierKey[] = "BindStarToLeftSpecifier";
+static const char bindStarToRightSpecifierKey[] = "BindStarToRightSpecifier";
+static const char extraPaddingForConditionsIfConfusingAlignKey[] = "ExtraPaddingForConditionsIfConfusingAlign";
+static const char alignAssignmentsKey[] = "AlignAssignments";
using namespace CppTools;
@@ -68,6 +84,10 @@ CppCodeStyleSettings::CppCodeStyleSettings() :
, indentStatementsRelativeToSwitchLabels(true)
, indentBlocksRelativeToSwitchLabels(false)
, indentControlFlowRelativeToSwitchLabels(true)
+ , bindStarToIdentifier(true)
+ , bindStarToTypeName(false)
+ , bindStarToLeftSpecifier(false)
+ , bindStarToRightSpecifier(false)
, extraPaddingForConditionsIfConfusingAlign(true)
, alignAssignments(false)
{
@@ -100,6 +120,10 @@ void CppCodeStyleSettings::toMap(const QString &prefix, QVariantMap *map) const
map->insert(prefix + QLatin1String(indentStatementsRelativeToSwitchLabelsKey), indentStatementsRelativeToSwitchLabels);
map->insert(prefix + QLatin1String(indentBlocksRelativeToSwitchLabelsKey), indentBlocksRelativeToSwitchLabels);
map->insert(prefix + QLatin1String(indentControlFlowRelativeToSwitchLabelsKey), indentControlFlowRelativeToSwitchLabels);
+ map->insert(prefix + QLatin1String(bindStarToIdentifierKey), bindStarToIdentifier);
+ map->insert(prefix + QLatin1String(bindStarToTypeNameKey), bindStarToTypeName);
+ map->insert(prefix + QLatin1String(bindStarToLeftSpecifierKey), bindStarToLeftSpecifier);
+ map->insert(prefix + QLatin1String(bindStarToRightSpecifierKey), bindStarToRightSpecifier);
map->insert(prefix + QLatin1String(extraPaddingForConditionsIfConfusingAlignKey), extraPaddingForConditionsIfConfusingAlign);
map->insert(prefix + QLatin1String(alignAssignmentsKey), alignAssignments);
}
@@ -134,6 +158,14 @@ void CppCodeStyleSettings::fromMap(const QString &prefix, const QVariantMap &map
indentBlocksRelativeToSwitchLabels).toBool();
indentControlFlowRelativeToSwitchLabels = map.value(prefix + QLatin1String(indentControlFlowRelativeToSwitchLabelsKey),
indentControlFlowRelativeToSwitchLabels).toBool();
+ bindStarToIdentifier = map.value(prefix + QLatin1String(bindStarToIdentifierKey),
+ bindStarToIdentifier).toBool();
+ bindStarToTypeName = map.value(prefix + QLatin1String(bindStarToTypeNameKey),
+ bindStarToTypeName).toBool();
+ bindStarToLeftSpecifier = map.value(prefix + QLatin1String(bindStarToLeftSpecifierKey),
+ bindStarToLeftSpecifier).toBool();
+ bindStarToRightSpecifier = map.value(prefix + QLatin1String(bindStarToRightSpecifierKey),
+ bindStarToRightSpecifier).toBool();
extraPaddingForConditionsIfConfusingAlign = map.value(prefix + QLatin1String(extraPaddingForConditionsIfConfusingAlignKey),
extraPaddingForConditionsIfConfusingAlign).toBool();
alignAssignments = map.value(prefix + QLatin1String(alignAssignmentsKey),
@@ -156,7 +188,61 @@ bool CppCodeStyleSettings::equals(const CppCodeStyleSettings &rhs) const
&& indentStatementsRelativeToSwitchLabels == rhs.indentStatementsRelativeToSwitchLabels
&& indentBlocksRelativeToSwitchLabels == rhs.indentBlocksRelativeToSwitchLabels
&& indentControlFlowRelativeToSwitchLabels == rhs.indentControlFlowRelativeToSwitchLabels
+ && bindStarToIdentifier == rhs.bindStarToIdentifier
+ && bindStarToTypeName == rhs.bindStarToTypeName
+ && bindStarToLeftSpecifier == rhs.bindStarToLeftSpecifier
+ && bindStarToRightSpecifier == rhs.bindStarToRightSpecifier
&& extraPaddingForConditionsIfConfusingAlign == rhs.extraPaddingForConditionsIfConfusingAlign
- && alignAssignments == rhs.alignAssignments;
+ && alignAssignments == rhs.alignAssignments;
+}
+
+static void configureOverviewWithCodeStyleSettings(CPlusPlus::Overview &overview,
+ const CppCodeStyleSettings &settings)
+{
+ overview.starBindFlags = CPlusPlus::Overview::StarBindFlags(0);
+ if (settings.bindStarToIdentifier)
+ overview.starBindFlags |= CPlusPlus::Overview::BindToIdentifier;
+ if (settings.bindStarToTypeName)
+ overview.starBindFlags |= CPlusPlus::Overview::BindToTypeName;
+ if (settings.bindStarToLeftSpecifier)
+ overview.starBindFlags |= CPlusPlus::Overview::BindToLeftSpecifier;
+ if (settings.bindStarToRightSpecifier)
+ overview.starBindFlags |= CPlusPlus::Overview::BindToRightSpecifier;
}
+CPlusPlus::Overview CppCodeStyleSettings::currentProjectCodeStyleOverview()
+{
+ ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ if (! project)
+ return currentGlobalCodeStyleOverview();
+
+ ProjectExplorer::EditorConfiguration *editorConfiguration = project->editorConfiguration();
+ QTC_ASSERT(editorConfiguration, return currentGlobalCodeStyleOverview());
+
+ TextEditor::ICodeStylePreferences *codeStylePreferences
+ = editorConfiguration->codeStyle(Constants::CPP_SETTINGS_ID);
+ QTC_ASSERT(codeStylePreferences, return currentGlobalCodeStyleOverview());
+
+ CppCodeStylePreferences *cppCodeStylePreferences
+ = dynamic_cast<CppCodeStylePreferences *>(codeStylePreferences);
+ QTC_ASSERT(cppCodeStylePreferences, return currentGlobalCodeStyleOverview());
+
+ CppCodeStyleSettings settings = cppCodeStylePreferences->currentCodeStyleSettings();
+
+ CPlusPlus::Overview overview;
+ configureOverviewWithCodeStyleSettings(overview, settings);
+ return overview;
+}
+
+CPlusPlus::Overview CppCodeStyleSettings::currentGlobalCodeStyleOverview()
+{
+ CPlusPlus::Overview overview;
+
+ CppCodeStylePreferences *cppCodeStylePreferences = CppToolsSettings::instance()->cppCodeStyle();
+ QTC_ASSERT(cppCodeStylePreferences, return overview);
+
+ CppCodeStyleSettings settings = cppCodeStylePreferences->currentCodeStyleSettings();
+
+ configureOverviewWithCodeStyleSettings(overview, settings);
+ return overview;
+}
diff --git a/src/plugins/cpptools/cppcodestylesettings.h b/src/plugins/cpptools/cppcodestylesettings.h
index a989fe819a..9a5ba5c28e 100644
--- a/src/plugins/cpptools/cppcodestylesettings.h
+++ b/src/plugins/cpptools/cppcodestylesettings.h
@@ -32,6 +32,8 @@
#include "cpptools_global.h"
+#include <cplusplus/Overview.h>
+
#include <QMetaType>
#include <QVariant>
@@ -61,6 +63,12 @@ public:
bool indentBlocksRelativeToSwitchLabels;
bool indentControlFlowRelativeToSwitchLabels;
+ // Formatting of pointer and reference declarations, see Overview::StarBindFlag.
+ bool bindStarToIdentifier;
+ bool bindStarToTypeName;
+ bool bindStarToLeftSpecifier;
+ bool bindStarToRightSpecifier;
+
// false: if (a &&
// b)
// c;
@@ -87,6 +95,21 @@ public:
bool equals(const CppCodeStyleSettings &rhs) const;
bool operator==(const CppCodeStyleSettings &s) const { return equals(s); }
bool operator!=(const CppCodeStyleSettings &s) const { return !equals(s); }
+
+ /*! Returns an Overview configured by the current project's code style.
+
+ If no current project is available or an error occurs when getting the
+ current project's code style, the current global code style settings
+ are applied.
+ */
+ static CPlusPlus::Overview currentProjectCodeStyleOverview();
+
+ /*! Returns an Overview configured by the current global code style.
+
+ If there occurred an error getting the current global code style, a
+ default constructed Overview is returned.
+ */
+ static CPlusPlus::Overview currentGlobalCodeStyleOverview();
};
} // namespace CppTools
diff --git a/src/plugins/cpptools/cppcodestylesettingspage.cpp b/src/plugins/cpptools/cppcodestylesettingspage.cpp
index 7e2b33a4cb..a8b9fee3fb 100644
--- a/src/plugins/cpptools/cppcodestylesettingspage.cpp
+++ b/src/plugins/cpptools/cppcodestylesettingspage.cpp
@@ -27,21 +27,27 @@
**
****************************************************************************/
-#include "cppcodestylesettingspage.h"
#include "cppcodestylepreferences.h"
-#include "ui_cppcodestylesettingspage.h"
+#include "cppcodestylesettingspage.h"
+#include "cpppointerdeclarationformatter.h"
+#include "cppqtstyleindenter.h"
#include "cpptoolsconstants.h"
#include "cpptoolssettings.h"
-#include "cppqtstyleindenter.h"
-#include <texteditor/snippets/isnippetprovider.h>
-#include <texteditor/fontsettings.h>
+#include "ui_cppcodestylesettingspage.h"
+
+#include <Overview.h>
+#include <pp.h>
+
+#include <coreplugin/icore.h>
+#include <cppeditor/cppeditorconstants.h>
+#include <extensionsystem/pluginmanager.h>
+#include <texteditor/codestyleeditor.h>
#include <texteditor/displaysettings.h>
-#include <texteditor/texteditorsettings.h>
+#include <texteditor/fontsettings.h>
+#include <texteditor/snippets/isnippetprovider.h>
#include <texteditor/tabsettings.h>
-#include <texteditor/codestyleeditor.h>
-#include <extensionsystem/pluginmanager.h>
-#include <cppeditor/cppeditorconstants.h>
-#include <coreplugin/icore.h>
+#include <texteditor/texteditorsettings.h>
+
#include <QTextBlock>
#include <QTextStream>
@@ -194,6 +200,19 @@ static const char *defaultCodeStyleSnippets[] = {
" myInstance.longMemberName += bar +\n"
" foo;\n"
"}\n"
+ ,
+ "int *foo(const Bar &b1, Bar &&b2, int*, int *&rpi)\n"
+ "{\n"
+ " int*pi = 0;\n"
+ " int*const*const cpcpi = &pi;\n"
+ " int*const*pcpi = &pi;\n"
+ " int**const cppi = &pi;\n"
+ "\n"
+ " void (*foo)(char *s) = 0;\n"
+ " int (*bar)[] = 0;\n"
+ "\n"
+ " return pi;\n"
+ "}\n"
};
using namespace TextEditor;
@@ -202,6 +221,44 @@ namespace CppTools {
namespace Internal {
+static void applyRefactorings(QTextDocument *textDocument, TextEditor::BaseTextEditorWidget *editor,
+ const CppCodeStyleSettings &settings)
+{
+ // Preprocess source
+ Environment env;
+ Preprocessor preprocess(0, &env);
+ const QByteArray preprocessedSource
+ = preprocess.run(QLatin1String("<no-file>"), textDocument->toPlainText());
+
+ Document::Ptr cppDocument = Document::create(QLatin1String("<no-file>"));
+ cppDocument->setUtf8Source(preprocessedSource);
+ cppDocument->parse(Document::ParseTranlationUnit);
+ cppDocument->check();
+
+ CppRefactoringFilePtr cppRefactoringFile = CppRefactoringChanges::file(editor, cppDocument);
+
+ // Run the formatter
+ Overview overview;
+ overview.showReturnTypes = true;
+ overview.starBindFlags = Overview::StarBindFlags(0);
+
+ if (settings.bindStarToIdentifier)
+ overview.starBindFlags |= Overview::BindToIdentifier;
+ if (settings.bindStarToTypeName)
+ overview.starBindFlags |= Overview::BindToTypeName;
+ if (settings.bindStarToLeftSpecifier)
+ overview.starBindFlags |= Overview::BindToLeftSpecifier;
+ if (settings.bindStarToRightSpecifier)
+ overview.starBindFlags |= Overview::BindToRightSpecifier;
+
+ PointerDeclarationFormatter formatter(cppRefactoringFile, overview);
+ Utils::ChangeSet change = formatter.format(cppDocument->translationUnit()->ast());
+
+ // Apply change
+ QTextCursor cursor(textDocument);
+ change.apply(&cursor);
+}
+
// ------------------ CppCodeStyleSettingsWidget
CppCodeStylePreferencesWidget::CppCodeStylePreferencesWidget(QWidget *parent)
@@ -215,10 +272,9 @@ CppCodeStylePreferencesWidget::CppCodeStylePreferencesWidget(QWidget *parent)
m_previews << m_ui->previewTextEditGeneral << m_ui->previewTextEditContent
<< m_ui->previewTextEditBraces << m_ui->previewTextEditSwitch
- << m_ui->previewTextEditPadding;
- for (int i = 0; i < m_previews.size(); ++i) {
- m_previews[i]->setPlainText(defaultCodeStyleSnippets[i]);
- }
+ << m_ui->previewTextEditPadding << m_ui->previewTextEditPointerReferences;
+ for (int i = 0; i < m_previews.size(); ++i)
+ m_previews[i]->setPlainText(QLatin1String(defaultCodeStyleSnippets[i]));
TextEditor::TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
decorateEditors(textEditorSettings->fontSettings());
@@ -261,6 +317,14 @@ CppCodeStylePreferencesWidget::CppCodeStylePreferencesWidget(QWidget *parent)
this, SLOT(slotCodeStyleSettingsChanged()));
connect(m_ui->alignAssignments, SIGNAL(toggled(bool)),
this, SLOT(slotCodeStyleSettingsChanged()));
+ connect(m_ui->bindStarToIdentifier, SIGNAL(toggled(bool)),
+ this, SLOT(slotCodeStyleSettingsChanged()));
+ connect(m_ui->bindStarToTypeName, SIGNAL(toggled(bool)),
+ this, SLOT(slotCodeStyleSettingsChanged()));
+ connect(m_ui->bindStarToLeftSpecifier, SIGNAL(toggled(bool)),
+ this, SLOT(slotCodeStyleSettingsChanged()));
+ connect(m_ui->bindStarToRightSpecifier, SIGNAL(toggled(bool)),
+ this, SLOT(slotCodeStyleSettingsChanged()));
m_ui->categoryTab->setCurrentIndex(0);
@@ -309,6 +373,10 @@ CppCodeStyleSettings CppCodeStylePreferencesWidget::cppCodeStyleSettings() const
set.indentStatementsRelativeToSwitchLabels = m_ui->indentCaseStatements->isChecked();
set.indentBlocksRelativeToSwitchLabels = m_ui->indentCaseBlocks->isChecked();
set.indentControlFlowRelativeToSwitchLabels = m_ui->indentCaseBreak->isChecked();
+ set.bindStarToIdentifier = m_ui->bindStarToIdentifier->isChecked();
+ set.bindStarToTypeName = m_ui->bindStarToTypeName->isChecked();
+ set.bindStarToLeftSpecifier = m_ui->bindStarToLeftSpecifier->isChecked();
+ set.bindStarToRightSpecifier = m_ui->bindStarToRightSpecifier->isChecked();
set.extraPaddingForConditionsIfConfusingAlign = m_ui->extraPaddingConditions->isChecked();
set.alignAssignments = m_ui->alignAssignments->isChecked();
@@ -338,6 +406,10 @@ void CppCodeStylePreferencesWidget::setCodeStyleSettings(const CppCodeStyleSetti
m_ui->indentCaseStatements->setChecked(s.indentStatementsRelativeToSwitchLabels);
m_ui->indentCaseBlocks->setChecked(s.indentBlocksRelativeToSwitchLabels);
m_ui->indentCaseBreak->setChecked(s.indentControlFlowRelativeToSwitchLabels);
+ m_ui->bindStarToIdentifier->setChecked(s.bindStarToIdentifier);
+ m_ui->bindStarToTypeName->setChecked(s.bindStarToTypeName);
+ m_ui->bindStarToLeftSpecifier->setChecked(s.bindStarToLeftSpecifier);
+ m_ui->bindStarToRightSpecifier->setChecked(s.bindStarToRightSpecifier);
m_ui->extraPaddingConditions->setChecked(s.extraPaddingForConditionsIfConfusingAlign);
m_ui->alignAssignments->setChecked(s.alignAssignments);
m_blockUpdates = wasBlocked;
@@ -353,6 +425,7 @@ void CppCodeStylePreferencesWidget::slotCurrentPreferencesChanged(TextEditor::IC
m_ui->bracesGroupBox->setEnabled(enable);
m_ui->switchGroupBox->setEnabled(enable);
m_ui->alignmentGroupBox->setEnabled(enable);
+ m_ui->pointerReferencesGroupBox->setEnabled(enable);
if (preview)
updatePreview();
}
@@ -377,10 +450,15 @@ QString CppCodeStylePreferencesWidget::searchKeywords() const
<< sep << m_ui->indentCaseStatements->text()
<< sep << m_ui->indentCaseBlocks->text()
<< sep << m_ui->indentCaseBreak->text()
+ << sep << m_ui->bindStarToIdentifier->text()
+ << sep << m_ui->bindStarToTypeName->text()
+ << sep << m_ui->bindStarToLeftSpecifier->text()
+ << sep << m_ui->bindStarToRightSpecifier->text()
<< sep << m_ui->contentGroupBox->title()
<< sep << m_ui->bracesGroupBox->title()
<< sep << m_ui->switchGroupBox->title()
<< sep << m_ui->alignmentGroupBox->title()
+ << sep << m_ui->pointerReferencesGroupBox->title()
<< sep << m_ui->extraPaddingConditions->text()
<< sep << m_ui->alignAssignments->text()
;
@@ -441,6 +519,7 @@ void CppCodeStylePreferencesWidget::updatePreview()
block = block.next();
}
+ applyRefactorings(doc, preview, ccss);
tc.endEditBlock();
}
}
@@ -480,9 +559,9 @@ CppCodeStyleSettingsPage::CppCodeStyleSettingsPage(QWidget *parent) :
Core::IOptionsPage(parent),
m_pageCppCodeStylePreferences(0)
{
- setId(QLatin1String(Constants::CPP_CODE_STYLE_SETTINGS_ID));
+ setId(Constants::CPP_CODE_STYLE_SETTINGS_ID);
setDisplayName(QCoreApplication::translate("CppTools", Constants::CPP_CODE_STYLE_SETTINGS_NAME));
- setCategory(QLatin1String(Constants::CPP_SETTINGS_CATEGORY));
+ setCategory(Constants::CPP_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("CppTools", Constants::CPP_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CPP_ICON));
}
@@ -513,17 +592,17 @@ void CppCodeStyleSettingsPage::apply()
if (originalCppCodeStylePreferences->codeStyleSettings() != m_pageCppCodeStylePreferences->codeStyleSettings()) {
originalCppCodeStylePreferences->setCodeStyleSettings(m_pageCppCodeStylePreferences->codeStyleSettings());
if (s)
- originalCppCodeStylePreferences->toSettings(CppTools::Constants::CPP_SETTINGS_ID, s);
+ originalCppCodeStylePreferences->toSettings(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID), s);
}
if (originalCppCodeStylePreferences->tabSettings() != m_pageCppCodeStylePreferences->tabSettings()) {
originalCppCodeStylePreferences->setTabSettings(m_pageCppCodeStylePreferences->tabSettings());
if (s)
- originalCppCodeStylePreferences->toSettings(CppTools::Constants::CPP_SETTINGS_ID, s);
+ originalCppCodeStylePreferences->toSettings(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID), s);
}
if (originalCppCodeStylePreferences->currentDelegate() != m_pageCppCodeStylePreferences->currentDelegate()) {
originalCppCodeStylePreferences->setCurrentDelegate(m_pageCppCodeStylePreferences->currentDelegate());
if (s)
- originalCppCodeStylePreferences->toSettings(CppTools::Constants::CPP_SETTINGS_ID, s);
+ originalCppCodeStylePreferences->toSettings(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID), s);
}
}
}
diff --git a/src/plugins/cpptools/cppcodestylesettingspage.ui b/src/plugins/cpptools/cppcodestylesettingspage.ui
index 0ca280a2f4..fed6d45722 100644
--- a/src/plugins/cpptools/cppcodestylesettingspage.ui
+++ b/src/plugins/cpptools/cppcodestylesettingspage.ui
@@ -17,7 +17,7 @@
<item>
<widget class="QTabWidget" name="categoryTab">
<property name="currentIndex">
- <number>0</number>
+ <number>5</number>
</property>
<widget class="QWidget" name="generalTab">
<attribute name="title">
@@ -404,6 +404,86 @@ if they would align to the next line</string>
</item>
</layout>
</widget>
+ <widget class="QWidget" name="typesTab">
+ <attribute name="title">
+ <string>Pointers and References</string>
+ </attribute>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <widget class="QGroupBox" name="pointerReferencesGroupBox">
+ <property name="title">
+ <string>Bind '*' and '&amp;&amp;' in types/declarations to</string>
+ </property>
+ <property name="flat">
+ <bool>true</bool>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_6">
+ <item>
+ <widget class="QCheckBox" name="bindStarToIdentifier">
+ <property name="toolTip">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;This does not apply to the star and reference symbol in pointer/reference to functions and arrays, e.g.:
+&lt;pre&gt; int (&amp;rf)() = ...;
+ int (*pf)() = ...;
+
+ int (&amp;ra)[2] = ...;
+ int (*pa)[2] = ...;
+
+&lt;/pre&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ <property name="text">
+ <string>Identifier</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="bindStarToTypeName">
+ <property name="text">
+ <string>Type name</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="bindStarToLeftSpecifier">
+ <property name="text">
+ <string>Left const/volatile</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="bindStarToRightSpecifier">
+ <property name="toolTip">
+ <string>This does not apply to references.</string>
+ </property>
+ <property name="text">
+ <string>Right const/volatile</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer_6">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="TextEditor::SnippetEditorWidget" name="previewTextEditPointerReferences">
+ <property name="plainText">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
</widget>
</item>
</layout>
diff --git a/src/plugins/cpptools/cppcompletion_test.cpp b/src/plugins/cpptools/cppcompletion_test.cpp
index f6cd29c270..3c42969f23 100644
--- a/src/plugins/cpptools/cppcompletion_test.cpp
+++ b/src/plugins/cpptools/cppcompletion_test.cpp
@@ -72,7 +72,7 @@ struct TestData
QTextDocument *doc;
};
-static QStringList getCompletions(TestData &data)
+static QStringList getCompletions(TestData &data, bool *replaceAccessOperator = 0)
{
QStringList completions;
@@ -86,13 +86,16 @@ static QStringList getCompletions(TestData &data)
IAssistProposalModel *model = proposal->model();
if (!model)
return completions;
- BasicProposalItemListModel *listmodel = dynamic_cast<BasicProposalItemListModel *>(model);
+ CppAssistProposalModel *listmodel = dynamic_cast<CppAssistProposalModel *>(model);
if (!listmodel)
return completions;
for (int i = 0; i < listmodel->size(); ++i)
completions << listmodel->text(i);
+ if (replaceAccessOperator)
+ *replaceAccessOperator = listmodel->m_replaceDotForArrow;
+
return completions;
}
@@ -139,19 +142,100 @@ void CppToolsPlugin::test_completion_forward_declarations_present()
setup(&data);
Utils::ChangeSet change;
- change.insert(data.pos, "Foo::Bar::");
+ change.insert(data.pos, QLatin1String("Foo::Bar::"));
QTextCursor cursor(data.doc);
change.apply(&cursor);
data.pos += 10;
QStringList expected;
- expected.append("Bar");
+ expected.append(QLatin1String("Bar"));
QStringList completions = getCompletions(data);
QCOMPARE(completions, expected);
}
+void CppToolsPlugin::test_completion_inside_parentheses_c_style_conversion()
+{
+ TestData data;
+ data.srcText = "\n"
+ "class Base\n"
+ "{\n"
+ " int i_base;\n"
+ "};\n"
+ "\n"
+ "class Derived : public Base\n"
+ "{\n"
+ " int i_derived;\n"
+ "};\n"
+ "\n"
+ "void fun()\n"
+ "{\n"
+ " Base *b = new Derived;\n"
+ " if (1)\n"
+ " @\n"
+ "}\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("((Derived *)b)->");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 4);
+ QVERIFY(completions.contains(QLatin1String("Derived")));
+ QVERIFY(completions.contains(QLatin1String("Base")));
+ QVERIFY(completions.contains(QLatin1String("i_derived")));
+ QVERIFY(completions.contains(QLatin1String("i_base")));
+
+}
+
+void CppToolsPlugin::test_completion_inside_parentheses_cast_operator_conversion()
+{
+ TestData data;
+ data.srcText = "\n"
+ "class Base\n"
+ "{\n"
+ " int i_base;\n"
+ "};\n"
+ "\n"
+ "class Derived : public Base\n"
+ "{\n"
+ " int i_derived;\n"
+ "};\n"
+ "\n"
+ "void fun()\n"
+ "{\n"
+ " Base *b = new Derived;\n"
+ " if (1)\n"
+ " @\n"
+ "}\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("(static_cast<Derived *>(b))->");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 4);
+ QVERIFY(completions.contains(QLatin1String("Derived")));
+ QVERIFY(completions.contains(QLatin1String("Base")));
+ QVERIFY(completions.contains(QLatin1String("i_derived")));
+ QVERIFY(completions.contains(QLatin1String("i_base")));
+}
+
void CppToolsPlugin::test_completion_basic_1()
{
TestData data;
@@ -172,24 +256,24 @@ void CppToolsPlugin::test_completion_basic_1()
QStringList basicCompletions = getCompletions(data);
- QVERIFY(!basicCompletions.contains("foo"));
- QVERIFY(!basicCompletions.contains("m"));
- QVERIFY(basicCompletions.contains("Foo"));
- QVERIFY(basicCompletions.contains("func"));
- QVERIFY(basicCompletions.contains("f"));
+ QVERIFY(!basicCompletions.contains(QLatin1String("foo")));
+ QVERIFY(!basicCompletions.contains(QLatin1String("m")));
+ QVERIFY(basicCompletions.contains(QLatin1String("Foo")));
+ QVERIFY(basicCompletions.contains(QLatin1String("func")));
+ QVERIFY(basicCompletions.contains(QLatin1String("f")));
Utils::ChangeSet change;
- change.insert(data.pos, "f.");
+ change.insert(data.pos, QLatin1String("f."));
QTextCursor cursor(data.doc);
change.apply(&cursor);
data.pos += 2;
QStringList memberCompletions = getCompletions(data);
- QVERIFY(memberCompletions.contains("foo"));
- QVERIFY(memberCompletions.contains("m"));
- QVERIFY(!memberCompletions.contains("func"));
- QVERIFY(!memberCompletions.contains("f"));
+ QVERIFY(memberCompletions.contains(QLatin1String("foo")));
+ QVERIFY(memberCompletions.contains(QLatin1String("m")));
+ QVERIFY(!memberCompletions.contains(QLatin1String("func")));
+ QVERIFY(!memberCompletions.contains(QLatin1String("f")));
}
void CppToolsPlugin::test_completion_template_1()
@@ -213,19 +297,19 @@ void CppToolsPlugin::test_completion_template_1()
setup(&data);
Utils::ChangeSet change;
- change.insert(data.pos, "Foo::");
+ change.insert(data.pos, QLatin1String("Foo::"));
QTextCursor cursor(data.doc);
change.apply(&cursor);
data.pos += 5;
QStringList completions = getCompletions(data);
- QVERIFY(completions.contains("Type"));
- QVERIFY(completions.contains("foo"));
- QVERIFY(completions.contains("m"));
- QVERIFY(!completions.contains("T"));
- QVERIFY(!completions.contains("f"));
- QVERIFY(!completions.contains("func"));
+ QVERIFY(completions.contains(QLatin1String("Type")));
+ QVERIFY(completions.contains(QLatin1String("foo")));
+ QVERIFY(completions.contains(QLatin1String("m")));
+ QVERIFY(!completions.contains(QLatin1String("T")));
+ QVERIFY(!completions.contains(QLatin1String("f")));
+ QVERIFY(!completions.contains(QLatin1String("func")));
}
void CppToolsPlugin::test_completion_template_2()
@@ -258,9 +342,9 @@ void CppToolsPlugin::test_completion_template_2()
QStringList completions = getCompletions(data);
QCOMPARE(completions.size(), 3);
- QVERIFY(completions.contains("Tupple"));
- QVERIFY(completions.contains("a"));
- QVERIFY(completions.contains("b"));
+ QVERIFY(completions.contains(QLatin1String("Tupple")));
+ QVERIFY(completions.contains(QLatin1String("a")));
+ QVERIFY(completions.contains(QLatin1String("b")));
}
void CppToolsPlugin::test_completion_template_3()
@@ -293,9 +377,9 @@ void CppToolsPlugin::test_completion_template_3()
QStringList completions = getCompletions(data);
QCOMPARE(completions.size(), 3);
- QVERIFY(completions.contains("Tupple"));
- QVERIFY(completions.contains("a"));
- QVERIFY(completions.contains("b"));
+ QVERIFY(completions.contains(QLatin1String("Tupple")));
+ QVERIFY(completions.contains(QLatin1String("a")));
+ QVERIFY(completions.contains(QLatin1String("b")));
}
void CppToolsPlugin::test_completion_template_4()
@@ -329,9 +413,9 @@ void CppToolsPlugin::test_completion_template_4()
QStringList completions = getCompletions(data);
QCOMPARE(completions.size(), 3);
- QVERIFY(completions.contains("Tupple"));
- QVERIFY(completions.contains("a"));
- QVERIFY(completions.contains("b"));
+ QVERIFY(completions.contains(QLatin1String("Tupple")));
+ QVERIFY(completions.contains(QLatin1String("a")));
+ QVERIFY(completions.contains(QLatin1String("b")));
}
void CppToolsPlugin::test_completion_template_5()
@@ -365,9 +449,9 @@ void CppToolsPlugin::test_completion_template_5()
QStringList completions = getCompletions(data);
QCOMPARE(completions.size(), 3);
- QVERIFY(completions.contains("Tupple"));
- QVERIFY(completions.contains("a"));
- QVERIFY(completions.contains("b"));
+ QVERIFY(completions.contains(QLatin1String("Tupple")));
+ QVERIFY(completions.contains(QLatin1String("a")));
+ QVERIFY(completions.contains(QLatin1String("b")));
}
void CppToolsPlugin::test_completion_template_6()
@@ -405,8 +489,115 @@ void CppToolsPlugin::test_completion_template_6()
QStringList completions = getCompletions(data);
QCOMPARE(completions.size(), 2);
- QVERIFY(completions.contains("Item"));
- QVERIFY(completions.contains("i"));
+ QVERIFY(completions.contains(QLatin1String("Item")));
+ QVERIFY(completions.contains(QLatin1String("i")));
+}
+
+
+void CppToolsPlugin::test_completion_template_7()
+{
+ TestData data;
+ data.srcText = "\n"
+ "struct Test\n"
+ "{\n"
+ " int i;\n"
+ "};\n"
+ "\n"
+ "template<typename T>\n"
+ "struct TemplateClass\n"
+ "{\n"
+ " T* ptr;\n"
+ "\n"
+ " typedef T element_type;\n"
+ " TemplateClass(T* t) : ptr(t) {}\n"
+ " element_type* operator->()\n"
+ " {\n"
+ " return ptr;\n"
+ " }\n"
+ "};\n"
+ "\n"
+ "TemplateClass<Test> p(new Test);\n"
+ "@\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("p->");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Test")));
+ QVERIFY(completions.contains(QLatin1String("i")));
+}
+
+void CppToolsPlugin::test_completion_type_of_pointer_is_typedef()
+{
+ TestData data;
+ data.srcText = "\n"
+ "typedef struct Foo\n"
+ "{\n"
+ " int foo;\n"
+ "} Foo;\n"
+ "Foo *bar;\n"
+ "@\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("bar->");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Foo")));
+ QVERIFY(completions.contains(QLatin1String("foo")));
+}
+
+void CppToolsPlugin::test_completion_instantiate_full_specialization()
+{
+ TestData data;
+ data.srcText = "\n"
+ "template<typename T>\n"
+ "struct Template\n"
+ "{\n"
+ " int templateT_i;\n"
+ "};\n"
+ "\n"
+ "template<>\n"
+ "struct Template<char>\n"
+ "{\n"
+ " int templateChar_i;\n"
+ "};\n"
+ "\n"
+ "Template<char> templateChar;\n"
+ "@\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("templateChar.");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Template")));
+ QVERIFY(completions.contains(QLatin1String("templateChar_i")));
}
void CppToolsPlugin::test_completion()
@@ -419,7 +610,7 @@ void CppToolsPlugin::test_completion()
setup(&data);
Utils::ChangeSet change;
- change.insert(data.pos, "c.");
+ change.insert(data.pos, QLatin1String("c."));
QTextCursor cursor(data.doc);
change.apply(&cursor);
data.pos += 2;
@@ -453,10 +644,10 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Other");
- completions.append("otherMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Other"));
+ completions.append(QLatin1String("otherMember"));
QTest::newRow("case: base as template directly") << code << completions;
@@ -471,12 +662,12 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Other");
- completions.append("otherMember");
- completions.append("More");
- completions.append("moreMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Other"));
+ completions.append(QLatin1String("otherMember"));
+ completions.append(QLatin1String("More"));
+ completions.append(QLatin1String("moreMember"));
QTest::newRow("case: base as class template") << code << completions;
@@ -491,12 +682,12 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Other");
- completions.append("otherMember");
- completions.append("More");
- completions.append("moreMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Other"));
+ completions.append(QLatin1String("otherMember"));
+ completions.append(QLatin1String("More"));
+ completions.append(QLatin1String("moreMember"));
QTest::newRow("case: base as globally qualified class template") << code << completions;
@@ -513,12 +704,12 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Other");
- completions.append("otherMember");
- completions.append("More");
- completions.append("moreMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Other"));
+ completions.append(QLatin1String("otherMember"));
+ completions.append(QLatin1String("More"));
+ completions.append(QLatin1String("moreMember"));
QTest::newRow("case: base as namespace qualified class template") << code << completions;
@@ -535,10 +726,10 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Final");
- completions.append("finalMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Final"));
+ completions.append(QLatin1String("finalMember"));
QTest::newRow("case: base as nested template name") << code << completions;
@@ -555,10 +746,10 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Final");
- completions.append("finalMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Final"));
+ completions.append(QLatin1String("finalMember"));
QTest::newRow("case: base as nested template name in non-template") << code << completions;
completions.clear();
@@ -574,12 +765,12 @@ void CppToolsPlugin::test_completion_template_as_base_data()
" @\n"
" // padding so we get the scope right\n"
"}";
- completions.append("Data");
- completions.append("dataMember");
- completions.append("Final");
- completions.append("finalMember");
- completions.append("Other");
- completions.append("otherMember");
+ completions.append(QLatin1String("Data"));
+ completions.append(QLatin1String("dataMember"));
+ completions.append(QLatin1String("Final"));
+ completions.append(QLatin1String("finalMember"));
+ completions.append(QLatin1String("Other"));
+ completions.append(QLatin1String("otherMember"));
QTest::newRow("case: base as template name in non-template") << code << completions;
}
@@ -611,10 +802,10 @@ void CppToolsPlugin::test_completion_use_global_identifier_as_base_class_data()
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_global");
- completions.append("int_final");
- completions.append("Final");
- completions.append("Global");
+ completions.append(QLatin1String("int_global"));
+ completions.append(QLatin1String("int_final"));
+ completions.append(QLatin1String("Final"));
+ completions.append(QLatin1String("Global"));
QTest::newRow("case: derived as global and base as global") << code << completions;
completions.clear();
@@ -637,10 +828,10 @@ void CppToolsPlugin::test_completion_use_global_identifier_as_base_class_data()
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_global");
- completions.append("int_final");
- completions.append("Final");
- completions.append("Global");
+ completions.append(QLatin1String("int_global"));
+ completions.append(QLatin1String("int_final"));
+ completions.append(QLatin1String("Final"));
+ completions.append(QLatin1String("Global"));
QTest::newRow("case: derived is inside namespace, base as global")
<< code << completions;
@@ -668,10 +859,10 @@ void CppToolsPlugin::test_completion_use_global_identifier_as_base_class_data()
// "@\n"
// "// padding so we get the scope right\n";
-// completions.append("int_global");
-// completions.append("int_final");
-// completions.append("Final");
-// completions.append("Global");
+// completions.append(QLatin1String("int_global"));
+// completions.append(QLatin1String("int_final"));
+// completions.append(QLatin1String("Final"));
+// completions.append(QLatin1String("Global"));
// QTest::newRow("case: derived is enclosed by template, base as global")
// << code << completions;
@@ -701,8 +892,8 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_a");
- completions.append("A");
+ completions.append(QLatin1String("int_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class is derived class") << code << completions;
completions.clear();
@@ -720,8 +911,8 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_a");
- completions.append("A");
+ completions.append(QLatin1String("int_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class is derived class. class is in namespace")
<< code << completions;
@@ -740,8 +931,8 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_a");
- completions.append("A");
+ completions.append(QLatin1String("int_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class is derived class. class is in namespace. "
"use scope operator for base class") << code << completions;
@@ -767,9 +958,9 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_ns1_a");
- completions.append("int_ns2_a");
- completions.append("A");
+ completions.append(QLatin1String("int_ns1_a"));
+ completions.append(QLatin1String("int_ns2_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class has the same name as derived but in different namespace")
<< code << completions;
@@ -795,9 +986,9 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_enclosing_a");
- completions.append("int_ns2_a");
- completions.append("A");
+ completions.append(QLatin1String("int_enclosing_a"));
+ completions.append(QLatin1String("int_ns2_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class has the same name as derived(in namespace) "
"but is nested by different class") << code << completions;
@@ -823,9 +1014,9 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_enclosing_base_a");
- completions.append("int_enclosing_derived_a");
- completions.append("A");
+ completions.append(QLatin1String("int_enclosing_base_a"));
+ completions.append(QLatin1String("int_enclosing_derived_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class has the same name as derived(nested) "
"but is nested by different class") << code << completions;
@@ -842,8 +1033,8 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
"@\n"
"// padding so we get the scope right\n";
- completions.append("int_a");
- completions.append("A");
+ completions.append(QLatin1String("int_a"));
+ completions.append(QLatin1String("A"));
QTest::newRow("case: base class is derived class. class is a template")
<< code << completions;
@@ -851,7 +1042,6 @@ void CppToolsPlugin::test_completion_base_class_has_name_the_same_as_derived_dat
}
-
void CppToolsPlugin::test_completion_cyclic_inheritance()
{
test_completion();
@@ -873,10 +1063,10 @@ void CppToolsPlugin::test_completion_cyclic_inheritance_data()
"A c;\n"
"@\n"
;
- completions.append("A");
- completions.append("_a");
- completions.append("B");
- completions.append("_b");
+ completions.append(QLatin1String("A"));
+ completions.append(QLatin1String("_a"));
+ completions.append(QLatin1String("B"));
+ completions.append(QLatin1String("_b"));
QTest::newRow("case: direct cyclic inheritance") << code << completions;
completions.clear();
@@ -889,12 +1079,12 @@ void CppToolsPlugin::test_completion_cyclic_inheritance_data()
"A c;\n"
"@\n"
;
- completions.append("A");
- completions.append("_a");
- completions.append("B");
- completions.append("_b");
- completions.append("C");
- completions.append("_c");
+ completions.append(QLatin1String("A"));
+ completions.append(QLatin1String("_a"));
+ completions.append(QLatin1String("B"));
+ completions.append(QLatin1String("_b"));
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("_c"));
QTest::newRow("case: indirect cyclic inheritance") << code << completions;
completions.clear();
@@ -907,12 +1097,12 @@ void CppToolsPlugin::test_completion_cyclic_inheritance_data()
"A c;\n"
"@\n"
;
- completions.append("A");
- completions.append("_a");
- completions.append("B");
- completions.append("_b");
- completions.append("C");
- completions.append("_c");
+ completions.append(QLatin1String("A"));
+ completions.append(QLatin1String("_a"));
+ completions.append(QLatin1String("B"));
+ completions.append(QLatin1String("_b"));
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("_c"));
QTest::newRow("case: indirect cyclic inheritance") << code << completions;
completions.clear();
@@ -931,11 +1121,11 @@ void CppToolsPlugin::test_completion_cyclic_inheritance_data()
"D<int, float> c;\n"
"@\n"
;
- completions.append("D");
- completions.append("_d_t");
- completions.append("_d_s");
- completions.append("C");
- completions.append("_c_t");
+ completions.append(QLatin1String("D"));
+ completions.append(QLatin1String("_d_t"));
+ completions.append(QLatin1String("_d_s"));
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("_c_t"));
QTest::newRow("case: direct cyclic inheritance with templates")
<< code << completions;
@@ -959,13 +1149,13 @@ void CppToolsPlugin::test_completion_cyclic_inheritance_data()
"D<int, float> c;\n"
"@\n"
;
- completions.append("D");
- completions.append("_d_t");
- completions.append("_d_s");
- completions.append("C");
- completions.append("_c_t");
- completions.append("B");
- completions.append("_b_t");
+ completions.append(QLatin1String("D"));
+ completions.append(QLatin1String("_d_t"));
+ completions.append(QLatin1String("_d_s"));
+ completions.append(QLatin1String("C"));
+ completions.append(QLatin1String("_c_t"));
+ completions.append(QLatin1String("B"));
+ completions.append(QLatin1String("_b_t"));
QTest::newRow("case: indirect cyclic inheritance with templates")
<< code << completions;
@@ -999,11 +1189,168 @@ void CppToolsPlugin::test_completion_cyclic_inheritance_data()
"Class<int> c;\n"
"@\n"
;
- completions.append("Class");
- completions.append("ClassRecurse");
- completions.append("class_t");
- completions.append("class_recurse_s");
- completions.append("class_recurse_t");
+ completions.append(QLatin1String("Class"));
+ completions.append(QLatin1String("ClassRecurse"));
+ completions.append(QLatin1String("class_t"));
+ completions.append(QLatin1String("class_recurse_s"));
+ completions.append(QLatin1String("class_recurse_t"));
QTest::newRow("case: direct cyclic inheritance with templates, more complex situation")
<< code << completions;
}
+
+void CppToolsPlugin::test_completion_enclosing_template_class()
+{
+ test_completion();
+}
+
+void CppToolsPlugin::test_completion_enclosing_template_class_data()
+{
+ QTest::addColumn<QByteArray>("code");
+ QTest::addColumn<QStringList>("expectedCompletions");
+
+ QByteArray code;
+ QStringList completions;
+
+ code = "\n"
+ "template<typename T>\n"
+ "struct Enclosing\n"
+ "{\n"
+ " struct Nested { int int_nested; }; \n"
+ " int int_enclosing;\n"
+ "};\n"
+ "\n"
+ "Enclosing<int>::Nested c;"
+ "@\n";
+ completions.append(QLatin1String("Nested"));
+ completions.append(QLatin1String("int_nested"));
+ QTest::newRow("case: nested class with enclosing template class")
+ << code << completions;
+
+ completions.clear();
+
+ code = "\n"
+ "template<typename T>\n"
+ "struct Enclosing\n"
+ "{\n"
+ " template<typename T> struct Nested { int int_nested; }; \n"
+ " int int_enclosing;\n"
+ "};\n"
+ "\n"
+ "Enclosing<int>::Nested<int> c;"
+ "@\n";
+ completions.append(QLatin1String("Nested"));
+ completions.append(QLatin1String("int_nested"));
+ QTest::newRow("case: nested template class with enclosing template class")
+ << code << completions;
+}
+
+void CppToolsPlugin::test_completion_instantiate_nested_class_when_enclosing_is_template()
+{
+ TestData data;
+ data.srcText = "\n"
+ "struct Foo \n"
+ "{\n"
+ " int foo_i;\n"
+ "};\n"
+ "\n"
+ "template <typename T>\n"
+ "struct Enclosing\n"
+ "{\n"
+ " struct Nested\n"
+ " {\n"
+ " T nested_t;\n"
+ " } nested;\n"
+ "\n"
+ " T enclosing_t;\n"
+ "};\n"
+ "\n"
+ "Enclosing<Foo> enclosing;\n"
+ "@\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("enclosing.nested.nested_t.");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Foo")));
+ QVERIFY(completions.contains(QLatin1String("foo_i")));
+}
+
+void CppToolsPlugin::test_completion_instantiate_nested_of_nested_class_when_enclosing_is_template()
+{
+ TestData data;
+ data.srcText = "\n"
+ "struct Foo \n"
+ "{\n"
+ " int foo_i;\n"
+ "};\n"
+ "\n"
+ "template <typename T>\n"
+ "struct Enclosing\n"
+ "{\n"
+ " struct Nested\n"
+ " {\n"
+ " T nested_t;\n"
+ " struct NestedNested\n"
+ " {\n"
+ " T nestedNested_t;\n"
+ " } nestedNested;\n"
+ " } nested;\n"
+ "\n"
+ " T enclosing_t;\n"
+ "};\n"
+ "\n"
+ "Enclosing<Foo> enclosing;\n"
+ "@\n"
+ ;
+
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("enclosing.nested.nestedNested.nestedNested_t.");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ QStringList completions = getCompletions(data);
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("Foo")));
+ QVERIFY(completions.contains(QLatin1String("foo_i")));
+}
+
+void CppToolsPlugin::test_completion_member_access_operator_1()
+{
+ TestData data;
+ data.srcText = "\n"
+ "struct S { void t(); };\n"
+ "void f() { S *s;\n"
+ "@\n"
+ "}\n"
+ ;
+ setup(&data);
+
+ Utils::ChangeSet change;
+ QString txt = QLatin1String("s.");
+ change.insert(data.pos, txt);
+ QTextCursor cursor(data.doc);
+ change.apply(&cursor);
+ data.pos += txt.length();
+
+ bool replaceAccessOperator = false;
+ QStringList completions = getCompletions(data, &replaceAccessOperator);
+
+ QCOMPARE(completions.size(), 2);
+ QVERIFY(completions.contains(QLatin1String("S")));
+ QVERIFY(completions.contains(QLatin1String("t")));
+ QVERIFY(replaceAccessOperator);
+}
diff --git a/src/plugins/cpptools/cppcompletionassist.cpp b/src/plugins/cpptools/cppcompletionassist.cpp
index f9d39b6e57..10708feedd 100644
--- a/src/plugins/cpptools/cppcompletionassist.cpp
+++ b/src/plugins/cpptools/cppcompletionassist.cpp
@@ -58,7 +58,6 @@
#include <coreplugin/mimedatabase.h>
#include <cppeditor/cppeditorconstants.h>
#include <texteditor/codeassist/basicproposalitem.h>
-#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <texteditor/codeassist/genericproposal.h>
#include <texteditor/codeassist/ifunctionhintproposalmodel.h>
#include <texteditor/codeassist/functionhintproposal.h>
@@ -91,29 +90,6 @@ struct CompleteFunctionDeclaration
Function *function;
};
-// ----------------------
-// CppAssistProposalModel
-// ----------------------
-class CppAssistProposalModel : public TextEditor::BasicProposalItemListModel
-{
-public:
- CppAssistProposalModel()
- : TextEditor::BasicProposalItemListModel()
- , m_completionOperator(T_EOF_SYMBOL)
- , m_replaceDotForArrow(false)
- , m_typeOfExpression(new TypeOfExpression)
- {
- m_typeOfExpression->setExpandTemplates(true);
- }
-
- virtual bool isSortable(const QString &prefix) const;
- virtual IAssistProposalItem *proposalItem(int index) const;
-
- unsigned m_completionOperator;
- bool m_replaceDotForArrow;
- QSharedPointer<TypeOfExpression> m_typeOfExpression;
-};
-
// ---------------------
// CppAssistProposalItem
// ---------------------
@@ -264,9 +240,8 @@ void CppAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *e
#if 0
} else if (function->templateParameterCount() != 0 && typedChar != QLatin1Char('(')) {
// If there are no arguments, then we need the template specification
- if (function->argumentCount() == 0) {
+ if (function->argumentCount() == 0)
extraChars += QLatin1Char('<');
- }
#endif
} else if (!isDereferenced(editor, basePosition) && ! function->isAmbiguous()) {
// When the user typed the opening parenthesis, he'll likely also type the closing one,
@@ -401,20 +376,20 @@ private:
QString CppFunctionHintModel::text(int index) const
{
Overview overview;
- overview.setShowReturnTypes(true);
- overview.setShowArgumentNames(true);
- overview.setMarkedArgument(m_currentArg + 1);
+ overview.showReturnTypes = true;
+ overview.showArgumentNames = true;
+ overview.markedArgument = m_currentArg + 1;
Function *f = m_functionSymbols.at(index);
- const QString prettyMethod = overview(f->type(), f->name());
- const int begin = overview.markedArgumentBegin();
- const int end = overview.markedArgumentEnd();
+ const QString prettyMethod = overview.prettyType(f->type(), f->name());
+ const int begin = overview.markedArgumentBegin;
+ const int end = overview.markedArgumentEnd;
QString hintText;
hintText += Qt::escape(prettyMethod.left(begin));
- hintText += "<b>";
+ hintText += QLatin1String("<b>");
hintText += Qt::escape(prettyMethod.mid(begin, end - begin));
- hintText += "</b>";
+ hintText += QLatin1String("</b>");
hintText += Qt::escape(prettyMethod.mid(end));
return hintText;
}
@@ -536,8 +511,8 @@ public:
: _item(0)
, _symbol(0)
{
- overview.setShowReturnTypes(true);
- overview.setShowArgumentNames(true);
+ overview.showReturnTypes = true;
+ overview.showArgumentNames = true;
}
BasicProposalItem *operator()(Symbol *symbol)
@@ -579,9 +554,8 @@ protected:
virtual void visit(const Identifier *name)
{
_item = newCompletionItem(name);
- if (!_symbol->isScope() || _symbol->isFunction()) {
+ if (!_symbol->isScope() || _symbol->isFunction())
_item->setDetail(overview.prettyType(_symbol->type(), name));
- }
}
virtual void visit(const TemplateNameId *name)
@@ -648,7 +622,7 @@ Function *asFunctionOrTemplateFunctionType(FullySpecifiedType ty)
CppCompletionAssistProcessor::CppCompletionAssistProcessor()
: m_startPosition(-1)
, m_objcEnabled(true)
- , m_snippetCollector(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID,
+ , m_snippetCollector(QLatin1String(CppEditor::Constants::CPP_SNIPPETS_GROUP_ID),
QIcon(QLatin1String(":/texteditor/images/snippet.png")))
, preprocessorCompletions(QStringList()
<< QLatin1String("define")
@@ -931,9 +905,6 @@ int CppCompletionAssistProcessor::startCompletionHelper()
&m_model->m_completionOperator,
/*want function call =*/ true);
- const Core::IDocument *document = m_interface->document();
- QString fileName = document->fileName();
-
if (m_model->m_completionOperator == T_DOXY_COMMENT) {
for (int i = 1; i < T_DOXY_LAST_TAG; ++i)
addCompletionItem(QString::fromLatin1(doxygenTagSpell(i)), m_icons.keywordIcon());
@@ -1005,6 +976,7 @@ int CppCompletionAssistProcessor::startCompletionHelper()
int line = 0, column = 0;
Convenience::convertPosition(m_interface->textDocument(), startOfExpression, &line, &column);
+ const QString fileName = m_interface->document()->fileName();
return startCompletionInternal(fileName, line, column, expression, endOfExpression);
}
@@ -1068,6 +1040,18 @@ bool CppCompletionAssistProcessor::tryObjCCompletion()
return true;
}
+namespace {
+enum CompletionOrder {
+ // default order is 0
+ FunctionArgumentsOrder = 2,
+ FunctionLocalsOrder = 2, // includes local types
+ PublicClassMemberOrder = 1,
+ InjectedClassNameOrder = -1,
+ MacrosOrder = -2,
+ KeywordsOrder = -2
+};
+}
+
void CppCompletionAssistProcessor::addCompletionItem(const QString &text,
const QIcon &icon,
int order,
@@ -1081,12 +1065,14 @@ void CppCompletionAssistProcessor::addCompletionItem(const QString &text,
m_completions.append(item);
}
-void CppCompletionAssistProcessor::addCompletionItem(CPlusPlus::Symbol *symbol)
+void CppCompletionAssistProcessor::addCompletionItem(CPlusPlus::Symbol *symbol,
+ int order)
{
ConvertToCompletionItem toCompletionItem;
BasicProposalItem *item = toCompletionItem(symbol);
if (item) {
item->setIcon(m_icons.iconForSymbol(symbol));
+ item->setOrder(order);
m_completions.append(item);
}
}
@@ -1116,17 +1102,17 @@ void CppCompletionAssistProcessor::completeObjCMsgSend(CPlusPlus::ClassOrNamespa
if (i > 0)
text += QLatin1Char(' ');
Symbol *arg = method->argumentAt(i);
- text += selectorName->nameAt(i)->identifier()->chars();
+ text += QString::fromUtf8(selectorName->nameAt(i)->identifier()->chars());
text += QLatin1Char(':');
text += TextEditor::Snippet::kVariableDelimiter;
text += QLatin1Char('(');
- text += oo(arg->type());
+ text += oo.prettyType(arg->type());
text += QLatin1Char(')');
- text += oo(arg->name());
+ text += oo.prettyName(arg->name());
text += TextEditor::Snippet::kVariableDelimiter;
}
} else {
- text = selectorName->identifier()->chars();
+ text = QString::fromUtf8(selectorName->identifier()->chars());
}
data = text;
@@ -1219,11 +1205,10 @@ bool CppCompletionAssistProcessor::objcKeywordsWanted() const
if (!m_objcEnabled)
return false;
- const Core::IDocument *document = m_interface->document();
- QString fileName = document->fileName();
+ const QString fileName = m_interface->document()->fileName();
const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- return mdb->findByFile(fileName).type() == CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE;
+ return mdb->findByFile(fileName).type() == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE);
}
int CppCompletionAssistProcessor::startCompletionInternal(const QString fileName,
@@ -1376,12 +1361,12 @@ void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentSco
for (Scope *scope = currentScope; scope; scope = scope->enclosingScope()) {
if (scope->isBlock()) {
for (unsigned i = 0; i < scope->memberCount(); ++i) {
- addCompletionItem(scope->memberAt(i));
+ addCompletionItem(scope->memberAt(i), FunctionLocalsOrder);
}
} else if (scope->isFunction()) {
Function *fun = scope->asFunction();
for (unsigned i = 0; i < fun->argumentCount(); ++i) {
- addCompletionItem(fun->argumentAt(i));
+ addCompletionItem(fun->argumentAt(i), FunctionArgumentsOrder);
}
break;
} else {
@@ -1393,10 +1378,10 @@ void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentSco
const QList<Symbol *> symbols = currentBinding->symbols();
if (! symbols.isEmpty()) {
- if (symbols.first()->isNamespace())
- completeNamespace(currentBinding);
- else
+ if (symbols.first()->isClass())
completeClass(currentBinding);
+ else
+ completeNamespace(currentBinding);
}
}
@@ -1404,7 +1389,7 @@ void CppCompletionAssistProcessor::globalCompletion(CPlusPlus::Scope *currentSco
completeNamespace(b);
addKeywords();
- addMacros(QLatin1String("<configuration>"), context.snapshot());
+ addMacros(CppModelManagerInterface::configurationFileName(), context.snapshot());
addMacros(context.thisDocument()->fileName(), context.snapshot());
addSnippets();
}
@@ -1423,7 +1408,7 @@ bool CppCompletionAssistProcessor::completeMember(const QList<CPlusPlus::LookupI
m_model->m_completionOperator,
&m_model->m_replaceDotForArrow)) {
if (binding)
- completeClass(binding, /*static lookup = */ false);
+ completeClass(binding, /*static lookup = */ true);
return ! m_completions.isEmpty();
}
@@ -1466,6 +1451,12 @@ bool CppCompletionAssistProcessor::completeScope(const QList<CPlusPlus::LookupIt
completeClass(b);
break;
}
+
+ } else if (Enum *e = ty->asEnumType()) {
+ if (ClassOrNamespace *b = context.lookupType(e)) {
+ completeNamespace(b);
+ break;
+ }
}
}
@@ -1490,11 +1481,11 @@ void CppCompletionAssistProcessor::completeNamespace(CPlusPlus::ClassOrNamespace
QSet<Scope *> scopesVisited;
foreach (Symbol *bb, binding->symbols()) {
- if (Namespace *ns = bb->asNamespace())
- scopesToVisit.append(ns);
+ if (Scope *scope = bb->asScope())
+ scopesToVisit.append(scope);
}
- foreach (Enum *e, binding->enums()) {
+ foreach (Enum *e, binding->unscopedEnums()) {
scopesToVisit.append(e);
}
@@ -1535,7 +1526,7 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
scopesToVisit.append(k);
}
- foreach (Enum *e, binding->enums())
+ foreach (Enum *e, binding->unscopedEnums())
scopesToVisit.append(e);
while (! scopesToVisit.isEmpty()) {
@@ -1545,7 +1536,8 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
scopesVisited.insert(scope);
- addCompletionItem(scope); // add a completion item for the injected class name.
+ if (staticLookup)
+ addCompletionItem(scope, InjectedClassNameOrder); // add a completion item for the injected class name.
for (Scope::iterator it = scope->firstMember(); it != scope->lastMember(); ++it) {
Symbol *member = *it;
@@ -1559,7 +1551,10 @@ void CppCompletionAssistProcessor::completeClass(CPlusPlus::ClassOrNamespace *b,
continue;
}
- addCompletionItem(member);
+ if (member->isPublic())
+ addCompletionItem(member, PublicClassMemberOrder);
+ else
+ addCompletionItem(member);
}
}
}
@@ -1574,9 +1569,9 @@ bool CppCompletionAssistProcessor::completeQtMethod(const QList<CPlusPlus::Looku
ConvertToCompletionItem toCompletionItem;
Overview o;
- o.setShowReturnTypes(false);
- o.setShowArgumentNames(false);
- o.setShowFunctionSignatures(true);
+ o.showReturnTypes = false;
+ o.showArgumentNames = false;
+ o.showFunctionSignatures = true;
QSet<QString> signatures;
foreach (const LookupItem &p, results) {
@@ -1678,7 +1673,7 @@ void CppCompletionAssistProcessor::addKeywords()
// keyword completion items.
for (int i = T_FIRST_KEYWORD; i < keywordLimit; ++i)
- addCompletionItem(QLatin1String(Token::name(i)), m_icons.keywordIcon());
+ addCompletionItem(QLatin1String(Token::name(i)), m_icons.keywordIcon(), KeywordsOrder);
}
void CppCompletionAssistProcessor::addMacros(const QString &fileName, const CPlusPlus::Snapshot &snapshot)
@@ -1689,7 +1684,7 @@ void CppCompletionAssistProcessor::addMacros(const QString &fileName, const CPlu
addMacros_helper(snapshot, fileName, &processed, &definedMacros);
foreach (const QString &macroName, definedMacros)
- addCompletionItem(macroName, m_icons.macroIcon());
+ addCompletionItem(macroName, m_icons.macroIcon(), MacrosOrder);
}
void CppCompletionAssistProcessor::addMacros_helper(const CPlusPlus::Snapshot &snapshot,
@@ -1793,9 +1788,8 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
Symbol *overload = r.declaration();
FullySpecifiedType overloadTy = overload->type().simplified();
- if (Function *funTy = overloadTy->asFunctionType()) {
+ if (Function *funTy = overloadTy->asFunctionType())
functions.append(funTy);
- }
}
}
}
@@ -1838,7 +1832,7 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
int lineStartToken = bs.startOfLine(startToken);
// make sure the required tokens are actually available
bs.LA(startToken - lineStartToken);
- QString possibleDecl = bs.mid(lineStartToken).trimmed().append("();");
+ QString possibleDecl = bs.mid(lineStartToken).trimmed().append(QLatin1String("();"));
Document::Ptr doc = Document::create(QLatin1String("<completion>"));
doc->setUtf8Source(possibleDecl.toLatin1());
@@ -1882,13 +1876,13 @@ bool CppCompletionAssistProcessor::completeConstructorOrFunction(const QList<CPl
// set up signature autocompletion
foreach (Function *f, functions) {
Overview overview;
- overview.setShowArgumentNames(true);
- overview.setShowDefaultArguments(false);
+ overview.showArgumentNames = true;
+ overview.showDefaultArguments = false;
const FullySpecifiedType localTy = rewriteType(f->type(), &env, control);
// gets: "parameter list) cv-spec",
- QString completion = overview(localTy).mid(1);
+ QString completion = overview.prettyType(localTy).mid(1);
addCompletionItem(completion, QIcon(), 0,
QVariant::fromValue(CompleteFunctionDeclaration(f)));
diff --git a/src/plugins/cpptools/cppcompletionassist.h b/src/plugins/cpptools/cppcompletionassist.h
index 654c455f1d..e574fb413a 100644
--- a/src/plugins/cpptools/cppcompletionassist.h
+++ b/src/plugins/cpptools/cppcompletionassist.h
@@ -41,10 +41,12 @@
# include <cplusplus/Symbol.h>
#endif
+#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <texteditor/codeassist/completionassistprovider.h>
#include <texteditor/codeassist/iassistprocessor.h>
#include <texteditor/snippets/snippetassistcollector.h>
#include <texteditor/codeassist/defaultassistinterface.h>
+#include <texteditor/codeassist/basicproposalitem.h>
#include <QStringList>
#include <QVariant>
@@ -64,7 +66,26 @@ namespace CppTools {
namespace Internal {
class CppCompletionAssistInterface;
-class CppAssistProposalModel;
+
+class CppAssistProposalModel : public TextEditor::BasicProposalItemListModel
+{
+public:
+ CppAssistProposalModel()
+ : TextEditor::BasicProposalItemListModel()
+ , m_completionOperator(CPlusPlus::T_EOF_SYMBOL)
+ , m_replaceDotForArrow(false)
+ , m_typeOfExpression(new CPlusPlus::TypeOfExpression)
+ {
+ m_typeOfExpression->setExpandTemplates(true);
+ }
+
+ virtual bool isSortable(const QString &prefix) const;
+ virtual TextEditor::IAssistProposalItem *proposalItem(int index) const;
+
+ unsigned m_completionOperator;
+ bool m_replaceDotForArrow;
+ QSharedPointer<CPlusPlus::TypeOfExpression> m_typeOfExpression;
+};
class InternalCompletionAssistProvider : public CppCompletionAssistProvider
{
@@ -120,7 +141,8 @@ private:
const QIcon &icon = QIcon(),
int order = 0,
const QVariant &data = QVariant());
- void addCompletionItem(CPlusPlus::Symbol *symbol);
+ void addCompletionItem(CPlusPlus::Symbol *symbol,
+ int order = 0);
void addSnippets();
void addKeywords();
void addMacros(const QString &fileName, const CPlusPlus::Snapshot &snapshot);
diff --git a/src/plugins/cpptools/cppcurrentdocumentfilter.cpp b/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
index 43b7b13066..ee859b1396 100644
--- a/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
+++ b/src/plugins/cpptools/cppcurrentdocumentfilter.cpp
@@ -40,13 +40,15 @@ using namespace CPlusPlus;
CppCurrentDocumentFilter::CppCurrentDocumentFilter(CppModelManager *manager, Core::EditorManager *editorManager)
: m_modelManager(manager)
{
+ setId("Methods in current Document");
+ setDisplayName(tr("C++ Methods in Current Document"));
setShortcutString(QString(QLatin1Char('.')));
setIncludedByDefault(false);
- search.setSymbolsToSearchFor(SearchSymbols::Declarations |
- SearchSymbols::Enums |
- SearchSymbols::Functions |
- SearchSymbols::Classes);
+ search.setSymbolsToSearchFor(SymbolSearcher::Declarations |
+ SymbolSearcher::Enums |
+ SymbolSearcher::Functions |
+ SymbolSearcher::Classes);
search.setSeparateScope(true);
@@ -68,7 +70,7 @@ QList<Locator::FilterEntry> CppCurrentDocumentFilter::matchesFor(QFutureInterfac
QRegExp regexp(asterisk + entry + asterisk, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
return goodEntries;
- bool hasWildcard = (entry.contains(asterisk) || entry.contains('?'));
+ bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?')));
if (m_currentFileName.isEmpty())
return goodEntries;
@@ -120,18 +122,16 @@ void CppCurrentDocumentFilter::refresh(QFutureInterface<void> &future)
void CppCurrentDocumentFilter::onDocumentUpdated(Document::Ptr doc)
{
- if (m_currentFileName == doc->fileName()) {
+ if (m_currentFileName == doc->fileName())
m_itemsOfCurrentDoc.clear();
- }
}
void CppCurrentDocumentFilter::onCurrentEditorChanged(Core::IEditor * currentEditor)
{
- if (currentEditor) {
+ if (currentEditor)
m_currentFileName = currentEditor->document()->fileName();
- } else {
+ else
m_currentFileName.clear();
- }
m_itemsOfCurrentDoc.clear();
}
diff --git a/src/plugins/cpptools/cppcurrentdocumentfilter.h b/src/plugins/cpptools/cppcurrentdocumentfilter.h
index 517fd79557..4f4fd08272 100644
--- a/src/plugins/cpptools/cppcurrentdocumentfilter.h
+++ b/src/plugins/cpptools/cppcurrentdocumentfilter.h
@@ -50,9 +50,6 @@ public:
CppCurrentDocumentFilter(CppModelManager *manager, Core::EditorManager *editorManager);
~CppCurrentDocumentFilter() {}
- QString displayName() const { return tr("Methods in Current Document"); }
- QString id() const { return QLatin1String("Methods in current Document"); }
- Priority priority() const { return Medium; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/cpptools/cppdoxygen.cpp b/src/plugins/cpptools/cppdoxygen.cpp
index 3e9c9804ba..ea596b75a7 100644
--- a/src/plugins/cpptools/cppdoxygen.cpp
+++ b/src/plugins/cpptools/cppdoxygen.cpp
@@ -266,66 +266,51 @@ const char *CppTools::doxygenTagSpell(int index)
{ return doxy_token_spell[index]; }
static inline int classify1(const QChar *s) {
- if (s[0].unicode() == 'a') {
+ if (s[0].unicode() == 'a')
return T_DOXY_A;
- }
- else if (s[0].unicode() == 'b') {
+ else if (s[0].unicode() == 'b')
return T_DOXY_B;
- }
- else if (s[0].unicode() == 'c') {
+ else if (s[0].unicode() == 'c')
return T_DOXY_C;
- }
- else if (s[0].unicode() == 'e') {
+ else if (s[0].unicode() == 'e')
return T_DOXY_E;
- }
- else if (s[0].unicode() == 'i') {
+ else if (s[0].unicode() == 'i')
return T_DOXY_I;
- }
- else if (s[0].unicode() == 'l') {
+ else if (s[0].unicode() == 'l')
return T_DOXY_L;
- }
- else if (s[0].unicode() == 'n') {
+ else if (s[0].unicode() == 'n')
return T_DOXY_N;
- }
- else if (s[0].unicode() == 'o') {
+ else if (s[0].unicode() == 'o')
return T_DOXY_O;
- }
- else if (s[0].unicode() == 'p') {
+ else if (s[0].unicode() == 'p')
return T_DOXY_P;
- }
return T_DOXY_IDENTIFIER;
}
static inline int classify2(const QChar *s) {
if (s[0].unicode() == 'e') {
- if (s[1].unicode() == 'm') {
+ if (s[1].unicode() == 'm')
return T_DOXY_EM;
- }
}
else if (s[0].unicode() == 'f') {
- if (s[1].unicode() == 'n') {
+ if (s[1].unicode() == 'n')
return T_DOXY_FN;
- }
}
else if (s[0].unicode() == 'i') {
- if (s[1].unicode() == 'f') {
+ if (s[1].unicode() == 'f')
return T_DOXY_IF;
- }
}
else if (s[0].unicode() == 'l') {
- if (s[1].unicode() == 'i') {
+ if (s[1].unicode() == 'i')
return T_DOXY_LI;
- }
}
else if (s[0].unicode() == 's') {
- if (s[1].unicode() == 'a') {
+ if (s[1].unicode() == 'a')
return T_DOXY_SA;
- }
}
else if (s[0].unicode() == 't') {
- if (s[1].unicode() == 't') {
+ if (s[1].unicode() == 't')
return T_DOXY_TT;
- }
}
return T_DOXY_IDENTIFIER;
}
@@ -333,103 +318,86 @@ static inline int classify2(const QChar *s) {
static inline int classify3(const QChar *s) {
if (s[0].unicode() == 'a') {
if (s[1].unicode() == 'r') {
- if (s[2].unicode() == 'g') {
+ if (s[2].unicode() == 'g')
return T_DOXY_ARG;
- }
}
}
else if (s[0].unicode() == 'b') {
if (s[1].unicode() == 'u') {
- if (s[2].unicode() == 'g') {
+ if (s[2].unicode() == 'g')
return T_DOXY_BUG;
- }
}
}
else if (s[0].unicode() == 'd') {
if (s[1].unicode() == 'e') {
- if (s[2].unicode() == 'f') {
+ if (s[2].unicode() == 'f')
return T_DOXY_DEF;
- }
}
else if (s[1].unicode() == 'o') {
- if (s[2].unicode() == 't') {
+ if (s[2].unicode() == 't')
return T_DOXY_DOT;
- }
}
}
else if (s[0].unicode() == 'g') {
if (s[1].unicode() == 'u') {
- if (s[2].unicode() == 'i') {
+ if (s[2].unicode() == 'i')
return T_DOXY_GUI;
- }
}
}
else if (s[0].unicode() == 'p') {
if (s[1].unicode() == 'a') {
- if (s[2].unicode() == 'r') {
+ if (s[2].unicode() == 'r')
return T_DOXY_PAR;
- }
}
else if (s[1].unicode() == 'r') {
- if (s[2].unicode() == 'e') {
+ if (s[2].unicode() == 'e')
return T_DOXY_PRE;
- }
}
}
else if (s[0].unicode() == 'r') {
if (s[1].unicode() == 'a') {
- if (s[2].unicode() == 'w') {
+ if (s[2].unicode() == 'w')
return T_DOXY_RAW;
- }
}
else if (s[1].unicode() == 'e') {
- if (s[2].unicode() == 'f') {
+ if (s[2].unicode() == 'f')
return T_DOXY_REF;
- }
}
else if (s[1].unicode() == 'o') {
- if (s[2].unicode() == 'w') {
+ if (s[2].unicode() == 'w')
return T_DOXY_ROW;
- }
}
}
else if (s[0].unicode() == 's') {
if (s[1].unicode() == 'e') {
- if (s[2].unicode() == 'e') {
+ if (s[2].unicode() == 'e')
return T_DOXY_SEE;
- }
}
else if (s[1].unicode() == 'q') {
- if (s[2].unicode() == 'l') {
+ if (s[2].unicode() == 'l')
return T_DOXY_SQL;
- }
}
else if (s[1].unicode() == 'u') {
- if (s[2].unicode() == 'b') {
+ if (s[2].unicode() == 'b')
return T_DOXY_SUB;
- }
- else if (s[2].unicode() == 'p') {
+ else if (s[2].unicode() == 'p')
return T_DOXY_SUP;
- }
}
else if (s[1].unicode() == 'v') {
- if (s[2].unicode() == 'g') {
+ if (s[2].unicode() == 'g')
return T_DOXY_SVG;
- }
}
}
else if (s[0].unicode() == 'v') {
if (s[1].unicode() == 'a') {
- if (s[2].unicode() == 'r') {
+ if (s[2].unicode() == 'r')
return T_DOXY_VAR;
- }
}
}
else if (s[0].unicode() == 'x') {
if (s[1].unicode() == 'm') {
- if (s[2].unicode() == 'l') {
+ if (s[2].unicode() == 'l')
return T_DOXY_XML;
- }
}
}
return T_DOXY_IDENTIFIER;
@@ -439,168 +407,146 @@ static inline int classify4(const QChar *s) {
if (s[0].unicode() == 'b') {
if (s[1].unicode() == 'o') {
if (s[2].unicode() == 'l') {
- if (s[3].unicode() == 'd') {
+ if (s[3].unicode() == 'd')
return T_DOXY_BOLD;
- }
}
}
}
else if (s[0].unicode() == 'c') {
if (s[1].unicode() == 'o') {
if (s[2].unicode() == 'd') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_CODE;
- }
}
else if (s[2].unicode() == 'n') {
- if (s[3].unicode() == 'd') {
+ if (s[3].unicode() == 'd')
return T_DOXY_COND;
- }
}
}
}
else if (s[0].unicode() == 'd') {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 't') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_DATE;
- }
}
}
else if (s[1].unicode() == 'o') {
if (s[2].unicode() == 't') {
- if (s[3].unicode() == 's') {
+ if (s[3].unicode() == 's')
return T_DOXY_DOTS;
- }
}
}
}
else if (s[0].unicode() == 'e') {
if (s[1].unicode() == 'l') {
if (s[2].unicode() == 's') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_ELSE;
- }
}
}
else if (s[1].unicode() == 'n') {
if (s[2].unicode() == 'u') {
- if (s[3].unicode() == 'm') {
+ if (s[3].unicode() == 'm')
return T_DOXY_ENUM;
- }
}
}
}
else if (s[0].unicode() == 'f') {
if (s[1].unicode() == 'i') {
if (s[2].unicode() == 'l') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_FILE;
- }
}
}
}
else if (s[0].unicode() == 'l') {
if (s[1].unicode() == 'i') {
if (s[2].unicode() == 'n') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_LINE;
- }
- else if (s[3].unicode() == 'k') {
+ else if (s[3].unicode() == 'k')
return T_DOXY_LINK;
- }
}
else if (s[2].unicode() == 's') {
- if (s[3].unicode() == 't') {
+ if (s[3].unicode() == 't')
return T_DOXY_LIST;
- }
}
}
}
else if (s[0].unicode() == 'm') {
if (s[1].unicode() == 'e') {
if (s[2].unicode() == 't') {
- if (s[3].unicode() == 'a') {
+ if (s[3].unicode() == 'a')
return T_DOXY_META;
- }
}
}
}
else if (s[0].unicode() == 'n') {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 'm') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_NAME;
- }
}
}
else if (s[1].unicode() == 'o') {
if (s[2].unicode() == 't') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_NOTE;
- }
}
}
}
else if (s[0].unicode() == 'o') {
if (s[1].unicode() == 'm') {
if (s[2].unicode() == 'i') {
- if (s[3].unicode() == 't') {
+ if (s[3].unicode() == 't')
return T_DOXY_OMIT;
- }
}
}
else if (s[1].unicode() == 'n') {
if (s[2].unicode() == 'l') {
- if (s[3].unicode() == 'y') {
+ if (s[3].unicode() == 'y')
return T_DOXY_ONLY;
- }
}
}
}
else if (s[0].unicode() == 'p') {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 'g') {
- if (s[3].unicode() == 'e') {
+ if (s[3].unicode() == 'e')
return T_DOXY_PAGE;
- }
}
else if (s[2].unicode() == 'r') {
- if (s[3].unicode() == 't') {
+ if (s[3].unicode() == 't')
return T_DOXY_PART;
- }
}
}
else if (s[1].unicode() == 'o') {
if (s[2].unicode() == 's') {
- if (s[3].unicode() == 't') {
+ if (s[3].unicode() == 't')
return T_DOXY_POST;
- }
}
}
}
else if (s[0].unicode() == 's') {
if (s[1].unicode() == 'k') {
if (s[2].unicode() == 'i') {
- if (s[3].unicode() == 'p') {
+ if (s[3].unicode() == 'p')
return T_DOXY_SKIP;
- }
}
}
}
else if (s[0].unicode() == 't') {
if (s[1].unicode() == 'e') {
if (s[2].unicode() == 's') {
- if (s[3].unicode() == 't') {
+ if (s[3].unicode() == 't')
return T_DOXY_TEST;
- }
}
}
else if (s[1].unicode() == 'o') {
if (s[2].unicode() == 'd') {
- if (s[3].unicode() == 'o') {
+ if (s[3].unicode() == 'o')
return T_DOXY_TODO;
- }
}
}
}
@@ -612,9 +558,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'r') {
if (s[2].unicode() == 'i') {
if (s[3].unicode() == 'e') {
- if (s[4].unicode() == 'f') {
+ if (s[4].unicode() == 'f')
return T_DOXY_BRIEF;
- }
}
}
}
@@ -623,9 +568,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'l') {
if (s[2].unicode() == 'a') {
if (s[3].unicode() == 's') {
- if (s[4].unicode() == 's') {
+ if (s[4].unicode() == 's')
return T_DOXY_CLASS;
- }
}
}
}
@@ -634,9 +578,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'n') {
if (s[2].unicode() == 'd') {
if (s[3].unicode() == 'i') {
- if (s[4].unicode() == 'f') {
+ if (s[4].unicode() == 'f')
return T_DOXY_ENDIF;
- }
}
}
}
@@ -645,9 +588,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'r') {
if (s[2].unicode() == 'o') {
if (s[3].unicode() == 'u') {
- if (s[4].unicode() == 'p') {
+ if (s[4].unicode() == 'p')
return T_DOXY_GROUP;
- }
}
}
}
@@ -656,27 +598,24 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'f') {
if (s[2].unicode() == 'n') {
if (s[3].unicode() == 'o') {
- if (s[4].unicode() == 't') {
+ if (s[4].unicode() == 't')
return T_DOXY_IFNOT;
- }
}
}
}
else if (s[1].unicode() == 'm') {
if (s[2].unicode() == 'a') {
if (s[3].unicode() == 'g') {
- if (s[4].unicode() == 'e') {
+ if (s[4].unicode() == 'e')
return T_DOXY_IMAGE;
- }
}
}
}
else if (s[1].unicode() == 'n') {
if (s[2].unicode() == 'd') {
if (s[3].unicode() == 'e') {
- if (s[4].unicode() == 'x') {
+ if (s[4].unicode() == 'x')
return T_DOXY_INDEX;
- }
}
}
}
@@ -685,9 +624,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 'c') {
if (s[3].unicode() == 'r') {
- if (s[4].unicode() == 'o') {
+ if (s[4].unicode() == 'o')
return T_DOXY_MACRO;
- }
}
}
}
@@ -696,9 +634,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 'r') {
if (s[3].unicode() == 'a') {
- if (s[4].unicode() == 'm') {
+ if (s[4].unicode() == 'm')
return T_DOXY_PARAM;
- }
}
}
}
@@ -707,9 +644,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'e') {
if (s[2].unicode() == 'i') {
if (s[3].unicode() == 'm') {
- if (s[4].unicode() == 'p') {
+ if (s[4].unicode() == 'p')
return T_DOXY_REIMP;
- }
}
}
}
@@ -718,18 +654,16 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'h') {
if (s[2].unicode() == 'o') {
if (s[3].unicode() == 'r') {
- if (s[4].unicode() == 't') {
+ if (s[4].unicode() == 't')
return T_DOXY_SHORT;
- }
}
}
}
else if (s[1].unicode() == 'i') {
if (s[2].unicode() == 'n') {
if (s[3].unicode() == 'c') {
- if (s[4].unicode() == 'e') {
+ if (s[4].unicode() == 'e')
return T_DOXY_SINCE;
- }
}
}
}
@@ -738,27 +672,24 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 'b') {
if (s[3].unicode() == 'l') {
- if (s[4].unicode() == 'e') {
+ if (s[4].unicode() == 'e')
return T_DOXY_TABLE;
- }
}
}
}
else if (s[1].unicode() == 'h') {
if (s[2].unicode() == 'r') {
if (s[3].unicode() == 'o') {
- if (s[4].unicode() == 'w') {
+ if (s[4].unicode() == 'w')
return T_DOXY_THROW;
- }
}
}
}
else if (s[1].unicode() == 'i') {
if (s[2].unicode() == 't') {
if (s[3].unicode() == 'l') {
- if (s[4].unicode() == 'e') {
+ if (s[4].unicode() == 'e')
return T_DOXY_TITLE;
- }
}
}
}
@@ -767,16 +698,14 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'n') {
if (s[2].unicode() == 'i') {
if (s[3].unicode() == 'o') {
- if (s[4].unicode() == 'n') {
+ if (s[4].unicode() == 'n')
return T_DOXY_UNION;
- }
}
}
else if (s[2].unicode() == 't') {
if (s[3].unicode() == 'i') {
- if (s[4].unicode() == 'l') {
+ if (s[4].unicode() == 'l')
return T_DOXY_UNTIL;
- }
}
}
}
@@ -785,9 +714,8 @@ static inline int classify5(const QChar *s) {
if (s[1].unicode() == 'a') {
if (s[2].unicode() == 'l') {
if (s[3].unicode() == 'u') {
- if (s[4].unicode() == 'e') {
+ if (s[4].unicode() == 'e')
return T_DOXY_VALUE;
- }
}
}
}
@@ -801,9 +729,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'c') {
if (s[3].unicode() == 'h') {
if (s[4].unicode() == 'o') {
- if (s[5].unicode() == 'r') {
+ if (s[5].unicode() == 'r')
return T_DOXY_ANCHOR;
- }
}
}
}
@@ -812,9 +739,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 't') {
if (s[3].unicode() == 'h') {
if (s[4].unicode() == 'o') {
- if (s[5].unicode() == 'r') {
+ if (s[5].unicode() == 'r')
return T_DOXY_AUTHOR;
- }
}
}
}
@@ -825,9 +751,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'm') {
if (s[3].unicode() == 'p') {
if (s[4].unicode() == 'a') {
- if (s[5].unicode() == 't') {
+ if (s[5].unicode() == 't')
return T_DOXY_COMPAT;
- }
}
}
}
@@ -838,9 +763,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 's') {
if (s[3].unicode() == 'e') {
if (s[4].unicode() == 'i') {
- if (s[5].unicode() == 'f') {
+ if (s[5].unicode() == 'f')
return T_DOXY_ELSEIF;
- }
}
}
}
@@ -849,16 +773,14 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'd') {
if (s[3].unicode() == 'd') {
if (s[4].unicode() == 'o') {
- if (s[5].unicode() == 't') {
+ if (s[5].unicode() == 't')
return T_DOXY_ENDDOT;
- }
}
}
else if (s[3].unicode() == 'r') {
if (s[4].unicode() == 'a') {
- if (s[5].unicode() == 'w') {
+ if (s[5].unicode() == 'w')
return T_DOXY_ENDRAW;
- }
}
}
}
@@ -867,9 +789,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'p') {
if (s[3].unicode() == 'i') {
if (s[4].unicode() == 'r') {
- if (s[5].unicode() == 'e') {
+ if (s[5].unicode() == 'e')
return T_DOXY_EXPIRE;
- }
}
}
}
@@ -880,9 +801,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'a') {
if (s[3].unicode() == 'd') {
if (s[4].unicode() == 'e') {
- if (s[5].unicode() == 'r') {
+ if (s[5].unicode() == 'r')
return T_DOXY_HEADER;
- }
}
}
}
@@ -893,9 +813,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'd') {
if (s[3].unicode() == 'u') {
if (s[4].unicode() == 'l') {
- if (s[5].unicode() == 'e') {
+ if (s[5].unicode() == 'e')
return T_DOXY_MODULE;
- }
}
}
}
@@ -906,9 +825,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'e') {
if (s[3].unicode() == 'n') {
if (s[4].unicode() == 'g') {
- if (s[5].unicode() == 'l') {
+ if (s[5].unicode() == 'l')
return T_DOXY_OPENGL;
- }
}
}
}
@@ -919,16 +837,14 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 't') {
if (s[3].unicode() == 'u') {
if (s[4].unicode() == 'r') {
- if (s[5].unicode() == 'n') {
+ if (s[5].unicode() == 'n')
return T_DOXY_RETURN;
- }
}
}
else if (s[3].unicode() == 'v') {
if (s[4].unicode() == 'a') {
- if (s[5].unicode() == 'l') {
+ if (s[5].unicode() == 'l')
return T_DOXY_RETVAL;
- }
}
}
}
@@ -939,9 +855,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'i') {
if (s[3].unicode() == 'p') {
if (s[4].unicode() == 't') {
- if (s[5].unicode() == 'o') {
+ if (s[5].unicode() == 'o')
return T_DOXY_SKIPTO;
- }
}
}
}
@@ -950,9 +865,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'r') {
if (s[3].unicode() == 'u') {
if (s[4].unicode() == 'c') {
- if (s[5].unicode() == 't') {
+ if (s[5].unicode() == 't')
return T_DOXY_STRUCT;
- }
}
}
}
@@ -963,9 +877,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'r') {
if (s[3].unicode() == 'g') {
if (s[4].unicode() == 'e') {
- if (s[5].unicode() == 't') {
+ if (s[5].unicode() == 't')
return T_DOXY_TARGET;
- }
}
}
}
@@ -974,9 +887,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'r') {
if (s[3].unicode() == 'o') {
if (s[4].unicode() == 'w') {
- if (s[5].unicode() == 's') {
+ if (s[5].unicode() == 's')
return T_DOXY_THROWS;
- }
}
}
}
@@ -987,9 +899,8 @@ static inline int classify6(const QChar *s) {
if (s[2].unicode() == 'b') {
if (s[3].unicode() == 'k') {
if (s[4].unicode() == 'i') {
- if (s[5].unicode() == 't') {
+ if (s[5].unicode() == 't')
return T_DOXY_WEBKIT;
- }
}
}
}
@@ -1005,9 +916,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'c') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'd') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_BADCODE;
- }
}
}
}
@@ -1020,9 +930,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 't') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'o') {
- if (s[6].unicode() == 'n') {
+ if (s[6].unicode() == 'n')
return T_DOXY_CAPTION;
- }
}
}
}
@@ -1033,9 +942,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'p') {
if (s[4].unicode() == 't') {
if (s[5].unicode() == 'e') {
- if (s[6].unicode() == 'r') {
+ if (s[6].unicode() == 'r')
return T_DOXY_CHAPTER;
- }
}
}
}
@@ -1046,9 +954,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'y') {
if (s[4].unicode() == 'd') {
if (s[5].unicode() == 'o') {
- if (s[6].unicode() == 'c') {
+ if (s[6].unicode() == 'c')
return T_DOXY_COPYDOC;
- }
}
}
}
@@ -1057,9 +964,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'e') {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'i') {
- if (s[6].unicode() == 'b') {
+ if (s[6].unicode() == 'b')
return T_DOXY_CORELIB;
- }
}
}
}
@@ -1072,9 +978,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'f') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'l') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_DOTFILE;
- }
}
}
}
@@ -1087,46 +992,40 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'c') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'd') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_ENDCODE;
- }
}
else if (s[5].unicode() == 'n') {
- if (s[6].unicode() == 'd') {
+ if (s[6].unicode() == 'd')
return T_DOXY_ENDCOND;
- }
}
}
}
else if (s[3].unicode() == 'l') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'n') {
- if (s[6].unicode() == 'k') {
+ if (s[6].unicode() == 'k')
return T_DOXY_ENDLINK;
- }
}
else if (s[5].unicode() == 's') {
- if (s[6].unicode() == 't') {
+ if (s[6].unicode() == 't')
return T_DOXY_ENDLIST;
- }
}
}
}
else if (s[3].unicode() == 'o') {
if (s[4].unicode() == 'm') {
if (s[5].unicode() == 'i') {
- if (s[6].unicode() == 't') {
+ if (s[6].unicode() == 't')
return T_DOXY_ENDOMIT;
- }
}
}
}
else if (s[3].unicode() == 'p') {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 'r') {
- if (s[6].unicode() == 't') {
+ if (s[6].unicode() == 't')
return T_DOXY_ENDPART;
- }
}
}
}
@@ -1137,9 +1036,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'm') {
if (s[4].unicode() == 'p') {
if (s[5].unicode() == 'l') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_EXAMPLE;
- }
}
}
}
@@ -1152,9 +1050,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'l') {
if (s[4].unicode() == 'u') {
if (s[5].unicode() == 'd') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_INCLUDE;
- }
}
}
}
@@ -1163,9 +1060,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'r') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'u') {
- if (s[6].unicode() == 'p') {
+ if (s[6].unicode() == 'p')
return T_DOXY_INGROUP;
- }
}
}
}
@@ -1178,9 +1074,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'w') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'r') {
- if (s[6].unicode() == 'd') {
+ if (s[6].unicode() == 'd')
return T_DOXY_KEYWORD;
- }
}
}
}
@@ -1193,9 +1088,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'o') {
if (s[4].unicode() == 'n') {
if (s[5].unicode() == 'l') {
- if (s[6].unicode() == 'y') {
+ if (s[6].unicode() == 'y')
return T_DOXY_MANONLY;
- }
}
}
}
@@ -1208,9 +1102,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'w') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'r') {
- if (s[6].unicode() == 'k') {
+ if (s[6].unicode() == 'k')
return T_DOXY_NETWORK;
- }
}
}
}
@@ -1219,9 +1112,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'c') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'd') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_NEWCODE;
- }
}
}
}
@@ -1234,9 +1126,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'c') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'd') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_OLDCODE;
- }
}
}
}
@@ -1249,9 +1140,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'k') {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 'g') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_PACKAGE;
- }
}
}
}
@@ -1262,9 +1152,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'n') {
if (s[4].unicode() == 't') {
if (s[5].unicode() == 't') {
- if (s[6].unicode() == 'o') {
+ if (s[6].unicode() == 'o')
return T_DOXY_PRINTTO;
- }
}
}
}
@@ -1277,9 +1166,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'a') {
if (s[4].unicode() == 't') {
if (s[5].unicode() == 'e') {
- if (s[6].unicode() == 's') {
+ if (s[6].unicode() == 's')
return T_DOXY_RELATES;
- }
}
}
}
@@ -1288,9 +1176,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'a') {
if (s[4].unicode() == 'r') {
if (s[5].unicode() == 'k') {
- if (s[6].unicode() == 's') {
+ if (s[6].unicode() == 's')
return T_DOXY_REMARKS;
- }
}
}
}
@@ -1299,9 +1186,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'u') {
if (s[4].unicode() == 'r') {
if (s[5].unicode() == 'n') {
- if (s[6].unicode() == 's') {
+ if (s[6].unicode() == 's')
return T_DOXY_RETURNS;
- }
}
}
}
@@ -1314,9 +1200,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 't') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'o') {
- if (s[6].unicode() == 'n') {
+ if (s[6].unicode() == 'n')
return T_DOXY_SECTION;
- }
}
}
}
@@ -1325,9 +1210,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'v') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'c') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_SERVICE;
- }
}
}
}
@@ -1338,9 +1222,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'e') {
if (s[4].unicode() == 'b') {
if (s[5].unicode() == 'a') {
- if (s[6].unicode() == 'r') {
+ if (s[6].unicode() == 'r')
return T_DOXY_SIDEBAR;
- }
}
}
}
@@ -1351,9 +1234,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'p') {
if (s[4].unicode() == 'p') {
if (s[5].unicode() == 'e') {
- if (s[6].unicode() == 't') {
+ if (s[6].unicode() == 't')
return T_DOXY_SNIPPET;
- }
}
}
}
@@ -1366,9 +1248,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'e') {
if (s[4].unicode() == 'd') {
if (s[5].unicode() == 'e') {
- if (s[6].unicode() == 'f') {
+ if (s[6].unicode() == 'f')
return T_DOXY_TYPEDEF;
- }
}
}
}
@@ -1381,9 +1262,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'o') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'l') {
- if (s[6].unicode() == 's') {
+ if (s[6].unicode() == 's')
return T_DOXY_UITOOLS;
- }
}
}
}
@@ -1394,9 +1274,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'c') {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'd') {
- if (s[6].unicode() == 'e') {
+ if (s[6].unicode() == 'e')
return T_DOXY_UNICODE;
- }
}
}
}
@@ -1409,9 +1288,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 's') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'o') {
- if (s[6].unicode() == 'n') {
+ if (s[6].unicode() == 'n')
return T_DOXY_VERSION;
- }
}
}
}
@@ -1424,9 +1302,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'n') {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'n') {
- if (s[6].unicode() == 'g') {
+ if (s[6].unicode() == 'g')
return T_DOXY_WARNING;
- }
}
}
}
@@ -1439,9 +1316,8 @@ static inline int classify7(const QChar *s) {
if (s[3].unicode() == 'o') {
if (s[4].unicode() == 'n') {
if (s[5].unicode() == 'l') {
- if (s[6].unicode() == 'y') {
+ if (s[6].unicode() == 'y')
return T_DOXY_XMLONLY;
- }
}
}
}
@@ -1459,9 +1335,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'r') {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'c') {
- if (s[7].unicode() == 't') {
+ if (s[7].unicode() == 't')
return T_DOXY_ABSTRACT;
- }
}
}
}
@@ -1474,9 +1349,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'n') {
if (s[5].unicode() == 'd') {
if (s[6].unicode() == 'e') {
- if (s[7].unicode() == 'x') {
+ if (s[7].unicode() == 'x')
return T_DOXY_ADDINDEX;
- }
}
}
}
@@ -1491,9 +1365,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'n') {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'm') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_BASENAME;
- }
}
}
}
@@ -1508,9 +1381,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'i') {
if (s[6].unicode() == 'n') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_CODELINE;
- }
}
}
}
@@ -1525,9 +1397,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'r') {
if (s[5].unicode() == 'o') {
if (s[6].unicode() == 'u') {
- if (s[7].unicode() == 'p') {
+ if (s[7].unicode() == 'p')
return T_DOXY_DEFGROUP;
- }
}
}
}
@@ -1542,9 +1413,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 'b') {
if (s[6].unicode() == 'l') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_ENDTABLE;
- }
}
}
}
@@ -1559,9 +1429,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'n') {
if (s[5].unicode() == 'o') {
if (s[6].unicode() == 't') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_FOOTNOTE;
- }
}
}
}
@@ -1576,9 +1445,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'o') {
if (s[5].unicode() == 'n') {
if (s[6].unicode() == 'l') {
- if (s[7].unicode() == 'y') {
+ if (s[7].unicode() == 'y')
return T_DOXY_HTMLONLY;
- }
}
}
}
@@ -1593,9 +1461,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'd') {
if (s[5].unicode() == 'u') {
if (s[6].unicode() == 'l') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_INMODULE;
- }
}
}
}
@@ -1606,9 +1473,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'r') {
if (s[5].unicode() == 'n') {
if (s[6].unicode() == 'a') {
- if (s[7].unicode() == 'l') {
+ if (s[7].unicode() == 'l')
return T_DOXY_INTERNAL;
- }
}
}
}
@@ -1623,9 +1489,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'e') {
if (s[6].unicode() == 's') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_LEGALESE;
- }
}
}
}
@@ -1640,9 +1505,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'p') {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'g') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_MAINPAGE;
- }
}
}
}
@@ -1657,9 +1521,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'p') {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'g') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_NEXTPAGE;
- }
}
}
}
@@ -1674,9 +1537,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'e') {
if (s[6].unicode() == 't') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_OBSOLETE;
- }
}
}
}
@@ -1689,9 +1551,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'o') {
if (s[6].unicode() == 'a') {
- if (s[7].unicode() == 'd') {
+ if (s[7].unicode() == 'd')
return T_DOXY_OVERLOAD;
- }
}
}
}
@@ -1706,9 +1567,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'e') {
if (s[5].unicode() == 'r') {
if (s[6].unicode() == 't') {
- if (s[7].unicode() == 'y') {
+ if (s[7].unicode() == 'y')
return T_DOXY_PROPERTY;
- }
}
}
}
@@ -1723,9 +1583,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 't') {
if (s[5].unicode() == 'l') {
if (s[6].unicode() == 'i') {
- if (s[7].unicode() == 'b') {
+ if (s[7].unicode() == 'b')
return T_DOXY_QTESTLIB;
- }
}
}
}
@@ -1740,18 +1599,14 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 'o') {
if (s[6].unicode() == 'n') {
- if (s[7].unicode() == '1') {
+ if (s[7].unicode() == '1')
return T_DOXY_SECTION1;
- }
- else if (s[7].unicode() == '2') {
+ else if (s[7].unicode() == '2')
return T_DOXY_SECTION2;
- }
- else if (s[7].unicode() == '3') {
+ else if (s[7].unicode() == '3')
return T_DOXY_SECTION3;
- }
- else if (s[7].unicode() == '4') {
+ else if (s[7].unicode() == '4')
return T_DOXY_SECTION4;
- }
}
}
}
@@ -1764,9 +1619,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'l') {
if (s[5].unicode() == 'i') {
if (s[6].unicode() == 'n') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_SKIPLINE;
- }
}
}
}
@@ -1779,9 +1633,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'l') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_SUBTITLE;
- }
}
}
}
@@ -1796,9 +1649,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 'b') {
if (s[6].unicode() == 'l') {
- if (s[7].unicode() == 'e') {
+ if (s[7].unicode() == 'e')
return T_DOXY_VARIABLE;
- }
}
}
}
@@ -1811,9 +1663,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'a') {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'i') {
- if (s[7].unicode() == 'm') {
+ if (s[7].unicode() == 'm')
return T_DOXY_VERBATIM;
- }
}
}
}
@@ -1828,9 +1679,8 @@ static inline int classify8(const QChar *s) {
if (s[4].unicode() == 'i') {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'e') {
- if (s[7].unicode() == 'm') {
+ if (s[7].unicode() == 'm')
return T_DOXY_XREFITEM;
- }
}
}
}
@@ -1850,9 +1700,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'o') {
- if (s[8].unicode() == 'n') {
+ if (s[8].unicode() == 'n')
return T_DOXY_ATTENTION;
- }
}
}
}
@@ -1869,9 +1718,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'r') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'p') {
- if (s[8].unicode() == 'h') {
+ if (s[8].unicode() == 'h')
return T_DOXY_CALLGRAPH;
- }
}
}
}
@@ -1888,9 +1736,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'o') {
- if (s[8].unicode() == 'n') {
+ if (s[8].unicode() == 'n')
return T_DOXY_EXCEPTION;
- }
}
}
}
@@ -1907,9 +1754,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'p') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'g') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_INDEXPAGE;
- }
}
}
}
@@ -1922,9 +1768,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'f') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'c') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_INTERFACE;
- }
}
}
}
@@ -1937,9 +1782,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'i') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'n') {
- if (s[8].unicode() == 't') {
+ if (s[8].unicode() == 't')
return T_DOXY_INVARIANT;
- }
}
}
}
@@ -1956,9 +1800,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'o') {
if (s[6].unicode() == 'n') {
if (s[7].unicode() == 'l') {
- if (s[8].unicode() == 'y') {
+ if (s[8].unicode() == 'y')
return T_DOXY_LATEXONLY;
- }
}
}
}
@@ -1975,9 +1818,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'l') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 's') {
- if (s[8].unicode() == 's') {
+ if (s[8].unicode() == 's')
return T_DOXY_MAINCLASS;
- }
}
}
}
@@ -1994,9 +1836,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'p') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'c') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_NAMESPACE;
- }
}
}
}
@@ -2013,9 +1854,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'a') {
if (s[6].unicode() == 'l') {
if (s[7].unicode() == 'u') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_OMITVALUE;
- }
}
}
}
@@ -2032,9 +1872,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'r') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'p') {
- if (s[8].unicode() == 'h') {
+ if (s[8].unicode() == 'h')
return T_DOXY_PARAGRAPH;
- }
}
}
}
@@ -2049,9 +1888,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'l') {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'n') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_PRINTLINE;
- }
}
}
}
@@ -2068,9 +1906,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 't') {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'o') {
- if (s[8].unicode() == 'n') {
+ if (s[8].unicode() == 'n')
return T_DOXY_QUOTATION;
- }
}
}
}
@@ -2079,9 +1916,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'f') {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'l') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_QUOTEFILE;
- }
}
}
}
@@ -2098,9 +1934,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'r') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'n') {
- if (s[8].unicode() == 't') {
+ if (s[8].unicode() == 't')
return T_DOXY_REENTRANT;
- }
}
}
}
@@ -2117,9 +1952,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'n') {
if (s[6].unicode() == 't') {
if (s[7].unicode() == 'i') {
- if (s[8].unicode() == 'l') {
+ if (s[8].unicode() == 'l')
return T_DOXY_SKIPUNTIL;
- }
}
}
}
@@ -2134,9 +1968,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'p') {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 'g') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_STARTPAGE;
- }
}
}
}
@@ -2153,9 +1986,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'l') {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'n') {
- if (s[8].unicode() == 'e') {
+ if (s[8].unicode() == 'e')
return T_DOXY_UNDERLINE;
- }
}
}
}
@@ -2172,9 +2004,8 @@ static inline int classify9(const QChar *s) {
if (s[5].unicode() == 'r') {
if (s[6].unicode() == 'o') {
if (s[7].unicode() == 'u') {
- if (s[8].unicode() == 'p') {
+ if (s[8].unicode() == 'p')
return T_DOXY_WEAKGROUP;
- }
}
}
}
@@ -2196,9 +2027,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'r') {
if (s[7].unicode() == 'o') {
if (s[8].unicode() == 'u') {
- if (s[9].unicode() == 'p') {
+ if (s[9].unicode() == 'p')
return T_DOXY_ADDTOGROUP;
- }
}
}
}
@@ -2217,9 +2047,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'a') {
if (s[7].unicode() == 't') {
if (s[8].unicode() == 'e') {
- if (s[9].unicode() == 'd') {
+ if (s[9].unicode() == 'd')
return T_DOXY_DEPRECATED;
- }
}
}
}
@@ -2238,9 +2067,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'p') {
if (s[7].unicode() == 't') {
if (s[8].unicode() == 'e') {
- if (s[9].unicode() == 'r') {
+ if (s[9].unicode() == 'r')
return T_DOXY_ENDCHAPTER;
- }
}
}
}
@@ -2253,9 +2081,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'o') {
if (s[7].unicode() == 'n') {
if (s[8].unicode() == 'l') {
- if (s[9].unicode() == 'y') {
+ if (s[9].unicode() == 'y')
return T_DOXY_ENDMANONLY;
- }
}
}
}
@@ -2268,9 +2095,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'e') {
if (s[7].unicode() == 'b') {
if (s[8].unicode() == 'a') {
- if (s[9].unicode() == 'r') {
+ if (s[9].unicode() == 'r')
return T_DOXY_ENDSIDEBAR;
- }
}
}
}
@@ -2283,9 +2109,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'o') {
if (s[7].unicode() == 'n') {
if (s[8].unicode() == 'l') {
- if (s[9].unicode() == 'y') {
+ if (s[9].unicode() == 'y')
return T_DOXY_ENDXMLONLY;
- }
}
}
}
@@ -2302,9 +2127,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'i') {
if (s[7].unicode() == 'o') {
if (s[8].unicode() == 'n') {
- if (s[9].unicode() == 's') {
+ if (s[9].unicode() == 's')
return T_DOXY_EXCEPTIONS;
- }
}
}
}
@@ -2323,9 +2147,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'f') {
if (s[7].unicode() == 'i') {
if (s[8].unicode() == 'l') {
- if (s[9].unicode() == 'e') {
+ if (s[9].unicode() == 'e')
return T_DOXY_HEADERFILE;
- }
}
}
}
@@ -2344,9 +2167,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'n') {
if (s[7].unicode() == 't') {
if (s[8].unicode() == 'i') {
- if (s[9].unicode() == 'l') {
+ if (s[9].unicode() == 'l')
return T_DOXY_PRINTUNTIL;
- }
}
}
}
@@ -2365,9 +2187,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 'p') {
if (s[7].unicode() == 'o') {
if (s[8].unicode() == 'r') {
- if (s[9].unicode() == 't') {
+ if (s[9].unicode() == 't')
return T_DOXY_QT3SUPPORT;
- }
}
}
}
@@ -2386,9 +2207,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 't') {
if (s[7].unicode() == 'i') {
if (s[8].unicode() == 'o') {
- if (s[9].unicode() == 'n') {
+ if (s[9].unicode() == 'n')
return T_DOXY_SUBSECTION;
- }
}
}
}
@@ -2407,9 +2227,8 @@ static inline int classify10(const QChar *s) {
if (s[6].unicode() == 's') {
if (s[7].unicode() == 'a') {
if (s[8].unicode() == 'f') {
- if (s[9].unicode() == 'e') {
+ if (s[9].unicode() == 'e')
return T_DOXY_THREADSAFE;
- }
}
}
}
@@ -2433,9 +2252,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'l') {
if (s[8].unicode() == 'u') {
if (s[9].unicode() == 'd') {
- if (s[10].unicode() == 'e') {
+ if (s[10].unicode() == 'e')
return T_DOXY_DONTINCLUDE;
- }
}
}
}
@@ -2456,9 +2274,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'r') {
if (s[8].unicode() == 'a') {
if (s[9].unicode() == 'c') {
- if (s[10].unicode() == 't') {
+ if (s[10].unicode() == 't')
return T_DOXY_ENDABSTRACT;
- }
}
}
}
@@ -2473,9 +2290,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'n') {
if (s[8].unicode() == 'o') {
if (s[9].unicode() == 't') {
- if (s[10].unicode() == 'e') {
+ if (s[10].unicode() == 'e')
return T_DOXY_ENDFOOTNOTE;
- }
}
}
}
@@ -2490,9 +2306,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'o') {
if (s[8].unicode() == 'n') {
if (s[9].unicode() == 'l') {
- if (s[10].unicode() == 'y') {
+ if (s[10].unicode() == 'y')
return T_DOXY_ENDHTMLONLY;
- }
}
}
}
@@ -2507,9 +2322,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'l') {
if (s[8].unicode() == 'e') {
if (s[9].unicode() == 's') {
- if (s[10].unicode() == 'e') {
+ if (s[10].unicode() == 'e')
return T_DOXY_ENDLEGALESE;
- }
}
}
}
@@ -2524,18 +2338,14 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'i') {
if (s[8].unicode() == 'o') {
if (s[9].unicode() == 'n') {
- if (s[10].unicode() == '1') {
+ if (s[10].unicode() == '1')
return T_DOXY_ENDSECTION1;
- }
- else if (s[10].unicode() == '2') {
+ else if (s[10].unicode() == '2')
return T_DOXY_ENDSECTION2;
- }
- else if (s[10].unicode() == '3') {
+ else if (s[10].unicode() == '3')
return T_DOXY_ENDSECTION3;
- }
- else if (s[10].unicode() == '4') {
+ else if (s[10].unicode() == '4')
return T_DOXY_ENDSECTION4;
- }
}
}
}
@@ -2550,9 +2360,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'a') {
if (s[8].unicode() == 't') {
if (s[9].unicode() == 'i') {
- if (s[10].unicode() == 'm') {
+ if (s[10].unicode() == 'm')
return T_DOXY_ENDVERBATIM;
- }
}
}
}
@@ -2573,9 +2382,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'r') {
if (s[8].unicode() == 'i') {
if (s[9].unicode() == 't') {
- if (s[10].unicode() == 'y') {
+ if (s[10].unicode() == 'y')
return T_DOXY_GRANULARITY;
- }
}
}
}
@@ -2596,9 +2404,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'l') {
if (s[8].unicode() == 'u') {
if (s[9].unicode() == 'd') {
- if (s[10].unicode() == 'e') {
+ if (s[10].unicode() == 'e')
return T_DOXY_HTMLINCLUDE;
- }
}
}
}
@@ -2619,9 +2426,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'm') {
if (s[8].unicode() == 'a') {
if (s[9].unicode() == 'g') {
- if (s[10].unicode() == 'e') {
+ if (s[10].unicode() == 'e')
return T_DOXY_INLINEIMAGE;
- }
}
}
}
@@ -2642,9 +2448,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'n') {
if (s[8].unicode() == 'a') {
if (s[9].unicode() == 'r') {
- if (s[10].unicode() == 'y') {
+ if (s[10].unicode() == 'y')
return T_DOXY_PRELIMINARY;
- }
}
}
}
@@ -2665,9 +2470,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'a') {
if (s[8].unicode() == 'l') {
if (s[9].unicode() == 's') {
- if (s[10].unicode() == 'o') {
+ if (s[10].unicode() == 'o')
return T_DOXY_RELATESALSO;
- }
}
}
}
@@ -2688,9 +2492,8 @@ static inline int classify11(const QChar *s) {
if (s[7].unicode() == 'l') {
if (s[8].unicode() == 'u') {
if (s[9].unicode() == 'd') {
- if (s[10].unicode() == 'e') {
+ if (s[10].unicode() == 'e')
return T_DOXY_VERBINCLUDE;
- }
}
}
}
@@ -2716,9 +2519,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'p') {
if (s[9].unicode() == 'a') {
if (s[10].unicode() == 'g') {
- if (s[11].unicode() == 'e') {
+ if (s[11].unicode() == 'e')
return T_DOXY_CONTENTSPAGE;
- }
}
}
}
@@ -2741,9 +2543,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'o') {
if (s[9].unicode() == 'n') {
if (s[10].unicode() == 'l') {
- if (s[11].unicode() == 'y') {
+ if (s[11].unicode() == 'y')
return T_DOXY_ENDLATEXONLY;
- }
}
}
}
@@ -2760,9 +2561,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 't') {
if (s[9].unicode() == 'i') {
if (s[10].unicode() == 'o') {
- if (s[11].unicode() == 'n') {
+ if (s[11].unicode() == 'n')
return T_DOXY_ENDQUOTATION;
- }
}
}
}
@@ -2783,9 +2583,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'p') {
if (s[9].unicode() == 'a') {
if (s[10].unicode() == 'g') {
- if (s[11].unicode() == 'e') {
+ if (s[11].unicode() == 'e')
return T_DOXY_EXTERNALPAGE;
- }
}
}
}
@@ -2808,9 +2607,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'l') {
if (s[9].unicode() == 'i') {
if (s[10].unicode() == 's') {
- if (s[11].unicode() == 't') {
+ if (s[11].unicode() == 't')
return T_DOXY_GENERATELIST;
- }
}
}
}
@@ -2833,9 +2631,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'f') {
if (s[9].unicode() == 'i') {
if (s[10].unicode() == 'l') {
- if (s[11].unicode() == 'e') {
+ if (s[11].unicode() == 'e')
return T_DOXY_INHEADERFILE;
- }
}
}
}
@@ -2858,9 +2655,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'r') {
if (s[9].unicode() == 'a') {
if (s[10].unicode() == 'n') {
- if (s[11].unicode() == 't') {
+ if (s[11].unicode() == 't')
return T_DOXY_NONREENTRANT;
- }
}
}
}
@@ -2883,9 +2679,8 @@ static inline int classify12(const QChar *s) {
if (s[8].unicode() == 'p') {
if (s[9].unicode() == 'a') {
if (s[10].unicode() == 'g') {
- if (s[11].unicode() == 'e') {
+ if (s[11].unicode() == 'e')
return T_DOXY_PREVIOUSPAGE;
- }
}
}
}
@@ -2913,9 +2708,8 @@ static inline int classify13(const QChar *s) {
if (s[9].unicode() == 'r') {
if (s[10].unicode() == 'o') {
if (s[11].unicode() == 'u') {
- if (s[12].unicode() == 'p') {
+ if (s[12].unicode() == 'p')
return T_DOXY_INPUBLICGROUP;
- }
}
}
}
@@ -2940,9 +2734,8 @@ static inline int classify13(const QChar *s) {
if (s[9].unicode() == 'p') {
if (s[10].unicode() == 'i') {
if (s[11].unicode() == 'n') {
- if (s[12].unicode() == 'g') {
+ if (s[12].unicode() == 'g')
return T_DOXY_NOSUBGROUPING;
- }
}
}
}
@@ -2967,9 +2760,8 @@ static inline int classify13(const QChar *s) {
if (s[9].unicode() == 'f') {
if (s[10].unicode() == 'i') {
if (s[11].unicode() == 'l') {
- if (s[12].unicode() == 'e') {
+ if (s[12].unicode() == 'e')
return T_DOXY_QUOTEFROMFILE;
- }
}
}
}
@@ -2982,9 +2774,8 @@ static inline int classify13(const QChar *s) {
if (s[9].unicode() == 't') {
if (s[10].unicode() == 'i') {
if (s[11].unicode() == 'o') {
- if (s[12].unicode() == 'n') {
+ if (s[12].unicode() == 'n')
return T_DOXY_QUOTEFUNCTION;
- }
}
}
}
@@ -3009,9 +2800,8 @@ static inline int classify13(const QChar *s) {
if (s[9].unicode() == 't') {
if (s[10].unicode() == 'i') {
if (s[11].unicode() == 'o') {
- if (s[12].unicode() == 'n') {
+ if (s[12].unicode() == 'n')
return T_DOXY_SUBSUBSECTION;
- }
}
}
}
@@ -3042,9 +2832,8 @@ static inline int classify15(const QChar *s) {
if (s[11].unicode() == 'i') {
if (s[12].unicode() == 'z') {
if (s[13].unicode() == 'e') {
- if (s[14].unicode() == 'r') {
+ if (s[14].unicode() == 'r')
return T_DOXY_HIDEINITIALIZER;
- }
}
}
}
@@ -3073,9 +2862,8 @@ static inline int classify15(const QChar *s) {
if (s[11].unicode() == 'i') {
if (s[12].unicode() == 'z') {
if (s[13].unicode() == 'e') {
- if (s[14].unicode() == 'r') {
+ if (s[14].unicode() == 'r')
return T_DOXY_SHOWINITIALIZER;
- }
}
}
}
@@ -3104,9 +2892,8 @@ static inline int classify15(const QChar *s) {
if (s[11].unicode() == 'e') {
if (s[12].unicode() == 'n') {
if (s[13].unicode() == 't') {
- if (s[14].unicode() == 's') {
+ if (s[14].unicode() == 's')
return T_DOXY_TABLEOFCONTENTS;
- }
}
}
}
diff --git a/src/plugins/cpptools/cppfilesettingspage.cpp b/src/plugins/cpptools/cppfilesettingspage.cpp
index 01a168e379..66eff6cbce 100644
--- a/src/plugins/cpptools/cppfilesettingspage.cpp
+++ b/src/plugins/cpptools/cppfilesettingspage.cpp
@@ -38,6 +38,7 @@
#include <extensionsystem/pluginmanager.h>
+#include <utils/environment.h>
#include <utils/fileutils.h>
#include <QSettings>
@@ -149,11 +150,7 @@ static bool keyWordReplacement(const QString &keyWord,
return true;
}
if (keyWord == QLatin1String("%USER%")) {
-#ifdef Q_OS_WIN
- *value = QString::fromLocal8Bit(qgetenv("USERNAME"));
-#else
- *value = QString::fromLocal8Bit(qgetenv("USER"));
-#endif
+ *value = Utils::Environment::systemEnvironment().userName();
return true;
}
// Environment variables (for example '%$EMAIL%').
@@ -322,9 +319,9 @@ CppFileSettingsPage::CppFileSettingsPage(QSharedPointer<CppFileSettings> &settin
Core::IOptionsPage(parent),
m_settings(settings)
{
- setId(QLatin1String(Constants::CPP_FILE_SETTINGS_ID));
+ setId(Constants::CPP_FILE_SETTINGS_ID);
setDisplayName(QCoreApplication::translate("CppTools", Constants::CPP_FILE_SETTINGS_NAME));
- setCategory(QLatin1String(Constants::CPP_SETTINGS_CATEGORY));
+ setCategory(Constants::CPP_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("CppTools", Constants::CPP_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CPP_ICON));
}
diff --git a/src/plugins/cpptools/cppfindreferences.cpp b/src/plugins/cpptools/cppfindreferences.cpp
index 56edd5dd7a..7fe6aed53d 100644
--- a/src/plugins/cpptools/cppfindreferences.cpp
+++ b/src/plugins/cpptools/cppfindreferences.cpp
@@ -250,13 +250,13 @@ void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol,
Overview overview;
Find::SearchResult *search = Find::SearchResultWindow::instance()->startNewSearch(tr("C++ Usages:"),
QString(),
- overview(context.fullyQualifiedName(symbol)),
+ overview.prettyName(context.fullyQualifiedName(symbol)),
replace ? Find::SearchResultWindow::SearchAndReplace
: Find::SearchResultWindow::SearchOnly,
QLatin1String("CppEditor"));
search->setTextToReplace(replacement);
- connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
- SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>)));
+ connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)),
+ SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)));
connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
search->setSearchAgainSupported(true);
connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
@@ -297,15 +297,16 @@ void CppFindReferences::findAll_helper(Find::SearchResult *search)
Core::ProgressManager *progressManager = Core::ICore::progressManager();
Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
- CppTools::Constants::TASK_SEARCH);
+ QLatin1String(CppTools::Constants::TASK_SEARCH));
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
void CppFindReferences::onReplaceButtonClicked(const QString &text,
- const QList<Find::SearchResultItem> &items)
+ const QList<Find::SearchResultItem> &items,
+ bool preserveCase)
{
- const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items);
+ const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items, preserveCase);
if (!fileNames.isEmpty()) {
_modelManager->updateSourceFiles(fileNames);
Find::SearchResultWindow::instance()->hide();
@@ -410,7 +411,7 @@ namespace {
class SymbolFinder : public SymbolVisitor
{
public:
- SymbolFinder(const QStringList &uid) : m_uid(uid), m_index(0), m_result(0) { }
+ SymbolFinder(const QList<QByteArray> &uid) : m_uid(uid), m_index(0), m_result(0) { }
Symbol *result() const { return m_result; }
bool preVisit(Symbol *symbol)
@@ -439,7 +440,7 @@ public:
}
private:
- QStringList m_uid;
+ QList<QByteArray> m_uid;
int m_index;
Symbol *m_result;
};
@@ -449,9 +450,8 @@ bool CppFindReferences::findSymbol(CppFindReferencesParameters *parameters,
const Snapshot &snapshot)
{
QString symbolFile = QLatin1String(parameters->symbol->fileName());
- if (!snapshot.contains(symbolFile)) {
+ if (!snapshot.contains(symbolFile))
return false;
- }
Document::Ptr newSymbolDocument = snapshot.document(symbolFile);
// document is not parsed and has no bindings yet, do it
@@ -461,7 +461,7 @@ bool CppFindReferences::findSymbol(CppFindReferencesParameters *parameters,
doc->check();
// construct id of old symbol
- QStringList uid;
+ QList<QByteArray> uid;
Symbol *current = parameters->symbol;
do {
uid.prepend(idForSymbol(current));
@@ -573,22 +573,21 @@ _Lrestart:
const Macro &useMacro = use.macro();
if (useMacro.fileName() == macro.fileName()) { // Check if this is a match, but possibly against an outdated document.
+ if (source.isEmpty())
+ source = getSource(fileName, workingCopy);
+
if (macro.fileRevision() > useMacro.fileRevision()) {
// yes, it is outdated, so re-preprocess and start from scratch for this file.
- source = getSource(fileName, workingCopy).toLatin1();
doc = snapshot.preprocessedDocument(source, fileName);
goto _Lrestart;
}
- }
- if (useMacro.fileName() == macro.fileName() && macro.name() == useMacro.name()) {
- if (source.isEmpty())
- source = getSource(fileName, workingCopy);
-
- unsigned lineStart;
- const QString &lineSource = matchingLine(use.begin(), source, &lineStart);
- usages.append(Usage(fileName, lineSource, use.beginLine(),
- use.begin() - lineStart, useMacro.name().length()));
+ if (macro.name() == useMacro.name()) {
+ unsigned lineStart;
+ const QString &lineSource = matchingLine(use.begin(), source, &lineStart);
+ usages.append(Usage(fileName, lineSource, use.beginLine(),
+ use.begin() - lineStart, useMacro.name().length()));
+ }
}
}
@@ -650,7 +649,7 @@ void CppFindReferences::findMacroUses(const Macro &macro, const QString &replace
Find::SearchResult *search = Find::SearchResultWindow::instance()->startNewSearch(
tr("C++ Macro Usages:"),
QString(),
- macro.name(),
+ QString::fromUtf8(macro.name()),
replace ? Find::SearchResultWindow::SearchAndReplace
: Find::SearchResultWindow::SearchOnly,
QLatin1String("CppEditor"));
@@ -684,13 +683,13 @@ void CppFindReferences::findMacroUses(const Macro &macro, const QString &replace
Core::ProgressManager *progressManager = Core::ICore::progressManager();
Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
- CppTools::Constants::TASK_SEARCH);
+ QLatin1String(CppTools::Constants::TASK_SEARCH));
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
void CppFindReferences::renameMacroUses(const Macro &macro, const QString &replacement)
{
- const QString textToReplace = replacement.isEmpty() ? macro.name() : replacement;
+ const QString textToReplace = replacement.isEmpty() ? QString::fromUtf8(macro.name()) : replacement;
findMacroUses(macro, textToReplace, true);
}
diff --git a/src/plugins/cpptools/cppfindreferences.h b/src/plugins/cpptools/cppfindreferences.h
index 9adaa3ab5a..13b1b6f3fb 100644
--- a/src/plugins/cpptools/cppfindreferences.h
+++ b/src/plugins/cpptools/cppfindreferences.h
@@ -89,7 +89,7 @@ private Q_SLOTS:
void cancel();
void setPaused(bool paused);
void openEditor(const Find::SearchResultItem &item);
- void onReplaceButtonClicked(const QString &text, const QList<Find::SearchResultItem> &items);
+ void onReplaceButtonClicked(const QString &text, const QList<Find::SearchResultItem> &items, bool preserveCase);
void searchAgain();
private:
diff --git a/src/plugins/cpptools/cppfunctionsfilter.cpp b/src/plugins/cpptools/cppfunctionsfilter.cpp
index 9fa2177fb5..670276d463 100644
--- a/src/plugins/cpptools/cppfunctionsfilter.cpp
+++ b/src/plugins/cpptools/cppfunctionsfilter.cpp
@@ -34,10 +34,12 @@ using namespace CppTools::Internal;
CppFunctionsFilter::CppFunctionsFilter(CppModelManager *manager)
: CppLocatorFilter(manager)
{
+ setId("Methods");
+ setDisplayName(tr("C++ Methods and Functions"));
setShortcutString(QString(QLatin1Char('m')));
setIncludedByDefault(false);
- search.setSymbolsToSearchFor(SearchSymbols::Functions);
+ search.setSymbolsToSearchFor(SymbolSearcher::Functions);
search.setSeparateScope(true);
}
diff --git a/src/plugins/cpptools/cppfunctionsfilter.h b/src/plugins/cpptools/cppfunctionsfilter.h
index 9119d38a6f..9d67ef2543 100644
--- a/src/plugins/cpptools/cppfunctionsfilter.h
+++ b/src/plugins/cpptools/cppfunctionsfilter.h
@@ -30,7 +30,7 @@
#ifndef CPPFUNCTIONSFILTER_H
#define CPPFUNCTIONSFILTER_H
-#include <cpplocatorfilter.h>
+#include "cpplocatorfilter.h"
namespace CppTools {
namespace Internal {
@@ -42,10 +42,6 @@ class CppFunctionsFilter : public CppLocatorFilter
public:
CppFunctionsFilter(CppModelManager *manager);
~CppFunctionsFilter();
-
- QString displayName() const { return tr("Methods and Functions"); }
- QString id() const { return QLatin1String("Methods"); }
- Priority priority() const { return Medium; }
};
} // namespace Internal
diff --git a/src/plugins/cpptools/cpphighlightingsupportinternal.cpp b/src/plugins/cpptools/cpphighlightingsupportinternal.cpp
index 1cc128d78f..e20c0a9a2f 100644
--- a/src/plugins/cpptools/cpphighlightingsupportinternal.cpp
+++ b/src/plugins/cpptools/cpphighlightingsupportinternal.cpp
@@ -53,8 +53,18 @@ QFuture<CppHighlightingSupport::Use> CppHighlightingSupportInternal::highlightin
const Document::Ptr &doc,
const Snapshot &snapshot) const
{
- //Get macro uses
QList<CheckSymbols::Use> macroUses;
+
+ //Get macro definitions
+ foreach (const CPlusPlus::Macro& macro, doc->definedMacros()) {
+ int line, column;
+ editor()->convertPosition(macro.offset(), &line, &column);
+ ++column; //Highlighting starts at (column-1) --> compensate here
+ CheckSymbols::Use use(line, column, macro.name().size(), SemanticInfo::MacroUse);
+ macroUses.append(use);
+ }
+
+ //Get macro uses
foreach (Document::MacroUse macro, doc->macroUses()) {
const QString name = QString::fromUtf8(macro.macro().name());
diff --git a/src/plugins/cpptools/cppindexingsupport.cpp b/src/plugins/cpptools/cppindexingsupport.cpp
new file mode 100644
index 0000000000..e7d118d283
--- /dev/null
+++ b/src/plugins/cpptools/cppindexingsupport.cpp
@@ -0,0 +1,47 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+
+#include "cppindexingsupport.h"
+
+namespace CppTools {
+
+CppIndexingSupport::~CppIndexingSupport()
+{
+}
+
+SymbolSearcher::SymbolSearcher(QObject *parent)
+ : QObject(parent)
+{
+}
+
+SymbolSearcher::~SymbolSearcher()
+{}
+
+} // namespace CppTools
diff --git a/src/plugins/remotelinux/deploymentsettingsassistant.h b/src/plugins/cpptools/cppindexingsupport.h
index d783295dd2..d6cf2121fc 100644
--- a/src/plugins/remotelinux/deploymentsettingsassistant.h
+++ b/src/plugins/cpptools/cppindexingsupport.h
@@ -26,44 +26,68 @@
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
-#ifndef DEPLOYMENTSETTINGSASSISTANT_H
-#define DEPLOYMENTSETTINGSASSISTANT_H
-#include "remotelinux_export.h"
+#ifndef CPPTOOLS_CPPINDEXINGSUPPORT_H
+#define CPPTOOLS_CPPINDEXINGSUPPORT_H
-#include <QObject>
-#include <QStringList>
+#include "cpptools_global.h"
-namespace ProjectExplorer { class Project; }
+#include <find/searchresultwindow.h>
+#include <find/textfindconstants.h>
-namespace RemoteLinux {
-class DeployableFile;
-class DeployableFilesPerProFile;
-class DeploymentInfo;
+#include <QFuture>
+#include <QStringList>
-namespace Internal { class DeploymentSettingsAssistantInternal; }
+namespace CppTools {
-class REMOTELINUX_EXPORT DeploymentSettingsAssistant : public QObject
+class CPPTOOLS_EXPORT SymbolSearcher: public QObject
{
Q_OBJECT
public:
- DeploymentSettingsAssistant(DeploymentInfo *deploymentInfo, ProjectExplorer::Project *parent);
- ~DeploymentSettingsAssistant();
+ enum SymbolType {
+ Classes = 0x1,
+ Functions = 0x2,
+ Enums = 0x4,
+ Declarations = 0x8
+ };
+
+ Q_DECLARE_FLAGS(SymbolTypes, SymbolType)
- bool addDeployableToProFile(const QString &qmakeScope,
- const DeployableFilesPerProFile *proFileInfo,
- const QString &variableName, const DeployableFile &deployable);
+ enum SearchScope {
+ SearchProjectsOnly,
+ SearchGlobal
+ };
-private slots:
- void handleDeploymentInfoUpdated();
+ struct Parameters
+ {
+ QString text;
+ Find::FindFlags flags;
+ SymbolTypes types;
+ SearchScope scope;
+ };
-private:
- bool addLinesToProFile(const QString &qmakeScope, const DeployableFilesPerProFile *proFileInfo, const QStringList &lines);
- Internal::DeploymentSettingsAssistantInternal * const d;
+public:
+ SymbolSearcher(QObject *parent = 0);
+ virtual ~SymbolSearcher() = 0;
+ virtual void runSearch(QFutureInterface<Find::SearchResultItem> &future) = 0;
};
-} // namespace RemoteLinux
-#endif // DEPLOYMENTSETTINGSASSISTANT_H
+class CPPTOOLS_EXPORT CppIndexingSupport
+{
+public:
+ virtual ~CppIndexingSupport() = 0;
+
+ virtual QFuture<void> refreshSourceFiles(const QStringList &sourceFiles) = 0;
+ virtual SymbolSearcher *createSymbolSearcher(SymbolSearcher::Parameters parameters, QSet<QString> fileNames) = 0;
+};
+
+} // namespace CppTools
+
+Q_DECLARE_METATYPE(CppTools::SymbolSearcher::SearchScope)
+Q_DECLARE_METATYPE(CppTools::SymbolSearcher::Parameters)
+Q_DECLARE_METATYPE(CppTools::SymbolSearcher::SymbolTypes)
+
+#endif // CPPTOOLS_CPPINDEXINGSUPPORT_H
diff --git a/src/plugins/cpptools/cpplocalsymbols.cpp b/src/plugins/cpptools/cpplocalsymbols.cpp
index 682cc6ab14..18b1ce5974 100644
--- a/src/plugins/cpptools/cpplocalsymbols.cpp
+++ b/src/plugins/cpptools/cpplocalsymbols.cpp
@@ -127,6 +127,11 @@ protected:
return true;
}
+ virtual bool visit(CaptureAST *ast)
+ {
+ return checkLocalUse(ast->identifier, ast->firstToken());
+ }
+
virtual bool visit(IdExpressionAST *ast)
{
return checkLocalUse(ast->name, ast->firstToken());
diff --git a/src/plugins/cpptools/cpplocatorfilter.cpp b/src/plugins/cpptools/cpplocatorfilter.cpp
index 2ecb3df87d..b9631bc680 100644
--- a/src/plugins/cpptools/cpplocatorfilter.cpp
+++ b/src/plugins/cpptools/cpplocatorfilter.cpp
@@ -32,15 +32,19 @@
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
+#include <utils/fileutils.h>
#include <QStringMatcher>
using namespace CppTools::Internal;
+using namespace Utils;
CppLocatorFilter::CppLocatorFilter(CppModelManager *manager)
: m_manager(manager),
m_forceNewSearchList(true)
{
+ setId("Classes and Methods");
+ setDisplayName(tr("C++ Classes and Methods"));
setShortcutString(QString(QLatin1Char(':')));
setIncludedByDefault(false);
@@ -86,7 +90,7 @@ QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locato
QRegExp regexp(asterisk + entry+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
return goodEntries;
- bool hasWildcard = (entry.contains(asterisk) || entry.contains('?'));
+ bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?')));
QHashIterator<QString, QList<ModelItemInfo> > it(m_searchList);
while (it.hasNext()) {
@@ -102,10 +106,12 @@ QList<Locator::FilterEntry> CppLocatorFilter::matchesFor(QFutureInterface<Locato
QVariant id = qVariantFromValue(info);
Locator::FilterEntry filterEntry(this, info.symbolName, id, info.icon);
- if (! info.symbolType.isEmpty())
+ if (! info.symbolType.isEmpty()) {
filterEntry.extraInfo = info.symbolType;
- else
- filterEntry.extraInfo = info.fileName;
+ } else {
+ filterEntry.extraInfo = FileUtils::shortNativePath(
+ FileName::fromString(info.fileName));
+ }
if (info.symbolName.startsWith(entry))
betterEntries.append(filterEntry);
diff --git a/src/plugins/cpptools/cpplocatorfilter.h b/src/plugins/cpptools/cpplocatorfilter.h
index 140fd70845..82ec145871 100644
--- a/src/plugins/cpptools/cpplocatorfilter.h
+++ b/src/plugins/cpptools/cpplocatorfilter.h
@@ -41,13 +41,11 @@ class CppModelManager;
class CppLocatorFilter : public Locator::ILocatorFilter
{
Q_OBJECT
+
public:
CppLocatorFilter(CppModelManager *manager);
~CppLocatorFilter();
- QString displayName() const { return tr("Classes and Methods"); }
- QString id() const { return QLatin1String("Classes and Methods"); }
- Priority priority() const { return Medium; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/cpptools/cppmodelmanager.cpp b/src/plugins/cpptools/cppmodelmanager.cpp
index 032e358a5e..a86686f9ed 100644
--- a/src/plugins/cpptools/cppmodelmanager.cpp
+++ b/src/plugins/cpptools/cppmodelmanager.cpp
@@ -30,37 +30,34 @@
#include <cplusplus/pp.h>
#include <cplusplus/Overview.h>
+#include "builtinindexingsupport.h"
#include "cppmodelmanager.h"
#include "cppcompletionassist.h"
#include "cpphighlightingsupport.h"
#include "cpphighlightingsupportinternal.h"
+#include "cppindexingsupport.h"
#include "abstracteditorsupport.h"
-#ifndef ICHECK_BUILD
-# include "cpptoolsconstants.h"
-# include "cpptoolseditorsupport.h"
-# include "cppfindreferences.h"
-#endif
+#include "cpptoolsconstants.h"
+#include "cpptoolseditorsupport.h"
+#include "cppfindreferences.h"
#include <functional>
#include <QtConcurrentRun>
-#ifndef ICHECK_BUILD
-# include <QFutureSynchronizer>
-# include <utils/runextensions.h>
-# include <texteditor/itexteditor.h>
-# include <texteditor/basetexteditor.h>
-# include <projectexplorer/project.h>
-# include <projectexplorer/projectexplorer.h>
-# include <projectexplorer/projectexplorerconstants.h>
-# include <projectexplorer/session.h>
-# include <coreplugin/icore.h>
-# include <coreplugin/mimedatabase.h>
-# include <coreplugin/editormanager/editormanager.h>
-# include <coreplugin/progressmanager/progressmanager.h>
-# include <extensionsystem/pluginmanager.h>
-#else
-# include <QDir>
-#endif
-
+#include <QFutureSynchronizer>
+#include <utils/runextensions.h>
+#include <texteditor/itexteditor.h>
+#include <texteditor/basetexteditor.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/session.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/progressmanager/progressmanager.h>
+#include <extensionsystem/pluginmanager.h>
+
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <TranslationUnit.h>
@@ -91,9 +88,10 @@
#include <sstream>
namespace CPlusPlus {
+
uint qHash(const CppModelManagerInterface::ProjectPart &p)
{
- uint h = qHash(p.defines) ^ p.language ^ ((int) p.cxx11Enabled);
+ uint h = qHash(p.defines) ^ p.language ^ p.qtVersion;
foreach (const QString &i, p.includePaths)
h ^= qHash(i);
@@ -103,6 +101,7 @@ uint qHash(const CppModelManagerInterface::ProjectPart &p)
return h;
}
+
bool operator==(const CppModelManagerInterface::ProjectPart &p1,
const CppModelManagerInterface::ProjectPart &p2)
{
@@ -110,12 +109,13 @@ bool operator==(const CppModelManagerInterface::ProjectPart &p1,
return false;
if (p1.language != p2.language)
return false;
- if (p1.cxx11Enabled != p2.cxx11Enabled)
+ if (p1.qtVersion!= p2.qtVersion)
return false;
if (p1.includePaths != p2.includePaths)
return false;
return p1.frameworkPaths == p2.frameworkPaths;
}
+
} // namespace CPlusPlus
using namespace CppTools;
@@ -164,8 +164,6 @@ protected:
#endif // QTCREATOR_WITH_DUMP_AST
-static const char pp_configuration_file[] = "<configuration>";
-
static const char pp_configuration[] =
"# 1 \"<configuration>\"\n"
"#define __cplusplus 1\n"
@@ -197,26 +195,15 @@ static const char pp_configuration[] =
"#define __inline inline\n"
"#define __forceinline inline\n";
-#ifndef ICHECK_BUILD
CppPreprocessor::CppPreprocessor(QPointer<CppModelManager> modelManager, bool dumpFileNameWhileParsing)
- : snapshot(modelManager->snapshot()),
+ : m_snapshot(modelManager->snapshot()),
m_modelManager(modelManager),
m_dumpFileNameWhileParsing(dumpFileNameWhileParsing),
- preprocess(this, &env),
- m_revision(0)
-{
- preprocess.setKeepComments(true);
-}
-
-#else
-
-CppPreprocessor::CppPreprocessor(QPointer<CPlusPlus::ParseManager> modelManager)
- : preprocess(this, &env),
- m_dumpFileNameWhileParsing(false),
+ m_preprocess(this, &m_env),
m_revision(0)
{
+ m_preprocess.setKeepComments(true);
}
-#endif
CppPreprocessor::~CppPreprocessor()
{ }
@@ -234,23 +221,21 @@ void CppPreprocessor::setIncludePaths(const QStringList &includePaths)
for (int i = 0; i < includePaths.size(); ++i) {
const QString &path = includePaths.at(i);
-#ifdef Q_OS_DARWIN
- if (i + 1 < includePaths.size() && path.endsWith(QLatin1String(".framework/Headers"))) {
- const QFileInfo pathInfo(path);
- const QFileInfo frameworkFileInfo(pathInfo.path());
- const QString frameworkName = frameworkFileInfo.baseName();
-
- const QFileInfo nextIncludePath = includePaths.at(i + 1);
- if (nextIncludePath.fileName() == frameworkName) {
- // We got a QtXXX.framework/Headers followed by $QTDIR/include/QtXXX.
- // In this case we prefer to include files from $QTDIR/include/QtXXX.
- continue;
+ if (Utils::HostOsInfo::isMacHost()) {
+ if (i + 1 < includePaths.size() && path.endsWith(QLatin1String(".framework/Headers"))) {
+ const QFileInfo pathInfo(path);
+ const QFileInfo frameworkFileInfo(pathInfo.path());
+ const QString frameworkName = frameworkFileInfo.baseName();
+
+ const QFileInfo nextIncludePath = includePaths.at(i + 1);
+ if (nextIncludePath.fileName() == frameworkName) {
+ // We got a QtXXX.framework/Headers followed by $QTDIR/include/QtXXX.
+ // In this case we prefer to include files from $QTDIR/include/QtXXX.
+ continue;
+ }
}
}
- m_includePaths.append(path);
-#else
- m_includePaths.append(path);
-#endif
+ m_includePaths.append(cleanPath(path));
}
}
@@ -275,19 +260,18 @@ void CppPreprocessor::addFrameworkPath(const QString &frameworkPath)
// The algorithm below is a bit too eager, but that's because we're not getting
// in the frameworks we're linking against. If we would have that, then we could
// add only those private frameworks.
- if (!m_frameworkPaths.contains(frameworkPath)) {
- m_frameworkPaths.append(frameworkPath);
- }
+ QString cleanFrameworkPath = cleanPath(frameworkPath);
+ if (!m_frameworkPaths.contains(cleanFrameworkPath))
+ m_frameworkPaths.append(cleanFrameworkPath);
- const QDir frameworkDir(frameworkPath);
+ const QDir frameworkDir(cleanFrameworkPath);
const QStringList filter = QStringList() << QLatin1String("*.framework");
foreach (const QFileInfo &framework, frameworkDir.entryInfoList(filter)) {
if (!framework.isDir())
continue;
const QFileInfo privateFrameworks(framework.absoluteFilePath(), QLatin1String("Frameworks"));
- if (privateFrameworks.exists() && privateFrameworks.isDir()) {
+ if (privateFrameworks.exists() && privateFrameworks.isDir())
addFrameworkPath(privateFrameworks.absoluteFilePath());
- }
}
}
@@ -297,7 +281,6 @@ void CppPreprocessor::setProjectFiles(const QStringList &files)
void CppPreprocessor::setTodo(const QStringList &files)
{ m_todo = QSet<QString>::fromList(files); }
-#ifndef ICHECK_BUILD
namespace {
class Process: public std::unary_function<Document::Ptr, void>
{
@@ -326,13 +309,12 @@ public:
_doc->check(_mode);
if (_modelManager)
- _modelManager->emitDocumentUpdated(_doc); // ### TODO: compress
+ _modelManager->emitDocumentUpdated(_doc);
_doc->releaseSourceAndAST();
}
};
} // end of anonymous namespace
-#endif
void CppPreprocessor::run(const QString &fileName)
{
@@ -342,7 +324,7 @@ void CppPreprocessor::run(const QString &fileName)
void CppPreprocessor::resetEnvironment()
{
- env.reset();
+ m_env.reset();
m_processed.clear();
}
@@ -391,25 +373,30 @@ QString CppPreprocessor::tryIncludeFile(QString &fileName, IncludeType type, uns
return QString();
}
- }
- const QString originalFileName = fileName;
- const QString contents = tryIncludeFile_helper(fileName, type, revision);
- if (type == IncludeGlobal)
+ const QString originalFileName = fileName;
+ const QString contents = tryIncludeFile_helper(fileName, type, revision);
m_fileNameCache.insert(originalFileName, fileName);
- return contents;
+ return contents;
+ }
+
+ // IncludeLocal, IncludeNext
+ return tryIncludeFile_helper(fileName, type, revision);
}
-static inline void appendDirSeparatorIfNeeded(QString &path)
+QString CppPreprocessor::cleanPath(const QString &path)
{
- if (!path.endsWith(QLatin1Char('/'), Qt::CaseInsensitive))
- path += QLatin1Char('/');
+ QString result = QDir::cleanPath(path);
+ const QChar slash(QLatin1Char('/'));
+ if (!result.endsWith(slash))
+ result.append(slash);
+ return result;
}
QString CppPreprocessor::tryIncludeFile_helper(QString &fileName, IncludeType type, unsigned *revision)
{
QFileInfo fileInfo(fileName);
- if (fileName == QLatin1String(pp_configuration_file) || fileInfo.isAbsolute()) {
+ if (fileName == Preprocessor::configurationFileName || fileInfo.isAbsolute()) {
QString contents;
includeFile(fileName, &contents, revision);
return contents;
@@ -417,10 +404,7 @@ QString CppPreprocessor::tryIncludeFile_helper(QString &fileName, IncludeType ty
if (type == IncludeLocal && m_currentDoc) {
QFileInfo currentFileInfo(m_currentDoc->fileName());
- QString path = currentFileInfo.absolutePath();
- appendDirSeparatorIfNeeded(path);
- path += fileName;
- path = QDir::cleanPath(path);
+ QString path = cleanPath(currentFileInfo.absolutePath()) + fileName;
QString contents;
if (includeFile(path, &contents, revision)) {
fileName = path;
@@ -429,23 +413,7 @@ QString CppPreprocessor::tryIncludeFile_helper(QString &fileName, IncludeType ty
}
foreach (const QString &includePath, m_includePaths) {
- QString path = includePath;
- appendDirSeparatorIfNeeded(path);
- path += fileName;
- path = QDir::cleanPath(path);
- QString contents;
- if (includeFile(path, &contents, revision)) {
- fileName = path;
- return contents;
- }
- }
-
- // look in the system include paths
- foreach (const QString &includePath, m_systemIncludePaths) {
- QString path = includePath;
- appendDirSeparatorIfNeeded(path);
- path += fileName;
- path = QDir::cleanPath(path);
+ QString path = includePath + fileName;
QString contents;
if (includeFile(path, &contents, revision)) {
fileName = path;
@@ -456,15 +424,10 @@ QString CppPreprocessor::tryIncludeFile_helper(QString &fileName, IncludeType ty
int index = fileName.indexOf(QLatin1Char('/'));
if (index != -1) {
QString frameworkName = fileName.left(index);
- QString name = fileName.mid(index + 1);
+ QString name = frameworkName + QLatin1String(".framework/Headers/") + fileName.mid(index + 1);
foreach (const QString &frameworkPath, m_frameworkPaths) {
- QString path = frameworkPath;
- appendDirSeparatorIfNeeded(path);
- path += frameworkName;
- path += QLatin1String(".framework/Headers/");
- path += name;
- path = QDir::cleanPath(path);
+ QString path = frameworkPath + name;
QString contents;
if (includeFile(path, &contents, revision)) {
fileName = path;
@@ -473,19 +436,6 @@ QString CppPreprocessor::tryIncludeFile_helper(QString &fileName, IncludeType ty
}
}
- QString path = fileName;
- if (path.at(0) != QLatin1Char('/'))
- path.prepend(QLatin1Char('/'));
-
- foreach (const QString &projectFile, m_projectFiles) {
- if (projectFile.endsWith(path)) {
- fileName = projectFile;
- QString contents;
- includeFile(fileName, &contents, revision);
- return contents;
- }
- }
-
//qDebug() << "**** file" << fileName << "not found!";
return QString();
}
@@ -549,6 +499,14 @@ void CppPreprocessor::stopExpandingMacro(unsigned, const Macro &)
//qDebug() << "stop expanding:" << macro.name;
}
+void CppPreprocessor::markAsIncludeGuard(const QByteArray &macroName)
+{
+ if (!m_currentDoc)
+ return;
+
+ m_currentDoc->setIncludeGuardMacroName(macroName);
+}
+
void CppPreprocessor::mergeEnvironment(Document::Ptr doc)
{
if (! doc)
@@ -564,13 +522,13 @@ void CppPreprocessor::mergeEnvironment(Document::Ptr doc)
foreach (const Document::Include &incl, doc->includes()) {
QString includedFile = incl.fileName();
- if (Document::Ptr includedDoc = snapshot.document(includedFile))
+ if (Document::Ptr includedDoc = m_snapshot.document(includedFile))
mergeEnvironment(includedDoc);
else
run(includedFile);
}
- env.addMacros(doc->definedMacros());
+ m_env.addMacros(doc->definedMacros());
}
void CppPreprocessor::startSkippingBlocks(unsigned offset)
@@ -619,7 +577,7 @@ void CppPreprocessor::sourceNeeded(unsigned line, QString &fileName, IncludeType
;
}
- Document::Ptr doc = snapshot.document(fileName);
+ Document::Ptr doc = m_snapshot.document(fileName);
if (doc) {
mergeEnvironment(doc);
return;
@@ -635,7 +593,7 @@ void CppPreprocessor::sourceNeeded(unsigned line, QString &fileName, IncludeType
Document::Ptr previousDoc = switchDocument(doc);
- const QByteArray preprocessedCode = preprocess.run(fileName, contents);
+ const QByteArray preprocessedCode = m_preprocess.run(fileName, contents);
// { QByteArray b(preprocessedCode); b.replace("\n", "<<<\n"); qDebug("Preprocessed code for \"%s\": [[%s]]", fileName.toUtf8().constData(), b.constData()); }
@@ -643,24 +601,14 @@ void CppPreprocessor::sourceNeeded(unsigned line, QString &fileName, IncludeType
doc->keepSourceAndAST();
doc->tokenize();
- snapshot.insert(doc);
+ m_snapshot.insert(doc);
m_todo.remove(fileName);
-#ifndef ICHECK_BUILD
- Process process(m_modelManager, doc, snapshot, m_workingCopy);
+ Process process(m_modelManager, doc, m_snapshot, m_workingCopy);
process();
(void) switchDocument(previousDoc);
-#else
- doc->releaseSource();
- Document::CheckMode mode = Document::FastCheck;
- mode = Document::FullCheck;
- doc->parse();
- doc->check(mode);
-
- (void) switchDocument(previousDoc);
-#endif
}
Document::Ptr CppPreprocessor::switchDocument(Document::Ptr doc)
@@ -670,7 +618,6 @@ Document::Ptr CppPreprocessor::switchDocument(Document::Ptr doc)
return previousDoc;
}
-#ifndef ICHECK_BUILD
void CppModelManager::updateModifiedSourceFiles()
{
const Snapshot snapshot = this->snapshot();
@@ -690,13 +637,6 @@ void CppModelManager::updateModifiedSourceFiles()
updateSourceFiles(sourceFiles);
}
-CppModelManager *CppModelManager::instance()
-{
- // TODO this is pretty stupid. use regular singleton pattern.
- return ExtensionSystem::PluginManager::getObject<CppModelManager>();
-}
-
-
/*!
\class CppTools::CppModelManager
\brief The CppModelManager keeps track of one CppCodeModel instance
@@ -706,15 +646,27 @@ CppModelManager *CppModelManager::instance()
modified within Qt Creator.
*/
+QMutex CppModelManager::m_modelManagerMutex;
+CppModelManager *CppModelManager::m_modelManagerInstance = 0;
+
+CppModelManager *CppModelManager::instance()
+{
+ if (m_modelManagerInstance)
+ return m_modelManagerInstance;
+ QMutexLocker locker(&m_modelManagerMutex);
+ if (!m_modelManagerInstance)
+ m_modelManagerInstance = new CppModelManager;
+ return m_modelManagerInstance;
+}
+
CppModelManager::CppModelManager(QObject *parent)
: CppModelManagerInterface(parent)
+ , m_completionAssistProvider(0)
+ , m_highlightingFactory(0)
+ , m_indexingSupporter(0)
{
m_findReferences = new CppFindReferences(this);
m_indexerEnabled = qgetenv("QTCREATOR_NO_CODE_INDEXER").isNull();
- m_dumpFileNameWhileParsing = !qgetenv("QTCREATOR_DUMP_FILENAME_WHILE_PARSING").isNull();
-
- m_revision = 0;
- m_synchronizer.setCancelOnWait(true);
m_dirty = true;
@@ -759,6 +711,7 @@ CppModelManager::CppModelManager(QObject *parent)
ExtensionSystem::PluginManager::addObject(m_completionAssistProvider);
m_highlightingFallback = new CppHighlightingSupportInternalFactory;
m_highlightingFactory = m_highlightingFallback;
+ m_internalIndexingSupport = new BuiltinIndexingSupport;
}
CppModelManager::~CppModelManager()
@@ -766,6 +719,7 @@ CppModelManager::~CppModelManager()
ExtensionSystem::PluginManager::removeObject(m_completionAssistProvider);
delete m_completionFallback;
delete m_highlightingFallback;
+ delete m_internalIndexingSupport;
}
Snapshot CppModelManager::snapshot() const
@@ -794,8 +748,11 @@ QStringList CppModelManager::internalProjectFiles() const
while (it.hasNext()) {
it.next();
ProjectInfo pinfo = it.value();
- foreach (const ProjectPart::Ptr &part, pinfo.projectParts())
+ foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
+ files += part->headerFiles;
files += part->sourceFiles;
+ files += part->objcSourceFiles;
+ }
}
files.removeDuplicates();
return files;
@@ -809,7 +766,8 @@ QStringList CppModelManager::internalIncludePaths() const
it.next();
ProjectInfo pinfo = it.value();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts())
- includePaths += part->includePaths;
+ foreach (const QString &path, part->includePaths)
+ includePaths.append(CppPreprocessor::cleanPath(path));
}
includePaths.removeDuplicates();
return includePaths;
@@ -823,7 +781,8 @@ QStringList CppModelManager::internalFrameworkPaths() const
it.next();
ProjectInfo pinfo = it.value();
foreach (const ProjectPart::Ptr &part, pinfo.projectParts())
- frameworkPaths += part->frameworkPaths;
+ foreach (const QString &path, part->frameworkPaths)
+ frameworkPaths.append(CppPreprocessor::cleanPath(path));
}
frameworkPaths.removeDuplicates();
return frameworkPaths;
@@ -851,6 +810,49 @@ QByteArray CppModelManager::internalDefinedMacros() const
return macros;
}
+/// This method will aquire the mutex!
+void CppModelManager::dumpModelManagerConfiguration()
+{
+ // Tons of debug output...
+ qDebug()<<"========= CppModelManager::dumpModelManagerConfiguration ======";
+ foreach (const ProjectInfo &pinfo, m_projects.values()) {
+ qDebug()<<" for project:"<< pinfo.project().data()->document()->fileName();
+ foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
+ qDebug() << "=== part ===";
+ const char* lang;
+ switch (part->language) {
+ case ProjectPart::CXX: lang = "C++"; break;
+ case ProjectPart::CXX11: lang = "C++11"; break;
+ case ProjectPart::C89: lang = "C89"; break;
+ case ProjectPart::C99: lang = "C99"; break;
+ default: lang = "INVALID";
+ }
+
+ qDebug() << "language:" << lang;
+ qDebug() << "Qt version:" << part->qtVersion;
+ qDebug() << "precompiled header:" << part->precompiledHeaders;
+ qDebug() << "defines:" << part->defines;
+ qDebug() << "includes:" << part->includePaths;
+ qDebug() << "frameworkPaths:" << part->frameworkPaths;
+ qDebug() << "headers:" << part->headerFiles;
+ qDebug() << "sources:" << part->sourceFiles;
+ qDebug() << "objc sources:" << part->objcSourceFiles;
+ qDebug() << "";
+ }
+ }
+
+ ensureUpdated();
+ qDebug() << "=== Merged include paths ===";
+ foreach (const QString &inc, m_includePaths)
+ qDebug() << inc;
+ qDebug() << "=== Merged framework paths ===";
+ foreach (const QString &inc, m_frameworkPaths)
+ qDebug() << inc;
+ qDebug() << "=== Merged defined macros ===";
+ qDebug() << m_definedMacros;
+ qDebug()<<"========= End of dump ======";
+}
+
void CppModelManager::addEditorSupport(AbstractEditorSupport *editorSupport)
{
m_addtionalEditorSupport.insert(editorSupport);
@@ -904,13 +906,13 @@ CppModelManager::WorkingCopy CppModelManager::buildWorkingCopyList()
QSetIterator<AbstractEditorSupport *> jt(m_addtionalEditorSupport);
while (jt.hasNext()) {
AbstractEditorSupport *es = jt.next();
- workingCopy.insert(es->fileName(), es->contents());
+ workingCopy.insert(es->fileName(), QString::fromUtf8(es->contents()));
}
// add the project configuration file
QByteArray conf(pp_configuration);
conf += definedMacros();
- workingCopy.insert(pp_configuration_file, conf);
+ workingCopy.insert(configurationFileName(), QString::fromUtf8(conf));
return workingCopy;
}
@@ -921,7 +923,14 @@ CppModelManager::WorkingCopy CppModelManager::workingCopy() const
}
QFuture<void> CppModelManager::updateSourceFiles(const QStringList &sourceFiles)
-{ return refreshSourceFiles(sourceFiles); }
+{
+ if (sourceFiles.isEmpty() || !m_indexerEnabled)
+ return QFuture<void>();
+
+ if (m_indexingSupporter)
+ m_indexingSupporter->refreshSourceFiles(sourceFiles);
+ return m_internalIndexingSupport->refreshSourceFiles(sourceFiles);
+}
QList<CppModelManager::ProjectInfo> CppModelManager::projectInfos() const
{
@@ -939,40 +948,34 @@ CppModelManager::ProjectInfo CppModelManager::projectInfo(ProjectExplorer::Proje
void CppModelManager::updateProjectInfo(const ProjectInfo &pinfo)
{
-#if 0
- // Tons of debug output...
- qDebug()<<"========= CppModelManager::updateProjectInfo ======";
- qDebug()<<" for project:"<< pinfo.project().data()->document()->fileName();
- foreach (const ProjectPart::Ptr &part, pinfo.projectParts()) {
- qDebug() << "=== part ===";
- qDebug() << "language:" << (part->language == CXX ? "C++" : "ObjC++");
- qDebug() << "C++11:" << part->cxx11Enabled;
- qDebug() << "Qt version:" << part->qtVersion;
- qDebug() << "precompiled header:" << part->precompiledHeaders;
- qDebug() << "defines:" << part->defines;
- qDebug() << "includes:" << part->includePaths;
- qDebug() << "frameworkPaths:" << part->frameworkPaths;
- qDebug() << "sources:" << part->sourceFiles;
- qDebug() << "";
- }
+ { // only hold the mutex for a limited scope, so the dumping afterwards can aquire it without deadlocking.
+ QMutexLocker locker(&mutex);
- qDebug() << "";
-#endif
- QMutexLocker locker(&mutex);
+ if (! pinfo.isValid())
+ return;
- if (! pinfo.isValid())
- return;
+ ProjectExplorer::Project *project = pinfo.project().data();
+ m_projects.insert(project, pinfo);
+ m_dirty = true;
- ProjectExplorer::Project *project = pinfo.project().data();
- m_projects.insert(project, pinfo);
- m_dirty = true;
+ m_srcToProjectPart.clear();
+
+ foreach (const ProjectInfo &projectInfo, m_projects.values()) {
+ foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts()) {
+ foreach (const QString &sourceFile, projectPart->sourceFiles)
+ m_srcToProjectPart[sourceFile].append(projectPart);
+ foreach (const QString &objcSourceFile, projectPart->objcSourceFiles)
+ m_srcToProjectPart[objcSourceFile].append(projectPart);
+ foreach (const QString &headerFile, projectPart->headerFiles)
+ m_srcToProjectPart[headerFile].append(projectPart);
+ }
+ }
+ }
- m_srcToProjectPart.clear();
+ if (!qgetenv("QTCREATOR_DUMP_PROJECT_INFO").isEmpty())
+ dumpModelManagerConfiguration();
- foreach (const ProjectInfo &projectInfo, m_projects.values())
- foreach (const ProjectPart::Ptr &projectPart, projectInfo.projectParts())
- foreach (const QString &sourceFile, projectPart->sourceFiles)
- m_srcToProjectPart[sourceFile].append(projectPart);
+ emit projectPartsUpdated(pinfo.project().data());
}
QList<CppModelManager::ProjectPart::Ptr> CppModelManager::projectPart(const QString &fileName) const
@@ -981,14 +984,6 @@ QList<CppModelManager::ProjectPart::Ptr> CppModelManager::projectPart(const QStr
if (!parts.isEmpty())
return parts;
- //### FIXME: This is a DIRTY hack!
- if (fileName.endsWith(".h")) {
- QString cppFile = fileName.mid(0, fileName.length() - 2) + QLatin1String(".cpp");
- parts = m_srcToProjectPart.value(cppFile);
- if (!parts.isEmpty())
- return parts;
- }
-
DependencyTable table;
table.build(snapshot());
QStringList deps = table.filesDependingOn(fileName);
@@ -1001,44 +996,6 @@ QList<CppModelManager::ProjectPart::Ptr> CppModelManager::projectPart(const QStr
return parts;
}
-QFuture<void> CppModelManager::refreshSourceFiles(const QStringList &sourceFiles)
-{
- if (! sourceFiles.isEmpty() && m_indexerEnabled) {
- const WorkingCopy workingCopy = buildWorkingCopyList();
-
- CppPreprocessor *preproc = new CppPreprocessor(this, m_dumpFileNameWhileParsing);
- preproc->setRevision(++m_revision);
- preproc->setProjectFiles(projectFiles());
- preproc->setIncludePaths(includePaths());
- preproc->setFrameworkPaths(frameworkPaths());
- preproc->setWorkingCopy(workingCopy);
-
- QFuture<void> result = QtConcurrent::run(&CppModelManager::parse,
- preproc, sourceFiles);
-
- if (m_synchronizer.futures().size() > 10) {
- QList<QFuture<void> > futures = m_synchronizer.futures();
-
- m_synchronizer.clearFutures();
-
- foreach (const QFuture<void> &future, futures) {
- if (! (future.isFinished() || future.isCanceled()))
- m_synchronizer.addFuture(future);
- }
- }
-
- m_synchronizer.addFuture(result);
-
- if (sourceFiles.count() > 1) {
- Core::ICore::progressManager()->addTask(result, tr("Parsing"),
- CppTools::Constants::TASK_INDEX);
- }
-
- return result;
- }
- return QFuture<void>();
-}
-
/*!
\fn void CppModelManager::editorOpened(Core::IEditor *editor)
\brief If a C++ editor is opened, the model manager listens to content changes
@@ -1253,9 +1210,8 @@ void CppModelManager::onAboutToRemoveProject(ProjectExplorer::Project *project)
void CppModelManager::onAboutToUnloadSession()
{
- if (Core::ProgressManager *pm = Core::ICore::progressManager()) {
- pm->cancelTasks(CppTools::Constants::TASK_INDEX);
- }
+ if (Core::ProgressManager *pm = Core::ICore::progressManager())
+ pm->cancelTasks(QLatin1String(CppTools::Constants::TASK_INDEX));
do {
QMutexLocker locker(&mutex);
m_projects.clear();
@@ -1265,81 +1221,6 @@ void CppModelManager::onAboutToUnloadSession()
GC();
}
-void CppModelManager::parse(QFutureInterface<void> &future,
- CppPreprocessor *preproc,
- QStringList files)
-{
- if (files.isEmpty())
- return;
-
- const Core::MimeDatabase *mimeDb = Core::ICore::mimeDatabase();
- Core::MimeType cSourceTy = mimeDb->findByType(QLatin1String("text/x-csrc"));
- Core::MimeType cppSourceTy = mimeDb->findByType(QLatin1String("text/x-c++src"));
- Core::MimeType mSourceTy = mimeDb->findByType(QLatin1String("text/x-objcsrc"));
-
- QStringList sources;
- QStringList headers;
-
- QStringList suffixes = cSourceTy.suffixes();
- suffixes += cppSourceTy.suffixes();
- suffixes += mSourceTy.suffixes();
-
- foreach (const QString &file, files) {
- QFileInfo info(file);
-
- preproc->snapshot.remove(file);
-
- if (suffixes.contains(info.suffix()))
- sources.append(file);
- else
- headers.append(file);
- }
-
- const int sourceCount = sources.size();
- files = sources;
- files += headers;
-
- preproc->setTodo(files);
-
- future.setProgressRange(0, files.size());
-
- QString conf = QLatin1String(pp_configuration_file);
-
- bool processingHeaders = false;
-
- for (int i = 0; i < files.size(); ++i) {
- if (future.isPaused())
- future.waitForResume();
-
- if (future.isCanceled())
- break;
-
- const QString fileName = files.at(i);
-
- const bool isSourceFile = i < sourceCount;
- if (isSourceFile)
- (void) preproc->run(conf);
-
- else if (! processingHeaders) {
- (void) preproc->run(conf);
-
- processingHeaders = true;
- }
-
- preproc->run(fileName);
-
- future.setProgressValue(files.size() - preproc->todo().size());
-
- if (isSourceFile)
- preproc->resetEnvironment();
- }
-
- future.setProgressValue(files.size());
- preproc->modelManager()->finishedRefreshingSourceFiles(files);
-
- delete preproc;
-}
-
void CppModelManager::GC()
{
protectSnapshot.lock();
@@ -1358,9 +1239,8 @@ void CppModelManager::GC()
processed.insert(fn);
- if (Document::Ptr doc = currentSnapshot.document(fn)) {
+ if (Document::Ptr doc = currentSnapshot.document(fn))
todo += doc->includedFiles();
- }
}
QStringList removedFiles;
@@ -1421,6 +1301,17 @@ void CppModelManager::setHighlightingSupportFactory(CppHighlightingSupportFactor
m_highlightingFactory = m_highlightingFallback;
}
+void CppModelManager::setIndexingSupport(CppIndexingSupport *indexingSupport)
+{
+ if (indexingSupport)
+ m_indexingSupporter = indexingSupport;
+}
+
+CppIndexingSupport *CppModelManager::indexingSupport()
+{
+ return m_indexingSupporter ? m_indexingSupporter : m_internalIndexingSupport;
+}
+
void CppModelManager::setExtraDiagnostics(const QString &fileName, int kind,
const QList<Document::DiagnosticMessage> &diagnostics)
{
@@ -1444,6 +1335,3 @@ QList<Document::DiagnosticMessage> CppModelManager::extraDiagnostics(const QStri
}
return m_extraDiagnostics.value(fileName).value(kind);
}
-
-#endif
-
diff --git a/src/plugins/cpptools/cppmodelmanager.h b/src/plugins/cpptools/cppmodelmanager.h
index 5681dcc408..9ea4463d25 100644
--- a/src/plugins/cpptools/cppmodelmanager.h
+++ b/src/plugins/cpptools/cppmodelmanager.h
@@ -33,26 +33,19 @@
#include "cpptools_global.h"
#include "cpptoolsconstants.h"
#include "ModelManagerInterface.h"
-#ifndef ICHECK_BUILD
-# include <projectexplorer/project.h>
-#endif
+#include <projectexplorer/project.h>
#include <cplusplus/CppDocument.h>
#include <cplusplus/PreprocessorClient.h>
-#ifndef ICHECK_BUILD
-# include <texteditor/basetexteditor.h>
-#endif
+#include <texteditor/basetexteditor.h>
#include <cplusplus/PreprocessorEnvironment.h>
#include <cplusplus/pp-engine.h>
-#ifdef ICHECK_BUILD
-# include "parsemanager.h"
-#else
-# include <QHash>
-# include <QFutureInterface>
-# include <QFutureSynchronizer>
-# include <QMutex>
-# include <QTimer>
-# include <QTextEdit> // for QTextEdit::ExtraSelection
-#endif
+
+#include <QHash>
+#include <QFutureInterface>
+#include <QFutureSynchronizer>
+#include <QMutex>
+#include <QTimer>
+#include <QTextEdit> // for QTextEdit::ExtraSelection
namespace Core {
class IEditor;
@@ -82,13 +75,12 @@ class CppEditorSupport;
class CppPreprocessor;
class CppFindReferences;
-#ifndef ICHECK_BUILD
class CPPTOOLS_EXPORT CppModelManager : public CPlusPlus::CppModelManagerInterface
{
Q_OBJECT
public:
- CppModelManager(QObject *parent);
+ CppModelManager(QObject *parent = 0);
virtual ~CppModelManager();
static CppModelManager *instance();
@@ -104,8 +96,6 @@ public:
virtual CPlusPlus::Snapshot snapshot() const;
virtual void GC();
- QFuture<void> refreshSourceFiles(const QStringList &sourceFiles);
-
virtual bool isCppEditor(Core::IEditor *editor) const;
CppEditorSupport *editorSupport(TextEditor::ITextEditor *editor) const
@@ -141,30 +131,8 @@ public:
virtual CppHighlightingSupport *highlightingSupport(Core::IEditor *editor) const;
virtual void setHighlightingSupportFactory(CppHighlightingSupportFactory *highlightingFactory);
-Q_SIGNALS:
- void projectPathChanged(const QString &projectPath);
-
- void aboutToRemoveFiles(const QStringList &files);
-
-public Q_SLOTS:
- void editorOpened(Core::IEditor *editor);
- void editorAboutToClose(Core::IEditor *editor);
- virtual void updateModifiedSourceFiles();
-
-private Q_SLOTS:
- // this should be executed in the GUI thread.
- void onDocumentUpdated(CPlusPlus::Document::Ptr doc);
- void onExtraDiagnosticsUpdated(const QString &fileName);
- void onAboutToRemoveProject(ProjectExplorer::Project *project);
- void onAboutToUnloadSession();
- void onProjectAdded(ProjectExplorer::Project *project);
- void postEditorUpdate();
- void updateEditorSelections();
-
-private:
- void updateEditor(CPlusPlus::Document::Ptr doc);
-
- WorkingCopy buildWorkingCopyList();
+ virtual void setIndexingSupport(CppIndexingSupport *indexingSupport);
+ virtual CppIndexingSupport *indexingSupport();
QStringList projectFiles()
{
@@ -190,15 +158,42 @@ private:
return m_definedMacros;
}
+Q_SIGNALS:
+ void projectPathChanged(const QString &projectPath);
+
+ void aboutToRemoveFiles(const QStringList &files);
+
+public Q_SLOTS:
+ void editorOpened(Core::IEditor *editor);
+ void editorAboutToClose(Core::IEditor *editor);
+ virtual void updateModifiedSourceFiles();
+
+private Q_SLOTS:
+ // this should be executed in the GUI thread.
+ void onDocumentUpdated(CPlusPlus::Document::Ptr doc);
+ void onExtraDiagnosticsUpdated(const QString &fileName);
+ void onAboutToRemoveProject(ProjectExplorer::Project *project);
+ void onAboutToUnloadSession();
+ void onProjectAdded(ProjectExplorer::Project *project);
+ void postEditorUpdate();
+ void updateEditorSelections();
+
+private:
+ void updateEditor(CPlusPlus::Document::Ptr doc);
+
+ WorkingCopy buildWorkingCopyList();
+
void ensureUpdated();
QStringList internalProjectFiles() const;
QStringList internalIncludePaths() const;
QStringList internalFrameworkPaths() const;
QByteArray internalDefinedMacros() const;
- static void parse(QFutureInterface<void> &future,
- CppPreprocessor *preproc,
- QStringList files);
+ void dumpModelManagerConfiguration();
+
+private:
+ static QMutex m_modelManagerMutex;
+ static CppModelManager *m_modelManagerInstance;
private:
CPlusPlus::Snapshot m_snapshot;
@@ -237,12 +232,8 @@ private:
QTimer *m_updateEditorSelectionsTimer;
- QFutureSynchronizer<void> m_synchronizer;
- unsigned m_revision;
-
CppFindReferences *m_findReferences;
bool m_indexerEnabled;
- bool m_dumpFileNameWhileParsing;
mutable QMutex protectExtraDiagnostics;
QHash<QString, QHash<int, QList<CPlusPlus::Document::DiagnosticMessage> > > m_extraDiagnostics;
@@ -253,17 +244,14 @@ private:
CppCompletionAssistProvider *m_completionFallback;
CppHighlightingSupportFactory *m_highlightingFactory;
CppHighlightingSupportFactory *m_highlightingFallback;
+ CppIndexingSupport *m_indexingSupporter;
+ CppIndexingSupport *m_internalIndexingSupport;
};
-#endif
class CPPTOOLS_EXPORT CppPreprocessor: public CPlusPlus::Client
{
public:
-#ifndef ICHECK_BUILD
CppPreprocessor(QPointer<CppModelManager> modelManager, bool dumpFileNameWhileParsing = false);
-#else
- CppPreprocessor(QPointer<CPlusPlus::ParseManager> modelManager);
-#endif
virtual ~CppPreprocessor();
void setRevision(unsigned revision);
@@ -277,6 +265,7 @@ public:
void run(const QString &fileName);
void resetEnvironment();
+ static QString cleanPath(const QString &path);
const QSet<QString> &todo() const
{ return m_todo; }
@@ -285,7 +274,7 @@ public:
{ return m_modelManager.data(); }
public: // attributes
- CPlusPlus::Snapshot snapshot;
+ CPlusPlus::Snapshot m_snapshot;
protected:
CPlusPlus::Document::Ptr switchDocument(CPlusPlus::Document::Ptr doc);
@@ -307,19 +296,17 @@ protected:
const CPlusPlus::Macro &macro,
const QVector<CPlusPlus::MacroArgumentReference> &actuals);
virtual void stopExpandingMacro(unsigned offset, const CPlusPlus::Macro &macro);
+ virtual void markAsIncludeGuard(const QByteArray &macroName);
virtual void startSkippingBlocks(unsigned offset);
virtual void stopSkippingBlocks(unsigned offset);
virtual void sourceNeeded(unsigned line, QString &fileName, IncludeType type);
private:
-#ifndef ICHECK_BUILD
QPointer<CppModelManager> m_modelManager;
-#endif
bool m_dumpFileNameWhileParsing;
- CPlusPlus::Environment env;
- CPlusPlus::Preprocessor preprocess;
+ CPlusPlus::Environment m_env;
+ CPlusPlus::Preprocessor m_preprocess;
QStringList m_includePaths;
- QStringList m_systemIncludePaths;
CPlusPlus::CppModelManagerInterface::WorkingCopy m_workingCopy;
QStringList m_projectFiles;
QStringList m_frameworkPaths;
diff --git a/src/plugins/cpptools/cppmodelmanager_test.cpp b/src/plugins/cpptools/cppmodelmanager_test.cpp
new file mode 100644
index 0000000000..bc786e8bdb
--- /dev/null
+++ b/src/plugins/cpptools/cppmodelmanager_test.cpp
@@ -0,0 +1,138 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "cpptoolsplugin.h"
+#include "CppDocument.h"
+#include "cppmodelmanager.h"
+#include "modelmanagertesthelper.h"
+
+#include <QtTest>
+#include <QDebug>
+
+using namespace CppTools::Internal;
+
+typedef CPlusPlus::Document Document;
+typedef CPlusPlus::CppModelManagerInterface::ProjectInfo ProjectInfo;
+typedef CPlusPlus::CppModelManagerInterface::ProjectPart ProjectPart;
+typedef ProjectExplorer::Project Project;
+
+namespace {
+QString testDataDir(const QString& subdir, bool cleaned = true)
+{
+ QString path = QLatin1String(SRCDIR "/../../../tests/cppmodelmanager/testdata");
+ if (!subdir.isEmpty())
+ path += QLatin1String("/") + subdir;
+ if (cleaned)
+ return CppPreprocessor::cleanPath(path);
+ else
+ return path;
+}
+
+QString testIncludeDir(bool cleaned = true)
+{
+ return testDataDir(QLatin1String("include"), cleaned);
+}
+
+QString testFrameworksDir(bool cleaned = true)
+{
+ return testDataDir(QLatin1String("frameworks"), cleaned);
+}
+
+QString testSource(const QString &fileName)
+{
+ return testDataDir(QLatin1String("sources")) + fileName;
+}
+} // anonymous namespace
+
+void CppToolsPlugin::test_modelmanager_paths()
+{
+ ModelManagerTestHelper helper;
+ CppModelManager *mm = CppModelManager::instance();
+
+ Project *project = helper.createProject(QLatin1String("test_modelmanager_paths"));
+ ProjectInfo pi = mm->projectInfo(project);
+ QCOMPARE(pi.project().data(), project);
+
+ ProjectPart::Ptr part(new ProjectPart);
+ pi.appendProjectPart(part);
+ part->language = ProjectPart::CXX;
+ part->qtVersion = ProjectPart::Qt5;
+ part->defines = QByteArray("#define OH_BEHAVE -1\n");
+ part->includePaths = QStringList() << testIncludeDir(false);
+ part->frameworkPaths = QStringList() << testFrameworksDir(false);
+
+ mm->updateProjectInfo(pi);
+
+ QStringList includePaths = mm->includePaths();
+ QCOMPARE(includePaths.size(), 1);
+ QVERIFY(includePaths.contains(testIncludeDir()));
+
+ QStringList frameworkPaths = mm->frameworkPaths();
+ QCOMPARE(frameworkPaths.size(), 1);
+ QVERIFY(frameworkPaths.contains(testFrameworksDir()));
+}
+
+void CppToolsPlugin::test_modelmanager_framework_headers()
+{
+ ModelManagerTestHelper helper;
+ CppModelManager *mm = CppModelManager::instance();
+
+ Project *project = helper.createProject(QLatin1String("test_modelmanager_framework_headers"));
+ ProjectInfo pi = mm->projectInfo(project);
+ QCOMPARE(pi.project().data(), project);
+
+ ProjectPart::Ptr part(new ProjectPart);
+ pi.appendProjectPart(part);
+ part->language = ProjectPart::CXX;
+ part->qtVersion = ProjectPart::Qt5;
+ part->defines = QByteArray("#define OH_BEHAVE -1\n");
+ part->includePaths << testIncludeDir();
+ part->frameworkPaths << testFrameworksDir();
+ part->sourceFiles << testSource(QLatin1String("test_modelmanager_framework_headers.cpp"));
+
+ mm->updateProjectInfo(pi);
+ mm->updateSourceFiles(part->sourceFiles).waitForFinished();
+ QCoreApplication::processEvents();
+
+ QVERIFY(mm->snapshot().contains(part->sourceFiles.first()));
+ Document::Ptr doc = mm->snapshot().document(part->sourceFiles.first());
+ QVERIFY(!doc.isNull());
+ CPlusPlus::Namespace *ns = doc->globalNamespace();
+ QVERIFY(ns);
+ QVERIFY(ns->memberCount() > 0);
+ for (unsigned i = 0, ei = ns->memberCount(); i < ei; ++i) {
+ CPlusPlus::Symbol *s = ns->memberAt(i);
+ QVERIFY(s);
+ QVERIFY(s->name());
+ const CPlusPlus::Identifier *id = s->name()->asNameId();
+ QVERIFY(id);
+ QByteArray chars = id->chars();
+ QVERIFY(chars.startsWith("success"));
+ }
+}
diff --git a/src/plugins/cpptools/cpppointerdeclarationformatter.cpp b/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
new file mode 100644
index 0000000000..ba0fa4c60f
--- /dev/null
+++ b/src/plugins/cpptools/cpppointerdeclarationformatter.cpp
@@ -0,0 +1,417 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+
+#include "cpppointerdeclarationformatter.h"
+
+#include <AST.h>
+
+#include <QTextCursor>
+
+#define DEBUG_OUTPUT 0
+#define CHECK_RV(cond, err, r) if (!(cond)) { if (DEBUG_OUTPUT) qDebug() << (err); return r; }
+#define CHECK_R(cond, err) if (!(cond)) { if (DEBUG_OUTPUT) qDebug() << (err); return; }
+#define CHECK_C(cond, err) if (!(cond)) { if (DEBUG_OUTPUT) qDebug() << (err); continue; }
+
+using namespace CppTools;
+
+/*!
+ \brief Skip not type relevant specifiers and return the index of the
+ first specifier token which is not followed by __attribute__
+ ((T___ATTRIBUTE__)).
+
+ This is used to get 'correct' start of the activation range in
+ simple declarations.
+
+ Consider these cases:
+
+ static char *s = 0;
+ typedef char *s cp;
+ __attribute__((visibility("default"))) char *f();
+
+ For all cases we want to skip all the not type relevant specifer
+ (since these are not part of the type and thus are not rewritten).
+
+ \param list The specifier list to iterate
+ \param translationUnit The TranslationUnit
+ \param endToken Do not check further than this token
+ \param found Output parameter, must not be 0.
+ */
+static unsigned firstTypeSpecifierWithoutFollowingAttribute(
+ SpecifierListAST *list, TranslationUnit *translationUnit, unsigned endToken, bool *found)
+{
+ *found = false;
+ if (! list || ! translationUnit || ! endToken)
+ return 0;
+
+ for (SpecifierListAST *it = list; it; it = it->next) {
+ SpecifierAST *specifier = it->value;
+ CHECK_RV(specifier, "No specifier", 0);
+ const unsigned index = specifier->firstToken();
+ CHECK_RV(index < endToken, "EndToken reached", 0);
+
+ const int tokenKind = translationUnit->tokenKind(index);
+ switch (tokenKind) {
+ case T_VIRTUAL:
+ case T_INLINE:
+ case T_FRIEND:
+ case T_REGISTER:
+ case T_STATIC:
+ case T_EXTERN:
+ case T_MUTABLE:
+ case T_TYPEDEF:
+ case T_CONSTEXPR:
+ case T___ATTRIBUTE__:
+ continue;
+ default:
+ // Check if attributes follow
+ for (unsigned i = index; i <= endToken; ++i) {
+ const int tokenKind = translationUnit->tokenKind(i);
+ if (tokenKind == T___ATTRIBUTE__)
+ return 0;
+ }
+ *found = true;
+ return index;
+ }
+ }
+
+ return 0;
+}
+
+PointerDeclarationFormatter::PointerDeclarationFormatter(
+ const CppRefactoringFilePtr refactoringFile,
+ const Overview &overview,
+ CursorHandling cursorHandling)
+ : ASTVisitor(refactoringFile->cppDocument()->translationUnit())
+ , m_cppRefactoringFile(refactoringFile)
+ , m_overview(overview)
+ , m_cursorHandling(cursorHandling)
+{}
+
+/*!
+ Handle
+ (1) Simple declarations like in "char *s, *t, *int foo();"
+ (2) Return types of function declarations.
+ */
+bool PointerDeclarationFormatter::visit(SimpleDeclarationAST *ast)
+{
+ CHECK_RV(ast, "Invalid AST", true);
+
+ DeclaratorListAST *declaratorList = ast->declarator_list;
+ CHECK_RV(declaratorList, "No declarator list", true);
+ DeclaratorAST *firstDeclarator = declaratorList->value;
+ CHECK_RV(firstDeclarator, "No declarator", true);
+ CHECK_RV(ast->symbols, "No Symbols", true);
+ CHECK_RV(ast->symbols->value, "No Symbol", true);
+
+ List<Symbol *> *sit = ast->symbols;
+ DeclaratorListAST *dit = declaratorList;
+ for (; sit && dit; sit = sit->next, dit = dit->next) {
+ DeclaratorAST *declarator = dit->value;
+ Symbol *symbol = sit->value;
+
+ const bool isFirstDeclarator = declarator == firstDeclarator;
+
+ // If were not handling the first declarator, we need to remove
+ // characters from the beginning since our rewritten declaration
+ // will contain all type specifiers.
+ int charactersToRemove = 0;
+ if (! isFirstDeclarator) {
+ const int startAST = m_cppRefactoringFile->startOf(ast);
+ const int startFirstDeclarator = m_cppRefactoringFile->startOf(firstDeclarator);
+ CHECK_RV(startAST < startFirstDeclarator, "No specifier", true);
+ charactersToRemove = startFirstDeclarator - startAST;
+ }
+
+ // Specify activation range
+ int lastActivationToken = 0;
+ Range range;
+ // (2) Handle function declaration's return type
+ if (symbol->type()->asFunctionType()) {
+ PostfixDeclaratorListAST *pfDeclaratorList = declarator->postfix_declarator_list;
+ CHECK_RV(pfDeclaratorList, "No postfix declarator list", true);
+ PostfixDeclaratorAST *pfDeclarator = pfDeclaratorList->value;
+ CHECK_RV(pfDeclarator, "No postfix declarator", true);
+ FunctionDeclaratorAST *functionDeclarator = pfDeclarator->asFunctionDeclarator();
+ CHECK_RV(functionDeclarator, "No function declarator", true);
+ // End the activation range before the '(' token.
+ lastActivationToken = functionDeclarator->lparen_token - 1;
+
+ SpecifierListAST *specifierList = isFirstDeclarator
+ ? ast->decl_specifier_list
+ : declarator->attribute_list;
+
+ unsigned firstActivationToken = 0;
+ bool foundBegin = false;
+ firstActivationToken = firstTypeSpecifierWithoutFollowingAttribute(
+ specifierList,
+ m_cppRefactoringFile->cppDocument()->translationUnit(),
+ lastActivationToken,
+ &foundBegin);
+ if (! foundBegin) {
+ CHECK_RV(! isFirstDeclarator, "Declaration without attributes not supported", true);
+ firstActivationToken = declarator->firstToken();
+ }
+
+ range.start = m_cppRefactoringFile->startOf(firstActivationToken);
+
+ // (1) Handle 'normal' declarations.
+ } else {
+ if (isFirstDeclarator) {
+ bool foundBegin = false;
+ unsigned firstActivationToken = firstTypeSpecifierWithoutFollowingAttribute(
+ ast->decl_specifier_list,
+ m_cppRefactoringFile->cppDocument()->translationUnit(),
+ declarator->firstToken(),
+ &foundBegin);
+ CHECK_RV(foundBegin, "Declaration without attributes not supported", true);
+ range.start = m_cppRefactoringFile->startOf(firstActivationToken);
+ } else {
+ range.start = m_cppRefactoringFile->startOf(declarator);
+ }
+ lastActivationToken = declarator->equal_token
+ ? declarator->equal_token - 1
+ : declarator->lastToken() - 1;
+ }
+ range.end = m_cppRefactoringFile->endOf(lastActivationToken);
+
+ checkAndRewrite(symbol, range, charactersToRemove);
+ }
+ return true;
+}
+
+/*! Handle return types of function definitions */
+bool PointerDeclarationFormatter::visit(FunctionDefinitionAST *ast)
+{
+ DeclaratorAST *declarator = ast->declarator;
+ CHECK_RV(declarator, "No declarator", true);
+ CHECK_RV(declarator->ptr_operator_list, "No Pointer or references", true);
+ Symbol *symbol = ast->symbol;
+
+ PostfixDeclaratorListAST *pfDeclaratorList = declarator->postfix_declarator_list;
+ CHECK_RV(pfDeclaratorList, "No postfix declarator list", true);
+ PostfixDeclaratorAST *pfDeclarator = pfDeclaratorList->value;
+ CHECK_RV(pfDeclarator, "No postfix declarator", true);
+ FunctionDeclaratorAST *functionDeclarator = pfDeclarator->asFunctionDeclarator();
+ CHECK_RV(functionDeclarator, "No function declarator", true);
+
+ // Specify activation range
+ bool foundBegin = false;
+ const unsigned lastActivationToken = functionDeclarator->lparen_token - 1;
+ const unsigned firstActivationToken = firstTypeSpecifierWithoutFollowingAttribute(
+ ast->decl_specifier_list,
+ m_cppRefactoringFile->cppDocument()->translationUnit(),
+ lastActivationToken,
+ &foundBegin);
+ CHECK_RV(foundBegin, "Declaration without attributes not supported", true);
+ Range range(m_cppRefactoringFile->startOf(firstActivationToken),
+ m_cppRefactoringFile->endOf(lastActivationToken));
+
+ checkAndRewrite(symbol, range);
+ return true;
+}
+
+/*! Handle parameters in function declarations and definitions */
+bool PointerDeclarationFormatter::visit(ParameterDeclarationAST *ast)
+{
+ DeclaratorAST *declarator = ast->declarator;
+ CHECK_RV(declarator, "No declarator", true);
+ CHECK_RV(declarator->ptr_operator_list, "No Pointer or references", true);
+ Symbol *symbol = ast->symbol;
+
+ // Specify activation range
+ const int lastActivationToken = ast->equal_token
+ ? ast->equal_token - 1
+ : ast->lastToken() - 1;
+ Range range(m_cppRefactoringFile->startOf(ast),
+ m_cppRefactoringFile->endOf(lastActivationToken));
+
+ checkAndRewrite(symbol, range);
+ return true;
+}
+
+/*! Handle declaration in foreach statement */
+bool PointerDeclarationFormatter::visit(ForeachStatementAST *ast)
+{
+ DeclaratorAST *declarator = ast->declarator;
+ CHECK_RV(declarator, "No declarator", true);
+ CHECK_RV(declarator->ptr_operator_list, "No Pointer or references", true);
+ CHECK_RV(ast->type_specifier_list, "No type specifier", true);
+ SpecifierAST *firstSpecifier = ast->type_specifier_list->value;
+ CHECK_RV(firstSpecifier, "No first type specifier", true);
+ CHECK_RV(ast->symbol, "No symbol", true);
+ Symbol *symbol = ast->symbol->memberAt(0);
+
+ // Specify activation range
+ const int lastActivationToken = declarator->equal_token
+ ? declarator->equal_token - 1
+ : declarator->lastToken() - 1;
+ Range range(m_cppRefactoringFile->startOf(firstSpecifier),
+ m_cppRefactoringFile->endOf(lastActivationToken));
+
+ checkAndRewrite(symbol, range);
+ return true;
+}
+
+bool PointerDeclarationFormatter::visit(IfStatementAST *ast)
+{
+ processIfWhileForStatement(ast->condition, ast->symbol);
+ return true;
+}
+
+bool PointerDeclarationFormatter::visit(WhileStatementAST *ast)
+{
+ processIfWhileForStatement(ast->condition, ast->symbol);
+ return true;
+}
+
+bool PointerDeclarationFormatter::visit(ForStatementAST *ast)
+{
+ processIfWhileForStatement(ast->condition, ast->symbol);
+ return true;
+}
+
+/*! Handle declaration in if, while and for statements */
+void PointerDeclarationFormatter::processIfWhileForStatement(ExpressionAST *expression,
+ Symbol *statementSymbol)
+{
+ CHECK_R(expression, "No expression");
+ CHECK_R(statementSymbol, "No symbol");
+
+ ConditionAST *condition = expression->asCondition();
+ CHECK_R(condition, "No condition");
+ DeclaratorAST *declarator = condition->declarator;
+ CHECK_R(declarator, "No declarator");
+ CHECK_R(declarator->ptr_operator_list, "No Pointer or references");
+ CHECK_R(declarator->equal_token, "No equal token");
+ Block *block = statementSymbol->asBlock();
+ CHECK_R(block, "No block");
+ CHECK_R(block->memberCount() > 0, "No block members");
+
+ // Get the right symbol
+ //
+ // This is especially important for e.g.
+ //
+ // for (char *s = 0; char *t = 0;) {}
+ //
+ // The declaration for 's' will be handled in visit(SimpleDeclarationAST *ast),
+ // so handle declaration for 't' here.
+ Scope::iterator it = block->lastMember() - 1;
+ Symbol *symbol = *it;
+ if (symbol && symbol->asScope()) { // True if there is a "{ ... }" following.
+ --it;
+ symbol = *it;
+ }
+
+ // Specify activation range
+ Range range(m_cppRefactoringFile->startOf(condition),
+ m_cppRefactoringFile->endOf(declarator->equal_token - 1));
+
+ checkAndRewrite(symbol, range);
+}
+
+/*!
+ \brief Do some further checks and rewrite the symbol's type and
+ name into the given range
+
+ \param symbol the symbol to be rewritten
+ \param range the substitution range in the file
+ */
+void PointerDeclarationFormatter::checkAndRewrite(Symbol *symbol, Range range,
+ unsigned charactersToRemove)
+{
+ CHECK_R(range.start >= 0 && range.end > 0, "Range invalid");
+ CHECK_R(range.start < range.end, "Range invalid");
+ CHECK_R(symbol, "No symbol");
+
+ // Check range with respect to cursor position / selection
+ if (m_cursorHandling == RespectCursor) {
+ const QTextCursor cursor = m_cppRefactoringFile->cursor();
+ if (cursor.hasSelection()) {
+ CHECK_R(cursor.selectionStart() <= range.start, "Change not in selection range");
+ CHECK_R(range.end <= cursor.selectionEnd(), "Change not in selection range");
+ } else {
+ CHECK_R(range.start <= cursor.selectionStart(), "Cursor before activation range");
+ CHECK_R(cursor.selectionEnd() <= range.end, "Cursor after activation range");
+ }
+ }
+
+ FullySpecifiedType type = symbol->type();
+ if (Function *function = type->asFunctionType())
+ type = function->returnType();
+
+ // Check if pointers or references are involved
+ const QString originalDeclaration = m_cppRefactoringFile->textOf(range);
+ CHECK_R(originalDeclaration.contains(QLatin1Char('&'))
+ || originalDeclaration.contains(QLatin1Char('*')), "No pointer or references");
+
+ // Does the rewritten declaration (part) differs from the original source (part)?
+ QString rewrittenDeclaration = rewriteDeclaration(type, symbol->name());
+ rewrittenDeclaration.remove(0, charactersToRemove);
+ CHECK_R(originalDeclaration != rewrittenDeclaration, "Rewritten is same as original");
+
+ if (DEBUG_OUTPUT) {
+ qDebug("Rewritten: \"%s\" --> \"%s\"", originalDeclaration.toLatin1().constData(),
+ rewrittenDeclaration.toLatin1().constData());
+ }
+
+ // Creating the replacement in the changeset may fail due to operations
+ // in the changeset that overlap with the current range.
+ //
+ // Consider this case:
+ //
+ // void (*foo)(char * s) = 0;
+ //
+ // First visit(SimpleDeclarationAST *ast) will be called. It creates a
+ // replacement that also includes the parameter.
+ // Next visit(ParameterDeclarationAST *ast) is called with the
+ // original source. It tries to create an replacement operation
+ // at this position and fails due to overlapping ranges (the
+ // simple declaration range includes parameter declaration range).
+ ChangeSet change(m_changeSet);
+ if (change.replace(range, rewrittenDeclaration))
+ m_changeSet = change;
+ else if (DEBUG_OUTPUT)
+ qDebug() << "Replacement operation failed";
+}
+
+/*! Rewrite/format the given type and name. */
+QString PointerDeclarationFormatter::rewriteDeclaration(FullySpecifiedType type, const Name *name)
+ const
+{
+ CHECK_RV(type.isValid(), "Invalid type", QString());
+
+ const char *identifier = 0;
+ if (const Name *declarationName = name) {
+ if (const Identifier *id = declarationName->identifier())
+ identifier = id->chars();
+ }
+
+ return m_overview.prettyType(type, QLatin1String(identifier));
+}
diff --git a/src/plugins/cpptools/cpppointerdeclarationformatter.h b/src/plugins/cpptools/cpppointerdeclarationformatter.h
new file mode 100644
index 0000000000..214e72396c
--- /dev/null
+++ b/src/plugins/cpptools/cpppointerdeclarationformatter.h
@@ -0,0 +1,122 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CPPPOINTERFORMATTER_H
+#define CPPPOINTERFORMATTER_H
+
+#include "cpptools_global.h"
+
+#include <AST.h>
+#include <ASTVisitor.h>
+#include <Overview.h>
+#include <Symbols.h>
+
+#include <cpptools/cpprefactoringchanges.h>
+#include <utils/changeset.h>
+
+namespace CppTools {
+
+using namespace CPlusPlus;
+using namespace CppTools;
+using Utils::ChangeSet;
+
+typedef Utils::ChangeSet::Range Range;
+
+/*!
+ \class CppTools::PointerDeclarationFormatter
+
+ \brief Rewrite pointer or reference declarations accordingly to an Overview.
+
+ The following constructs are supported:
+ \list
+ \o Simple declarations
+ \o Parameters and return types of function declarations and definitions
+ \o Control flow statements like if, while, for, foreach
+ \endlist
+*/
+
+class CPPTOOLS_EXPORT PointerDeclarationFormatter: protected ASTVisitor
+{
+public:
+ /*!
+ \enum PointerDeclarationFormatter::CursorHandling
+
+ This simplifies the QuickFix implementation.
+
+ \value RespectCursor
+ Consider the cursor position / selection of the CppRefactoringFile
+ for rejecting edit operation candidates for the resulting ChangeSet.
+ If there is a selection, the range of the edit operation candidate
+ should be inside the selection. If there is no selection, the cursor
+ position should be within the range of the edit operation candidate.
+ \value IgnoreCursor
+ Cursor position or selection of the CppRefactoringFile will
+ _not_ be considered for aborting.
+ */
+ enum CursorHandling { RespectCursor, IgnoreCursor };
+
+ explicit PointerDeclarationFormatter(const CppRefactoringFilePtr refactoringFile,
+ const Overview &overview,
+ CursorHandling cursorHandling = IgnoreCursor);
+
+ /*!
+ Returns a ChangeSet for applying the formatting changes.
+ The ChangeSet is empty if it was not possible to rewrite anything.
+ */
+ ChangeSet format(AST *ast)
+ {
+ if (ast)
+ accept(ast);
+ return m_changeSet;
+ }
+
+protected:
+ bool visit(SimpleDeclarationAST *ast);
+ bool visit(FunctionDefinitionAST *ast);
+ bool visit(ParameterDeclarationAST *ast);
+ bool visit(IfStatementAST *ast);
+ bool visit(WhileStatementAST *ast);
+ bool visit(ForStatementAST *ast);
+ bool visit(ForeachStatementAST *ast);
+
+private:
+ void processIfWhileForStatement(ExpressionAST *expression, Symbol *symbol);
+ void checkAndRewrite(Symbol *symbol, Range range, unsigned charactersToRemove = 0);
+ QString rewriteDeclaration(FullySpecifiedType type, const Name *name) const;
+
+ const CppRefactoringFilePtr m_cppRefactoringFile;
+ const Overview &m_overview;
+ const CursorHandling m_cursorHandling;
+
+ ChangeSet m_changeSet;
+};
+
+} // namespace CppTools
+
+#endif // CPPPOINTERFORMATTER_H
diff --git a/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp b/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp
new file mode 100644
index 0000000000..dbffa14c68
--- /dev/null
+++ b/src/plugins/cpptools/cpppointerdeclarationformatter_test.cpp
@@ -0,0 +1,577 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "cpptoolsplugin.h"
+
+#include <AST.h>
+#include <CppDocument.h>
+#include <Symbols.h>
+#include <TranslationUnit.h>
+#include <pp.h>
+
+#include <cpptools/cpppointerdeclarationformatter.h>
+#include <cpptools/cpprefactoringchanges.h>
+#include <cpptools/cpptoolsplugin.h>
+#include <texteditor/plaintexteditor.h>
+#include <utils/changeset.h>
+#include <utils/fileutils.h>
+
+#include <QDebug>
+#include <QDir>
+#include <QTextCursor>
+#include <QTextDocument>
+#include <QtTest>
+
+using namespace CPlusPlus;
+using namespace CppTools;
+using namespace CppTools::Internal;
+
+using Utils::ChangeSet;
+typedef Utils::ChangeSet::Range Range;
+
+Q_DECLARE_METATYPE(Overview)
+
+static QString stripCursor(const QString &source)
+{
+ QString copy(source);
+ const int pos = copy.indexOf(QLatin1Char('@'));
+ if (pos != -1)
+ copy.remove(pos, 1);
+ else
+ qDebug() << Q_FUNC_INFO << "Warning: No cursor marker to strip.";
+ return copy;
+}
+
+struct TestEnvironment
+{
+ QByteArray source;
+ Snapshot snapshot;
+ CppRefactoringFilePtr cppRefactoringFile;
+ TextEditor::BaseTextEditorWidget *editor;
+ Document::Ptr document;
+ QTextDocument *textDocument;
+ TranslationUnit *translationUnit;
+ Environment env;
+
+ TestEnvironment(const QByteArray &source, Document::ParseMode parseMode)
+ {
+ // Find cursor position and remove cursor marker '@'
+ int cursorPosition = 0;
+ QString sourceWithoutCursorMarker = QLatin1String(source);
+ const int pos = sourceWithoutCursorMarker.indexOf(QLatin1Char('@'));
+ if (pos != -1) {
+ sourceWithoutCursorMarker.remove(pos, 1);
+ cursorPosition = pos;
+ }
+
+ // Write source to temprorary file
+ const QString filePath = QDir::tempPath() + QLatin1String("/file.h");
+ document = Document::create(filePath);
+ Utils::FileSaver documentSaver(document->fileName());
+ documentSaver.write(sourceWithoutCursorMarker.toLatin1());
+ documentSaver.finalize();
+
+ // Preprocess source
+ Preprocessor preprocess(0, &env);
+ const QByteArray preprocessedSource = preprocess.run(filePath, sourceWithoutCursorMarker);
+
+ document->setUtf8Source(preprocessedSource);
+ document->parse(parseMode);
+ document->check();
+ translationUnit = document->translationUnit();
+ snapshot.insert(document);
+ editor = new TextEditor::PlainTextEditorWidget(0);
+ QString error;
+ editor->open(&error, document->fileName(), document->fileName());
+
+ // Set cursor position
+ QTextCursor cursor = editor->textCursor();
+ cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::MoveAnchor, cursorPosition);
+ editor->setTextCursor(cursor);
+
+ textDocument = editor->document();
+ cppRefactoringFile = CppRefactoringChanges::file(editor, document);
+ }
+
+ void applyFormatting(AST *ast, PointerDeclarationFormatter::CursorHandling cursorHandling)
+ {
+ Overview overview;
+ overview.showReturnTypes = true;
+ overview.showArgumentNames = true;
+ overview.starBindFlags = Overview::StarBindFlags(0);
+
+ // Run the formatter
+ PointerDeclarationFormatter formatter(cppRefactoringFile, overview, cursorHandling);
+ ChangeSet change = formatter.format(ast); // ChangeSet may be empty.
+
+ // Apply change
+ QTextCursor cursor(textDocument);
+ change.apply(&cursor);
+ }
+};
+
+void CppToolsPlugin::test_format_pointerdeclaration_in_simpledeclarations()
+{
+ QFETCH(QString, source);
+ QFETCH(QString, reformattedSource);
+
+ TestEnvironment env(source.toLatin1(), Document::ParseDeclaration);
+ AST *ast = env.translationUnit->ast();
+ QVERIFY(ast);
+
+ env.applyFormatting(ast, PointerDeclarationFormatter::RespectCursor);
+
+ QCOMPARE(env.textDocument->toPlainText(), reformattedSource);
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_in_simpledeclarations_data()
+{
+ QTest::addColumn<QString>("source");
+ QTest::addColumn<QString>("reformattedSource");
+
+ QString source;
+
+ //
+ // Naming scheme for the test cases: <description>_(in|out)-(start|middle|end)
+ // in/out:
+ // Denotes whether the cursor is in or out of the quickfix activation range
+ // start/middle/end:
+ // Denotes whether is cursor is near to the range start, middle or end
+ //
+
+ QTest::newRow("basic_in-start")
+ << "@char *s;"
+ << "char * s;";
+
+ source = QLatin1String("char *s;@");
+ QTest::newRow("basic_out-end")
+ << source << stripCursor(source);
+
+ QTest::newRow("basic_in-end")
+ << "char *s@;"
+ << "char * s;";
+
+ QTest::newRow("basic-with-ws_in-start")
+ << "\n @char *s; " // Add some whitespace to check position detection.
+ << "\n char * s; ";
+
+ source = QLatin1String("\n @ char *s; ");
+ QTest::newRow("basic-with-ws_out-start")
+ << source << stripCursor(source);
+
+ QTest::newRow("basic-with-const_in-start")
+ << "@const char *s;"
+ << "const char * s;";
+
+ QTest::newRow("basic-with-const-and-init-value_in-end")
+ << "const char *s@ = 0;"
+ << "const char * s = 0;";
+
+ source = QLatin1String("const char *s @= 0;");
+ QTest::newRow("basic-with-const-and-init-value_out-end")
+ << source << stripCursor(source);
+
+ QTest::newRow("first-declarator_in-start")
+ << "@const char *s, *t;"
+ << "const char * s, *t;";
+
+ QTest::newRow("first-declarator_in-end")
+ << "const char *s@, *t;"
+ << "const char * s, *t;";
+
+ source = QLatin1String("const char *s,@ *t;");
+ QTest::newRow("first-declarator_out-end")
+ << source << stripCursor(source);
+
+ QTest::newRow("function-declaration-param_in-start")
+ << "int f(@char *s);"
+ << "int f(char * s);";
+
+ QTest::newRow("function-declaration-param_in-end")
+ << "int f(char *s@);"
+ << "int f(char * s);";
+
+ QTest::newRow("function-declaration-param_in-end")
+ << "int f(char *s@ = 0);"
+ << "int f(char * s = 0);";
+
+ QTest::newRow("function-declaration-param-multiple-params_in-end")
+ << "int f(char *s@, int);"
+ << "int f(char * s, int);";
+
+ source = QLatin1String("int f(char *s)@;");
+ QTest::newRow("function-declaration-param_out-end")
+ << source << stripCursor(source);
+
+ source = QLatin1String("int f@(char *s);");
+ QTest::newRow("function-declaration-param_out-start")
+ << source << stripCursor(source);
+
+ source = QLatin1String("int f(char *s =@ 0);");
+ QTest::newRow("function-declaration-param_out-end")
+ << source << stripCursor(source);
+
+ // Function definitions are handled by the same code as function
+ // declarations, so just check a minimal example.
+ QTest::newRow("function-definition-param_in-middle")
+ << "int f(char @*s) {}"
+ << "int f(char * s) {}";
+
+ QTest::newRow("function-declaration-returntype_in-start")
+ << "@char *f();"
+ << "char * f();";
+
+ QTest::newRow("function-declaration-returntype_in-end")
+ << "char *f@();"
+ << "char * f();";
+
+ source = QLatin1String("char *f(@);");
+ QTest::newRow("function-declaration-returntype_out-end")
+ << source << stripCursor(source);
+
+ QTest::newRow("function-definition-returntype_in-end")
+ << "char *f@() {}"
+ << "char * f() {}";
+
+ QTest::newRow("function-definition-returntype_in-start")
+ << "@char *f() {}"
+ << "char * f() {}";
+
+ source = QLatin1String("char *f(@) {}");
+ QTest::newRow("function-definition-returntype_out-end")
+ << source << stripCursor(source);
+
+ source = QLatin1String("inline@ char *f() {}");
+ QTest::newRow("function-definition-returntype-inline_out-start")
+ << source << stripCursor(source);
+
+ // Same code is also used for for other specifiers like virtual, inline, friend, ...
+ QTest::newRow("function-definition-returntype-static-inline_in-start")
+ << "static inline @char *f() {}"
+ << "static inline char * f() {}";
+
+ QTest::newRow("function-declaration-returntype-static-inline_in-start")
+ << "static inline @char *f();"
+ << "static inline char * f();";
+
+ source = QLatin1String("static inline@ char *f() {}");
+ QTest::newRow("function-definition-returntype-static-inline_out-start")
+ << source << stripCursor(source);
+
+ QTest::newRow("function-declaration-returntype-static-custom-type_in-start")
+ << "static @CustomType *f();"
+ << "static CustomType * f();";
+
+ source = QLatin1String("static@ CustomType *f();");
+ QTest::newRow("function-declaration-returntype-static-custom-type_out-start")
+ << source << stripCursor(source);
+
+ QTest::newRow("function-declaration-returntype-symbolvisibilityattributes_in-start")
+ << "__attribute__((visibility(\"default\"))) @char *f();"
+ << "__attribute__((visibility(\"default\"))) char * f();";
+
+ source = QLatin1String("@__attribute__((visibility(\"default\"))) char *f();");
+ QTest::newRow("function-declaration-returntype-symbolvisibilityattributes_out-start")
+ << source << stripCursor(source);
+
+ // The following two are not supported at the moment.
+ source = QLatin1String("@char * __attribute__((visibility(\"default\"))) f();");
+ QTest::newRow("function-declaration-returntype-symbolvisibilityattributes_out-start")
+ << source << stripCursor(source);
+
+ source = QLatin1String("@char * __attribute__((visibility(\"default\"))) f() {}");
+ QTest::newRow("function-definition-returntype-symbolvisibilityattributes_out-start")
+ << source << stripCursor(source);
+
+ // NOTE: Since __declspec() is not parsed (but defined to nothing),
+ // we can't detect it properly. Therefore, we fail on code with
+ // FOO_EXPORT macros with __declspec() for pointer return types;
+
+ QTest::newRow("typedef_in-start")
+ << "typedef @char *s;"
+ << "typedef char * s;";
+
+ source = QLatin1String("@typedef char *s;");
+ QTest::newRow("typedef_out-start")
+ << source << stripCursor(source);
+
+ QTest::newRow("static_in-start")
+ << "static @char *s;"
+ << "static char * s;";
+
+ QTest::newRow("pointerToFunction_in-start")
+ << "int (*bar)(@char *s);"
+ << "int (*bar)(char * s);";
+
+ source = QLatin1String("int (@*bar)();");
+ QTest::newRow("pointerToFunction_in-start")
+ << source << stripCursor(source);
+
+ source = QLatin1String("int (@*bar)[] = 0;");
+ QTest::newRow("pointerToArray_in-start")
+ << source << stripCursor(source);
+
+ //
+ // Additional test cases that does not fit into the naming scheme
+ //
+
+ // The following case is a side effect of the reformatting. Though
+ // the pointer type is according to the overview, the double space
+ // before 'char' gets corrected.
+ QTest::newRow("remove-extra-whitespace")
+ << "@const char * s = 0;"
+ << "const char * s = 0;";
+
+ // Nothing to pretty print since no pointer or references are involved.
+ source = QLatin1String("@char bla;"); // Two spaces to get sure nothing is reformatted.
+ QTest::newRow("precondition-fail-no-pointer")
+ << source << stripCursor(source);
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_in_controlflowstatements()
+{
+ QFETCH(QString, source);
+ QFETCH(QString, reformattedSource);
+
+ TestEnvironment env(source.toLatin1(), Document::ParseStatement);
+ AST *ast = env.translationUnit->ast();
+ QVERIFY(ast);
+
+ env.applyFormatting(ast, PointerDeclarationFormatter::RespectCursor);
+
+ QCOMPARE(env.textDocument->toPlainText(), reformattedSource);
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_in_controlflowstatements_data()
+{
+ QTest::addColumn<QString>("source");
+ QTest::addColumn<QString>("reformattedSource");
+
+ QString source;
+
+ //
+ // Same naming scheme as in test_format_pointerdeclaration_in_simpledeclarations_data()
+ //
+
+ QTest::newRow("if_in-start")
+ << "if (@char *s = 0);"
+ << "if (char * s = 0);";
+
+ source = QLatin1String("if @(char *s = 0);");
+ QTest::newRow("if_out-start")
+ << source << stripCursor(source);
+
+ QTest::newRow("if_in-end")
+ << "if (char *s@ = 0);"
+ << "if (char * s = 0);";
+
+ source = QLatin1String("if (char *s @= 0);");
+ QTest::newRow("if_out-end")
+ << source << stripCursor(source);
+
+ // if and for statements are handled by the same code, so just
+ // check minimal examples for these
+ QTest::newRow("while")
+ << "while (@char *s = 0);"
+ << "while (char * s = 0);";
+
+ QTest::newRow("for")
+ << "for (;@char *s = 0;);"
+ << "for (;char * s = 0;);";
+
+ // Should also work since it's a simple declaration
+ // for (char *s = 0; true;);
+
+ QTest::newRow("foreach_in-start")
+ << "foreach (@char *s, list);"
+ << "foreach (char * s, list);";
+
+ source = QLatin1String("foreach @(char *s, list);");
+ QTest::newRow("foreach-out-start")
+ << source << stripCursor(source);
+
+ QTest::newRow("foreach_in_end")
+ << "foreach (const char *s@, list);"
+ << "foreach (const char * s, list);";
+
+ source = QLatin1String("foreach (const char *s,@ list);");
+ QTest::newRow("foreach_out_end")
+ << source << stripCursor(source);
+
+ //
+ // Additional test cases that does not fit into the naming scheme
+ //
+
+ source = QLatin1String("@if (char s = 0);"); // Two spaces to get sure nothing is reformatted.
+ QTest::newRow("precondition-fail-no-pointer") << source << stripCursor(source);
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_multiple_declarators()
+{
+ QFETCH(QString, source);
+ QFETCH(QString, reformattedSource);
+
+ TestEnvironment env(source.toLatin1(), Document::ParseDeclaration);
+ AST *ast = env.translationUnit->ast();
+ QVERIFY(ast);
+
+ env.applyFormatting(ast, PointerDeclarationFormatter::RespectCursor);
+
+ QCOMPARE(env.textDocument->toPlainText(), reformattedSource);
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_multiple_declarators_data()
+{
+ QTest::addColumn<QString>("source");
+ QTest::addColumn<QString>("reformattedSource");
+
+ QString source;
+
+ QTest::newRow("function-declaration_in-start")
+ << "char *s = 0, @*f(int i) = 0;"
+ << "char *s = 0, * f(int i) = 0;";
+
+ QTest::newRow("non-pointer-before_in-start")
+ << "char c, @*t;"
+ << "char c, * t;";
+
+ QTest::newRow("pointer-before_in-start")
+ << "char *s, @*t;"
+ << "char *s, * t;";
+
+ QTest::newRow("pointer-before_in-end")
+ << "char *s, *t@;"
+ << "char *s, * t;";
+
+ source = QLatin1String("char *s,@ *t;");
+ QTest::newRow("md1-out_start")
+ << source << stripCursor(source);
+
+ source = QLatin1String("char *s, *t;@");
+ QTest::newRow("md1-out_end")
+ << source << stripCursor(source);
+
+ QTest::newRow("non-pointer-after_in-start")
+ << "char c, @*t, d;"
+ << "char c, * t, d;";
+
+ QTest::newRow("pointer-after_in-start")
+ << "char c, @*t, *d;"
+ << "char c, * t, *d;";
+
+ QTest::newRow("function-pointer_in-start")
+ << "char *s, @*(*foo)(char *s) = 0;"
+ << "char *s, *(*foo)(char * s) = 0;";
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_multiple_matches()
+{
+ QFETCH(QString, source);
+ QFETCH(QString, reformattedSource);
+
+ TestEnvironment env(source.toLatin1(), Document::ParseTranlationUnit);
+ AST *ast = env.translationUnit->ast();
+ QVERIFY(ast);
+
+ env.applyFormatting(ast, PointerDeclarationFormatter::IgnoreCursor);
+
+ QCOMPARE(env.textDocument->toPlainText(), reformattedSource);
+}
+
+void CppToolsPlugin::test_format_pointerdeclaration_multiple_matches_data()
+{
+ QTest::addColumn<QString>("source");
+ QTest::addColumn<QString>("reformattedSource");
+
+ QTest::newRow("rvalue-reference")
+ << "int g(Bar&&c) {}"
+ << "int g(Bar && c) {}";
+
+ QTest::newRow("if2")
+ << "int g() { if (char *s = 0) { char *t = 0; } }"
+ << "int g() { if (char * s = 0) { char * t = 0; } }";
+
+ QTest::newRow("if1")
+ << "int g() { if (int i = 0) { char *t = 0; } }"
+ << "int g() { if (int i = 0) { char * t = 0; } }";
+
+ QTest::newRow("for1")
+ << "int g() { for (char *s = 0; char *t = 0; s++); }"
+ << "int g() { for (char * s = 0; char * t = 0; s++); }";
+
+ QTest::newRow("for2")
+ << "int g() { for (char *s = 0; char *t = 0; s++) { char *u = 0; } }"
+ << "int g() { for (char * s = 0; char * t = 0; s++) { char * u = 0; } }";
+
+ QTest::newRow("for3")
+ << "int g() { for (char *s; char *t = 0; s++) { char *u = 0; } }"
+ << "int g() { for (char * s; char * t = 0; s++) { char * u = 0; } }";
+
+ QTest::newRow("multiple-declarators")
+ << "const char c, *s, *(*foo)(char *s) = 0;"
+ << "const char c, * s, *(*foo)(char * s) = 0;";
+
+ QTest::newRow("complex")
+ <<
+ "int *foo(const int &b, int*, int *&rpi)\n"
+ "{\n"
+ " int*pi = 0;\n"
+ " int*const*const cpcpi = &pi;\n"
+ " int*const*pcpi = &pi;\n"
+ " int**const cppi = &pi;\n"
+ "\n"
+ " void (*foo)(char *s) = 0;\n"
+ " int (*bar)[] = 0;\n"
+ "\n"
+ " char *s = 0, *f(int i) = 0;\n"
+ " const char c, *s, *(*foo)(char *s) = 0;"
+ "\n"
+ " for (char *s; char *t = 0; s++) { char *u = 0; }"
+ "\n"
+ " return 0;\n"
+ "}\n"
+ <<
+ "int * foo(const int & b, int *, int *& rpi)\n"
+ "{\n"
+ " int * pi = 0;\n"
+ " int * const * const cpcpi = &pi;\n"
+ " int * const * pcpi = &pi;\n"
+ " int ** const cppi = &pi;\n"
+ "\n"
+ " void (*foo)(char * s) = 0;\n"
+ " int (*bar)[] = 0;\n"
+ "\n"
+ " char * s = 0, * f(int i) = 0;\n"
+ " const char c, * s, *(*foo)(char * s) = 0;"
+ "\n"
+ " for (char * s; char * t = 0; s++) { char * u = 0; }"
+ "\n"
+ " return 0;\n"
+ "}\n";
+}
diff --git a/src/plugins/cpptools/cpptools.pro b/src/plugins/cpptools/cpptools.pro
index 1e0fbc7473..50ffa5d562 100644
--- a/src/plugins/cpptools/cpptools.pro
+++ b/src/plugins/cpptools/cpptools.pro
@@ -4,8 +4,6 @@ include(../../qtcreatorplugin.pri)
include($$IDE_SOURCE_TREE/src/plugins/locator/locator.pri)
include(cpptools_dependencies.pri)
-# DEFINES += QT_NO_CAST_FROM_ASCII
-DEFINES += QT_NO_CAST_TO_ASCII
INCLUDEPATH += .
DEFINES += CPPTOOLS_LIBRARY
HEADERS += completionsettingspage.h \
@@ -47,7 +45,10 @@ HEADERS += completionsettingspage.h \
cppsemanticinfo.h \
cppcompletionassistprovider.h \
ModelManagerInterface.h \
- TypeHierarchyBuilder.h
+ TypeHierarchyBuilder.h \
+ cppindexingsupport.h \
+ builtinindexingsupport.h \
+ cpppointerdeclarationformatter.h
SOURCES += completionsettingspage.cpp \
cppclassesfilter.cpp \
@@ -86,7 +87,10 @@ SOURCES += completionsettingspage.cpp \
cppsemanticinfo.cpp \
cppcompletionassistprovider.cpp \
ModelManagerInterface.cpp \
- TypeHierarchyBuilder.cpp
+ TypeHierarchyBuilder.cpp \
+ cppindexingsupport.cpp \
+ builtinindexingsupport.cpp \
+ cpppointerdeclarationformatter.cpp
FORMS += completionsettingspage.ui \
cppfilesettingspage.ui \
@@ -95,5 +99,13 @@ FORMS += completionsettingspage.ui \
equals(TEST, 1) {
SOURCES += \
cppcodegen_test.cpp \
- cppcompletion_test.cpp
+ cppcompletion_test.cpp \
+ cppmodelmanager_test.cpp \
+ modelmanagertesthelper.cpp \
+ cpppointerdeclarationformatter_test.cpp
+
+ HEADERS += \
+ modelmanagertesthelper.h
+
+ DEFINES += SRCDIR=\\\"$$PWD\\\"
}
diff --git a/src/plugins/cpptools/cpptools.qbs b/src/plugins/cpptools/cpptools.qbs
index 709f1edecb..dc02251a1f 100644
--- a/src/plugins/cpptools/cpptools.qbs
+++ b/src/plugins/cpptools/cpptools.qbs
@@ -1,6 +1,8 @@
import qbs.base 1.0
+import qbs.fileinfo as FileInfo
import "../QtcPlugin.qbs" as QtcPlugin
+import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "CppTools"
@@ -14,16 +16,11 @@ QtcPlugin {
Depends { name: "CPlusPlus" }
Depends { name: "LanguageUtils" }
- Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_NO_CAST_TO_ASCII"])
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
+ "ModelManagerInterface.cpp",
+ "ModelManagerInterface.h",
+ "TypeHierarchyBuilder.cpp",
+ "TypeHierarchyBuilder.h",
"abstracteditorsupport.cpp",
"abstracteditorsupport.h",
"commentssettings.cpp",
@@ -31,6 +28,8 @@ QtcPlugin {
"completionsettingspage.cpp",
"completionsettingspage.h",
"completionsettingspage.ui",
+ "cppchecksymbols.cpp",
+ "cppchecksymbols.h",
"cppclassesfilter.cpp",
"cppclassesfilter.h",
"cppcodeformatter.cpp",
@@ -38,6 +37,7 @@ QtcPlugin {
"cppcodestylepreferences.cpp",
"cppcodestylepreferences.h",
"cppcodestylepreferencesfactory.cpp",
+ "cppcodestylepreferencesfactory.h",
"cppcodestylesettings.cpp",
"cppcodestylesettings.h",
"cppcodestylesettingspage.cpp",
@@ -45,12 +45,14 @@ QtcPlugin {
"cppcodestylesettingspage.ui",
"cppcompletionassist.cpp",
"cppcompletionassist.h",
+ "cppcompletionassistprovider.cpp",
+ "cppcompletionassistprovider.h",
+ "cppcompletionsupport.cpp",
+ "cppcompletionsupport.h",
"cppcurrentdocumentfilter.cpp",
"cppcurrentdocumentfilter.h",
"cppdoxygen.cpp",
"cppdoxygen.h",
- "cppcompletionsupport.cpp",
- "cppcompletionsupport.h",
"cppfilesettingspage.cpp",
"cppfilesettingspage.h",
"cppfilesettingspage.ui",
@@ -58,24 +60,26 @@ QtcPlugin {
"cppfindreferences.h",
"cppfunctionsfilter.cpp",
"cppfunctionsfilter.h",
- "cpphighlightingsupportinternal.cpp",
- "cpphighlightingsupportinternal.h",
"cpphighlightingsupport.cpp",
"cpphighlightingsupport.h",
+ "cpphighlightingsupportinternal.cpp",
+ "cpphighlightingsupportinternal.h",
+ "cppindexingsupport.cpp",
+ "cppindexingsupport.h",
+ "cpplocalsymbols.cpp",
+ "cpplocalsymbols.h",
"cpplocatorfilter.cpp",
"cpplocatorfilter.h",
"cppmodelmanager.cpp",
"cppmodelmanager.h",
"cppqtstyleindenter.cpp",
"cppqtstyleindenter.h",
+ "cpppointerdeclarationformatter.cpp",
+ "cpppointerdeclarationformatter.h",
"cpprefactoringchanges.cpp",
"cpprefactoringchanges.h",
"cppsemanticinfo.cpp",
"cppsemanticinfo.h",
- "cppchecksymbols.cpp",
- "cppchecksymbols.h",
- "cpplocalsymbols.cpp",
- "cpplocalsymbols.h",
"cpptools_global.h",
"cpptoolsconstants.h",
"cpptoolseditorsupport.cpp",
@@ -98,17 +102,24 @@ QtcPlugin {
"symbolsfindfilter.h",
"uicodecompletionsupport.cpp",
"uicodecompletionsupport.h",
- "cppcompletionassistprovider.cpp",
- "cppcompletionassistprovider.h",
- "cppcodestylepreferencesfactory.h",
- "ModelManagerInterface.cpp",
- "ModelManagerInterface.h",
- "TypeHierarchyBuilder.cpp",
- "TypeHierarchyBuilder.h"
+ "builtinindexingsupport.cpp",
+ "builtinindexingsupport.h"
]
+ Group {
+ condition: Defaults.testsEnabled(qbs)
+ files: [
+ "cppcodegen_test.cpp",
+ "cppcompletion_test.cpp",
+ "cppmodelmanager_test.cpp",
+ "modelmanagertesthelper.cpp", "modelmanagertesthelper.h",
+ "cpppointerdeclarationformatter_test.cpp"
+ ]
+
+ cpp.defines: outer.concat(['SRCDIR="' + FileInfo.path(filePath) + '"'])
+ }
+
ProductModule {
Depends { name: "CPlusPlus" }
}
}
-
diff --git a/src/plugins/cpptools/cpptoolseditorsupport.cpp b/src/plugins/cpptools/cpptoolseditorsupport.cpp
index dcf64733ab..0afb194be2 100644
--- a/src/plugins/cpptools/cpptoolseditorsupport.cpp
+++ b/src/plugins/cpptools/cpptoolseditorsupport.cpp
@@ -108,9 +108,8 @@ void CppEditorSupport::updateDocument()
{
_revision = editorRevision();
- if (qobject_cast<TextEditor::BaseTextEditorWidget*>(_textEditor->widget()) != 0) {
+ if (qobject_cast<TextEditor::BaseTextEditorWidget*>(_textEditor->widget()) != 0)
_modelManager->stopEditorSelectionsUpdate();
- }
_updateDocumentTimer->start(_updateDocumentInterval);
}
@@ -123,8 +122,8 @@ void CppEditorSupport::updateDocumentNow()
_updateDocumentTimer->stop();
QStringList sourceFiles(_textEditor->document()->fileName());
- _cachedContents = _textEditor->contents().toUtf8();
- _documentParser = _modelManager->refreshSourceFiles(sourceFiles);
+ _cachedContents = _textEditor->contents();
+ _documentParser = _modelManager->updateSourceFiles(sourceFiles);
}
}
diff --git a/src/plugins/cpptools/cpptoolsplugin.cpp b/src/plugins/cpptools/cpptoolsplugin.cpp
index 0342ab3285..ac5e0ff2f9 100644
--- a/src/plugins/cpptools/cpptoolsplugin.cpp
+++ b/src/plugins/cpptools/cpptoolsplugin.cpp
@@ -39,6 +39,7 @@
#include "cpplocatorfilter.h"
#include "symbolsfindfilter.h"
#include "cpptoolssettings.h"
+#include "cpptoolsreuse.h"
#include <extensionsystem/pluginmanager.h>
@@ -54,6 +55,7 @@
#include <coreplugin/vcsmanager.h>
#include <coreplugin/documentmanager.h>
#include <cppeditor/cppeditorconstants.h>
+#include <texteditor/basetexteditor.h>
#include <QtConcurrentRun>
#include <QFutureSynchronizer>
@@ -74,15 +76,17 @@
#include <sstream>
-using namespace CppTools::Internal;
using namespace CPlusPlus;
+namespace CppTools {
+namespace Internal {
+
enum { debug = 0 };
static CppToolsPlugin *m_instance = 0;
+static QHash<QString, QString> m_headerSourceMapping;
CppToolsPlugin::CppToolsPlugin() :
- m_modelManager(0),
m_fileSettings(new CppFileSettings)
{
m_instance = this;
@@ -91,7 +95,7 @@ CppToolsPlugin::CppToolsPlugin() :
CppToolsPlugin::~CppToolsPlugin()
{
m_instance = 0;
- m_modelManager = 0; // deleted automatically
+ delete CppModelManager::instance();
}
bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
@@ -102,20 +106,19 @@ bool CppToolsPlugin::initialize(const QStringList &arguments, QString *error)
m_settings = new CppToolsSettings(this); // force registration of cpp tools settings
// Objects
- m_modelManager = new CppModelManager(this);
+ CppModelManager *modelManager = CppModelManager::instance();
Core::VcsManager *vcsManager = Core::ICore::vcsManager();
connect(vcsManager, SIGNAL(repositoryChanged(QString)),
- m_modelManager, SLOT(updateModifiedSourceFiles()));
+ modelManager, SLOT(updateModifiedSourceFiles()));
connect(Core::DocumentManager::instance(), SIGNAL(filesChangedInternally(QStringList)),
- m_modelManager, SLOT(updateSourceFiles(QStringList)));
- addAutoReleasedObject(m_modelManager);
+ modelManager, SLOT(updateSourceFiles(QStringList)));
- addAutoReleasedObject(new CppLocatorFilter(m_modelManager));
- addAutoReleasedObject(new CppClassesFilter(m_modelManager));
- addAutoReleasedObject(new CppFunctionsFilter(m_modelManager));
- addAutoReleasedObject(new CppCurrentDocumentFilter(m_modelManager, Core::ICore::editorManager()));
+ addAutoReleasedObject(new CppLocatorFilter(modelManager));
+ addAutoReleasedObject(new CppClassesFilter(modelManager));
+ addAutoReleasedObject(new CppFunctionsFilter(modelManager));
+ addAutoReleasedObject(new CppCurrentDocumentFilter(modelManager, Core::ICore::editorManager()));
addAutoReleasedObject(new CppFileSettingsPage(m_fileSettings));
- addAutoReleasedObject(new SymbolsFindFilter(m_modelManager));
+ addAutoReleasedObject(new SymbolsFindFilter(modelManager));
addAutoReleasedObject(new CppCodeStyleSettingsPage);
// Menus
@@ -156,8 +159,31 @@ void CppToolsPlugin::switchHeaderSource()
{
Core::IEditor *editor = Core::EditorManager::currentEditor();
QString otherFile = correspondingHeaderOrSource(editor->document()->fileName());
- if (!otherFile.isEmpty())
- Core::EditorManager::openEditor(otherFile);
+ if (otherFile.isEmpty())
+ return;
+
+ Core::EditorManager* editorManager = Core::EditorManager::instance();
+ editorManager->addCurrentPositionToNavigationHistory();
+ TextEditor::BaseTextEditorWidget *ed = qobject_cast<TextEditor::BaseTextEditorWidget *>(editor->widget());
+ if (editorManager->hasSplitter()) {
+ if (ed->forceOpenLinksInNextSplit()) {
+ editorManager->gotoOtherSplit();
+ } else if (ed->openLinksInNextSplit()) {
+ bool isVisible = false;
+ foreach (Core::IEditor *visEditor, editorManager->visibleEditors()) {
+ if (visEditor->document() &&
+ (otherFile == visEditor->document()->fileName())) {
+ isVisible = true;
+ editorManager->activateEditor(visEditor);
+ break;
+ }
+ }
+
+ if (!isVisible)
+ editorManager->gotoOtherSplit();
+ }
+ }
+ Core::EditorManager::openEditor(otherFile);
}
static QStringList findFilesInProject(const QString &name,
@@ -190,9 +216,9 @@ enum FileType {
UnknownType
};
-static inline FileType fileType(const Core::MimeDatabase *mimeDatase, const QFileInfo & fi)
+static inline FileType fileType(const Core::MimeDatabase *mimeDatabase, const QFileInfo & fi)
{
- const Core::MimeType mimeType = mimeDatase->findByFile(fi);
+ const Core::MimeType mimeType = mimeDatabase->findByFile(fi);
if (!mimeType)
return UnknownType;
const QString typeName = mimeType.type();
@@ -210,20 +236,20 @@ static inline FileType fileType(const Core::MimeDatabase *mimeDatase, const QFi
// Return the suffixes that should be checked when trying to find a
// source belonging to a header and vice versa
-static QStringList matchingCandidateSuffixes(const Core::MimeDatabase *mimeDatase, FileType type)
+static QStringList matchingCandidateSuffixes(const Core::MimeDatabase *mimeDatabase, FileType type)
{
switch (type) {
case UnknownType:
break;
case HeaderFile: // Note that C/C++ headers are undistinguishable
- return mimeDatase->findByType(QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)).suffixes()
- + mimeDatase->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes()
- + mimeDatase->findByType(QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
+ return mimeDatabase->findByType(QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)).suffixes()
+ + mimeDatabase->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes()
+ + mimeDatabase->findByType(QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes();
case C_SourceFile:
- return mimeDatase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
+ return mimeDatabase->findByType(QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)).suffixes();
case CPP_SourceFile:
case ObjectiveCPP_SourceFile:
- return mimeDatase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
+ return mimeDatabase->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).suffixes();
}
return QStringList();
}
@@ -250,16 +276,23 @@ static int commonStringLength(const QString &s1, const QString &s2)
return length;
}
-QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) const
+} // namespace Internal
+
+QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader)
{
+ using namespace Internal;
+
+ const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
const QFileInfo fi(fileName);
- if (m_headerSourceMapping.contains(fi.absoluteFilePath()))
+ if (m_headerSourceMapping.contains(fi.absoluteFilePath())) {
+ if (wasHeader)
+ *wasHeader = fileType(mimeDatabase, fi) == HeaderFile;
return m_headerSourceMapping.value(fi.absoluteFilePath());
+ }
- const Core::MimeDatabase *mimeDatase = Core::ICore::mimeDatabase();
- ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
-
- const FileType type = fileType(mimeDatase, fi);
+ FileType type = fileType(mimeDatabase, fi);
+ if (wasHeader)
+ *wasHeader = type == HeaderFile;
if (debug)
qDebug() << Q_FUNC_INFO << fileName << type;
@@ -269,7 +302,7 @@ QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) co
const QString baseName = fi.completeBaseName();
const QString privateHeaderSuffix = QLatin1String("_p");
- const QStringList suffixes = matchingCandidateSuffixes(mimeDatase, type);
+ const QStringList suffixes = matchingCandidateSuffixes(mimeDatabase, type);
QStringList candidateFileNames = baseNameWithAllSuffixes(baseName, suffixes);
if (type == HeaderFile) {
@@ -298,6 +331,7 @@ QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) co
}
// Find files in the project
+ ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
if (project) {
QString bestFileName;
int compareValue = 0;
@@ -324,12 +358,6 @@ QString CppToolsPlugin::correspondingHeaderOrSourceI(const QString &fileName) co
return QString();
}
-QString CppToolsPlugin::correspondingHeaderOrSource(const QString &fileName)
-{
- const QString rc = m_instance->correspondingHeaderOrSourceI(fileName);
- if (debug)
- qDebug() << Q_FUNC_INFO << fileName << rc;
- return rc;
-}
+} // namespace CppTools
-Q_EXPORT_PLUGIN(CppToolsPlugin)
+Q_EXPORT_PLUGIN(CppTools::Internal::CppToolsPlugin)
diff --git a/src/plugins/cpptools/cpptoolsplugin.h b/src/plugins/cpptools/cpptoolsplugin.h
index a36acac43e..b53fe75065 100644
--- a/src/plugins/cpptools/cpptoolsplugin.h
+++ b/src/plugins/cpptools/cpptoolsplugin.h
@@ -30,6 +30,8 @@
#ifndef CPPTOOLS_H
#define CPPTOOLS_H
+#include "cpptools_global.h"
+
#include <extensionsystem/iplugin.h>
#include <projectexplorer/projectexplorer.h>
#include <find/ifindfilter.h>
@@ -69,14 +71,11 @@ public:
bool initialize(const QStringList &arguments, QString *errorMessage);
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
- CppModelManager *cppModelManager() { return m_modelManager; }
- static QString correspondingHeaderOrSource(const QString &fileName);
private slots:
void switchHeaderSource();
-#ifdef WITH_TESTS
- // codegen tests
+#ifdef WITH_TESTS
void test_codegen_public_in_empty_class();
void test_codegen_public_in_nonempty_class();
void test_codegen_public_before_protected();
@@ -90,6 +89,8 @@ private slots:
void test_codegen_definition_middle_member();
void test_completion_forward_declarations_present();
+ void test_completion_inside_parentheses_c_style_conversion();
+ void test_completion_inside_parentheses_cast_operator_conversion();
void test_completion_basic_1();
void test_completion_template_1();
void test_completion_template_2();
@@ -97,6 +98,9 @@ private slots:
void test_completion_template_4();
void test_completion_template_5();
void test_completion_template_6();
+ void test_completion_template_7();
+ void test_completion_type_of_pointer_is_typedef();
+ void test_completion_instantiate_full_specialization();
void test_completion_template_as_base();
void test_completion_template_as_base_data();
void test_completion_use_global_identifier_as_base_class();
@@ -105,18 +109,31 @@ private slots:
void test_completion_base_class_has_name_the_same_as_derived_data();
void test_completion_cyclic_inheritance();
void test_completion_cyclic_inheritance_data();
+ void test_completion_enclosing_template_class();
+ void test_completion_enclosing_template_class_data();
+ void test_completion_instantiate_nested_class_when_enclosing_is_template();
+ void test_completion_instantiate_nested_of_nested_class_when_enclosing_is_template();
+ void test_completion_member_access_operator_1();
+
+ void test_format_pointerdeclaration_in_simpledeclarations();
+ void test_format_pointerdeclaration_in_simpledeclarations_data();
+ void test_format_pointerdeclaration_in_controlflowstatements();
+ void test_format_pointerdeclaration_in_controlflowstatements_data();
+ void test_format_pointerdeclaration_multiple_declarators();
+ void test_format_pointerdeclaration_multiple_declarators_data();
+ void test_format_pointerdeclaration_multiple_matches();
+ void test_format_pointerdeclaration_multiple_matches_data();
+
+ void test_modelmanager_paths();
+ void test_modelmanager_framework_headers();
private:
void test_completion();
#endif
private:
- QString correspondingHeaderOrSourceI(const QString &fileName) const;
-
- CppModelManager *m_modelManager;
QSharedPointer<CppFileSettings> m_fileSettings;
CppToolsSettings *m_settings;
- mutable QHash<QString, QString> m_headerSourceMapping;
};
} // namespace Internal
diff --git a/src/plugins/cpptools/cpptoolsreuse.h b/src/plugins/cpptools/cpptoolsreuse.h
index ee3016c259..d1eed216f9 100644
--- a/src/plugins/cpptools/cpptoolsreuse.h
+++ b/src/plugins/cpptools/cpptoolsreuse.h
@@ -52,6 +52,8 @@ bool CPPTOOLS_EXPORT isValidIdentifier(const QString &s);
bool CPPTOOLS_EXPORT isQtKeyword(const QStringRef &text);
+QString CPPTOOLS_EXPORT correspondingHeaderOrSource(const QString &fileName, bool *wasHeader = 0);
+
} // CppTools
#endif // CPPTOOLSREUSE_H
diff --git a/src/plugins/cpptools/cpptoolssettings.cpp b/src/plugins/cpptools/cpptoolssettings.cpp
index e17cd21c0f..c1c74059fe 100644
--- a/src/plugins/cpptools/cpptoolssettings.cpp
+++ b/src/plugins/cpptools/cpptoolssettings.cpp
@@ -45,7 +45,7 @@
#include <coreplugin/icore.h>
#include <QSettings>
-static const char *idKey = "CppGlobal";
+static const char idKey[] = "CppGlobal";
using namespace CppTools;
using namespace CppTools::Internal;
@@ -102,7 +102,7 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
d->m_globalCodeStyle = new CppCodeStylePreferences(this);
d->m_globalCodeStyle->setDelegatingPool(pool);
d->m_globalCodeStyle->setDisplayName(tr("Global", "Settings"));
- d->m_globalCodeStyle->setId(idKey);
+ d->m_globalCodeStyle->setId(QLatin1String(idKey));
pool->addCodeStyle(d->m_globalCodeStyle);
textEditorSettings->registerCodeStyle(CppTools::Constants::CPP_SETTINGS_ID, d->m_globalCodeStyle);
@@ -171,7 +171,7 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
// load global settings (after built-in settings are added to the pool)
QSettings *s = Core::ICore::settings();
- d->m_globalCodeStyle->fromSettings(CppTools::Constants::CPP_SETTINGS_ID, Core::ICore::settings());
+ d->m_globalCodeStyle->fromSettings(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID), Core::ICore::settings());
// legacy handling start (Qt Creator Version < 2.4)
const bool legacyTransformed =
@@ -214,7 +214,7 @@ CppToolsSettings::CppToolsSettings(QObject *parent)
// change the current delegate and save
d->m_globalCodeStyle->setCurrentDelegate(oldCreator);
- d->m_globalCodeStyle->toSettings(CppTools::Constants::CPP_SETTINGS_ID, s);
+ d->m_globalCodeStyle->toSettings(QLatin1String(CppTools::Constants::CPP_SETTINGS_ID), s);
}
// mark old settings as transformed
s->setValue(QLatin1String("CppCodeStyleSettings/LegacyTransformed"), true);
diff --git a/src/plugins/cpptools/insertionpointlocator.cpp b/src/plugins/cpptools/insertionpointlocator.cpp
index 1960e781dd..3cc3cf6f77 100644
--- a/src/plugins/cpptools/insertionpointlocator.cpp
+++ b/src/plugins/cpptools/insertionpointlocator.cpp
@@ -27,7 +27,7 @@
**
****************************************************************************/
-#include "cpptoolsplugin.h"
+#include "cpptoolsreuse.h"
#include "cpprefactoringchanges.h"
#include "insertionpointlocator.h"
#include "symbolfinder.h"
@@ -95,18 +95,27 @@ struct AccessRange
unsigned start;
unsigned end;
InsertionPointLocator::AccessSpec xsSpec;
+ unsigned colonToken;
AccessRange()
: start(0)
, end(0)
, xsSpec(InsertionPointLocator::Invalid)
+ , colonToken(0)
{}
- AccessRange(unsigned start, unsigned end, InsertionPointLocator::AccessSpec xsSpec)
+ AccessRange(unsigned start, unsigned end, InsertionPointLocator::AccessSpec xsSpec, unsigned colonToken)
: start(start)
, end(end)
, xsSpec(xsSpec)
+ , colonToken(colonToken)
{}
+
+ bool isEmpty() const
+ {
+ unsigned contentStart = 1 + (colonToken ? colonToken : start);
+ return contentStart == end;
+ }
};
class FindInClass: public ASTVisitor
@@ -146,16 +155,19 @@ protected:
ast->rbrace_token);
unsigned beforeToken = 0;
+ bool needsLeadingEmptyLine = false;
bool needsPrefix = false;
bool needsSuffix = false;
- findMatch(ranges, _xsSpec, beforeToken, needsPrefix, needsSuffix);
+ findMatch(ranges, _xsSpec, beforeToken, needsLeadingEmptyLine, needsPrefix, needsSuffix);
unsigned line = 0, column = 0;
getTokenStartPosition(beforeToken, &line, &column);
QString prefix;
+ if (needsLeadingEmptyLine)
+ prefix += QLatin1String("\n");
if (needsPrefix)
- prefix = generate(_xsSpec);
+ prefix += generate(_xsSpec);
QString suffix;
if (needsSuffix)
@@ -169,12 +181,15 @@ protected:
static void findMatch(const QList<AccessRange> &ranges,
InsertionPointLocator::AccessSpec xsSpec,
unsigned &beforeToken,
+ bool &needsLeadingEmptyLine,
bool &needsPrefix,
bool &needsSuffix)
{
QTC_ASSERT(!ranges.isEmpty(), return);
const int lastIndex = ranges.size() - 1;
+ needsLeadingEmptyLine = false;
+
// try an exact match, and ignore the first (default) access spec:
for (int i = lastIndex; i > 0; --i) {
const AccessRange &range = ranges.at(i);
@@ -200,6 +215,7 @@ protected:
// otherwise:
beforeToken = ranges.first().end;
+ needsLeadingEmptyLine = !ranges.first().isEmpty();
needsPrefix = true;
needsSuffix = (ranges.size() != 1);
}
@@ -210,14 +226,14 @@ protected:
int lastRangeEnd) const
{
QList<AccessRange> ranges;
- ranges.append(AccessRange(firstRangeStart, lastRangeEnd, initialXs));
+ ranges.append(AccessRange(firstRangeStart, lastRangeEnd, initialXs, 0));
for (DeclarationListAST *iter = decls; iter; iter = iter->next) {
DeclarationAST *decl = iter->value;
if (AccessDeclarationAST *xsDecl = decl->asAccessDeclaration()) {
const unsigned token = xsDecl->access_specifier_token;
- int newXsSpec = initialXs;
+ InsertionPointLocator::AccessSpec newXsSpec = initialXs;
bool isSlot = xsDecl->slots_token
&& tokenKind(xsDecl->slots_token) == T_Q_SLOTS;
@@ -242,7 +258,8 @@ protected:
break;
case T_Q_SLOTS: {
- newXsSpec = ranges.last().xsSpec | InsertionPointLocator::SlotBit;
+ newXsSpec = (InsertionPointLocator::AccessSpec)
+ (ranges.last().xsSpec | InsertionPointLocator::SlotBit);
break;
}
@@ -250,9 +267,10 @@ protected:
break;
}
- if (newXsSpec != ranges.last().xsSpec) {
+ if (newXsSpec != ranges.last().xsSpec || ranges.size() == 1) {
ranges.last().end = token;
- ranges.append(AccessRange(token, lastRangeEnd, (InsertionPointLocator::AccessSpec) newXsSpec));
+ AccessRange r(token, lastRangeEnd, newXsSpec, xsDecl->colon_token);
+ ranges.append(r);
}
}
}
@@ -528,14 +546,14 @@ static InsertionLocation nextToSurroundingDefinitions(Declaration *declaration,
if (!definitionFunction)
return noResult;
- Document::Ptr targetDoc = changes.snapshot().document(definition->fileName());
+ Document::Ptr targetDoc = changes.snapshot().document(QString::fromUtf8(definition->fileName()));
if (!targetDoc)
return noResult;
targetDoc->translationUnit()->getPosition(definitionFunction->endOffset(), &line, &column);
} else {
// we don't have an offset to the start of the function definition, so we need to manually find it...
- CppRefactoringFilePtr targetFile = changes.file(definition->fileName());
+ CppRefactoringFilePtr targetFile = changes.file(QString::fromUtf8(definition->fileName()));
if (!targetFile->isValid())
return noResult;
@@ -547,7 +565,7 @@ static InsertionLocation nextToSurroundingDefinitions(Declaration *declaration,
targetFile->cppDocument()->translationUnit()->getTokenStartPosition(functionDefinition->firstToken(), &line, &column);
}
- return InsertionLocation(definition->fileName(), prefix, suffix, line, column);
+ return InsertionLocation(QString::fromUtf8(definition->fileName()), prefix, suffix, line, column);
}
QList<InsertionLocation> InsertionPointLocator::methodDefinition(
@@ -578,7 +596,7 @@ QList<InsertionLocation> InsertionPointLocator::methodDefinition(
declaration->fileNameLength());
QString target = declFileName;
if (!isSourceFile(declFileName)) {
- QString candidate = Internal::CppToolsPlugin::correspondingHeaderOrSource(declFileName);
+ QString candidate = CppTools::correspondingHeaderOrSource(declFileName);
if (!candidate.isEmpty())
target = candidate;
}
diff --git a/src/plugins/cpptools/modelmanagertesthelper.cpp b/src/plugins/cpptools/modelmanagertesthelper.cpp
new file mode 100644
index 0000000000..a9b3409030
--- /dev/null
+++ b/src/plugins/cpptools/modelmanagertesthelper.cpp
@@ -0,0 +1,99 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "modelmanagertesthelper.h"
+
+#include <QtTest>
+
+#include <cassert>
+
+using namespace CppTools::Internal;
+
+TestProject::TestProject(const QString &name, QObject *parent)
+ : m_name (name)
+{
+ setParent(parent);
+}
+
+TestProject::~TestProject()
+{
+}
+
+ModelManagerTestHelper::ModelManagerTestHelper(QObject *parent) :
+ QObject(parent)
+
+{
+ CppModelManager *mm = CppModelManager::instance();
+ assert(mm);
+
+ connect(this, SIGNAL(aboutToRemoveProject(ProjectExplorer::Project*)), mm, SLOT(onAboutToRemoveProject(ProjectExplorer::Project*)));
+ connect(this, SIGNAL(projectAdded(ProjectExplorer::Project*)), mm, SLOT(onProjectAdded(ProjectExplorer::Project*)));
+
+ cleanup();
+ verifyClean();
+}
+
+ModelManagerTestHelper::~ModelManagerTestHelper()
+{
+ cleanup();
+ verifyClean();
+}
+
+void ModelManagerTestHelper::cleanup()
+{
+ CppModelManager *mm = CppModelManager::instance();
+ assert(mm);
+
+ QList<ProjectInfo> pies = mm->projectInfos();
+ foreach (const ProjectInfo &pie, pies)
+ emit aboutToRemoveProject(pie.project().data());
+}
+
+void ModelManagerTestHelper::verifyClean()
+{
+ CppModelManager *mm = CppModelManager::instance();
+ assert(mm);
+
+ QVERIFY(mm->projectInfos().isEmpty());
+ QVERIFY(mm->includePaths().isEmpty());
+ QVERIFY(mm->frameworkPaths().isEmpty());
+ QVERIFY(mm->definedMacros().isEmpty());
+ QVERIFY(mm->projectFiles().isEmpty());
+ QVERIFY(mm->snapshot().isEmpty());
+ QCOMPARE(mm->workingCopy().size(), 1);
+ QVERIFY(mm->workingCopy().contains(mm->configurationFileName()));
+}
+
+ModelManagerTestHelper::Project *ModelManagerTestHelper::createProject(const QString &name)
+{
+ TestProject *tp = new TestProject(name, this);
+ emit projectAdded(tp);
+ return tp;
+}
+
diff --git a/src/plugins/cpptools/modelmanagertesthelper.h b/src/plugins/cpptools/modelmanagertesthelper.h
new file mode 100644
index 0000000000..f0e1a2af29
--- /dev/null
+++ b/src/plugins/cpptools/modelmanagertesthelper.h
@@ -0,0 +1,94 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CPPTOOLS_INTERNAL_MODELMANAGERTESTHELPER_H
+#define CPPTOOLS_INTERNAL_MODELMANAGERTESTHELPER_H
+
+#include "cppmodelmanager.h"
+
+#include <QObject>
+
+namespace CppTools {
+namespace Internal {
+
+class TestProject: public ProjectExplorer::Project
+{
+ Q_OBJECT
+
+public:
+ TestProject(const QString &name, QObject *parent);
+ virtual ~TestProject();
+
+ virtual QString displayName() const
+ { return m_name; }
+
+ virtual Core::Id id() const
+ { return Core::Id::fromString(m_name); }
+
+ virtual Core::IDocument *document() const
+ { return 0; }
+
+ virtual ProjectExplorer::IProjectManager *projectManager() const
+ { return 0; }
+
+ virtual ProjectExplorer::ProjectNode *rootProjectNode() const
+ { return 0; }
+
+ virtual QStringList files(FilesMode fileMode) const
+ { Q_UNUSED(fileMode); return QStringList(); }
+
+private:
+ QString m_name;
+};
+
+class ModelManagerTestHelper: public QObject
+{
+ Q_OBJECT
+
+public:
+ typedef CPlusPlus::CppModelManagerInterface::ProjectInfo ProjectInfo;
+ typedef ProjectExplorer::Project Project;
+
+ explicit ModelManagerTestHelper(QObject *parent = 0);
+ ~ModelManagerTestHelper();
+
+ void cleanup();
+ void verifyClean();
+
+ Project *createProject(const QString &name);
+
+signals:
+ void aboutToRemoveProject(ProjectExplorer::Project *project);
+ void projectAdded(ProjectExplorer::Project*);
+};
+
+} // namespace Internal
+} // namespace CppTools
+
+#endif // CPPTOOLS_INTERNAL_MODELMANAGERTESTHELPER_H
diff --git a/src/plugins/cpptools/searchsymbols.cpp b/src/plugins/cpptools/searchsymbols.cpp
index 8d3aff747b..9641d70b06 100644
--- a/src/plugins/cpptools/searchsymbols.cpp
+++ b/src/plugins/cpptools/searchsymbols.cpp
@@ -39,13 +39,13 @@ using namespace CPlusPlus;
using namespace CppTools;
SearchSymbols::SymbolTypes SearchSymbols::AllTypes =
- SearchSymbols::Classes
- | SearchSymbols::Functions
- | SearchSymbols::Enums
- | SearchSymbols::Declarations;
+ SymbolSearcher::Classes
+ | SymbolSearcher::Functions
+ | SymbolSearcher::Enums
+ | SymbolSearcher::Declarations;
SearchSymbols::SearchSymbols():
- symbolsToSearchFor(Classes | Functions | Enums),
+ symbolsToSearchFor(SymbolSearcher::Classes | SymbolSearcher::Functions | SymbolSearcher::Enums),
separateScope(false)
{
}
@@ -84,7 +84,7 @@ QString SearchSymbols::switchScope(const QString &scope)
bool SearchSymbols::visit(Enum *symbol)
{
- if (!(symbolsToSearchFor & Enums))
+ if (!(symbolsToSearchFor & SymbolSearcher::Enums))
return false;
QString name = symbolName(symbol);
@@ -102,7 +102,7 @@ bool SearchSymbols::visit(Enum *symbol)
bool SearchSymbols::visit(Function *symbol)
{
- if (!(symbolsToSearchFor & Functions))
+ if (!(symbolsToSearchFor & SymbolSearcher::Functions))
return false;
QString extraScope;
@@ -139,7 +139,7 @@ bool SearchSymbols::visit(Namespace *symbol)
bool SearchSymbols::visit(Declaration *symbol)
{
- if (!(symbolsToSearchFor & Declarations))
+ if (!(symbolsToSearchFor & SymbolSearcher::Declarations))
return false;
QString name = symbolName(symbol);
@@ -157,7 +157,7 @@ bool SearchSymbols::visit(Class *symbol)
QString name = symbolName(symbol);
QString scopedName = scopedSymbolName(name);
QString previousScope = switchScope(scopedName);
- if (symbolsToSearchFor & Classes) {
+ if (symbolsToSearchFor & SymbolSearcher::Classes) {
appendItem(separateScope ? name : scopedName,
separateScope ? previousScope : QString(),
ModelItemInfo::Class, symbol);
@@ -278,13 +278,12 @@ QString SearchSymbols::symbolName(const Symbol *symbol) const
} else if (symbol->isEnum()) {
type = QLatin1String("enum");
} else if (const Class *c = symbol->asClass()) {
- if (c->isUnion()) {
+ if (c->isUnion())
type = QLatin1String("union");
- } else if (c->isStruct()) {
+ else if (c->isStruct())
type = QLatin1String("struct");
- } else {
+ else
type = QLatin1String("class");
- }
} else {
type = QLatin1String("symbol");
}
diff --git a/src/plugins/cpptools/searchsymbols.h b/src/plugins/cpptools/searchsymbols.h
index 8357c28084..b29c0c00fb 100644
--- a/src/plugins/cpptools/searchsymbols.h
+++ b/src/plugins/cpptools/searchsymbols.h
@@ -32,6 +32,8 @@
#include "cpptools_global.h"
+#include "cppindexingsupport.h"
+
#include <cplusplus/CppDocument.h>
#include <cplusplus/Icons.h>
#include <cplusplus/Overview.h>
@@ -101,14 +103,7 @@ class SearchSymbols: public std::unary_function<CPlusPlus::Document::Ptr, QList<
protected CPlusPlus::SymbolVisitor
{
public:
- enum SymbolType {
- Classes = 0x1,
- Functions = 0x2,
- Enums = 0x4,
- Declarations = 0x8
- };
-
- Q_DECLARE_FLAGS(SymbolTypes, SymbolType)
+ typedef SymbolSearcher::SymbolTypes SymbolTypes;
static SymbolTypes AllTypes;
@@ -181,7 +176,6 @@ private:
} // namespace CppTools
Q_DECLARE_OPERATORS_FOR_FLAGS(CppTools::SearchSymbols::SymbolTypes)
-Q_DECLARE_METATYPE(CppTools::SearchSymbols::SymbolTypes)
Q_DECLARE_METATYPE(CppTools::ModelItemInfo)
#endif // SEARCHSYMBOLS_H
diff --git a/src/plugins/cpptools/symbolsfindfilter.cpp b/src/plugins/cpptools/symbolsfindfilter.cpp
index eb91bd12a8..bc352a30f3 100644
--- a/src/plugins/cpptools/symbolsfindfilter.cpp
+++ b/src/plugins/cpptools/symbolsfindfilter.cpp
@@ -55,67 +55,13 @@ namespace {
const char * const SETTINGS_GROUP = "CppSymbols";
const char * const SETTINGS_SYMBOLTYPES = "SymbolsToSearchFor";
const char * const SETTINGS_SEARCHSCOPE = "SearchScope";
-
- void runSearch(QFutureInterface<Find::SearchResultItem> &future,
- SymbolsFindParameters parameters, CPlusPlus::Snapshot snapshot,
- QSet<QString> fileNames)
- {
- future.setProgressRange(0, snapshot.size());
- future.setProgressValue(0);
- int progress = 0;
-
- SearchSymbols search;
- search.setSymbolsToSearchFor(parameters.types);
- search.setSeparateScope(true);
- CPlusPlus::Snapshot::const_iterator it = snapshot.begin();
-
- QString findString = (parameters.flags & Find::FindRegularExpression
- ? parameters.text : QRegExp::escape(parameters.text));
- if (parameters.flags & Find::FindWholeWords)
- findString = QString::fromLatin1("\\b%1\\b").arg(findString);
- QRegExp matcher(findString, (parameters.flags & Find::FindCaseSensitively
- ? Qt::CaseSensitive : Qt::CaseInsensitive));
- while (it != snapshot.end()) {
- if (future.isPaused())
- future.waitForResume();
- if (future.isCanceled())
- break;
- if (fileNames.isEmpty() || fileNames.contains(it.value()->fileName())) {
- QVector<Find::SearchResultItem> resultItems;
- QList<ModelItemInfo> modelInfos = search(it.value());
- foreach (const ModelItemInfo &info, modelInfos) {
- int index = matcher.indexIn(info.symbolName);
- if (index != -1) {
- QStringList path = info.fullyQualifiedName.mid(0,
- info.fullyQualifiedName.size() - 1);
- Find::SearchResultItem item;
- item.path = path;
- item.text = info.symbolName;
- item.textMarkPos = -1;
- item.textMarkLength = 0;
- item.icon = info.icon;
- item.lineNumber = -1;
- item.userData = qVariantFromValue(info);
- resultItems << item;
- }
- }
- if (!resultItems.isEmpty())
- future.reportResults(resultItems);
- }
- ++it;
- ++progress;
- future.setProgressValue(progress);
- }
- if (future.isPaused())
- future.waitForResume();
- }
-} //namespace
+} // anonymous namespace
SymbolsFindFilter::SymbolsFindFilter(CppModelManager *manager)
: m_manager(manager),
m_enabled(true),
m_symbolsToSearch(SearchSymbols::AllTypes),
- m_scope(SearchProjectsOnly)
+ m_scope(SymbolSearcher::SearchProjectsOnly)
{
// for disabling while parser is running
connect(Core::ICore::progressManager(), SIGNAL(taskStarted(QString)),
@@ -176,7 +122,7 @@ void SymbolsFindFilter::findAll(const QString &txt, Find::FindFlags findFlags)
connect(this, SIGNAL(enabledChanged(bool)), search, SLOT(setSearchAgainEnabled(bool)));
window->popup(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus);
- SymbolsFindParameters parameters;
+ SymbolSearcher::Parameters parameters;
parameters.text = txt;
parameters.flags = findFlags;
parameters.types = m_symbolsToSearch;
@@ -187,9 +133,9 @@ void SymbolsFindFilter::findAll(const QString &txt, Find::FindFlags findFlags)
void SymbolsFindFilter::startSearch(Find::SearchResult *search)
{
- SymbolsFindParameters parameters = search->userData().value<SymbolsFindParameters>();
+ SymbolSearcher::Parameters parameters = search->userData().value<SymbolSearcher::Parameters>();
QSet<QString> projectFileNames;
- if (parameters.scope == SymbolsFindFilter::SearchProjectsOnly) {
+ if (parameters.scope == SymbolSearcher::SearchProjectsOnly) {
foreach (ProjectExplorer::Project *project,
ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects()) {
projectFileNames += project->files(ProjectExplorer::Project::AllFiles).toSet();
@@ -202,12 +148,13 @@ void SymbolsFindFilter::startSearch(Find::SearchResult *search)
this, SLOT(finish()));
connect(watcher, SIGNAL(resultsReadyAt(int,int)),
this, SLOT(addResults(int,int)));
- watcher->setFuture(QtConcurrent::run<Find::SearchResultItem, SymbolsFindParameters,
- CPlusPlus::Snapshot, QSet<QString> >(runSearch, parameters,
- m_manager->snapshot(), projectFileNames));
+ SymbolSearcher *symbolSearcher = m_manager->indexingSupport()->createSymbolSearcher(parameters, projectFileNames);
+ connect(watcher, SIGNAL(finished()),
+ symbolSearcher, SLOT(deleteLater()));
+ watcher->setFuture(QtConcurrent::run(&SymbolSearcher::runSearch, symbolSearcher));
Core::FutureProgress *progress = Core::ICore::progressManager()->addTask(watcher->future(),
tr("Searching"),
- Find::Constants::TASK_SEARCH);
+ QLatin1String(Find::Constants::TASK_SEARCH));
connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
}
@@ -256,25 +203,25 @@ QWidget *SymbolsFindFilter::createConfigWidget()
void SymbolsFindFilter::writeSettings(QSettings *settings)
{
settings->beginGroup(QLatin1String(SETTINGS_GROUP));
- settings->setValue(SETTINGS_SYMBOLTYPES, (int)m_symbolsToSearch);
- settings->setValue(SETTINGS_SEARCHSCOPE, (int)m_scope);
+ settings->setValue(QLatin1String(SETTINGS_SYMBOLTYPES), (int)m_symbolsToSearch);
+ settings->setValue(QLatin1String(SETTINGS_SEARCHSCOPE), (int)m_scope);
settings->endGroup();
}
void SymbolsFindFilter::readSettings(QSettings *settings)
{
settings->beginGroup(QLatin1String(SETTINGS_GROUP));
- m_symbolsToSearch = (SearchSymbols::SymbolTypes)settings->value(SETTINGS_SYMBOLTYPES,
+ m_symbolsToSearch = (SearchSymbols::SymbolTypes)settings->value(QLatin1String(SETTINGS_SYMBOLTYPES),
(int)SearchSymbols::AllTypes).toInt();
- m_scope = (SearchScope)settings->value(SETTINGS_SEARCHSCOPE,
- (int)SearchProjectsOnly).toInt();
+ m_scope = (SearchScope)settings->value(QLatin1String(SETTINGS_SEARCHSCOPE),
+ (int)SymbolSearcher::SearchProjectsOnly).toInt();
settings->endGroup();
emit symbolsToSearchChanged();
}
void SymbolsFindFilter::onTaskStarted(const QString &type)
{
- if (type == CppTools::Constants::TASK_INDEX) {
+ if (type == QLatin1String(CppTools::Constants::TASK_INDEX)) {
m_enabled = false;
emit enabledChanged(m_enabled);
}
@@ -282,7 +229,7 @@ void SymbolsFindFilter::onTaskStarted(const QString &type)
void SymbolsFindFilter::onAllTasksFinished(const QString &type)
{
- if (type == CppTools::Constants::TASK_INDEX) {
+ if (type == QLatin1String(CppTools::Constants::TASK_INDEX)) {
m_enabled = true;
emit enabledChanged(m_enabled);
}
@@ -304,16 +251,16 @@ QString SymbolsFindFilter::label() const
QString SymbolsFindFilter::toolTip(Find::FindFlags findFlags) const
{
QStringList types;
- if (m_symbolsToSearch & SearchSymbols::Classes)
+ if (m_symbolsToSearch & SymbolSearcher::Classes)
types.append(tr("Classes"));
- if (m_symbolsToSearch & SearchSymbols::Functions)
+ if (m_symbolsToSearch & SymbolSearcher::Functions)
types.append(tr("Methods"));
- if (m_symbolsToSearch & SearchSymbols::Enums)
+ if (m_symbolsToSearch & SymbolSearcher::Enums)
types.append(tr("Enums"));
- if (m_symbolsToSearch & SearchSymbols::Declarations)
+ if (m_symbolsToSearch & SymbolSearcher::Declarations)
types.append(tr("Declarations"));
return tr("Scope: %1\nTypes: %2\nFlags: %3")
- .arg(searchScope() == SearchGlobal ? tr("All") : tr("Projects"))
+ .arg(searchScope() == SymbolSearcher::SearchGlobal ? tr("All") : tr("Projects"))
.arg(types.join(tr(", ")))
.arg(Find::IFindFilter::descriptionForFindFlags(findFlags));
}
@@ -374,31 +321,31 @@ SymbolsFindFilterConfigWidget::SymbolsFindFilterConfigWidget(SymbolsFindFilter *
void SymbolsFindFilterConfigWidget::getState()
{
SearchSymbols::SymbolTypes symbols = m_filter->symbolsToSearch();
- m_typeClasses->setChecked(symbols & SearchSymbols::Classes);
- m_typeMethods->setChecked(symbols & SearchSymbols::Functions);
- m_typeEnums->setChecked(symbols & SearchSymbols::Enums);
- m_typeDeclarations->setChecked(symbols & SearchSymbols::Declarations);
+ m_typeClasses->setChecked(symbols & SymbolSearcher::Classes);
+ m_typeMethods->setChecked(symbols & SymbolSearcher::Functions);
+ m_typeEnums->setChecked(symbols & SymbolSearcher::Enums);
+ m_typeDeclarations->setChecked(symbols & SymbolSearcher::Declarations);
SymbolsFindFilter::SearchScope scope = m_filter->searchScope();
- m_searchProjectsOnly->setChecked(scope == SymbolsFindFilter::SearchProjectsOnly);
- m_searchGlobal->setChecked(scope == SymbolsFindFilter::SearchGlobal);
+ m_searchProjectsOnly->setChecked(scope == SymbolSearcher::SearchProjectsOnly);
+ m_searchGlobal->setChecked(scope == SymbolSearcher::SearchGlobal);
}
void SymbolsFindFilterConfigWidget::setState() const
{
SearchSymbols::SymbolTypes symbols;
if (m_typeClasses->isChecked())
- symbols |= SearchSymbols::Classes;
+ symbols |= SymbolSearcher::Classes;
if (m_typeMethods->isChecked())
- symbols |= SearchSymbols::Functions;
+ symbols |= SymbolSearcher::Functions;
if (m_typeEnums->isChecked())
- symbols |= SearchSymbols::Enums;
+ symbols |= SymbolSearcher::Enums;
if (m_typeDeclarations->isChecked())
- symbols |= SearchSymbols::Declarations;
+ symbols |= SymbolSearcher::Declarations;
m_filter->setSymbolsToSearch(symbols);
if (m_searchProjectsOnly->isChecked())
- m_filter->setSearchScope(SymbolsFindFilter::SearchProjectsOnly);
+ m_filter->setSearchScope(SymbolSearcher::SearchProjectsOnly);
else
- m_filter->setSearchScope(SymbolsFindFilter::SearchGlobal);
+ m_filter->setSearchScope(SymbolSearcher::SearchGlobal);
}
diff --git a/src/plugins/cpptools/symbolsfindfilter.h b/src/plugins/cpptools/symbolsfindfilter.h
index e7d59cb95e..4f5da51814 100644
--- a/src/plugins/cpptools/symbolsfindfilter.h
+++ b/src/plugins/cpptools/symbolsfindfilter.h
@@ -50,12 +50,11 @@ class CppModelManager;
class SymbolsFindFilter : public Find::IFindFilter
{
Q_OBJECT
+
public:
- enum SearchScope {
- SearchProjectsOnly,
- SearchGlobal
- };
+ typedef SymbolSearcher::SearchScope SearchScope;
+public:
explicit SymbolsFindFilter(CppModelManager *manager);
QString id() const;
@@ -102,15 +101,6 @@ private:
SearchScope m_scope;
};
-class SymbolsFindParameters
-{
-public:
- QString text;
- Find::FindFlags flags;
- SearchSymbols::SymbolTypes types;
- SymbolsFindFilter::SearchScope scope;
-};
-
class SymbolsFindFilterConfigWidget : public QWidget
{
Q_OBJECT
@@ -137,7 +127,4 @@ private:
} // Internal
} // CppTools
-Q_DECLARE_METATYPE(CppTools::Internal::SymbolsFindFilter::SearchScope)
-Q_DECLARE_METATYPE(CppTools::Internal::SymbolsFindParameters)
-
#endif // SYMBOLSFINDFILTER_H
diff --git a/src/plugins/cpptools/uicodecompletionsupport.cpp b/src/plugins/cpptools/uicodecompletionsupport.cpp
index 715d6c9a1d..b9e2f7bdde 100644
--- a/src/plugins/cpptools/uicodecompletionsupport.cpp
+++ b/src/plugins/cpptools/uicodecompletionsupport.cpp
@@ -44,8 +44,8 @@ UiCodeModelSupport::UiCodeModelSupport(CppModelManagerInterface *modelmanager,
: AbstractEditorSupport(modelmanager),
m_sourceName(source),
m_fileName(uiHeaderFile),
- m_updateIncludingFiles(false),
- m_initialized(false)
+ m_initialized(false),
+ m_running(false)
{
if (debug)
qDebug()<<"ctor UiCodeModelSupport for"<<m_sourceName<<uiHeaderFile;
@@ -91,10 +91,6 @@ void UiCodeModelSupport::init() const
qDebug()<<"uic run wasn't succesfull";
m_cacheTime = QDateTime ();
m_contents = QByteArray();
- // and if the header file wasn't there, next time we need to update
- // all of the files that include this header
- if (!uiHeaderFileInfo.exists())
- m_updateIncludingFiles = true;
return;
}
} else {
@@ -108,6 +104,8 @@ QByteArray UiCodeModelSupport::contents() const
{
if (!m_initialized)
init();
+ if (m_running)
+ finishProcess();
return m_contents;
}
@@ -133,42 +131,58 @@ void UiCodeModelSupport::setFileName(const QString &name)
bool UiCodeModelSupport::runUic(const QString &ui) const
{
- QProcess process;
const QString uic = uicCommand();
if (uic.isEmpty())
return false;
- process.setEnvironment(environment());
+ m_process.setEnvironment(environment());
if (debug)
qDebug() << "UiCodeModelSupport::runUic " << uic << " on " << ui.size() << " bytes";
- process.start(uic, QStringList(), QIODevice::ReadWrite);
- if (!process.waitForStarted())
+ m_process.start(uic, QStringList(), QIODevice::ReadWrite);
+ if (!m_process.waitForStarted())
return false;
- process.write(ui.toUtf8());
- if (!process.waitForBytesWritten(3000))
+ m_process.write(ui.toUtf8());
+ if (!m_process.waitForBytesWritten(3000))
goto error;
- process.closeWriteChannel();
- if (!process.waitForFinished(3000) && process.exitStatus() != QProcess::NormalExit && process.exitCode() != 0)
- goto error;
-
- m_contents = process.readAllStandardOutput();
- m_cacheTime = QDateTime::currentDateTime();
- if (debug)
- qDebug() << "ok" << m_contents.size() << "bytes.";
+ m_process.closeWriteChannel();
+ m_running = true;
return true;
error:
if (debug)
- qDebug() << "failed" << process.readAllStandardError();
- process.kill();
+ qDebug() << "failed" << m_process.readAllStandardError();
+ m_process.kill();
+ m_running = false;
return false;
}
void UiCodeModelSupport::updateFromEditor(const QString &formEditorContents)
{
- if (runUic(formEditorContents)) {
- updateDocument();
+ if (runUic(formEditorContents))
+ if (finishProcess())
+ updateDocument();
+}
+
+bool UiCodeModelSupport::finishProcess() const
+{
+ if (!m_running)
+ return false;
+ if (!m_process.waitForFinished(3000)
+ && m_process.exitStatus() != QProcess::NormalExit
+ && m_process.exitCode() != 0) {
+ if (debug)
+ qDebug() << "failed" << m_process.readAllStandardError();
+ m_process.kill();
+ m_running = false;
+ return false;
}
+
+ m_contents = m_process.readAllStandardOutput();
+ m_cacheTime = QDateTime::currentDateTime();
+ if (debug)
+ qDebug() << "ok" << m_contents.size() << "bytes.";
+ m_running = false;
+ return true;
}
void UiCodeModelSupport::updateFromBuild()
diff --git a/src/plugins/cpptools/uicodecompletionsupport.h b/src/plugins/cpptools/uicodecompletionsupport.h
index 39ddeed012..5a1d8883de 100644
--- a/src/plugins/cpptools/uicodecompletionsupport.h
+++ b/src/plugins/cpptools/uicodecompletionsupport.h
@@ -37,6 +37,7 @@
#include "ModelManagerInterface.h"
#include <QDateTime>
+#include <QProcess>
namespace CppTools {
@@ -59,12 +60,14 @@ protected:
private:
void init() const;
bool runUic(const QString &ui) const;
+ bool finishProcess() const;
+ mutable QProcess m_process;
QString m_sourceName;
QString m_fileName;
- mutable bool m_updateIncludingFiles;
mutable bool m_initialized;
mutable QByteArray m_contents;
mutable QDateTime m_cacheTime;
+ mutable bool m_running;
};
} // CppTools
diff --git a/src/plugins/cvs/cvs.pro b/src/plugins/cvs/cvs.pro
index 77fdac9810..0f042def66 100644
--- a/src/plugins/cvs/cvs.pro
+++ b/src/plugins/cvs/cvs.pro
@@ -8,7 +8,6 @@ include(../../plugins/coreplugin/coreplugin.pri)
include(../../plugins/vcsbase/vcsbase.pri)
include(../../libs/utils/utils.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
HEADERS += annotationhighlighter.h \
cvsplugin.h \
cvscontrol.h \
diff --git a/src/plugins/cvs/cvs.qbs b/src/plugins/cvs/cvs.qbs
index f45ca0a576..d89725f59d 100644
--- a/src/plugins/cvs/cvs.qbs
+++ b/src/plugins/cvs/cvs.qbs
@@ -12,36 +12,29 @@ QtcPlugin {
Depends { name: "VcsBase" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
+ "annotationhighlighter.cpp",
"annotationhighlighter.h",
- "cvsplugin.h",
- "cvscontrol.h",
- "settingspage.h",
- "cvseditor.h",
- "cvssubmiteditor.h",
- "cvssettings.h",
- "cvsutils.h",
- "cvsconstants.h",
+ "checkoutwizard.cpp",
"checkoutwizard.h",
+ "checkoutwizardpage.cpp",
"checkoutwizardpage.h",
- "annotationhighlighter.cpp",
- "cvsplugin.cpp",
+ "cvs.qrc",
+ "cvsconstants.h",
"cvscontrol.cpp",
- "settingspage.cpp",
+ "cvscontrol.h",
"cvseditor.cpp",
- "cvssubmiteditor.cpp",
+ "cvseditor.h",
+ "cvsplugin.cpp",
+ "cvsplugin.h",
"cvssettings.cpp",
+ "cvssettings.h",
+ "cvssubmiteditor.cpp",
+ "cvssubmiteditor.h",
"cvsutils.cpp",
- "checkoutwizard.cpp",
- "checkoutwizardpage.cpp",
+ "cvsutils.h",
+ "settingspage.cpp",
+ "settingspage.h",
"settingspage.ui",
- "cvs.qrc"
]
}
diff --git a/src/plugins/cvs/cvscontrol.cpp b/src/plugins/cvs/cvscontrol.cpp
index 1d5e101a4e..85e383a9dc 100644
--- a/src/plugins/cvs/cvscontrol.cpp
+++ b/src/plugins/cvs/cvscontrol.cpp
@@ -50,7 +50,7 @@ QString CvsControl::displayName() const
Core::Id CvsControl::id() const
{
- return VcsBase::Constants::VCS_ID_CVS;
+ return Core::Id(VcsBase::Constants::VCS_ID_CVS);
}
bool CvsControl::isConfigured() const
diff --git a/src/plugins/cvs/cvseditor.cpp b/src/plugins/cvs/cvseditor.cpp
index cba98aa7e4..b0eccfe596 100644
--- a/src/plugins/cvs/cvseditor.cpp
+++ b/src/plugins/cvs/cvseditor.cpp
@@ -55,6 +55,16 @@ CvsEditor::CvsEditor(const VcsBase::VcsBaseEditorParameters *type,
{
QTC_ASSERT(m_revisionAnnotationPattern.isValid(), return);
QTC_ASSERT(m_revisionLogPattern.isValid(), return);
+ /* Diff format:
+ \code
+ cvs diff -d -u -r1.1 -r1.2:
+ --- mainwindow.cpp<\t>13 Jul 2009 13:50:15 -0000<tab>1.1
+ +++ mainwindow.cpp<\t>14 Jul 2009 07:09:24 -0000<tab>1.2
+ @@ -6,6 +6,5 @@
+ \endcode
+ */
+ setDiffFilePattern(QRegExp(QLatin1String("^[-+]{3} ([^\\t]+)")));
+ setLogEntryPattern(QRegExp(QLatin1String("^revision (.+)$")));
setAnnotateRevisionTextFormat(tr("Annotate revision \"%1\""));
}
@@ -113,45 +123,12 @@ QString CvsEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-/* \code
-cvs diff -d -u -r1.1 -r1.2:
---- mainwindow.cpp<\t>13 Jul 2009 13:50:15 -0000 <\t>1.1
-+++ mainwindow.cpp<\t>14 Jul 2009 07:09:24 -0000<\t>1.2
-@@ -6,6 +6,5 @@
-\endcode
-*/
-
-VcsBase::DiffHighlighter *CvsEditor::createDiffHighlighter() const
-{
- const QRegExp filePattern(QLatin1String("^[-+][-+][-+] .*1\\.[\\d\\.]+$"));
- QTC_CHECK(filePattern.isValid());
- return new VcsBase::DiffHighlighter(filePattern);
-}
-
VcsBase::BaseAnnotationHighlighter *CvsEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new CvsAnnotationHighlighter(changes, bg);
}
-QString CvsEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
-{
- // "+++ mainwindow.cpp<\t>13 Jul 2009 13:50:15 -0000 1.1"
- // Go back chunks
- const QString diffIndicator = QLatin1String("+++ ");
- for (QTextBlock block = inBlock; block.isValid() ; block = block.previous()) {
- QString diffFileName = block.text();
- if (diffFileName.startsWith(diffIndicator)) {
- diffFileName.remove(0, diffIndicator.size());
- const int tabIndex = diffFileName.indexOf(QLatin1Char('\t'));
- if (tabIndex != -1)
- diffFileName.truncate(tabIndex);
- return findDiffFile(diffFileName);
- }
- }
- return QString();
-}
-
QStringList CvsEditor::annotationPreviousVersions(const QString &revision) const
{
if (isFirstRevision(revision))
diff --git a/src/plugins/cvs/cvseditor.h b/src/plugins/cvs/cvseditor.h
index c3e88b6c43..6e6895f651 100644
--- a/src/plugins/cvs/cvseditor.h
+++ b/src/plugins/cvs/cvseditor.h
@@ -48,9 +48,7 @@ public:
private:
QSet<QString> annotationChanges() const;
QString changeUnderCursor(const QTextCursor &) const;
- VcsBase::DiffHighlighter *createDiffHighlighter() const;
VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- QString fileNameFromDiffSpecification(const QTextBlock &diffFileName) const;
QStringList annotationPreviousVersions(const QString &revision) const;
mutable QRegExp m_revisionAnnotationPattern;
diff --git a/src/plugins/cvs/cvsplugin.cpp b/src/plugins/cvs/cvsplugin.cpp
index 26c81a4941..bb05b1350a 100644
--- a/src/plugins/cvs/cvsplugin.cpp
+++ b/src/plugins/cvs/cvsplugin.cpp
@@ -71,6 +71,10 @@
#include <QMenu>
#include <QMessageBox>
+#ifdef WITH_TESTS
+#include <QTest>
+#endif
+
using namespace VcsBase;
using namespace Core;
@@ -147,7 +151,7 @@ static inline const VcsBaseEditorParameters *findType(int ie)
static inline QString debugCodec(const QTextCodec *c)
{
- return c ? QString::fromAscii(c->name()) : QString::fromAscii("Null codec");
+ return c ? QString::fromLatin1(c->name()) : QString::fromLatin1("Null codec");
}
static inline bool messageBoxQuestion(const QString &title, const QString &question, QWidget *parent = 0)
@@ -213,7 +217,8 @@ static const VcsBaseSubmitEditorParameters submitParameters = {
Constants::CVS_SUBMIT_MIMETYPE,
Constants::CVSCOMMITEDITOR_ID,
Constants::CVSCOMMITEDITOR_DISPLAY_NAME,
- Constants::CVSCOMMITEDITOR
+ Constants::CVSCOMMITEDITOR,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
bool CvsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
@@ -248,7 +253,7 @@ bool CvsPlugin::initialize(const QStringList &arguments, QString *errorMessage)
addAutoReleasedObject(new CheckoutWizard);
const QString prefix = QLatin1String("cvs");
- m_commandLocator = new Locator::CommandLocator(QLatin1String("CVS"), prefix, prefix);
+ m_commandLocator = new Locator::CommandLocator("CVS", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
// Register actions
@@ -681,11 +686,10 @@ void CvsPlugin::revertAll()
const CvsResponse revertResponse =
runCvs(state.topLevel(), args, m_settings.timeOutMS(),
SshPasswordPrompt|ShowStdOutInLogWindow);
- if (revertResponse.result == CvsResponse::Ok) {
+ if (revertResponse.result == CvsResponse::Ok)
cvsVersionControl()->emitRepositoryChanged(state.topLevel());
- } else {
+ else
QMessageBox::warning(0, title, tr("Revert failed: %1").arg(revertResponse.message), QMessageBox::Ok);
- }
}
void CvsPlugin::revertCurrentFile()
@@ -719,9 +723,8 @@ void CvsPlugin::revertCurrentFile()
const CvsResponse revertResponse =
runCvs(state.currentFileTopLevel(), args, m_settings.timeOutMS(),
SshPasswordPrompt|ShowStdOutInLogWindow);
- if (revertResponse.result == CvsResponse::Ok) {
+ if (revertResponse.result == CvsResponse::Ok)
cvsVersionControl()->emitFilesChanged(QStringList(state.currentFile()));
- }
}
void CvsPlugin::diffProject()
@@ -776,11 +779,10 @@ void CvsPlugin::startCommit(const QString &workingDir, const QStringList &files)
StateList statusOutput = parseStatusOutput(QString(), response.stdOut);
if (!files.isEmpty()) {
for (StateList::iterator it = statusOutput.begin(); it != statusOutput.end() ; ) {
- if (files.contains(it->second)) {
+ if (files.contains(it->second))
++it;
- } else {
+ else
it = statusOutput.erase(it);
- }
}
}
if (statusOutput.empty()) {
@@ -1269,7 +1271,7 @@ IEditor *CvsPlugin::showOutputInEditor(const QString& title, const QString &outp
{
const VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
- const Id id = params->id;
+ const Id id = Core::Id(QByteArray(params->id));
if (Cvs::Constants::debug)
qDebug() << "CVSPlugin::showOutputInEditor" << title << id.name()
<< "source=" << source << "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
@@ -1378,6 +1380,55 @@ CvsControl *CvsPlugin::cvsVersionControl() const
return static_cast<CvsControl *>(versionControl());
}
+#ifdef WITH_TESTS
+void CvsPlugin::testDiffFileResolving_data()
+{
+ QTest::addColumn<QByteArray>("header");
+ QTest::addColumn<QByteArray>("fileName");
+
+ QTest::newRow("Modified") << QByteArray(
+ "Index: src/plugins/cvs/cvseditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/cvs/cvseditor.cpp\t21 Jan 2013 20:34:20 -0000\t1.1\n"
+ "+++ src/plugins/cvs/cvseditor.cpp\t21 Jan 2013 20:34:28 -0000\n"
+ "@@ -120,7 +120,7 @@\n\n")
+ << QByteArray("src/plugins/cvs/cvseditor.cpp");
+}
+
+void CvsPlugin::testDiffFileResolving()
+{
+ CvsEditor editor(editorParameters + 3, 0);
+ editor.testDiffFileResolving();
+}
+
+void CvsPlugin::testLogResolving()
+{
+ QByteArray data(
+ "RCS file: /sources/cvs/ccvs/Attic/FIXED-BUGS,v\n"
+ "Working file: FIXED-BUGS\n"
+ "head: 1.3\n"
+ "branch:\n"
+ "locks: strict\n"
+ "access list:\n"
+ "symbolic names:\n"
+ "keyword substitution: kv\n"
+ "total revisions: 3; selected revisions: 3\n"
+ "description:\n"
+ "----------------------------\n"
+ "revision 1.3\n"
+ "date: 1995-04-29 06:22:41 +0300; author: jimb; state: dead; lines: +0 -0;\n"
+ "*** empty log message ***\n"
+ "----------------------------\n"
+ "revision 1.2\n"
+ "date: 1995-04-28 18:52:24 +0300; author: noel; state: Exp; lines: +6 -0;\n"
+ "added latest commentary\n"
+ "----------------------------\n"
+ );
+ CvsEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data, "1.3", "1.2");
+}
+#endif
+
} // namespace Internal
} // namespace Cvs
diff --git a/src/plugins/cvs/cvsplugin.h b/src/plugins/cvs/cvsplugin.h
index 429210e406..ec8235ae47 100644
--- a/src/plugins/cvs/cvsplugin.h
+++ b/src/plugins/cvs/cvsplugin.h
@@ -77,7 +77,7 @@ public:
CvsPlugin();
~CvsPlugin();
- virtual bool initialize(const QStringList &arguments, QString *errorMessage);
+ bool initialize(const QStringList &arguments, QString *errorMessage);
void cvsDiff(const QString &workingDir, const QStringList &files);
@@ -123,10 +123,15 @@ private slots:
void uneditCurrentFile();
void uneditCurrentRepository();
void cvsDiff(const Cvs::Internal::CvsDiffParameters &p);
+#ifdef WITH_TESTS
+ void testDiffFileResolving_data();
+ void testDiffFileResolving();
+ void testLogResolving();
+#endif
protected:
- virtual void updateActions(VcsBase::VcsBasePlugin::ActionState);
- virtual bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
+ void updateActions(VcsBase::VcsBasePlugin::ActionState);
+ bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
private:
bool isCommitEditorOpen() const;
diff --git a/src/plugins/cvs/cvssettings.cpp b/src/plugins/cvs/cvssettings.cpp
index e7ec19efd5..113057fc8d 100644
--- a/src/plugins/cvs/cvssettings.cpp
+++ b/src/plugins/cvs/cvssettings.cpp
@@ -30,6 +30,7 @@
#include "cvssettings.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QSettings>
#include <QTextStream>
@@ -47,12 +48,7 @@ enum { defaultTimeOutS = 30 };
static QString defaultCommand()
{
- QString rc;
- rc = QLatin1String("cvs");
-#if defined(Q_OS_WIN32)
- rc.append(QLatin1String(".exe"));
-#endif
- return rc;
+ return QLatin1String("cvs" QTC_HOST_EXE_SUFFIX);
}
namespace Cvs {
diff --git a/src/plugins/cvs/cvssubmiteditor.cpp b/src/plugins/cvs/cvssubmiteditor.cpp
index e237263082..92ceade1e6 100644
--- a/src/plugins/cvs/cvssubmiteditor.cpp
+++ b/src/plugins/cvs/cvssubmiteditor.cpp
@@ -30,7 +30,7 @@
#include "cvssubmiteditor.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
#include <vcsbase/submitfilemodel.h>
using namespace Cvs::Internal;
@@ -38,7 +38,7 @@ using namespace VcsBase;
CvsSubmitEditor::CvsSubmitEditor(const VcsBaseSubmitEditorParameters *parameters,
QWidget *parentWidget) :
- VcsBaseSubmitEditor(parameters, new Utils::SubmitEditorWidget(parentWidget)),
+ VcsBaseSubmitEditor(parameters, new VcsBase::SubmitEditorWidget(parentWidget)),
m_msgAdded(tr("Added")),
m_msgRemoved(tr("Removed")),
m_msgModified(tr("Modified"))
@@ -65,6 +65,6 @@ void CvsSubmitEditor::setStateList(const StateFilePairs &statusOutput)
const ConstIterator cend = statusOutput.constEnd();
for (ConstIterator it = statusOutput.constBegin(); it != cend; ++it)
- model->addFile(it->second, stateName(it->first), true);
+ model->addFile(it->second, stateName(it->first));
setFileModel(model);
}
diff --git a/src/plugins/cvs/cvsutils.cpp b/src/plugins/cvs/cvsutils.cpp
index 9f6339f3a0..eb3ace8230 100644
--- a/src/plugins/cvs/cvsutils.cpp
+++ b/src/plugins/cvs/cvsutils.cpp
@@ -50,7 +50,7 @@ QDebug operator<<(QDebug d, const CvsLogEntry &e)
{
QDebug nospace = d.nospace();
nospace << "File: " << e.file << e.revisions.size() << '\n';
- foreach(const CvsRevision &r, e.revisions)
+ foreach (const CvsRevision &r, e.revisions)
nospace << " " << r.revision << ' ' << r.date << ' ' << r.commitId << '\n';
return d;
}
@@ -93,7 +93,7 @@ QList<CvsLogEntry> parseLogEntries(const QString &o,
// Parse using a state enumeration and regular expressions as not to fall for weird
// commit messages in state 'RevisionState'
- foreach(const QString &line, lines) {
+ foreach (const QString &line, lines) {
switch (state) {
case FileState:
if (line.startsWith(workingFilePrefix)) {
@@ -130,11 +130,10 @@ QList<CvsLogEntry> parseLogEntries(const QString &o,
// Purge out files with no matching commits
if (!filterCommitId.isEmpty()) {
for (QList<CvsLogEntry>::iterator it = rc.begin(); it != rc.end(); ) {
- if (it->revisions.empty()) {
+ if (it->revisions.empty())
it = rc.erase(it);
- } else {
+ else
++it;
- }
}
}
return rc;
@@ -152,11 +151,10 @@ QString fixDiffOutput(QString d)
if (endOfLinePos == -1)
break;
const int nextLinePos = endOfLinePos + 1;
- if (d.at(pos) == questionMark) {
+ if (d.at(pos) == questionMark)
d.remove(pos, nextLinePos - pos);
- } else {
+ else
pos = nextLinePos;
- }
}
return d;
}
diff --git a/src/plugins/cvs/settingspage.cpp b/src/plugins/cvs/settingspage.cpp
index 048526917a..e5f051579e 100644
--- a/src/plugins/cvs/settingspage.cpp
+++ b/src/plugins/cvs/settingspage.cpp
@@ -94,7 +94,7 @@ QString SettingsPageWidget::searchKeywords() const
SettingsPage::SettingsPage()
{
- setId(QLatin1String(VcsBase::Constants::VCS_ID_CVS));
+ setId(VcsBase::Constants::VCS_ID_CVS);
setDisplayName(tr("CVS"));
}
diff --git a/src/plugins/debugger/basewindow.h b/src/plugins/debugger/basewindow.h
index d2d51dd625..0525bf000a 100644
--- a/src/plugins/debugger/basewindow.h
+++ b/src/plugins/debugger/basewindow.h
@@ -53,6 +53,7 @@ public:
void setModel(QAbstractItemModel *model) { m_treeView->setModel(model); }
QHeaderView *header() const { return m_treeView->header(); }
QAbstractItemModel *model() const { return m_treeView->model(); }
+ QTreeView *treeView() const { return m_treeView; }
private:
QTreeView *m_treeView;
diff --git a/src/plugins/debugger/breakhandler.cpp b/src/plugins/debugger/breakhandler.cpp
index 3d7cbda175..5a3a68929a 100644
--- a/src/plugins/debugger/breakhandler.cpp
+++ b/src/plugins/debugger/breakhandler.cpp
@@ -37,6 +37,8 @@
#include "debuggerstringutils.h"
#include "stackframe.h"
+#include <extensionsystem/invoker.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#if USE_BREAK_MODEL_TEST
@@ -180,11 +182,9 @@ QIcon BreakHandler::emptyIcon()
static inline bool fileNameMatch(const QString &f1, const QString &f2)
{
-#ifdef Q_OS_WIN
- return f1.compare(f2, Qt::CaseInsensitive) == 0;
-#else
+ if (Utils::HostOsInfo::isWindowsHost())
+ return f1.compare(f2, Qt::CaseInsensitive) == 0;
return f1 == f2;
-#endif
}
static bool isSimilarTo(const BreakpointParameters &data, const BreakpointResponse &needle)
@@ -398,11 +398,10 @@ void BreakHandler::loadBreakpoints()
v = map.value(_("message"));
if (v.isValid())
data.message = v.toString();
- if (data.isValid()) {
+ if (data.isValid())
appendBreakpoint(data);
- } else {
+ else
qWarning("Not restoring invalid breakpoint: %s", qPrintable(data.toString()));
- }
}
//qDebug() << "LOADED BREAKPOINTS" << this << list.size();
}
@@ -1163,18 +1162,20 @@ void BreakHandler::saveSessionData()
void BreakHandler::loadSessionData()
{
+ beginResetModel();
m_storage.clear();
- reset();
+ endResetModel();
loadBreakpoints();
}
void BreakHandler::removeSessionData()
{
+ beginResetModel();
Iterator it = m_storage.begin(), et = m_storage.end();
for ( ; it != et; ++it)
it->destroyMarker();
m_storage.clear();
- reset();
+ endResetModel();
}
void BreakHandler::breakByFunction(const QString &functionName)
@@ -1257,6 +1258,25 @@ void BreakHandler::updateLineNumberFromMarker(BreakpointModelId id, int lineNumb
emit layoutChanged();
}
+void BreakHandler::changeLineNumberFromMarker(BreakpointModelId id, int lineNumber)
+{
+ // We need to delay this as it is called from a marker which will be destroyed.
+ ExtensionSystem::InvokerBase invoker;
+ invoker.addArgument(id);
+ invoker.addArgument(lineNumber);
+ invoker.setConnectionType(Qt::QueuedConnection);
+ invoker.invoke(this, "changeLineNumberFromMarkerHelper");
+ QTC_CHECK(invoker.wasSuccessful());
+}
+
+void BreakHandler::changeLineNumberFromMarkerHelper(BreakpointModelId id, int lineNumber)
+{
+ BreakpointParameters data = breakpointData(id);
+ data.lineNumber = lineNumber;
+ removeBreakpoint(id);
+ appendBreakpoint(data);
+}
+
BreakpointModelIds BreakHandler::allBreakpointIds() const
{
BreakpointModelIds ids;
@@ -1419,8 +1439,13 @@ bool BreakHandler::BreakpointItem::needsChange() const
return true;
if (data.command != response.command)
return true;
- if (data.lineNumber != response.lineNumber)
+ if (data.type == BreakpointByFileAndLine && data.lineNumber != response.lineNumber)
return true;
+ // FIXME: Too strict, functions may have parameter lists, or not.
+ // if (data.type == BreakpointByFunction && data.functionName != response.functionName)
+ // return true;
+ // if (data.type == BreakpointByAddress && data.address != response.address)
+ // return true;
return false;
}
diff --git a/src/plugins/debugger/breakhandler.h b/src/plugins/debugger/breakhandler.h
index c7112aa9c5..6c01a3d7e3 100644
--- a/src/plugins/debugger/breakhandler.h
+++ b/src/plugins/debugger/breakhandler.h
@@ -133,6 +133,7 @@ public:
void setEnabled(BreakpointModelId id, bool on);
void updateFileNameFromMarker(BreakpointModelId id, const QString &fileName);
void updateLineNumberFromMarker(BreakpointModelId id, int lineNumber);
+ void changeLineNumberFromMarker(BreakpointModelId id, int lineNumber);
void setMarkerFileAndLine(BreakpointModelId id,
const QString &fileName, int lineNumber);
bool isOneShot(BreakpointModelId id) const;
@@ -189,6 +190,7 @@ private:
void loadBreakpoints();
void saveBreakpoints();
void cleanupBreakpoint(BreakpointModelId id);
+ Q_SLOT void changeLineNumberFromMarkerHelper(Debugger::Internal::BreakpointModelId id, int lineNumber);
struct BreakpointItem
{
diff --git a/src/plugins/debugger/breakpointmarker.cpp b/src/plugins/debugger/breakpointmarker.cpp
index 3b806ab061..92c5fb91f2 100644
--- a/src/plugins/debugger/breakpointmarker.cpp
+++ b/src/plugins/debugger/breakpointmarker.cpp
@@ -68,6 +68,16 @@ void BreakpointMarker::updateLineNumber(int lineNumber)
breakHandler()->updateLineNumberFromMarker(m_id, lineNumber);
}
+void BreakpointMarker::dragToLine(int lineNumber)
+{
+ breakHandler()->changeLineNumberFromMarker(m_id, lineNumber);
+}
+
+void BreakpointMarker::clicked()
+{
+ breakHandler()->removeBreakpoint(m_id);
+}
+
void BreakpointMarker::updateFileName(const QString &fileName)
{
BaseTextMark::updateFileName(fileName);
diff --git a/src/plugins/debugger/breakpointmarker.h b/src/plugins/debugger/breakpointmarker.h
index 75ac59233f..ff90a56a56 100644
--- a/src/plugins/debugger/breakpointmarker.h
+++ b/src/plugins/debugger/breakpointmarker.h
@@ -46,6 +46,10 @@ public:
void removedFromEditor();
void updateLineNumber(int lineNumber);
void updateFileName(const QString &fileName);
+ bool isDraggable() const { return true; }
+ void dragToLine(int lineNumber);
+ bool isClickable() const { return true; }
+ void clicked();
private:
BreakpointModelId m_id;
diff --git a/src/plugins/debugger/breakwindow.cpp b/src/plugins/debugger/breakwindow.cpp
index 4872a46cc6..8f4caabcc1 100644
--- a/src/plugins/debugger/breakwindow.cpp
+++ b/src/plugins/debugger/breakwindow.cpp
@@ -494,11 +494,10 @@ void BreakpointDialog::setParts(unsigned mask, const BreakpointParameters &data)
}
if (mask & ExpressionPart) {
- if (!data.expression.isEmpty()) {
+ if (!data.expression.isEmpty())
m_lineEditExpression->setText(data.expression);
- } else {
+ else
m_lineEditExpression->clear();
- }
}
if (mask & ConditionPart)
@@ -523,7 +522,7 @@ void BreakpointDialog::typeChanged(int)
const BreakpointType newType = type();
m_previousType = newType;
// Save current state.
- switch(previousType) {
+ switch (previousType) {
case UnknownType:
break;
case BreakpointByFileAndLine:
@@ -713,11 +712,15 @@ void BreakTreeView::keyPressEvent(QKeyEvent *ev)
void BreakTreeView::mouseDoubleClickEvent(QMouseEvent *ev)
{
QModelIndex indexUnderMouse = indexAt(ev->pos());
- if (indexUnderMouse.isValid() && indexUnderMouse.column() >= 4) {
- BreakpointModelId id = breakHandler()->findBreakpointByIndex(indexUnderMouse);
- editBreakpoints(BreakpointModelIds() << id);
+ if (indexUnderMouse.isValid()) {
+ if (indexUnderMouse.column() >= 4) {
+ BreakpointModelId id = breakHandler()->findBreakpointByIndex(indexUnderMouse);
+ editBreakpoints(BreakpointModelIds() << id);
+ }
+ } else {
+ addBreakpoint();
}
- QTreeView::mouseDoubleClickEvent(ev);
+ BaseTreeView::mouseDoubleClickEvent(ev);
}
void BreakTreeView::setModel(QAbstractItemModel *model)
diff --git a/src/plugins/debugger/cdb/cdbengine.cpp b/src/plugins/debugger/cdb/cdbengine.cpp
index 63408d83c9..1fa38bdda1 100644
--- a/src/plugins/debugger/cdb/cdbengine.cpp
+++ b/src/plugins/debugger/cdb/cdbengine.cpp
@@ -38,6 +38,7 @@
#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerinternalconstants.h"
+#include "debuggerprotocol.h"
#include "debuggerrunner.h"
#include "debuggerstartparameters.h"
#include "debuggertooltipmanager.h"
@@ -51,10 +52,10 @@
#include "threadshandler.h"
#include "watchhandler.h"
#include "watchutils.h"
-#include "gdb/gdbmi.h"
#include "shared/cdbsymbolpathlisteditor.h"
#include "shared/hostutils.h"
#include "procinterrupt.h"
+#include "sourceutils.h"
#include <TranslationUnit.h>
@@ -62,6 +63,8 @@
#include <texteditor/itexteditor.h>
#include <projectexplorer/abi.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/task.h>
+#include <projectexplorer/taskhub.h>
#include <utils/synchronousprocess.h>
#include <utils/qtcprocess.h>
@@ -374,6 +377,7 @@ CdbEngine::CdbEngine(const DebuggerStartParameters &sp, const OptionsPtr &option
m_operateByInstruction(true), // Default CDB setting
m_notifyEngineShutdownOnTermination(false),
m_hasDebuggee(false),
+ m_cdbIs64Bit(false),
m_elapsedLogTime(0),
m_sourceStepInto(false),
m_watchPointX(0),
@@ -542,7 +546,7 @@ bool CdbEngine::startConsole(const DebuggerStartParameters &sp, QString *errorMe
SLOT(consoleStubError(QString)));
connect(m_consoleStub.data(), SIGNAL(processStarted()),
SLOT(consoleStubProcessStarted()));
- connect(m_consoleStub.data(), SIGNAL(wrapperStopped()),
+ connect(m_consoleStub.data(), SIGNAL(stubStopped()),
SLOT(consoleStubExited()));
m_consoleStub->setWorkingDirectory(sp.workingDirectory);
if (sp.environment.size())
@@ -622,6 +626,19 @@ void CdbEngine::setupEngine()
STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyEngineSetupFailed")
notifyEngineSetupFailed();
}
+ const QString normalFormat = tr("Normal");
+ const QStringList stringFormats = QStringList()
+ << normalFormat << tr("Separate Window");
+ WatchHandler *wh = watchHandler();
+ wh->addTypeFormats("QString", stringFormats);
+ wh->addTypeFormats("QString *", stringFormats);
+ wh->addTypeFormats("QByteArray", stringFormats);
+ wh->addTypeFormats("QByteArray *", stringFormats);
+ wh->addTypeFormats("std__basic_string", stringFormats); // Python dumper naming convention for std::[w]string
+ const QStringList imageFormats = QStringList()
+ << normalFormat << tr("Image");
+ wh->addTypeFormats("QImage", imageFormats);
+ wh->addTypeFormats("QImage *", imageFormats);
}
bool CdbEngine::launchCDB(const DebuggerStartParameters &sp, QString *errorMessage)
@@ -639,13 +656,13 @@ bool CdbEngine::launchCDB(const DebuggerStartParameters &sp, QString *errorMessa
return false;
}
- const bool is64bit =
+ m_cdbIs64Bit =
#ifdef Q_OS_WIN
Utils::winIs64BitBinary(executable);
#else
false;
#endif
- const QFileInfo extensionFi(CdbEngine::extensionLibraryName(is64bit));
+ const QFileInfo extensionFi(CdbEngine::extensionLibraryName(m_cdbIs64Bit));
if (!extensionFi.isFile()) {
*errorMessage = QString::fromLatin1("Internal error: The extension %1 cannot be found.").
arg(QDir::toNativeSeparators(extensionFi.absoluteFilePath()));
@@ -667,6 +684,8 @@ bool CdbEngine::launchCDB(const DebuggerStartParameters &sp, QString *errorMessa
<< QLatin1String(".idle_cmd ") + QString::fromLatin1(m_extensionCommandPrefixBA) + QLatin1String("idle");
if (sp.useTerminal) // Separate console
arguments << QLatin1String("-2");
+ if (m_options->ignoreFirstChanceAccessViolation)
+ arguments << QLatin1String("-x");
if (!m_options->symbolPaths.isEmpty())
arguments << QLatin1String("-y") << m_options->symbolPaths.join(QString(QLatin1Char(';')));
if (!m_options->sourcePaths.isEmpty())
@@ -764,6 +783,11 @@ void CdbEngine::setupInferior()
}
postCommand("sxn 0x4000001f", 0); // Do not break on WowX86 exceptions.
postCommand(".asm source_line", 0); // Source line in assembly
+ postCommand(m_extensionCommandPrefixBA + "setparameter maxStringLength="
+ + debuggerCore()->action(MaximalStringLength)->value().toByteArray()
+ + " maxStackDepth="
+ + debuggerCore()->action(MaximalStackDepth)->value().toByteArray()
+ , 0);
postExtensionCommand("pid", QByteArray(), 0, &CdbEngine::handlePid);
}
@@ -801,7 +825,7 @@ void CdbEngine::runEngine()
if (debug)
qDebug("runEngine");
foreach (const QString &breakEvent, m_options->breakEvents)
- postCommand(QByteArray("sxe ") + breakEvent.toAscii(), 0);
+ postCommand(QByteArray("sxe ") + breakEvent.toLatin1(), 0);
// Break functions: each function must be fully qualified,
// else the debugger will slow down considerably.
foreach (const QString &breakFunctionS, m_options->breakFunctions) {
@@ -820,6 +844,14 @@ void CdbEngine::runEngine()
postCommand(breakAtFunctionCommand(breakFunction), 0);
}
}
+ if (debuggerCore()->boolSetting(BreakOnWarning)) {
+ postCommand("bm /( QtCored4!qWarning", 0); // 'bm': All overloads.
+ postCommand("bm /( Qt5Cored!QMessageLogger::warning", 0);
+ }
+ if (debuggerCore()->boolSetting(BreakOnFatal)) {
+ postCommand("bm /( QtCored4!qFatal", 0); // 'bm': All overloads.
+ postCommand("bm /( Qt5Cored!QMessageLogger::fatal", 0);
+ }
if (startParameters().startMode == AttachCore) {
QTC_ASSERT(!m_coreStopReason.isNull(), return; );
notifyInferiorUnrunnable();
@@ -931,11 +963,10 @@ void CdbEngine::processFinished()
m_process.exitStatus(), m_process.exitCode());
const bool crashed = m_process.exitStatus() == QProcess::CrashExit;
- if (crashed) {
+ if (crashed)
showMessage(tr("CDB crashed"), LogError); // not in your life.
- } else {
+ else
showMessage(tr("CDB exited (%1)").arg(m_process.exitCode()), LogMisc);
- }
if (m_notifyEngineShutdownOnTermination) {
if (crashed) {
@@ -1129,11 +1160,10 @@ void CdbEngine::interruptInferior()
qDebug() << "CdbEngine::interruptInferior()" << stateName(state());
bool ok = false;
- if (!canInterruptInferior()) {
+ if (!canInterruptInferior())
showMessage(tr("Interrupting is not possible in remote sessions."), LogError);
- } else {
+ else
ok = doInterruptInferior(NoSpecialStop);
- }
// Restore running state if stop failed.
if (!ok) {
STATE_DEBUG(state(), Q_FUNC_INFO, __LINE__, "notifyInferiorStopOk")
@@ -1159,7 +1189,9 @@ bool CdbEngine::doInterruptInferior(SpecialStopMode sm)
showMessage(QString::fromLatin1("Interrupting process %1...").arg(inferiorPid()), LogMisc);
QString errorMessage;
- const bool ok = interruptProcess(inferiorPid(), CdbEngineType, &errorMessage);
+
+ const bool ok = interruptProcess(inferiorPid(), CdbEngineType,
+ &errorMessage, m_cdbIs64Bit);
if (!ok) {
m_specialStopMode = oldSpecialMode;
showMessage(errorMessage, LogError);
@@ -1179,7 +1211,7 @@ void CdbEngine::executeRunToLine(const ContextData &data)
bp.fileName = data.fileName;
bp.lineNumber = data.lineNumber;
}
- postCommand(cdbAddBreakpointCommand(bp, m_sourcePathMappings, BreakpointModelId(quint16(-1)), true), 0);
+ postCommand(cdbAddBreakpointCommand(bp, m_sourcePathMappings, BreakpointModelId(), true), 0);
continueInferior();
}
@@ -1189,7 +1221,7 @@ void CdbEngine::executeRunToFunction(const QString &functionName)
BreakpointParameters bp(BreakpointByFunction);
bp.functionName = functionName;
- postCommand(cdbAddBreakpointCommand(bp, m_sourcePathMappings, BreakpointModelId(quint16(-1)), true), 0);
+ postCommand(cdbAddBreakpointCommand(bp, m_sourcePathMappings, BreakpointModelId(), true), 0);
continueInferior();
}
@@ -1251,7 +1283,7 @@ void CdbEngine::handleJumpToLineAddressResolution(const CdbBuiltinCommandPtr &cm
bool ok;
const quint64 address = answer.toLongLong(&ok, 16);
if (ok && address) {
- QTC_ASSERT(qVariantCanConvert<ContextData>(cmd->cookie), return);
+ QTC_ASSERT(cmd->cookie.canConvert<ContextData>(), return);
const ContextData cookie = qvariant_cast<ContextData>(cmd->cookie);
jumpToAddress(address);
gotoLocation(Location(cookie.fileName, cookie.lineNumber));
@@ -1261,7 +1293,7 @@ void CdbEngine::handleJumpToLineAddressResolution(const CdbBuiltinCommandPtr &cm
static inline bool isAsciiWord(const QString &s)
{
foreach (const QChar &c, s) {
- if (!c.isLetterOrNumber() || c.toAscii() == 0)
+ if (!c.isLetterOrNumber() || c.toLatin1() == 0)
return false;
}
return true;
@@ -1304,15 +1336,6 @@ void CdbEngine::assignValueInDebugger(const WatchData *w, const QString &expr, c
updateLocals();
}
-void CdbEngine::parseThreads(const GdbMi &data, int forceCurrentThreadId /* = -1 */)
-{
- int currentThreadId;
- Threads threads = ThreadsHandler::parseGdbmiThreads(data, &currentThreadId);
- threadsHandler()->setThreads(threads);
- threadsHandler()->setCurrentThreadId(forceCurrentThreadId >= 0 ?
- forceCurrentThreadId : currentThreadId);
-}
-
void CdbEngine::handleThreads(const CdbExtensionCommandPtr &reply)
{
if (debug)
@@ -1320,7 +1343,7 @@ void CdbEngine::handleThreads(const CdbExtensionCommandPtr &reply)
if (reply->success) {
GdbMi data;
data.fromString(reply->reply);
- parseThreads(data);
+ threadsHandler()->updateThreads(data);
// Continue sequence
postCommandSequence(reply->commandSequence);
} else {
@@ -1426,7 +1449,10 @@ void CdbEngine::activateFrame(int index)
if (index < 0)
return;
const StackFrames &frames = stackHandler()->frames();
- QTC_ASSERT(index < frames.size(), return);
+ if (index >= frames.size()) {
+ reloadFullStack(); // Clicked on "More...".
+ return;
+ }
const StackFrame frame = frames.at(index);
if (debug || debugLocals)
@@ -1437,11 +1463,10 @@ void CdbEngine::activateFrame(int index)
if (showAssembler) { // Assembly code: Clean out model and force instruction mode.
watchHandler()->removeAllData();
QAction *assemblerAction = theAssemblerAction();
- if (assemblerAction->isChecked()) {
+ if (assemblerAction->isChecked())
gotoLocation(frame);
- } else {
+ else
assemblerAction->trigger(); // Seems to trigger update
- }
} else {
gotoLocation(frame);
updateLocals(true);
@@ -1474,7 +1499,7 @@ void CdbEngine::updateLocals(bool forNewStackFrame)
if (!expanded.isEmpty()) {
str << blankSeparator << "-e ";
int i = 0;
- foreach(const QByteArray &e, expanded) {
+ foreach (const QByteArray &e, expanded) {
if (i++)
str << ',';
str << e;
@@ -1490,7 +1515,7 @@ void CdbEngine::updateLocals(bool forNewStackFrame)
if (!uninitializedVariables.isEmpty()) {
str << blankSeparator << "-u \"";
int i = 0;
- foreach(const QString &u, uninitializedVariables) {
+ foreach (const QString &u, uninitializedVariables) {
if (i++)
str << ',';
str << localsPrefixC << u;
@@ -1516,15 +1541,14 @@ void CdbEngine::updateLocals(bool forNewStackFrame)
QVariant(flags));
}
-void CdbEngine::selectThread(int index)
+void CdbEngine::selectThread(ThreadId threadId)
{
- if (index < 0 || index == threadsHandler()->currentThread())
+ if (!threadId.isValid() || threadId == threadsHandler()->currentThread())
return;
- const int newThreadId = threadsHandler()->threads().at(index).id;
- threadsHandler()->setCurrentThread(index);
+ threadsHandler()->setCurrentThread(threadId);
- const QByteArray cmd = '~' + QByteArray::number(newThreadId) + " s";
+ const QByteArray cmd = '~' + QByteArray::number(threadId.raw()) + " s";
postBuiltinCommand(cmd, 0, &CdbEngine::dummyHandler, CommandListStack);
}
@@ -1684,7 +1708,7 @@ void CdbEngine::handleResolveSymbol(const QList<quint64> &addresses, const QVari
{
// Disassembly mode: Determine suitable range containing the
// agent's address within the function to display.
- if (qVariantCanConvert<DisassemblerAgent*>(cookie)) {
+ if (cookie.canConvert<DisassemblerAgent*>()) {
DisassemblerAgent *agent = cookie.value<DisassemblerAgent *>();
const quint64 agentAddress = agent->address();
quint64 functionAddress = 0;
@@ -1723,7 +1747,7 @@ void CdbEngine::handleResolveSymbol(const QList<quint64> &addresses, const QVari
// Parse: "00000000`77606060 cc int 3"
void CdbEngine::handleDisassembler(const CdbBuiltinCommandPtr &command)
{
- QTC_ASSERT(qVariantCanConvert<DisassemblerAgent*>(command->cookie), return);
+ QTC_ASSERT(command->cookie.canConvert<DisassemblerAgent*>(), return);
DisassemblerAgent *agent = qvariant_cast<DisassemblerAgent*>(command->cookie);
agent->setContents(parseCdbDisassembler(command->reply));
}
@@ -1733,11 +1757,10 @@ void CdbEngine::fetchMemory(MemoryAgent *agent, QObject *editor, quint64 addr, q
if (debug)
qDebug("CdbEngine::fetchMemory %llu bytes from 0x%llx", length, addr);
const MemoryViewCookie cookie(agent, editor, addr, length);
- if (m_accessible) {
+ if (m_accessible)
postFetchMemory(cookie);
- } else {
+ else
doInterruptInferiorCustomSpecialStop(qVariantFromValue(cookie));
- }
}
void CdbEngine::postFetchMemory(const MemoryViewCookie &cookie)
@@ -1762,7 +1785,7 @@ void CdbEngine::changeMemory(Internal::MemoryAgent *, QObject *, quint64 addr, c
void CdbEngine::handleMemory(const CdbExtensionCommandPtr &command)
{
- QTC_ASSERT(qVariantCanConvert<MemoryViewCookie>(command->cookie), return);
+ QTC_ASSERT(command->cookie.canConvert<MemoryViewCookie>(), return);
const MemoryViewCookie memViewCookie = qvariant_cast<MemoryViewCookie>(command->cookie);
if (command->success) {
const QByteArray data = QByteArray::fromBase64(command->reply);
@@ -1902,9 +1925,8 @@ void CdbEngine::handleLocals(const CdbExtensionCommandPtr &reply)
GdbMi root;
root.fromString(reply->reply);
QTC_ASSERT(root.isList(), return);
- if (debugLocals) {
+ if (debugLocals)
qDebug() << root.toString(true, 4);
- }
// Courtesy of GDB engine
foreach (const GdbMi &child, root.children()) {
WatchData dummy;
@@ -2046,12 +2068,10 @@ unsigned CdbEngine::examineStopReason(const GdbMi &stopReason,
if (reason == "breakpoint") {
// Note: Internal breakpoints (run to line) are reported with id=0.
// Step out creates temporary breakpoints with id 10000.
- BreakpointModelId id;
int number = 0;
- const GdbMi breakpointIdG = stopReason.findChild("breakpointId");
- if (breakpointIdG.isValid()) {
- id = BreakpointModelId(breakpointIdG.data().toInt());
- if (id && breakHandler()->engineBreakpointIds(this).contains(id)) {
+ BreakpointModelId id = cdbIdToBreakpointModelId(stopReason.findChild("breakpointId"));
+ if (id.isValid()) {
+ if (breakHandler()->engineBreakpointIds(this).contains(id)) {
const BreakpointResponse parameters = breakHandler()->response(id);
if (!parameters.message.isEmpty()) {
showMessage(parameters.message + QLatin1Char('\n'), AppOutput);
@@ -2077,13 +2097,12 @@ unsigned CdbEngine::examineStopReason(const GdbMi &stopReason,
}
}
QString tid = QString::number(threadId);
- if (id && breakHandler()->type(id) == WatchpointAtAddress) {
+ if (id && breakHandler()->type(id) == WatchpointAtAddress)
*message = msgWatchpointByAddressTriggered(id, number, breakHandler()->address(id), tid);
- } else if (id && breakHandler()->type(id) == WatchpointAtExpression) {
+ else if (id && breakHandler()->type(id) == WatchpointAtExpression)
*message = msgWatchpointByExpressionTriggered(id, number, breakHandler()->expression(id), tid);
- } else {
+ else
*message = msgBreakpointTriggered(id, number, tid);
- }
rc |= StopReportStatusMessage|StopNotifyStop;
return rc;
}
@@ -2091,7 +2110,6 @@ unsigned CdbEngine::examineStopReason(const GdbMi &stopReason,
WinException exception;
exception.fromGdbMI(stopReason);
QString description = exception.toString();
-#ifdef Q_OS_WIN
// It is possible to hit on a startup trap or WOW86 exception while stepping (if something
// pulls DLLs. Avoid showing a 'stopped' Message box.
if (exception.exceptionCode == winExceptionStartupCompleteTrap
@@ -2111,7 +2129,6 @@ unsigned CdbEngine::examineStopReason(const GdbMi &stopReason,
*message = msgInterrupted();
return rc;
}
-#endif
*exceptionBoxMessage = msgStoppedByException(description, QString::number(threadId));
*message = description;
rc |= StopShowExceptionMessageBox|StopReportStatusMessage|StopNotifyStop;
@@ -2140,7 +2157,7 @@ void CdbEngine::handleSessionIdle(const QByteArray &messageBA)
m_specialStopMode = NoSpecialStop;
- switch(specialStopMode) {
+ switch (specialStopMode) {
case SpecialStopSynchronizeBreakpoints:
if (debug)
qDebug("attemptBreakpointSynchronization in special stop");
@@ -2181,7 +2198,7 @@ void CdbEngine::processStop(const GdbMi &stopReason, bool conditionalBreakPointT
// Further examine stop and report to user
QString message;
QString exceptionBoxMessage;
- int forcedThreadId = -1;
+ ThreadId forcedThreadId;
const unsigned stopFlags = examineStopReason(stopReason, &message, &exceptionBoxMessage,
conditionalBreakPointTriggered);
// Do the non-blocking log reporting
@@ -2218,7 +2235,7 @@ void CdbEngine::processStop(const GdbMi &stopReason, bool conditionalBreakPointT
if (stopFlags & StopInArtificialThread) {
showMessage(tr("Switching to main thread..."), LogMisc);
postCommand("~0 s", 0);
- forcedThreadId = 0;
+ forcedThreadId = ThreadId(0);
// Re-fetch stack again.
postCommandSequence(CommandListStack);
} else {
@@ -2234,7 +2251,9 @@ void CdbEngine::processStop(const GdbMi &stopReason, bool conditionalBreakPointT
}
const GdbMi threads = stopReason.findChild("threads");
if (threads.isValid()) {
- parseThreads(threads, forcedThreadId);
+ threadsHandler()->updateThreads(threads);
+ if (forcedThreadId.isValid())
+ threadsHandler()->setCurrentThread(forcedThreadId);
} else {
showMessage(QString::fromLatin1(stopReason.findChild("threaderror").data()), LogError);
}
@@ -2262,7 +2281,7 @@ void CdbEngine::handleSessionAccessible(unsigned long cdbExState)
qDebug("CdbEngine::handleSessionAccessible %dms in state '%s'/'%s', special mode %d",
elapsedLogTime(), cdbStatusName(cdbExState), stateName(state()), m_specialStopMode);
- switch(s) {
+ switch (s) {
case EngineShutdownRequested:
shutdownEngine();
break;
@@ -2321,11 +2340,10 @@ void CdbEngine::handleExtensionMessage(char t, int token, const QByteArray &what
QDebug nospace = qDebug().nospace();
nospace << "handleExtensionMessage " << t << ' ' << token << ' ' << what
<< ' ' << stateName(state());
- if (t == 'N' || debug > 1) {
+ if (t == 'N' || debug > 1)
nospace << ' ' << message;
- } else {
+ else
nospace << ' ' << message.size() << " bytes";
- }
}
// Is there a reply expected, some command queued?
@@ -2392,10 +2410,20 @@ void CdbEngine::handleExtensionMessage(char t, int token, const QByteArray &what
exception.fromGdbMI(gdbmi);
const QString message = exception.toString(true);
showStatusMessage(message);
-#ifdef Q_OS_WIN // Report C++ exception in application output as well.
+ // Report C++ exception in application output as well.
if (exception.exceptionCode == winExceptionCppException)
showMessage(message + QLatin1Char('\n'), AppOutput);
-#endif
+ if (!isDebuggerWinException(exception.exceptionCode)) {
+ const Task::TaskType type =
+ isFatalWinException(exception.exceptionCode) ? Task::Error : Task::Warning;
+ const Utils::FileName fileName = exception.file.isEmpty() ?
+ Utils::FileName() :
+ Utils::FileName::fromUserInput(QString::fromLocal8Bit(exception.file));
+ const Task task(type, exception.toString(false),
+ fileName, exception.lineNumber,
+ Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME));
+ taskHub()->addTask(task);
+ }
return;
}
@@ -2556,7 +2584,7 @@ static QByteArray multiBreakpointCommand(const char *cmdC, const Breakpoints &bp
{
QByteArray cmd(cmdC);
ByteArrayInputStream str(cmd);
- foreach(const BreakpointData *bp, bps)
+ foreach (const BreakpointData *bp, bps)
str << ' ' << bp->bpNumber;
return cmd;
}
@@ -2750,21 +2778,21 @@ void CdbEngine::attemptBreakpointSynchronization()
if (parameters.enabled != handler->response(id).enabled) {
// Change enabled/disabled breakpoints without triggering update.
postCommand((parameters.enabled ? "be " : "bd ")
- + QByteArray::number(id.majorPart()), 0);
+ + QByteArray::number(breakPointIdToCdbId(id)), 0);
response.pending = false;
response.enabled = parameters.enabled;
handler->setResponse(id, response);
} else {
// Delete and re-add, triggering update
addedChanged = true;
- postCommand("bc " + QByteArray::number(id.majorPart()), 0);
+ postCommand("bc " + QByteArray::number(breakPointIdToCdbId(id)), 0);
postCommand(cdbAddBreakpointCommand(parameters, m_sourcePathMappings, id, false), 0);
m_pendingBreakpointMap.insert(id, response);
}
handler->notifyBreakpointChangeOk(id);
break;
case BreakpointRemoveRequested:
- postCommand("bc " + QByteArray::number(id.majorPart()), 0);
+ postCommand("bc " + QByteArray::number(breakPointIdToCdbId(id)), 0);
handler->notifyBreakpointRemoveProceeding(id);
handler->notifyBreakpointRemoveOk(id);
m_pendingBreakpointMap.remove(id);
@@ -2815,13 +2843,20 @@ CdbEngine::NormalizedSourceFileName CdbEngine::sourceMapNormalizeFileNameFromDeb
// Parse frame from GDBMI. Duplicate of the gdb code, but that
// has more processing.
-static StackFrames parseFrames(const GdbMi &gdbmi)
+static StackFrames parseFrames(const GdbMi &gdbmi, bool *incomplete = 0)
{
+ if (incomplete)
+ *incomplete = false;
StackFrames rc;
const int count = gdbmi.childCount();
rc.reserve(count);
for (int i = 0; i < count; i++) {
const GdbMi &frameMi = gdbmi.childAt(i);
+ if (!frameMi.childCount()) { // Empty item indicates "More...".
+ if (incomplete)
+ *incomplete = true;
+ break;
+ }
StackFrame frame;
frame.level = i;
const GdbMi fullName = frameMi.findChild("fullname");
@@ -2846,7 +2881,8 @@ unsigned CdbEngine::parseStackTrace(const GdbMi &data, bool sourceStepInto)
// 'ILT+'). If that is the case, execute another 't' to step into the actual function. .
// Note that executing 't 2' does not work since it steps 2 instructions on a non-call code line.
int current = -1;
- StackFrames frames = parseFrames(data);
+ bool incomplete;
+ StackFrames frames = parseFrames(data, &incomplete);
const int count = frames.size();
for (int i = 0; i < count; i++) {
const bool hasFile = !frames.at(i).file.isEmpty();
@@ -2866,7 +2902,7 @@ unsigned CdbEngine::parseStackTrace(const GdbMi &data, bool sourceStepInto)
if (count && current == -1) // No usable frame, use assembly.
current = 0;
// Set
- stackHandler()->setFrames(frames);
+ stackHandler()->setFrames(frames, incomplete);
activateFrame(current);
return 0;
}
@@ -2886,13 +2922,12 @@ void CdbEngine::handleStackTrace(const CdbExtensionCommandPtr &command)
void CdbEngine::handleExpression(const CdbExtensionCommandPtr &command)
{
int value = 0;
- if (command->success) {
+ if (command->success)
value = command->reply.toInt();
- } else {
+ else
showMessage(QString::fromLocal8Bit(command->errorMessage), LogError);
- }
// Is this a conditional breakpoint?
- if (command->cookie.isValid() && qVariantCanConvert<ConditionalBreakPointCookie>(command->cookie)) {
+ if (command->cookie.isValid() && command->cookie.canConvert<ConditionalBreakPointCookie>()) {
const ConditionalBreakPointCookie cookie = qvariant_cast<ConditionalBreakPointCookie>(command->cookie);
const QString message = value ?
tr("Value %1 obtained from evaluating the condition of breakpoint %2, stopping.").
@@ -2901,11 +2936,10 @@ void CdbEngine::handleExpression(const CdbExtensionCommandPtr &command)
arg(cookie.id.toString());
showMessage(message, LogMisc);
// Stop if evaluation is true, else continue
- if (value) {
+ if (value)
processStop(cookie.stopReason, true);
- } else {
+ else
postCommand("g", 0);
- }
}
}
@@ -2936,11 +2970,11 @@ void CdbEngine::postCommandSequence(unsigned mask)
return;
}
if (mask & CommandListStack) {
- postExtensionCommand("stack", QByteArray(), 0, &CdbEngine::handleStackTrace, mask & ~CommandListStack);
+ postExtensionCommand("stack", "unlimited", 0, &CdbEngine::handleStackTrace, mask & ~CommandListStack);
return;
}
if (mask & CommandListRegisters) {
- QTC_ASSERT(threadsHandler()->currentThread() >= 0, return);
+ QTC_ASSERT(threadsHandler()->currentThreadIndex() >= 0, return);
postExtensionCommand("registers", QByteArray(), 0, &CdbEngine::handleRegisters, mask & ~CommandListRegisters);
return;
}
@@ -3061,11 +3095,10 @@ void CdbEngine::handleBreakPoints(const GdbMi &value)
}
} // not pending reported
} // foreach
- if (m_pendingBreakpointMap.empty()) {
+ if (m_pendingBreakpointMap.empty())
str << QLatin1String("All breakpoints have been resolved.\n");
- } else {
+ else
str << QString::fromLatin1("%1 breakpoint(s) pending...\n").arg(m_pendingBreakpointMap.size());
- }
showMessage(message, LogMisc);
}
@@ -3101,13 +3134,13 @@ void CdbEngine::postWidgetAtCommand()
void CdbEngine::handleCustomSpecialStop(const QVariant &v)
{
- if (qVariantCanConvert<MemoryChangeCookie>(v)) {
- const MemoryChangeCookie changeData = qVariantValue<MemoryChangeCookie>(v);
+ if (v.canConvert<MemoryChangeCookie>()) {
+ const MemoryChangeCookie changeData = qvariant_cast<MemoryChangeCookie>(v);
postCommand(cdbWriteMemoryCommand(changeData.address, changeData.data), 0);
return;
}
- if (qVariantCanConvert<MemoryViewCookie>(v)) {
- postFetchMemory(qVariantValue<MemoryViewCookie>(v));
+ if (v.canConvert<MemoryViewCookie>()) {
+ postFetchMemory(qvariant_cast<MemoryViewCookie>(v));
return;
}
}
diff --git a/src/plugins/debugger/cdb/cdbengine.h b/src/plugins/debugger/cdb/cdbengine.h
index a81c87094e..e063fafad2 100644
--- a/src/plugins/debugger/cdb/cdbengine.h
+++ b/src/plugins/debugger/cdb/cdbengine.h
@@ -32,6 +32,7 @@
#include "debuggerengine.h"
#include "breakpoint.h"
+#include "threaddata.h"
#include <QSharedPointer>
#include <QProcess>
@@ -113,7 +114,7 @@ public:
virtual void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
virtual void activateFrame(int index);
- virtual void selectThread(int index);
+ virtual void selectThread(ThreadId threadId);
virtual bool stateAcceptsBreakpointChanges() const;
virtual bool acceptsBreakpoint(BreakpointModelId id) const;
@@ -242,7 +243,6 @@ private:
int elapsedLogTime() const;
void addLocalsOptions(ByteArrayInputStream &s) const;
unsigned parseStackTrace(const GdbMi &data, bool sourceStepInto);
- void parseThreads(const GdbMi &, int forceCurrentThreadId = -1);
const QByteArray m_creatorExtPrefix;
const QByteArray m_tokenPrefix;
@@ -265,6 +265,7 @@ private:
bool m_operateByInstruction;
bool m_notifyEngineShutdownOnTermination;
bool m_hasDebuggee;
+ bool m_cdbIs64Bit;
QTime m_logTime;
mutable int m_elapsedLogTime;
QByteArray m_extensionMessageBuffer;
diff --git a/src/plugins/debugger/cdb/cdboptions.cpp b/src/plugins/debugger/cdb/cdboptions.cpp
index 6f7f20cecb..99a5832e60 100644
--- a/src/plugins/debugger/cdb/cdboptions.cpp
+++ b/src/plugins/debugger/cdb/cdboptions.cpp
@@ -39,13 +39,17 @@ static const char breakFunctionsKeyC[] = "BreakFunctions";
static const char additionalArgumentsKeyC[] = "AdditionalArguments";
static const char cdbConsoleKeyC[] = "CDB_Console";
static const char breakpointCorrectionKeyC[] = "BreakpointCorrection";
+static const char ignoreFirstChanceAccessViolationKeyC[] = "IgnoreFirstChanceAccessViolation";
namespace Debugger {
namespace Internal {
const char *CdbOptions::crtDbgReport = "CrtDbgReport";
-CdbOptions::CdbOptions() : cdbConsole(false), breakpointCorrection(true)
+CdbOptions::CdbOptions()
+ : cdbConsole(false)
+ , breakpointCorrection(true)
+ , ignoreFirstChanceAccessViolation(false)
{
}
@@ -58,7 +62,8 @@ void CdbOptions::clear()
{
symbolPaths.clear();
sourcePaths.clear();
- cdbConsole = false;
+ breakpointCorrection = true;
+ cdbConsole = ignoreFirstChanceAccessViolation = false;
breakEvents.clear();
breakFunctions.clear();
}
@@ -79,6 +84,7 @@ void CdbOptions::fromSettings(QSettings *s)
breakFunctions = s->value(keyRoot + QLatin1String(breakFunctionsKeyC), QStringList()).toStringList();
cdbConsole = s->value(keyRoot + QLatin1String(cdbConsoleKeyC), QVariant(false)).toBool();
breakpointCorrection = s->value(keyRoot + QLatin1String(breakpointCorrectionKeyC), QVariant(true)).toBool();
+ ignoreFirstChanceAccessViolation = s->value(keyRoot + QLatin1String(ignoreFirstChanceAccessViolationKeyC), false).toBool();
}
void CdbOptions::toSettings(QSettings *s) const
@@ -91,6 +97,7 @@ void CdbOptions::toSettings(QSettings *s) const
s->setValue(QLatin1String(additionalArgumentsKeyC), additionalArguments);
s->setValue(QLatin1String(cdbConsoleKeyC), QVariant(cdbConsole));
s->setValue(QLatin1String(breakpointCorrectionKeyC), QVariant(breakpointCorrection));
+ s->setValue(QLatin1String(ignoreFirstChanceAccessViolationKeyC), QVariant(ignoreFirstChanceAccessViolation));
s->endGroup();
}
@@ -98,6 +105,7 @@ bool CdbOptions::equals(const CdbOptions &rhs) const
{
return cdbConsole == rhs.cdbConsole
&& breakpointCorrection == rhs.breakpointCorrection
+ && ignoreFirstChanceAccessViolation == rhs.ignoreFirstChanceAccessViolation
&& additionalArguments == rhs.additionalArguments
&& symbolPaths == rhs.symbolPaths
&& sourcePaths == rhs.sourcePaths
diff --git a/src/plugins/debugger/cdb/cdboptions.h b/src/plugins/debugger/cdb/cdboptions.h
index d29c9a8cb6..93801bfd46 100644
--- a/src/plugins/debugger/cdb/cdboptions.h
+++ b/src/plugins/debugger/cdb/cdboptions.h
@@ -66,6 +66,8 @@ public:
bool cdbConsole;
// Perform code-model based correction of breakpoint location.
bool breakpointCorrection;
+ // Add -x to command line.
+ bool ignoreFirstChanceAccessViolation;
static const char *crtDbgReport;
};
diff --git a/src/plugins/debugger/cdb/cdboptionspage.cpp b/src/plugins/debugger/cdb/cdboptionspage.cpp
index 0a766a140e..7f28581b61 100644
--- a/src/plugins/debugger/cdb/cdboptionspage.cpp
+++ b/src/plugins/debugger/cdb/cdboptionspage.cpp
@@ -32,6 +32,7 @@
#include "commonoptionspage.h"
#include "debuggerinternalconstants.h"
#include "cdbengine.h"
+#include "cdbsymbolpathlisteditor.h"
#include <utils/synchronousprocess.h>
@@ -39,7 +40,10 @@
#include <QTextStream>
#include <QLineEdit>
+#include <QDialogButtonBox>
+#include <QPushButton>
#include <QCheckBox>
+#include <QVBoxLayout>
namespace Debugger {
namespace Internal {
@@ -157,6 +161,46 @@ QStringList CdbBreakEventWidget::breakEvents() const
return rc;
}
+CdbPathDialog::CdbPathDialog(QWidget *parent, Mode mode)
+ : QDialog(parent)
+ , m_pathListEditor(0)
+{
+ setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
+ setMinimumWidth(700);
+
+ switch (mode) {
+ case SymbolPaths:
+ setWindowTitle(tr("CDB Symbol Paths"));
+ m_pathListEditor = new CdbSymbolPathListEditor(this);
+ break;
+ case SourcePaths:
+ setWindowTitle(tr("CDB Source Paths"));
+ m_pathListEditor = new Utils::PathListEditor(this);
+ break;
+ }
+
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ QGroupBox *groupBox = new QGroupBox(this);
+ (new QVBoxLayout(groupBox))->addWidget(m_pathListEditor);
+ layout->addWidget(groupBox);
+ QDialogButtonBox *buttonBox =
+ new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
+ Qt::Horizontal, this);
+ connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
+ connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
+ layout->addWidget(buttonBox);
+}
+
+QStringList CdbPathDialog::paths() const
+{
+ return m_pathListEditor->pathList();
+}
+
+void CdbPathDialog::setPaths(const QStringList &paths)
+{
+ m_pathListEditor->setPathList(paths);
+}
+
CdbOptionsPageWidget::CdbOptionsPageWidget(QWidget *parent) :
QWidget(parent), m_breakEventWidget(new CdbBreakEventWidget)
{
@@ -165,11 +209,11 @@ CdbOptionsPageWidget::CdbOptionsPageWidget(QWidget *parent) :
// accommodate all options. This page only shows on
// Windows, which has large margins by default.
- const int margin = m_ui.verticalLayout->margin();
+ const int margin = layout()->margin();
const QMargins margins(margin, margin / 3, margin, margin / 3);
m_ui.startupFormLayout->setContentsMargins(margins);
- m_ui.pathFormLayout->setContentsMargins(margins);
+ m_ui.pathGroupBox->layout()->setContentsMargins(margins);
m_ui.breakpointLayout->setContentsMargins(margins);
QVBoxLayout *eventLayout = new QVBoxLayout;
@@ -181,13 +225,35 @@ CdbOptionsPageWidget::CdbOptionsPageWidget(QWidget *parent) :
const QString hint = tr("This is useful to catch runtime error messages, for example caused by assert().");
m_ui.breakCrtDbgReportCheckBox
->setToolTip(CommonOptionsPage::msgSetBreakpointAtFunctionToolTip(CdbOptions::crtDbgReport, hint));
+
+ connect(m_ui.symbolPathButton, SIGNAL(clicked()), this, SLOT(showSymbolPathDialog()));
+ connect(m_ui.sourcePathButton, SIGNAL(clicked()), this, SLOT(showSourcePathDialog()));
+}
+
+void CdbOptionsPageWidget::setSymbolPaths(const QStringList &s)
+{
+ m_symbolPaths = s;
+ const QString summary =
+ tr("Symbol paths: %1").arg(m_symbolPaths.isEmpty() ?
+ tr("<none>") : QString::number(m_symbolPaths.size()));
+ m_ui.symbolPathLabel->setText(summary);
+}
+
+void CdbOptionsPageWidget::setSourcePaths(const QStringList &s)
+{
+ m_sourcePaths = s;
+ const QString summary =
+ tr("Source paths: %1").arg(m_sourcePaths.isEmpty() ?
+ tr("<none>") : QString::number(m_sourcePaths.size()));
+ m_ui.sourcePathLabel->setText(summary);
}
void CdbOptionsPageWidget::setOptions(CdbOptions &o)
{
m_ui.additionalArgumentsLineEdit->setText(o.additionalArguments);
setSymbolPaths(o.symbolPaths);
- m_ui.sourcePathListEditor->setPathList(o.sourcePaths);
+ setSourcePaths(o.sourcePaths);
+ m_ui.ignoreFirstChanceAccessViolationCheckBox->setChecked(o.ignoreFirstChanceAccessViolation);
m_breakEventWidget->setBreakEvents(o.breakEvents);
m_ui.consoleCheckBox->setChecked(o.cdbConsole);
m_ui.breakpointCorrectionCheckBox->setChecked(o.breakpointCorrection);
@@ -198,8 +264,9 @@ CdbOptions CdbOptionsPageWidget::options() const
{
CdbOptions rc;
rc.additionalArguments = m_ui.additionalArgumentsLineEdit->text().trimmed();
- rc.symbolPaths = symbolPaths();
- rc.sourcePaths = m_ui.sourcePathListEditor->pathList();
+ rc.symbolPaths = m_symbolPaths;
+ rc.sourcePaths = m_sourcePaths;
+ rc.ignoreFirstChanceAccessViolation = m_ui.ignoreFirstChanceAccessViolationCheckBox->isChecked();
rc.breakEvents = m_breakEventWidget->breakEvents();
rc.cdbConsole = m_ui.consoleCheckBox->isChecked();
rc.breakpointCorrection = m_ui.breakpointCorrectionCheckBox->isChecked();
@@ -208,21 +275,39 @@ CdbOptions CdbOptionsPageWidget::options() const
return rc;
}
-QStringList CdbOptionsPageWidget::symbolPaths() const
+void CdbOptionsPageWidget::showSymbolPathDialog()
{
- return m_ui.symbolPathListEditor->pathList();
+ CdbPathDialog pathDialog(this, CdbPathDialog::SymbolPaths);
+ pathDialog.setPaths(m_symbolPaths);
+ if (pathDialog.exec() == QDialog::Accepted)
+ setSymbolPaths(pathDialog.paths());
}
-void CdbOptionsPageWidget::setSymbolPaths(const QStringList &s)
+void CdbOptionsPageWidget::showSourcePathDialog()
{
- m_ui.symbolPathListEditor->setPathList(s);
+ CdbPathDialog pathDialog(this, CdbPathDialog::SourcePaths);
+ pathDialog.setPaths(m_sourcePaths);
+ if (pathDialog.exec() == QDialog::Accepted)
+ setSourcePaths(pathDialog.paths());
+}
+
+static QString stripColon(QString s)
+{
+ const int lastColon = s.lastIndexOf(QLatin1Char(':'));
+ if (lastColon != -1)
+ s.truncate(lastColon);
+ return s;
}
QString CdbOptionsPageWidget::searchKeywords() const
{
QString rc;
- QTextStream(&rc) << m_ui.symbolPathLabel->text()
- << ' ' << m_ui.sourcePathLabel->text();
+ QTextStream(&rc)
+ << stripColon(m_ui.additionalArgumentsLabel->text()) << ' '
+ << stripColon(m_ui.breakFunctionGroupBox->title()) << ' '
+ << m_ui.breakpointsGroupBox->title() << ' '
+ << stripColon(m_ui.symbolPathLabel->text()) << ' '
+ << stripColon(m_ui.sourcePathLabel->text());
rc.remove(QLatin1Char('&'));
return rc;
}
@@ -237,20 +322,14 @@ CdbOptionsPage::CdbOptionsPage() :
CdbOptionsPage::m_instance = this;
m_options->fromSettings(Core::ICore::settings());
- setId(CdbOptionsPage::settingsId());
-
+ setId("F.Cda");
setDisplayName(tr("CDB"));
- setCategory(QLatin1String(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY));
+ setCategory(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Debugger",
Constants::DEBUGGER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::DEBUGGER_COMMON_SETTINGS_CATEGORY_ICON));
}
-QString CdbOptionsPage::settingsId()
-{
- return QLatin1String("F.Cda");
-}
-
CdbOptionsPage::~CdbOptionsPage()
{
CdbOptionsPage::m_instance = 0;
diff --git a/src/plugins/debugger/cdb/cdboptionspage.h b/src/plugins/debugger/cdb/cdboptionspage.h
index 4d8c5fbcf7..cc871a4efd 100644
--- a/src/plugins/debugger/cdb/cdboptionspage.h
+++ b/src/plugins/debugger/cdb/cdboptionspage.h
@@ -38,14 +38,20 @@
#include <QWidget>
#include <QPointer>
#include <QSharedPointer>
+#include <QDialog>
QT_BEGIN_NAMESPACE
class QCheckBox;
QT_END_NAMESPACE
+namespace Utils {
+ class PathListEditor;
+}
namespace Debugger {
namespace Internal {
+class CdbSymbolPathListEditor;
+
// Widget displaying a list of break events for the 'sxe' command
// with a checkbox to enable 'break' and optionally a QLineEdit for
// events with parameters (like 'out:Needle').
@@ -67,6 +73,24 @@ private:
QList<QLineEdit*> m_lineEdits;
};
+class CdbPathDialog : public QDialog
+{
+ Q_OBJECT
+public:
+ enum Mode {
+ SymbolPaths,
+ SourcePaths
+ };
+
+ explicit CdbPathDialog(QWidget *parent, Mode mode);
+
+ QStringList paths() const;
+ void setPaths(const QStringList &paths);
+
+private:
+ Utils::PathListEditor *m_pathListEditor;
+};
+
class CdbOptionsPageWidget : public QWidget
{
Q_OBJECT
@@ -79,13 +103,20 @@ public:
QString searchKeywords() const;
+private slots:
+ void showSymbolPathDialog();
+ void showSourcePathDialog();
+
private:
- QStringList symbolPaths() const;
- void setSymbolPaths(const QStringList &s);
+ void setSymbolPaths(const QStringList &);
+ void setSourcePaths(const QStringList &);
+
inline QString path() const;
Ui::CdbOptionsPageWidget m_ui;
CdbBreakEventWidget *m_breakEventWidget;
+ QStringList m_symbolPaths;
+ QStringList m_sourcePaths;
};
class CdbOptionsPage : public Core::IOptionsPage
@@ -97,7 +128,6 @@ public:
virtual ~CdbOptionsPage();
static CdbOptionsPage *instance();
- static QString settingsId();
// IOptionsPage
QWidget *createPage(QWidget *parent);
diff --git a/src/plugins/debugger/cdb/cdboptionspagewidget.ui b/src/plugins/debugger/cdb/cdboptionspagewidget.ui
index 41b3d6a1ff..647449105f 100644
--- a/src/plugins/debugger/cdb/cdboptionspagewidget.ui
+++ b/src/plugins/debugger/cdb/cdboptionspagewidget.ui
@@ -12,8 +12,8 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <item row="0" column="0">
<widget class="QGroupBox" name="cdbPathGroupBox">
<property name="title">
<string extracomment="Placeholder">Startup</string>
@@ -54,59 +54,99 @@
</layout>
</widget>
</item>
+ <item row="0" column="1">
+ <widget class="QGroupBox" name="pathGroupBox">
+ <property name="title">
+ <string>Paths</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="symbolPathLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QPushButton" name="symbolPathButton">
+ <property name="text">
+ <string>Edit...</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="sourcePathLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QPushButton" name="sourcePathButton">
+ <property name="text">
+ <string>Edit...</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QGroupBox" name="breakpointsGroupBox">
+ <property name="title">
+ <string>Breakpoints</string>
+ </property>
+ <layout class="QVBoxLayout" name="breakpointLayout">
+ <item>
+ <widget class="QCheckBox" name="breakpointCorrectionCheckBox">
+ <property name="toolTip">
+ <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Attempt to correct the location of a breakpoint based on file and line number should it be in a comment or in a line for which no code is generated. The correction is based on the code model.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
+ </property>
+ <property name="text">
+ <string>Correct breakpoint location</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QGroupBox" name="breakFunctionGroupBox">
+ <property name="title">
+ <string>Break on functions:</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="QCheckBox" name="breakCrtDbgReportCheckBox"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="2" column="0" colspan="2">
+ <widget class="QGroupBox" name="eventGroupBox">
+ <property name="title">
+ <string>Break on:</string>
+ </property>
+ </widget>
+ </item>
</layout>
</item>
<item>
- <widget class="QGroupBox" name="startupGroupBox">
+ <widget class="QGroupBox" name="variousGroupBox">
<property name="title">
- <string>Debugger Paths</string>
+ <string>Various</string>
</property>
- <layout class="QFormLayout" name="pathFormLayout">
- <property name="fieldGrowthPolicy">
- <enum>QFormLayout::AllNonFixedFieldsGrow</enum>
- </property>
- <item row="0" column="0">
- <widget class="QLabel" name="symbolPathLabel">
- <property name="text">
- <string>&amp;Symbol paths:</string>
- </property>
- <property name="buddy">
- <cstring>symbolPathListEditor</cstring>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="Debugger::Internal::CdbSymbolPathListEditor" name="symbolPathListEditor" native="true"/>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="sourcePathLabel">
- <property name="text">
- <string>S&amp;ource paths:</string>
- </property>
- <property name="buddy">
- <cstring>sourcePathListEditor</cstring>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="Utils::PathListEditor" name="sourcePathListEditor" native="true"/>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="breakpointsGroupBox">
- <property name="title">
- <string>Breakpoints</string>
- </property>
- <layout class="QVBoxLayout" name="breakpointLayout">
+ <layout class="QVBoxLayout" name="verticalLayout_3">
<item>
- <widget class="QCheckBox" name="breakpointCorrectionCheckBox">
- <property name="toolTip">
- <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Attempt to correct the location of a breakpoint based on file and line number should it be in a comment or in a line for which no code is generated. The correction is based on the code model.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
- </property>
+ <widget class="QCheckBox" name="ignoreFirstChanceAccessViolationCheckBox">
<property name="text">
- <string>Correct breakpoint location</string>
+ <string>Ignore first chance access violations</string>
</property>
</widget>
</item>
@@ -114,25 +154,6 @@
</widget>
</item>
<item>
- <widget class="QGroupBox" name="eventGroupBox">
- <property name="title">
- <string>Break on:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QGroupBox" name="breakFunctionGroupBox">
- <property name="title">
- <string>Break on functions:</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <item>
- <widget class="QCheckBox" name="breakCrtDbgReportCheckBox"/>
- </item>
- </layout>
- </widget>
- </item>
- <item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
@@ -147,20 +168,6 @@
</item>
</layout>
</widget>
- <customwidgets>
- <customwidget>
- <class>Utils::PathListEditor</class>
- <extends>QWidget</extends>
- <header location="global">utils/pathlisteditor.h</header>
- <container>1</container>
- </customwidget>
- <customwidget>
- <class>Debugger::Internal::CdbSymbolPathListEditor</class>
- <extends>QWidget</extends>
- <header location="global">cdbsymbolpathlisteditor.h</header>
- <container>1</container>
- </customwidget>
- </customwidgets>
<resources/>
<connections/>
</ui>
diff --git a/src/plugins/debugger/cdb/cdbparsehelpers.cpp b/src/plugins/debugger/cdb/cdbparsehelpers.cpp
index f894ec6659..b08679db87 100644
--- a/src/plugins/debugger/cdb/cdbparsehelpers.cpp
+++ b/src/plugins/debugger/cdb/cdbparsehelpers.cpp
@@ -28,13 +28,14 @@
****************************************************************************/
#include "cdbparsehelpers.h"
+
#include "breakpoint.h"
-#include "threadshandler.h"
-#include "registerhandler.h"
#include "bytearrayinputstream.h"
-#include "gdb/gdbmi.h"
+#include "debuggerprotocol.h"
#include "disassemblerlines.h"
+#include "registerhandler.h"
#include "shared/hostutils.h"
+#include "threadshandler.h"
#include <utils/qtcassert.h>
@@ -131,6 +132,33 @@ static BreakpointParameters fixWinMSVCBreakpoint(const BreakpointParameters &p)
return p;
}
+int breakPointIdToCdbId(const BreakpointModelId &id)
+{
+ return cdbBreakPointStartId + id.majorPart();
+}
+
+template <class ModelId>
+inline ModelId cdbIdToBreakpointId(const GdbMi &data)
+{
+ if (data.isValid()) { // Might not be valid if there is not id
+ bool ok;
+ const int id = data.data().toInt(&ok);
+ if (ok && id >= cdbBreakPointStartId)
+ return ModelId(id - cdbBreakPointStartId);
+ }
+ return ModelId();
+}
+
+BreakpointModelId cdbIdToBreakpointModelId(const GdbMi &id)
+{
+ return cdbIdToBreakpointId<BreakpointModelId>(id);
+}
+
+BreakpointResponseId cdbIdToBreakpointResponseId(const GdbMi &id)
+{
+ return cdbIdToBreakpointId<BreakpointResponseId>(id);
+}
+
QByteArray cdbAddBreakpointCommand(const BreakpointParameters &bpIn,
const QList<QPair<QString, QString> > &sourcePathMapping,
BreakpointModelId id /* = BreakpointId() */,
@@ -148,7 +176,7 @@ QByteArray cdbAddBreakpointCommand(const BreakpointParameters &bpIn,
// when resolving).
str << (bp.type == WatchpointAtAddress ? "ba" : "bu");
if (id.isValid())
- str << id.toString();
+ str << breakPointIdToCdbId(id);
str << ' ';
if (oneshot)
str << "/1 ";
@@ -263,7 +291,7 @@ static inline bool parseThread(QByteArray line, ThreadData *thread, bool *curren
thread->targetId = QLatin1String("0x") + QString::fromLatin1(pidTid.mid(dotPos + 1));
}
case 1:
- thread->id = tokens.at(0).toInt();
+ thread->id = ThreadId(tokens.at(0).toInt());
break;
} // switch size
return true;
@@ -304,13 +332,8 @@ void parseBreakPoint(const GdbMi &gdbmi, BreakpointResponse *r,
gdbmiChildToBool(gdbmi, "enabled", &(r->enabled));
gdbmiChildToBool(gdbmi, "deferred", &(r->pending));
r->id = BreakpointResponseId();
- const GdbMi idG = gdbmi.findChild("id");
- if (idG.isValid()) { // Might not be valid if there is not id
- bool ok;
- const int id = idG.data().toInt(&ok);
- if (ok)
- r->id = BreakpointResponseId(id);
- }
+ // Might not be valid if there is not id
+ r->id = cdbIdToBreakpointResponseId(gdbmi.findChild("id"));
const GdbMi moduleG = gdbmi.findChild("module");
if (moduleG.isValid())
r->module = QString::fromLocal8Bit(moduleG.data());
@@ -363,11 +386,10 @@ QString debugByteArray(const QByteArray &a)
str << "\\r";
break;
default:
- if (uc >=32 && uc < 128) {
+ if (uc >=32 && uc < 128)
str << a.at(i);
- } else {
+ else
str << '<' << unsigned(uc) << '>';
- }
break;
}
}
@@ -413,10 +435,10 @@ QString WinException::toString(bool includeLocation) const
{
QString rc;
QTextStream str(&rc);
-#ifdef Q_OS_WIN
formatWindowsException(exceptionCode, exceptionAddress,
exceptionFlags, info1, info2, str);
-#endif
+ if (firstChance)
+ str << " (first chance)";
if (includeLocation) {
if (lineNumber) {
str << " at " << QLatin1String(file) << ':' << lineNumber;
@@ -555,7 +577,7 @@ bool parseCdbDisassemblerLine(const QString &line, DisassemblerLine *dLine, uint
dLine->address = addressS.toULongLong(&ok, 16);
if (!ok)
return false;
- dLine->rawData = QByteArray::fromHex(line.mid(rawDataPos, rawDataEnd - rawDataPos).toAscii());
+ dLine->rawData = QByteArray::fromHex(line.mid(rawDataPos, rawDataEnd - rawDataPos).toLatin1());
dLine->data = line.right(line.size() - instructionPos).trimmed();
return true;
}
@@ -592,9 +614,8 @@ DisassemblerLines parseCdbDisassembler(const QList<QByteArray> &a)
}
// Determine address of function from the first assembler line after a
// function header line.
- if (!functionAddress && disassemblyLine.address) {
+ if (!functionAddress && disassemblyLine.address)
functionAddress = disassemblyLine.address - functionOffset;
- }
if (functionAddress && disassemblyLine.address)
disassemblyLine.offset = disassemblyLine.address - functionAddress;
disassemblyLine.function = currentFunction;
diff --git a/src/plugins/debugger/cdb/cdbparsehelpers.h b/src/plugins/debugger/cdb/cdbparsehelpers.h
index 4c8955a285..f271f518af 100644
--- a/src/plugins/debugger/cdb/cdbparsehelpers.h
+++ b/src/plugins/debugger/cdb/cdbparsehelpers.h
@@ -59,6 +59,13 @@ QString cdbSourcePathMapping(QString fileName,
const QList<QPair<QString, QString> > &sourcePathMapping,
SourcePathMode mode);
+// Ensure unique 'namespace' for breakpoints of the breakhandler.
+enum { cdbBreakPointStartId = 1000 };
+
+int breakPointIdToCdbId(const BreakpointModelId &id);
+BreakpointModelId cdbIdToBreakpointModelId(const GdbMi &id);
+BreakpointResponseId cdbIdToBreakpointResponseId(const GdbMi &id);
+
// Convert breakpoint in CDB syntax (applying source path mappings using native paths).
QByteArray cdbAddBreakpointCommand(const BreakpointParameters &d,
const QList<QPair<QString, QString> > &sourcePathMapping,
diff --git a/src/plugins/debugger/commonoptionspage.cpp b/src/plugins/debugger/commonoptionspage.cpp
index 10a2042635..61d4bf8dd6 100644
--- a/src/plugins/debugger/commonoptionspage.cpp
+++ b/src/plugins/debugger/commonoptionspage.cpp
@@ -36,11 +36,12 @@
#include <coreplugin/icore.h>
#include <coreplugin/manhattanstyle.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <projectexplorer/projectexplorer.h>
-#include <QFileInfo>
+#include <QLabel>
#include <QTextStream>
using namespace Core;
@@ -54,29 +55,113 @@ CommonOptionsPageWidget::CommonOptionsPageWidget
(const QSharedPointer<Utils::SavedActionSet> &group, QWidget *parent)
: QWidget(parent), m_group(group)
{
- m_ui.setupUi(this);
+ QGroupBox *behaviorBox = new QGroupBox(this);
+ behaviorBox->setTitle(tr("Behavior"));
+
+ checkBoxUseAlternatingRowColors = new QCheckBox(behaviorBox);
+ checkBoxUseAlternatingRowColors->setText(tr("Use alternating row colors in debug views"));
+
+ checkBoxFontSizeFollowsEditor = new QCheckBox(behaviorBox);
+ checkBoxFontSizeFollowsEditor->setToolTip(tr("Change the font size in the debugger views when the font size in the main editor changes."));
+ checkBoxFontSizeFollowsEditor->setText(tr("Debugger font size follows main editor"));
+
+ checkBoxUseToolTipsInMainEditor = new QCheckBox(behaviorBox);
+ checkBoxUseToolTipsInMainEditor->setText(tr("Use tooltips in main editor while debugging"));
+
+ checkBoxListSourceFiles = new QCheckBox(behaviorBox);
+ checkBoxListSourceFiles->setToolTip(tr("Populate the source file view automatically. This might slow down debugger startup considerably."));
+ checkBoxListSourceFiles->setText(tr("Populate source file view automatically"));
+
+ checkBoxCloseBuffersOnExit = new QCheckBox(behaviorBox);
+ checkBoxCloseBuffersOnExit->setText(tr("Close temporary buffers on debugger exit"));
+
+ checkBoxSwitchModeOnExit = new QCheckBox(behaviorBox);
+ checkBoxSwitchModeOnExit->setText(tr("Switch to previous mode on debugger exit"));
+
+ checkBoxBringToForegroundOnInterrrupt = new QCheckBox(behaviorBox);
+ checkBoxBringToForegroundOnInterrrupt->setText(tr("Bring Qt Creator to foreground when application interrupts"));
+
+ checkBoxShowQmlObjectTree = new QCheckBox(behaviorBox);
+ checkBoxShowQmlObjectTree->setToolTip(tr("Show QML object tree in Locals & Expressions when connected and not stepping."));
+ checkBoxShowQmlObjectTree->setText(tr("Show QML object tree"));
+
+ checkBoxBreakpointsFullPath = new QCheckBox(behaviorBox);
+ checkBoxBreakpointsFullPath->setToolTip(tr("Enable a full file path in breakpoints by default also for the GDB"));
+ checkBoxBreakpointsFullPath->setText(tr("Breakpoints full path by default"));
+
+ checkBoxRegisterForPostMortem = new QCheckBox(behaviorBox);
+ checkBoxRegisterForPostMortem->setToolTip(tr("Register Qt Creator for debugging crashed applications."));
+ checkBoxRegisterForPostMortem->setText(tr("Use Qt Creator for post-mortem debugging"));
+
+ labelMaximalStackDepth = new QLabel(tr("Maximum stack depth:"), behaviorBox);
+
+ spinBoxMaximalStackDepth = new QSpinBox(behaviorBox);
+ spinBoxMaximalStackDepth->setSpecialValueText(tr("<unlimited>"));
+ spinBoxMaximalStackDepth->setMaximum(999);
+ spinBoxMaximalStackDepth->setSingleStep(5);
+ spinBoxMaximalStackDepth->setValue(10);
+
+ labelMaximalStringLength = new QLabel(tr("Maximum string length:"), behaviorBox);
+
+ spinBoxMaximalStringLength = new QSpinBox(behaviorBox);
+ spinBoxMaximalStringLength->setSpecialValueText(tr("<unlimited>"));
+ spinBoxMaximalStringLength->setMaximum(10000000);
+ spinBoxMaximalStringLength->setSingleStep(1000);
+ spinBoxMaximalStringLength->setValue(10000);
+
+ sourcesMappingWidget = new DebuggerSourcePathMappingWidget(this);
+
+ QHBoxLayout *horizontalLayout = new QHBoxLayout();
+ horizontalLayout->addWidget(labelMaximalStackDepth);
+ horizontalLayout->addWidget(spinBoxMaximalStackDepth);
+ horizontalLayout->addStretch();
+
+ QHBoxLayout *horizontalLayout2 = new QHBoxLayout();
+ horizontalLayout2->addWidget(labelMaximalStringLength);
+ horizontalLayout2->addWidget(spinBoxMaximalStringLength);
+ horizontalLayout2->addStretch();
+
+ QGridLayout *gridLayout = new QGridLayout(behaviorBox);
+ gridLayout->addWidget(checkBoxUseAlternatingRowColors, 0, 0, 1, 1);
+ gridLayout->addWidget(checkBoxUseToolTipsInMainEditor, 1, 0, 1, 1);
+ gridLayout->addWidget(checkBoxCloseBuffersOnExit, 2, 0, 1, 1);
+ gridLayout->addWidget(checkBoxBringToForegroundOnInterrrupt, 3, 0, 1, 1);
+ gridLayout->addWidget(checkBoxBreakpointsFullPath, 4, 0, 1, 1);
+ gridLayout->addLayout(horizontalLayout, 6, 0, 1, 2);
+
+ gridLayout->addWidget(checkBoxFontSizeFollowsEditor, 0, 1, 1, 1);
+ gridLayout->addWidget(checkBoxListSourceFiles, 1, 1, 1, 1);
+ gridLayout->addWidget(checkBoxSwitchModeOnExit, 2, 1, 1, 1);
+ gridLayout->addWidget(checkBoxShowQmlObjectTree, 3, 1, 1, 1);
+ gridLayout->addWidget(checkBoxRegisterForPostMortem, 4, 1, 1, 1);
+ gridLayout->addLayout(horizontalLayout2, 6, 1, 1, 2);
+
+ QVBoxLayout *verticalLayout = new QVBoxLayout(this);
+ verticalLayout->addWidget(behaviorBox);
+ verticalLayout->addWidget(sourcesMappingWidget);
+ verticalLayout->addStretch();
DebuggerCore *dc = debuggerCore();
m_group->clear();
m_group->insert(dc->action(ListSourceFiles),
- m_ui.checkBoxListSourceFiles);
+ checkBoxListSourceFiles);
m_group->insert(dc->action(UseAlternatingRowColors),
- m_ui.checkBoxUseAlternatingRowColors);
+ checkBoxUseAlternatingRowColors);
m_group->insert(dc->action(UseToolTipsInMainEditor),
- m_ui.checkBoxUseToolTipsInMainEditor);
+ checkBoxUseToolTipsInMainEditor);
m_group->insert(dc->action(CloseBuffersOnExit),
- m_ui.checkBoxCloseBuffersOnExit);
+ checkBoxCloseBuffersOnExit);
m_group->insert(dc->action(SwitchModeOnExit),
- m_ui.checkBoxSwitchModeOnExit);
+ checkBoxSwitchModeOnExit);
m_group->insert(dc->action(BreakpointsFullPathByDefault),
- m_ui.checkBoxBreakpointsFullPath);
+ checkBoxBreakpointsFullPath);
m_group->insert(dc->action(RaiseOnInterrupt),
- m_ui.checkBoxBringToForegroundOnInterrrupt);
+ checkBoxBringToForegroundOnInterrrupt);
m_group->insert(dc->action(ShowQmlObjectTree),
- m_ui.checkBoxShowQmlObjectTree);
+ checkBoxShowQmlObjectTree);
m_group->insert(dc->action(FontSizeFollowsEditor),
- m_ui.checkBoxFontSizeFollowsEditor);
+ checkBoxFontSizeFollowsEditor);
m_group->insert(dc->action(AutoDerefPointers), 0);
m_group->insert(dc->action(UseToolTipsInLocalsView), 0);
m_group->insert(dc->action(AlwaysAdjustLocalsColumnWidths), 0);
@@ -88,8 +173,8 @@ CommonOptionsPageWidget::CommonOptionsPageWidget
m_group->insert(dc->action(UseAddressInBreakpointsView), 0);
m_group->insert(dc->action(UseAddressInStackView), 0);
m_group->insert(dc->action(AlwaysAdjustStackColumnWidths), 0);
- m_group->insert(dc->action(MaximalStackDepth),
- m_ui.spinBoxMaximalStackDepth);
+ m_group->insert(dc->action(MaximalStackDepth), spinBoxMaximalStackDepth);
+ m_group->insert(dc->action(MaximalStringLength), spinBoxMaximalStringLength);
m_group->insert(dc->action(ShowStdNamespace), 0);
m_group->insert(dc->action(ShowQtNamespace), 0);
m_group->insert(dc->action(SortStructMembers), 0);
@@ -97,36 +182,35 @@ CommonOptionsPageWidget::CommonOptionsPageWidget
m_group->insert(dc->action(VerboseLog), 0);
m_group->insert(dc->action(BreakOnThrow), 0);
m_group->insert(dc->action(BreakOnCatch), 0);
-#ifdef Q_OS_WIN
- Utils::SavedAction *registerAction = dc->action(RegisterForPostMortem);
- m_group->insert(registerAction,
- m_ui.checkBoxRegisterForPostMortem);
- connect(registerAction, SIGNAL(toggled(bool)),
- m_ui.checkBoxRegisterForPostMortem, SLOT(setChecked(bool)));
-#else
- m_ui.checkBoxRegisterForPostMortem->setVisible(false);
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ Utils::SavedAction *registerAction = dc->action(RegisterForPostMortem);
+ m_group->insert(registerAction,
+ checkBoxRegisterForPostMortem);
+ connect(registerAction, SIGNAL(toggled(bool)),
+ checkBoxRegisterForPostMortem, SLOT(setChecked(bool)));
+ } else {
+ checkBoxRegisterForPostMortem->setVisible(false);
+ }
}
QString CommonOptionsPageWidget::searchKeyWords() const
{
QString rc;
const QLatin1Char sep(' ');
- QTextStream(&rc)
- << sep << m_ui.checkBoxUseAlternatingRowColors->text()
- << sep << m_ui.checkBoxFontSizeFollowsEditor->text()
- << sep << m_ui.checkBoxUseToolTipsInMainEditor->text()
- << sep << m_ui.checkBoxListSourceFiles->text()
- << sep << m_ui.checkBoxBreakpointsFullPath->text()
-#ifdef Q_OS_WIN
- << sep << m_ui.checkBoxRegisterForPostMortem->text()
-#endif
- << sep << m_ui.checkBoxCloseBuffersOnExit->text()
- << sep << m_ui.checkBoxSwitchModeOnExit->text()
- << sep << m_ui.labelMaximalStackDepth->text()
- << sep << m_ui.checkBoxBringToForegroundOnInterrrupt->text()
- << sep << m_ui.checkBoxShowQmlObjectTree->text()
- ;
+ QTextStream stream(&rc);
+ stream << sep << checkBoxUseAlternatingRowColors->text()
+ << sep << checkBoxFontSizeFollowsEditor->text()
+ << sep << checkBoxUseToolTipsInMainEditor->text()
+ << sep << checkBoxListSourceFiles->text()
+ << sep << checkBoxBreakpointsFullPath->text()
+ << sep << checkBoxCloseBuffersOnExit->text()
+ << sep << checkBoxSwitchModeOnExit->text()
+ << sep << labelMaximalStackDepth->text()
+ << sep << checkBoxBringToForegroundOnInterrrupt->text()
+ << sep << checkBoxShowQmlObjectTree->text();
+ if (Utils::HostOsInfo::isWindowsHost())
+ stream << sep << checkBoxRegisterForPostMortem->text();
+
rc.remove(QLatin1Char('&'));
return rc;
}
@@ -134,13 +218,13 @@ QString CommonOptionsPageWidget::searchKeyWords() const
GlobalDebuggerOptions CommonOptionsPageWidget::globalOptions() const
{
GlobalDebuggerOptions o;
- o.sourcePathMap = m_ui.sourcesMappingWidget->sourcePathMap();
+ o.sourcePathMap = sourcesMappingWidget->sourcePathMap();
return o;
}
void CommonOptionsPageWidget::setGlobalOptions(const GlobalDebuggerOptions &go)
{
- m_ui.sourcesMappingWidget->setSourcePathMap(go.sourcePathMap);
+ sourcesMappingWidget->setSourcePathMap(go.sourcePathMap);
}
///////////////////////////////////////////////////////////////////////
@@ -152,9 +236,9 @@ void CommonOptionsPageWidget::setGlobalOptions(const GlobalDebuggerOptions &go)
CommonOptionsPage::CommonOptionsPage(const QSharedPointer<GlobalDebuggerOptions> &go) :
m_options(go)
{
- setId(QLatin1String(DEBUGGER_COMMON_SETTINGS_ID));
+ setId(DEBUGGER_COMMON_SETTINGS_ID);
setDisplayName(QCoreApplication::translate("Debugger", "General"));
- setCategory(QLatin1String(DEBUGGER_SETTINGS_CATEGORY));
+ setCategory(DEBUGGER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Debugger", DEBUGGER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(DEBUGGER_COMMON_SETTINGS_CATEGORY_ICON));
}
@@ -225,10 +309,10 @@ QString CommonOptionsPage::msgSetBreakpointAtFunctionToolTip(const char *functio
LocalsAndExpressionsOptionsPage::LocalsAndExpressionsOptionsPage()
{
- setId(QLatin1String("Z.LocalsAndExpressions"));
+ setId("Z.LocalsAndExpressions");
//: '&&' will appear as one (one is marking keyboard shortcut)
setDisplayName(QCoreApplication::translate("Debugger", "Locals && Expressions"));
- setCategory(QLatin1String(DEBUGGER_SETTINGS_CATEGORY));
+ setCategory(DEBUGGER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Debugger", DEBUGGER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(DEBUGGER_COMMON_SETTINGS_CATEGORY_ICON));
}
diff --git a/src/plugins/debugger/commonoptionspage.h b/src/plugins/debugger/commonoptionspage.h
index 9c06b6eaa3..f3549969ae 100644
--- a/src/plugins/debugger/commonoptionspage.h
+++ b/src/plugins/debugger/commonoptionspage.h
@@ -30,18 +30,21 @@
#ifndef DEBUGGER_COMMONOPTIONSPAGE_H
#define DEBUGGER_COMMONOPTIONSPAGE_H
-#include "ui_commonoptionspage.h"
+#include "debuggersourcepathmappingwidget.h"
#include "ui_localsandexpressionsoptionspage.h"
#include <coreplugin/dialogs/ioptionspage.h>
#include <utils/savedaction.h>
-#include <QSharedPointer>
+#include <QCheckBox>
+#include <QLabel>
#include <QPointer>
-#include <QWidget>
+#include <QSharedPointer>
+#include <QSpinBox>
namespace Debugger {
namespace Internal {
+
class GlobalDebuggerOptions;
///////////////////////////////////////////////////////////////////////
@@ -52,6 +55,7 @@ class GlobalDebuggerOptions;
class CommonOptionsPageWidget : public QWidget
{
+ Q_OBJECT
public:
explicit CommonOptionsPageWidget(const QSharedPointer<Utils::SavedActionSet> &group, QWidget *parent = 0);
@@ -60,7 +64,22 @@ public:
void setGlobalOptions(const GlobalDebuggerOptions &go);
private:
- Ui::CommonOptionsPage m_ui;
+ QCheckBox *checkBoxUseAlternatingRowColors;
+ QCheckBox *checkBoxFontSizeFollowsEditor;
+ QCheckBox *checkBoxUseToolTipsInMainEditor;
+ QCheckBox *checkBoxListSourceFiles;
+ QCheckBox *checkBoxCloseBuffersOnExit;
+ QCheckBox *checkBoxSwitchModeOnExit;
+ QCheckBox *checkBoxBringToForegroundOnInterrrupt;
+ QCheckBox *checkBoxShowQmlObjectTree;
+ QCheckBox *checkBoxBreakpointsFullPath;
+ QCheckBox *checkBoxRegisterForPostMortem;
+ QLabel *labelMaximalStackDepth;
+ QLabel *labelMaximalStringLength;
+ QSpinBox *spinBoxMaximalStackDepth;
+ QSpinBox *spinBoxMaximalStringLength;
+
+ DebuggerSourcePathMappingWidget *sourcesMappingWidget;
const QSharedPointer<Utils::SavedActionSet> m_group;
};
diff --git a/src/plugins/debugger/commonoptionspage.ui b/src/plugins/debugger/commonoptionspage.ui
deleted file mode 100644
index d31e3c85ec..0000000000
--- a/src/plugins/debugger/commonoptionspage.ui
+++ /dev/null
@@ -1,194 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>Debugger::Internal::CommonOptionsPage</class>
- <widget class="QWidget" name="Debugger::Internal::CommonOptionsPage">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>765</width>
- <height>341</height>
- </rect>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QGroupBox" name="behaviorBox">
- <property name="title">
- <string>Behavior</string>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QCheckBox" name="checkBoxUseAlternatingRowColors">
- <property name="text">
- <string>Use alternating row colors in debug views</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QCheckBox" name="checkBoxFontSizeFollowsEditor">
- <property name="toolTip">
- <string>Change the font size in the debugger views when the font size in the main editor changes.</string>
- </property>
- <property name="text">
- <string>Debugger font size follows main editor</string>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QCheckBox" name="checkBoxUseToolTipsInMainEditor">
- <property name="text">
- <string>Use tooltips in main editor while debugging</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QCheckBox" name="checkBoxListSourceFiles">
- <property name="toolTip">
- <string>Populate the source file view automatically. This might slow down debugger startup considerably.</string>
- </property>
- <property name="text">
- <string>Populate source file view automatically</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QCheckBox" name="checkBoxCloseBuffersOnExit">
- <property name="text">
- <string>Close temporary buffers on debugger exit</string>
- </property>
- </widget>
- </item>
- <item row="2" column="1">
- <widget class="QCheckBox" name="checkBoxSwitchModeOnExit">
- <property name="text">
- <string>Switch to previous mode on debugger exit</string>
- </property>
- </widget>
- </item>
- <item row="3" column="0">
- <widget class="QCheckBox" name="checkBoxBringToForegroundOnInterrrupt">
- <property name="text">
- <string>Bring Qt Creator to foreground when application interrupts</string>
- </property>
- </widget>
- </item>
- <item row="3" column="1">
- <widget class="QCheckBox" name="checkBoxShowQmlObjectTree">
- <property name="toolTip">
- <string>Show QML object tree in Locals &amp; Expressions when connected and not stepping.</string>
- </property>
- <property name="text">
- <string>Show QML object tree</string>
- </property>
- </widget>
- </item>
- <item row="4" column="0">
- <widget class="QCheckBox" name="checkBoxBreakpointsFullPath">
- <property name="toolTip">
- <string>Enable a full file path in breakpoints by default also for the GDB</string>
- </property>
- <property name="text">
- <string>Breakpoints full path by default</string>
- </property>
- </widget>
- </item>
- <item row="4" column="1">
- <widget class="QCheckBox" name="checkBoxRegisterForPostMortem">
- <property name="toolTip">
- <string>Register Qt Creator for debugging crashed applications.</string>
- </property>
- <property name="text">
- <string>Use Qt Creator for post-mortem debugging</string>
- </property>
- </widget>
- </item>
- <item row="6" column="0" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QLabel" name="labelMaximalStackDepth">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="text">
- <string>Maximum stack depth:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QSpinBox" name="spinBoxMaximalStackDepth">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="specialValueText">
- <string>&lt;unlimited&gt;</string>
- </property>
- <property name="maximum">
- <number>999</number>
- </property>
- <property name="singleStep">
- <number>5</number>
- </property>
- <property name="value">
- <number>10</number>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::MinimumExpanding</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </item>
- <item>
- <widget class="Debugger::Internal::DebuggerSourcePathMappingWidget" name="sourcesMappingWidget"/>
- </item>
- <item>
- <spacer name="verticalSpacer">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- <property name="sizeType">
- <enum>QSizePolicy::MinimumExpanding</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>0</width>
- <height>0</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <customwidgets>
- <customwidget>
- <class>Debugger::Internal::DebuggerSourcePathMappingWidget</class>
- <extends>QGroupBox</extends>
- <header>debuggersourcepathmappingwidget.h</header>
- <container>1</container>
- </customwidget>
- </customwidgets>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/plugins/debugger/debugger.pro b/src/plugins/debugger/debugger.pro
index fa66556673..0ca196b27f 100644
--- a/src/plugins/debugger/debugger.pro
+++ b/src/plugins/debugger/debugger.pro
@@ -8,7 +8,7 @@ TARGET = Debugger
include(../../qtcreatorplugin.pri)
include(debugger_dependencies.pri)
-DEFINES += DEBUGGER_LIBRARY QT_NO_CAST_FROM_ASCII
+DEFINES += DEBUGGER_LIBRARY
INCLUDEPATH += $$PWD/../../libs/utils
@@ -34,6 +34,7 @@ HEADERS += \
debuggerengine.h \
debuggermainwindow.h \
debuggerplugin.h \
+ debuggerprotocol.h \
debuggerrunner.h \
debuggerstartparameters.h \
debuggerstreamops.h \
@@ -56,6 +57,7 @@ HEADERS += \
sourceagent.h \
sourcefileshandler.h \
sourcefileswindow.h \
+ sourceutils.h \
stackframe.h \
stackhandler.h \
stackwindow.h \
@@ -70,13 +72,8 @@ HEADERS += \
debuggertooltipmanager.h \
debuggersourcepathmappingwidget.h \
memoryview.h \
- qtmessagelogwindow.h \
- qtmessagelogeditor.h \
- qtmessagelogview.h \
- qtmessagelogproxymodel.h \
- qtmessagelogitemdelegate.h \
- qtmessageloghandler.h \
- localsandexpressionswindow.h
+ localsandexpressionswindow.h \
+ imageviewer.h
SOURCES += \
basewindow.cpp \
@@ -90,6 +87,7 @@ SOURCES += \
debuggerengine.cpp \
debuggermainwindow.cpp \
debuggerplugin.cpp \
+ debuggerprotocol.cpp \
debuggerrunner.cpp \
debuggerstreamops.cpp \
debuggerkitconfigwidget.cpp \
@@ -110,6 +108,7 @@ SOURCES += \
sourceagent.cpp \
sourcefileshandler.cpp \
sourcefileswindow.cpp \
+ sourceutils.cpp \
stackhandler.cpp \
stackwindow.cpp \
threadshandler.cpp \
@@ -123,17 +122,11 @@ SOURCES += \
debuggertooltipmanager.cpp \
debuggersourcepathmappingwidget.cpp \
memoryview.cpp \
- qtmessagelogwindow.cpp \
- qtmessagelogproxymodel.cpp \
- qtmessagelogview.cpp \
- qtmessagelogitemdelegate.cpp \
- qtmessageloghandler.cpp \
- qtmessagelogeditor.cpp \
- localsandexpressionswindow.cpp
+ localsandexpressionswindow.cpp \
+ imageviewer.cpp
FORMS += \
- localsandexpressionsoptionspage.ui \
- commonoptionspage.ui
+ localsandexpressionsoptionspage.ui
RESOURCES += debugger.qrc
diff --git a/src/plugins/debugger/debugger.qbs b/src/plugins/debugger/debugger.qbs
index eede402cfc..d87a42171f 100644
--- a/src/plugins/debugger/debugger.qbs
+++ b/src/plugins/debugger/debugger.qbs
@@ -1,10 +1,10 @@
import qbs.base 1.0
import "../QtcPlugin.qbs" as QtcPlugin
+import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "Debugger"
- type: base.concat(["installed_content"])
Depends { name: "Qt"; submodules: ["widgets", "network", "script"] }
Depends { name: "Core" }
@@ -19,32 +19,23 @@ QtcPlugin {
Depends { name: "QtcSsh" }
Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
+ cpp.includePaths: base.concat([
"shared",
"lldb",
- "..",
- "../../libs",
"../../shared/json",
- buildDirectory,
- "../../libs/utils",
- "../../shared/registryaccess/"
- ]
+ "../../shared/registryaccess"
+ ])
Group {
- condition: qbs.buildVariant === "debug"
+ condition: Defaults.testsEnabled(qbs)
+ qbs.install: true
qbs.installDir: "tests/manual/debugger/simple/"
- fileTags: ["install"]
files: ["../../../tests/manual/debugger/simple/simple.pro"]
}
files: [
- "debugger.qrc",
- "debuggerkitconfigwidget.cpp",
- "debuggerkitconfigwidget.h",
- "debuggerkitinformation.cpp",
- "debuggerkitinformation.h",
"basewindow.cpp",
+ "basewindow.h",
"breakhandler.cpp",
"breakhandler.h",
"breakpoint.cpp",
@@ -55,17 +46,29 @@ QtcPlugin {
"breakwindow.h",
"commonoptionspage.cpp",
"commonoptionspage.h",
- "commonoptionspage.ui",
+ "debugger.qrc",
"debugger_global.h",
+ "debuggeractions.cpp",
+ "debuggeractions.h",
+ "debuggerconstants.h",
"debuggercore.h",
"debuggerdialogs.cpp",
"debuggerdialogs.h",
"debuggerengine.cpp",
"debuggerengine.h",
"debuggerinternalconstants.h",
+ "debuggerkitconfigwidget.cpp",
+ "debuggerkitconfigwidget.h",
+ "debuggerkitinformation.cpp",
+ "debuggerkitinformation.h",
"debuggermainwindow.cpp",
"debuggermainwindow.h",
+ "debuggerplugin.cpp",
"debuggerplugin.h",
+ "debuggerprotocol.cpp",
+ "debuggerprotocol.h",
+ "debuggerruncontrolfactory.h",
+ "debuggerrunner.cpp",
"debuggerrunner.h",
"debuggersourcepathmappingwidget.cpp",
"debuggersourcepathmappingwidget.h",
@@ -79,6 +82,8 @@ QtcPlugin {
"disassembleragent.h",
"disassemblerlines.cpp",
"disassemblerlines.h",
+ "imageviewer.cpp",
+ "imageviewer.h",
"loadcoredialog.cpp",
"loadcoredialog.h",
"localsandexpressionsoptionspage.ui",
@@ -98,18 +103,6 @@ QtcPlugin {
"outputcollector.h",
"procinterrupt.cpp",
"procinterrupt.h",
- "qtmessagelogwindow.h",
- "qtmessagelogeditor.h",
- "qtmessagelogview.h",
- "qtmessagelogproxymodel.h",
- "qtmessagelogitemdelegate.h",
- "qtmessageloghandler.h",
- "qtmessagelogwindow.cpp",
- "qtmessagelogproxymodel.cpp",
- "qtmessagelogview.cpp",
- "qtmessagelogitemdelegate.cpp",
- "qtmessageloghandler.cpp",
- "qtmessagelogeditor.cpp",
"registerhandler.cpp",
"registerhandler.h",
"registerwindow.cpp",
@@ -124,6 +117,8 @@ QtcPlugin {
"sourcefileshandler.h",
"sourcefileswindow.cpp",
"sourcefileswindow.h",
+ "sourceutils.cpp",
+ "sourceutils.h",
"stackframe.cpp",
"stackframe.h",
"stackhandler.cpp",
@@ -145,13 +140,6 @@ QtcPlugin {
"watchutils.h",
"watchwindow.cpp",
"watchwindow.h",
- "basewindow.h",
- "debuggeractions.cpp",
- "debuggeractions.h",
- "debuggerconstants.h",
- "debuggerplugin.cpp",
- "debuggerruncontrolfactory.h",
- "debuggerrunner.cpp",
"cdb/bytearrayinputstream.cpp",
"cdb/bytearrayinputstream.h",
"cdb/cdbengine.cpp",
@@ -163,17 +151,19 @@ QtcPlugin {
"cdb/cdboptionspagewidget.ui",
"cdb/cdbparsehelpers.cpp",
"cdb/cdbparsehelpers.h",
- "gdb/gdb.qrc",
"gdb/abstractgdbprocess.cpp",
"gdb/abstractgdbprocess.h",
"gdb/abstractplaingdbadapter.cpp",
"gdb/abstractplaingdbadapter.h",
+ "gdb/attachgdbadapter.cpp",
"gdb/attachgdbadapter.h",
+ "gdb/classicgdbengine.cpp",
"gdb/coregdbadapter.cpp",
"gdb/coregdbadapter.h",
+ "gdb/gdb.qrc",
"gdb/gdbengine.cpp",
- "gdb/gdbmi.cpp",
- "gdb/gdbmi.h",
+ "gdb/gdbengine.h",
+ "gdb/gdboptionspage.cpp",
"gdb/gdboptionspage.h",
"gdb/localgdbprocess.cpp",
"gdb/localgdbprocess.h",
@@ -186,14 +176,10 @@ QtcPlugin {
"gdb/remotegdbserveradapter.h",
"gdb/remoteplaingdbadapter.cpp",
"gdb/remoteplaingdbadapter.h",
- "gdb/termgdbadapter.h",
- "gdb/attachgdbadapter.cpp",
- "gdb/classicgdbengine.cpp",
- "gdb/gdbengine.h",
- "gdb/gdboptionspage.cpp",
- "gdb/termgdbadapter.cpp",
"gdb/startgdbserverdialog.cpp",
"gdb/startgdbserverdialog.h",
+ "gdb/termgdbadapter.cpp",
+ "gdb/termgdbadapter.h",
"images/breakpoint_16.png",
"images/breakpoint_24.png",
"images/breakpoint_disabled_16.png",
@@ -226,29 +212,40 @@ QtcPlugin {
"images/location_24.png",
"images/tracepoint.png",
"images/watchpoint.png",
+ "lldb/ipcenginehost.cpp",
+ "lldb/ipcenginehost.h",
+ "lldb/lldbenginehost.cpp",
+ "lldb/lldbenginehost.h",
+ "namedemangler/demanglerexceptions.h",
+ "namedemangler/globalparsestate.cpp",
+ "namedemangler/globalparsestate.h",
+ "namedemangler/namedemangler.cpp",
+ "namedemangler/namedemangler.h",
+ "namedemangler/parsetreenodes.cpp",
+ "namedemangler/parsetreenodes.h",
"pdb/pdbengine.cpp",
"pdb/pdbengine.h",
- "qml/qmlengine.h",
- "qml/qmladapter.h",
+ "qml/baseqmldebuggerclient.cpp",
"qml/baseqmldebuggerclient.h",
- "qml/qmlcppengine.h",
- "qml/qscriptdebuggerclient.h",
- "qml/qmlv8debuggerclient.h",
+ "qml/interactiveinterpreter.cpp",
"qml/interactiveinterpreter.h",
- "qml/qmlv8debuggerclientconstants.h",
- "qml/qmlengine.cpp",
"qml/qmladapter.cpp",
- "qml/baseqmldebuggerclient.cpp",
+ "qml/qmladapter.h",
"qml/qmlcppengine.cpp",
- "qml/qscriptdebuggerclient.cpp",
- "qml/qmlv8debuggerclient.cpp",
- "qml/interactiveinterpreter.cpp",
+ "qml/qmlcppengine.h",
+ "qml/qmlengine.cpp",
+ "qml/qmlengine.h",
"qml/qmlinspectoradapter.cpp",
"qml/qmlinspectoradapter.h",
"qml/qmlinspectoragent.cpp",
"qml/qmlinspectoragent.h",
"qml/qmllivetextpreview.cpp",
"qml/qmllivetextpreview.h",
+ "qml/qmlv8debuggerclient.cpp",
+ "qml/qmlv8debuggerclient.h",
+ "qml/qmlv8debuggerclientconstants.h",
+ "qml/qscriptdebuggerclient.cpp",
+ "qml/qscriptdebuggerclient.h",
"script/scriptengine.cpp",
"script/scriptengine.h",
"shared/backtrace.cpp",
@@ -257,17 +254,6 @@ QtcPlugin {
"shared/cdbsymbolpathlisteditor.h",
"shared/hostutils.cpp",
"shared/hostutils.h",
- "lldb/ipcenginehost.cpp",
- "lldb/ipcenginehost.h",
- "lldb/lldbenginehost.cpp",
- "lldb/lldbenginehost.h",
- "namedemangler/namedemangler.cpp",
- "namedemangler/namedemangler.h",
- "namedemangler/parsetreenodes.cpp",
- "namedemangler/parsetreenodes.h",
- "namedemangler/demanglerexceptions.h",
- "namedemangler/globalparsestate.h",
- "namedemangler/globalparsestate.cpp"
]
Group {
@@ -275,7 +261,7 @@ QtcPlugin {
prefix: "../../shared/registryaccess/"
files: [
"registryaccess.cpp",
- "registryaccess.h"
+ "registryaccess.h",
]
}
@@ -285,7 +271,7 @@ QtcPlugin {
"registerpostmortemaction.cpp",
"registerpostmortemaction.h",
"shared/peutils.cpp",
- "shared/peutils.h"
+ "shared/peutils.h",
]
}
@@ -294,7 +280,7 @@ QtcPlugin {
files: [
"lldb/lldboptionspage.cpp",
"lldb/lldboptionspage.h",
- "lldb/lldboptionspagewidget.ui"
+ "lldb/lldboptionspagewidget.ui",
]
}
@@ -313,4 +299,3 @@ QtcPlugin {
cpp.includePaths: ["."]
}
}
-
diff --git a/src/plugins/debugger/debugger.qrc b/src/plugins/debugger/debugger.qrc
index a75fb1625e..b1e7d73495 100644
--- a/src/plugins/debugger/debugger.qrc
+++ b/src/plugins/debugger/debugger.qrc
@@ -30,12 +30,6 @@
<file>images/location_16.png</file>
<file>images/location_24.png</file>
<file>images/pin.xpm</file>
- <file>images/collapse.png</file>
- <file>images/error.png</file>
- <file>images/expand.png</file>
- <file>images/log.png</file>
- <file>images/prompt.png</file>
- <file>images/warning.png</file>
<file>images/qml/zoom.png</file>
<file>images/qml/select.png</file>
<file>images/qml/app-on-top.png</file>
diff --git a/src/plugins/debugger/debuggeractions.cpp b/src/plugins/debugger/debuggeractions.cpp
index 7846adeae0..95abf02003 100644
--- a/src/plugins/debugger/debuggeractions.cpp
+++ b/src/plugins/debugger/debuggeractions.cpp
@@ -397,6 +397,11 @@ DebuggerSettings::DebuggerSettings(QSettings *settings)
insertItem(GdbStartupCommands, item);
item = new SavedAction(this);
+ item->setSettingsKey(debugModeGroup, QLatin1String("GdbPostAttachCommands"));
+ item->setDefaultValue(QString());
+ insertItem(GdbPostAttachCommands, item);
+
+ item = new SavedAction(this);
item->setSettingsKey(debugModeGroup, QLatin1String("CloseBuffersOnExit"));
item->setCheckable(true);
item->setDefaultValue(false);
@@ -434,6 +439,18 @@ DebuggerSettings::DebuggerSettings(QSettings *settings)
insertItem(AttemptQuickStart, item);
item = new SavedAction(this);
+ item->setSettingsKey(debugModeGroup, QLatin1String("MultiInferior"));
+ item->setCheckable(true);
+ item->setDefaultValue(false);
+ insertItem(MultiInferior, item);
+
+ item = new SavedAction(this);
+ item->setSettingsKey(debugModeGroup, QLatin1String("IntelFlavor"));
+ item->setCheckable(true);
+ item->setDefaultValue(false);
+ insertItem(IntelFlavor, item);
+
+ item = new SavedAction(this);
item->setSettingsKey(debugModeGroup, QLatin1String("UseToolTips"));
item->setText(tr("Use tooltips in main editor when debugging"));
item->setToolTip(tr("Checking this will enable tooltips for variable "
@@ -536,6 +553,11 @@ DebuggerSettings::DebuggerSettings(QSettings *settings)
insertItem(MaximalStackDepth, item);
item = new SavedAction(this);
+ item->setSettingsKey(debugModeGroup, QLatin1String("MaximalStringLength"));
+ item->setDefaultValue(10000);
+ insertItem(MaximalStringLength, item);
+
+ item = new SavedAction(this);
item->setText(tr("Reload Full Stack"));
insertItem(ExpandStack, item);
diff --git a/src/plugins/debugger/debuggeractions.h b/src/plugins/debugger/debuggeractions.h
index 562294b6e9..c06d47674c 100644
--- a/src/plugins/debugger/debuggeractions.h
+++ b/src/plugins/debugger/debuggeractions.h
@@ -119,11 +119,14 @@ enum DebuggerActionCode
LoadGdbInit,
AttemptQuickStart,
GdbStartupCommands,
+ GdbPostAttachCommands,
GdbWatchdogTimeout,
AutoEnrichParameters,
UseDynamicType,
TargetAsync,
WarnOnReleaseBuilds,
+ MultiInferior,
+ IntelFlavor,
// Stack
MaximalStackDepth,
@@ -137,6 +140,7 @@ enum DebuggerActionCode
SortStructMembers,
AutoDerefPointers,
AlwaysAdjustLocalsColumnWidths,
+ MaximalStringLength,
// Source List
ListSourceFiles,
diff --git a/src/plugins/debugger/debuggerconstants.h b/src/plugins/debugger/debuggerconstants.h
index 67653efeed..b6fd23663b 100644
--- a/src/plugins/debugger/debuggerconstants.h
+++ b/src/plugins/debugger/debuggerconstants.h
@@ -76,8 +76,11 @@ const char DOCKWIDGET_THREADS[] = "Debugger.Docks.Threads";
const char DOCKWIDGET_WATCHERS[] = "Debugger.Docks.LocalsAndWatchers";
const char DOCKWIDGET_QML_INSPECTOR[] = "Debugger.Docks.QmlInspector";
-const char DOCKWIDGET_QML_SCRIPTCONSOLE[] = "Debugger.Docks.ScriptConsole";
const char DOCKWIDGET_DEFAULT_AREA[] = "Debugger.Docks.DefaultArea";
+
+const char TASK_CATEGORY_DEBUGGER_TEST[] = "DebuggerTest";
+const char TASK_CATEGORY_DEBUGGER_DEBUGINFO[] = "Debuginfo";
+const char TASK_CATEGORY_DEBUGGER_RUNTIME[] = "DebugRuntime";
} // namespace Constants
enum DebuggerState
@@ -166,7 +169,9 @@ enum DebuggerCapabilities
CatchCapability = 0x200000, //!< fork, vfork, syscall
OperateByInstructionCapability = 0x400000,
RunToLineCapability = 0x800000,
- MemoryAddressCapability = 0x1000000
+ MemoryAddressCapability = 0x1000000,
+ ShowModuleSectionsCapability = 0x200000,
+ WatchComplexExpressionsCapability = 0x400000 // Used to filter out challenges for cdb.
};
enum LogChannel
@@ -183,9 +188,8 @@ enum LogChannel
AppOutput, // stdout
AppError, // stderr
AppStuff, // (possibly) windows debug channel
- StatusBar, // LogStatus and also put to the status bar
- QtMessageLogOutput,
- QtMessageLogStatus
+ StatusBar, // LogStatus and also put to the status bar
+ ConsoleOutput // Used to output to console
};
enum DebuggerEngineType
diff --git a/src/plugins/debugger/debuggercore.h b/src/plugins/debugger/debuggercore.h
index a0dedb0e46..ec5bd3c4f3 100644
--- a/src/plugins/debugger/debuggercore.h
+++ b/src/plugins/debugger/debuggercore.h
@@ -64,6 +64,7 @@ namespace Internal {
class BreakHandler;
class SnapshotHandler;
class Symbol;
+class Section;
class DebuggerToolTipManager;
class GlobalDebuggerOptions;
@@ -113,10 +114,11 @@ public:
// DebuggerEngineType et = NoEngineType) const = 0;
virtual void showModuleSymbols(const QString &moduleName,
const QVector<Symbol> &symbols) = 0;
+ virtual void showModuleSections(const QString &moduleName,
+ const QVector<Section> &sections) = 0;
virtual void openMemoryEditor() = 0;
virtual void languagesChanged() = 0;
virtual void executeDebuggerCommand(const QString &command, DebuggerLanguages languages) = 0;
- virtual bool evaluateScriptExpression(const QString &expression) = 0;
virtual Utils::SavedAction *action(int code) const = 0;
virtual bool boolSetting(int code) const = 0;
diff --git a/src/plugins/debugger/debuggerdialogs.cpp b/src/plugins/debugger/debuggerdialogs.cpp
index 52cd8a97e4..7eb5a0b848 100644
--- a/src/plugins/debugger/debuggerdialogs.cpp
+++ b/src/plugins/debugger/debuggerdialogs.cpp
@@ -207,7 +207,7 @@ QString StartApplicationParameters::displayName() const
void StartApplicationParameters::toSettings(QSettings *settings) const
{
- settings->setValue(_("LastKitId"), kitId.toString());
+ settings->setValue(_("LastKitId"), kitId.toSetting());
settings->setValue(_("LastServerPort"), serverPort);
settings->setValue(_("LastExternalExecutable"), localExecutable);
settings->setValue(_("LastExternalExecutableArguments"), processArgs);
@@ -220,8 +220,7 @@ void StartApplicationParameters::toSettings(QSettings *settings) const
void StartApplicationParameters::fromSettings(const QSettings *settings)
{
- const QString kitIdString = settings->value(_("LastKitId")).toString();
- kitId = kitIdString.isEmpty() ? Id() : Id(kitIdString);
+ kitId = Id::fromSetting(settings->value(_("LastKitId")));
serverPort = settings->value(_("LastServerPort")).toUInt();
localExecutable = settings->value(_("LastExternalExecutable")).toString();
processArgs = settings->value(_("LastExternalExecutableArguments")).toString();
diff --git a/src/plugins/debugger/debuggerengine.cpp b/src/plugins/debugger/debuggerengine.cpp
index ac4615ab4b..e962e94941 100644
--- a/src/plugins/debugger/debuggerengine.cpp
+++ b/src/plugins/debugger/debuggerengine.cpp
@@ -47,7 +47,6 @@
#include "stackhandler.h"
#include "threadshandler.h"
#include "watchhandler.h"
-#include "qtmessageloghandler.h"
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
@@ -65,6 +64,8 @@
#include <utils/qtcassert.h>
#include <utils/fileinprojectfinder.h>
+#include <qmljs/consolemanagerinterface.h>
+
#include <QDebug>
#include <QTimer>
#include <QFile>
@@ -296,7 +297,6 @@ public:
StackHandler m_stackHandler;
ThreadsHandler m_threadsHandler;
WatchHandler m_watchHandler;
- QtMessageLogHandler m_qtMessageHandler;
QFutureInterface<void> m_progress;
DisassemblerAgent m_disassemblerAgent;
@@ -427,11 +427,6 @@ WatchHandler *DebuggerEngine::watchHandler() const
: &d->m_watchHandler;
}
-QtMessageLogHandler *DebuggerEngine::qtMessageLogHandler() const
-{
- return &d->m_qtMessageHandler;
-}
-
SourceFilesHandler *DebuggerEngine::sourceFilesHandler() const
{
return d->m_masterEngine
@@ -509,14 +504,6 @@ QAbstractItemModel *DebuggerEngine::sourceFilesModel() const
return model;
}
-QAbstractItemModel *DebuggerEngine::qtMessageLogModel() const
-{
- QAbstractItemModel *model = qtMessageLogHandler()->model();
- if (model->objectName().isEmpty()) // Make debugging easier.
- model->setObjectName(objectName() + QLatin1String("QtMessageLogModel"));
- return model;
-}
-
void DebuggerEngine::fetchMemory(MemoryAgent *, QObject *,
quint64 addr, quint64 length)
{
@@ -545,15 +532,15 @@ void DebuggerEngine::showMessage(const QString &msg, int channel, int timeout) c
}
//if (msg.size() && msg.at(0).isUpper() && msg.at(1).isUpper())
// qDebug() << qPrintable(msg) << "IN STATE" << state();
- if (channel == QtMessageLogOutput)
- qtMessageLogHandler()->appendMessage(QtMessageLogHandler::UndefinedType, msg);
+ QmlJS::ConsoleManagerInterface *consoleManager = QmlJS::ConsoleManagerInterface::instance();
+ if (channel == ConsoleOutput && consoleManager)
+ consoleManager->printToConsolePane(QmlJS::ConsoleItem::UndefinedType, msg);
debuggerCore()->showMessage(msg, channel, timeout);
- if (d->m_runControl) {
+ if (d->m_runControl)
d->m_runControl->showMessage(msg, channel);
- } else {
+ else
qWarning("Warning: %s (no active run control)", qPrintable(msg));
- }
}
void DebuggerEngine::startDebugger(DebuggerRunControl *runControl)
@@ -998,9 +985,8 @@ void DebuggerEngine::notifyInferiorStopOk()
showMessage(_("NOTE: ... FORWARDING TO 'STOP OK'. "));
setState(InferiorStopOk);
}
- if (state() == InferiorStopOk || state() == InferiorStopFailed) {
+ if (state() == InferiorStopOk || state() == InferiorStopFailed)
d->queueShutdownInferior();
- }
showMessage(_("NOTE: ... IGNORING STOP MESSAGE"));
return;
}
@@ -1245,10 +1231,6 @@ void DebuggerEngine::setState(DebuggerState state, bool forced)
handler->notifyBreakpointReleased(id);
}
- const bool running = d->m_state == InferiorRunOk;
- if (running)
- threadsHandler()->notifyRunning();
-
showMessage(msg, LogDebug);
updateViews();
@@ -1431,7 +1413,7 @@ void DebuggerEngine::updateWatchData(const WatchData &, const WatchUpdateFlags &
{
}
-void DebuggerEngine::watchDataSelected(const QByteArray &iname)
+void DebuggerEngine::watchDataSelected(const QByteArray &)
{
}
@@ -1471,6 +1453,10 @@ void DebuggerEngine::requestModuleSymbols(const QString &)
{
}
+void DebuggerEngine::requestModuleSections(const QString &)
+{
+}
+
void DebuggerEngine::reloadRegisters()
{
}
@@ -1483,6 +1469,10 @@ void DebuggerEngine::reloadFullStack()
{
}
+void DebuggerEngine::reloadDebuggingHelpers()
+{
+}
+
void DebuggerEngine::addOptionPages(QList<Core::IOptionsPage*> *) const
{
}
@@ -1602,10 +1592,6 @@ void DebuggerEngine::changeBreakpoint(BreakpointModelId id)
QTC_CHECK(false);
}
-void DebuggerEngine::selectThread(int)
-{
-}
-
void DebuggerEngine::assignValueInDebugger(const WatchData *,
const QString &, const QVariant &)
{
@@ -1671,12 +1657,6 @@ void DebuggerEngine::executeDebuggerCommand(const QString &, DebuggerLanguages)
showStatusMessage(tr("This debugger cannot handle user input."));
}
-bool DebuggerEngine::evaluateScriptExpression(const QString &)
-{
- showStatusMessage(tr("This debugger cannot handle user input."));
- return false;
-}
-
BreakHandler *DebuggerEngine::breakHandler() const
{
return debuggerCore()->breakHandler();
@@ -1959,8 +1939,12 @@ TaskHub *DebuggerEnginePrivate::taskHub()
{
if (!m_taskHub) {
m_taskHub = ProjectExplorerPlugin::instance()->taskHub();
- m_taskHub->addCategory(Core::Id("Debuginfo"), tr("Debug Information"));
- m_taskHub->addCategory(Core::Id("DebuggerTest"), tr("Debugger Test"));
+ m_taskHub->addCategory(Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO),
+ tr("Debug Information"));
+ m_taskHub->addCategory(Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_TEST),
+ tr("Debugger Test"));
+ m_taskHub->addCategory(Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME),
+ tr("Debugger Runtime"));
}
return m_taskHub;
}
diff --git a/src/plugins/debugger/debuggerengine.h b/src/plugins/debugger/debuggerengine.h
index 6f2cd0b3fe..64ec1ef9e6 100644
--- a/src/plugins/debugger/debuggerengine.h
+++ b/src/plugins/debugger/debuggerengine.h
@@ -32,7 +32,8 @@
#include "debugger_global.h"
#include "debuggerconstants.h"
-#include "breakpoint.h" // For 'BreakpointId'
+#include "breakpoint.h" // For BreakpointModelId.
+#include "threaddata.h" // For ThreadId.
#include <QObject>
#include <QStringList>
@@ -76,7 +77,6 @@ class QmlAdapter;
class QmlCppEngine;
class DebuggerToolTipContext;
class MemoryMarkup;
-class QtMessageLogHandler;
struct WatchUpdateFlags
{
@@ -181,10 +181,12 @@ public:
virtual void loadSymbolsForStack();
virtual void loadAllSymbols();
virtual void requestModuleSymbols(const QString &moduleName);
+ virtual void requestModuleSections(const QString &moduleName);
virtual void reloadRegisters();
virtual void reloadSourceFiles();
virtual void reloadFullStack();
+ virtual void reloadDebuggingHelpers();
virtual void setRegisterValue(int regnr, const QString &value);
virtual void addOptionPages(QList<Core::IOptionsPage*> *) const;
@@ -208,7 +210,7 @@ public:
virtual bool acceptsDebuggerCommands() const { return true; }
virtual void assignValueInDebugger(const Internal::WatchData *data,
const QString &expr, const QVariant &value);
- virtual void selectThread(int index);
+ virtual void selectThread(Internal::ThreadId threadId) = 0;
virtual Internal::ModulesHandler *modulesHandler() const;
virtual Internal::RegisterHandler *registerHandler() const;
@@ -217,7 +219,6 @@ public:
virtual Internal::WatchHandler *watchHandler() const;
virtual Internal::SourceFilesHandler *sourceFilesHandler() const;
virtual Internal::BreakHandler *breakHandler() const;
- virtual Internal::QtMessageLogHandler *qtMessageLogHandler() const;
virtual QAbstractItemModel *modulesModel() const;
virtual QAbstractItemModel *registerModel() const;
@@ -230,7 +231,6 @@ public:
virtual QAbstractItemModel *toolTipsModel() const; // Deprecated, FIXME: use watchModel
virtual QAbstractItemModel *watchModel() const;
virtual QAbstractItemModel *sourceFilesModel() const;
- virtual QAbstractItemModel *qtMessageLogModel() const;
void progressPing();
void handleFinished();
@@ -355,7 +355,6 @@ protected:
virtual void executeRunToFunction(const QString &functionName);
virtual void executeJumpToLine(const Internal::ContextData &data);
virtual void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
- virtual bool evaluateScriptExpression(const QString &expression);
virtual void frameUp();
virtual void frameDown();
diff --git a/src/plugins/debugger/debuggerkitconfigwidget.cpp b/src/plugins/debugger/debuggerkitconfigwidget.cpp
index df93043786..50ea28d72a 100644
--- a/src/plugins/debugger/debuggerkitconfigwidget.cpp
+++ b/src/plugins/debugger/debuggerkitconfigwidget.cpp
@@ -62,21 +62,11 @@ static const char debuggingToolsWikiLinkC[] = "http://qt-project.org/wiki/Qt_Cre
// DebuggerKitConfigWidget:
// -----------------------------------------------------------------------
-DebuggerKitConfigWidget::DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy,
- const DebuggerKitInformation *ki,
- QWidget *parent) :
- ProjectExplorer::KitConfigWidget(parent),
- m_kit(workingCopy),
- m_info(ki),
- m_label(new QLabel(this)),
- m_button(new QPushButton(tr("Manage..."), this))
+DebuggerKitConfigWidget::DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy)
+ : KitConfigWidget(workingCopy),
+ m_label(new QLabel),
+ m_button(new QPushButton(tr("Manage...")))
{
- setToolTip(tr("The debugger to use for this kit."));
-
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
- layout->addWidget(m_label);
-
// ToolButton with Menu, defaulting to 'Autodetect'.
QMenu *buttonMenu = new QMenu(m_button);
QAction *autoDetectAction = buttonMenu->addAction(tr("Auto-detect"));
@@ -88,6 +78,16 @@ DebuggerKitConfigWidget::DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCo
refresh();
}
+QString DebuggerKitConfigWidget::toolTip() const
+{
+ return tr("The debugger to use for this kit.");
+}
+
+QWidget *DebuggerKitConfigWidget::mainWidget() const
+{
+ return m_label;
+}
+
QWidget *DebuggerKitConfigWidget::buttonWidget() const
{
return m_button;
@@ -138,11 +138,10 @@ DebuggerKitConfigDialog::DebuggerKitConfigDialog(QWidget *parent)
formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(GdbEngineType), QVariant(int(GdbEngineType)));
- if (ProjectExplorer::Abi::hostAbi().os() == ProjectExplorer::Abi::WindowsOS) {
+ if (ProjectExplorer::Abi::hostAbi().os() == ProjectExplorer::Abi::WindowsOS)
m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(CdbEngineType), QVariant(int(CdbEngineType)));
- } else {
+ else
m_comboBox->addItem(DebuggerKitInformation::debuggerEngineName(LldbEngineType), QVariant(int(LldbEngineType)));
- }
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(refreshLabel()));
QLabel *engineTypeLabel = new QLabel(tr("&Engine:"));
engineTypeLabel->setBuddy(m_comboBox);
diff --git a/src/plugins/debugger/debuggerkitconfigwidget.h b/src/plugins/debugger/debuggerkitconfigwidget.h
index 02c7ebadf5..689ec78f67 100644
--- a/src/plugins/debugger/debuggerkitconfigwidget.h
+++ b/src/plugins/debugger/debuggerkitconfigwidget.h
@@ -61,25 +61,23 @@ class DebuggerKitConfigWidget : public ProjectExplorer::KitConfigWidget
Q_OBJECT
public:
- DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy,
- const DebuggerKitInformation *ki,
- QWidget *parent = 0);
+ DebuggerKitConfigWidget(ProjectExplorer::Kit *workingCopy);
QString displayName() const;
+ QString toolTip() const;
void makeReadOnly();
void refresh();
QWidget *buttonWidget() const;
+ QWidget *mainWidget() const;
private slots:
void autoDetectDebugger();
void showDialog();
private:
- ProjectExplorer::Kit *m_kit;
- const DebuggerKitInformation *m_info;
QLabel *m_label;
QPushButton *m_button;
};
diff --git a/src/plugins/debugger/debuggerkitinformation.cpp b/src/plugins/debugger/debuggerkitinformation.cpp
index f36e694fb6..23550f4c8c 100644
--- a/src/plugins/debugger/debuggerkitinformation.cpp
+++ b/src/plugins/debugger/debuggerkitinformation.cpp
@@ -222,11 +222,10 @@ static unsigned debuggerConfigurationErrors(const ProjectExplorer::Kit *k)
return NoDebugger;
const QFileInfo fi = item.binary.toFileInfo();
- if (!fi.exists() || fi.isDir()) {
+ if (!fi.exists() || fi.isDir())
result |= DebuggerNotFound;
- } else if (!fi.isExecutable()) {
+ else if (!fi.isExecutable())
result |= DebuggerNotExecutable;
- }
if (!fi.exists() || fi.isDir())
// We need an absolute path to be able to locate Python on Windows.
@@ -271,7 +270,7 @@ QList<ProjectExplorer::Task> DebuggerKitInformation::validateDebugger(const Proj
KitConfigWidget *DebuggerKitInformation::createConfigWidget(Kit *k) const
{
- return new Internal::DebuggerKitConfigWidget(k, this);
+ return new Internal::DebuggerKitConfigWidget(k);
}
QString DebuggerKitInformation::userOutput(const DebuggerItem &item)
diff --git a/src/plugins/debugger/debuggermainwindow.cpp b/src/plugins/debugger/debuggermainwindow.cpp
index 7431f7a6f1..1b153dfa0a 100644
--- a/src/plugins/debugger/debuggermainwindow.cpp
+++ b/src/plugins/debugger/debuggermainwindow.cpp
@@ -689,7 +689,6 @@ void DebuggerMainWindowPrivate::setSimpleDockWidgetArrangement()
QDockWidget *threadsDock = q->dockWidget(QLatin1String(DOCKWIDGET_THREADS));
QDockWidget *outputDock = q->dockWidget(QLatin1String(DOCKWIDGET_OUTPUT));
QDockWidget *qmlInspectorDock = q->dockWidget(QLatin1String(DOCKWIDGET_QML_INSPECTOR));
- QDockWidget *consoleDock = q->dockWidget(QLatin1String(DOCKWIDGET_QML_SCRIPTCONSOLE));
QDockWidget *modulesDock = q->dockWidget(QLatin1String(DOCKWIDGET_MODULES));
QDockWidget *registerDock = q->dockWidget(QLatin1String(DOCKWIDGET_REGISTER));
QDockWidget *sourceFilesDock = q->dockWidget(QLatin1String(DOCKWIDGET_SOURCE_FILES));
@@ -700,7 +699,6 @@ void DebuggerMainWindowPrivate::setSimpleDockWidgetArrangement()
QTC_ASSERT(snapshotsDock, return);
QTC_ASSERT(threadsDock, return);
QTC_ASSERT(outputDock, return);
- QTC_ASSERT(consoleDock, return);
QTC_ASSERT(modulesDock, return);
QTC_ASSERT(registerDock, return);
QTC_ASSERT(sourceFilesDock, return);
@@ -713,7 +711,7 @@ void DebuggerMainWindowPrivate::setSimpleDockWidgetArrangement()
// toolBar
// --------------------------------------------------------------------------------
- // stack,qmlinspector | breakpoints,modules,register,threads,sourceFiles,snapshots,scriptconsole
+ // stack,qmlinspector | breakpoints,modules,register,threads,sourceFiles,snapshots
//
q->splitDockWidget(toolBarDock, stackDock, Qt::Vertical);
q->splitDockWidget(stackDock, breakDock, Qt::Horizontal);
@@ -726,13 +724,10 @@ void DebuggerMainWindowPrivate::setSimpleDockWidgetArrangement()
q->tabifyDockWidget(breakDock, threadsDock);
q->tabifyDockWidget(breakDock, sourceFilesDock);
q->tabifyDockWidget(breakDock, snapshotsDock);
- q->tabifyDockWidget(breakDock, consoleDock);
if (m_activeDebugLanguages.testFlag(Debugger::QmlLanguage)) {
if (qmlInspectorDock)
qmlInspectorDock->show();
- if (consoleDock)
- consoleDock->show();
} else {
// CPP only
threadsDock->show();
diff --git a/src/plugins/debugger/debuggerplugin.cpp b/src/plugins/debugger/debuggerplugin.cpp
index b67e1c8fa7..e92b3985e0 100644
--- a/src/plugins/debugger/debuggerplugin.cpp
+++ b/src/plugins/debugger/debuggerplugin.cpp
@@ -45,7 +45,6 @@
#include "breakpoint.h"
#include "breakhandler.h"
#include "breakwindow.h"
-#include "qtmessagelogwindow.h"
#include "disassemblerlines.h"
#include "logwindow.h"
#include "moduleswindow.h"
@@ -63,6 +62,7 @@
#include "localsandexpressionswindow.h"
#include "loadcoredialog.h"
#include "hostutils.h"
+#include "sourceutils.h"
#include "snapshothandler.h"
#include "threadshandler.h"
@@ -92,8 +92,9 @@
#include <extensionsystem/invoker.h>
#include <projectexplorer/abi.h>
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/buildmanager.h>
#include <projectexplorer/devicesupport/deviceprocessesdialog.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
@@ -114,6 +115,7 @@
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
#include <utils/styledbar.h>
@@ -158,7 +160,7 @@
//# define STATE_DEBUG(s)
// do { QString msg; QTextStream ts(&msg); ts << s;
// showMessage(msg, LogDebug); } while (0)
-# define STATE_DEBUG(s) do { qDebug() << s; } while(0)
+# define STATE_DEBUG(s) do { qDebug() << s; } while (0)
#else
# define STATE_DEBUG(s)
#endif
@@ -394,11 +396,6 @@ namespace PE = ProjectExplorer::Constants;
namespace Debugger {
-namespace Constants {
-
-} // namespace Constants
-
-
namespace Internal {
// To be passed through margin menu action's data
@@ -462,12 +459,12 @@ static QToolButton *toolButton(QAction *action)
return button;
}
-static void setProxyAction(ProxyAction *proxy, const char *id)
+static void setProxyAction(ProxyAction *proxy, Core::Id id)
{
proxy->setAction(ActionManager::command(id)->action());
}
-static QToolButton *toolButton(const char *id)
+static QToolButton *toolButton(Core::Id id)
{
return toolButton(ActionManager::command(id)->action());
}
@@ -494,6 +491,7 @@ public:
bool hasCapability(unsigned cap) const;
bool acceptsBreakpoint(BreakpointModelId) const { return false; }
bool acceptsDebuggerCommands() const { return false; }
+ void selectThread(ThreadId) {}
};
bool DummyEngine::hasCapability(unsigned cap) const
@@ -552,9 +550,9 @@ public:
//
///////////////////////////////////////////////////////////////////////
-static inline QString executableForPid(qint64 pid)
+static QString executableForPid(qint64 pid)
{
- foreach (const ProjectExplorer::DeviceProcess &p, ProjectExplorer::DeviceProcessList::localProcesses())
+ foreach (const DeviceProcess &p, DeviceProcessList::localProcesses())
if (p.pid == pid)
return p.exe;
return QString();
@@ -668,19 +666,21 @@ bool fillParameters(DebuggerStartParameters *sp, const Kit *kit /* = 0 */, QStri
*errorMessage = DebuggerKitInformation::tr("No kit found.");
return false;
}
- const QList<ProjectExplorer::Task> tasks = DebuggerKitInformation::validateDebugger(kit);
- if (!tasks.isEmpty()) {
- sp->startMode = NoStartMode;
- if (errorMessage) {
- foreach (const ProjectExplorer::Task &t, tasks) {
- if (errorMessage->isEmpty())
- errorMessage->append(QLatin1Char('\n'));
- errorMessage->append(t.description);
+ // validate debugger if C++ debugging is enabled
+ if (sp->languages & CppLanguage) {
+ const QList<Task> tasks = DebuggerKitInformation::validateDebugger(kit);
+ if (!tasks.isEmpty()) {
+ sp->startMode = NoStartMode;
+ if (errorMessage) {
+ foreach (const Task &t, tasks) {
+ if (errorMessage->isEmpty())
+ errorMessage->append(QLatin1Char('\n'));
+ errorMessage->append(t.description);
+ }
}
+ return false;
}
- return false;
}
-
sp->cppEngineType = DebuggerKitInformation::engineType(kit);
sp->sysRoot = SysRootKitInformation::sysRoot(kit).toString();
sp->debuggerCommand = DebuggerKitInformation::debuggerCommand(kit).toString();
@@ -779,7 +779,8 @@ public slots:
void selectThread(int index)
{
- currentEngine()->selectThread(index);
+ ThreadId id = m_currentEngine->threadsHandler()->threadAt(index);
+ m_currentEngine->selectThread(id);
}
void breakpointSetMarginActionTriggered()
@@ -962,13 +963,14 @@ public slots:
void aboutToSaveSession();
void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
- bool evaluateScriptExpression(const QString &expression);
void coreShutdown();
#ifdef WITH_TESTS
public slots:
void testLoadProject(const QString &proFile, const TestCallBack &cb);
void testProjectLoaded(ProjectExplorer::Project *project);
+ void testProjectEvaluated();
+ void testProjectBuilt(bool success);
void testUnloadProject();
void testFinished();
@@ -986,6 +988,7 @@ public slots:
void testBenchmark1();
public:
+ Project *m_testProject;
bool m_testSuccess;
QList<TestCallBack> m_testCallbacks;
@@ -1164,7 +1167,10 @@ public slots:
int line, column;
exp = cppExpressionAt(textEditor, tc.position(), &line, &column);
}
- exp = fixCppExpression(exp);
+ if (currentEngine()->hasCapability(WatchComplexExpressionsCapability))
+ exp = removeObviousSideEffects(exp);
+ else
+ exp = fixCppExpression(exp);
if (exp.isEmpty())
return;
currentEngine()->watchHandler()->watchVariable(exp);
@@ -1190,9 +1196,8 @@ public slots:
// Go to source only if we have the file.
if (currentEngine()->stackHandler()->currentIndex() >= 0) {
const StackFrame frame = currentEngine()->stackHandler()->currentFrame();
- if (operateByInstructionTriggered || frame.isUsable()) {
+ if (operateByInstructionTriggered || frame.isUsable())
currentEngine()->gotoLocation(Location(frame, true));
- }
}
}
@@ -1213,6 +1218,7 @@ public slots:
QString stringSetting(int code) const;
void showModuleSymbols(const QString &moduleName, const Symbols &symbols);
+ void showModuleSections(const QString &moduleName, const Sections &sections);
bool parseArgument(QStringList::const_iterator &it,
const QStringList::const_iterator &cend, QString *errorMessage);
@@ -1276,7 +1282,6 @@ public:
BaseWindow *m_breakWindow;
BreakHandler *m_breakHandler;
- QtMessageLogWindow *m_qtMessageLogWindow;
WatchWindow *m_returnWindow;
WatchWindow *m_localsWindow;
WatchWindow *m_watchersWindow;
@@ -1342,7 +1347,6 @@ DebuggerPluginPrivate::DebuggerPluginPrivate(DebuggerPlugin *plugin) :
m_threadsWindow = 0;
m_logWindow = 0;
m_localsAndExpressionsWindow = 0;
- m_qtMessageLogWindow = 0;
m_mainWindow = 0;
m_snapshotHandler = 0;
@@ -1465,7 +1469,7 @@ bool DebuggerPluginPrivate::parseArgument(QStringList::const_iterator &it,
// a handshake when attaching to a crashed Windows process.
// This is created by $QTC/src/tools/qtcdebugger/main.cpp:
// args << QLatin1String("-wincrashevent")
- // << QString("%1:%2").arg(argWinCrashEvent).arg(argProcessId);
+ // << QString::fromLatin1("%1:%2").arg(argWinCrashEvent).arg(argProcessId);
if (*it == _("-wincrashevent")) {
++it;
if (it == cend) {
@@ -1556,7 +1560,7 @@ void DebuggerPluginPrivate::onCurrentProjectChanged(Project *project)
m_exitAction->setEnabled(false);
m_startAction->setEnabled(true);
m_debugWithoutDeployAction->setEnabled(true);
- setProxyAction(m_visibleStartAction, Constants::DEBUG);
+ setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
}
void DebuggerPluginPrivate::languagesChanged()
@@ -1691,16 +1695,17 @@ void DebuggerPluginPrivate::attachToProcess(bool startServerOnly)
return;
}
- #ifdef Q_OS_WIN
- if (isWinProcessBeingDebugged(process.pid)) {
+ bool isWindows = false;
+ if (const ToolChain *tc = ToolChainKitInformation::toolChain(kit))
+ isWindows = tc->targetAbi().os() == Abi::WindowsOS;
+ if (isWindows && isWinProcessBeingDebugged(process.pid)) {
QMessageBox::warning(ICore::mainWindow(), tr("Process Already Under Debugger Control"),
tr("The process %1 is already under the control of a debugger.\n"
"Qt Creator cannot attach to it.").arg(process.pid));
return;
}
- #endif
- if (device->type() == ProjectExplorer::Constants::DESKTOP_DEVICE_TYPE) {
+ if (device->type() == PE::DESKTOP_DEVICE_TYPE) {
DebuggerStartParameters sp;
QTC_ASSERT(fillParameters(&sp, kit), return);
sp.attachPID = process.pid;
@@ -1715,7 +1720,7 @@ void DebuggerPluginPrivate::attachToProcess(bool startServerOnly)
}
}
-void DebuggerPluginPrivate::attachExternalApplication(ProjectExplorer::RunControl *rc)
+void DebuggerPluginPrivate::attachExternalApplication(RunControl *rc)
{
DebuggerStartParameters sp;
sp.attachPID = rc->applicationProcessHandle().pid();
@@ -1793,7 +1798,7 @@ void DebuggerPluginPrivate::startRemoteEngine()
sp.connParams.timeout = 5;
sp.connParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByPassword;
sp.connParams.port = 22;
- sp.connParams.proxyType = QSsh::SshConnectionParameters::NoProxy;
+ sp.connParams.options = QSsh::SshIgnoreDefaultProxy;
sp.executable = dlg.inferiorPath();
sp.serverStartScript = dlg.enginePath();
@@ -1817,8 +1822,6 @@ void DebuggerPluginPrivate::runScheduled()
void DebuggerPluginPrivate::editorOpened(IEditor *editor)
{
- if (!isEditorDebuggable(editor))
- return;
ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor);
if (!textEditor)
return;
@@ -1839,9 +1842,6 @@ void DebuggerPluginPrivate::updateBreakMenuItem(IEditor *editor)
void DebuggerPluginPrivate::requestContextMenu(ITextEditor *editor,
int lineNumber, QMenu *menu)
{
- if (!isEditorDebuggable(editor))
- return;
-
BreakpointMenuContextData args;
args.lineNumber = lineNumber;
bool contextUsable = true;
@@ -2062,7 +2062,6 @@ void DebuggerPluginPrivate::connectEngine(DebuggerEngine *engine)
m_threadsWindow->setModel(engine->threadsModel());
m_watchersWindow->setModel(engine->watchersModel());
m_inspectorWindow->setModel(engine->inspectorModel());
- m_qtMessageLogWindow->setModel(engine->qtMessageLogModel());
engine->watchHandler()->rebuildModel();
@@ -2190,7 +2189,6 @@ void DebuggerPluginPrivate::setInitialState()
action(AutoDerefPointers)->setEnabled(true);
action(ExpandStack)->setEnabled(false);
- m_qtMessageLogWindow->setEnabled(true);
}
void DebuggerPluginPrivate::updateWatchersWindow(bool showWatch, bool showReturn)
@@ -2206,11 +2204,11 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
QTC_ASSERT(m_returnWindow->model(), return);
QTC_ASSERT(!engine->isSlaveEngine(), return);
- m_threadBox->setCurrentIndex(engine->threadsHandler()->currentThread());
+ m_threadBox->setCurrentIndex(engine->threadsHandler()->currentThreadIndex());
engine->watchHandler()->updateWatchersWindow();
const DebuggerState state = engine->state();
- //showMessage(QString("PLUGIN SET STATE: ")
+ //showMessage(QString::fromLatin1("PLUGIN SET STATE: ")
// + DebuggerEngine::stateName(state), LogStatus);
//qDebug() << "PLUGIN SET STATE: " << state;
@@ -2228,7 +2226,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(false);
m_startAction->setEnabled(true);
m_debugWithoutDeployAction->setEnabled(true);
- setProxyAction(m_visibleStartAction, Constants::DEBUG);
+ setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
m_hiddenStopAction->setAction(m_undisturbableAction);
} else if (state == InferiorStopOk) {
// F5 continues, Shift-F5 kills. It is "continuable".
@@ -2237,7 +2235,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
- setProxyAction(m_visibleStartAction, Constants::CONTINUE);
+ setProxyAction(m_visibleStartAction, Core::Id(Constants::CONTINUE));
m_hiddenStopAction->setAction(m_exitAction);
m_localsAndExpressionsWindow->setShowLocals(true);
} else if (state == InferiorRunOk) {
@@ -2247,7 +2245,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(true);
m_startAction->setEnabled(false);
m_debugWithoutDeployAction->setEnabled(false);
- setProxyAction(m_visibleStartAction, Constants::INTERRUPT);
+ setProxyAction(m_visibleStartAction, Core::Id(Constants::INTERRUPT));
m_hiddenStopAction->setAction(m_interruptAction);
m_localsAndExpressionsWindow->setShowLocals(false);
} else if (state == DebuggerFinished) {
@@ -2257,7 +2255,7 @@ void DebuggerPluginPrivate::updateState(DebuggerEngine *engine)
m_exitAction->setEnabled(false);
m_startAction->setEnabled(true);
m_debugWithoutDeployAction->setEnabled(true);
- setProxyAction(m_visibleStartAction, Constants::DEBUG);
+ setProxyAction(m_visibleStartAction, Core::Id(Constants::DEBUG));
m_hiddenStopAction->setAction(m_undisturbableAction);
m_codeModelSnapshot = CPlusPlus::Snapshot();
setBusyCursor(false);
@@ -2401,9 +2399,7 @@ void DebuggerPluginPrivate::onModeChanged(IMode *mode)
void DebuggerPluginPrivate::showSettingsDialog()
{
- ICore::showOptionsDialog(
- _(DEBUGGER_SETTINGS_CATEGORY),
- _(DEBUGGER_COMMON_SETTINGS_ID));
+ ICore::showOptionsDialog(DEBUGGER_SETTINGS_CATEGORY, DEBUGGER_COMMON_SETTINGS_ID);
}
void DebuggerPluginPrivate::updateDebugWithoutDeployMenu()
@@ -2483,11 +2479,6 @@ void DebuggerPluginPrivate::showStatusMessage(const QString &msg0, int timeout)
m_statusLabel->showStatusMessage(msg, timeout);
}
-bool DebuggerPluginPrivate::evaluateScriptExpression(const QString &expression)
-{
- return currentEngine()->evaluateScriptExpression(expression);
-}
-
void DebuggerPluginPrivate::openMemoryEditor()
{
AddressDialog dialog;
@@ -2555,10 +2546,6 @@ void DebuggerPluginPrivate::showMessage(const QString &msg, int channel, int tim
m_logWindow->showInput(LogError, QLatin1String("ERROR: ") + msg);
m_logWindow->showOutput(LogError, QLatin1String("ERROR: ") + msg);
break;
- case QtMessageLogStatus:
- QTC_ASSERT(m_qtMessageLogWindow, return);
- m_qtMessageLogWindow->showStatus(msg, timeout);
- break;
default:
m_logWindow->showOutput(channel, msg);
break;
@@ -2735,8 +2722,6 @@ void DebuggerPluginPrivate::extensionsInitialized()
m_breakWindow->setObjectName(QLatin1String(DOCKWIDGET_BREAK));
m_breakWindow->setModel(m_breakHandler->model());
- m_qtMessageLogWindow = new QtMessageLogWindow();
- m_qtMessageLogWindow->setObjectName(QLatin1String(DOCKWIDGET_QML_SCRIPTCONSOLE));
m_modulesWindow = new ModulesWindow;
m_modulesWindow->setObjectName(QLatin1String(DOCKWIDGET_MODULES));
m_logWindow = new LogWindow;
@@ -2848,8 +2833,7 @@ void DebuggerPluginPrivate::extensionsInitialized()
connect(action(OperateByInstruction), SIGNAL(triggered(bool)),
SLOT(handleOperateByInstructionTriggered(bool)));
- ActionContainer *debugMenu =
- ActionManager::actionContainer(ProjectExplorer::Constants::M_DEBUG);
+ ActionContainer *debugMenu = ActionManager::actionContainer(PE::M_DEBUG);
// Dock widgets
QDockWidget *dock = 0;
@@ -2869,7 +2853,6 @@ void DebuggerPluginPrivate::extensionsInitialized()
dock->setProperty(DOCKWIDGET_DEFAULT_AREA, Qt::TopDockWidgetArea);
m_mainWindow->createDockWidget(CppLanguage, m_breakWindow);
- m_mainWindow->createDockWidget(QmlLanguage, m_qtMessageLogWindow);
m_mainWindow->createDockWidget(CppLanguage, m_snapshotWindow);
m_mainWindow->createDockWidget(CppLanguage, m_stackWindow);
m_mainWindow->createDockWidget(CppLanguage, m_threadsWindow);
@@ -2933,11 +2916,11 @@ void DebuggerPluginPrivate::extensionsInitialized()
act->setText(tr("Attach to QML Port..."));
connect(act, SIGNAL(triggered()), SLOT(attachToQmlPort()));
-#ifdef Q_OS_WIN
- m_startRemoteCdbAction = new QAction(tr("Attach to Remote CDB Session..."), this);
- connect(m_startRemoteCdbAction, SIGNAL(triggered()),
- SLOT(startRemoteCdbSession()));
-#endif
+ if (HostOsInfo::isWindowsHost()) {
+ m_startRemoteCdbAction = new QAction(tr("Attach to Remote CDB Session..."), this);
+ connect(m_startRemoteCdbAction, SIGNAL(triggered()),
+ SLOT(startRemoteCdbSession()));
+ }
act = m_detachAction = new QAction(this);
act->setText(tr("Detach Debugger"));
@@ -3356,6 +3339,36 @@ void DebuggerPluginPrivate::showModuleSymbols(const QString &moduleName,
createNewDock(w);
}
+void DebuggerPluginPrivate::showModuleSections(const QString &moduleName,
+ const Sections &sections)
+{
+ QTreeWidget *w = new QTreeWidget;
+ w->setUniformRowHeights(true);
+ w->setColumnCount(5);
+ w->setRootIsDecorated(false);
+ w->setAlternatingRowColors(true);
+ w->setSortingEnabled(true);
+ w->setObjectName(QLatin1String("Sections.") + moduleName);
+ QStringList header;
+ header.append(tr("Name"));
+ header.append(tr("From"));
+ header.append(tr("To"));
+ header.append(tr("Address"));
+ header.append(tr("Flags"));
+ w->setHeaderLabels(header);
+ w->setWindowTitle(tr("Sections in \"%1\"").arg(moduleName));
+ foreach (const Section &s, sections) {
+ QTreeWidgetItem *it = new QTreeWidgetItem;
+ it->setData(0, Qt::DisplayRole, s.name);
+ it->setData(1, Qt::DisplayRole, s.from);
+ it->setData(2, Qt::DisplayRole, s.to);
+ it->setData(3, Qt::DisplayRole, s.address);
+ it->setData(4, Qt::DisplayRole, s.flags);
+ w->addTopLevelItem(it);
+ }
+ createNewDock(w);
+}
+
void DebuggerPluginPrivate::aboutToShutdown()
{
m_plugin->removeObject(this);
@@ -3381,7 +3394,8 @@ using namespace Debugger::Internal;
This is the "external" interface of the debugger plugin that's visible
from Qt Creator core. The internal interface to global debugger
functionality that is used by debugger views and debugger engines
- is DebuggerCore, implemented in DebuggerPluginPrivate. */
+ is DebuggerCore, implemented in DebuggerPluginPrivate.
+*/
DebuggerPlugin::DebuggerPlugin()
{
@@ -3463,10 +3477,13 @@ void DebuggerPluginPrivate::testLoadProject(const QString &proFile, const TestCa
m_testCallbacks.append(cb);
QString error;
- if (pe->openProject(proFile, &error))
- return; // Will end up in callback.
+ if (pe->openProject(proFile, &error)) {
+ // Will end up in callback below due to the connections to
+ // signal currentProjectChanged().
+ return;
+ }
- // Eat the unused callback.
+ // Project opening failed. Eat the unused callback.
qWarning("Cannot open %s: %s", qPrintable(proFile), qPrintable(error));
QVERIFY(false);
m_testCallbacks.pop_back();
@@ -3478,14 +3495,25 @@ void DebuggerPluginPrivate::testProjectLoaded(Project *project)
qWarning("Changed to null project.");
return;
}
- ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
- disconnect(pe, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
- this, SLOT(testProjectLoaded(ProjectExplorer::Project*)));
+ m_testProject = project;
+ connect(project, SIGNAL(proFilesEvaluated()), SLOT(testProjectEvaluated()));
+ project->configureAsExampleProject(QStringList());
+}
- QString fileName = project->document()->fileName();
+void DebuggerPluginPrivate::testProjectEvaluated()
+{
+ QString fileName = m_testProject->document()->fileName();
QVERIFY(!fileName.isEmpty());
qWarning("Project %s loaded", qPrintable(fileName));
+ connect(ProjectExplorerPlugin::instance()->buildManager(),
+ SIGNAL(buildQueueFinished(bool)),
+ SLOT(testProjectBuilt(bool)));
+ ProjectExplorerPlugin::instance()->buildProject(m_testProject);
+}
+void DebuggerPluginPrivate::testProjectBuilt(bool success)
+{
+ QVERIFY(success);
QVERIFY(!m_testCallbacks.isEmpty());
TestCallBack cb = m_testCallbacks.takeLast();
invoke<void>(cb.receiver, cb.slot);
@@ -3508,12 +3536,13 @@ static Kit *currentKit()
Target *t = activeTarget();
if (!t || !t->isEnabled())
return 0;
- return activeTarget()->kit();
+ return t->kit();
}
static LocalApplicationRunConfiguration *activeLocalRunConfiguration()
{
- return qobject_cast<LocalApplicationRunConfiguration *>(activeTarget()->activeRunConfiguration());
+ Target *t = activeTarget();
+ return t ? qobject_cast<LocalApplicationRunConfiguration *>(t->activeRunConfiguration()) : 0;
}
void DebuggerPluginPrivate::testRunProject(const DebuggerStartParameters &sp, const TestCallBack &cb)
diff --git a/src/plugins/debugger/gdb/gdbmi.cpp b/src/plugins/debugger/debuggerprotocol.cpp
index 609b50a874..4c677cc498 100644
--- a/src/plugins/debugger/gdb/gdbmi.cpp
+++ b/src/plugins/debugger/debuggerprotocol.cpp
@@ -27,13 +27,12 @@
**
****************************************************************************/
-#include "gdbmi.h"
-
-#include <utils/qtcassert.h>
+#include "debuggerprotocol.h"
#include <QByteArray>
+#include <QCoreApplication>
+#include <QDateTime>
#include <QDebug>
-#include <QRegExp>
#include <QTextStream>
#include <ctype.h>
@@ -181,7 +180,7 @@ void GdbMi::parseValue(const char *&from, const char *to)
void GdbMi::parseTuple(const char *&from, const char *to)
{
//qDebug() << "parseTuple: " << QByteArray(from, to - from);
- QTC_CHECK(*from == '{');
+ //QTC_CHECK(*from == '{');
++from;
parseTuple_helper(from, to);
}
@@ -209,7 +208,7 @@ void GdbMi::parseTuple_helper(const char *&from, const char *to)
void GdbMi::parseList(const char *&from, const char *to)
{
//qDebug() << "parseList: " << QByteArray(from, to - from);
- QTC_CHECK(*from == '[');
+ //QTC_CHECK(*from == '[');
++from;
m_type = List;
skipCommas(from, to);
@@ -429,5 +428,151 @@ void extractGdbVersion(const QString &msg,
*gdbBuildVersion = build.section(dot, 1, 1).toInt();
}
+//////////////////////////////////////////////////////////////////////////////////
+//
+// Decoding
+//
+//////////////////////////////////////////////////////////////////////////////////
+
+static QString quoteUnprintableLatin1(const QByteArray &ba)
+{
+ QString res;
+ char buf[10];
+ for (int i = 0, n = ba.size(); i != n; ++i) {
+ const unsigned char c = ba.at(i);
+ if (isprint(c)) {
+ res += QLatin1Char(c);
+ } else {
+ qsnprintf(buf, sizeof(buf) - 1, "\\%x", int(c));
+ res += QLatin1String(buf);
+ }
+ }
+ return res;
+}
+
+static QDate dateFromData(int jd)
+{
+ return jd ? QDate::fromJulianDay(jd) : QDate();
+}
+
+static QTime timeFromData(int ms)
+{
+ return ms == -1 ? QTime() : QTime(0, 0, 0, 0).addMSecs(ms);
+}
+
+QString decodeData(const QByteArray &ba, int encoding)
+{
+ switch (encoding) {
+ case Unencoded8Bit: // 0
+ return quoteUnprintableLatin1(ba);
+ case Base64Encoded8BitWithQuotes: { // 1, used for QByteArray
+ const QChar doubleQuote(QLatin1Char('"'));
+ QString rc = doubleQuote;
+ rc += quoteUnprintableLatin1(QByteArray::fromBase64(ba));
+ rc += doubleQuote;
+ return rc;
+ }
+ case Base64Encoded16BitWithQuotes: { // 2, used for QString
+ const QChar doubleQuote(QLatin1Char('"'));
+ const QByteArray decodedBa = QByteArray::fromBase64(ba);
+ QString rc = doubleQuote;
+ rc += QString::fromUtf16(reinterpret_cast<const ushort *>
+ (decodedBa.data()), decodedBa.size() / 2);
+ rc += doubleQuote;
+ return rc;
+ }
+ case Base64Encoded32BitWithQuotes: { // 3
+ const QByteArray decodedBa = QByteArray::fromBase64(ba);
+ const QChar doubleQuote(QLatin1Char('"'));
+ QString rc = doubleQuote;
+ rc += QString::fromUcs4(reinterpret_cast<const uint *>
+ (decodedBa.data()), decodedBa.size() / 4);
+ rc += doubleQuote;
+ return rc;
+ }
+ case Base64Encoded16Bit: { // 4, without quotes (see 2)
+ const QByteArray decodedBa = QByteArray::fromBase64(ba);
+ return QString::fromUtf16(reinterpret_cast<const ushort *>
+ (decodedBa.data()), decodedBa.size() / 2);
+ }
+ case Base64Encoded8Bit: { // 5, without quotes (see 1)
+ return quoteUnprintableLatin1(QByteArray::fromBase64(ba));
+ }
+ case Hex2EncodedLatin1WithQuotes: { // 6, %02x encoded 8 bit Latin1 data
+ const QChar doubleQuote(QLatin1Char('"'));
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return doubleQuote + QString::fromLatin1(decodedBa) + doubleQuote;
+ }
+ case Hex4EncodedLittleEndianWithQuotes: { // 7, %04x encoded 16 bit data
+ const QChar doubleQuote(QLatin1Char('"'));
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return doubleQuote + QString::fromUtf16(reinterpret_cast<const ushort *>
+ (decodedBa.data()), decodedBa.size() / 2) + doubleQuote;
+ }
+ case Hex8EncodedLittleEndianWithQuotes: { // 8, %08x encoded 32 bit data
+ const QChar doubleQuote(QLatin1Char('"'));
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return doubleQuote + QString::fromUcs4(reinterpret_cast<const uint *>
+ (decodedBa.data()), decodedBa.size() / 4) + doubleQuote;
+ }
+ case Hex2EncodedUtf8WithQuotes: { // 9, %02x encoded 8 bit UTF-8 data
+ const QChar doubleQuote(QLatin1Char('"'));
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return doubleQuote + QString::fromUtf8(decodedBa) + doubleQuote;
+ }
+ case Hex8EncodedBigEndian: { // 10, %08x encoded 32 bit data
+ const QChar doubleQuote(QLatin1Char('"'));
+ QByteArray decodedBa = QByteArray::fromHex(ba);
+ for (int i = 0; i < decodedBa.size() - 3; i += 4) {
+ char c = decodedBa.at(i);
+ decodedBa[i] = decodedBa.at(i + 3);
+ decodedBa[i + 3] = c;
+ c = decodedBa.at(i + 1);
+ decodedBa[i + 1] = decodedBa.at(i + 2);
+ decodedBa[i + 2] = c;
+ }
+ return doubleQuote + QString::fromUcs4(reinterpret_cast<const uint *>
+ (decodedBa.data()), decodedBa.size() / 4) + doubleQuote;
+ }
+ case Hex4EncodedBigEndianWithQuotes: { // 11, %04x encoded 16 bit data
+ const QChar doubleQuote(QLatin1Char('"'));
+ QByteArray decodedBa = QByteArray::fromHex(ba);
+ for (int i = 0; i < decodedBa.size(); i += 2) {
+ char c = decodedBa.at(i);
+ decodedBa[i] = decodedBa.at(i + 1);
+ decodedBa[i + 1] = c;
+ }
+ return doubleQuote + QString::fromUtf16(reinterpret_cast<const ushort *>
+ (decodedBa.data()), decodedBa.size() / 2) + doubleQuote;
+ }
+ case Hex4EncodedLittleEndianWithoutQuotes: { // 12, see 7, without quotes
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return QString::fromUtf16(reinterpret_cast<const ushort *>
+ (decodedBa.data()), decodedBa.size() / 2);
+ }
+ case Hex2EncodedLocal8BitWithQuotes: { // 13, %02x encoded 8 bit UTF-8 data
+ const QChar doubleQuote(QLatin1Char('"'));
+ const QByteArray decodedBa = QByteArray::fromHex(ba);
+ return doubleQuote + QString::fromLocal8Bit(decodedBa) + doubleQuote;
+ }
+ case JulianDate: { // 14, an integer count
+ const QDate date = dateFromData(ba.toInt());
+ return date.toString(Qt::TextDate);
+ }
+ case MillisecondsSinceMidnight: {
+ const QTime time = timeFromData(ba.toInt());
+ return time.toString(Qt::TextDate);
+ }
+ case JulianDateAndMillisecondsSinceMidnight: {
+ const int p = ba.indexOf('/');
+ const QDate date = dateFromData(ba.left(p).toInt());
+ const QTime time = timeFromData(ba.mid(p + 1 ).toInt());
+ return QDateTime(date, time).toString(Qt::TextDate);
+ }
+ }
+ qDebug() << "ENCODING ERROR: " << encoding;
+ return QCoreApplication::translate("Debugger", "<Encoding error>");
+}
+
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/gdb/gdbmi.h b/src/plugins/debugger/debuggerprotocol.h
index b9d3e39ae3..2fcdbfacfc 100644
--- a/src/plugins/debugger/gdb/gdbmi.h
+++ b/src/plugins/debugger/debuggerprotocol.h
@@ -27,8 +27,10 @@
**
****************************************************************************/
-#ifndef DEBUGGER_GDBMI_H
-#define DEBUGGER_GDBMI_H
+#ifndef DEBUGGER_PROTOCOL_H
+#define DEBUGGER_PROTOCOL_H
+
+#include "debugger_global.h"
#include <QByteArray>
#include <QList>
@@ -172,9 +174,53 @@ public:
void extractGdbVersion(const QString &msg,
int *gdbVersion, int *gdbBuildVersion, bool *isMacGdb, bool *isQnxGdb);
+// Keep in sync with dumper.py
+enum DebuggerEncoding
+{
+ Unencoded8Bit = 0,
+ Base64Encoded8BitWithQuotes = 1,
+ Base64Encoded16BitWithQuotes = 2,
+ Base64Encoded32BitWithQuotes = 3,
+ Base64Encoded16Bit = 4,
+ Base64Encoded8Bit = 5,
+ Hex2EncodedLatin1WithQuotes = 6,
+ Hex4EncodedLittleEndianWithQuotes = 7,
+ Hex8EncodedLittleEndianWithQuotes = 8,
+ Hex2EncodedUtf8WithQuotes = 9,
+ Hex8EncodedBigEndian = 10,
+ Hex4EncodedBigEndianWithQuotes = 11,
+ Hex4EncodedLittleEndianWithoutQuotes = 12,
+ Hex2EncodedLocal8BitWithQuotes = 13,
+ JulianDate = 14,
+ MillisecondsSinceMidnight = 15,
+ JulianDateAndMillisecondsSinceMidnight = 16,
+ Hex2EncodedInt1 = 17,
+ Hex2EncodedInt2 = 18,
+ Hex2EncodedInt4 = 19,
+ Hex2EncodedInt8 = 20,
+ Hex2EncodedUInt1 = 21,
+ Hex2EncodedUInt2 = 22,
+ Hex2EncodedUInt4 = 23,
+ Hex2EncodedUInt8 = 24,
+ Hex2EncodedFloat4 = 25,
+ Hex2EncodedFloat8 = 26
+};
+
+// Keep in sync with dumper.py, symbolgroupvalue.cpp of CDB
+enum DebuggerDisplay {
+ StopDisplay = 0,
+ DisplayImageData = 1,
+ DisplayUtf16String = 2,
+ DisplayImageFile = 3,
+ DisplayProcess = 4,
+ DisplayLatin1String = 5,
+ DisplayUtf8String = 6
+};
+// Decode string data as returned by the dumper helpers.
+QString decodeData(const QByteArray &baIn, int encoding);
+
} // namespace Internal
} // namespace Debugger
-//Q_DECLARE_METATYPE(GdbDebugger::Internal::GdbMi)
-#endif // DEBUGGER_GDBMI_H
+#endif // DEBUGGER_PROTOCOL_H
diff --git a/src/plugins/debugger/debuggerrunner.cpp b/src/plugins/debugger/debuggerrunner.cpp
index d91f1fcea6..1b89d1083f 100644
--- a/src/plugins/debugger/debuggerrunner.cpp
+++ b/src/plugins/debugger/debuggerrunner.cpp
@@ -48,11 +48,12 @@
#endif
#include <projectexplorer/abi.h>
-#include <projectexplorer/applicationrunconfiguration.h> // For LocalApplication*
+#include <projectexplorer/localapplicationrunconfiguration.h> // For LocalApplication*
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
+#include <projectexplorer/taskhub.h>
#include <projectexplorer/toolchain.h>
#include <utils/outputformat.h>
@@ -70,6 +71,7 @@
#include <QErrorMessage>
#include <QFormLayout>
#include <QLabel>
+#include <QPointer>
using namespace Debugger::Internal;
using namespace ProjectExplorer;
@@ -261,7 +263,7 @@ public:
public:
DebuggerRunControl *q;
DebuggerEngine *m_engine;
- const QWeakPointer<RunConfiguration> m_myRunConfiguration;
+ const QPointer<RunConfiguration> m_myRunConfiguration;
bool m_running;
};
@@ -594,13 +596,16 @@ static bool fixupEngineTypes(DebuggerStartParameters &sp, RunConfiguration *rc,
DebuggerRunControl *DebuggerRunControlFactory::doCreate
(const DebuggerStartParameters &sp0, RunConfiguration *rc, QString *errorMessage)
{
- Q_UNUSED(errorMessage);
+ TaskHub *th = ProjectExplorerPlugin::instance()->taskHub();
+ th->clearTasks(Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO));
+ th->clearTasks(Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_TEST));
+ th->clearTasks(Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME));
+
DebuggerStartParameters sp = sp0;
if (!debuggerCore()->boolSetting(AutoEnrichParameters)) {
const QString sysroot = sp.sysRoot;
- if (sp.debugInfoLocation.isEmpty()) {
+ if (sp.debugInfoLocation.isEmpty())
sp.debugInfoLocation = sysroot + QLatin1String("/usr/lib/debug");
- }
if (sp.debugSourceLocation.isEmpty()) {
QString base = sysroot + QLatin1String("/usr/src/debug/");
sp.debugSourceLocation.append(base + QLatin1String("qt5base/src/corelib"));
diff --git a/src/plugins/debugger/debuggerstreamops.cpp b/src/plugins/debugger/debuggerstreamops.cpp
index fd7693fe47..7443baa53c 100644
--- a/src/plugins/debugger/debuggerstreamops.cpp
+++ b/src/plugins/debugger/debuggerstreamops.cpp
@@ -40,7 +40,7 @@ namespace Internal {
QDataStream &operator<<(QDataStream &stream, const ThreadData &d)
{
- stream << (qint64)d.id;
+ stream << d.id.raw();
stream << d.address;
stream << d.function;
stream << d.fileName;
@@ -54,7 +54,7 @@ QDataStream &operator>>(QDataStream &stream, ThreadData &d)
{
qint64 id;
stream >> id;
- d.id = id;
+ d.id = ThreadId(id);
stream >> d.address;
stream >> d.function;
stream >> d.fileName;
diff --git a/src/plugins/debugger/debuggertooltipmanager.cpp b/src/plugins/debugger/debuggertooltipmanager.cpp
index 0cc7fe4637..af3e0729e9 100644
--- a/src/plugins/debugger/debuggertooltipmanager.cpp
+++ b/src/plugins/debugger/debuggertooltipmanager.cpp
@@ -44,9 +44,9 @@
#include <coreplugin/editormanager/editormanager.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
-#include <texteditor/tooltip/tooltip.h>
-#include <texteditor/tooltip/tipcontents.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <utils/qtcassert.h>
#include <QToolButton>
@@ -220,7 +220,7 @@ public:
DebuggerToolTipEditor::DebuggerToolTipEditor(IEditor *ie) :
textEditor(0), baseTextEditor(0), document(0)
{
- if (ie && ie->document() && isEditorDebuggable(ie)) {
+ if (ie && ie->document()) {
if (ITextEditor *te = qobject_cast<ITextEditor *>(ie)) {
if (BaseTextEditorWidget *pe = qobject_cast<BaseTextEditorWidget *>(ie->widget())) {
textEditor = te;
@@ -280,11 +280,10 @@ void StandardItemTreeModelBuilder::addItem(const QString &s)
void StandardItemTreeModelBuilder::pushRow()
{
- if (m_rowParents.isEmpty()) {
+ if (m_rowParents.isEmpty())
m_model->appendRow(m_row);
- } else {
+ else
m_rowParents.top()->appendRow(m_row);
- }
m_rowParents.push(m_row.front());
m_row.clear();
}
@@ -379,11 +378,10 @@ void XmlWriterTreeModelVisitor::run()
void XmlWriterTreeModelVisitor::handleItem(const QModelIndex &m)
{
const QString value = m.data(Qt::DisplayRole).toString();
- if (value.isEmpty()) {
+ if (value.isEmpty())
m_writer.writeEmptyElement(m_modelItemElement);
- } else {
+ else
m_writer.writeTextElement(m_modelItemElement, value);
- }
}
// TreeModelVisitor for debugging/copying models
@@ -517,7 +515,7 @@ void DebuggerToolTipWidget::pin()
if (parentWidget()) {
// We are currently within a text editor tooltip:
// Rip out of parent widget and re-show as a tooltip
- WidgetContent::pinToolTip(this);
+ Utils::WidgetContent::pinToolTip(this);
} else {
// We have just be restored from session data.
setWindowFlags(Qt::ToolTip);
@@ -1030,11 +1028,10 @@ void DebuggerToolTipWidget::restoreTreeModel(QXmlStreamReader &r, QStandardItemM
case QXmlStreamReader::EndElement: {
const QStringRef element = r.name();
// Row closing: pop off parent.
- if (element == QLatin1String(modelRowElementC)) {
+ if (element == QLatin1String(modelRowElementC))
builder.endRow();
- } else if (element == QLatin1String(modelElementC)) {
+ else if (element == QLatin1String(modelElementC))
withinModel = false;
- }
}
break; // EndElement
default:
@@ -1131,8 +1128,8 @@ void DebuggerToolTipManager::showToolTip(const QPoint &p, IEditor *editor,
QWidget *widget = editor->widget();
if (debugToolTipPositioning)
qDebug() << "DebuggerToolTipManager::showToolTip" << p << " Mouse at " << QCursor::pos();
- const WidgetContent widgetContent(toolTipWidget, true);
- ToolTip::instance()->show(p, widgetContent, widget);
+ const Utils::WidgetContent widgetContent(toolTipWidget, true);
+ Utils::ToolTip::instance()->show(p, widgetContent, widget);
registerToolTip(toolTipWidget);
}
@@ -1145,11 +1142,10 @@ void DebuggerToolTipManager::registerToolTip(DebuggerToolTipWidget *toolTipWidge
void DebuggerToolTipManager::purgeClosedToolTips()
{
for (DebuggerToolTipWidgetList::iterator it = m_tooltips.begin(); it != m_tooltips.end() ; ) {
- if (it->isNull()) {
+ if (it->isNull())
it = m_tooltips.erase(it);
- } else {
+ else
++it;
- }
}
}
@@ -1272,11 +1268,10 @@ void DebuggerToolTipManager::slotUpdateVisibleToolTips()
// Reposition and show all tooltips of that file.
const QString fileName = toolTipEditor.fileName();
foreach (const QPointer<DebuggerToolTipWidget> &tw, m_tooltips) {
- if (tw->fileName() == fileName) {
+ if (tw->fileName() == fileName)
tw->positionShow(toolTipEditor);
- } else {
+ else
tw->hide();
- }
}
}
@@ -1440,7 +1435,7 @@ void DebuggerToolTipManager::slotTooltipOverrideRequested(ITextEditor *editor,
break; // Avoid flicker.
DebuggerCore *core = debuggerCore();
- if (!isEditorDebuggable(editor) || !core->boolSetting(UseToolTipsInMainEditor))
+ if (!core->boolSetting(UseToolTipsInMainEditor))
break;
currentEngine = core->currentEngine();
diff --git a/src/plugins/debugger/disassembleragent.cpp b/src/plugins/debugger/disassembleragent.cpp
index becb265070..f121a3e987 100644
--- a/src/plugins/debugger/disassembleragent.cpp
+++ b/src/plugins/debugger/disassembleragent.cpp
@@ -371,7 +371,7 @@ void DisassemblerAgent::updateLocationMarker()
QPlainTextEdit *plainTextEdit =
qobject_cast<QPlainTextEdit *>(d->editor->widget());
- QTC_ASSERT(plainTextEdit, return);
+ QTC_ASSERT(plainTextEdit, return);
QTextCursor tc = plainTextEdit->textCursor();
QTextBlock block = tc.document()->findBlockByNumber(lineNumber - 1);
tc.setPosition(block.position());
diff --git a/src/plugins/debugger/gdb/abstractplaingdbadapter.cpp b/src/plugins/debugger/gdb/abstractplaingdbadapter.cpp
index 0c1de8b3d7..305d68d71a 100644
--- a/src/plugins/debugger/gdb/abstractplaingdbadapter.cpp
+++ b/src/plugins/debugger/gdb/abstractplaingdbadapter.cpp
@@ -28,11 +28,11 @@
****************************************************************************/
#include "abstractplaingdbadapter.h"
-#include "gdbmi.h"
-#include "gdbengine.h"
-#include "debuggerstartparameters.h"
+
#include "debuggeractions.h"
#include "debuggercore.h"
+#include "debuggerprotocol.h"
+#include "debuggerstartparameters.h"
#include "debuggerstringutils.h"
#include <QDir>
diff --git a/src/plugins/debugger/gdb/attachgdbadapter.cpp b/src/plugins/debugger/gdb/attachgdbadapter.cpp
index 4b71ba73fa..9467471bd9 100644
--- a/src/plugins/debugger/gdb/attachgdbadapter.cpp
+++ b/src/plugins/debugger/gdb/attachgdbadapter.cpp
@@ -28,12 +28,11 @@
****************************************************************************/
#include "attachgdbadapter.h"
-#include "gdbmi.h"
-#include "debuggerstartparameters.h"
-#include "gdbengine.h"
-#include "procinterrupt.h"
+#include "debuggerprotocol.h"
#include "debuggerstringutils.h"
+#include "debuggerstartparameters.h"
+#include "procinterrupt.h"
#include <utils/qtcassert.h>
@@ -88,6 +87,7 @@ void GdbAttachEngine::handleAttach(const GdbResponse &response)
case GdbResultRunning:
showMessage(_("INFERIOR ATTACHED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
+ tryLoadPythonDumpers();
handleInferiorPrepared();
break;
case GdbResultError:
diff --git a/src/plugins/debugger/gdb/classicgdbengine.cpp b/src/plugins/debugger/gdb/classicgdbengine.cpp
index c96735eeab..897ead3f3f 100644
--- a/src/plugins/debugger/gdb/classicgdbengine.cpp
+++ b/src/plugins/debugger/gdb/classicgdbengine.cpp
@@ -28,13 +28,13 @@
****************************************************************************/
#include "gdbengine.h"
-#include "gdbmi.h"
-#include "debuggerstartparameters.h"
#include "debuggeractions.h"
#include "debuggercore.h"
+#include "debuggerprotocol.h"
+#include "debuggerstartparameters.h"
#include "debuggerstringutils.h"
-
+#include "sourceutils.h"
#include "stackhandler.h"
#include "watchhandler.h"
@@ -552,11 +552,10 @@ void DumperHelper::evaluationParameters(const WatchData &data,
// in rare cases we need more or less:
switch (td.type) {
case QAbstractItemType:
- if (data.dumperFlags.isEmpty()) {
+ if (data.dumperFlags.isEmpty())
qWarning("Internal error: empty dumper state '%s'.", data.iname.constData());
- } else {
+ else
inner = data.dumperFlags.mid(1);
- }
break;
case QObjectSlotType:
case QObjectSignalType: {
@@ -1068,11 +1067,10 @@ void GdbEngine::handleDebuggingHelperValue3Classic(const GdbResponse &response)
data1.type = data.type.left(data.type.size() - 4);
data1.iname = data.iname + '.' + QByteArray::number(i);
const QByteArray &addressSpec = list.at(i);
- if (addressSpec.startsWith("0x")) {
+ if (addressSpec.startsWith("0x"))
data.setHexAddress(addressSpec);
- } else {
+ else
data.dumperFlags = addressSpec; // Item model dumpers pull tricks
- }
data1.exp = "((" + gdbQuoteTypes(data1.type) + "*)" + addressSpec + ')';
data1.setHasChildren(false);
data1.setValueNeeded();
@@ -1230,8 +1228,8 @@ void GdbEngine::handleStackListLocalsClassic(const GdbResponse &response)
QStringList uninitializedVariables;
if (debuggerCore()->action(UseCodeModel)->isChecked()) {
const StackFrame frame =
- qVariantCanConvert<Debugger::Internal::StackFrame>(response.cookie)
- ? qVariantValue<Debugger::Internal::StackFrame>(response.cookie)
+ response.cookie.canConvert<Debugger::Internal::StackFrame>()
+ ? qvariant_cast<Debugger::Internal::StackFrame>(response.cookie)
: stackHandler()->currentFrame();
if (frame.isUsable())
getUninitializedVariables(debuggerCore()->cppCodeModelSnapshot(),
@@ -1284,8 +1282,8 @@ static void showQtDumperLibraryWarning(const QString &details)
dialog.exec();
if (dialog.clickedButton() == qtPref) {
Core::ICore::showOptionsDialog(
- _(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY),
- _(QtSupport::Constants::QTVERSION_SETTINGS_PAGE_ID));
+ ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ QtSupport::Constants::QTVERSION_SETTINGS_PAGE_ID);
} else if (dialog.clickedButton() == helperOff) {
debuggerCore()->action(UseDebuggingHelpers)->setValue(qVariantFromValue(false), false);
}
diff --git a/src/plugins/debugger/gdb/coregdbadapter.cpp b/src/plugins/debugger/gdb/coregdbadapter.cpp
index fc782d8c64..71f3f4657c 100644
--- a/src/plugins/debugger/gdb/coregdbadapter.cpp
+++ b/src/plugins/debugger/gdb/coregdbadapter.cpp
@@ -29,12 +29,11 @@
#include "coregdbadapter.h"
-#include "debuggerstartparameters.h"
-#include "debuggercore.h"
#include "debuggeractions.h"
+#include "debuggercore.h"
+#include "debuggerprotocol.h"
+#include "debuggerstartparameters.h"
#include "debuggerstringutils.h"
-#include "gdbmi.h"
-#include "gdbengine.h"
#include <utils/consoleprocess.h>
#include <utils/elfreader.h>
@@ -185,7 +184,7 @@ void GdbCoreEngine::handleTargetCore(const GdbResponse &response)
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
if (response.resultClass == GdbResultDone) {
// HACK: The namespace is not accessible in the initial run.
- loadPythonDumpers();
+ tryLoadPythonDumpers();
showMessage(tr("Attached to core."), StatusBar);
handleInferiorPrepared();
// Due to the auto-solib-add off setting, we don't have any
diff --git a/src/plugins/debugger/gdb/gdb.pri b/src/plugins/debugger/gdb/gdb.pri
index b371e63e73..7a100e6851 100644
--- a/src/plugins/debugger/gdb/gdb.pri
+++ b/src/plugins/debugger/gdb/gdb.pri
@@ -1,5 +1,4 @@
HEADERS += \
- $$PWD/gdbmi.h \
$$PWD/gdbengine.h \
$$PWD/gdboptionspage.h \
$$PWD/attachgdbadapter.h \
@@ -15,7 +14,6 @@ HEADERS += \
$$PWD/startgdbserverdialog.h
SOURCES += \
- $$PWD/gdbmi.cpp \
$$PWD/gdbengine.cpp \
$$PWD/classicgdbengine.cpp \
$$PWD/pythongdbengine.cpp \
diff --git a/src/plugins/debugger/gdb/gdbengine.cpp b/src/plugins/debugger/gdb/gdbengine.cpp
index f472cf96e7..f939934234 100644
--- a/src/plugins/debugger/gdb/gdbengine.cpp
+++ b/src/plugins/debugger/gdb/gdbengine.cpp
@@ -44,13 +44,14 @@
#include "debuggerconstants.h"
#include "debuggercore.h"
#include "debuggerplugin.h"
+#include "debuggerprotocol.h"
#include "debuggerrunner.h"
#include "debuggerstringutils.h"
#include "debuggertooltipmanager.h"
#include "disassembleragent.h"
-#include "gdbmi.h"
#include "gdboptionspage.h"
#include "memoryagent.h"
+#include "sourceutils.h"
#include "watchutils.h"
#include "breakhandler.h"
@@ -75,6 +76,7 @@
#include <projectexplorer/itaskhandler.h>
#include <texteditor/itexteditor.h>
#include <utils/elfreader.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <utils/savedaction.h>
@@ -261,6 +263,7 @@ GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
m_terminalTrap = startParameters.useTerminal;
m_fullStartDone = false;
m_forceAsyncModel = false;
+ m_pythonAttemptedToLoad = false;
invalidateSourcesList();
@@ -278,6 +281,8 @@ GdbEngine::GdbEngine(const DebuggerStartParameters &startParameters)
SLOT(reloadLocals()));
connect(debuggerCore()->action(UseDynamicType), SIGNAL(valueChanged(QVariant)),
SLOT(reloadLocals()));
+ connect(debuggerCore()->action(IntelFlavor), SIGNAL(valueChanged(QVariant)),
+ SLOT(reloadDisassembly()));
}
GdbEngine::~GdbEngine()
@@ -343,24 +348,23 @@ static void dump(const char *first, const char *middle, const QString & to)
// Parse "~:gdb: unknown target exception 0xc0000139 at 0x77bef04e\n"
// and return an exception message
-static inline QString msgWinException(const QByteArray &data)
+static inline QString msgWinException(const QByteArray &data, unsigned *exCodeIn = 0)
{
+ if (exCodeIn)
+ *exCodeIn = 0;
const int exCodePos = data.indexOf("0x");
const int blankPos = exCodePos != -1 ? data.indexOf(' ', exCodePos + 1) : -1;
const int addressPos = blankPos != -1 ? data.indexOf("0x", blankPos + 1) : -1;
if (addressPos < 0)
return GdbEngine::tr("An exception was triggered.");
const unsigned exCode = data.mid(exCodePos, blankPos - exCodePos).toUInt(0, 0);
+ if (exCodeIn)
+ *exCodeIn = exCode;
const quint64 address = data.mid(addressPos).trimmed().toULongLong(0, 0);
QString rc;
QTextStream str(&rc);
str << GdbEngine::tr("An exception was triggered: ");
-#ifdef Q_OS_WIN
formatWindowsException(exCode, address, 0, 0, 0, str);
-#else
- Q_UNUSED(exCode)
- Q_UNUSED(address)
-#endif
str << '.';
return rc;
}
@@ -466,6 +470,8 @@ void GdbEngine::handleResponse(const QByteArray &buff)
m_pendingLogStreamOutput.clear();
m_pendingConsoleStreamOutput.clear();
} else if (asyncClass == "running") {
+ GdbMi threads = result.findChild("thread-id");
+ threadsHandler()->notifyRunning(threads.data());
if (state() == InferiorRunOk || state() == InferiorSetupRequested) {
// We get multiple *running after thread creation and in Windows terminals.
showMessage(QString::fromLatin1("NOTE: INFERIOR STILL RUNNING IN STATE %1.").
@@ -526,6 +532,10 @@ void GdbEngine::handleResponse(const QByteArray &buff)
//"{id="1",group-id="28902"}"
QByteArray id = result.findChild("id").data();
showStatusMessage(tr("Thread %1 created").arg(_(id)), 1000);
+ ThreadData thread;
+ thread.id = ThreadId(id.toLong());
+ thread.groupId = result.findChild("group-id").data();
+ threadsHandler()->updateThread(thread);
} else if (asyncClass == "thread-group-exited") {
// Archer has "{id="28902"}"
QByteArray id = result.findChild("id").data();
@@ -537,6 +547,7 @@ void GdbEngine::handleResponse(const QByteArray &buff)
QByteArray groupid = result.findChild("group-id").data();
showStatusMessage(tr("Thread %1 in group %2 exited")
.arg(_(id)).arg(_(groupid)), 1000);
+ threadsHandler()->removeThread(ThreadId(id.toLong()));
} else if (asyncClass == "thread-selected") {
QByteArray id = result.findChild("id").data();
showStatusMessage(tr("Thread %1 selected").arg(_(id)), 1000);
@@ -689,8 +700,13 @@ void GdbEngine::handleResponse(const QByteArray &buff)
// [Windows, most likely some DLL/Entry point not found]:
// "gdb: unknown target exception 0xc0000139 at 0x77bef04e"
// This may be fatal and cause the target to exit later
- m_lastWinException = msgWinException(data);
+ unsigned exCode;
+ m_lastWinException = msgWinException(data, &exCode);
showMessage(m_lastWinException, LogMisc);
+ const Task::TaskType type = isFatalWinException(exCode) ? Task::Error : Task::Warning;
+ const Task task(type, m_lastWinException, Utils::FileName(), 0,
+ Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_RUNTIME));
+ taskHub()->addTask(task);
}
if (data.startsWith("QMLBP:")) {
@@ -732,7 +748,7 @@ void GdbEngine::handleResponse(const QByteArray &buff)
Task task(Task::Warning,
tr("Missing debug information for %1\nTry: %2")
.arg(m_lastMissingDebugInfo).arg(cmd),
- FileName(), 0, Core::Id("Debuginfo"));
+ FileName(), 0, Core::Id(Debugger::Constants::TASK_CATEGORY_DEBUGGER_DEBUGINFO));
taskHub()->addTask(task);
@@ -754,19 +770,18 @@ void GdbEngine::handleResponse(const QByteArray &buff)
break;
QByteArray resultClass = QByteArray::fromRawData(from, inner - from);
- if (resultClass == "done") {
+ if (resultClass == "done")
response.resultClass = GdbResultDone;
- } else if (resultClass == "running") {
+ else if (resultClass == "running")
response.resultClass = GdbResultRunning;
- } else if (resultClass == "connected") {
+ else if (resultClass == "connected")
response.resultClass = GdbResultConnected;
- } else if (resultClass == "error") {
+ else if (resultClass == "error")
response.resultClass = GdbResultError;
- } else if (resultClass == "exit") {
+ else if (resultClass == "exit")
response.resultClass = GdbResultExit;
- } else {
+ else
response.resultClass = GdbResultUnknown;
- }
from = inner;
if (from != to) {
@@ -944,9 +959,8 @@ void GdbEngine::postCommandHelper(const GdbCommand &cmd)
showMessage(_("QUEUING COMMAND " + cmd.command));
m_commandsToRunOnTemporaryBreak.append(cmd);
if (state() == InferiorStopRequested) {
- if (cmd.flags & LosesChild) {
+ if (cmd.flags & LosesChild)
notifyInferiorIll();
- }
showMessage(_("CHILD ALREADY BEING INTERRUPTED. STILL HOPING."));
// Calling shutdown() here breaks all situations where two
// NeedsStop commands are issued in quick succession.
@@ -1396,6 +1410,9 @@ void GdbEngine::handleStopResponse(const GdbMi &data)
return;
}
+ GdbMi threads = data.findChild("stopped-thread");
+ threadsHandler()->notifyStopped(threads.data());
+
const QByteArray reason = data.findChild("reason").data();
if (isExitedReason(reason)) {
@@ -1418,11 +1435,12 @@ void GdbEngine::handleStopResponse(const GdbMi &data)
return;
}
+ tryLoadPythonDumpers();
+
bool gotoHandleStop1 = true;
if (!m_fullStartDone) {
m_fullStartDone = true;
postCommand("sharedlibrary .*");
- loadPythonDumpers();
postCommand("p 3", CB(handleStop1));
gotoHandleStop1 = false;
}
@@ -1747,10 +1765,6 @@ void GdbEngine::handleStop2(const GdbMi &data)
// Let the event loop run before deciding whether to update the stack.
m_stackNeeded = true; // setTokenBarrier() might reset this.
- if (isStopperThread)
- m_currentThreadId = 0;
- else
- m_currentThreadId = data.findChild("thread-id").data().toInt();
QTimer::singleShot(0, this, SLOT(handleStop2()));
}
@@ -1760,8 +1774,6 @@ void GdbEngine::handleStop2()
if (!m_stackNeeded)
return;
- reloadStack(false); // Will trigger register reload.
-
if (supportsThreads()) {
if (m_isMacGdb || m_gdbVersion < 70100) {
postCommand("-thread-list-ids", Discardable, CB(handleThreadListIds));
@@ -1770,7 +1782,6 @@ void GdbEngine::handleStop2()
postCommand("-thread-info", Discardable, CB(handleThreadInfo));
}
}
-
}
void GdbEngine::handleInfoProc(const GdbResponse &response)
@@ -1831,6 +1842,14 @@ void GdbEngine::handleListFeatures(const GdbResponse &response)
void GdbEngine::handleHasPython(const GdbResponse &response)
{
+ if (response.resultClass == GdbResultDone)
+ m_hasPython = true;
+ else
+ pythonDumpersFailed();
+}
+
+void GdbEngine::handlePythonSetup(const GdbResponse &response)
+{
if (response.resultClass == GdbResultDone) {
m_hasPython = true;
GdbMi data;
@@ -1852,8 +1871,6 @@ void GdbEngine::handleHasPython(const GdbResponse &response)
}
const GdbMi hasInferiorThreadList = data.findChild("hasInferiorThreadList");
m_hasInferiorThreadList = (hasInferiorThreadList.data().toInt() != 0);
- } else {
- pythonDumpersFailed();
}
}
@@ -2120,9 +2137,11 @@ bool GdbEngine::hasCapability(unsigned cap) const
| AddWatcherCapability
| WatchWidgetsCapability
| ShowModuleSymbolsCapability
+ | ShowModuleSectionsCapability
| CatchCapability
| OperateByInstructionCapability
| RunToLineCapability
+ | WatchComplexExpressionsCapability
| MemoryAddressCapability))
return true;
@@ -2166,11 +2185,10 @@ void GdbEngine::executeStep()
setTokenBarrier();
notifyInferiorRunRequested();
showStatusMessage(tr("Step requested..."), 5000);
- if (isReverseDebugging()) {
+ if (isReverseDebugging())
postCommand("reverse-step", RunRequest, CB(handleExecuteStep));
- } else {
+ else
postCommand("-exec-step", RunRequest, CB(handleExecuteStep));
- }
}
void GdbEngine::handleExecuteStep(const GdbResponse &response)
@@ -3317,7 +3335,7 @@ void GdbEngine::handleShowModuleSymbols(const GdbResponse &response)
const QString modulePath = cookie.section(QLatin1Char('@'), 0, 0);
const QString fileName = cookie.section(QLatin1Char('@'), 1, 1);
if (response.resultClass == GdbResultDone) {
- Symbols rc;
+ Symbols symbols;
QFile file(fileName);
file.open(QIODevice::ReadOnly);
// Object file /opt/dev/qt/lib/libQtNetworkMyns.so.4:
@@ -3361,17 +3379,62 @@ void GdbEngine::handleShowModuleSymbols(const GdbResponse &response)
symbol.name = _(line.mid(posName, lenName));
symbol.section = _(line.mid(posSection, lenSection));
symbol.demangled = _(line.mid(posDemangled, lenDemangled));
- rc.push_back(symbol);
+ symbols.push_back(symbol);
}
file.close();
file.remove();
- debuggerCore()->showModuleSymbols(modulePath, rc);
+ debuggerCore()->showModuleSymbols(modulePath, symbols);
} else {
showMessageBox(QMessageBox::Critical, tr("Cannot Read Symbols"),
tr("Cannot read symbols for module \"%1\".").arg(fileName));
}
}
+void GdbEngine::requestModuleSections(const QString &moduleName)
+{
+ // There seems to be no way to get the symbols from a single .so.
+ postCommand("maint info section ALLOBJ",
+ NeedsStop, CB(handleShowModuleSections), moduleName);
+}
+
+void GdbEngine::handleShowModuleSections(const GdbResponse &response)
+{
+ // ~" Object file: /usr/lib/i386-linux-gnu/libffi.so.6\n"
+ // ~" 0xb44a6114->0xb44a6138 at 0x00000114: .note.gnu.build-id ALLOC LOAD READONLY DATA HAS_CONTENTS\n"
+ if (response.resultClass == GdbResultDone) {
+ const QString moduleName = response.cookie.toString();
+ const QStringList lines = QString::fromLocal8Bit(response.consoleStreamOutput).split(QLatin1Char('\n'));
+ const QString prefix = QLatin1String(" Object file: ");
+ const QString needle = prefix + moduleName;
+ Sections sections;
+ bool active = false;
+ foreach (const QString &line, lines) {
+ if (line.startsWith(prefix)) {
+ if (active)
+ break;
+ if (line == needle)
+ active = true;
+ } else {
+ if (active) {
+ QStringList items = line.split(QLatin1Char(' '), QString::SkipEmptyParts);
+ QString fromTo = items.value(0, QString());
+ const int pos = fromTo.indexOf(QLatin1Char('-'));
+ QTC_ASSERT(pos >= 0, continue);
+ Section section;
+ section.from = fromTo.left(pos);
+ section.to = fromTo.mid(pos + 2);
+ section.address = items.value(2, QString());
+ section.name = items.value(3, QString());
+ section.flags = items.value(4, QString());
+ sections.append(section);
+ }
+ }
+ }
+ if (!sections.isEmpty())
+ debuggerCore()->showModuleSections(moduleName, sections);
+ }
+}
+
void GdbEngine::reloadModules()
{
if (state() == InferiorRunOk || state() == InferiorStopOk)
@@ -3488,15 +3551,12 @@ void GdbEngine::reloadSourceFilesInternal()
//
//////////////////////////////////////////////////////////////////////
-void GdbEngine::selectThread(int index)
+void GdbEngine::selectThread(ThreadId threadId)
{
- threadsHandler()->setCurrentThread(index);
- Threads threads = threadsHandler()->threads();
- QTC_ASSERT(index < threads.size(), return);
- const int id = threads.at(index).id;
+ threadsHandler()->setCurrentThread(threadId);
showStatusMessage(tr("Retrieving data for stack view thread 0x%1...")
- .arg(id, 0, 16), 10000);
- postCommand("-thread-select " + QByteArray::number(id), Discardable,
+ .arg(threadId.raw(), 0, 16), 10000);
+ postCommand("-thread-select " + QByteArray::number(threadId.raw()), Discardable,
CB(handleStackSelectThread));
}
@@ -3640,17 +3700,21 @@ void GdbEngine::handleStackSelectFrame(const GdbResponse &response)
void GdbEngine::handleThreadInfo(const GdbResponse &response)
{
if (response.resultClass == GdbResultDone) {
- int currentThreadId;
- const Threads threads =
- ThreadsHandler::parseGdbmiThreads(response.data, &currentThreadId);
- threadsHandler()->setThreads(threads);
- threadsHandler()->setCurrentThreadId(currentThreadId);
+ ThreadsHandler *handler = threadsHandler();
+ handler->updateThreads(response.data);
+ // This is necessary as the current thread might not be in the list.
+ if (!handler->currentThread().isValid()) {
+ ThreadId other = handler->threadAt(0);
+ if (other.isValid())
+ selectThread(other);
+ }
updateViews(); // Adjust Threads combobox.
if (m_hasInferiorThreadList && debuggerCore()->boolSetting(ShowThreadNames)) {
postCommand("threadnames " +
debuggerCore()->action(MaximalStackDepth)->value().toByteArray(),
Discardable, CB(handleThreadNames));
}
+ reloadStack(false); // Will trigger register reload.
} else {
// Fall back for older versions: Try to get at least a list
// of running threads.
@@ -3662,37 +3726,29 @@ void GdbEngine::handleThreadListIds(const GdbResponse &response)
{
// "72^done,{thread-ids={thread-id="2",thread-id="1"},number-of-threads="2"}
// In gdb 7.1+ additionally: current-thread-id="1"
+ ThreadsHandler *handler = threadsHandler();
const QList<GdbMi> items = response.data.findChild("thread-ids").children();
- Threads threads;
for (int index = 0, n = items.size(); index != n; ++index) {
ThreadData thread;
- thread.id = items.at(index).data().toInt();
- threads.append(thread);
+ thread.id = ThreadId(items.at(index).data().toInt());
+ handler->updateThread(thread);
}
- threadsHandler()->setThreads(threads);
- threadsHandler()->setCurrentThreadId(m_currentThreadId);
+ reloadStack(false); // Will trigger register reload.
}
void GdbEngine::handleThreadNames(const GdbResponse &response)
{
if (response.resultClass == GdbResultDone) {
+ ThreadsHandler *handler = threadsHandler();
GdbMi names;
names.fromString(response.consoleStreamOutput);
-
- Threads threads = threadsHandler()->threads();
-
foreach (const GdbMi &name, names.children()) {
- int id = name.findChild("id").data().toInt();
- for (int index = 0, n = threads.size(); index != n; ++index) {
- ThreadData &thread = threads[index];
- if (thread.id == quint64(id)) {
- thread.name = decodeData(name.findChild("value").data(),
- name.findChild("valueencoded").data().toInt());
- break;
- }
- }
+ ThreadData thread;
+ thread.id = ThreadId(name.findChild("id").data().toInt());
+ thread.name = decodeData(name.findChild("value").data(),
+ name.findChild("valueencoded").data().toInt());
+ handler->updateThread(thread);
}
- threadsHandler()->setThreads(threads);
updateViews();
}
}
@@ -4539,6 +4595,12 @@ DisassemblerLines GdbEngine::parseDisassembler(const GdbResponse &response)
return parseCliDisassembler(response.consoleStreamOutput);
}
+void GdbEngine::reloadDisassembly()
+{
+ setTokenBarrier();
+ updateLocals();
+}
+
void GdbEngine::handleDisassemblerCheck(const GdbResponse &response)
{
m_disassembleUsesComma = response.resultClass != GdbResultDone;
@@ -4649,7 +4711,7 @@ void GdbEngine::startGdb(const QStringList &args)
handleGdbStartFailed();
handleAdapterStartFailed(
msgNoGdbBinaryForToolChain(sp.toolChainAbi),
- _(Constants::DEBUGGER_COMMON_SETTINGS_ID));
+ Constants::DEBUGGER_COMMON_SETTINGS_ID);
return;
}
QStringList gdbArgs;
@@ -4730,10 +4792,10 @@ void GdbEngine::startGdb(const QStringList &args)
postCommand("set width 0");
postCommand("set height 0");
- postCommand("set breakpoint always-inserted on", ConsoleCommand);
+ //postCommand("set breakpoint always-inserted on", ConsoleCommand);
// displaced-stepping does not work in Thumb mode.
//postCommand("set displaced-stepping on");
- postCommand("set trust-readonly-sections on", ConsoleCommand);
+ //postCommand("set trust-readonly-sections on", ConsoleCommand);
postCommand("set remotecache on", ConsoleCommand);
//postCommand("set non-stop on", ConsoleCommand);
@@ -4793,10 +4855,18 @@ void GdbEngine::startGdb(const QStringList &args)
} else {
m_fullStartDone = true;
postCommand("set auto-solib-add on", ConsoleCommand);
- loadPythonDumpers();
}
+ if (debuggerCore()->boolSetting(MultiInferior)) {
+ //postCommand("set follow-exec-mode new");
+ postCommand("set detach-on-fork off");
+ }
+
+ // Quick check whether we have python.
+ postCommand("python print 43", ConsoleCommand, CB(handleHasPython));
+
// Dummy command to guarantee a roundtrip before the adapter proceed.
+ // Make sure this stays the last command in startGdb().
postCommand("pwd", ConsoleCommand, CB(reportEngineSetupOk));
}
@@ -4834,10 +4904,15 @@ void GdbEngine::loadInitScript()
}
}
-void GdbEngine::loadPythonDumpers()
+void GdbEngine::tryLoadPythonDumpers()
{
if (m_forceAsyncModel)
return;
+ if (!m_hasPython)
+ return;
+ if (m_pythonAttemptedToLoad)
+ return;
+ m_pythonAttemptedToLoad = true;
const QByteArray dumperSourcePath =
Core::ICore::resourcePath().toLocal8Bit() + "/dumper/";
@@ -4849,9 +4924,22 @@ void GdbEngine::loadPythonDumpers()
postCommand("python execfile('" + dumperSourcePath + "qttypes.py')",
ConsoleCommand|NonCriticalResponse);
+ postCommand("python qqStringCutOff = "
+ + debuggerCore()->action(MaximalStringLength)->value().toByteArray(),
+ ConsoleCommand|NonCriticalResponse);
+
loadInitScript();
- postCommand("bbsetup", ConsoleCommand, CB(handleHasPython));
+ postCommand("bbsetup", ConsoleCommand, CB(handlePythonSetup));
+}
+
+void GdbEngine::reloadDebuggingHelpers()
+{
+ // Only supported for python.
+ if (m_hasPython) {
+ m_pythonAttemptedToLoad = false;
+ tryLoadPythonDumpers();
+ }
}
void GdbEngine::handleGdbError(QProcess::ProcessError error)
@@ -4921,17 +5009,17 @@ void GdbEngine::abortDebugger()
}
void GdbEngine::handleAdapterStartFailed(const QString &msg,
- const QString &settingsIdHint)
+ Core::Id settingsIdHint)
{
QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
showMessage(_("ADAPTER START FAILED"));
if (!msg.isEmpty()) {
const QString title = tr("Adapter start failed");
- if (settingsIdHint.isEmpty()) {
+ if (!settingsIdHint.isValid()) {
Core::ICore::showWarningWithOptions(title, msg);
} else {
Core::ICore::showWarningWithOptions(title, msg, QString(),
- _(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY), settingsIdHint);
+ Constants::DEBUGGER_SETTINGS_CATEGORY, settingsIdHint);
}
}
notifyEngineSetupFailed();
@@ -4951,6 +5039,11 @@ void GdbEngine::handleInferiorPrepared()
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
+ if (debuggerCore()->boolSetting(IntelFlavor)) {
+ //postCommand("set follow-exec-mode new");
+ postCommand("set disassembly-flavor intel");
+ }
+
if (sp.breakOnMain) {
QByteArray cmd = "tbreak ";
cmd += sp.toolChainAbi.os() == Abi::WindowsOS ? "qMain" : "main";
@@ -4988,19 +5081,17 @@ void GdbEngine::finishInferiorSetup()
void GdbEngine::handleDebugInfoLocation(const GdbResponse &response)
{
-#ifdef Q_OS_WIN
- const char pathSep = ';';
-#else
- const char pathSep = ':';
-#endif
if (response.resultClass == GdbResultDone) {
const QByteArray debugInfoLocation = startParameters().debugInfoLocation.toLocal8Bit();
if (QFile::exists(QString::fromLocal8Bit(debugInfoLocation))) {
const QByteArray curDebugInfoLocations = response.consoleStreamOutput.split('"').value(1);
- if (curDebugInfoLocations.isEmpty())
+ if (curDebugInfoLocations.isEmpty()) {
postCommand("set debug-file-directory " + debugInfoLocation);
- else
- postCommand("set debug-file-directory " + debugInfoLocation + pathSep + curDebugInfoLocations);
+ } else {
+ postCommand("set debug-file-directory " + debugInfoLocation
+ + HostOsInfo::pathListSeparator().toLatin1()
+ + curDebugInfoLocations);
+ }
}
}
}
@@ -5033,13 +5124,18 @@ void GdbEngine::handleNamespaceExtraction(const GdbResponse &response)
} else {
if (debuggerCore()->boolSetting(BreakOnAbort))
postCommand("-break-insert -f abort");
- if (debuggerCore()->boolSetting(BreakOnWarning))
+ if (debuggerCore()->boolSetting(BreakOnWarning)) {
postCommand("-break-insert -f '" + qtNamespace() + "qWarning'");
- if (debuggerCore()->boolSetting(BreakOnFatal))
+ postCommand("-break-insert -f '" + qtNamespace() + "QMessageLogger::warning'");
+ }
+ if (debuggerCore()->boolSetting(BreakOnFatal)) {
postCommand("-break-insert -f '" + qtNamespace() + "qFatal'",
- CB(handleBreakOnQFatal));
- else
+ CB(handleBreakOnQFatal), QVariant(false));
+ postCommand("-break-insert -f '" + qtNamespace() + "QMessageLogger::fatal'",
+ CB(handleBreakOnQFatal), QVariant(true));
+ } else {
notifyInferiorSetupOk();
+ }
}
}
@@ -5056,7 +5152,8 @@ void GdbEngine::handleBreakOnQFatal(const GdbResponse &response)
}
// Continue setup.
- notifyInferiorSetupOk();
+ if (response.cookie.toBool())
+ notifyInferiorSetupOk();
}
void GdbEngine::notifyInferiorSetupFailed(const QString &msg)
@@ -5309,7 +5406,7 @@ bool GdbEngine::prepareCommand()
// perr == BadQuoting is never returned on Windows
// FIXME? QTCREATORBUG-2809
handleAdapterStartFailed(QCoreApplication::translate("DebuggerEngine", // Same message in CdbEngine
- "Debugging complex command lines is currently not supported on Windows."), QString());
+ "Debugging complex command lines is currently not supported on Windows."), Core::Id());
return false;
}
#endif
@@ -5362,6 +5459,14 @@ void GdbEngine::interruptLocalInferior(qint64 pid)
}
}
+QByteArray GdbEngine::dotEscape(QByteArray str)
+{
+ str.replace(' ', '.');
+ str.replace('\\', '.');
+ str.replace('/', '.');
+ return str;
+}
+
//
// Factory
//
diff --git a/src/plugins/debugger/gdb/gdbengine.h b/src/plugins/debugger/gdb/gdbengine.h
index 689c133e00..b70d9e4756 100644
--- a/src/plugins/debugger/gdb/gdbengine.h
+++ b/src/plugins/debugger/gdb/gdbengine.h
@@ -35,6 +35,9 @@
#include "stackframe.h"
#include "watchhandler.h"
#include "watchutils.h"
+#include "threaddata.h"
+
+#include <coreplugin/id.h>
#include <QByteArray>
#include <QProcess>
@@ -227,18 +230,19 @@ protected: ////////// Gdb Process Management //////////
void startGdb(const QStringList &args = QStringList());
void reportEngineSetupOk(const GdbResponse &response);
+ void handleCheckForPython(const GdbResponse &response);
void handleInferiorShutdown(const GdbResponse &response);
void handleGdbExit(const GdbResponse &response);
void handleNamespaceExtraction(const GdbResponse &response);
void loadInitScript();
- void loadPythonDumpers();
+ void tryLoadPythonDumpers();
void pythonDumpersFailed();
// Something went wrong with the adapter *before* adapterStarted() was emitted.
// Make sure to clean up everything before emitting this signal.
void handleAdapterStartFailed(const QString &msg,
- const QString &settingsIdHint = QString());
+ Core::Id settingsIdHint = Core::Id());
// This triggers the initial breakpoint synchronization and causes
// finishInferiorSetup() being called once done.
@@ -387,6 +391,7 @@ protected:
void handleShowVersion(const GdbResponse &response);
void handleListFeatures(const GdbResponse &response);
void handleHasPython(const GdbResponse &response);
+ void handlePythonSetup(const GdbResponse &response);
int m_gdbVersion; // 6.8.0 is 60800
int m_gdbBuildVersion; // MAC only?
@@ -437,7 +442,7 @@ private: ////////// Inferior Management //////////
private: ////////// View & Data Stuff //////////
protected:
- void selectThread(int index);
+ void selectThread(ThreadId threadId);
void activateFrame(int index);
void resetLocation();
@@ -475,11 +480,13 @@ private: ////////// View & Data Stuff //////////
Q_SLOT void loadAllSymbols();
void loadSymbolsForStack();
void requestModuleSymbols(const QString &moduleName);
+ void requestModuleSections(const QString &moduleName);
void reloadModules();
void examineModules();
void reloadModulesInternal();
void handleModulesList(const GdbResponse &response);
void handleShowModuleSymbols(const GdbResponse &response);
+ void handleShowModuleSections(const GdbResponse &response);
//
// Snapshot specific stuff
@@ -523,6 +530,7 @@ private: ////////// View & Data Stuff //////////
DisassemblerLines parseDisassembler(const GdbResponse &response);
DisassemblerLines parseCliDisassembler(const QByteArray &response);
DisassemblerLines parseMiDisassembler(const GdbMi &response);
+ Q_SLOT void reloadDisassembly();
bool m_disassembleUsesComma;
@@ -645,6 +653,7 @@ protected:
bool checkDebuggingHelpersClassic();
void setDebuggingHelperStateClassic(DebuggingHelperState);
void tryLoadDebuggingHelpersClassic();
+ void reloadDebuggingHelpers();
DebuggingHelperState m_debuggingHelperState;
DumperHelper m_dumperHelper;
@@ -661,10 +670,8 @@ protected:
QString tooltipExpression() const;
QScopedPointer<GdbToolTipContext> m_toolTipContext;
-
// For short-circuiting stack and thread list evaluation.
bool m_stackNeeded;
- int m_currentThreadId;
//
// Qml
@@ -701,6 +708,7 @@ protected:
// debug information.
bool attemptQuickStart() const;
bool m_fullStartDone;
+ bool m_pythonAttemptedToLoad;
// Test
bool m_forceAsyncModel;
@@ -713,6 +721,7 @@ protected:
static QString msgInferiorSetupOk();
static QString msgInferiorRunOk();
static QString msgConnectRemoteServerFailed(const QString &why);
+ static QByteArray dotEscape(QByteArray str);
protected:
enum DumperHandling
diff --git a/src/plugins/debugger/gdb/gdboptionspage.cpp b/src/plugins/debugger/gdb/gdboptionspage.cpp
index 0d023f1c09..014db0cf01 100644
--- a/src/plugins/debugger/gdb/gdboptionspage.cpp
+++ b/src/plugins/debugger/gdb/gdboptionspage.cpp
@@ -76,9 +76,13 @@ public:
QCheckBox *checkBoxBreakOnAbort;
QCheckBox *checkBoxEnableReverseDebugging;
QCheckBox *checkBoxAttemptQuickStart;
+ QCheckBox *checkBoxMultiInferior;
+ QCheckBox *checkBoxIntelFlavor;
QGroupBox *groupBoxStartupCommands;
QTextEdit *textEditStartupCommands;
+ QGroupBox *groupBoxPostAttachCommands;
+ QTextEdit *textEditPostAttachCommands;
//QGroupBox *groupBoxPluginDebugging;
//QRadioButton *radioButtonAllPluginBreakpoints;
@@ -183,6 +187,7 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
"of debug information such as <i>/usr/src/debug</i> "
"when starting GDB.</body></html>"));
+ // #fixme: 2.7 Move to common settings page.
checkBoxBreakOnWarning = new QCheckBox(groupBoxGeneral);
checkBoxBreakOnWarning->setText(CommonOptionsPage::msgSetBreakpointAtFunction("qWarning"));
checkBoxBreakOnWarning->setToolTip(CommonOptionsPage::msgSetBreakpointAtFunctionToolTip("qWarning"));
@@ -210,13 +215,30 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
"This can result in faster startup times at the price of not being able to "
"set breakpoints by file and number.</body></html>"));
+ checkBoxMultiInferior = new QCheckBox(groupBoxGeneral);
+ checkBoxMultiInferior->setText(GdbOptionsPage::tr("Debug all children"));
+ checkBoxMultiInferior->setToolTip(GdbOptionsPage::tr(
+ "<html><head/><body>Keep debugging all children after a fork."
+ "</body></html>"));
+
+ checkBoxIntelFlavor = new QCheckBox(groupBoxGeneral);
+ checkBoxIntelFlavor->setText(GdbOptionsPage::tr("Use Intel style disassembly"));
+ checkBoxIntelFlavor->setToolTip(GdbOptionsPage::tr(
+ "<html><head/><body>GDB shows by default AT&&T style disassembly."
+ "</body></html>"));
+
groupBoxStartupCommands = new QGroupBox(this);
groupBoxStartupCommands->setTitle(GdbOptionsPage::tr("Additional Startup Commands"));
groupBoxStartupCommands->setToolTip(GdbOptionsPage::tr(
"<html><head/><body><p>GDB commands entered here will be executed after "
"GDB has been started and the debugging helpers have been initialized.</p>"
"<p>You can add commands to load further debugging helpers here, or "
- "modify existing ones.</p><p>To execute arbitrary Python scripts, "
+ "modify existing ones.</p>"
+ "<p>To execute simple Python commands, prefix them with \"python\".</p>"
+ "<p>To execute sequences of Python commands spanning multiple lines "
+ "prepend the block with \"python\" on a separate line, and append "
+ "\"end\" on a separate line.</p>"
+ "<p>To execute arbitrary Python scripts, "
"use <i>python execfile('/path/to/script.py')</i>.</p>"
"</body></html>"));
@@ -224,6 +246,19 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
textEditStartupCommands->setAcceptRichText(false);
textEditStartupCommands->setToolTip(groupBoxStartupCommands->toolTip());
+ groupBoxPostAttachCommands = new QGroupBox(this);
+ groupBoxPostAttachCommands->setTitle(GdbOptionsPage::tr("Additional Attach Commands"));
+ groupBoxPostAttachCommands->setToolTip(GdbOptionsPage::tr(
+ "<html><head/><body><p>GDB commands entered here will be executed after "
+ "GDB has successfully attached to remote targets.</p>"
+ "<p>You can add commands to further set up the target here, "
+ "such as \"monitor reset\" or \"load\"."
+ "</body></html>"));
+
+ textEditPostAttachCommands = new QTextEdit(groupBoxPostAttachCommands);
+ textEditPostAttachCommands->setAcceptRichText(false);
+ textEditPostAttachCommands->setToolTip(groupBoxPostAttachCommands->toolTip());
+
/*
groupBoxPluginDebugging = new QGroupBox(q);
groupBoxPluginDebugging->setTitle(GdbOptionsPage::tr(
@@ -258,6 +293,7 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
formLayout->addRow(checkBoxUseDynamicType);
formLayout->addRow(checkBoxLoadGdbInit);
formLayout->addRow(checkBoxWarnOnReleaseBuilds);
+ formLayout->addRow(checkBoxIntelFlavor);
formLayout->addRow(labelDangerous);
formLayout->addRow(checkBoxTargetAsync);
formLayout->addRow(checkBoxAutoEnrichParameters);
@@ -266,18 +302,23 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
formLayout->addRow(checkBoxBreakOnAbort);
formLayout->addRow(checkBoxEnableReverseDebugging);
formLayout->addRow(checkBoxAttemptQuickStart);
+ formLayout->addRow(checkBoxMultiInferior);
QGridLayout *startLayout = new QGridLayout(groupBoxStartupCommands);
startLayout->addWidget(textEditStartupCommands, 0, 0, 1, 1);
+ QGridLayout *postAttachLayout = new QGridLayout(groupBoxPostAttachCommands);
+ postAttachLayout->addWidget(textEditPostAttachCommands, 0, 0, 1, 1);
+
//QHBoxLayout *horizontalLayout = new QHBoxLayout();
//horizontalLayout->addItem(new QSpacerItem(10, 10, QSizePolicy::Preferred, QSizePolicy::Minimum));
//horizontalLayout->addWidget(labelSelectedPluginBreakpoints);
//horizontalLayout->addWidget(lineEditSelectedPluginBreakpointsPattern);
QGridLayout *gridLayout = new QGridLayout(this);
- gridLayout->addWidget(groupBoxGeneral, 0, 0);
- gridLayout->addWidget(groupBoxStartupCommands, 0, 1);
+ gridLayout->addWidget(groupBoxGeneral, 0, 0, 2, 1);
+ gridLayout->addWidget(groupBoxStartupCommands, 0, 1, 1, 1);
+ gridLayout->addWidget(groupBoxPostAttachCommands, 1, 1, 1, 1);
//gridLayout->addWidget(groupBoxStartupCommands, 0, 1, 1, 1);
//gridLayout->addWidget(radioButtonAllPluginBreakpoints, 0, 0, 1, 1);
@@ -289,6 +330,7 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
DebuggerCore *dc = debuggerCore();
group.insert(dc->action(GdbStartupCommands), textEditStartupCommands);
+ group.insert(dc->action(GdbPostAttachCommands), textEditPostAttachCommands);
group.insert(dc->action(LoadGdbInit), checkBoxLoadGdbInit);
group.insert(dc->action(AutoEnrichParameters), checkBoxAutoEnrichParameters);
group.insert(dc->action(UseDynamicType), checkBoxUseDynamicType);
@@ -300,6 +342,8 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
group.insert(dc->action(BreakOnAbort), checkBoxBreakOnAbort);
group.insert(dc->action(GdbWatchdogTimeout), spinBoxGdbWatchdogTimeout);
group.insert(dc->action(AttemptQuickStart), checkBoxAttemptQuickStart);
+ group.insert(dc->action(MultiInferior), checkBoxMultiInferior);
+ group.insert(dc->action(IntelFlavor), checkBoxIntelFlavor);
group.insert(dc->action(UseMessageBoxForSignals), checkBoxUseMessageBoxForSignals);
group.insert(dc->action(SkipKnownFrames), checkBoxSkipKnownFrames);
@@ -324,6 +368,7 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
<< sep << checkBoxUseMessageBoxForSignals->text()
<< sep << checkBoxAdjustBreakpointLocations->text()
<< sep << checkBoxAttemptQuickStart->text()
+ << sep << checkBoxMultiInferior->text()
// << sep << groupBoxPluginDebugging->title()
// << sep << radioButtonAllPluginBreakpoints->text()
// << sep << radioButtonSelectedPluginBreakpoints->text()
@@ -335,9 +380,9 @@ GdbOptionsPageWidget::GdbOptionsPageWidget(QWidget *parent)
GdbOptionsPage::GdbOptionsPage()
{
- setId(QLatin1String("M.Gdb"));
+ setId("M.Gdb");
setDisplayName(tr("GDB"));
- setCategory(QLatin1String(Constants::DEBUGGER_SETTINGS_CATEGORY));
+ setCategory(Constants::DEBUGGER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Debugger", Constants::DEBUGGER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::DEBUGGER_COMMON_SETTINGS_CATEGORY_ICON));
}
diff --git a/src/plugins/debugger/gdb/localplaingdbadapter.cpp b/src/plugins/debugger/gdb/localplaingdbadapter.cpp
index 5d5ce71407..366b20860a 100644
--- a/src/plugins/debugger/gdb/localplaingdbadapter.cpp
+++ b/src/plugins/debugger/gdb/localplaingdbadapter.cpp
@@ -37,6 +37,7 @@
#include <projectexplorer/abi.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
@@ -61,11 +62,8 @@ GdbLocalPlainEngine::GdbLocalPlainEngine(const DebuggerStartParameters &startPar
GdbEngine::DumperHandling GdbLocalPlainEngine::dumperHandling() const
{
// LD_PRELOAD fails for System-Qt on Mac.
-#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
- return DumperLoadedByGdb;
-#else
- return DumperLoadedByGdbPreload;
-#endif
+ return Utils::HostOsInfo::isWindowsHost() || Utils::HostOsInfo::isMacHost()
+ ? DumperLoadedByGdb : DumperLoadedByGdbPreload;
}
void GdbLocalPlainEngine::setupEngine()
diff --git a/src/plugins/debugger/gdb/pythongdbengine.cpp b/src/plugins/debugger/gdb/pythongdbengine.cpp
index 623c0318da..9b8ed82ea4 100644
--- a/src/plugins/debugger/gdb/pythongdbengine.cpp
+++ b/src/plugins/debugger/gdb/pythongdbengine.cpp
@@ -28,7 +28,8 @@
****************************************************************************/
#include "gdbengine.h"
-#include "gdbmi.h"
+
+#include "debuggerprotocol.h"
#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerstringutils.h"
diff --git a/src/plugins/debugger/gdb/remotegdbserveradapter.cpp b/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
index f9a583003f..733e7b5a9e 100644
--- a/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
+++ b/src/plugins/debugger/gdb/remotegdbserveradapter.cpp
@@ -30,15 +30,16 @@
#include "remotegdbserveradapter.h"
#include "debuggeractions.h"
-#include "debuggerstartparameters.h"
#include "debuggercore.h"
+#include "debuggerprotocol.h"
+#include "debuggerstartparameters.h"
#include "debuggerstringutils.h"
-#include "gdbengine.h"
-#include "gdbmi.h"
-#include <utils/qtcassert.h>
-#include <utils/fancymainwindow.h>
#include <projectexplorer/abi.h>
+#include <utils/fancymainwindow.h>
+#include <utils/hostosinfo.h>
+#include <utils/qtcassert.h>
+#include <utils/qtcprocess.h>
#include <QFileInfo>
#include <QMessageBox>
@@ -84,7 +85,14 @@ void GdbRemoteServerEngine::setupEngine()
QTC_ASSERT(state() == EngineSetupRequested, qDebug() << state());
showMessage(_("TRYING TO START ADAPTER"));
if (!startParameters().serverStartScript.isEmpty()) {
- m_uploadProc.start(_("/bin/sh ") + startParameters().serverStartScript);
+
+ // Provide script information about the environment
+ QString arglist;
+ Utils::QtcProcess::addArg(&arglist, startParameters().serverStartScript);
+ Utils::QtcProcess::addArg(&arglist, startParameters().executable);
+ Utils::QtcProcess::addArg(&arglist, startParameters().remoteChannel);
+
+ m_uploadProc.start(_("/bin/sh ") + arglist);
m_uploadProc.waitForStarted();
}
if (startParameters().remoteSetupNeeded)
@@ -156,11 +164,6 @@ void GdbRemoteServerEngine::setupInferior()
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
const DebuggerStartParameters &sp = startParameters();
-#ifdef Q_OS_WIN
- #define PATHSEP ";"
-#else
- #define PATHSEP ":"
-#endif
QString executableFileName;
if (!sp.executable.isEmpty()) {
QFileInfo fi(sp.executable);
@@ -178,7 +181,8 @@ void GdbRemoteServerEngine::setupInferior()
// if (!remoteArch.isEmpty())
// postCommand("set architecture " + remoteArch);
- const QString solibSearchPath = sp.solibSearchPath.join(QLatin1String(PATHSEP));
+ const QString solibSearchPath
+ = sp.solibSearchPath.join(QString(Utils::HostOsInfo::pathListSeparator()));
if (!solibSearchPath.isEmpty())
postCommand("set solib-search-path " + solibSearchPath.toLocal8Bit());
@@ -285,6 +289,11 @@ void GdbRemoteServerEngine::handleTargetRemote(const GdbResponse &record)
// gdb server will stop the remote application itself.
showMessage(_("INFERIOR STARTED"));
showMessage(msgAttachedToStoppedInferior(), StatusBar);
+ QString postAttachCommands = debuggerCore()->stringSetting(GdbPostAttachCommands);
+ if (!postAttachCommands.isEmpty()) {
+ foreach (const QString &cmd, postAttachCommands.split(QLatin1Char('\n')))
+ postCommand(cmd.toLatin1());
+ }
handleInferiorPrepared();
} else {
// 16^error,msg="hd:5555: Connection timed out."
@@ -304,11 +313,10 @@ void GdbRemoteServerEngine::handleTargetQnx(const GdbResponse &response)
showMessage(msgAttachedToStoppedInferior(), StatusBar);
const qint64 pid = isMasterEngine() ? startParameters().attachPID : masterEngine()->startParameters().attachPID;
- if (pid > -1) {
+ if (pid > -1)
postCommand("attach " + QByteArray::number(pid), CB(handleAttach));
- } else {
+ else
handleInferiorPrepared();
- }
} else {
// 16^error,msg="hd:5555: Connection timed out."
QString msg = msgConnectRemoteServerFailed(
diff --git a/src/plugins/debugger/gdb/termgdbadapter.cpp b/src/plugins/debugger/gdb/termgdbadapter.cpp
index 8ede54051a..d0f19cd2a6 100644
--- a/src/plugins/debugger/gdb/termgdbadapter.cpp
+++ b/src/plugins/debugger/gdb/termgdbadapter.cpp
@@ -29,14 +29,14 @@
#include "termgdbadapter.h"
+#include "debuggercore.h"
+#include "debuggerprotocol.h"
#include "debuggerstartparameters.h"
-#include "gdbmi.h"
-#include "gdbengine.h"
-#include "procinterrupt.h"
#include "debuggerstringutils.h"
-#include "debuggercore.h"
+#include "procinterrupt.h"
#include "shared/hostutils.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <coreplugin/icore.h>
@@ -60,11 +60,10 @@ GdbTermEngine::GdbTermEngine(const DebuggerStartParameters &startParameters)
{
#ifdef Q_OS_WIN
// Windows up to xp needs a workaround for attaching to freshly started processes. see proc_stub_win
- if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA) {
+ if (QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA)
m_stubProc.setMode(Utils::ConsoleProcess::Suspend);
- } else {
+ else
m_stubProc.setMode(Utils::ConsoleProcess::Debug);
- }
#else
m_stubProc.setMode(Utils::ConsoleProcess::Debug);
m_stubProc.setSettings(Core::ICore::settings());
@@ -79,11 +78,9 @@ GdbTermEngine::~GdbTermEngine()
GdbEngine::DumperHandling GdbTermEngine::dumperHandling() const
{
// LD_PRELOAD fails for System-Qt on Mac.
-#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
- return DumperLoadedByGdb;
-#else
- return DumperLoadedByAdapter; // Handles loading itself via LD_PRELOAD
-#endif
+ return Utils::HostOsInfo::isWindowsHost() || Utils::HostOsInfo::isMacHost()
+ ? DumperLoadedByGdb
+ : DumperLoadedByAdapter; // Handles loading itself via LD_PRELOAD
}
void GdbTermEngine::setupEngine()
@@ -106,7 +103,7 @@ void GdbTermEngine::setupEngine()
connect(&m_stubProc, SIGNAL(processError(QString)), SLOT(stubError(QString)));
connect(&m_stubProc, SIGNAL(processStarted()), SLOT(stubStarted()));
- connect(&m_stubProc, SIGNAL(wrapperStopped()), SLOT(stubExited()));
+ connect(&m_stubProc, SIGNAL(stubStopped()), SLOT(stubExited()));
// FIXME: Starting the stub implies starting the inferior. This is
// fairly unclean as far as the state machine and error reporting go.
@@ -146,25 +143,29 @@ void GdbTermEngine::setupInferior()
void GdbTermEngine::handleStubAttached(const GdbResponse &response)
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
-#ifdef Q_OS_WIN
- QString errorMessage;
-#endif // Q_OS_WIN
+
switch (response.resultClass) {
case GdbResultDone:
case GdbResultRunning:
-#ifdef Q_OS_WIN
- // Resume thread that was suspended by console stub process (see stub code).
- if (winResumeThread(m_stubProc.applicationMainThreadID(), &errorMessage)) {
- showMessage(QString::fromLatin1("Inferior attached, thread %1 resumed").
- arg(m_stubProc.applicationMainThreadID()), LogMisc);
+ if (startParameters().toolChainAbi.os() != ProjectExplorer::Abi::WindowsOS) {
+ showMessage(_("INFERIOR ATTACHED"));
} else {
- showMessage(QString::fromLatin1("Inferior attached, unable to resume thread %1: %2").
- arg(m_stubProc.applicationMainThreadID()).arg(errorMessage),
- LogWarning);
- }
+ QString errorMessage;
+ // Resume thread that was suspended by console stub process (see stub code).
+#ifdef Q_OS_WIN
+ const qint64 mainThreadId = m_stubProc.applicationMainThreadID();
#else
- showMessage(_("INFERIOR ATTACHED"));
-#endif // Q_OS_WIN
+ const qint64 mainThreadId = -1;
+#endif
+ if (winResumeThread(mainThreadId, &errorMessage)) {
+ showMessage(QString::fromLatin1("Inferior attached, thread %1 resumed").
+ arg(mainThreadId), LogMisc);
+ } else {
+ showMessage(QString::fromLatin1("Inferior attached, unable to resume thread %1: %2").
+ arg(mainThreadId).arg(errorMessage),
+ LogWarning);
+ }
+ }
handleInferiorPrepared();
break;
case GdbResultError:
diff --git a/src/plugins/debugger/imageviewer.cpp b/src/plugins/debugger/imageviewer.cpp
new file mode 100644
index 0000000000..0f898e54ef
--- /dev/null
+++ b/src/plugins/debugger/imageviewer.cpp
@@ -0,0 +1,170 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "imageviewer.h"
+#include "debuggerinternalconstants.h"
+
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
+
+#include <QLabel>
+#include <QVBoxLayout>
+#include <QImage>
+#include <QPixmap>
+#include <QPoint>
+#include <QMouseEvent>
+#include <QScrollArea>
+#include <QMenu>
+#include <QAction>
+#include <QKeySequence>
+#include <QClipboard>
+#include <QApplication>
+#include <QPainter>
+#include <QDir>
+#include <QTemporaryFile>
+#include <QVariant>
+
+// Widget showing the image in a 1-pixel frame with context menu.
+class ImageWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit ImageWidget(QWidget *parent = 0) : QWidget(parent) {}
+
+ void setImage(const QImage &image);
+ const QImage &image() const { return m_image; }
+
+signals:
+ void clicked(const QString &message);
+
+protected:
+ void paintEvent(QPaintEvent *);
+ void mousePressEvent(QMouseEvent *ev);
+
+private:
+ QImage m_image;
+};
+
+void ImageWidget::setImage(const QImage &image)
+{
+ setFixedSize(image.size() + QSize(2, 2));
+ m_image = image;
+}
+
+void ImageWidget::mousePressEvent(QMouseEvent *ev)
+{
+ const QPoint imagePos = ev->pos() - QPoint(1, 1);
+ if (m_image.isNull() || imagePos.x() < 0 || imagePos.y() < 0 || imagePos.x() >= m_image.width() || imagePos.y() >= m_image.height()) {
+ emit clicked(QString());
+ } else {
+ const QRgb color = m_image.pixel(imagePos);
+ const QString message =
+ ImageViewer::tr("Color at %1,%2: red: %3 green: %4 blue: %5 alpha: %6").
+ arg(imagePos.x()).arg(imagePos.y()).
+ arg(qRed(color)).arg(qGreen(color)).arg(qBlue(color)).arg(qAlpha(color));
+ emit clicked(message);
+ }
+}
+
+void ImageWidget::paintEvent(QPaintEvent *)
+{
+ if (m_image.isNull())
+ return;
+ QPainter painter(this);
+ QRect rect(QPoint(0, 0), m_image.size() + QSize(1, 1));
+ painter.drawRect(rect);
+ painter.drawImage(QPoint(1, 1), m_image);
+}
+
+ImageViewer::ImageViewer(QWidget *parent)
+ : QWidget(parent)
+ , m_scrollArea(new QScrollArea(this))
+ , m_imageWidget(new ImageWidget)
+ , m_infoLabel(new QLabel)
+{
+ QVBoxLayout *mainLayout = new QVBoxLayout(this);
+ mainLayout->addWidget(m_infoLabel);
+ mainLayout->addWidget(m_scrollArea);
+ m_scrollArea->setWidget(m_imageWidget);
+ connect(m_imageWidget, SIGNAL(clicked(QString)), this, SLOT(clicked(QString)));
+}
+
+void ImageViewer::setImage(const QImage &i)
+{
+ m_imageWidget->setImage(i);
+ m_info = tr("Size: %1x%2, %3 byte, format: %4, depth: %5")
+ .arg(i.width()).arg(i.height()).arg(i.byteCount()).arg(i.format()).arg(i.depth());
+ clicked(QString());
+}
+
+void ImageViewer::clicked(const QString &message)
+{
+ const QString text = m_info + QLatin1Char('\n')
+ + (message.isEmpty() ? tr("<Click to display color>") : message);
+ m_infoLabel->setText(text);
+}
+
+// Open Qt Creator's image viewer
+static void openImageViewer(const QImage &image)
+{
+ QString fileName = QDir::tempPath();
+ if (!fileName.endsWith(QLatin1Char('/')))
+ fileName += QLatin1Char('/');
+ fileName += QLatin1String("qtcreatorXXXXXX.png");
+ {
+ QTemporaryFile temporaryFile(fileName);
+ temporaryFile.setAutoRemove(false);
+ image.save(&temporaryFile);
+ fileName = temporaryFile.fileName();
+ temporaryFile.close();
+ }
+ if (Core::IEditor *e = Core::EditorManager::instance()->openEditor(fileName))
+ e->setProperty(Debugger::Constants::OPENED_BY_DEBUGGER, QVariant(true));
+}
+
+void ImageViewer::contextMenuEvent(QContextMenuEvent *ev)
+{
+ // Offer copy and open in Creator's image viewer.
+ const QImage &image = m_imageWidget->image();
+ const bool hasImage = !image.isNull();
+ QMenu menu;
+ QAction *copyAction = menu.addAction(tr("Copy Image"));
+ copyAction->setShortcut(QKeySequence::Copy);
+ QAction *imageViewerAction = menu.addAction(tr("Open Image Viewer"));
+ copyAction->setEnabled(hasImage);
+ imageViewerAction->setEnabled(hasImage);
+ QAction *action = menu.exec(ev->globalPos());
+ if (action == copyAction) {
+ QApplication::clipboard()->setImage(image);
+ } else if (action == imageViewerAction) {
+ openImageViewer(image);
+ }
+}
+
+#include "imageviewer.moc"
diff --git a/src/plugins/qmldesigner/components/integration/integrationcore.h b/src/plugins/debugger/imageviewer.h
index ced905dd6d..77049d2aae 100644
--- a/src/plugins/qmldesigner/components/integration/integrationcore.h
+++ b/src/plugins/debugger/imageviewer.h
@@ -27,38 +27,40 @@
**
****************************************************************************/
-#ifndef QMLDESIGNERCORE_H
-#define QMLDESIGNERCORE_H
+#ifndef IMAGEVIEWER_H
+#define IMAGEVIEWER_H
-#include <QObject>
+#include <QWidget>
QT_BEGIN_NAMESPACE
-class QWidget;
-class QDialog;
+class QScrollArea;
+class QLabel;
+class QImage;
+class QContextMenuEvent;
QT_END_NAMESPACE
-namespace QmlDesigner {
+class ImageWidget;
-class ItemLibraryWidget;
-class FormWindowManager;
-class PluginManager;
-class CorePrivate;
-
-class IntegrationCore
+// Image viewer showing images in scroll area, displays color on click.
+class ImageViewer : public QWidget
{
- Q_DISABLE_COPY(IntegrationCore)
+ Q_OBJECT
public:
- IntegrationCore();
- ~IntegrationCore();
+ explicit ImageViewer(QWidget *parent = 0);
+
+ void setImage(const QImage &);
- PluginManager *pluginManager() const;
+protected:
+ void contextMenuEvent(QContextMenuEvent *);
- static IntegrationCore *instance();
+private slots:
+ void clicked(const QString &);
private:
- CorePrivate *d;
+ QScrollArea *m_scrollArea;
+ ImageWidget *m_imageWidget;
+ QLabel *m_infoLabel;
+ QString m_info;
};
-} // namspace QmlDesigner
-
-#endif // QMLDESIGNERCORE_H
+#endif // IMAGEVIEWER_H
diff --git a/src/plugins/debugger/lldb/guest/lldbengineguest.cpp b/src/plugins/debugger/lldb/guest/lldbengineguest.cpp
index 310b3cece5..312a6cb457 100644
--- a/src/plugins/debugger/lldb/guest/lldbengineguest.cpp
+++ b/src/plugins/debugger/lldb/guest/lldbengineguest.cpp
@@ -493,9 +493,8 @@ void LldbEngineGuest::selectThread(qint64 token)
qDebug() << "\t\tsymbol: " << sym.IsValid() << sym.GetName() << sym.GetMangledName();
qDebug() << "\t\tfunction:" << func.IsValid();
qDebug() << "\t\ttu: " << tu.IsValid();
- if (tu.IsValid()) {
+ if (tu.IsValid())
- }
qDebug() << "\t\tmodule: " << module.IsValid() << module.GetFileSpec().IsValid()
<< module.GetFileSpec().GetFilename();
qDebug() << "\t\tblock: " << block.IsValid() << block.GetInlinedName();
@@ -676,9 +675,8 @@ void LldbEngineGuest::lldbEvent(lldb::SBEvent *ev)
case 1:
switch (m_process->GetState()) {
case lldb::eStateRunning: // 5
- if (!m_running) {
+ if (!m_running)
m_running = true;
- }
notifyInferiorPid(m_process->GetProcessID());
switch (state()) {
case EngineRunRequested:
@@ -696,9 +694,8 @@ void LldbEngineGuest::lldbEvent(lldb::SBEvent *ev)
}
break;
case lldb::eStateExited: // 9
- if (m_running) {
+ if (m_running)
m_running = false;
- }
switch (state()) {
case InferiorShutdownRequested:
notifyInferiorShutdownOk();
@@ -716,9 +713,8 @@ void LldbEngineGuest::lldbEvent(lldb::SBEvent *ev)
}
break;
case lldb::eStateStopped: // 4
- if (m_running) {
+ if (m_running)
m_running = false;
- }
switch (state()) {
case InferiorShutdownRequested:
notifyInferiorShutdownOk();
@@ -735,9 +731,8 @@ void LldbEngineGuest::lldbEvent(lldb::SBEvent *ev)
}
break;
case lldb::eStateCrashed: // 7
- if (m_running) {
+ if (m_running)
m_running = false;
- }
switch (state()) {
case InferiorShutdownRequested:
notifyInferiorShutdownOk();
diff --git a/src/plugins/debugger/lldb/ipcenginehost.cpp b/src/plugins/debugger/lldb/ipcenginehost.cpp
index 4507980d25..0562939916 100644
--- a/src/plugins/debugger/lldb/ipcenginehost.cpp
+++ b/src/plugins/debugger/lldb/ipcenginehost.cpp
@@ -208,7 +208,6 @@ void IPCEngineHost::executeJumpToLine(const ContextData &data)
rpcCall(ExecuteJumpToLine, p);
}
-
void IPCEngineHost::activateFrame(int index)
{
resetLocation();
@@ -221,16 +220,15 @@ void IPCEngineHost::activateFrame(int index)
rpcCall(ActivateFrame, p);
}
-void IPCEngineHost::selectThread(int index)
+void IPCEngineHost::selectThread(ThreadId id)
{
resetLocation();
- Threads threads = threadsHandler()->threads();
- QTC_ASSERT(index < threads.size(), return);
+ QTC_ASSERT(id.isValid(), return);
QByteArray p;
{
QDataStream s(&p, QIODevice::WriteOnly);
SET_NATIVE_BYTE_ORDER(s);
- s << quint64(threads.at(index).id);
+ s << id.raw();
}
rpcCall(SelectThread, p);
}
@@ -432,7 +430,7 @@ void IPCEngineHost::rpcCallback(quint64 f, QByteArray payload)
gotoLocation(Location(sh->currentFrame(), true));
else if (!m_sourceAgents.contains(sh->currentFrame().file))
fetchFrameSource(token);
- foreach(SourceAgent *agent, m_sourceAgents.values())
+ foreach (SourceAgent *agent, m_sourceAgents.values())
agent->updateLocationMarker();
}
break;
@@ -442,7 +440,7 @@ void IPCEngineHost::rpcCallback(quint64 f, QByteArray payload)
SET_NATIVE_BYTE_ORDER(s);
quint64 token;
s >> token;
- threadsHandler()->setCurrentThreadId(token);
+ threadsHandler()->setCurrentThread(ThreadId(token));
}
break;
case IPCEngineGuest::ListFrames:
diff --git a/src/plugins/debugger/lldb/ipcenginehost.h b/src/plugins/debugger/lldb/ipcenginehost.h
index 67009d7068..8364d50657 100644
--- a/src/plugins/debugger/lldb/ipcenginehost.h
+++ b/src/plugins/debugger/lldb/ipcenginehost.h
@@ -104,7 +104,7 @@ public:
void executeRunToFunction(const QString &functionName);
void executeJumpToLine(const ContextData &data);
void activateFrame(int index);
- void selectThread(int index);
+ void selectThread(ThreadId index);
void fetchDisassembler(DisassemblerAgent *);
bool acceptsBreakpoint(BreakpointModelId) const { return true; } // FIXME
void insertBreakpoint(BreakpointModelId id);
diff --git a/src/plugins/debugger/lldb/lldbenginehost.cpp b/src/plugins/debugger/lldb/lldbenginehost.cpp
index d8a0ff1123..2bac195eb2 100644
--- a/src/plugins/debugger/lldb/lldbenginehost.cpp
+++ b/src/plugins/debugger/lldb/lldbenginehost.cpp
@@ -97,9 +97,8 @@ qint64 SshIODevice::readData (char * data, qint64 maxSize)
return 0;
qint64 size = maxSize;
while (size > 0) {
- if (!buckets.size()) {
+ if (!buckets.size())
return maxSize - size;
- }
QByteArray &bucket = buckets.head();
if ((size + buckethead) >= bucket.size()) {
int d = bucket.size() - buckethead;
@@ -160,7 +159,7 @@ LldbEngineHost::LldbEngineHost(const DebuggerStartParameters &startParameters)
QString a = Core::ICore::resourcePath() + QLatin1String("/qtcreator-lldb");
- if(getenv("QTC_LLDB_GUEST") != 0)
+ if (getenv("QTC_LLDB_GUEST") != 0)
a = QString::fromLocal8Bit(getenv("QTC_LLDB_GUEST"));
showStatusMessage(QString(QLatin1String("starting %1")).arg(a));
diff --git a/src/plugins/debugger/lldb/lldboptionspage.cpp b/src/plugins/debugger/lldb/lldboptionspage.cpp
index eaba80fd40..9fe0cb2a30 100644
--- a/src/plugins/debugger/lldb/lldboptionspage.cpp
+++ b/src/plugins/debugger/lldb/lldboptionspage.cpp
@@ -72,7 +72,7 @@ LldbOptionsPage::LldbOptionsPage()
// m_options->fromSettings(Core::ICore::settings());
setId(QLatin1String("F.Lldb"));
setDisplayName(tr("LLDB"));
- setCategory(QLatin1String(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY));
+ setCategory(Debugger::Constants::DEBUGGER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Debugger", Constants::DEBUGGER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QIcon(QLatin1String(Constants::DEBUGGER_COMMON_SETTINGS_CATEGORY_ICON)));
}
diff --git a/src/plugins/debugger/localsandexpressionswindow.cpp b/src/plugins/debugger/localsandexpressionswindow.cpp
index ab597bfef5..a9b96c265e 100644
--- a/src/plugins/debugger/localsandexpressionswindow.cpp
+++ b/src/plugins/debugger/localsandexpressionswindow.cpp
@@ -35,6 +35,9 @@
#include <QSplitter>
#include <QStackedWidget>
+const int LOCAL_WIDGET_INDEX = 0;
+const int INSPECTOR_WIDGET_INDEX = 1;
+
namespace Debugger {
namespace Internal {
@@ -79,7 +82,13 @@ void LocalsAndExpressionsWindow::setShowLocals(bool showLocals)
void LocalsAndExpressionsWindow::showLocals()
{
- m_localsAndInspector->setCurrentIndex(m_showLocals ? 0 : 1);
+ m_localsAndInspector->setCurrentIndex(m_showLocals ? LOCAL_WIDGET_INDEX
+ : INSPECTOR_WIDGET_INDEX);
+}
+
+QWidget *LocalsAndExpressionsWindow::inspectorWidget() const
+{
+ return m_localsAndInspector->widget(INSPECTOR_WIDGET_INDEX);
}
} // namespace Internal
diff --git a/src/plugins/debugger/localsandexpressionswindow.h b/src/plugins/debugger/localsandexpressionswindow.h
index 988760f629..32b152205a 100644
--- a/src/plugins/debugger/localsandexpressionswindow.h
+++ b/src/plugins/debugger/localsandexpressionswindow.h
@@ -50,6 +50,7 @@ public:
QWidget *returnWidget, QWidget *watchers, QWidget *parent = 0);
void setShowLocals(bool showLocals);
+ QWidget *inspectorWidget() const;
private slots:
void showLocals();
diff --git a/src/plugins/debugger/logwindow.cpp b/src/plugins/debugger/logwindow.cpp
index 112662a47b..237a7af6cb 100644
--- a/src/plugins/debugger/logwindow.cpp
+++ b/src/plugins/debugger/logwindow.cpp
@@ -31,6 +31,7 @@
#include "debuggeractions.h"
#include "debuggercore.h"
+#include "debuggerengine.h"
#include <QDebug>
#include <QFile>
@@ -161,7 +162,14 @@ public:
m_saveContentsAction = new QAction(this);
m_saveContentsAction->setText(tr("Save Contents"));
m_saveContentsAction->setEnabled(true);
- connect(m_saveContentsAction, SIGNAL(triggered()), this, SLOT(saveContents()));
+ connect(m_saveContentsAction, SIGNAL(triggered()),
+ this, SLOT(saveContents()));
+
+ m_reloadDebuggingHelpersAction = new QAction(this);
+ m_reloadDebuggingHelpersAction->setText(tr("Reload Debugging Helpers"));
+ m_reloadDebuggingHelpersAction->setEnabled(true);
+ connect(m_reloadDebuggingHelpersAction, SIGNAL(triggered()),
+ this, SLOT(reloadDebuggingHelpers()));
}
void contextMenuEvent(QContextMenuEvent *ev)
@@ -171,6 +179,7 @@ public:
menu->addAction(m_saveContentsAction); // X11 clipboard is unreliable for long texts
menu->addAction(debuggerCore()->action(LogTimeStamps));
menu->addAction(debuggerCore()->action(VerboseLog));
+ menu->addAction(m_reloadDebuggingHelpersAction);
menu->addSeparator();
menu->addAction(debuggerCore()->action(SettingsDialog));
menu->exec(ev->globalPos());
@@ -192,10 +201,12 @@ public:
private slots:
void saveContents();
+ void reloadDebuggingHelpers();
private:
QAction *m_clearContentsAction;
QAction *m_saveContentsAction;
+ QAction *m_reloadDebuggingHelpersAction;
};
void DebuggerPane::saveContents()
@@ -203,6 +214,11 @@ void DebuggerPane::saveContents()
LogWindow::writeLogContents(this, this);
}
+void DebuggerPane::reloadDebuggingHelpers()
+{
+ debuggerCore()->currentEngine()->reloadDebuggingHelpers();
+}
+
/////////////////////////////////////////////////////////////////////
//
// InputPane
diff --git a/src/plugins/debugger/memoryagent.cpp b/src/plugins/debugger/memoryagent.cpp
index e57d265e80..43da6fdaf9 100644
--- a/src/plugins/debugger/memoryagent.cpp
+++ b/src/plugins/debugger/memoryagent.cpp
@@ -141,12 +141,6 @@ void MemoryAgent::connectBinEditorWidget(QWidget *w)
SIGNAL(newRangeRequested(Core::IEditor*,quint64)),
SLOT(provideNewRange(Core::IEditor*,quint64)));
connect(w,
- SIGNAL(startOfFileRequested(Core::IEditor*)),
- SLOT(handleStartOfFileRequested(Core::IEditor*)));
- connect(w,
- SIGNAL(endOfFileRequested(Core::IEditor*)),
- SLOT(handleEndOfFileRequested(Core::IEditor*)));
- connect(w,
SIGNAL(dataChanged(Core::IEditor*,quint64,QByteArray)),
SLOT(handleDataChanged(Core::IEditor*,quint64,QByteArray)));
connect(w,
@@ -250,23 +244,6 @@ void MemoryAgent::provideNewRange(IEditor *, quint64 address)
MemoryView::setBinEditorRange(w, address, DataRange, BinBlockSize);
}
-// Since we are not dealing with files, we take these signals to mean
-// "move to start/end of range". This seems to make more sense than
-// jumping to the start or end of the address space, respectively.
-void MemoryAgent::handleStartOfFileRequested(IEditor *)
-{
- QWidget *w = qobject_cast<QWidget *>(sender());
- QTC_ASSERT(w, return);
- MemoryView::binEditorSetCursorPosition(w, 0);
-}
-
-void MemoryAgent::handleEndOfFileRequested(IEditor *)
-{
- QWidget *w = qobject_cast<QWidget *>(sender());
- QTC_ASSERT(w, return);
- MemoryView::binEditorSetCursorPosition(w, DataRange - 1);
-}
-
void MemoryAgent::handleDataChanged(IEditor *,
quint64 addr, const QByteArray &data)
{
diff --git a/src/plugins/debugger/memoryagent.h b/src/plugins/debugger/memoryagent.h
index 17b290fe7f..c54ff94932 100644
--- a/src/plugins/debugger/memoryagent.h
+++ b/src/plugins/debugger/memoryagent.h
@@ -99,8 +99,6 @@ public slots:
private slots:
void fetchLazyData(Core::IEditor *, quint64 block);
void provideNewRange(Core::IEditor *editor, quint64 address);
- void handleStartOfFileRequested(Core::IEditor *editor);
- void handleEndOfFileRequested(Core::IEditor *editor);
void handleDataChanged(Core::IEditor *editor, quint64 address,
const QByteArray &data);
void handleWatchpointRequest(quint64 address, uint size);
diff --git a/src/plugins/debugger/moduleshandler.cpp b/src/plugins/debugger/moduleshandler.cpp
index 7ac5e029ce..104b069f2d 100644
--- a/src/plugins/debugger/moduleshandler.cpp
+++ b/src/plugins/debugger/moduleshandler.cpp
@@ -194,15 +194,17 @@ QVariant ModulesModel::data(const QModelIndex &index, int role) const
void ModulesModel::setModules(const Modules &m)
{
+ beginResetModel();
m_modules = m;
- reset();
+ endResetModel();
}
void ModulesModel::clearModel()
{
if (!m_modules.isEmpty()) {
+ beginResetModel();
m_modules.clear();
- reset();
+ endResetModel();
}
}
diff --git a/src/plugins/debugger/moduleshandler.h b/src/plugins/debugger/moduleshandler.h
index 10e15af8ea..c39d4f58da 100644
--- a/src/plugins/debugger/moduleshandler.h
+++ b/src/plugins/debugger/moduleshandler.h
@@ -68,6 +68,24 @@ typedef QVector<Symbol> Symbols;
//////////////////////////////////////////////////////////////////
//
+// Section
+//
+//////////////////////////////////////////////////////////////////
+
+class Section
+{
+public:
+ QString from;
+ QString to;
+ QString address;
+ QString name;
+ QString flags;
+};
+
+typedef QVector<Section> Sections;
+
+//////////////////////////////////////////////////////////////////
+//
// Module
//
//////////////////////////////////////////////////////////////////
diff --git a/src/plugins/debugger/moduleswindow.cpp b/src/plugins/debugger/moduleswindow.cpp
index bf0aa3fdf5..dbe8b7f757 100644
--- a/src/plugins/debugger/moduleswindow.cpp
+++ b/src/plugins/debugger/moduleswindow.cpp
@@ -34,6 +34,7 @@
#include "debuggercore.h"
#include "debuggerengine.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
@@ -111,6 +112,7 @@ void ModulesTreeView::contextMenuEvent(QContextMenuEvent *ev)
QAction *actLoadSymbolsForModule = 0;
QAction *actEditFile = 0;
QAction *actShowModuleSymbols = 0;
+ QAction *actShowModuleSections = 0;
QAction *actShowDependencies = 0; // Show dependencies by running 'depends.exe'
if (name.isEmpty()) {
actLoadSymbolsForModule = new QAction(tr("Load Symbols for Module"), &menu);
@@ -119,6 +121,8 @@ void ModulesTreeView::contextMenuEvent(QContextMenuEvent *ev)
actEditFile->setEnabled(false);
actShowModuleSymbols = new QAction(tr("Show Symbols"), &menu);
actShowModuleSymbols->setEnabled(false);
+ actShowModuleSections = new QAction(tr("Show Sections"), &menu);
+ actShowModuleSections->setEnabled(false);
actShowDependencies = new QAction(tr("Show Dependencies"), &menu);
actShowDependencies->setEnabled(false);
} else {
@@ -130,12 +134,14 @@ void ModulesTreeView::contextMenuEvent(QContextMenuEvent *ev)
actShowModuleSymbols
= new QAction(tr("Show Symbols in File \"%1\"").arg(name), &menu);
actShowModuleSymbols->setEnabled(engine->hasCapability(ShowModuleSymbolsCapability));
+ actShowModuleSections
+ = new QAction(tr("Show Sections in File \"%1\"").arg(name), &menu);
+ actShowModuleSections->setEnabled(engine->hasCapability(ShowModuleSymbolsCapability));
actShowDependencies = new QAction(tr("Show Dependencies of \"%1\"").arg(name), &menu);
actShowDependencies->setEnabled(!fileName.isEmpty());
-#ifndef Q_OS_WIN
- // FIXME: Dependencies only available on Windows, when "depends" is installed.
- actShowDependencies->setEnabled(false);
-#endif
+ if (!Utils::HostOsInfo::isWindowsHost())
+ // FIXME: Dependencies only available on Windows, when "depends" is installed.
+ actShowDependencies->setEnabled(false);
}
menu.addAction(actUpdateModuleList);
@@ -146,6 +152,7 @@ void ModulesTreeView::contextMenuEvent(QContextMenuEvent *ev)
menu.addAction(actLoadSymbolsForModule);
menu.addAction(actEditFile);
menu.addAction(actShowModuleSymbols);
+ menu.addAction(actShowModuleSections);
addBaseContextActions(&menu);
QAction *act = menu.exec(ev->globalPos());
@@ -164,6 +171,8 @@ void ModulesTreeView::contextMenuEvent(QContextMenuEvent *ev)
engine->gotoLocation(fileName);
else if (act == actShowModuleSymbols)
engine->requestModuleSymbols(fileName);
+ else if (act == actShowModuleSections)
+ engine->requestModuleSections(fileName);
else if (actShowDependencies && act == actShowDependencies)
QProcess::startDetached(QLatin1String("depends"), QStringList(fileName));
else
diff --git a/src/plugins/debugger/namedemangler/namedemangler.cpp b/src/plugins/debugger/namedemangler/namedemangler.cpp
index cfcf06463c..4776cb255e 100644
--- a/src/plugins/debugger/namedemangler/namedemangler.cpp
+++ b/src/plugins/debugger/namedemangler/namedemangler.cpp
@@ -55,7 +55,7 @@ bool NameDemanglerPrivate::demangle(const QString &mangledName)
{
bool success;
try {
- m_parseState.m_mangledName = mangledName.toAscii();
+ m_parseState.m_mangledName = mangledName.toLatin1();
m_parseState.m_pos = 0;
m_demangledName.clear();
diff --git a/src/plugins/debugger/namedemangler/parsetreenodes.cpp b/src/plugins/debugger/namedemangler/parsetreenodes.cpp
index fa4cbb8a34..47568c1f96 100644
--- a/src/plugins/debugger/namedemangler/parsetreenodes.cpp
+++ b/src/plugins/debugger/namedemangler/parsetreenodes.cpp
@@ -230,7 +230,7 @@ BuiltinTypeNode::BuiltinTypeNode(const BuiltinTypeNode &other)
bool BuiltinTypeNode::mangledRepresentationStartsWith(char c)
{
- return strchr("vwbcahstijlmxynofgedzDu", c);
+ return std::strchr("vwbcahstijlmxynofgedzDu", c);
}
/*
@@ -2103,15 +2103,6 @@ template<int base> NonNegativeNumberNode<base>::NonNegativeNumberNode(const NonN
{
}
-template<int base> bool NonNegativeNumberNode<base>::mangledRepresentationStartsWith(char c)
-{
- // Base can only be 10 or 36.
- if (base == 10)
- return strchr("0123456789", c);
- else
- return strchr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", c);
-}
-
template<int base> void NonNegativeNumberNode<base>::parse()
{
QByteArray numberRepr;
diff --git a/src/plugins/debugger/namedemangler/parsetreenodes.h b/src/plugins/debugger/namedemangler/parsetreenodes.h
index f75b7abfc6..72897b2bcd 100644
--- a/src/plugins/debugger/namedemangler/parsetreenodes.h
+++ b/src/plugins/debugger/namedemangler/parsetreenodes.h
@@ -552,7 +552,10 @@ template<int base> class NonNegativeNumberNode : public ParseTreeNode
public:
typedef QSharedPointer<NonNegativeNumberNode<base> > Ptr;
NonNegativeNumberNode(GlobalParseState *parseState) : ParseTreeNode(parseState) {}
- static bool mangledRepresentationStartsWith(char c);
+ static bool mangledRepresentationStartsWith(char c) {
+ // Base can only be 10 or 36.
+ return (c >= '0' && c <= '9') || (base == 36 && c >= 'A' && c <= 'Z');
+ }
quint64 number() const { return m_number; }
QByteArray toByteArray() const;
diff --git a/src/plugins/debugger/pdb/pdbengine.cpp b/src/plugins/debugger/pdb/pdbengine.cpp
index 60681e66e6..18c2bc591f 100644
--- a/src/plugins/debugger/pdb/pdbengine.cpp
+++ b/src/plugins/debugger/pdb/pdbengine.cpp
@@ -29,11 +29,12 @@
#include "pdbengine.h"
-#include "debuggerstartparameters.h"
#include "debuggeractions.h"
#include "debuggercore.h"
#include "debuggerdialogs.h"
#include "debuggerplugin.h"
+#include "debuggerprotocol.h"
+#include "debuggerstartparameters.h"
#include "debuggerstringutils.h"
#include "debuggertooltipmanager.h"
@@ -41,11 +42,10 @@
#include "moduleshandler.h"
#include "registerhandler.h"
#include "stackhandler.h"
+#include "sourceutils.h"
#include "watchhandler.h"
#include "watchutils.h"
-#include "../gdb/gdbmi.h"
-
#include <utils/qtcassert.h>
#include <texteditor/itexteditor.h>
@@ -321,9 +321,9 @@ void PdbEngine::activateFrame(int frameIndex)
gotoLocation(handler->currentFrame());
}
-void PdbEngine::selectThread(int index)
+void PdbEngine::selectThread(ThreadId threadId)
{
- Q_UNUSED(index)
+ Q_UNUSED(threadId)
}
bool PdbEngine::acceptsBreakpoint(BreakpointModelId id) const
diff --git a/src/plugins/debugger/pdb/pdbengine.h b/src/plugins/debugger/pdb/pdbengine.h
index 1dfda1076a..356b38f7f3 100644
--- a/src/plugins/debugger/pdb/pdbengine.h
+++ b/src/plugins/debugger/pdb/pdbengine.h
@@ -86,7 +86,7 @@ private:
void executeJumpToLine(const ContextData &data);
void activateFrame(int index);
- void selectThread(int index);
+ void selectThread(ThreadId threadId);
bool acceptsBreakpoint(BreakpointModelId id) const;
void insertBreakpoint(BreakpointModelId id);
@@ -162,7 +162,7 @@ private:
QQueue<PdbCommand> m_commands;
- QByteArray m_inbuffer;
+ QByteArray m_inbuffer;
QString m_scriptFileName;
QProcess m_pdbProc;
QString m_pdb;
diff --git a/src/plugins/debugger/procinterrupt.cpp b/src/plugins/debugger/procinterrupt.cpp
index 8d8a7ab7ae..d67512498e 100644
--- a/src/plugins/debugger/procinterrupt.cpp
+++ b/src/plugins/debugger/procinterrupt.cpp
@@ -78,7 +78,7 @@ static BOOL isWow64Process(HANDLE hproc)
}
// Open the process and break into it
-bool Debugger::Internal::interruptProcess(int pID, int engineType, QString *errorMessage)
+bool Debugger::Internal::interruptProcess(int pID, int engineType, QString *errorMessage, const bool engineExecutableIs64Bit)
{
bool ok = false;
HANDLE inferior = NULL;
@@ -98,9 +98,10 @@ bool Debugger::Internal::interruptProcess(int pID, int engineType, QString *erro
// Qt-Creator compiled 64 bit
// Windows must be 64 bit
// CDB 64 bit: use DebugBreakProcess for 32 an 64 bit processes.
- // CDB 32 bit: untested
+ // TODO: CDB 32 bit: inferior 32 bit can not use DebugBreakProcess, we need a win32interrupt.exe
// GDB: not supported
const bool useDebugBreakApi= true;
+ Q_UNUSED(engineExecutableIs64Bit)
#else
// Qt-Creator compiled 32 bit:
@@ -115,8 +116,9 @@ bool Debugger::Internal::interruptProcess(int pID, int engineType, QString *erro
// works in theory for other WOW64 processes, the break appears
// as a WOW64 breakpoint, which CDB is configured to ignore since
// it also triggers on module loading.
- // CDB 32 bit: untested
- useDebugBreakApi = false;
+ // CDB 32 bit: 32 bit applications can not be interrupted using the win64interrupt.exe
+ // So we need to find out which bitness the currently used cdb has.
+ useDebugBreakApi = !engineExecutableIs64Bit;
} else {
// GDB: Use win64interrupt for native 64bit processes only (it fails
// for WOW64 processes.
@@ -165,7 +167,7 @@ bool Debugger::Internal::interruptProcess(int pID, int engineType, QString *erro
#include <string.h>
bool Debugger::Internal::interruptProcess(int pID, int /* engineType */,
- QString *errorMessage)
+ QString *errorMessage, const bool /*engineExecutableIs64Bit*/)
{
if (pID <= 0) {
*errorMessage = msgCannotInterrupt(pID, QString::fromLatin1("Invalid process id."));
diff --git a/src/plugins/debugger/procinterrupt.h b/src/plugins/debugger/procinterrupt.h
index 3617a63ebd..888d152419 100644
--- a/src/plugins/debugger/procinterrupt.h
+++ b/src/plugins/debugger/procinterrupt.h
@@ -35,7 +35,8 @@
namespace Debugger {
namespace Internal {
-bool interruptProcess(int pID, int engineType, QString *errorMessage);
+bool interruptProcess(int pID, int engineType, QString *errorMessage,
+ const bool engineExecutableIs64Bit = false);
} // Internal
} // GdbDebugger
diff --git a/src/plugins/debugger/qml/baseqmldebuggerclient.cpp b/src/plugins/debugger/qml/baseqmldebuggerclient.cpp
index a1f875d48c..17e1e96d02 100644
--- a/src/plugins/debugger/qml/baseqmldebuggerclient.cpp
+++ b/src/plugins/debugger/qml/baseqmldebuggerclient.cpp
@@ -65,11 +65,10 @@ void BaseQmlDebuggerClient::statusChanged(QmlDebug::ClientStatus status)
void BaseQmlDebuggerClient::sendMessage(const QByteArray &msg)
{
- if (status() == QmlDebug::Enabled) {
+ if (status() == QmlDebug::Enabled)
QmlDebugClient::sendMessage(msg);
- } else {
+ else
d->sendBuffer.append(msg);
- }
}
void BaseQmlDebuggerClient::flushSendBuffer()
diff --git a/src/plugins/debugger/qml/qmladapter.cpp b/src/plugins/debugger/qml/qmladapter.cpp
index d62fcfe786..792301370e 100644
--- a/src/plugins/debugger/qml/qmladapter.cpp
+++ b/src/plugins/debugger/qml/qmladapter.cpp
@@ -95,9 +95,8 @@ void QmlAdapter::closeConnection()
if (m_connectionTimer.isActive()) {
m_connectionTimer.stop();
} else {
- if (m_conn) {
+ if (m_conn)
m_conn->close();
- }
}
}
diff --git a/src/plugins/debugger/qml/qmlcppengine.cpp b/src/plugins/debugger/qml/qmlcppengine.cpp
index 7edd7e9bf2..d8e56ad190 100644
--- a/src/plugins/debugger/qml/qmlcppengine.cpp
+++ b/src/plugins/debugger/qml/qmlcppengine.cpp
@@ -33,7 +33,6 @@
#include "debuggerstartparameters.h"
#include "stackhandler.h"
#include "qmlengine.h"
-#include "qtmessageloghandler.h"
#include "watchdata.h"
#include "watchhandler.h"
@@ -42,6 +41,7 @@
#include <texteditor/itexteditor.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <cppeditor/cppeditorconstants.h>
+#include <qmljs/consolemanagerinterface.h>
#include <QTimer>
@@ -274,9 +274,9 @@ bool QmlCppEngine::acceptsBreakpoint(BreakpointModelId id) const
|| d->m_qmlEngine->acceptsBreakpoint(id);
}
-void QmlCppEngine::selectThread(int index)
+void QmlCppEngine::selectThread(ThreadId threadId)
{
- d->m_activeEngine->selectThread(index);
+ d->m_activeEngine->selectThread(threadId);
}
void QmlCppEngine::assignValueInDebugger(const WatchData *data,
@@ -408,11 +408,6 @@ void QmlCppEngine::executeDebuggerCommand(const QString &command, DebuggerLangua
d->m_cppEngine->executeDebuggerCommand(command, languages);
}
-bool QmlCppEngine::evaluateScriptExpression(const QString &expression)
-{
- return d->m_qmlEngine->evaluateScriptExpression(expression);
-}
-
/////////////////////////////////////////////////////////
void QmlCppEngine::setupEngine()
@@ -474,6 +469,9 @@ void QmlCppEngine::shutdownEngine()
{
EDEBUG("\nMASTER SHUTDOWN ENGINE");
d->m_cppEngine->shutdownSlaveEngine();
+ QmlJS::ConsoleManagerInterface *consoleManager = QmlJS::ConsoleManagerInterface::instance();
+ if (consoleManager)
+ consoleManager->setScriptEvaluator(0);
}
void QmlCppEngine::quitDebugger()
@@ -800,11 +798,6 @@ void QmlCppEngine::resetLocation()
DebuggerEngine::resetLocation();
}
-Internal::QtMessageLogHandler *QmlCppEngine::qtMessageLogHandler() const
-{
- return d->m_qmlEngine->qtMessageLogHandler();
-}
-
DebuggerEngine *QmlCppEngine::cppEngine() const
{
return d->m_cppEngine;
diff --git a/src/plugins/debugger/qml/qmlcppengine.h b/src/plugins/debugger/qml/qmlcppengine.h
index f35948bad5..21d4fffec9 100644
--- a/src/plugins/debugger/qml/qmlcppengine.h
+++ b/src/plugins/debugger/qml/qmlcppengine.h
@@ -78,7 +78,7 @@ public:
void attemptBreakpointSynchronization();
bool acceptsBreakpoint(BreakpointModelId id) const;
- void selectThread(int index);
+ void selectThread(ThreadId threadId);
void assignValueInDebugger(const WatchData *data,
const QString &expr, const QVariant &value);
@@ -93,8 +93,6 @@ public:
int timeout = -1) const;
void resetLocation();
- Internal::QtMessageLogHandler *qtMessageLogHandler() const;
-
void notifyInferiorIll();
protected:
@@ -113,7 +111,6 @@ protected:
void executeRunToFunction(const QString &functionName);
void executeJumpToLine(const ContextData &data);
void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
- bool evaluateScriptExpression(const QString &expression);
void setupEngine();
void setupInferior();
diff --git a/src/plugins/debugger/qml/qmlengine.cpp b/src/plugins/debugger/qml/qmlengine.cpp
index b34c1d53c9..20f3384be6 100644
--- a/src/plugins/debugger/qml/qmlengine.cpp
+++ b/src/plugins/debugger/qml/qmlengine.cpp
@@ -41,6 +41,8 @@
#include "debuggerrunner.h"
#include "debuggerstringutils.h"
#include "debuggertooltipmanager.h"
+#include "localsandexpressionswindow.h"
+#include "watchwindow.h"
#include "breakhandler.h"
#include "moduleshandler.h"
@@ -49,13 +51,13 @@
#include "watchhandler.h"
#include "sourcefileshandler.h"
#include "watchutils.h"
-#include "qtmessageloghandler.h"
-#include <extensionsystem/pluginmanager.h>
#include <qmldebug/baseenginedebugclient.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
+#include <qmljs/consolemanagerinterface.h>
+#include <qmljs/consoleitem.h>
#include <utils/environment.h>
#include <utils/qtcassert.h>
@@ -82,6 +84,8 @@
#include <QTcpSocket>
#include <QHostAddress>
+#include <QDockWidget>
+
#define DEBUG_QML 1
#if DEBUG_QML
# define SDEBUG(s) qDebug() << s
@@ -259,6 +263,11 @@ public:
quint32 *column;
};
+QmlJS::ConsoleManagerInterface *qmlConsoleManager()
+{
+ return QmlJS::ConsoleManagerInterface::instance();
+}
+
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
@@ -273,7 +282,6 @@ QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters, DebuggerEng
, m_automaticConnect(false)
{
setObjectName(QLatin1String("QmlEngine"));
- ExtensionSystem::PluginManager::addObject(this);
if (masterEngine)
setMasterEngine(masterEngine);
@@ -291,7 +299,7 @@ QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters, DebuggerEng
SLOT(updateCurrentContext()));
connect(stackHandler(), SIGNAL(currentIndexChanged()),
SLOT(updateCurrentContext()));
- connect(&m_inspectorAdapter, SIGNAL(selectionChanged()),
+ connect(inspectorTreeView(), SIGNAL(currentIndexChanged(QModelIndex)),
SLOT(updateCurrentContext()));
connect(m_inspectorAdapter.agent(), SIGNAL(
expressionResult(quint32,QVariant)),
@@ -331,27 +339,23 @@ QmlEngine::QmlEngine(const DebuggerStartParameters &startParameters, DebuggerEng
m_noDebugOutputTimer.setInterval(8000);
connect(&m_noDebugOutputTimer, SIGNAL(timeout()), this, SLOT(tryToConnect()));
- qtMessageLogHandler()->setHasEditableRow(true);
-
- connect(ModelManagerInterface::instance(),
- SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
- this,
- SLOT(documentUpdated(QmlJS::Document::Ptr)));
-
+ ModelManagerInterface *mmIface = ModelManagerInterface::instance();
+ if (mmIface) {
+ connect(ModelManagerInterface::instance(), SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
+ this, SLOT(documentUpdated(QmlJS::Document::Ptr)));
+ }
// we won't get any debug output
if (startParameters.useTerminal) {
m_noDebugOutputTimer.setInterval(0);
m_retryOnConnectFail = true;
m_automaticConnect = true;
}
+ if (qmlConsoleManager())
+ qmlConsoleManager()->setScriptEvaluator(this);
}
QmlEngine::~QmlEngine()
{
- if (ExtensionSystem::PluginManager::allObjects().contains(this)) {
- ExtensionSystem::PluginManager::removeObject(this);
- }
-
QList<Core::IEditor *> editorsToClose;
QHash<QString, QWeakPointer<TextEditor::ITextEditor> >::iterator iter;
@@ -382,9 +386,8 @@ void QmlEngine::connectionEstablished()
{
attemptBreakpointSynchronization();
- if (!watchHandler()->watcherNames().isEmpty()) {
+ if (!watchHandler()->watcherNames().isEmpty())
synchronizeWatchers();
- }
connect(watchersModel(),SIGNAL(layoutChanged()),this,SLOT(synchronizeWatchers()));
if (state() == EngineRunRequested)
@@ -528,9 +531,8 @@ void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/)
void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
- if (channel == AppOutput || channel == AppError) {
+ if (channel == AppOutput || channel == AppError)
const_cast<QmlEngine*>(this)->filterApplicationMessage(msg, channel);
- }
DebuggerEngine::showMessage(msg, channel, timeout);
}
@@ -556,9 +558,8 @@ void QmlEngine::gotoLocation(const Location &location)
if (!editor) {
editor = Core::EditorManager::openEditorWithContents(QmlJSEditor::Constants::C_QMLJSEDITOR_ID,
&titlePattern);
- if (editor) {
+ if (editor)
editor->setProperty(Constants::OPENED_BY_DEBUGGER, true);
- }
updateEditor(editor, m_sourceDocuments.value(fileName));
}
@@ -644,9 +645,8 @@ void QmlEngine::shutdownInferior()
if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->endSession();
- if (isSlaveEngine()) {
+ if (isSlaveEngine())
resetLocation();
- }
stopApplicationLauncher();
closeConnection();
@@ -655,6 +655,8 @@ void QmlEngine::shutdownInferior()
void QmlEngine::shutdownEngine()
{
+ if (qmlConsoleManager())
+ qmlConsoleManager()->setScriptEvaluator(0);
m_noDebugOutputTimer.stop();
// double check (ill engine?):
@@ -686,9 +688,8 @@ void QmlEngine::setupEngine()
void QmlEngine::continueInferior()
{
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->continueInferior();
- }
resetLocation();
notifyInferiorRunRequested();
notifyInferiorRunOk();
@@ -696,44 +697,39 @@ void QmlEngine::continueInferior()
void QmlEngine::interruptInferior()
{
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->interruptInferior();
- }
notifyInferiorStopOk();
}
void QmlEngine::executeStep()
{
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->executeStep();
- }
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeStepI()
{
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->executeStepI();
- }
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeStepOut()
{
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->executeStepOut();
- }
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeNext()
{
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->executeNext();
- }
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
@@ -777,15 +773,14 @@ void QmlEngine::activateFrame(int index)
if (state() != InferiorStopOk && state() != InferiorUnrunnable)
return;
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->activateFrame(index);
- }
gotoLocation(stackHandler()->frames().value(index));
}
-void QmlEngine::selectThread(int index)
+void QmlEngine::selectThread(ThreadId threadId)
{
- Q_UNUSED(index)
+ Q_UNUSED(threadId)
}
void QmlEngine::insertBreakpoint(BreakpointModelId id)
@@ -848,9 +843,8 @@ void QmlEngine::removeBreakpoint(BreakpointModelId id)
}
}
- if (handler->state(id) == BreakpointRemoveProceeding) {
+ if (handler->state(id) == BreakpointRemoveProceeding)
handler->notifyBreakpointRemoveOk(id);
- }
}
void QmlEngine::changeBreakpoint(BreakpointModelId id)
@@ -868,9 +862,8 @@ void QmlEngine::changeBreakpoint(BreakpointModelId id)
}
}
- if (handler->state(id) == BreakpointChangeProceeding) {
+ if (handler->state(id) == BreakpointChangeProceeding)
handler->notifyBreakpointChangeOk(id);
- }
}
void QmlEngine::attemptBreakpointSynchronization()
@@ -935,9 +928,8 @@ bool QmlEngine::acceptsBreakpoint(BreakpointModelId id) const
//For now, the event breakpoint can be set after the activeDebuggerClient is known
//This is because the older client does not support BreakpointOnQmlSignalHandler
bool acceptBreakpoint = false;
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
acceptBreakpoint = m_adapter.activeDebuggerClient()->acceptsBreakpoint(id);
- }
return acceptBreakpoint;
}
@@ -956,9 +948,8 @@ void QmlEngine::reloadModules()
void QmlEngine::reloadSourceFiles()
{
- if (m_adapter.activeDebuggerClient()) {
+ if (m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->getSourceFiles();
- }
}
void QmlEngine::requestModuleSymbols(const QString &moduleName)
@@ -1008,9 +999,8 @@ void QmlEngine::updateWatchData(const WatchData &data,
m_inspectorAdapter.agent()->updateWatchData(data);
} else {
if (!data.name.isEmpty() && m_adapter.activeDebuggerClient()) {
- if (data.isValueNeeded()) {
+ if (data.isValueNeeded())
m_adapter.activeDebuggerClient()->updateWatchData(data);
- }
if (data.isChildrenNeeded()
&& watchHandler()->isExpandedIName(data.iname)) {
m_adapter.activeDebuggerClient()->expandObject(data.iname, data.id);
@@ -1042,14 +1032,61 @@ void QmlEngine::synchronizeWatchers()
}
}
+QmlJS::ConsoleItem *constructLogItemTree(QmlJS::ConsoleItem *parent,
+ const QVariant &result,
+ const QString &key = QString())
+{
+ using namespace QmlJS;
+ bool sorted = debuggerCore()->boolSetting(SortStructMembers);
+ if (!result.isValid())
+ return 0;
+
+ ConsoleItem *item = new ConsoleItem(parent);
+ if (result.type() == QVariant::Map) {
+ if (key.isEmpty())
+ item->setText(_("Object"));
+ else
+ item->setText(key + _(" : Object"));
+
+ QMapIterator<QString, QVariant> i(result.toMap());
+ while (i.hasNext()) {
+ i.next();
+ ConsoleItem *child = constructLogItemTree(item, i.value(), i.key());
+ if (child)
+ item->insertChild(child, sorted);
+ }
+ } else if (result.type() == QVariant::List) {
+ if (key.isEmpty())
+ item->setText(_("List"));
+ else
+ item->setText(QString(_("[%1] : List")).arg(key));
+ QVariantList resultList = result.toList();
+ for (int i = 0; i < resultList.count(); i++) {
+ ConsoleItem *child = constructLogItemTree(item, resultList.at(i),
+ QString::number(i));
+ if (child)
+ item->insertChild(child, sorted);
+ }
+ } else if (result.canConvert(QVariant::String)) {
+ item->setText(result.toString());
+ } else {
+ item->setText(_("Unknown Value"));
+ }
+
+ return item;
+}
+
void QmlEngine::expressionEvaluated(quint32 queryId, const QVariant &result)
{
if (queryIds.contains(queryId)) {
queryIds.removeOne(queryId);
- QtMessageLogItem *item = constructLogItemTree(qtMessageLogHandler()->root(),
- result);
- if (item)
- qtMessageLogHandler()->appendItem(item);
+ using namespace QmlJS;
+ ConsoleManagerInterface *consoleManager = qmlConsoleManager();
+ if (consoleManager) {
+ ConsoleItem *item = constructLogItemTree(consoleManager->rootItem(), result);
+ if (item)
+ consoleManager->printToConsolePane(item);
+ }
}
}
@@ -1102,79 +1139,86 @@ void QmlEngine::documentUpdated(QmlJS::Document::Ptr doc)
void QmlEngine::updateCurrentContext()
{
- const QString context = state() == InferiorStopOk ?
- stackHandler()->currentFrame().function :
- m_inspectorAdapter.currentSelectedDisplayName();
- showMessage(tr("Context: ").append(context), QtMessageLogStatus);
+ QString context;
+ if (state() == InferiorStopOk) {
+ context = stackHandler()->currentFrame().function;
+ } else {
+ QModelIndex currentIndex = inspectorTreeView()->currentIndex();
+ const WatchData *currentData = watchHandler()->watchData(currentIndex);
+ const WatchData *parentData = watchHandler()->watchData(currentIndex.parent());
+ const WatchData *grandParentData = watchHandler()->watchData(
+ currentIndex.parent().parent());
+ if (currentData->id != parentData->id)
+ context = currentData->name;
+ else if (parentData->id != grandParentData->id)
+ context = parentData->name;
+ else
+ context = grandParentData->name;
+ }
+
+ QmlJS::ConsoleManagerInterface *consoleManager = qmlConsoleManager();
+ if (consoleManager)
+ consoleManager->setContext(tr("Context: ").append(context));
}
void QmlEngine::appendDebugOutput(QtMsgType type, const QString &message,
const QmlDebug::QDebugContextInfo &info)
{
- QtMessageLogHandler::ItemType itemType;
+ using namespace QmlJS;
+ ConsoleItem::ItemType itemType;
switch (type) {
case QtDebugMsg:
- itemType = QtMessageLogHandler::DebugType;
+ itemType = ConsoleItem::DebugType;
break;
case QtWarningMsg:
- itemType = QtMessageLogHandler::WarningType;
+ itemType = ConsoleItem::WarningType;
break;
case QtCriticalMsg:
case QtFatalMsg:
- itemType = QtMessageLogHandler::ErrorType;
+ itemType = ConsoleItem::ErrorType;
break;
default:
//This case is not possible
return;
}
- QtMessageLogItem *item = new QtMessageLogItem(qtMessageLogHandler()->root(),
- itemType, message);
- item->file = info.file;
- item->line = info.line;
- qtMessageLogHandler()->appendItem(item);
+ ConsoleManagerInterface *consoleManager = qmlConsoleManager();
+ if (consoleManager) {
+ ConsoleItem *item = new ConsoleItem(consoleManager->rootItem(), itemType, message);
+ item->file = info.file;
+ item->line = info.line;
+ consoleManager->printToConsolePane(item);
+ }
}
void QmlEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
{
- if ((languages & QmlLanguage) && m_adapter.activeDebuggerClient()) {
+ if ((languages & QmlLanguage) && m_adapter.activeDebuggerClient())
m_adapter.activeDebuggerClient()->executeDebuggerCommand(command);
- }
}
-bool QmlEngine::evaluateScriptExpression(const QString &expression)
+bool QmlEngine::evaluateScript(const QString &expression)
{
bool didEvaluate = true;
- //Check if string is only white spaces
- if (!expression.trimmed().isEmpty()) {
- //check if it can be evaluated
- if (canEvaluateScript(expression)) {
- //Evaluate expression based on engine state
- //When engine->state() == InferiorStopOk, the expression
- //is sent to V8DebugService. In all other cases, the
- //expression is evaluated by QDeclarativeEngine.
- if (state() != InferiorStopOk) {
- QmlInspectorAgent *agent = m_inspectorAdapter.agent();
- quint32 queryId
- = agent->queryExpressionResult(
- m_inspectorAdapter.currentSelectedDebugId(),
- expression);
- if (queryId) {
- queryIds << queryId;
- } else {
- didEvaluate = false;
- qtMessageLogHandler()->
- appendItem(
- new QtMessageLogItem(
- qtMessageLogHandler()->root(),
- QtMessageLogHandler::ErrorType,
- _("Error evaluating expression.")));
- }
- } else {
- executeDebuggerCommand(expression, QmlLanguage);
- }
+ // Evaluate expression based on engine state
+ // When engine->state() == InferiorStopOk, the expression is sent to debuggerClient.
+ if (state() != InferiorStopOk) {
+ QModelIndex currentIndex = inspectorTreeView()->currentIndex();
+ QmlInspectorAgent *agent = m_inspectorAdapter.agent();
+ quint32 queryId = agent->queryExpressionResult(watchHandler()->watchData(currentIndex)->id,
+ expression);
+ if (queryId) {
+ queryIds << queryId;
} else {
didEvaluate = false;
+ using namespace QmlJS;
+ ConsoleManagerInterface *consoleManager = qmlConsoleManager();
+ if (consoleManager) {
+ consoleManager->printToConsolePane(ConsoleItem::ErrorType,
+ _("Error evaluating expression."));
+ }
}
+ } else {
+ executeDebuggerCommand(expression, QmlLanguage);
}
return didEvaluate;
}
@@ -1281,69 +1325,39 @@ bool QmlEngine::canEvaluateScript(const QString &script)
return m_interpreter.canEvaluate();
}
-QtMessageLogItem *QmlEngine::constructLogItemTree(
- QtMessageLogItem *parent, const QVariant &result, const QString &key)
-{
- if (!result.isValid())
- return 0;
-
- QtMessageLogItem *item = new QtMessageLogItem(parent);
- if (result.type() == QVariant::Map) {
- if (key.isEmpty())
- item->setText(_("Object"));
- else
- item->setText(key + _(" : Object"));
-
- QMapIterator<QString, QVariant> i(result.toMap());
- while (i.hasNext()) {
- i.next();
- QtMessageLogItem *child = constructLogItemTree(item,
- i.value(), i.key());
- if (child)
- item->insertChild(child);
- }
- } else if (result.type() == QVariant::List) {
- if (key.isEmpty())
- item->setText(_("List"));
- else
- item->setText(QString(_("[%1] : List")).arg(key));
- QVariantList resultList = result.toList();
- for (int i = 0; i < resultList.count(); i++) {
- QtMessageLogItem *child = constructLogItemTree(item, resultList.at(i),
- QString::number(i));
- if (child)
- item->insertChild(child);
- }
- } else if (result.canConvert(QVariant::String)) {
- item->setText(result.toString());
- } else {
- item->setText(_("Unknown Value"));
- }
-
- return item;
-}
-
bool QmlEngine::adjustBreakpointLineAndColumn(
const QString &filePath, quint32 *line, quint32 *column, bool *valid)
{
- bool success = true;
+ bool success = false;
//check if file is in the latest snapshot
//ignoring documentChangedOnDisk
//TODO:: update breakpoints if document is changed.
- Document::Ptr doc = ModelManagerInterface::instance()->newestSnapshot().
- document(filePath);
- if (doc.isNull()) {
- ModelManagerInterface::instance()->updateSourceFiles(
- QStringList() << filePath, false);
- success = false;
- } else {
- ASTWalker walker;
- walker(doc->ast(), line, column);
- *valid = walker.done;
+ ModelManagerInterface *mmIface = ModelManagerInterface::instance();
+ if (mmIface) {
+ Document::Ptr doc = mmIface->newestSnapshot().
+ document(filePath);
+ if (doc.isNull()) {
+ ModelManagerInterface::instance()->updateSourceFiles(
+ QStringList() << filePath, false);
+ } else {
+ ASTWalker walker;
+ walker(doc->ast(), line, column);
+ *valid = walker.done;
+ success = true;
+ }
}
return success;
}
+WatchTreeView *QmlEngine::inspectorTreeView() const
+{
+ DebuggerMainWindow *dw = qobject_cast<DebuggerMainWindow *>(debuggerCore()->mainWindow());
+ LocalsAndExpressionsWindow *leW = qobject_cast<LocalsAndExpressionsWindow *>(
+ dw->dockWidget(QLatin1String(Constants::DOCKWIDGET_WATCHERS))->widget());
+ WatchWindow *inspectorWindow = qobject_cast<WatchWindow *>(leW->inspectorWidget());
+ return qobject_cast<WatchTreeView *>(inspectorWindow->treeView());
+}
+
DebuggerEngine *createQmlEngine(const DebuggerStartParameters &sp)
{
return new QmlEngine(sp);
diff --git a/src/plugins/debugger/qml/qmlengine.h b/src/plugins/debugger/qml/qmlengine.h
index 5a3e10eb72..7fdfcaf767 100644
--- a/src/plugins/debugger/qml/qmlengine.h
+++ b/src/plugins/debugger/qml/qmlengine.h
@@ -39,6 +39,7 @@
#include <qmldebug/qdebugmessageclient.h>
#include <qmldebug/qmloutputparser.h>
#include <qmljs/qmljsdocument.h>
+#include <qmljs/iscriptevaluator.h>
#include <utils/outputformat.h>
#include <QAbstractSocket>
@@ -52,9 +53,9 @@ namespace Debugger {
namespace Internal {
class QmlAdapter;
-class QtMessageLogItem;
+class WatchTreeView;
-class QmlEngine : public DebuggerEngine
+class QmlEngine : public DebuggerEngine, QmlJS::IScriptEvaluator
{
Q_OBJECT
@@ -140,7 +141,7 @@ private:
void executeJumpToLine(const ContextData &data);
void activateFrame(int index);
- void selectThread(int index);
+ void selectThread(ThreadId threadId);
void attemptBreakpointSynchronization();
void removeBreakpoint(BreakpointModelId id);
@@ -164,7 +165,7 @@ private:
const WatchUpdateFlags &flags);
void watchDataSelected(const QByteArray &iname);
void executeDebuggerCommand(const QString &command, DebuggerLanguages languages);
- bool evaluateScriptExpression(const QString &expression);
+ bool evaluateScript(const QString &expression);
bool hasCapability(unsigned) const;
void quitDebugger();
@@ -182,12 +183,11 @@ private:
void updateEditor(Core::IEditor *editor, const QTextDocument *document);
bool canEvaluateScript(const QString &script);
- QtMessageLogItem *constructLogItemTree(QtMessageLogItem *parent,
- const QVariant &result,
- const QString &key = QString());
bool adjustBreakpointLineAndColumn(const QString &filePath, quint32 *line,
quint32 *column, bool *valid);
+ WatchTreeView *inspectorTreeView() const;
+
QmlAdapter m_adapter;
QmlInspectorAdapter m_inspectorAdapter;
ProjectExplorer::ApplicationLauncher m_applicationLauncher;
diff --git a/src/plugins/debugger/qml/qmlinspectoradapter.cpp b/src/plugins/debugger/qml/qmlinspectoradapter.cpp
index 8b8e3e7c67..59002b55cc 100644
--- a/src/plugins/debugger/qml/qmlinspectoradapter.cpp
+++ b/src/plugins/debugger/qml/qmlinspectoradapter.cpp
@@ -300,37 +300,39 @@ void QmlInspectorAdapter::createPreviewForEditor(Core::IEditor *newEditor)
QString filename = newEditor->document()->fileName();
QmlJS::ModelManagerInterface *modelManager =
QmlJS::ModelManagerInterface::instance();
- QmlJS::Document::Ptr doc = modelManager->snapshot().document(filename);
- if (!doc) {
- if (filename.endsWith(QLatin1String(".qml")) || filename.endsWith(QLatin1String(".js"))) {
- // add to list of docs that we have to update when
- // snapshot figures out that there's a new document
- m_pendingPreviewDocumentNames.append(filename);
+ if (modelManager) {
+ QmlJS::Document::Ptr doc = modelManager->snapshot().document(filename);
+ if (!doc) {
+ if (filename.endsWith(QLatin1String(".qml")) || filename.endsWith(QLatin1String(".js"))) {
+ // add to list of docs that we have to update when
+ // snapshot figures out that there's a new document
+ m_pendingPreviewDocumentNames.append(filename);
+ }
+ return;
+ }
+ if (!doc->qmlProgram() && !filename.endsWith(QLatin1String(".js")))
+ return;
+
+ QmlJS::Document::Ptr initdoc = m_loadedSnapshot.document(filename);
+ if (!initdoc)
+ initdoc = doc;
+
+ if (m_textPreviews.contains(filename)) {
+ QmlLiveTextPreview *preview = m_textPreviews.value(filename);
+ preview->associateEditor(newEditor);
+ } else {
+ QmlLiveTextPreview *preview
+ = new QmlLiveTextPreview(doc, initdoc, this, this);
+
+ preview->setApplyChangesToQmlInspector(
+ debuggerCore()->action(QmlUpdateOnSave)->isChecked());
+ connect(preview, SIGNAL(reloadRequest()),
+ this, SLOT(onReload()));
+
+ m_textPreviews.insert(newEditor->document()->fileName(), preview);
+ preview->associateEditor(newEditor);
+ preview->updateDebugIds();
}
- return;
- }
- if (!doc->qmlProgram() && !filename.endsWith(QLatin1String(".js")))
- return;
-
- QmlJS::Document::Ptr initdoc = m_loadedSnapshot.document(filename);
- if (!initdoc)
- initdoc = doc;
-
- if (m_textPreviews.contains(filename)) {
- QmlLiveTextPreview *preview = m_textPreviews.value(filename);
- preview->associateEditor(newEditor);
- } else {
- QmlLiveTextPreview *preview
- = new QmlLiveTextPreview(doc, initdoc, this, this);
-
- preview->setApplyChangesToQmlInspector(
- debuggerCore()->action(QmlUpdateOnSave)->isChecked());
- connect(preview, SIGNAL(reloadRequest()),
- this, SLOT(onReload()));
-
- m_textPreviews.insert(newEditor->document()->fileName(), preview);
- preview->associateEditor(newEditor);
- preview->updateDebugIds();
}
}
@@ -420,15 +422,17 @@ void QmlInspectorAdapter::setActiveEngineClient(BaseEngineDebugClient *client)
m_engineClient->status() == QmlDebug::Enabled) {
QmlJS::ModelManagerInterface *modelManager
= QmlJS::ModelManagerInterface::instance();
- QmlJS::Snapshot snapshot = modelManager->snapshot();
- for (QHash<QString, QmlLiveTextPreview *>::const_iterator it
- = m_textPreviews.constBegin();
- it != m_textPreviews.constEnd(); ++it) {
- QmlJS::Document::Ptr doc = snapshot.document(it.key());
- it.value()->resetInitialDoc(doc);
+ if (modelManager) {
+ QmlJS::Snapshot snapshot = modelManager->snapshot();
+ for (QHash<QString, QmlLiveTextPreview *>::const_iterator it
+ = m_textPreviews.constBegin();
+ it != m_textPreviews.constEnd(); ++it) {
+ QmlJS::Document::Ptr doc = snapshot.document(it.key());
+ it.value()->resetInitialDoc(doc);
+ }
+
+ initializePreviews();
}
-
- initializePreviews();
}
}
@@ -437,22 +441,24 @@ void QmlInspectorAdapter::initializePreviews()
Core::EditorManager *em = Core::EditorManager::instance();
QmlJS::ModelManagerInterface *modelManager
= QmlJS::ModelManagerInterface::instance();
- m_loadedSnapshot = modelManager->snapshot();
-
- if (!m_listeningToEditorManager) {
- m_listeningToEditorManager = true;
- connect(em, SIGNAL(editorAboutToClose(Core::IEditor*)),
- this, SLOT(removePreviewForEditor(Core::IEditor*)));
- connect(em, SIGNAL(editorOpened(Core::IEditor*)),
- this, SLOT(createPreviewForEditor(Core::IEditor*)));
- connect(modelManager,
- SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)),
- this, SLOT(updatePendingPreviewDocuments(QmlJS::Document::Ptr)));
- }
+ if (modelManager) {
+ m_loadedSnapshot = modelManager->snapshot();
+
+ if (!m_listeningToEditorManager) {
+ m_listeningToEditorManager = true;
+ connect(em, SIGNAL(editorAboutToClose(Core::IEditor*)),
+ this, SLOT(removePreviewForEditor(Core::IEditor*)));
+ connect(em, SIGNAL(editorOpened(Core::IEditor*)),
+ this, SLOT(createPreviewForEditor(Core::IEditor*)));
+ connect(modelManager,
+ SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)),
+ this, SLOT(updatePendingPreviewDocuments(QmlJS::Document::Ptr)));
+ }
- // initial update
- foreach (Core::IEditor *editor, em->openedEditors())
- createPreviewForEditor(editor);
+ // initial update
+ foreach (Core::IEditor *editor, em->openedEditors())
+ createPreviewForEditor(editor);
+ }
}
void QmlInspectorAdapter::showConnectionStatusMessage(const QString &message)
@@ -479,7 +485,6 @@ void QmlInspectorAdapter::jumpToObjectDefinitionInEditor(
if (debugId != -1 && debugId != m_currentSelectedDebugId) {
m_currentSelectedDebugId = debugId;
m_currentSelectedDebugName = agent()->displayName(debugId);
- emit selectionChanged();
}
}
@@ -493,12 +498,7 @@ void QmlInspectorAdapter::selectObject(const ObjectReference &obj,
if (target == EditorTarget)
jumpToObjectDefinitionInEditor(obj.source());
- if (!agent()->selectObjectInTree(obj.debugId()))
- return;
-
- m_currentSelectedDebugId = obj.debugId();
- m_currentSelectedDebugName = agent()->displayName(obj.debugId());
- emit selectionChanged();
+ agent()->selectObjectInTree(obj.debugId());
}
void QmlInspectorAdapter::deletePreviews()
@@ -545,13 +545,15 @@ void QmlInspectorAdapter::onReloaded()
{
QmlJS::ModelManagerInterface *modelManager =
QmlJS::ModelManagerInterface::instance();
- QmlJS::Snapshot snapshot = modelManager->snapshot();
- m_loadedSnapshot = snapshot;
- for (QHash<QString, QmlLiveTextPreview *>::const_iterator it
- = m_textPreviews.constBegin();
- it != m_textPreviews.constEnd(); ++it) {
- QmlJS::Document::Ptr doc = snapshot.document(it.key());
- it.value()->resetInitialDoc(doc);
+ if (modelManager) {
+ QmlJS::Snapshot snapshot = modelManager->snapshot();
+ m_loadedSnapshot = snapshot;
+ for (QHash<QString, QmlLiveTextPreview *>::const_iterator it
+ = m_textPreviews.constBegin();
+ it != m_textPreviews.constEnd(); ++it) {
+ QmlJS::Document::Ptr doc = snapshot.document(it.key());
+ it.value()->resetInitialDoc(doc);
+ }
}
m_agent->reloadEngines();
}
diff --git a/src/plugins/debugger/qml/qmlinspectoradapter.h b/src/plugins/debugger/qml/qmlinspectoradapter.h
index 62da6971fa..33f2855d1b 100644
--- a/src/plugins/debugger/qml/qmlinspectoradapter.h
+++ b/src/plugins/debugger/qml/qmlinspectoradapter.h
@@ -79,7 +79,6 @@ public:
signals:
void expressionResult();
- void selectionChanged();
private slots:
void onEngineStateChanged(const Debugger::DebuggerState);
diff --git a/src/plugins/debugger/qml/qmlinspectoragent.cpp b/src/plugins/debugger/qml/qmlinspectoragent.cpp
index 3322a337c6..3c3fcd80dd 100644
--- a/src/plugins/debugger/qml/qmlinspectoragent.cpp
+++ b/src/plugins/debugger/qml/qmlinspectoragent.cpp
@@ -344,7 +344,7 @@ bool QmlInspectorAgent::addObjectWatch(int objectDebugId)
return true;
// is flooding the debugging output log!
- // log(LogSend, QString("WATCH_PROPERTY %1").arg(objectDebugId));
+ // log(LogSend, QString::fromLatin1("WATCH_PROPERTY %1").arg(objectDebugId));
if (m_engineClient->addWatch(objectDebugId))
m_objectWatches.append(objectDebugId);
diff --git a/src/plugins/debugger/qml/qmllivetextpreview.cpp b/src/plugins/debugger/qml/qmllivetextpreview.cpp
index f03e897bfa..55fe7148f4 100644
--- a/src/plugins/debugger/qml/qmllivetextpreview.cpp
+++ b/src/plugins/debugger/qml/qmllivetextpreview.cpp
@@ -363,10 +363,10 @@ QmlLiveTextPreview::QmlLiveTextPreview(const QmlJS::Document::Ptr &doc,
QmlJS::ModelManagerInterface *modelManager
= QmlJS::ModelManagerInterface::instance();
-
- connect(modelManager, SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)),
- SLOT(documentChanged(QmlJS::Document::Ptr)));
-
+ if (modelManager) {
+ connect(modelManager, SIGNAL(documentChangedOnDisk(QmlJS::Document::Ptr)),
+ SLOT(documentChanged(QmlJS::Document::Ptr)));
+ }
connect(m_inspectorAdapter->agent(), SIGNAL(objectTreeUpdated()),
SLOT(updateDebugIds()));
connect(this,
@@ -714,7 +714,7 @@ void QmlLiveTextPreview::showSyncWarning(
foreach (TextEditor::BaseTextEditorWidget *editor, m_editors) {
if (editor) {
Core::InfoBar *infoBar = editor->editorDocument()->infoBar();
- Core::InfoBarEntry info(QLatin1String(INFO_OUT_OF_SYNC), errorMessage);
+ Core::InfoBarEntry info(Core::Id(INFO_OUT_OF_SYNC), errorMessage);
BaseToolsClient *toolsClient = m_inspectorAdapter->toolsClient();
if (toolsClient && toolsClient->supportReload())
info.setCustomButtonInfo(tr("Reload QML"), this,
@@ -735,7 +735,7 @@ void QmlLiveTextPreview::removeOutofSyncInfo()
foreach (TextEditor::BaseTextEditorWidget *editor, m_editors) {
if (editor) {
Core::InfoBar *infoBar = editor->editorDocument()->infoBar();
- infoBar->removeInfo(QLatin1String(INFO_OUT_OF_SYNC));
+ infoBar->removeInfo(Core::Id(INFO_OUT_OF_SYNC));
}
}
}
diff --git a/src/plugins/debugger/qml/qmlv8debuggerclient.cpp b/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
index 6b99c6024a..88d5d04c59 100644
--- a/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
+++ b/src/plugins/debugger/qml/qmlv8debuggerclient.cpp
@@ -36,12 +36,16 @@
#include "breakhandler.h"
#include "qmlengine.h"
#include "stackhandler.h"
-#include "qtmessageloghandler.h"
+#include "debuggercore.h"
+#include "debuggeractions.h"
#include <utils/qtcassert.h>
#include <coreplugin/editormanager/editormanager.h>
#include <texteditor/basetexteditor.h>
+#include <qmljs/consolemanagerinterface.h>
+#include <qmljs/consoleitem.h>
+
#include <QTextBlock>
#include <QVariant>
#include <QStack>
@@ -116,19 +120,14 @@ public:
void version();
//void profile(ProfileCommand command); //NOT SUPPORTED
void gc();
-
- QmlV8ObjectData extractData(const QVariant &data, const QVariant &refsVal);
void clearCache();
void logSendMessage(const QString &msg) const;
void logReceiveMessage(const QString &msg) const;
- QtMessageLogItem *constructLogItemTree(QtMessageLogItem *parent,
- const QmlV8ObjectData &objectData, const QVariant &refsVal);
private:
QByteArray packMessage(const QByteArray &type, const QByteArray &message = QByteArray());
QScriptValue initObject();
- QVariant valueFromRef(int handle, const QVariant &refsVal, bool *success);
public:
QmlV8DebuggerClient *q;
@@ -761,8 +760,23 @@ void QmlV8DebuggerClientPrivate::gc()
q->sendMessage(packMessage(V8REQUEST, jsonMessage.toString().toUtf8()));
}
-QmlV8ObjectData QmlV8DebuggerClientPrivate::extractData(const QVariant &data,
- const QVariant &refsVal)
+QVariant valueFromRef(int handle, const QVariant &refsVal, bool *success)
+{
+ *success = false;
+ QVariant variant;
+ const QVariantList refs = refsVal.toList();
+ foreach (const QVariant &ref, refs) {
+ const QVariantMap refData = ref.toMap();
+ if (refData.value(_(HANDLE)).toInt() == handle) {
+ variant = refData;
+ *success = true;
+ break;
+ }
+ }
+ return variant;
+}
+
+QmlV8ObjectData extractData(const QVariant &data, const QVariant &refsVal)
{
// { "handle" : <handle>,
// "type" : <"undefined", "null", "boolean", "number", "string", "object", "function" or "frame">
@@ -900,24 +914,6 @@ QScriptValue QmlV8DebuggerClientPrivate::initObject()
return jsonVal;
}
-QVariant QmlV8DebuggerClientPrivate::valueFromRef(int handle,
- const QVariant &refsVal,
- bool *success)
-{
- *success = false;
- QVariant variant;
- const QVariantList refs = refsVal.toList();
- foreach (const QVariant &ref, refs) {
- const QVariantMap refData = ref.toMap();
- if (refData.value(_(HANDLE)).toInt() == handle) {
- variant = refData;
- *success = true;
- break;
- }
- }
- return variant;
-}
-
void QmlV8DebuggerClientPrivate::logSendMessage(const QString &msg) const
{
if (engine)
@@ -930,34 +926,6 @@ void QmlV8DebuggerClientPrivate::logReceiveMessage(const QString &msg) const
engine->logMessage(QLatin1String("V8DebuggerClient"), QmlEngine::LogReceive, msg);
}
-QtMessageLogItem *QmlV8DebuggerClientPrivate::constructLogItemTree(
- QtMessageLogItem *parent,
- const QmlV8ObjectData &objectData,
- const QVariant &refsVal)
-{
- if (!objectData.value.isValid())
- return 0;
-
- QString text;
- if (objectData.name.isEmpty())
- text = objectData.value.toString();
- else
- text = QString(_("%1: %2")).arg(QString::fromAscii(objectData.name))
- .arg(objectData.value.toString());
-
- QtMessageLogItem *item = new QtMessageLogItem(parent,
- QtMessageLogHandler::UndefinedType, text);
-
- foreach (const QVariant &property, objectData.properties) {
- QtMessageLogItem *child = constructLogItemTree(
- item, extractData(property, refsVal), refsVal);
- if (child)
- item->insertChild(child);
- }
-
- return item;
-}
-
///////////////////////////////////////////////////////////////////////
//
// QmlV8DebuggerClient
@@ -1125,9 +1093,8 @@ void QmlV8DebuggerClient::assignValueInDebugger(const WatchData * /*data*/,
d->evaluate(expression, false, false, stackHandler->currentIndex());
d->updateLocalsAndWatchers.append(d->sequence);
} else {
- d->engine->showMessage(QString(_("Cannot evaluate"
- "%1 in current stack frame")).
- arg(expression), QtMessageLogOutput);
+ d->engine->showMessage(QString(_("Cannot evaluate %1 in current stack frame")).arg(
+ expression), ConsoleOutput);
}
}
@@ -1144,9 +1111,8 @@ void QmlV8DebuggerClient::executeDebuggerCommand(const QString &command)
d->debuggerCommands.append(d->sequence);
} else {
//Currently cannot evaluate if not in a javascript break
- d->engine->showMessage(QString(_("Cannot evaluate %1"
- "in current stack frame")).
- arg(command), QtMessageLogOutput);
+ d->engine->showMessage(QString(_("Cannot evaluate %1 in current stack frame")).arg(
+ command), ConsoleOutput);
}
}
@@ -1241,14 +1207,12 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
//do nothing, wait for next break
} else if (debugCommand == _(BACKTRACE)) {
- if (success) {
+ if (success)
updateStack(resp.value(_(BODY)), resp.value(_(REFS)));
- }
} else if (debugCommand == _(LOOKUP)) {
- if (success) {
+ if (success)
expandLocalsAndWatchers(resp.value(_(BODY)), resp.value(_(REFS)));
- }
} else if (debugCommand == _(EVALUATE)) {
int seq = resp.value(_("request_seq")).toInt();
@@ -1262,9 +1226,8 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
}
} else if (debugCommand == _(LISTBREAKPOINTS)) {
- if (success) {
+ if (success)
updateBreakpoints(resp.value(_(BODY)));
- }
} else if (debugCommand == _(SETBREAKPOINT)) {
// { "seq" : <number>,
@@ -1330,14 +1293,12 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
} else if (debugCommand == _(FRAME)) {
- if (success) {
+ if (success)
setCurrentFrameDetails(resp.value(_(BODY)), resp.value(_(REFS)));
- }
} else if (debugCommand == _(SCOPE)) {
- if (success) {
+ if (success)
updateScope(resp.value(_(BODY)), resp.value(_(REFS)));
- }
} else if (debugCommand == _(SCOPES)) {
} else if (debugCommand == _(SOURCE)) {
@@ -1512,9 +1473,8 @@ void QmlV8DebuggerClient::messageReceived(const QByteArray &data)
d->backtrace();
}
- if (d->engine->state() == InferiorStopOk) {
+ if (d->engine->state() == InferiorStopOk)
d->backtrace();
- }
} else if (eventType == _("afterCompile")) {
//Currently break point relocation is disabled.
@@ -1630,17 +1590,17 @@ StackFrame QmlV8DebuggerClient::extractStackFrame(const QVariant &bodyVal, const
return stackFrame;
}
- QmlV8ObjectData objectData = d->extractData(body.value(_("func")), refsVal);
+ QmlV8ObjectData objectData = extractData(body.value(_("func")), refsVal);
QString functionName = objectData.value.toString();
if (functionName.isEmpty())
functionName = tr("Anonymous Function");
stackFrame.function = functionName;
- objectData = d->extractData(body.value(_("script")), refsVal);
+ objectData = extractData(body.value(_("script")), refsVal);
stackFrame.file = d->engine->toFileInProject(objectData.value.toString());
stackFrame.usable = QFileInfo(stackFrame.file).isReadable();
- objectData = d->extractData(body.value(_("receiver")), refsVal);
+ objectData = extractData(body.value(_("receiver")), refsVal);
stackFrame.to = objectData.value.toString();
stackFrame.line = body.value(_("line")).toInt() + 1;
@@ -1700,8 +1660,7 @@ void QmlV8DebuggerClient::setCurrentFrameDetails(const QVariant &bodyVal, const
data.exp = QByteArray("this");
data.name = QLatin1String(data.exp);
data.iname = QByteArray("local.") + data.exp;
- QmlV8ObjectData objectData = d->extractData(
- currentFrame.value(_("receiver")), refsVal);
+ QmlV8ObjectData objectData = extractData(currentFrame.value(_("receiver")), refsVal);
data.id = objectData.handle;
data.type = objectData.type;
data.value = objectData.value.toString();
@@ -1759,12 +1718,12 @@ void QmlV8DebuggerClient::updateScope(const QVariant &bodyVal, const QVariant &r
if (bodyMap.value(_("frameIndex")).toInt() != stackHandler->currentIndex())
return;
- QmlV8ObjectData objectData = d->extractData(bodyMap.value(_("object")), refsVal);
+ QmlV8ObjectData objectData = extractData(bodyMap.value(_("object")), refsVal);
QList<int> handlesToLookup;
QList<WatchData> locals;
foreach (const QVariant &property, objectData.properties) {
- QmlV8ObjectData localData = d->extractData(property, refsVal);
+ QmlV8ObjectData localData = extractData(property, refsVal);
WatchData data;
data.exp = localData.name;
//Check for v8 specific local data
@@ -1794,9 +1753,37 @@ void QmlV8DebuggerClient::updateScope(const QVariant &bodyVal, const QVariant &r
d->engine->watchHandler()->insertData(locals);
}
-void QmlV8DebuggerClient::updateEvaluationResult(int sequence, bool success, const QVariant &bodyVal,
+QmlJS::ConsoleItem *constructLogItemTree(QmlJS::ConsoleItem *parent,
+ const QmlV8ObjectData &objectData,
const QVariant &refsVal)
{
+ using namespace QmlJS;
+ bool sorted = debuggerCore()->boolSetting(SortStructMembers);
+ if (!objectData.value.isValid())
+ return 0;
+
+ QString text;
+ if (objectData.name.isEmpty())
+ text = objectData.value.toString();
+ else
+ text = QString(_("%1: %2")).arg(QString::fromAscii(objectData.name))
+ .arg(objectData.value.toString());
+
+ ConsoleItem *item = new ConsoleItem(parent, ConsoleItem::UndefinedType, text);
+
+ foreach (const QVariant &property, objectData.properties) {
+ ConsoleItem *child = constructLogItemTree(item, extractData(property, refsVal),
+ refsVal);
+ if (child)
+ item->insertChild(child, sorted);
+ }
+
+ return item;
+}
+
+void QmlV8DebuggerClient::updateEvaluationResult(int sequence, bool success,
+ const QVariant &bodyVal, const QVariant &refsVal)
+{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
@@ -1819,17 +1806,20 @@ void QmlV8DebuggerClient::updateEvaluationResult(int sequence, bool success, con
} else if (d->debuggerCommands.contains(sequence)) {
d->updateLocalsAndWatchers.removeOne(sequence);
- QmlV8ObjectData body = d->extractData(bodyVal, refsVal);
- QtMessageLogItem *item = d->constructLogItemTree(d->engine->qtMessageLogHandler()->root(),
- body, refsVal);
- if (item)
- d->engine->qtMessageLogHandler()->appendItem(item);
+ QmlV8ObjectData body = extractData(bodyVal, refsVal);
+ using namespace QmlJS;
+ ConsoleManagerInterface *consoleManager = ConsoleManagerInterface::instance();
+ if (consoleManager) {
+ ConsoleItem *item = constructLogItemTree(consoleManager->rootItem(), body, refsVal);
+ if (item)
+ consoleManager->printToConsolePane(item);
+ }
//Update the locals
foreach (int index, d->currentFrameScopes)
d->scope(index);
} else {
- QmlV8ObjectData body = d->extractData(bodyVal, refsVal);
+ QmlV8ObjectData body = extractData(bodyVal, refsVal);
if (d->evaluatingExpression.contains(sequence)) {
QString exp = d->evaluatingExpression.take(sequence);
QList<WatchData> watchDataList;
@@ -1928,7 +1918,7 @@ void QmlV8DebuggerClient::expandLocalsAndWatchers(const QVariant &bodyVal, const
QStringList handlesList = body.keys();
WatchHandler *watchHandler = d->engine->watchHandler();
foreach (const QString &handle, handlesList) {
- QmlV8ObjectData bodyObjectData = d->extractData(
+ QmlV8ObjectData bodyObjectData = extractData(
body.value(handle), refsVal);
QByteArray prepend = d->localsAndWatchers.take(handle.toInt());
@@ -1965,7 +1955,7 @@ QList<WatchData> QmlV8DebuggerClient::createWatchDataList(const WatchData *paren
if (properties.count()) {
QTC_ASSERT(parent, return watchDataList);
foreach (const QVariant &property, properties) {
- QmlV8ObjectData propertyData = d->extractData(property, refsVal);
+ QmlV8ObjectData propertyData = extractData(property, refsVal);
WatchData data;
data.name = QString::fromUtf8(propertyData.name);
@@ -2031,7 +2021,7 @@ void QmlV8DebuggerClient::highlightExceptionCode(int lineNumber,
QString message = QString(_("%1: %2: %3")).arg(filePath).arg(lineNumber)
.arg(errorMessage);
- d->engine->showMessage(message, QtMessageLogOutput);
+ d->engine->showMessage(message, ConsoleOutput);
}
}
}
diff --git a/src/plugins/debugger/qml/qscriptdebuggerclient.cpp b/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
index 6279e78502..50d0b0906a 100644
--- a/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
+++ b/src/plugins/debugger/qml/qscriptdebuggerclient.cpp
@@ -299,11 +299,10 @@ void QScriptDebuggerClient::synchronizeBreakpoints()
str << cmd << " (";
bool first = true;
foreach (const JSAgentBreakpointData &bp, d->breakpoints) {
- if (first) {
+ if (first)
first = false;
- } else {
+ else
str << ", ";
- }
str << '[' << bp.functionName << ", " << bp.fileUrl << ", " << bp.lineNumber << ']';
}
str << ')';
@@ -488,7 +487,7 @@ void QScriptDebuggerClient::messageReceived(const QByteArray &data)
if (iname.startsWith("watch.")) {
watchHandler->insertData(data);
} else if (iname == "console") {
- d->engine->showMessage(data.value, QtMessageLogOutput);
+ d->engine->showMessage(data.value, ConsoleOutput);
} else if (iname.startsWith("local.")) {
data.name = data.name.left(data.name.indexOf(QLatin1Char(' ')));
watchHandler->insertData(data);
diff --git a/src/plugins/debugger/qtmessageloghandler.cpp b/src/plugins/debugger/qtmessageloghandler.cpp
deleted file mode 100644
index c1792aa27b..0000000000
--- a/src/plugins/debugger/qtmessageloghandler.cpp
+++ /dev/null
@@ -1,405 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "qtmessageloghandler.h"
-#include "debuggercore.h"
-#include "debuggeractions.h"
-
-#include <utils/qtcassert.h>
-
-#include <QFontMetrics>
-
-namespace Debugger {
-namespace Internal {
-
-///////////////////////////////////////////////////////////////////////
-//
-// QtMessageLogItem
-//
-///////////////////////////////////////////////////////////////////////
-
-QtMessageLogItem::QtMessageLogItem(QtMessageLogItem *parent,
- QtMessageLogHandler::ItemType itemType, const QString &text)
- : m_parentItem(parent),
- itemType(itemType),
- line(-1)
-
-{
- setText(text);
-}
-
-QtMessageLogItem::~QtMessageLogItem()
-{
- qDeleteAll(m_childItems);
-}
-
-QtMessageLogItem *QtMessageLogItem::child(int number)
-{
- return m_childItems.value(number);
-}
-
-int QtMessageLogItem::childCount() const
-{
- return m_childItems.size();
-}
-
-int QtMessageLogItem::childNumber() const
-{
- if (m_parentItem)
- return m_parentItem->m_childItems.indexOf(
- const_cast<QtMessageLogItem *>(this));
-
- return 0;
-}
-
-bool QtMessageLogItem::insertChildren(int position, int count)
-{
- if (position < 0 || position > m_childItems.size())
- return false;
-
- for (int row = 0; row < count; ++row) {
- QtMessageLogItem *item = new
- QtMessageLogItem(this , QtMessageLogHandler::UndefinedType,
- QString());
- m_childItems.insert(position, item);
- }
-
- return true;
-}
-
-void QtMessageLogItem::insertChild(QtMessageLogItem *item)
-{
- if (!debuggerCore()->boolSetting(SortStructMembers)) {
- m_childItems.insert(m_childItems.count(), item);
- return;
- }
-
- int i = 0;
- for (; i < m_childItems.count(); i++) {
- if (item->m_text < m_childItems[i]->m_text) {
- break;
- }
- }
- m_childItems.insert(i, item);
-}
-
-bool QtMessageLogItem::insertChild(int position, QtMessageLogItem *item)
-{
- if (position < 0 || position > m_childItems.size())
- return false;
-
- m_childItems.insert(position, item);
-
- return true;
-}
-
-QtMessageLogItem *QtMessageLogItem::parent()
-{
- return m_parentItem;
-}
-
-bool QtMessageLogItem::removeChildren(int position, int count)
-{
- if (position < 0 || position + count > m_childItems.size())
- return false;
-
- for (int row = 0; row < count; ++row)
- delete m_childItems.takeAt(position);
-
- return true;
-}
-
-bool QtMessageLogItem::detachChild(int position)
-{
- if (position < 0 || position > m_childItems.size())
- return false;
-
- m_childItems.removeAt(position);
-
- return true;
-}
-
-void QtMessageLogItem::setText(const QString &text)
-{
- m_text = text;
- for (int i = 0; i < m_text.length(); ++i) {
- if (m_text.at(i).isPunct())
- m_text.insert(++i, QChar(0x200b)); // ZERO WIDTH SPACE
- }
-}
-
-const QString &QtMessageLogItem::text() const
-{
- return m_text;
-}
-
-///////////////////////////////////////////////////////////////////////
-//
-// QtMessageLogHandler
-//
-///////////////////////////////////////////////////////////////////////
-
-QtMessageLogHandler::QtMessageLogHandler(QObject *parent) :
- QAbstractItemModel(parent),
- m_hasEditableRow(false),
- m_rootItem(new QtMessageLogItem(0)),
- m_maxSizeOfFileName(0)
-{
-}
-
-QtMessageLogHandler::~QtMessageLogHandler()
-{
- delete m_rootItem;
-}
-
-void QtMessageLogHandler::clear()
-{
- beginResetModel();
- reset();
- delete m_rootItem;
- m_rootItem = new QtMessageLogItem(0);
- endResetModel();
-
- if (m_hasEditableRow)
- appendEditableRow();
-}
-
-bool QtMessageLogHandler::appendItem(QtMessageLogItem *item, int position)
-{
- if (position < 0)
- position = m_rootItem->childCount() - 1;
-
- beginInsertRows(QModelIndex(), position, position);
- bool success = m_rootItem->insertChild(position, item);
- endInsertRows();
-
- return success;
-}
-
-bool QtMessageLogHandler::appendMessage(QtMessageLogHandler::ItemType itemType,
- const QString &message, int position)
-{
- return appendItem(new QtMessageLogItem(m_rootItem, itemType, message), position);
-}
-
-void QtMessageLogHandler::setHasEditableRow(bool hasEditableRow)
-{
- if (m_hasEditableRow && !hasEditableRow)
- removeEditableRow();
-
- if (!m_hasEditableRow && hasEditableRow)
- appendEditableRow();
-
- m_hasEditableRow = hasEditableRow;
-}
-
-bool QtMessageLogHandler::hasEditableRow() const
-{
- return m_hasEditableRow;
-}
-
-void QtMessageLogHandler::appendEditableRow()
-{
- int position = m_rootItem->childCount();
- if (appendItem(new QtMessageLogItem(m_rootItem, QtMessageLogHandler::InputType), position))
- emit selectEditableRow(index(position, 0),
- QItemSelectionModel::ClearAndSelect);
-}
-
-void QtMessageLogHandler::removeEditableRow()
-{
- if (m_rootItem->child(m_rootItem->childCount() - 1)->itemType ==
- QtMessageLogHandler::InputType)
- removeRow(m_rootItem->childCount() - 1);
-}
-
-int QtMessageLogHandler::sizeOfFile(const QFont &font)
-{
- int lastReadOnlyRow = m_rootItem->childCount();
- if (m_hasEditableRow)
- lastReadOnlyRow -= 2;
- else
- lastReadOnlyRow -= 1;
- if (lastReadOnlyRow < 0)
- return 0;
- QString filename = m_rootItem->child(lastReadOnlyRow)->file;
- const int pos = filename.lastIndexOf(QLatin1Char('/'));
- if (pos != -1)
- filename = filename.mid(pos + 1);
-
- QFontMetrics fm(font);
- m_maxSizeOfFileName = qMax(m_maxSizeOfFileName, fm.width(filename));
-
- return m_maxSizeOfFileName;
-}
-
-int QtMessageLogHandler::sizeOfLineNumber(const QFont &font)
-{
- QFontMetrics fm(font);
- return fm.width(QLatin1String("88888"));
-}
-
-QVariant QtMessageLogHandler::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid())
- return QVariant();
-
- QtMessageLogItem *item = getItem(index);
-
- if (role == Qt::DisplayRole )
- return item->text();
- else if (role == QtMessageLogHandler::TypeRole)
- return int(item->itemType);
- else if (role == QtMessageLogHandler::FileRole)
- return item->file;
- else if (role == QtMessageLogHandler::LineRole)
- return item->line;
- else
- return QVariant();
-}
-
-QModelIndex QtMessageLogHandler::index(int row, int column,
- const QModelIndex &parent) const
-{
- if (parent.isValid() && parent.column() != 0)
- return QModelIndex();
-
- if (column > 0)
- return QModelIndex();
-
- QtMessageLogItem *parentItem = getItem(parent);
-
- QtMessageLogItem *childItem = parentItem->child(row);
- if (childItem)
- return createIndex(row, column, childItem);
- else
- return QModelIndex();
-}
-
-QModelIndex QtMessageLogHandler::parent(const QModelIndex &index) const
-{
- if (!index.isValid())
- return QModelIndex();
-
- QtMessageLogItem *childItem = getItem(index);
- QtMessageLogItem *parentItem = childItem->parent();
-
- if (parentItem == m_rootItem)
- return QModelIndex();
-
- //can parentItem be 0?
- if (!parentItem)
- return QModelIndex();
- return createIndex(parentItem->childNumber(), 0, parentItem);
-}
-
-int QtMessageLogHandler::rowCount(const QModelIndex &parent) const
-{
- QtMessageLogItem *parentItem = getItem(parent);
-
- return parentItem->childCount();
-}
-
-int QtMessageLogHandler::columnCount(const QModelIndex & /* parent */) const
-{
- return 1;
-}
-
-Qt::ItemFlags QtMessageLogHandler::flags(const QModelIndex &index) const
-{
- if (!index.isValid())
- return 0;
-
- QtMessageLogItem *item = getItem(index);
- if (m_hasEditableRow && item->parent() == m_rootItem
- && index.row() == m_rootItem->childCount() - 1)
- return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
- return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
-}
-
-bool QtMessageLogHandler::setData(const QModelIndex &index, const QVariant &value,
- int role)
-{
- QtMessageLogItem *item = getItem(index);
- bool result = false;
- if (role == Qt::DisplayRole) {
- item->setText(value.toString());
- result = true;
- } else if (role == QtMessageLogHandler::TypeRole) {
- item->itemType = (QtMessageLogHandler::ItemType)value.toInt();
- result = true;
- } else if (role == QtMessageLogHandler::FileRole) {
- item->file = value.toString();
- result = true;
- } else if (role == QtMessageLogHandler::LineRole) {
- item->line = value.toInt();
- result = true;
- }
-
- if (result)
- emit dataChanged(index, index);
-
- return result;
-}
-
-bool QtMessageLogHandler::insertRows(int position, int rows, const QModelIndex &parent)
-{
- QtMessageLogItem *parentItem = getItem(parent);
- bool success;
-
- beginInsertRows(parent, position, position + rows - 1);
- success = parentItem->insertChildren(position, rows);
- endInsertRows();
-
- return success;
-}
-
-bool QtMessageLogHandler::removeRows(int position, int rows, const QModelIndex &parent)
-{
- QtMessageLogItem *parentItem = getItem(parent);
- bool success = true;
-
- beginRemoveRows(parent, position, position + rows - 1);
- success = parentItem->removeChildren(position, rows);
- endRemoveRows();
-
- return success;
-}
-
-QtMessageLogItem *QtMessageLogHandler::getItem(const QModelIndex &index) const
-{
- if (index.isValid()) {
- QtMessageLogItem *item = static_cast<QtMessageLogItem*>(index.internalPointer());
- if (item) return item;
- }
- return m_rootItem;
-}
-
-} //Internal
-} //Debugger
diff --git a/src/plugins/debugger/qtmessagelogwindow.cpp b/src/plugins/debugger/qtmessagelogwindow.cpp
deleted file mode 100644
index bfb2a2c6b6..0000000000
--- a/src/plugins/debugger/qtmessagelogwindow.cpp
+++ /dev/null
@@ -1,253 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "qtmessagelogwindow.h"
-#include "qtmessagelogview.h"
-#include "qtmessageloghandler.h"
-#include "qtmessagelogitemdelegate.h"
-#include "debuggerstringutils.h"
-#include "qtmessagelogproxymodel.h"
-
-#include <utils/statuslabel.h>
-#include <utils/styledbar.h>
-#include <utils/savedaction.h>
-
-#include <coreplugin/icore.h>
-#include <coreplugin/coreconstants.h>
-#include <coreplugin/findplaceholder.h>
-
-#include <aggregation/aggregate.h>
-#include <find/treeviewfind.h>
-
-#include <QSettings>
-#include <QHBoxLayout>
-#include <QVBoxLayout>
-#include <QToolButton>
-
-static const char CONSOLE[] = "Console";
-static const char SHOW_LOG[] = "showLog";
-static const char SHOW_WARNING[] = "showWarning";
-static const char SHOW_ERROR[] = "showError";
-
-namespace Debugger {
-namespace Internal {
-
-/////////////////////////////////////////////////////////////////////
-//
-// QtMessageLogWindow
-//
-/////////////////////////////////////////////////////////////////////
-
-QtMessageLogWindow::QtMessageLogWindow(QWidget *parent)
- : QWidget(parent)
-{
- setWindowTitle(tr(CONSOLE));
- setObjectName(_(CONSOLE));
-
- const int statusBarHeight = 25;
-
- QVBoxLayout *vbox = new QVBoxLayout(this);
- vbox->setMargin(0);
- vbox->setSpacing(0);
-
- QWidget *statusbarContainer = new Utils::StyledBar();
- statusbarContainer->setStyleSheet(QLatin1String("background: #9B9B9B"));
- statusbarContainer->setFixedHeight(statusBarHeight);
- QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer);
- hbox->setMargin(0);
- hbox->setSpacing(0);
-
- hbox->addSpacing(5);
-
- //Status Label
- m_statusLabel = new Utils::StatusLabel;
- hbox->addWidget(m_statusLabel);
- hbox->addWidget(new Utils::StyledSeparator);
-
- const int buttonWidth = 25;
- //Filters
- QToolButton *button = new QToolButton(this);
- button->setAutoRaise(true);
- button->setFixedWidth(buttonWidth);
- m_showLogAction = new Utils::SavedAction(this);
- m_showLogAction->setDefaultValue(true);
- m_showLogAction->setSettingsKey(_(CONSOLE), _(SHOW_LOG));
- m_showLogAction->setText(tr("Log"));
- m_showLogAction->setToolTip(tr("Show debug, log, and info messages."));
- m_showLogAction->setCheckable(true);
- m_showLogAction->setIcon(QIcon(_(":/debugger/images/log.png")));
- button->setDefaultAction(m_showLogAction);
- hbox->addWidget(button);
-
- button = new QToolButton(this);
- button->setAutoRaise(true);
- button->setFixedWidth(buttonWidth);
- m_showWarningAction = new Utils::SavedAction(this);
- m_showWarningAction->setDefaultValue(true);
- m_showWarningAction->setSettingsKey(_(CONSOLE), _(SHOW_WARNING));
- m_showWarningAction->setText(tr("Warning"));
- m_showWarningAction->setToolTip(tr("Show warning messages."));
- m_showWarningAction->setCheckable(true);
- m_showWarningAction->setIcon(QIcon(_(":/debugger/images/warning.png")));
- button->setDefaultAction(m_showWarningAction);
- hbox->addWidget(button);
-
- button = new QToolButton(this);
- button->setAutoRaise(true);
- button->setFixedWidth(buttonWidth);
- m_showErrorAction = new Utils::SavedAction(this);
- m_showErrorAction->setDefaultValue(true);
- m_showErrorAction->setSettingsKey(_(CONSOLE), _(SHOW_ERROR));
- m_showErrorAction->setText(tr("Error"));
- m_showErrorAction->setToolTip(tr("Show error and fatal messages."));
- m_showErrorAction->setCheckable(true);
- m_showErrorAction->setIcon(QIcon(_(":/debugger/images/error.png")));
- button->setDefaultAction(m_showErrorAction);
- hbox->addWidget(button);
- hbox->addWidget(new Utils::StyledSeparator);
-
- //Clear Button
- button = new QToolButton;
- button->setAutoRaise(true);
- button->setFixedWidth(buttonWidth);
- m_clearAction = new QAction(tr("Clear Console"), this);
- m_clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE)));
- button->setDefaultAction(m_clearAction);
- hbox->addWidget(button);
- hbox->addWidget(new Utils::StyledSeparator);
-
- m_treeView = new QtMessageLogView(this);
- m_treeView->setSizePolicy(QSizePolicy::MinimumExpanding,
- QSizePolicy::MinimumExpanding);
-
- m_proxyModel = new QtMessageLogProxyModel(this);
- connect(m_showLogAction, SIGNAL(toggled(bool)),
- m_proxyModel, SLOT(setShowLogs(bool)));
- connect(m_showWarningAction, SIGNAL(toggled(bool)),
- m_proxyModel, SLOT(setShowWarnings(bool)));
- connect(m_showErrorAction, SIGNAL(toggled(bool)),
- m_proxyModel, SLOT(setShowErrors(bool)));
-
- m_treeView->setModel(m_proxyModel);
- connect(m_proxyModel,
- SIGNAL(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)),
- m_treeView->selectionModel(),
- SLOT(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)));
- connect(m_proxyModel,
- SIGNAL(scrollToBottom()),
- m_treeView,
- SLOT(onScrollToBottom()));
-
- m_itemDelegate = new QtMessageLogItemDelegate(this);
- connect(m_treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
- m_itemDelegate, SLOT(currentChanged(QModelIndex,QModelIndex)));
- m_treeView->setItemDelegate(m_itemDelegate);
-
- vbox->addWidget(statusbarContainer);
- vbox->addWidget(m_treeView);
- vbox->addWidget(new Core::FindToolBarPlaceHolder(this));
-
- readSettings();
- connect(Core::ICore::instance(),
- SIGNAL(saveSettingsRequested()), SLOT(writeSettings()));
-
- Aggregation::Aggregate *aggregate = new Aggregation::Aggregate();
- aggregate->add(m_treeView);
- aggregate->add(new Find::TreeViewFind(m_treeView));
-}
-
-QtMessageLogWindow::~QtMessageLogWindow()
-{
- writeSettings();
-}
-
-void QtMessageLogWindow::readSettings()
-{
- QSettings *settings = Core::ICore::settings();
- m_showLogAction->readSettings(settings);
- m_showWarningAction->readSettings(settings);
- m_showErrorAction->readSettings(settings);
-}
-
-void QtMessageLogWindow::showStatus(const QString &context, int timeout)
-{
- m_statusLabel->showStatusMessage(context, timeout);
-}
-
-void QtMessageLogWindow::writeSettings() const
-{
- QSettings *settings = Core::ICore::settings();
- m_showLogAction->writeSettings(settings);
- m_showWarningAction->writeSettings(settings);
- m_showErrorAction->writeSettings(settings);
-}
-
-void QtMessageLogWindow::setModel(QAbstractItemModel *model)
-{
- QtMessageLogHandler *oldHandler = qobject_cast<QtMessageLogHandler *>(
- m_proxyModel->sourceModel());
- if (oldHandler) {
- disconnect(m_clearAction, SIGNAL(triggered()), oldHandler, SLOT(clear()));
- disconnect(oldHandler,
- SIGNAL(selectEditableRow(
- QModelIndex,QItemSelectionModel::SelectionFlags)),
- m_proxyModel,
- SLOT(selectEditableRow(
- QModelIndex,QItemSelectionModel::SelectionFlags)));
- disconnect(oldHandler,
- SIGNAL(rowsInserted(QModelIndex,int,int)),
- m_proxyModel,
- SLOT(onRowsInserted(QModelIndex,int,int)));
- }
-
- QtMessageLogHandler *newHandler = qobject_cast<QtMessageLogHandler *>(model);
- m_proxyModel->setSourceModel(newHandler);
- m_itemDelegate->setItemModel(newHandler);
-
- if (newHandler) {
- connect(m_clearAction, SIGNAL(triggered()), newHandler, SLOT(clear()));
- connect(newHandler,
- SIGNAL(selectEditableRow(
- QModelIndex,QItemSelectionModel::SelectionFlags)),
- m_proxyModel,
- SLOT(selectEditableRow(
- QModelIndex,QItemSelectionModel::SelectionFlags)));
-
- //Scroll to bottom when rows matching current filter settings are inserted
- //Not connecting rowsRemoved as the only way to remove rows is to clear the
- //model which will automatically reset the view.
- connect(newHandler,
- SIGNAL(rowsInserted(QModelIndex,int,int)),
- m_proxyModel,
- SLOT(onRowsInserted(QModelIndex,int,int)));
- }
-}
-
-} // namespace Internal
-} // namespace Debugger
diff --git a/src/plugins/debugger/registerhandler.cpp b/src/plugins/debugger/registerhandler.cpp
index a9d929742b..4d342a928f 100644
--- a/src/plugins/debugger/registerhandler.cpp
+++ b/src/plugins/debugger/registerhandler.cpp
@@ -485,8 +485,9 @@ Qt::ItemFlags RegisterHandler::flags(const QModelIndex &idx) const
void RegisterHandler::removeAll()
{
+ beginResetModel();
m_registers.clear();
- reset();
+ endResetModel();
}
bool RegisterHandler::isEmpty() const
@@ -508,12 +509,13 @@ static inline bool compareRegisterSet(const Registers &r1, const Registers &r2)
void RegisterHandler::setRegisters(const Registers &registers)
{
+ beginResetModel();
m_registers = registers;
const int size = m_registers.size();
for (int r = 0; r < size; r++)
m_registers[r].changed = false;
calculateWidth();
- reset();
+ endResetModel();
}
void RegisterHandler::setAndMarkRegisters(const Registers &registers)
@@ -549,9 +551,10 @@ void RegisterHandler::calculateWidth()
void RegisterHandler::setNumberBase(int base)
{
if (m_base != base) {
+ beginResetModel();
m_base = base;
calculateWidth();
- emit reset();
+ endResetModel();
}
}
diff --git a/src/plugins/debugger/script/scriptengine.cpp b/src/plugins/debugger/script/scriptengine.cpp
index be749cdfc5..eb31b8f701 100644
--- a/src/plugins/debugger/script/scriptengine.cpp
+++ b/src/plugins/debugger/script/scriptengine.cpp
@@ -37,6 +37,7 @@
#include "debuggerstringutils.h"
#include "moduleshandler.h"
#include "registerhandler.h"
+#include "sourceutils.h"
#include "stackhandler.h"
#include "watchhandler.h"
#include "watchutils.h"
@@ -438,9 +439,9 @@ void ScriptEngine::activateFrame(int index)
Q_UNUSED(index)
}
-void ScriptEngine::selectThread(int index)
+void ScriptEngine::selectThread(ThreadId threadId)
{
- Q_UNUSED(index)
+ Q_UNUSED(threadId)
}
bool ScriptEngine::acceptsBreakpoint(BreakpointModelId id) const
@@ -705,7 +706,7 @@ static inline QString msgDebugInsert(const WatchData &d0, const QList<WatchData>
QString rc;
QTextStream str(&rc);
str << "INSERTING " << d0.toString() << '\n';
- foreach(const WatchData &c, children)
+ foreach (const WatchData &c, children)
str << " " << c.toString() << '\n';
return rc;
}
@@ -784,11 +785,10 @@ void ScriptEngine::updateSubItem(const WatchData &data0)
data1.name = it.name();
data.id = m_watchIdCounter++;
m_watchIdToScriptValue.insert(data.id, it.value());
- if (watchHandler()->isExpandedIName(data1.iname)) {
+ if (watchHandler()->isExpandedIName(data1.iname))
data1.setChildrenNeeded();
- } else {
+ else
data1.setChildrenUnneeded();
- }
children.push_back(data1);
}
data.setHasChildren(!children.isEmpty());
diff --git a/src/plugins/debugger/script/scriptengine.h b/src/plugins/debugger/script/scriptengine.h
index c07984928b..96f5e41242 100644
--- a/src/plugins/debugger/script/scriptengine.h
+++ b/src/plugins/debugger/script/scriptengine.h
@@ -85,7 +85,7 @@ private:
void executeJumpToLine(const ContextData &data);
void activateFrame(int index);
- void selectThread(int index);
+ void selectThread(ThreadId threadId);
bool acceptsBreakpoint(BreakpointModelId id) const;
void attemptBreakpointSynchronization();
diff --git a/src/plugins/debugger/shared/hostutils.cpp b/src/plugins/debugger/shared/hostutils.cpp
index 844f17c49c..17a5574432 100644
--- a/src/plugins/debugger/shared/hostutils.cpp
+++ b/src/plugins/debugger/shared/hostutils.cpp
@@ -82,11 +82,6 @@ bool winResumeThread(unsigned long dwThreadId, QString *errorMessage)
return ok;
}
-unsigned long winGetCurrentProcessId()
-{
- return GetCurrentProcessId();
-}
-
bool isWinProcessBeingDebugged(unsigned long pid)
{
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
@@ -199,9 +194,8 @@ void formatWindowsException(unsigned long code, quint64 address,
break;
}
str << ", flags=0x" << flags;
- if (flags == EXCEPTION_NONCONTINUABLE) {
+ if (flags == EXCEPTION_NONCONTINUABLE)
str << " (execution cannot be continued)";
- }
str.setIntegerBase(10);
}
@@ -228,7 +222,16 @@ bool isFatalWinException(long code)
return true;
}
-#endif // Q_OS_WIN
+#else // Q_OS_WIN
+
+bool winResumeThread(unsigned long, QString *) { return false; }
+bool isWinProcessBeingDebugged(unsigned long) { return false; }
+void formatWindowsException(unsigned long , quint64, unsigned long,
+ quint64, quint64, QTextStream &) { }
+bool isFatalWinException(long) { return false; }
+bool isDebuggerWinException(unsigned long) { return false; }
+
+#endif // !Q_OS_WIN
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/shared/hostutils.h b/src/plugins/debugger/shared/hostutils.h
index ffef6a0385..d544b12936 100644
--- a/src/plugins/debugger/shared/hostutils.h
+++ b/src/plugins/debugger/shared/hostutils.h
@@ -40,13 +40,9 @@ QT_END_NAMESPACE
namespace Debugger {
namespace Internal {
-#ifdef Q_OS_WIN
-
// Resume a suspended thread by id.
bool winResumeThread(unsigned long dwThreadId, QString *errorMessage);
-unsigned long winGetCurrentProcessId();
-
bool isWinProcessBeingDebugged(unsigned long pid);
// Special exception codes.
@@ -75,8 +71,6 @@ bool isFatalWinException(long code);
// Check for EXCEPTION_BREAKPOINT, EXCEPTION_SINGLE_STEP
bool isDebuggerWinException(unsigned long code);
-#endif // defined(Q_OS_WIN)
-
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/shared/peutils.cpp b/src/plugins/debugger/shared/peutils.cpp
index aa9f3a1345..10fe3fc564 100644
--- a/src/plugins/debugger/shared/peutils.cpp
+++ b/src/plugins/debugger/shared/peutils.cpp
@@ -261,7 +261,7 @@ bool getPDBFiles(const QString &peExecutableFileName, QStringList *rc, QString *
if (debugSectionCount)
collectPDBfiles(fileMemory, debugDir, debugSectionCount, rc);
success = true;
- } while(false);
+ } while (false);
if (fileMemory)
UnmapViewOfFile(fileMemory);
diff --git a/src/plugins/debugger/snapshothandler.cpp b/src/plugins/debugger/snapshothandler.cpp
index 0069670d91..47792426cf 100644
--- a/src/plugins/debugger/snapshothandler.cpp
+++ b/src/plugins/debugger/snapshothandler.cpp
@@ -213,10 +213,11 @@ Qt::ItemFlags SnapshotHandler::flags(const QModelIndex &index) const
void SnapshotHandler::activateSnapshot(int index)
{
+ beginResetModel();
m_currentIndex = index;
//qDebug() << "ACTIVATING INDEX: " << m_currentIndex << " OF " << size();
debuggerCore()->displayDebugger(at(index), true);
- reset();
+ endResetModel();
}
void SnapshotHandler::createSnapshot(int index)
@@ -239,28 +240,31 @@ void SnapshotHandler::removeSnapshot(int index)
//QString fileName = engine->startParameters().coreFile;
//if (!fileName.isEmpty())
// QFile::remove(fileName);
+ beginResetModel();
m_snapshots.removeAt(index);
if (index == m_currentIndex)
m_currentIndex = -1;
else if (index < m_currentIndex)
--m_currentIndex;
//engine->quitDebugger();
- reset();
+ endResetModel();
}
void SnapshotHandler::removeAll()
{
+ beginResetModel();
m_snapshots.clear();
m_currentIndex = -1;
- reset();
+ endResetModel();
}
void SnapshotHandler::appendSnapshot(DebuggerEngine *engine)
{
+ beginResetModel();
m_snapshots.append(engine);
m_currentIndex = size() - 1;
- reset();
+ endResetModel();
}
void SnapshotHandler::removeSnapshot(DebuggerEngine *engine)
@@ -273,8 +277,9 @@ void SnapshotHandler::removeSnapshot(DebuggerEngine *engine)
void SnapshotHandler::setCurrentIndex(int index)
{
+ beginResetModel();
m_currentIndex = index;
- reset();
+ endResetModel();
}
DebuggerEngine *SnapshotHandler::at(int i) const
diff --git a/src/plugins/debugger/snapshothandler.h b/src/plugins/debugger/snapshothandler.h
index fd9c081a86..c0f3dded92 100644
--- a/src/plugins/debugger/snapshothandler.h
+++ b/src/plugins/debugger/snapshothandler.h
@@ -75,7 +75,7 @@ private:
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
- Q_SLOT void resetModel() { reset(); }
+ Q_SLOT void resetModel() { beginResetModel(); endResetModel(); }
int m_currentIndex;
QList< QPointer<DebuggerEngine> > m_snapshots;
diff --git a/src/plugins/debugger/snapshotwindow.cpp b/src/plugins/debugger/snapshotwindow.cpp
index 123df37de2..116448c4b7 100644
--- a/src/plugins/debugger/snapshotwindow.cpp
+++ b/src/plugins/debugger/snapshotwindow.cpp
@@ -93,7 +93,7 @@ void SnapshotTreeView::contextMenuEvent(QContextMenuEvent *ev)
QAction *actRemove = menu.addAction(tr("Remove Snapshot"));
actRemove->setEnabled(idx.isValid());
-
+
addBaseContextActions(&menu);
QAction *act = menu.exec(ev->globalPos());
diff --git a/src/plugins/debugger/sourcefileshandler.cpp b/src/plugins/debugger/sourcefileshandler.cpp
index 47def06f50..21b7047f88 100644
--- a/src/plugins/debugger/sourcefileshandler.cpp
+++ b/src/plugins/debugger/sourcefileshandler.cpp
@@ -48,9 +48,10 @@ void SourceFilesHandler::clearModel()
{
if (m_shortNames.isEmpty())
return;
+ beginResetModel();
m_shortNames.clear();
m_fullNames.clear();
- reset();
+ endResetModel();
}
QVariant SourceFilesHandler::headerData(int section,
@@ -100,6 +101,7 @@ QVariant SourceFilesHandler::data(const QModelIndex &index, int role) const
void SourceFilesHandler::setSourceFiles(const QMap<QString, QString> &sourceFiles)
{
+ beginResetModel();
m_shortNames.clear();
m_fullNames.clear();
QMap<QString, QString>::ConstIterator it = sourceFiles.begin();
@@ -108,7 +110,7 @@ void SourceFilesHandler::setSourceFiles(const QMap<QString, QString> &sourceFile
m_shortNames.append(it.key());
m_fullNames.append(it.value());
}
- reset();
+ endResetModel();
}
void SourceFilesHandler::removeAll()
diff --git a/src/plugins/debugger/sourcefileshandler.h b/src/plugins/debugger/sourcefileshandler.h
index 84a26d1040..2eb5dd5d40 100644
--- a/src/plugins/debugger/sourcefileshandler.h
+++ b/src/plugins/debugger/sourcefileshandler.h
@@ -55,7 +55,6 @@ public:
Qt::ItemFlags flags(const QModelIndex &index) const;
void clearModel();
- void update() { reset(); }
void setSourceFiles(const QMap<QString, QString> &sourceFiles);
void removeAll();
diff --git a/src/plugins/debugger/sourceutils.cpp b/src/plugins/debugger/sourceutils.cpp
new file mode 100644
index 0000000000..22dc8e34d3
--- /dev/null
+++ b/src/plugins/debugger/sourceutils.cpp
@@ -0,0 +1,431 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "sourceutils.h"
+
+#include "debuggerprotocol.h"
+#include "debuggerstringutils.h"
+#include "watchdata.h"
+#include "watchutils.h"
+
+#include <utils/qtcassert.h>
+
+#include <coreplugin/idocument.h>
+
+#include <texteditor/basetexteditor.h>
+#include <texteditor/basetextmark.h>
+#include <texteditor/itexteditor.h>
+#include <texteditor/texteditorconstants.h>
+#include <coreplugin/editormanager/editormanager.h>
+
+#include <cpptools/cpptoolsconstants.h>
+#include <cpptools/abstracteditorsupport.h>
+
+#include <cpptools/ModelManagerInterface.h>
+#include <cplusplus/ExpressionUnderCursor.h>
+#include <cplusplus/Overview.h>
+#include <Symbols.h>
+#include <Scope.h>
+
+#include <extensionsystem/pluginmanager.h>
+
+#include <QCoreApplication>
+#include <QDateTime>
+#include <QDebug>
+#include <QHash>
+#include <QStringList>
+#include <QTextStream>
+#include <QTime>
+
+#include <QTextCursor>
+#include <QPlainTextEdit>
+
+#include <string.h>
+#include <ctype.h>
+
+enum { debug = 0 };
+
+// Debug helpers for code model. @todo: Move to some CppTools library?
+namespace CPlusPlus {
+
+static void debugCppSymbolRecursion(QTextStream &str, const Overview &o,
+ const Symbol &s, bool doRecurse = true,
+ int recursion = 0)
+{
+ for (int i = 0; i < recursion; i++)
+ str << " ";
+ str << "Symbol: " << o.prettyName(s.name()) << " at line " << s.line();
+ if (s.isFunction())
+ str << " function";
+ if (s.isClass())
+ str << " class";
+ if (s.isDeclaration())
+ str << " declaration";
+ if (s.isBlock())
+ str << " block";
+ if (doRecurse && s.isScope()) {
+ const Scope *scoped = s.asScope();
+ const int size = scoped->memberCount();
+ str << " scoped symbol of " << size << '\n';
+ for (int m = 0; m < size; m++)
+ debugCppSymbolRecursion(str, o, *scoped->memberAt(m), true, recursion + 1);
+ } else {
+ str << '\n';
+ }
+}
+
+QDebug operator<<(QDebug d, const Symbol &s)
+{
+ QString output;
+ CPlusPlus::Overview o;
+ QTextStream str(&output);
+ debugCppSymbolRecursion(str, o, s, true, 0);
+ d.nospace() << output;
+ return d;
+}
+
+QDebug operator<<(QDebug d, const Scope &scope)
+{
+ QString output;
+ Overview o;
+ QTextStream str(&output);
+ const int size = scope.memberCount();
+ str << "Scope of " << size;
+ if (scope.isNamespace())
+ str << " namespace";
+ if (scope.isClass())
+ str << " class";
+ if (scope.isEnum())
+ str << " enum";
+ if (scope.isBlock())
+ str << " block";
+ if (scope.isFunction())
+ str << " function";
+ if (scope.isFunction())
+ str << " prototype";
+#if 0 // ### port me
+ if (const Symbol *owner = &scope) {
+ str << " owner: ";
+ debugCppSymbolRecursion(str, o, *owner, false, 0);
+ } else {
+ str << " 0-owner\n";
+ }
+#endif
+ for (int s = 0; s < size; s++)
+ debugCppSymbolRecursion(str, o, *scope.memberAt(s), true, 2);
+ d.nospace() << output;
+ return d;
+}
+} // namespace CPlusPlus
+
+namespace Debugger {
+namespace Internal {
+
+/* getUninitializedVariables(): Get variables that are not initialized
+ * at a certain line of a function from the code model to be able to
+ * indicate them as not in scope in the locals view.
+ * Find document + function in the code model, do a double check and
+ * collect declarative symbols that are in the function past or on
+ * the current line. blockRecursion() recurses up the scopes
+ * and collect symbols declared past or on the current line.
+ * Recursion goes up from the innermost scope, keeping a map
+ * of occurrences seen, to be able to derive the names of
+ * shadowed variables as the debugger sees them:
+\code
+int x; // Occurrence (1), should be reported as "x <shadowed 1>"
+if (true) {
+ int x = 5; (2) // Occurrence (2), should be reported as "x"
+}
+\endcode
+ */
+
+typedef QHash<QString, int> SeenHash;
+
+static void blockRecursion(const CPlusPlus::Overview &overview,
+ const CPlusPlus::Scope *scope,
+ unsigned line,
+ QStringList *uninitializedVariables,
+ SeenHash *seenHash,
+ int level = 0)
+{
+ // Go backwards in case someone has identical variables in the same scope.
+ // Fixme: loop variables or similar are currently seen in the outer scope
+ for (int s = scope->memberCount() - 1; s >= 0; --s){
+ const CPlusPlus::Symbol *symbol = scope->memberAt(s);
+ if (symbol->isDeclaration()) {
+ // Find out about shadowed symbols by bookkeeping
+ // the already seen occurrences in a hash.
+ const QString name = overview.prettyName(symbol->name());
+ SeenHash::iterator it = seenHash->find(name);
+ if (it == seenHash->end())
+ it = seenHash->insert(name, 0);
+ else
+ ++(it.value());
+ // Is the declaration on or past the current line, that is,
+ // the variable not initialized.
+ if (symbol->line() >= line)
+ uninitializedVariables->push_back(WatchData::shadowedName(name, it.value()));
+ }
+ }
+ // Next block scope.
+ if (const CPlusPlus::Scope *enclosingScope = scope->enclosingBlock())
+ blockRecursion(overview, enclosingScope, line, uninitializedVariables, seenHash, level + 1);
+}
+
+// Inline helper with integer error return codes.
+static inline
+int getUninitializedVariablesI(const CPlusPlus::Snapshot &snapshot,
+ const QString &functionName,
+ const QString &file,
+ int line,
+ QStringList *uninitializedVariables)
+{
+ uninitializedVariables->clear();
+ // Find document
+ if (snapshot.isEmpty() || functionName.isEmpty() || file.isEmpty() || line < 1)
+ return 1;
+ const CPlusPlus::Snapshot::const_iterator docIt = snapshot.find(file);
+ if (docIt == snapshot.end())
+ return 2;
+ const CPlusPlus::Document::Ptr doc = docIt.value();
+ // Look at symbol at line and find its function. Either it is the
+ // function itself or some expression/variable.
+ const CPlusPlus::Symbol *symbolAtLine = doc->lastVisibleSymbolAt(line, 0);
+ if (!symbolAtLine)
+ return 4;
+ // First figure out the function to do a safety name check
+ // and the innermost scope at cursor position
+ const CPlusPlus::Function *function = 0;
+ const CPlusPlus::Scope *innerMostScope = 0;
+ if (symbolAtLine->isFunction()) {
+ function = symbolAtLine->asFunction();
+ if (function->memberCount() == 1) // Skip over function block
+ if (CPlusPlus::Block *block = function->memberAt(0)->asBlock())
+ innerMostScope = block;
+ } else {
+ if (const CPlusPlus::Scope *functionScope = symbolAtLine->enclosingFunction()) {
+ function = functionScope->asFunction();
+ innerMostScope = symbolAtLine->isBlock() ?
+ symbolAtLine->asBlock() :
+ symbolAtLine->enclosingBlock();
+ }
+ }
+ if (!function || !innerMostScope)
+ return 7;
+ // Compare function names with a bit off fuzz,
+ // skipping modules from a CDB symbol "lib!foo" or namespaces
+ // that the code model does not show at this point
+ CPlusPlus::Overview overview;
+ const QString name = overview.prettyName(function->name());
+ if (!functionName.endsWith(name))
+ return 11;
+ if (functionName.size() > name.size()) {
+ const char previousChar = functionName.at(functionName.size() - name.size() - 1).toLatin1();
+ if (previousChar != ':' && previousChar != '!' )
+ return 11;
+ }
+ // Starting from the innermost block scope, collect declarations.
+ SeenHash seenHash;
+ blockRecursion(overview, innerMostScope, line, uninitializedVariables, &seenHash);
+ return 0;
+}
+
+bool getUninitializedVariables(const CPlusPlus::Snapshot &snapshot,
+ const QString &function,
+ const QString &file,
+ int line,
+ QStringList *uninitializedVariables)
+{
+ const int rc = getUninitializedVariablesI(snapshot, function, file, line, uninitializedVariables);
+ if (debug) {
+ QString msg;
+ QTextStream str(&msg);
+ str << "getUninitializedVariables() " << function << ' ' << file << ':' << line
+ << " returns (int) " << rc << " '"
+ << uninitializedVariables->join(QString(QLatin1Char(','))) << '\'';
+ if (rc)
+ str << " of " << snapshot.size() << " documents";
+ qDebug() << msg;
+ }
+ return rc == 0;
+}
+
+//QByteArray gdbQuoteTypes(const QByteArray &type)
+//{
+// // gdb does not understand sizeof(Core::IDocument*).
+// // "sizeof('Core::IDocument*')" is also not acceptable,
+// // it needs to be "sizeof('Core::IDocument'*)"
+// //
+// // We never will have a perfect solution here (even if we had a full blown
+// // C++ parser as we do not have information on what is a type and what is
+// // a variable name. So "a<b>::c" could either be two comparisons of values
+// // 'a', 'b' and '::c', or a nested type 'c' in a template 'a<b>'. We
+// // assume here it is the latter.
+// //return type;
+
+// // (*('myns::QPointer<myns::QObject>*'*)0x684060)" is not acceptable
+// // (*('myns::QPointer<myns::QObject>'**)0x684060)" is acceptable
+// if (isPointerType(type))
+// return gdbQuoteTypes(stripPointerType(type)) + '*';
+
+// QByteArray accu;
+// QByteArray result;
+// int templateLevel = 0;
+
+// const char colon = ':';
+// const char singleQuote = '\'';
+// const char lessThan = '<';
+// const char greaterThan = '>';
+// for (int i = 0; i != type.size(); ++i) {
+// const char c = type.at(i);
+// if (isLetterOrNumber(c) || c == '_' || c == colon || c == ' ') {
+// accu += c;
+// } else if (c == lessThan) {
+// ++templateLevel;
+// accu += c;
+// } else if (c == greaterThan) {
+// --templateLevel;
+// accu += c;
+// } else if (templateLevel > 0) {
+// accu += c;
+// } else {
+// if (accu.contains(colon) || accu.contains(lessThan))
+// result += singleQuote + accu + singleQuote;
+// else
+// result += accu;
+// accu.clear();
+// result += c;
+// }
+// }
+// if (accu.contains(colon) || accu.contains(lessThan))
+// result += singleQuote + accu + singleQuote;
+// else
+// result += accu;
+// //qDebug() << "GDB_QUOTING" << type << " TO " << result;
+
+// return result;
+//}
+
+// Utilities to decode string data returned by the dumper helpers.
+
+
+// Editor tooltip support
+bool isCppEditor(Core::IEditor *editor)
+{
+ using namespace CppTools::Constants;
+ const Core::IDocument *document= editor->document();
+ if (!document)
+ return false;
+ const QByteArray mimeType = document->mimeType().toLatin1();
+ return mimeType == C_SOURCE_MIMETYPE
+ || mimeType == CPP_SOURCE_MIMETYPE
+ || mimeType == CPP_HEADER_MIMETYPE
+ || mimeType == OBJECTIVE_CPP_SOURCE_MIMETYPE;
+}
+
+// Return the Cpp expression, and, if desired, the function
+QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
+ int *line, int *column, QString *function /* = 0 */)
+{
+ using namespace CppTools;
+ using namespace CPlusPlus;
+ *line = *column = 0;
+ if (function)
+ function->clear();
+
+ const QPlainTextEdit *plaintext = qobject_cast<QPlainTextEdit*>(editor->widget());
+ if (!plaintext)
+ return QString();
+
+ QString expr = plaintext->textCursor().selectedText();
+ CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
+ if (expr.isEmpty() && modelManager) {
+ QTextCursor tc(plaintext->document());
+ tc.setPosition(pos);
+
+ const QChar ch = editor->characterAt(pos);
+ if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
+ tc.movePosition(QTextCursor::EndOfWord);
+
+ // Fetch the expression's code.
+ CPlusPlus::ExpressionUnderCursor expressionUnderCursor;
+ expr = expressionUnderCursor(tc);
+ *column = tc.positionInBlock();
+ *line = tc.blockNumber();
+ } else {
+ const QTextCursor tc = plaintext->textCursor();
+ *column = tc.positionInBlock();
+ *line = tc.blockNumber();
+ }
+
+ if (function && !expr.isEmpty())
+ if (const Core::IDocument *document= editor->document())
+ if (modelManager)
+ *function = AbstractEditorSupport::functionAt(modelManager,
+ document->fileName(), *line, *column);
+
+ return expr;
+}
+
+// Ensure an expression can be added as side-effect
+// free debugger expression.
+QString fixCppExpression(const QString &expIn)
+{
+ QString exp = expIn.trimmed();;
+ // Extract the first identifier, everything else is considered
+ // too dangerous.
+ int pos1 = 0, pos2 = exp.size();
+ bool inId = false;
+ for (int i = 0; i != exp.size(); ++i) {
+ const QChar c = exp.at(i);
+ const bool isIdChar = c.isLetterOrNumber() || c.unicode() == '_';
+ if (inId && !isIdChar) {
+ pos2 = i;
+ break;
+ }
+ if (!inId && isIdChar) {
+ inId = true;
+ pos1 = i;
+ }
+ }
+ exp = exp.mid(pos1, pos2 - pos1);
+ return removeObviousSideEffects(exp);
+}
+
+QString cppFunctionAt(const QString &fileName, int line)
+{
+ using namespace CppTools;
+ using namespace CPlusPlus;
+ CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
+ return AbstractEditorSupport::functionAt(modelManager,
+ fileName, line, 1);
+}
+
+} // namespace Internal
+} // namespace Debugger
diff --git a/src/plugins/debugger/sourceutils.h b/src/plugins/debugger/sourceutils.h
new file mode 100644
index 0000000000..12bea32f19
--- /dev/null
+++ b/src/plugins/debugger/sourceutils.h
@@ -0,0 +1,60 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef SOURCE_UTILS_H
+#define SOURCE_UTILS_H
+
+#include <QSet>
+#include <QString>
+
+namespace TextEditor { class ITextEditor; }
+namespace Core { class IEditor; }
+namespace CPlusPlus { class Snapshot; }
+
+namespace Debugger {
+namespace Internal {
+
+// Editor tooltip support
+bool isCppEditor(Core::IEditor *editor);
+QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
+ int *line, int *column, QString *function = 0);
+QString fixCppExpression(const QString &exp);
+QString cppFunctionAt(const QString &fileName, int line);
+
+// Get variables that are not initialized at a certain line
+// of a function from the code model. Shadowed variables will
+// be reported using the debugger naming conventions '<shadowed n>'
+bool getUninitializedVariables(const CPlusPlus::Snapshot &snapshot,
+ const QString &function, const QString &file, int line,
+ QStringList *uninitializedVariables);
+
+} // namespace Internal
+} // namespace Debugger
+
+#endif // SOURCE_UTILS_H
diff --git a/src/plugins/debugger/stackhandler.cpp b/src/plugins/debugger/stackhandler.cpp
index 089dd9e0c3..5dbade1a1e 100644
--- a/src/plugins/debugger/stackhandler.cpp
+++ b/src/plugins/debugger/stackhandler.cpp
@@ -183,13 +183,15 @@ void StackHandler::setCurrentIndex(int level)
void StackHandler::removeAll()
{
+ beginResetModel();
m_stackFrames.clear();
setCurrentIndex(-1);
- reset();
+ endResetModel();
}
void StackHandler::setFrames(const StackFrames &frames, bool canExpand)
{
+ beginResetModel();
m_resetLocationScheduled = false;
m_contentsValid = true;
m_canExpand = canExpand;
@@ -198,7 +200,7 @@ void StackHandler::setFrames(const StackFrames &frames, bool canExpand)
setCurrentIndex(0);
else
m_currentIndex = -1;
- reset();
+ endResetModel();
emit stackChanged();
}
@@ -216,8 +218,9 @@ void StackHandler::scheduleResetLocation()
void StackHandler::resetLocation()
{
if (m_resetLocationScheduled) {
+ beginResetModel();
m_resetLocationScheduled = false;
- reset();
+ endResetModel();
}
}
diff --git a/src/plugins/debugger/stackhandler.h b/src/plugins/debugger/stackhandler.h
index 580a5b8a90..8ffb7c767d 100644
--- a/src/plugins/debugger/stackhandler.h
+++ b/src/plugins/debugger/stackhandler.h
@@ -93,7 +93,7 @@ private:
QVariant data(const QModelIndex &index, int role) const;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
- Q_SLOT void resetModel() { reset(); }
+ Q_SLOT void resetModel() { beginResetModel(); endResetModel(); }
StackFrames m_stackFrames;
int m_currentIndex;
diff --git a/src/plugins/debugger/threaddata.h b/src/plugins/debugger/threaddata.h
index 9e4a0a6d63..15927dc174 100644
--- a/src/plugins/debugger/threaddata.h
+++ b/src/plugins/debugger/threaddata.h
@@ -30,24 +30,49 @@
#ifndef THREADDATA_H
#define THREADDATA_H
-#include <QVector>
#include <QString>
+#include <QVector>
namespace Debugger {
namespace Internal {
////////////////////////////////////////////////////////////////////////
//
+// ThreadId
+//
+////////////////////////////////////////////////////////////////////////
+
+/*! A typesafe identifier. */
+class ThreadId
+{
+public:
+ ThreadId() : m_id(-1) {}
+ explicit ThreadId(qint64 id) : m_id(id) {}
+
+ bool isValid() const { return m_id != -1; }
+ qint64 raw() const { return m_id; }
+ bool operator==(const ThreadId other) const { return m_id == other.m_id; }
+
+private:
+ qint64 m_id;
+};
+
+////////////////////////////////////////////////////////////////////////
+//
// ThreadData
//
////////////////////////////////////////////////////////////////////////
-/*! A structure containing information about a single thread */
+/*! A structure containing information about a single thread. */
struct ThreadData
{
- ThreadData(quint64 threadid = 0)
- : id(threadid), frameLevel(-1), address (0), lineNumber(-1)
- {}
+ ThreadData()
+ {
+ frameLevel = -1;
+ lineNumber = -1;
+ address = 0;
+ stopped = true;
+ }
enum {
IdColumn,
@@ -58,9 +83,12 @@ struct ThreadData
StateColumn,
NameColumn,
TargetIdColumn,
+ DetailsColumn,
CoreColumn,
ComboNameColumn,
- ColumnCount = CoreColumn
+ ColumnCount = CoreColumn,
+
+ IdRole = Qt::UserRole
};
void notifyRunning() // Clear state information.
@@ -71,21 +99,25 @@ struct ThreadData
frameLevel = -1;
state.clear();
lineNumber = -1;
+ stopped = false;
}
// Permanent data.
- quint64 id;
+ ThreadId id;
+ QByteArray groupId;
QString targetId;
QString core;
+ bool stopped;
// State information when stopped.
qint32 frameLevel;
+ qint32 lineNumber;
quint64 address;
QString function;
QString module;
QString fileName;
+ QString details;
QString state;
- qint32 lineNumber;
QString name;
};
diff --git a/src/plugins/debugger/threadshandler.cpp b/src/plugins/debugger/threadshandler.cpp
index d563748e9d..1c4d1d173b 100644
--- a/src/plugins/debugger/threadshandler.cpp
+++ b/src/plugins/debugger/threadshandler.cpp
@@ -28,11 +28,13 @@
****************************************************************************/
#include "threadshandler.h"
-#include "gdb/gdbmi.h"
-#include "watchutils.h"
#include "debuggerconstants.h"
#include "debuggercore.h"
+#include "debuggerprotocol.h"
+#include "watchutils.h"
+
+#include <utils/qtcassert.h>
#include <QDebug>
#include <QTextStream>
@@ -41,6 +43,32 @@
namespace Debugger {
namespace Internal {
+void mergeThreadData(ThreadData &data, const ThreadData &other)
+{
+ if (!other.core.isEmpty())
+ data.core = other.core;
+ if (!other.fileName.isEmpty())
+ data.fileName = other.fileName;
+ if (!other.targetId.isEmpty())
+ data.targetId = other.targetId;
+ if (!other.name.isEmpty())
+ data.name = other.name;
+ if (other.frameLevel != -1)
+ data.frameLevel = other.frameLevel;
+ if (!other.function.isEmpty())
+ data.function = other.function;
+ if (!other.address)
+ data.address = other.address;
+ if (!other.module.isEmpty())
+ data.module = other.module;
+ if (!other.details.isEmpty())
+ data.details = other.details;
+ if (!other.state.isEmpty())
+ data.state = other.state;
+ if (other.lineNumber != -1)
+ data.lineNumber = other.lineNumber;
+}
+
////////////////////////////////////////////////////////////////////////
//
// ThreadsHandler
@@ -56,10 +84,13 @@ static QString threadToolTip(const ThreadData &thread)
QTextStream str(&rc);
str << "<html><head/><body><table>"
<< start << ThreadsHandler::tr("Thread&nbsp;id:")
- << sep << thread.id << end;
+ << sep << thread.id.raw() << end;
if (!thread.targetId.isEmpty())
str << start << ThreadsHandler::tr("Target&nbsp;id:")
<< sep << thread.targetId << end;
+ if (!thread.groupId.isEmpty())
+ str << start << ThreadsHandler::tr("Group&nbsp;id:")
+ << sep << thread.groupId << end;
if (!thread.name.isEmpty())
str << start << ThreadsHandler::tr("Name:")
<< sep << thread.name << end;
@@ -98,14 +129,13 @@ static QString threadToolTip(const ThreadData &thread)
*/
ThreadsHandler::ThreadsHandler()
- : m_currentIndex(0),
+ : m_currentIndex(-1),
m_positionIcon(QLatin1String(":/debugger/images/location_16.png")),
m_emptyIcon(QLatin1String(":/debugger/images/debugger_empty_14.png"))
{
m_resetLocationScheduled = false;
- m_contentsValid = false;
- m_proxyModel = new QSortFilterProxyModel(this);
- m_proxyModel->setSourceModel(this);
+// m_proxyModel = new QSortFilterProxyModel(this);
+// m_proxyModel->setSourceModel(this);
}
int ThreadsHandler::rowCount(const QModelIndex &parent) const
@@ -132,7 +162,7 @@ QVariant ThreadsHandler::data(const QModelIndex &index, int role) const
case Qt::DisplayRole:
switch (index.column()) {
case ThreadData::IdColumn:
- return thread.id;
+ return thread.id.raw();
case ThreadData::FunctionColumn:
return thread.function;
case ThreadData::FileColumn:
@@ -154,8 +184,10 @@ QVariant ThreadsHandler::data(const QModelIndex &index, int role) const
return thread.targetId;
case ThreadData::NameColumn:
return thread.name;
+ case ThreadData::DetailsColumn:
+ return thread.details;
case ThreadData::ComboNameColumn:
- return QString::fromLatin1("#%1 %2").arg(thread.id).arg(thread.name);
+ return QString::fromLatin1("#%1 %2").arg(thread.id.raw()).arg(thread.name);
}
case Qt::ToolTipRole:
return threadToolTip(thread);
@@ -164,6 +196,8 @@ QVariant ThreadsHandler::data(const QModelIndex &index, int role) const
if (index.column() == 0)
return (index.row() == m_currentIndex) ? m_positionIcon : m_emptyIcon;
break;
+ case ThreadData::IdRole:
+ return thread.id.raw();
default:
break;
}
@@ -192,6 +226,8 @@ QVariant ThreadsHandler::headerData
return tr("State");
case ThreadData::TargetIdColumn:
return tr("Target ID");
+ case ThreadData::DetailsColumn:
+ return tr("Details");
case ThreadData::NameColumn:
return tr("Name");
}
@@ -200,60 +236,87 @@ QVariant ThreadsHandler::headerData
Qt::ItemFlags ThreadsHandler::flags(const QModelIndex &index) const
{
- return m_contentsValid ? QAbstractTableModel::flags(index) : Qt::ItemFlags(0);
+ const int row = index.row();
+ const bool stopped = row >= 0 && row < m_threads.size()
+ && m_threads.at(row).stopped;
+ return stopped ? QAbstractTableModel::flags(index) : Qt::ItemFlags(0);
}
-int ThreadsHandler::currentThreadId() const
+ThreadId ThreadsHandler::currentThread() const
{
if (m_currentIndex < 0 || m_currentIndex >= m_threads.size())
- return -1;
+ return ThreadId();
return m_threads[m_currentIndex].id;
}
-void ThreadsHandler::setCurrentThread(int index)
+ThreadId ThreadsHandler::threadAt(int index) const
+{
+ QTC_ASSERT(index >= 0 && index < m_threads.size(), return ThreadId());
+ return m_threads[index].id;
+}
+
+void ThreadsHandler::setCurrentThread(ThreadId id)
{
+ const int index = indexOf(id);
if (index == m_currentIndex)
return;
+ if (index == -1) {
+ qWarning("ThreadsHandler::setCurrentThreadId: No such thread %d.", int(id.raw()));
+ return;
+ }
+
// Emit changed for previous frame.
- QModelIndex i = ThreadsHandler::index(m_currentIndex, 0);
- emit dataChanged(i, i);
+ if (m_currentIndex != -1)
+ dataChanged(m_currentIndex);
m_currentIndex = index;
// Emit changed for new frame.
- i = ThreadsHandler::index(m_currentIndex, 0);
- emit dataChanged(i, i);
+ dataChanged(m_currentIndex);
updateThreadBox();
}
-void ThreadsHandler::setCurrentThreadId(int id)
+int ThreadsHandler::indexOf(ThreadId threadId) const
{
- const int index = indexOf(id);
- if (index != -1)
- setCurrentThread(index);
- else
- qWarning("ThreadsHandler::setCurrentThreadId: No such thread %d.", id);
-}
-
-int ThreadsHandler::indexOf(quint64 threadId) const
-{
- const int count = m_threads.size();
- for (int i = 0; i < count; ++i)
+ for (int i = m_threads.size(); --i >= 0; )
if (m_threads.at(i).id == threadId)
return i;
return -1;
}
+void ThreadsHandler::updateThread(const ThreadData &thread)
+{
+ const int i = indexOf(thread.id);
+ if (i == -1) {
+ beginInsertRows(QModelIndex(), m_threads.size(), m_threads.size());
+ m_threads.append(thread);
+ endInsertRows();
+ } else {
+ mergeThreadData(m_threads[i], thread);
+ dataChanged(i);
+ }
+}
+
+void ThreadsHandler::removeThread(ThreadId threadId)
+{
+ const int i = indexOf(threadId);
+ if (i == -1)
+ return;
+ beginRemoveRows(QModelIndex(), i, i);
+ m_threads.remove(i);
+ endRemoveRows();
+}
+
void ThreadsHandler::setThreads(const Threads &threads)
{
+ beginResetModel();
m_threads = threads;
if (m_currentIndex >= m_threads.size())
m_currentIndex = -1;
m_resetLocationScheduled = false;
- m_contentsValid = true;
- reset();
+ endResetModel();
updateThreadBox();
}
@@ -261,53 +324,123 @@ void ThreadsHandler::updateThreadBox()
{
QStringList list;
foreach (const ThreadData &thread, m_threads)
- list.append(QString::fromLatin1("#%1 %2").arg(thread.id).arg(thread.name));
+ list.append(QString::fromLatin1("#%1 %2").arg(thread.id.raw()).arg(thread.name));
debuggerCore()->setThreads(list, m_currentIndex);
}
+void ThreadsHandler::dataChanged(int index)
+{
+ Q_UNUSED(index);
+ layoutChanged();
+}
+
Threads ThreadsHandler::threads() const
{
return m_threads;
}
+ThreadData ThreadsHandler::thread(ThreadId id) const
+{
+ const int i = indexOf(id);
+ return i == -1 ? ThreadData() : m_threads.at(i);
+}
+
void ThreadsHandler::removeAll()
{
+ beginResetModel();
m_threads.clear();
- m_currentIndex = 0;
- reset();
+ m_currentIndex = -1;
+ endResetModel();
}
-void ThreadsHandler::notifyRunning()
+void ThreadsHandler::notifyRunning(const QByteArray &data)
{
- // Threads stopped (that is, address != 0 showing)?
- if (m_threads.empty())
- return;
- if (m_threads.front().address == 0)
- return;
- const Threads::iterator end = m_threads.end();
- for (Threads::iterator it = m_threads.begin(); it != end; ++it)
- it->notifyRunning();
- emit dataChanged(index(0, 1),
- index(m_threads.size() - 1, ThreadData::ColumnCount - 1));
+ if (data.isEmpty() || data == "all") {
+ notifyAllRunning();
+ } else {
+ bool ok;
+ qlonglong id = data.toLongLong(&ok);
+ if (ok)
+ notifyRunning(ThreadId(id));
+ else // FIXME
+ notifyAllRunning();
+ }
+}
+
+void ThreadsHandler::notifyAllRunning()
+{
+ for (int i = m_threads.size(); --i >= 0; )
+ m_threads[i].notifyRunning();
+ layoutChanged();
+}
+
+void ThreadsHandler::notifyRunning(ThreadId id)
+{
+ int i = indexOf(id);
+ if (i >= 0) {
+ m_threads[i].notifyRunning();
+ dataChanged(i);
+ }
+}
+
+void ThreadsHandler::notifyStopped(const QByteArray &data)
+{
+ if (data.isEmpty() || data == "all") {
+ notifyAllStopped();
+ } else {
+ bool ok;
+ qlonglong id = data.toLongLong(&ok);
+ if (ok)
+ notifyRunning(ThreadId(id));
+ else // FIXME
+ notifyAllStopped();
+ }
}
-Threads ThreadsHandler::parseGdbmiThreads(const GdbMi &data, int *currentThread)
+void ThreadsHandler::notifyAllStopped()
+{
+ for (int i = m_threads.size(); --i >= 0; )
+ m_threads[i].stopped = true;
+ layoutChanged();
+}
+
+void ThreadsHandler::notifyStopped(ThreadId id)
+{
+ int i = indexOf(id);
+ if (i >= 0) {
+ m_threads[i].stopped = true;
+ dataChanged(i);
+ }
+}
+
+void ThreadsHandler::updateThreads(const GdbMi &data)
{
// ^done,threads=[{id="1",target-id="Thread 0xb7fdc710 (LWP 4264)",
// frame={level="0",addr="0x080530bf",func="testQString",args=[],
// file="/.../app.cpp",fullname="/../app.cpp",line="1175"},
// state="stopped",core="0"}],current-thread-id="1"
+
+ // Emit changed for previous frame.
+ if (m_currentIndex != -1) {
+ dataChanged(m_currentIndex);
+ m_currentIndex = -1;
+ }
+
+ ThreadId currentId;
+ const GdbMi current = data.findChild("current-thread-id");
+ if (current.isValid())
+ currentId = ThreadId(current.data().toLongLong());
+
const QList<GdbMi> items = data.findChild("threads").children();
const int n = items.size();
- Threads threads;
- threads.reserve(n);
for (int index = 0; index != n; ++index) {
bool ok = false;
const GdbMi item = items.at(index);
const GdbMi frame = item.findChild("frame");
ThreadData thread;
- thread.id = item.findChild("id").data().toInt();
+ thread.id = ThreadId(item.findChild("id").data().toInt());
thread.targetId = QString::fromLatin1(item.findChild("target-id").data());
+ thread.details = QString::fromLatin1(item.findChild("details").data());
thread.core = QString::fromLatin1(item.findChild("core").data());
thread.state = QString::fromLatin1(item.findChild("state").data());
thread.address = frame.findChild("addr").data().toULongLong(&ok, 0);
@@ -315,32 +448,39 @@ Threads ThreadsHandler::parseGdbmiThreads(const GdbMi &data, int *currentThread)
thread.fileName = QString::fromLatin1(frame.findChild("fullname").data());
thread.lineNumber = frame.findChild("line").data().toInt();
thread.module = QString::fromLocal8Bit(frame.findChild("from").data());
+ thread.stopped = true;
// Non-GDB (Cdb2) output name here.
thread.name = QString::fromLatin1(frame.findChild("name").data());
- threads.append(thread);
+ if (thread.state == QLatin1String("running"))
+ thread.stopped = false;
+ if (thread.id == currentId)
+ m_currentIndex = index;
+ updateThread(thread);
}
- if (currentThread)
- *currentThread = data.findChild("current-thread-id").data().toInt();
- return threads;
+
+ if (m_currentIndex != -1)
+ dataChanged(m_currentIndex);
+
+ updateThreadBox();
}
void ThreadsHandler::scheduleResetLocation()
{
m_resetLocationScheduled = true;
- m_contentsValid = false;
}
void ThreadsHandler::resetLocation()
{
if (m_resetLocationScheduled) {
m_resetLocationScheduled = false;
- reset();
+ layoutChanged();
}
}
QAbstractItemModel *ThreadsHandler::model()
{
- return m_proxyModel;
+ return this;
+ //return m_proxyModel;
}
} // namespace Internal
diff --git a/src/plugins/debugger/threadshandler.h b/src/plugins/debugger/threadshandler.h
index 6b3c93b825..4b717eae31 100644
--- a/src/plugins/debugger/threadshandler.h
+++ b/src/plugins/debugger/threadshandler.h
@@ -57,26 +57,35 @@ class ThreadsHandler : public QAbstractTableModel
public:
ThreadsHandler();
- int currentThread() const { return m_currentIndex; }
- void setCurrentThread(int index);
- int currentThreadId() const;
- void setCurrentThreadId(int id);
- int indexOf(quint64 threadId) const;
+ int currentThreadIndex() const { return m_currentIndex; }
+ ThreadId currentThread() const;
+ ThreadId threadAt(int index) const;
+ void setCurrentThread(ThreadId id);
+ void updateThread(const ThreadData &thread);
+ void updateThreads(const GdbMi &data);
+
+ void removeThread(ThreadId threadId);
void setThreads(const Threads &threads);
void removeAll();
Threads threads() const;
+ ThreadData thread(ThreadId id) const;
QAbstractItemModel *model();
// Clear out all frame information
- void notifyRunning();
+ void notifyRunning(const QByteArray &data);
+ void notifyRunning(ThreadId id);
+ void notifyAllRunning();
- static Threads parseGdbmiThreads(const GdbMi &data, int *currentThread = 0);
+ void notifyStopped(const QByteArray &data);
+ void notifyStopped(ThreadId id);
+ void notifyAllStopped();
void resetLocation();
void scheduleResetLocation();
private:
+ int indexOf(ThreadId threadId) const;
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
@@ -84,6 +93,7 @@ private:
int role = Qt::DisplayRole) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
void updateThreadBox();
+ void dataChanged(int index);
Threads m_threads;
int m_currentIndex;
@@ -91,9 +101,8 @@ private:
const QIcon m_emptyIcon;
bool m_resetLocationScheduled;
- bool m_contentsValid;
- QSortFilterProxyModel *m_proxyModel;
+ //QSortFilterProxyModel *m_proxyModel;
};
} // namespace Internal
diff --git a/src/plugins/debugger/threadswindow.cpp b/src/plugins/debugger/threadswindow.cpp
index c588793bfa..99ace3cd1e 100644
--- a/src/plugins/debugger/threadswindow.cpp
+++ b/src/plugins/debugger/threadswindow.cpp
@@ -53,7 +53,8 @@ ThreadsTreeView::ThreadsTreeView()
void ThreadsTreeView::rowActivated(const QModelIndex &index)
{
- debuggerCore()->currentEngine()->selectThread(index.row());
+ ThreadId id = ThreadId(index.data(ThreadData::IdRole).toLongLong());
+ debuggerCore()->currentEngine()->selectThread(id);
}
void ThreadsTreeView::setModel(QAbstractItemModel *model)
@@ -64,6 +65,7 @@ void ThreadsTreeView::setModel(QAbstractItemModel *model)
resizeColumnToContents(ThreadData::NameColumn);
resizeColumnToContents(ThreadData::StateColumn);
resizeColumnToContents(ThreadData::TargetIdColumn);
+ resizeColumnToContents(ThreadData::DetailsColumn);
}
void ThreadsTreeView::contextMenuEvent(QContextMenuEvent *ev)
diff --git a/src/plugins/debugger/watchdata.cpp b/src/plugins/debugger/watchdata.cpp
index c7665ebcdb..cfbaad22d1 100644
--- a/src/plugins/debugger/watchdata.cpp
+++ b/src/plugins/debugger/watchdata.cpp
@@ -27,11 +27,14 @@
**
****************************************************************************/
+// NOTE: Don't add dependencies to other files.
+// This is used in the debugger auto-tests.
+
#include "watchdata.h"
#include "watchutils.h"
-#include <QTextStream>
#include <QTextDocument>
+#include <QTextStream>
#include <QDebug>
////////////////////////////////////////////////////////////////////
diff --git a/src/plugins/debugger/watchdelegatewidgets.cpp b/src/plugins/debugger/watchdelegatewidgets.cpp
index 2a8e6bbdef..5484f51acc 100644
--- a/src/plugins/debugger/watchdelegatewidgets.cpp
+++ b/src/plugins/debugger/watchdelegatewidgets.cpp
@@ -90,10 +90,10 @@ IntegerValidator::IntegerValidator(QObject *parent) :
bool IntegerValidator::isCharAcceptable(const QChar &c, int base)
{
if (c.isLetter())
- return base == 16 && c.toLower().toAscii() <= 'f';
+ return base == 16 && c.toLower().toLatin1() <= 'f';
if (!c.isDigit())
return false;
- const int digit = c.toAscii() - '0';
+ const int digit = c.toLatin1() - '0';
if (base == 8 && digit > 7)
return false;
if (base == 2 && digit > 1)
@@ -134,11 +134,10 @@ QValidator::State IntegerValidator::validateEntry(const QString &s, int base, bo
if (bigInt)
return QValidator::Acceptable;
bool ok;
- if (signedV) {
+ if (signedV)
s.toLongLong(&ok, base);
- } else {
+ else
s.toULongLong(&ok, base);
- }
return ok ? QValidator::Acceptable : QValidator::Intermediate;
}
diff --git a/src/plugins/debugger/watchhandler.cpp b/src/plugins/debugger/watchhandler.cpp
index 5b5e9f31c2..219bb8b2c0 100644
--- a/src/plugins/debugger/watchhandler.cpp
+++ b/src/plugins/debugger/watchhandler.cpp
@@ -30,11 +30,13 @@
#include "watchhandler.h"
#include "breakhandler.h"
-#include "debuggerinternalconstants.h"
#include "debuggeractions.h"
#include "debuggercore.h"
-#include "debuggerengine.h"
#include "debuggerdialogs.h"
+#include "debuggerengine.h"
+#include "debuggerinternalconstants.h"
+#include "debuggerprotocol.h"
+#include "imageviewer.h"
#include "watchutils.h"
#include <utils/qtcassert.h>
@@ -52,6 +54,7 @@
#include <QLabel>
#include <QTextEdit>
+#include <QTabWidget>
#include <ctype.h>
#include <utils/qtcassert.h>
@@ -144,6 +147,26 @@ private:
//
///////////////////////////////////////////////////////////////////////
+class SeparateViewWidget : public QTabWidget
+{
+ Q_OBJECT
+
+public:
+ SeparateViewWidget(QWidget *parent) : QTabWidget(parent)
+ {
+ setTabsClosable(true);
+ connect(this, SIGNAL(tabCloseRequested(int)), SLOT(closeTab(int)));
+ setWindowFlags(windowFlags() | Qt::Window);
+ setWindowTitle(WatchHandler::tr("Debugger - Qt Creator"));
+ }
+
+public slots:
+ void closeTab(int index)
+ {
+ removeTab(index);
+ }
+};
+
class WatchModel : public QAbstractItemModel
{
Q_OBJECT
@@ -1136,11 +1159,10 @@ bool WatchModel::setData(const QModelIndex &idx, const QVariant &value, int role
case LocalsIndividualFormatRole: {
const int format = value.toInt();
- if (format == -1) {
+ if (format == -1)
theIndividualFormats.remove(data.iname);
- } else {
+ else
theIndividualFormats[data.iname] = format;
- }
engine()->updateWatchData(data);
break;
}
@@ -1256,17 +1278,15 @@ static bool watchDataLessThan(const QByteArray &iname1, int sortId1,
return sortId1 < sortId2;
// Get positions of last part of iname 'local.this.i1" -> "i1"
int cmpPos1 = iname1.lastIndexOf('.');
- if (cmpPos1 == -1) {
+ if (cmpPos1 == -1)
cmpPos1 = 0;
- } else {
+ else
cmpPos1++;
- }
int cmpPos2 = iname2.lastIndexOf('.');
- if (cmpPos2 == -1) {
+ if (cmpPos2 == -1)
cmpPos2 = 0;
- } else {
+ else
cmpPos2++;
- }
// Are we looking at an array with numerical inames 'local.this.i1.0" ->
// Go by sort id.
if (cmpPos1 < iname1.size() && cmpPos2 < iname2.size()
@@ -1591,11 +1611,10 @@ void WatchHandler::watchExpression(const QString &exp, const QString &name)
// (address) if it can be found. Default to watchExpression().
void WatchHandler::watchVariable(const QString &exp)
{
- if (const WatchData *localVariable = findCppLocalVariable(exp)) {
+ if (const WatchData *localVariable = findCppLocalVariable(exp))
watchExpression(QLatin1String(localVariable->exp), exp);
- } else {
+ else
watchExpression(exp);
- }
}
static void swapEndian(char *d, int nchar)
@@ -1611,38 +1630,77 @@ static void swapEndian(char *d, int nchar)
}
}
+static int indexOf(const QTabWidget *tw, const QWidget *w)
+{
+ for (int i = 0; i < tw->count(); ++i)
+ if (tw->widget(i) == w)
+ return i;
+ return -1;
+}
+
+void WatchHandler::removeSeparateWidget(QObject *o)
+{
+ const int index = o && o->isWidgetType() && !m_separateWindow.isNull() ?
+ indexOf(m_separateWindow, static_cast<QWidget *>(o)) : -1;
+ if (index != -1) {
+ m_separateWindow->removeTab(index);
+ if (!m_separateWindow->count())
+ m_separateWindow->hide();
+ }
+}
+
+void WatchHandler::showSeparateWidget(QWidget *w)
+{
+ if (m_separateWindow.isNull())
+ m_separateWindow = new SeparateViewWidget(debuggerCore()->mainWindow());
+
+ int index = indexOf(m_separateWindow, w);
+ if (index != -1)
+ m_separateWindow->setTabText(index, w->windowTitle());
+ else
+ index = m_separateWindow->addTab(w, w->windowTitle());
+ m_separateWindow->setCurrentIndex(index);
+ m_separateWindow->show();
+ m_separateWindow->raise();
+}
+
void WatchHandler::showEditValue(const WatchData &data)
{
const QByteArray key = data.address ? data.hexAddress() : data.iname;
QObject *w = m_model->m_editHandlers.value(key);
- if (data.editformat == 0x0) {
+ switch (data.editformat) {
+ case StopDisplay:
m_model->m_editHandlers.remove(data.iname);
delete w;
- } else if (data.editformat == 1 || data.editformat == 3) {
- // QImage
- QLabel *l = qobject_cast<QLabel *>(w);
+ break;
+ case DisplayImageData:
+ case DisplayImageFile: { // QImage
+ ImageViewer *l = qobject_cast<ImageViewer *>(w);
if (!l) {
+ removeSeparateWidget(w);
delete w;
- l = new QLabel;
+ l = new ImageViewer;
const QString title = data.address ?
tr("%1 Object at %2").arg(QLatin1String(data.type),
QLatin1String(data.hexAddress())) :
tr("%1 Object at Unknown Address").arg(QLatin1String(data.type));
l->setWindowTitle(title);
+ showSeparateWidget(l);
m_model->m_editHandlers[key] = l;
}
int width, height, format;
QByteArray ba;
- uchar *bits;
- if (data.editformat == 1) {
+ uchar *bits = 0;
+ if (data.editformat == DisplayImageData) {
ba = QByteArray::fromHex(data.editvalue);
const int *header = (int *)(ba.data());
- swapEndian(ba.data(), ba.size());
+ if (!ba.at(0) && !ba.at(1)) // Check on 'width' for Python dumpers returning 4-byte swapped-data.
+ swapEndian(ba.data(), ba.size());
bits = 12 + (uchar *)(ba.data());
width = header[0];
height = header[1];
format = header[2];
- } else { // data.editformat == 3
+ } else if (data.editformat == DisplayImageFile) {
QTextStream ts(data.editvalue);
QString fileName;
ts >> width >> height >> format >> fileName;
@@ -1651,31 +1709,34 @@ void WatchHandler::showEditValue(const WatchData &data)
ba = f.readAll();
bits = (uchar*)ba.data();
}
- QImage im(bits, width, height, QImage::Format(format));
-
-#if 1
- // Qt bug. Enforce copy of image data.
- QImage im2(im);
- im.detach();
-#endif
-
- l->setPixmap(QPixmap::fromImage(im));
- l->resize(width, height);
- l->show();
- } else if (data.editformat == 2) {
- // Display QString in a separate widget.
+ l->setImage(QImage(bits, width, height, QImage::Format(format)));
+ showSeparateWidget(l);
+ }
+ break;
+ case DisplayUtf16String:
+ case DisplayLatin1String:
+ case DisplayUtf8String: { // String data.
QTextEdit *t = qobject_cast<QTextEdit *>(w);
if (!t) {
+ removeSeparateWidget(w);
delete w;
t = new QTextEdit;
m_model->m_editHandlers[key] = t;
}
QByteArray ba = QByteArray::fromHex(data.editvalue);
- QString str = QString::fromUtf16((ushort *)ba.constData(), ba.size()/2);
+ QString str;
+ if (data.editformat == DisplayUtf16String)
+ str = QString::fromUtf16((ushort *)ba.constData(), ba.size()/2);
+ else if (data.editformat == DisplayLatin1String)
+ str = QString::fromLatin1(ba.constData(), ba.size());
+ else if (data.editformat == DisplayUtf8String)
+ str = QString::fromUtf8(ba.constData(), ba.size());
+ t->setWindowTitle(data.name);
t->setText(str);
- t->resize(400, 200);
- t->show();
- } else if (data.editformat == 4) {
+ showSeparateWidget(t);
+ }
+ break;
+ case DisplayProcess: {
// Generic Process.
int pos = data.editvalue.indexOf('|');
QByteArray cmd = data.editvalue.left(pos);
@@ -1688,8 +1749,11 @@ void WatchHandler::showEditValue(const WatchData &data)
m_model->m_editHandlers[key] = p;
}
p->write(input + '\n');
- } else {
+ }
+ break;
+ default:
QTC_ASSERT(false, qDebug() << "Display format: " << data.editformat);
+ break;
}
}
diff --git a/src/plugins/debugger/watchhandler.h b/src/plugins/debugger/watchhandler.h
index 80dde93dc8..6a920d6642 100644
--- a/src/plugins/debugger/watchhandler.h
+++ b/src/plugins/debugger/watchhandler.h
@@ -35,8 +35,11 @@
#include <QHash>
#include <QSet>
#include <QStringList>
+#include <QPointer>
#include <QAbstractItemModel>
+QT_FORWARD_DECLARE_CLASS(QTabWidget)
+
namespace Debugger {
class DebuggerEngine;
@@ -136,6 +139,9 @@ public:
void resetValueCache();
private:
+ void removeSeparateWidget(QObject *o);
+ void showSeparateWidget(QWidget *w);
+
friend class WatchModel;
void saveWatchers();
@@ -146,6 +152,7 @@ private:
WatchModel *m_model;
DebuggerEngine *m_engine;
+ QPointer<QTabWidget> m_separateWindow;
int m_watcherCounter;
diff --git a/src/plugins/debugger/watchutils.cpp b/src/plugins/debugger/watchutils.cpp
index 97027c44e8..c12cd2735d 100644
--- a/src/plugins/debugger/watchutils.cpp
+++ b/src/plugins/debugger/watchutils.cpp
@@ -27,145 +27,44 @@
**
****************************************************************************/
+// NOTE: Don't add dependencies to other files.
+// This is used in the debugger auto-tests.
+
#include "watchutils.h"
#include "watchdata.h"
-#include "debuggerstringutils.h"
-#include "gdb/gdbmi.h"
-
-#include <utils/qtcassert.h>
-
-#include <coreplugin/idocument.h>
-
-#include <texteditor/basetexteditor.h>
-#include <texteditor/basetextmark.h>
-#include <texteditor/itexteditor.h>
-#include <texteditor/texteditorconstants.h>
-#include <coreplugin/editormanager/editormanager.h>
-
-#include <cpptools/cpptoolsconstants.h>
-#include <cpptools/abstracteditorsupport.h>
+#include "debuggerprotocol.h"
-#include <cpptools/ModelManagerInterface.h>
-#include <cplusplus/ExpressionUnderCursor.h>
-#include <cplusplus/Overview.h>
-#include <Symbols.h>
-#include <Scope.h>
-
-#include <extensionsystem/pluginmanager.h>
-
-#include <QCoreApplication>
-#include <QDateTime>
#include <QDebug>
-#include <QHash>
-#include <QStringList>
-#include <QTextStream>
-#include <QTime>
-
-#include <QTextCursor>
-#include <QPlainTextEdit>
#include <string.h>
#include <ctype.h>
enum { debug = 0 };
-// Debug helpers for code model. @todo: Move to some CppTools library?
-namespace CPlusPlus {
-
-static void debugCppSymbolRecursion(QTextStream &str, const Overview &o,
- const Symbol &s, bool doRecurse = true,
- int recursion = 0)
-{
- for (int i = 0; i < recursion; i++)
- str << " ";
- str << "Symbol: " << o.prettyName(s.name()) << " at line " << s.line();
- if (s.isFunction())
- str << " function";
- if (s.isClass())
- str << " class";
- if (s.isDeclaration())
- str << " declaration";
- if (s.isBlock())
- str << " block";
- if (doRecurse && s.isScope()) {
- const Scope *scoped = s.asScope();
- const int size = scoped->memberCount();
- str << " scoped symbol of " << size << '\n';
- for (int m = 0; m < size; m++)
- debugCppSymbolRecursion(str, o, *scoped->memberAt(m), true, recursion + 1);
- } else {
- str << '\n';
- }
-}
+namespace Debugger {
+namespace Internal {
-QDebug operator<<(QDebug d, const Symbol &s)
+QString removeObviousSideEffects(const QString &expIn)
{
- QString output;
- CPlusPlus::Overview o;
- QTextStream str(&output);
- debugCppSymbolRecursion(str, o, s, true, 0);
- d.nospace() << output;
- return d;
-}
+ QString exp = expIn.trimmed();
+ if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')) || !hasLetterOrNumber(exp) || isKeyWord(exp))
+ return QString();
-QDebug operator<<(QDebug d, const Scope &scope)
-{
- QString output;
- Overview o;
- QTextStream str(&output);
- const int size = scope.memberCount();
- str << "Scope of " << size;
- if (scope.isNamespace())
- str << " namespace";
- if (scope.isClass())
- str << " class";
- if (scope.isEnum())
- str << " enum";
- if (scope.isBlock())
- str << " block";
- if (scope.isFunction())
- str << " function";
- if (scope.isFunction())
- str << " prototype";
-#if 0 // ### port me
- if (const Symbol *owner = &scope) {
- str << " owner: ";
- debugCppSymbolRecursion(str, o, *owner, false, 0);
- } else {
- str << " 0-owner\n";
- }
-#endif
- for (int s = 0; s < size; s++)
- debugCppSymbolRecursion(str, o, *scope.memberAt(s), true, 2);
- d.nospace() << output;
- return d;
-}
-} // namespace CPlusPlus
+ if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"')))
+ return QString();
-namespace Debugger {
-namespace Internal {
+ if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
+ exp.remove(0, 2);
-bool isEditorDebuggable(Core::IEditor *editor)
-{
- // Only blacklist Qml. Whitelisting would fail on C++ code in files
- // with strange names, more harm would be done this way.
- // IDocument *file = editor->document();
- // return !(file && file->mimeType() == "application/x-qml");
- // Nowadays, even Qml is debuggable.
- return editor;
-}
+ if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
+ exp.truncate(exp.size() - 2);
-QByteArray dotEscape(QByteArray str)
-{
- str.replace(' ', '.');
- str.replace('\\', '.');
- str.replace('/', '.');
- return str;
-}
+ if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
+ return QString();
-QString currentTime()
-{
- return QTime::currentTime().toString(QLatin1String("hh:mm:ss.zzz"));
+ if (hasSideEffects(exp) || exp.isEmpty())
+ return QString();
+ return exp;
}
bool isSkippableFunction(const QString &funcName, const QString &fileName)
@@ -279,9 +178,10 @@ bool hasSideEffects(const QString &exp)
bool isKeyWord(const QString &exp)
{
- // FIXME: incomplete
- QTC_ASSERT(!exp.isEmpty(), return false);
- switch (exp.at(0).toAscii()) {
+ // FIXME: incomplete.
+ if (!exp.isEmpty())
+ return false;
+ switch (exp.at(0).toLatin1()) {
case 'a':
return exp == QLatin1String("auto");
case 'b':
@@ -371,136 +271,6 @@ QString formatToolTipAddress(quint64 a)
return QLatin1String("0x") + rc;
}
-/* getUninitializedVariables(): Get variables that are not initialized
- * at a certain line of a function from the code model to be able to
- * indicate them as not in scope in the locals view.
- * Find document + function in the code model, do a double check and
- * collect declarative symbols that are in the function past or on
- * the current line. blockRecursion() recurses up the scopes
- * and collect symbols declared past or on the current line.
- * Recursion goes up from the innermost scope, keeping a map
- * of occurrences seen, to be able to derive the names of
- * shadowed variables as the debugger sees them:
-\code
-int x; // Occurrence (1), should be reported as "x <shadowed 1>"
-if (true) {
- int x = 5; (2) // Occurrence (2), should be reported as "x"
-}
-\endcode
- */
-
-typedef QHash<QString, int> SeenHash;
-
-static void blockRecursion(const CPlusPlus::Overview &overview,
- const CPlusPlus::Scope *scope,
- unsigned line,
- QStringList *uninitializedVariables,
- SeenHash *seenHash,
- int level = 0)
-{
- // Go backwards in case someone has identical variables in the same scope.
- // Fixme: loop variables or similar are currently seen in the outer scope
- for (int s = scope->memberCount() - 1; s >= 0; --s){
- const CPlusPlus::Symbol *symbol = scope->memberAt(s);
- if (symbol->isDeclaration()) {
- // Find out about shadowed symbols by bookkeeping
- // the already seen occurrences in a hash.
- const QString name = overview.prettyName(symbol->name());
- SeenHash::iterator it = seenHash->find(name);
- if (it == seenHash->end()) {
- it = seenHash->insert(name, 0);
- } else {
- ++(it.value());
- }
- // Is the declaration on or past the current line, that is,
- // the variable not initialized.
- if (symbol->line() >= line)
- uninitializedVariables->push_back(WatchData::shadowedName(name, it.value()));
- }
- }
- // Next block scope.
- if (const CPlusPlus::Scope *enclosingScope = scope->enclosingBlock())
- blockRecursion(overview, enclosingScope, line, uninitializedVariables, seenHash, level + 1);
-}
-
-// Inline helper with integer error return codes.
-static inline
-int getUninitializedVariablesI(const CPlusPlus::Snapshot &snapshot,
- const QString &functionName,
- const QString &file,
- int line,
- QStringList *uninitializedVariables)
-{
- uninitializedVariables->clear();
- // Find document
- if (snapshot.isEmpty() || functionName.isEmpty() || file.isEmpty() || line < 1)
- return 1;
- const CPlusPlus::Snapshot::const_iterator docIt = snapshot.find(file);
- if (docIt == snapshot.end())
- return 2;
- const CPlusPlus::Document::Ptr doc = docIt.value();
- // Look at symbol at line and find its function. Either it is the
- // function itself or some expression/variable.
- const CPlusPlus::Symbol *symbolAtLine = doc->lastVisibleSymbolAt(line, 0);
- if (!symbolAtLine)
- return 4;
- // First figure out the function to do a safety name check
- // and the innermost scope at cursor position
- const CPlusPlus::Function *function = 0;
- const CPlusPlus::Scope *innerMostScope = 0;
- if (symbolAtLine->isFunction()) {
- function = symbolAtLine->asFunction();
- if (function->memberCount() == 1) // Skip over function block
- if (CPlusPlus::Block *block = function->memberAt(0)->asBlock())
- innerMostScope = block;
- } else {
- if (const CPlusPlus::Scope *functionScope = symbolAtLine->enclosingFunction()) {
- function = functionScope->asFunction();
- innerMostScope = symbolAtLine->isBlock() ?
- symbolAtLine->asBlock() :
- symbolAtLine->enclosingBlock();
- }
- }
- if (!function || !innerMostScope)
- return 7;
- // Compare function names with a bit off fuzz,
- // skipping modules from a CDB symbol "lib!foo" or namespaces
- // that the code model does not show at this point
- CPlusPlus::Overview overview;
- const QString name = overview.prettyName(function->name());
- if (!functionName.endsWith(name))
- return 11;
- if (functionName.size() > name.size()) {
- const char previousChar = functionName.at(functionName.size() - name.size() - 1).toLatin1();
- if (previousChar != ':' && previousChar != '!' )
- return 11;
- }
- // Starting from the innermost block scope, collect declarations.
- SeenHash seenHash;
- blockRecursion(overview, innerMostScope, line, uninitializedVariables, &seenHash);
- return 0;
-}
-
-bool getUninitializedVariables(const CPlusPlus::Snapshot &snapshot,
- const QString &function,
- const QString &file,
- int line,
- QStringList *uninitializedVariables)
-{
- const int rc = getUninitializedVariablesI(snapshot, function, file, line, uninitializedVariables);
- if (debug) {
- QString msg;
- QTextStream str(&msg);
- str << "getUninitializedVariables() " << function << ' ' << file << ':' << line
- << " returns (int) " << rc << " '"
- << uninitializedVariables->join(QString(QLatin1Char(','))) << '\'';
- if (rc)
- str << " of " << snapshot.size() << " documents";
- qDebug() << msg;
- }
- return rc == 0;
-}
-
QByteArray gdbQuoteTypes(const QByteArray &type)
{
// gdb does not understand sizeof(Core::IDocument*).
@@ -559,145 +329,6 @@ QByteArray gdbQuoteTypes(const QByteArray &type)
// Utilities to decode string data returned by the dumper helpers.
-QString quoteUnprintableLatin1(const QByteArray &ba)
-{
- QString res;
- char buf[10];
- for (int i = 0, n = ba.size(); i != n; ++i) {
- const unsigned char c = ba.at(i);
- if (isprint(c)) {
- res += QLatin1Char(c);
- } else {
- qsnprintf(buf, sizeof(buf) - 1, "\\%x", int(c));
- res += QLatin1String(buf);
- }
- }
- return res;
-}
-
-static QDate dateFromData(int jd)
-{
- return jd ? QDate::fromJulianDay(jd) : QDate();
-}
-
-static QTime timeFromData(int ms)
-{
- return ms == -1 ? QTime() : QTime(0, 0, 0, 0).addMSecs(ms);
-}
-
-QString decodeData(const QByteArray &ba, int encoding)
-{
- switch (encoding) {
- case Unencoded8Bit: // 0
- return quoteUnprintableLatin1(ba);
- case Base64Encoded8BitWithQuotes: { // 1, used for QByteArray
- const QChar doubleQuote(QLatin1Char('"'));
- QString rc = doubleQuote;
- rc += quoteUnprintableLatin1(QByteArray::fromBase64(ba));
- rc += doubleQuote;
- return rc;
- }
- case Base64Encoded16BitWithQuotes: { // 2, used for QString
- const QChar doubleQuote(QLatin1Char('"'));
- const QByteArray decodedBa = QByteArray::fromBase64(ba);
- QString rc = doubleQuote;
- rc += QString::fromUtf16(reinterpret_cast<const ushort *>
- (decodedBa.data()), decodedBa.size() / 2);
- rc += doubleQuote;
- return rc;
- }
- case Base64Encoded32BitWithQuotes: { // 3
- const QByteArray decodedBa = QByteArray::fromBase64(ba);
- const QChar doubleQuote(QLatin1Char('"'));
- QString rc = doubleQuote;
- rc += QString::fromUcs4(reinterpret_cast<const uint *>
- (decodedBa.data()), decodedBa.size() / 4);
- rc += doubleQuote;
- return rc;
- }
- case Base64Encoded16Bit: { // 4, without quotes (see 2)
- const QByteArray decodedBa = QByteArray::fromBase64(ba);
- return QString::fromUtf16(reinterpret_cast<const ushort *>
- (decodedBa.data()), decodedBa.size() / 2);
- }
- case Base64Encoded8Bit: { // 5, without quotes (see 1)
- return quoteUnprintableLatin1(QByteArray::fromBase64(ba));
- }
- case Hex2EncodedLatin1WithQuotes: { // 6, %02x encoded 8 bit Latin1 data
- const QChar doubleQuote(QLatin1Char('"'));
- const QByteArray decodedBa = QByteArray::fromHex(ba);
- return doubleQuote + QString::fromLatin1(decodedBa) + doubleQuote;
- }
- case Hex4EncodedLittleEndianWithQuotes: { // 7, %04x encoded 16 bit data
- const QChar doubleQuote(QLatin1Char('"'));
- const QByteArray decodedBa = QByteArray::fromHex(ba);
- return doubleQuote + QString::fromUtf16(reinterpret_cast<const ushort *>
- (decodedBa.data()), decodedBa.size() / 2) + doubleQuote;
- }
- case Hex8EncodedLittleEndianWithQuotes: { // 8, %08x encoded 32 bit data
- const QChar doubleQuote(QLatin1Char('"'));
- const QByteArray decodedBa = QByteArray::fromHex(ba);
- return doubleQuote + QString::fromUcs4(reinterpret_cast<const uint *>
- (decodedBa.data()), decodedBa.size() / 4) + doubleQuote;
- }
- case Hex2EncodedUtf8WithQuotes: { // 9, %02x encoded 8 bit UTF-8 data
- const QChar doubleQuote(QLatin1Char('"'));
- const QByteArray decodedBa = QByteArray::fromHex(ba);
- return doubleQuote + QString::fromUtf8(decodedBa) + doubleQuote;
- }
- case Hex8EncodedBigEndian: { // 10, %08x encoded 32 bit data
- const QChar doubleQuote(QLatin1Char('"'));
- QByteArray decodedBa = QByteArray::fromHex(ba);
- for (int i = 0; i < decodedBa.size() - 3; i += 4) {
- char c = decodedBa.at(i);
- decodedBa[i] = decodedBa.at(i + 3);
- decodedBa[i + 3] = c;
- c = decodedBa.at(i + 1);
- decodedBa[i + 1] = decodedBa.at(i + 2);
- decodedBa[i + 2] = c;
- }
- return doubleQuote + QString::fromUcs4(reinterpret_cast<const uint *>
- (decodedBa.data()), decodedBa.size() / 4) + doubleQuote;
- }
- case Hex4EncodedBigEndianWithQuotes: { // 11, %04x encoded 16 bit data
- const QChar doubleQuote(QLatin1Char('"'));
- QByteArray decodedBa = QByteArray::fromHex(ba);
- for (int i = 0; i < decodedBa.size(); i += 2) {
- char c = decodedBa.at(i);
- decodedBa[i] = decodedBa.at(i + 1);
- decodedBa[i + 1] = c;
- }
- return doubleQuote + QString::fromUtf16(reinterpret_cast<const ushort *>
- (decodedBa.data()), decodedBa.size() / 2) + doubleQuote;
- }
- case Hex4EncodedLittleEndianWithoutQuotes: { // 12, see 7, without quotes
- const QByteArray decodedBa = QByteArray::fromHex(ba);
- return QString::fromUtf16(reinterpret_cast<const ushort *>
- (decodedBa.data()), decodedBa.size() / 2);
- }
- case Hex2EncodedLocal8BitWithQuotes: { // 13, %02x encoded 8 bit UTF-8 data
- const QChar doubleQuote(QLatin1Char('"'));
- const QByteArray decodedBa = QByteArray::fromHex(ba);
- return doubleQuote + QString::fromLocal8Bit(decodedBa) + doubleQuote;
- }
- case JulianDate: { // 14, an integer count
- const QDate date = dateFromData(ba.toInt());
- return date.toString(Qt::TextDate);
- }
- case MillisecondsSinceMidnight: {
- const QTime time = timeFromData(ba.toInt());
- return time.toString(Qt::TextDate);
- }
- case JulianDateAndMillisecondsSinceMidnight: {
- const int p = ba.indexOf('/');
- const QDate date = dateFromData(ba.left(p).toInt());
- const QTime time = timeFromData(ba.mid(p + 1 ).toInt());
- return QDateTime(date, time).toString(Qt::TextDate);
- }
- }
- qDebug() << "ENCODING ERROR: " << encoding;
- return QCoreApplication::translate("Debugger", "<Encoding error>");
-}
template <class T>
void decodeArrayHelper(QList<WatchData> *list, const WatchData &tmplate,
@@ -759,116 +390,6 @@ void decodeArray(QList<WatchData> *list, const WatchData &tmplate,
}
}
-// Editor tooltip support
-bool isCppEditor(Core::IEditor *editor)
-{
- using namespace CppTools::Constants;
- const Core::IDocument *document= editor->document();
- if (!document)
- return false;
- const QByteArray mimeType = document->mimeType().toLatin1();
- return mimeType == C_SOURCE_MIMETYPE
- || mimeType == CPP_SOURCE_MIMETYPE
- || mimeType == CPP_HEADER_MIMETYPE
- || mimeType == OBJECTIVE_CPP_SOURCE_MIMETYPE;
-}
-
-// Return the Cpp expression, and, if desired, the function
-QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
- int *line, int *column, QString *function /* = 0 */)
-{
- using namespace CppTools;
- using namespace CPlusPlus;
- *line = *column = 0;
- if (function)
- function->clear();
-
- const QPlainTextEdit *plaintext = qobject_cast<QPlainTextEdit*>(editor->widget());
- if (!plaintext)
- return QString();
-
- QString expr = plaintext->textCursor().selectedText();
- CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
- if (expr.isEmpty() && modelManager) {
- QTextCursor tc(plaintext->document());
- tc.setPosition(pos);
-
- const QChar ch = editor->characterAt(pos);
- if (ch.isLetterOrNumber() || ch == QLatin1Char('_'))
- tc.movePosition(QTextCursor::EndOfWord);
-
- // Fetch the expression's code.
- CPlusPlus::ExpressionUnderCursor expressionUnderCursor;
- expr = expressionUnderCursor(tc);
- *column = tc.positionInBlock();
- *line = tc.blockNumber();
- } else {
- const QTextCursor tc = plaintext->textCursor();
- *column = tc.positionInBlock();
- *line = tc.blockNumber();
- }
-
- if (function && !expr.isEmpty())
- if (const Core::IDocument *document= editor->document())
- if (modelManager)
- *function = AbstractEditorSupport::functionAt(modelManager,
- document->fileName(), *line, *column);
-
- return expr;
-}
-
-// Ensure an expression can be added as side-effect
-// free debugger expression.
-QString fixCppExpression(const QString &expIn)
-{
- QString exp = expIn;
- // Extract the first identifier, everything else is considered
- // too dangerous.
- int pos1 = 0, pos2 = exp.size();
- bool inId = false;
- for (int i = 0; i != exp.size(); ++i) {
- const QChar c = exp.at(i);
- const bool isIdChar = c.isLetterOrNumber() || c.unicode() == '_';
- if (inId && !isIdChar) {
- pos2 = i;
- break;
- }
- if (!inId && isIdChar) {
- inId = true;
- pos1 = i;
- }
- }
- exp = exp.mid(pos1, pos2 - pos1);
-
- if (exp.isEmpty() || exp.startsWith(QLatin1Char('#')) || !hasLetterOrNumber(exp) || isKeyWord(exp))
- return QString();
-
- if (exp.startsWith(QLatin1Char('"')) && exp.endsWith(QLatin1Char('"')))
- return QString();
-
- if (exp.startsWith(QLatin1String("++")) || exp.startsWith(QLatin1String("--")))
- exp.remove(0, 2);
-
- if (exp.endsWith(QLatin1String("++")) || exp.endsWith(QLatin1String("--")))
- exp.truncate(exp.size() - 2);
-
- if (exp.startsWith(QLatin1Char('<')) || exp.startsWith(QLatin1Char('[')))
- return QString();
-
- if (hasSideEffects(exp) || exp.isEmpty())
- return QString();
- return exp;
-}
-
-QString cppFunctionAt(const QString &fileName, int line)
-{
- using namespace CppTools;
- using namespace CPlusPlus;
- CppModelManagerInterface *modelManager = CppModelManagerInterface::instance();
- return AbstractEditorSupport::functionAt(modelManager,
- fileName, line, 1);
-}
-
//////////////////////////////////////////////////////////////////////
//
// GdbMi interaction
@@ -975,7 +496,7 @@ void setWatchDataType(WatchData &data, const GdbMi &item)
void setWatchDataDisplayedType(WatchData &data, const GdbMi &item)
{
if (item.isValid())
- data.displayedType = _(item.data());
+ data.displayedType = QString::fromLatin1(item.data());
}
void parseWatchData(const QSet<QByteArray> &expandedINames,
@@ -1042,7 +563,7 @@ void parseWatchData(const QSet<QByteArray> &expandedINames,
data1.sortId = i;
GdbMi name = child.findChild("name");
if (name.isValid())
- data1.name = _(name.data());
+ data1.name = QString::fromLatin1(name.data());
else
data1.name = QString::number(i);
GdbMi iname = child.findChild("iname");
@@ -1065,7 +586,7 @@ void parseWatchData(const QSet<QByteArray> &expandedINames,
QString skey = decodeData(key, encoding);
if (skey.size() > 13) {
skey = skey.left(12);
- skey += _("...");
+ skey += QLatin1String("...");
}
//data1.name += " (" + skey + ")";
data1.name = skey;
@@ -1075,6 +596,5 @@ void parseWatchData(const QSet<QByteArray> &expandedINames,
}
}
-
} // namespace Internal
} // namespace Debugger
diff --git a/src/plugins/debugger/watchutils.h b/src/plugins/debugger/watchutils.h
index 816a33ee18..5ef1e72f14 100644
--- a/src/plugins/debugger/watchutils.h
+++ b/src/plugins/debugger/watchutils.h
@@ -30,62 +30,18 @@
#ifndef WATCHUTILS_H
#define WATCHUTILS_H
+// NOTE: Don't add dependencies to other files.
+// This is used in the debugger auto-tests.
+
#include <QSet>
#include <QString>
-namespace TextEditor {
- class ITextEditor;
-}
-
-namespace Core {
- class IEditor;
-}
-
-namespace CPlusPlus {
- class Snapshot;
-}
-
namespace Debugger {
namespace Internal {
class WatchData;
class GdbMi;
-// Keep in sync with dumper.py
-enum DebuggerEncoding
-{
- Unencoded8Bit = 0,
- Base64Encoded8BitWithQuotes = 1,
- Base64Encoded16BitWithQuotes = 2,
- Base64Encoded32BitWithQuotes = 3,
- Base64Encoded16Bit = 4,
- Base64Encoded8Bit = 5,
- Hex2EncodedLatin1WithQuotes = 6,
- Hex4EncodedLittleEndianWithQuotes = 7,
- Hex8EncodedLittleEndianWithQuotes = 8,
- Hex2EncodedUtf8WithQuotes = 9,
- Hex8EncodedBigEndian = 10,
- Hex4EncodedBigEndianWithQuotes = 11,
- Hex4EncodedLittleEndianWithoutQuotes = 12,
- Hex2EncodedLocal8BitWithQuotes = 13,
- JulianDate = 14,
- MillisecondsSinceMidnight = 15,
- JulianDateAndMillisecondsSinceMidnight = 16,
- Hex2EncodedInt1 = 17,
- Hex2EncodedInt2 = 18,
- Hex2EncodedInt4 = 19,
- Hex2EncodedInt8 = 20,
- Hex2EncodedUInt1 = 21,
- Hex2EncodedUInt2 = 22,
- Hex2EncodedUInt4 = 23,
- Hex2EncodedUInt8 = 24,
- Hex2EncodedFloat4 = 25,
- Hex2EncodedFloat8 = 26
-};
-
-bool isEditorDebuggable(Core::IEditor *editor);
-QByteArray dotEscape(QByteArray str);
-QString currentTime();
bool isSkippableFunction(const QString &funcName, const QString &fileName);
bool isLeavableFunction(const QString &funcName, const QString &fileName);
@@ -102,28 +58,12 @@ bool isIntOrFloatType(const QByteArray &type);
bool isIntType(const QByteArray &type);
QString formatToolTipAddress(quint64 a);
+QString removeObviousSideEffects(const QString &exp);
-QString quoteUnprintableLatin1(const QByteArray &ba);
-
-// Editor tooltip support
-bool isCppEditor(Core::IEditor *editor);
-QString cppExpressionAt(TextEditor::ITextEditor *editor, int pos,
- int *line, int *column, QString *function = 0);
-QString fixCppExpression(const QString &exp);
-QString cppFunctionAt(const QString &fileName, int line);
-// Decode string data as returned by the dumper helpers.
-QString decodeData(const QByteArray &baIn, int encoding);
// Decode string data as returned by the dumper helpers.
void decodeArray(WatchData *list, const WatchData &tmplate,
const QByteArray &rawData, int encoding);
-// Get variables that are not initialized at a certain line
-// of a function from the code model. Shadowed variables will
-// be reported using the debugger naming conventions '<shadowed n>'
-bool getUninitializedVariables(const CPlusPlus::Snapshot &snapshot,
- const QString &function, const QString &file, int line,
- QStringList *uninitializedVariables);
-
//
// GdbMi interaction
diff --git a/src/plugins/debugger/watchwindow.cpp b/src/plugins/debugger/watchwindow.cpp
index f75cf05d4d..daf45c319c 100644
--- a/src/plugins/debugger/watchwindow.cpp
+++ b/src/plugins/debugger/watchwindow.cpp
@@ -43,6 +43,8 @@
#include "debuggertooltipmanager.h"
#include "memoryagent.h"
+#include <texteditor/syntaxhighlighter.h>
+
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
@@ -301,6 +303,7 @@ static MemoryMarkupList
MemoryMarkupList result;
int colorNumber = 0;
ColorNumberToolTips ranges(size, ColorNumberToolTip(colorNumber, rootToolTip));
+ colorNumber++;
const int childCount = memberVariableRecursion(model, modelIndex,
rootName, address, address + size,
&colorNumber, &ranges);
@@ -331,30 +334,19 @@ static MemoryMarkupList
}
}
- // Condense ranges of identical color into markup ranges. Assign member colors
- // interchangeably.
- const QColor baseColor = sizeIsEstimate ? defaultBackground : Qt::lightGray;
+ // Assign colors from a list, use base color for 0 (contrast to black text).
+ // Overwrite the first color (which is usually very bright) by the base color.
+ QList<QColor> colors = TextEditor::SyntaxHighlighter::generateColors(colorNumber + 2,
+ QColor(Qt::black));
+ colors[0] = sizeIsEstimate ? defaultBackground : Qt::lightGray;
const QColor registerColor = Qt::green;
- QColor memberColor1 = QColor(Qt::yellow).lighter();
- QColor memberColor2 = QColor(Qt::cyan).lighter();
-
int lastColorNumber = 0;
- int childNumber = 0;
for (unsigned i = 0; i < size; ++i) {
const ColorNumberToolTip &range = ranges.at(i);
if (result.isEmpty() || lastColorNumber != range.first) {
lastColorNumber = range.first;
- // Base colors: Parent/register
- QColor color = range.first == registerColorNumber ? registerColor : baseColor;
- if (range.first && range.first != registerColorNumber) {
- if (childNumber++ & 1) { // Alternating member colors.
- color = memberColor1;
- memberColor1 = memberColor1.darker(120);
- } else {
- color = memberColor2;
- memberColor2 = memberColor2.darker(120);
- }
- } // color switch
+ const QColor color = range.first == registerColorNumber ?
+ registerColor : colors.at(range.first);
result.push_back(MemoryMarkup(address + i, 1, color, range.second));
} else {
result.back().length++;
@@ -452,11 +444,10 @@ static void addStackLayoutMemoryView(DebuggerEngine *engine, bool separateView,
const RegisterMapConstIt regcEnd = regMap.constEnd();
for (RegisterMapConstIt it = regMap.constBegin(); it != regcEnd; ++it) {
const quint64 value = it.key();
- if (value < start && start - value < 512) {
+ if (value < start && start - value < 512)
start = value;
- } else if (value > end && value - end < 512) {
+ else if (value > end && value - end < 512)
end = value + 1;
- }
}
// Indicate all variables.
const QColor background = parent->palette().color(QPalette::Normal, QPalette::Base);
@@ -511,11 +502,8 @@ void WatchTreeView::collapseNode(const QModelIndex &idx)
void WatchTreeView::keyPressEvent(QKeyEvent *ev)
{
if (ev->key() == Qt::Key_Delete && m_type == WatchersType) {
- QModelIndexList indices = selectionModel()->selectedRows();
- if (indices.isEmpty() && selectionModel()->currentIndex().isValid())
- indices.append(selectionModel()->currentIndex());
WatchHandler *handler = currentEngine()->watchHandler();
- foreach (const QModelIndex &idx, indices)
+ foreach (const QModelIndex &idx, activeRows())
handler->removeData(idx.data(LocalsINameRole).toByteArray());
} else if (ev->key() == Qt::Key_Return
&& ev->modifiers() == Qt::ControlModifier
@@ -608,6 +596,7 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
DebuggerEngine *engine = currentEngine();
WatchHandler *handler = engine->watchHandler();
+ const QModelIndexList active = activeRows();
const QModelIndex idx = indexAt(ev->pos());
const QModelIndex mi0 = idx.sibling(idx.row(), 0);
const QModelIndex mi1 = idx.sibling(idx.row(), 1);
@@ -624,8 +613,10 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
const QStringList alternativeFormats =
mi0.data(LocalsTypeFormatListRole).toStringList();
- const int typeFormat =
+ int typeFormat =
mi0.data(LocalsTypeFormatRole).toInt();
+ if (typeFormat >= alternativeFormats.size())
+ typeFormat = -1;
const int individualFormat =
mi0.data(LocalsIndividualFormatRole).toInt();
const int unprintableBase = handler->unprintableBase();
@@ -931,9 +922,11 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
} else if (act == actRemoveWatches) {
handler->clearWatches();
} else if (act == clearTypeFormatAction) {
- setModelData(LocalsTypeFormatRole, -1, mi1);
+ foreach (const QModelIndex &idx, active)
+ setModelData(LocalsTypeFormatRole, -1, idx);
} else if (act == clearIndividualFormatAction) {
- setModelData(LocalsIndividualFormatRole, -1, mi1);
+ foreach (const QModelIndex &idx, active)
+ setModelData(LocalsIndividualFormatRole, -1, idx);
} else if (act == actShowInEditor) {
QString contents = handler->editorContents();
debuggerCore()->openTextEditor(tr("Locals & Expressions"), contents);
@@ -950,13 +943,20 @@ void WatchTreeView::contextMenuEvent(QContextMenuEvent *ev)
} else if (handleBaseContextAction(act)) {
;
} else {
+ // Restrict multiple changes to items of the same type
+ // to avoid assigning illegal formats.
+ const QVariant currentType = mi1.data(LocalsTypeRole);
for (int i = 0; i != typeFormatActions.size(); ++i) {
if (act == typeFormatActions.at(i))
- setModelData(LocalsTypeFormatRole, i, mi1);
+ foreach (const QModelIndex &idx, active)
+ if (idx.data(LocalsTypeRole) == currentType)
+ setModelData(LocalsTypeFormatRole, i, idx);
}
for (int i = 0; i != individualFormatActions.size(); ++i) {
if (act == individualFormatActions.at(i))
- setModelData(LocalsIndividualFormatRole, i, mi1);
+ foreach (const QModelIndex &idx, active)
+ if (idx.data(LocalsTypeRole) == currentType)
+ setModelData(LocalsIndividualFormatRole, i, idx);
}
}
}
@@ -972,6 +972,11 @@ bool WatchTreeView::event(QEvent *ev)
return BaseTreeView::event(ev);
}
+void WatchTreeView::currentChanged(const QModelIndex &current, const QModelIndex &)
+{
+ emit currentIndexChanged(current);
+}
+
void WatchTreeView::editItem(const QModelIndex &idx)
{
Q_UNUSED(idx) // FIXME
diff --git a/src/plugins/debugger/watchwindow.h b/src/plugins/debugger/watchwindow.h
index 9862157c60..8489d11eb6 100644
--- a/src/plugins/debugger/watchwindow.h
+++ b/src/plugins/debugger/watchwindow.h
@@ -59,6 +59,9 @@ public slots:
void watchExpression(const QString &exp, const QString &name);
void handleItemIsExpanded(const QModelIndex &idx);
+signals:
+ void currentIndexChanged(const QModelIndex &currentIndex);
+
private:
Q_SLOT void resetHelper();
Q_SLOT void expandNode(const QModelIndex &idx);
@@ -71,6 +74,7 @@ private:
void dragMoveEvent(QDragMoveEvent *ev);
void mouseDoubleClickEvent(QMouseEvent *ev);
bool event(QEvent *ev);
+ void currentChanged(const QModelIndex &current, const QModelIndex &previous);
void editItem(const QModelIndex &idx);
void resetHelper(const QModelIndex &idx);
diff --git a/src/plugins/designer/cpp/cppsettingspage.cpp b/src/plugins/designer/cpp/cppsettingspage.cpp
index eb355e9bde..346c9167ca 100644
--- a/src/plugins/designer/cpp/cppsettingspage.cpp
+++ b/src/plugins/designer/cpp/cppsettingspage.cpp
@@ -105,9 +105,9 @@ QString CppSettingsPageWidget::searchKeywords() const
CppSettingsPage::CppSettingsPage(QObject *parent) : Core::IOptionsPage(parent)
{
m_parameters.fromSettings(Core::ICore::settings());
- setId(QLatin1String(Designer::Constants::SETTINGS_CPP_SETTINGS_ID));
+ setId(Designer::Constants::SETTINGS_CPP_SETTINGS_ID);
setDisplayName(QCoreApplication::translate("Designer", Designer::Constants::SETTINGS_CPP_SETTINGS_NAME));
- setCategory(QLatin1String(Designer::Constants::SETTINGS_CATEGORY));
+ setCategory(Designer::Constants::SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Designer", Designer::Constants::SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Designer::Constants::SETTINGS_CATEGORY_ICON));
}
diff --git a/src/plugins/designer/cpp/formclasswizardpage.cpp b/src/plugins/designer/cpp/formclasswizardpage.cpp
index 656d39ca80..146fdc0274 100644
--- a/src/plugins/designer/cpp/formclasswizardpage.cpp
+++ b/src/plugins/designer/cpp/formclasswizardpage.cpp
@@ -132,9 +132,8 @@ bool FormClassWizardPage::validatePage()
{
QString errorMessage;
const bool rc = m_ui->newClassWidget->isValid(&errorMessage);
- if (!rc) {
+ if (!rc)
QMessageBox::warning(this, tr("%1 - Error").arg(title()), errorMessage);
- }
return rc;
}
diff --git a/src/plugins/designer/designer.pro b/src/plugins/designer/designer.pro
index 463adfa1ee..6b4a90221b 100644
--- a/src/plugins/designer/designer.pro
+++ b/src/plugins/designer/designer.pro
@@ -1,6 +1,6 @@
TEMPLATE = lib
TARGET = Designer
-DEFINES += DESIGNER_LIBRARY QT_NO_CAST_FROM_ASCII
+DEFINES += DESIGNER_LIBRARY
include(../../qtcreatorplugin.pri)
include(../../shared/designerintegrationv2/designerintegration.pri)
@@ -10,7 +10,7 @@ include(designer_dependencies.pri)
INCLUDEPATH += ../../tools/utils
greaterThan(QT_MAJOR_VERSION, 4) {
- QT += printsupport designer
+ QT += printsupport designer designercomponents
} else {
# -- figure out shared dir location
!exists($$[QT_INSTALL_HEADERS]/QtDesigner/private/qdesigner_integration_p.h) {
@@ -19,12 +19,11 @@ greaterThan(QT_MAJOR_VERSION, 4) {
}
INCLUDEPATH += $$QMAKE_INCDIR_QT/QtDesigner
qtAddLibrary(QtDesigner)
+ qtAddLibrary(QtDesignerComponents)
}
QT += xml
-qtAddLibrary(QtDesignerComponents)
-
HEADERS += formeditorplugin.h \
formeditorfactory.h \
formwindoweditor.h \
diff --git a/src/plugins/designer/designer.qbs b/src/plugins/designer/designer.qbs
index 19769a0ad7..f30940b731 100644
--- a/src/plugins/designer/designer.qbs
+++ b/src/plugins/designer/designer.qbs
@@ -14,78 +14,73 @@ QtcPlugin {
Depends { name: "cpp" }
cpp.defines: base.concat(["CPP_ENABLED"])
- cpp.includePaths: [
+ cpp.includePaths: base.concat([
"../../libs/3rdparty",
"cpp",
- "../../shared/designerintegrationv2",
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
+ "../../shared/designerintegrationv2"
+ ])
files: [
- "../../shared/designerintegrationv2/widgethost.h",
- "../../shared/designerintegrationv2/sizehandlerect.h",
- "../../shared/designerintegrationv2/formresizer.h",
- "../../shared/designerintegrationv2/widgethostconstants.h",
- "cpp/formclasswizardpage.h",
- "cpp/formclasswizarddialog.h",
- "cpp/formclasswizard.h",
- "cpp/formclasswizardparameters.h",
- "cpp/cppsettingspage.h",
- "formeditorplugin.h",
- "formeditorfactory.h",
- "formwindoweditor.h",
- "formwindowfile.h",
- "formwizard.h",
- "qtcreatorintegration.h",
- "designerconstants.h",
- "settingspage.h",
- "editorwidget.h",
- "formeditorw.h",
- "settingsmanager.h",
- "formtemplatewizardpage.h",
- "formwizarddialog.h",
+ "Designer.mimetypes.xml",
+ "README.txt",
+ "codemodelhelpers.cpp",
"codemodelhelpers.h",
+ "designer.qrc",
"designer_export.h",
- "designerxmleditor.h",
+ "designerconstants.h",
+ "designercontext.cpp",
"designercontext.h",
- "formeditorstack.h",
+ "designerxmleditor.cpp",
+ "designerxmleditor.h",
"editordata.h",
- "resourcehandler.h",
- "qtdesignerformclasscodegenerator.h",
- "../../shared/designerintegrationv2/widgethost.cpp",
- "../../shared/designerintegrationv2/sizehandlerect.cpp",
- "../../shared/designerintegrationv2/formresizer.cpp",
- "cpp/formclasswizardpage.cpp",
- "cpp/formclasswizarddialog.cpp",
- "cpp/formclasswizard.cpp",
- "cpp/formclasswizardparameters.cpp",
- "cpp/cppsettingspage.cpp",
- "formeditorplugin.cpp",
+ "editorwidget.cpp",
+ "editorwidget.h",
"formeditorfactory.cpp",
+ "formeditorfactory.h",
+ "formeditorplugin.cpp",
+ "formeditorplugin.h",
+ "formeditorstack.cpp",
+ "formeditorstack.h",
+ "formeditorw.cpp",
+ "formeditorw.h",
+ "formtemplatewizardpage.cpp",
+ "formtemplatewizardpage.h",
"formwindoweditor.cpp",
+ "formwindoweditor.h",
"formwindowfile.cpp",
+ "formwindowfile.h",
"formwizard.cpp",
- "qtcreatorintegration.cpp",
- "settingspage.cpp",
- "editorwidget.cpp",
- "formeditorw.cpp",
- "settingsmanager.cpp",
- "formtemplatewizardpage.cpp",
+ "formwizard.h",
"formwizarddialog.cpp",
- "codemodelhelpers.cpp",
- "designerxmleditor.cpp",
- "designercontext.cpp",
- "formeditorstack.cpp",
- "resourcehandler.cpp",
+ "formwizarddialog.h",
+ "qtcreatorintegration.cpp",
+ "qtcreatorintegration.h",
"qtdesignerformclasscodegenerator.cpp",
- "cpp/formclasswizardpage.ui",
+ "qtdesignerformclasscodegenerator.h",
+ "resourcehandler.cpp",
+ "resourcehandler.h",
+ "settingsmanager.cpp",
+ "settingsmanager.h",
+ "settingspage.cpp",
+ "settingspage.h",
+ "../../shared/designerintegrationv2/formresizer.cpp",
+ "../../shared/designerintegrationv2/formresizer.h",
+ "../../shared/designerintegrationv2/sizehandlerect.cpp",
+ "../../shared/designerintegrationv2/sizehandlerect.h",
+ "../../shared/designerintegrationv2/widgethost.cpp",
+ "../../shared/designerintegrationv2/widgethost.h",
+ "../../shared/designerintegrationv2/widgethostconstants.h",
+ "cpp/cppsettingspage.cpp",
+ "cpp/cppsettingspage.h",
"cpp/cppsettingspagewidget.ui",
- "designer.qrc",
- "Designer.mimetypes.xml",
- "README.txt"
+ "cpp/formclasswizard.cpp",
+ "cpp/formclasswizard.h",
+ "cpp/formclasswizarddialog.cpp",
+ "cpp/formclasswizarddialog.h",
+ "cpp/formclasswizardpage.cpp",
+ "cpp/formclasswizardpage.h",
+ "cpp/formclasswizardpage.ui",
+ "cpp/formclasswizardparameters.cpp",
+ "cpp/formclasswizardparameters.h",
]
}
-
diff --git a/src/plugins/designer/formeditorfactory.cpp b/src/plugins/designer/formeditorfactory.cpp
index 1f7775551a..622f2e853a 100644
--- a/src/plugins/designer/formeditorfactory.cpp
+++ b/src/plugins/designer/formeditorfactory.cpp
@@ -61,7 +61,7 @@ FormEditorFactory::FormEditorFactory()
Core::Id FormEditorFactory::id() const
{
- return K_DESIGNER_XML_EDITOR_ID;
+ return Core::Id(K_DESIGNER_XML_EDITOR_ID);
}
QString FormEditorFactory::displayName() const
@@ -75,7 +75,7 @@ Core::IDocument *FormEditorFactory::open(const QString &fileName)
if (!iface)
return 0;
if (qobject_cast<FormWindowEditor *>(iface)) {
- Core::InfoBarEntry info(QLatin1String(Constants::INFO_READ_ONLY),
+ Core::InfoBarEntry info(Core::Id(Constants::INFO_READ_ONLY),
tr("This file can only be edited in <b>Design</b> mode."));
info.setCustomButtonInfo(tr("Switch mode"), this, SLOT(designerModeClicked()));
iface->document()->infoBar()->addInfo(info);
diff --git a/src/plugins/designer/formeditorstack.cpp b/src/plugins/designer/formeditorstack.cpp
index 1e39063a3d..6d15ba8c8e 100644
--- a/src/plugins/designer/formeditorstack.cpp
+++ b/src/plugins/designer/formeditorstack.cpp
@@ -95,7 +95,7 @@ void FormEditorStack::add(const EditorData &data)
int FormEditorStack::indexOfFormWindow(const QDesignerFormWindowInterface *fw) const
{
const int count = m_formEditors.size();
- for(int i = 0; i < count; ++i)
+ for (int i = 0; i < count; ++i)
if (m_formEditors[i].widgetHost->formWindow() == fw)
return i;
return -1;
@@ -104,7 +104,7 @@ int FormEditorStack::indexOfFormWindow(const QDesignerFormWindowInterface *fw) c
int FormEditorStack::indexOfFormEditor(const QObject *xmlEditor) const
{
const int count = m_formEditors.size();
- for(int i = 0; i < count; ++i)
+ for (int i = 0; i < count; ++i)
if (m_formEditors[i].formWindowEditor == xmlEditor)
return i;
return -1;
@@ -158,7 +158,7 @@ void FormEditorStack::updateFormWindowSelectionHandles()
if (Designer::Constants::Internal::debug)
qDebug() << "updateFormWindowSelectionHandles";
QDesignerFormWindowInterface *activeFormWindow = m_designerCore->formWindowManager()->activeFormWindow();
- foreach(const EditorData &fdm, m_formEditors) {
+ foreach (const EditorData &fdm, m_formEditors) {
const bool active = activeFormWindow == fdm.widgetHost->formWindow();
fdm.widgetHost->updateFormWindowSelectionHandles(active);
}
@@ -189,7 +189,7 @@ void FormEditorStack::modeAboutToChange(Core::IMode *m)
// Sync the editor when entering edit mode
if (m && m->id() == Core::Constants::MODE_EDIT)
- foreach(const EditorData &data, m_formEditors)
+ foreach (const EditorData &data, m_formEditors)
data.formWindowEditor->syncXmlEditor();
}
diff --git a/src/plugins/designer/formeditorw.cpp b/src/plugins/designer/formeditorw.cpp
index 660e45f598..7eda1df9f9 100644
--- a/src/plugins/designer/formeditorw.cpp
+++ b/src/plugins/designer/formeditorw.cpp
@@ -803,7 +803,7 @@ void FormEditorW::toolChanged(int t)
void FormEditorW::closeFormEditorsForXmlEditors(QList<Core::IEditor*> editors)
{
- foreach(Core::IEditor *editor, editors) {
+ foreach (Core::IEditor *editor, editors) {
m_editorWidget->removeFormWindowEditor(editor);
}
}
diff --git a/src/plugins/designer/formwindoweditor.cpp b/src/plugins/designer/formwindoweditor.cpp
index 8aa26444e5..ef1d96572d 100644
--- a/src/plugins/designer/formwindoweditor.cpp
+++ b/src/plugins/designer/formwindoweditor.cpp
@@ -178,7 +178,7 @@ bool FormWindowEditor::open(QString *errorString, const QString &fileName, const
d->m_file.setFileName(absfileName);
d->m_file.setShouldAutoSave(false);
- if (Internal::ResourceHandler *rh = qFindChild<Designer::Internal::ResourceHandler*>(form))
+ if (Internal::ResourceHandler *rh = form->findChild<Designer::Internal::ResourceHandler*>())
rh->updateResources();
emit changed();
@@ -208,7 +208,7 @@ Core::IDocument *FormWindowEditor::document()
Core::Id FormWindowEditor::id() const
{
- return Designer::Constants::K_DESIGNER_XML_EDITOR_ID;
+ return Core::Id(Designer::Constants::K_DESIGNER_XML_EDITOR_ID);
}
QString FormWindowEditor::displayName() const
@@ -278,7 +278,7 @@ TextEditor::PlainTextEditor *FormWindowEditor::textEditor()
Core::Id FormWindowEditor::preferredModeType() const
{
- return Core::Constants::MODE_DESIGN_TYPE;
+ return Core::Id(Core::Constants::MODE_DESIGN_TYPE);
}
} // namespace Designer
diff --git a/src/plugins/designer/qt_private/formwindowbase_p.h b/src/plugins/designer/qt_private/formwindowbase_p.h
index c28d2a968a..07ef5bd20c 100644
--- a/src/plugins/designer/qt_private/formwindowbase_p.h
+++ b/src/plugins/designer/qt_private/formwindowbase_p.h
@@ -183,7 +183,7 @@ private slots:
private:
void syncGridFeature();
- FormWindowBasePrivate *m_d;
+ FormWindowBasePrivate *m_d;
};
} // namespace qdesigner_internal
diff --git a/src/plugins/designer/qtcreatorintegration.cpp b/src/plugins/designer/qtcreatorintegration.cpp
index b1e2a5c649..8edb838c39 100644
--- a/src/plugins/designer/qtcreatorintegration.cpp
+++ b/src/plugins/designer/qtcreatorintegration.cpp
@@ -484,9 +484,8 @@ void QtCreatorIntegration::slotNavigateToSlot(const QString &objectName, const Q
const QStringList &parameterNames)
{
QString errorMessage;
- if (!navigateToSlot(objectName, signalSignature, parameterNames, &errorMessage) && !errorMessage.isEmpty()) {
+ if (!navigateToSlot(objectName, signalSignature, parameterNames, &errorMessage) && !errorMessage.isEmpty())
QMessageBox::warning(m_few->designerEditor()->topLevel(), tr("Error finding/adding a slot."), errorMessage);
- }
}
// Build name of the class as generated by uic, insert Ui namespace
diff --git a/src/plugins/designer/qtdesignerformclasscodegenerator.cpp b/src/plugins/designer/qtdesignerformclasscodegenerator.cpp
index e3d2b4226e..50837f5c9e 100644
--- a/src/plugins/designer/qtdesignerformclasscodegenerator.cpp
+++ b/src/plugins/designer/qtdesignerformclasscodegenerator.cpp
@@ -201,9 +201,8 @@ bool QtDesignerFormClassCodeGenerator::generateCpp(const FormClassWizardParamete
// Class declaration
headerStr << '\n' << namespaceIndent << "class " << unqualifiedClassName
<< " : public " << formBaseClass;
- if (generationParameters.embedding == Internal::InheritedUiClass) {
+ if (generationParameters.embedding == Internal::InheritedUiClass)
headerStr << ", private " << uiClassName;
- }
headerStr << "\n{\n" << namespaceIndent << indent << "Q_OBJECT\n\n"
<< namespaceIndent << "public:\n"
<< namespaceIndent << indent << "explicit " << unqualifiedClassName << "(QWidget *parent = 0);\n";
diff --git a/src/plugins/designer/settingspage.cpp b/src/plugins/designer/settingspage.cpp
index 5cb45acbe5..76451aebf7 100644
--- a/src/plugins/designer/settingspage.cpp
+++ b/src/plugins/designer/settingspage.cpp
@@ -46,9 +46,9 @@ using namespace Designer::Internal;
SettingsPage::SettingsPage(QDesignerOptionsPageInterface *designerPage) :
m_designerPage(designerPage), m_initialized(false)
{
- setId(m_designerPage->name());
+ setId(Core::Id::fromString(m_designerPage->name()));
setDisplayName(m_designerPage->name());
- setCategory(QLatin1String(Designer::Constants::SETTINGS_CATEGORY));
+ setCategory(Designer::Constants::SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Designer",
Designer::Constants::SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Designer::Constants::SETTINGS_CATEGORY_ICON));
@@ -75,7 +75,7 @@ void SettingsPage::finish()
SettingsPageProvider::SettingsPageProvider(QObject *parent)
: IOptionsPageProvider(parent), m_initialized(false)
{
- setCategory(QLatin1String(Designer::Constants::SETTINGS_CATEGORY));
+ setCategory(Designer::Constants::SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Designer",
Designer::Constants::SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Designer::Constants::SETTINGS_CATEGORY_ICON));
diff --git a/src/plugins/fakevim/fakevim.pro b/src/plugins/fakevim/fakevim.pro
index 442e7a7206..cf98503f33 100644
--- a/src/plugins/fakevim/fakevim.pro
+++ b/src/plugins/fakevim/fakevim.pro
@@ -7,7 +7,6 @@ include(../../plugins/coreplugin/coreplugin.pri)
include(../../plugins/texteditor/texteditor.pri)
include(../../plugins/find/find.pri)
-# DEFINES += QT_NO_CAST_FROM_ASCII QT_NO_CAST_TO_ASCII
QT += gui
SOURCES += fakevimactions.cpp \
fakevimhandler.cpp \
@@ -16,3 +15,7 @@ HEADERS += fakevimactions.h \
fakevimhandler.h \
fakevimplugin.h
FORMS += fakevimoptions.ui
+
+equals(TEST, 1) {
+ SOURCES += fakevim_test.cpp
+}
diff --git a/src/plugins/fakevim/fakevim.qbs b/src/plugins/fakevim/fakevim.qbs
index 600bd96ff0..218897eb2e 100644
--- a/src/plugins/fakevim/fakevim.qbs
+++ b/src/plugins/fakevim/fakevim.qbs
@@ -1,6 +1,7 @@
import qbs.base 1.0
import "../QtcPlugin.qbs" as QtcPlugin
+import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "FakeVim"
@@ -8,23 +9,20 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "TextEditor" }
Depends { name: "Find" }
- Depends { name: "cpp" }
Depends { name: "Qt.widgets" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
"fakevimactions.cpp",
- "fakevimhandler.cpp",
- "fakevimplugin.cpp",
"fakevimactions.h",
+ "fakevimhandler.cpp",
"fakevimhandler.h",
+ "fakevimoptions.ui",
+ "fakevimplugin.cpp",
"fakevimplugin.h",
- "fakevimoptions.ui"
]
-}
+ Group {
+ condition: Defaults.testsEnabled(qbs)
+ files: ["fakevim_test.cpp"]
+ }
+}
diff --git a/src/plugins/fakevim/fakevim_test.cpp b/src/plugins/fakevim/fakevim_test.cpp
new file mode 100644
index 0000000000..4219f3607b
--- /dev/null
+++ b/src/plugins/fakevim/fakevim_test.cpp
@@ -0,0 +1,2816 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Lukas Holecek <hluk@email.cz>
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+/*!
+ * Tests for FakeVim plugin.
+ * All test are based on Vim behaviour.
+ */
+
+#include "fakevimplugin.h"
+#include "fakevimhandler.h"
+
+#include <coreplugin/editormanager/editormanager.h>
+#include <texteditor/basetexteditor.h>
+
+#include <QtTest>
+#include <QTextEdit>
+#include <QTextDocument>
+#include <QTextBlock>
+
+//TESTED_COMPONENT=src/plugins/fakevim
+
+/*!
+ * Tests after this macro will be skipped and warning printed.
+ * Uncomment it to test a feature -- if tests succeeds it should be removed from the test.
+ */
+#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
+# define NOT_IMPLEMENTED QSKIP("Not fully implemented!", SkipSingle);
+#else
+# define NOT_IMPLEMENTED QSKIP("Not fully implemented!");
+#endif
+
+// Text cursor representation in comparisons.
+#define X "|"
+
+// More distinct line separator in code.
+#define N "\n"
+
+// Document line start and end string in error text.
+#define LINE_START "\t\t<"
+#define LINE_END ">\n"
+
+typedef QLatin1String _;
+
+// Format of message after comparison fails (used by KEYS, COMMAND).
+static const QString helpFormat = _(
+ "\n\tBefore command [%1]:\n" \
+ LINE_START "%2" LINE_END \
+ "\n\tAfter the command:\n" \
+ LINE_START "%3" LINE_END \
+ "\n\tShould be:\n" \
+ LINE_START "%4" LINE_END);
+
+// Compare document contents with a expectedText.
+// Also check cursor position if the expectedText contains | chracter.
+#define COMPARE(beforeText, beforePosition, afterText, afterPosition, expectedText, cmd) \
+ do { \
+ QByteArray before(beforeText); \
+ QByteArray actual(afterText); \
+ QByteArray expected = expectedText; \
+ data.oldPosition = beforePosition; \
+ data.oldText = before; \
+ if (expected.contains(X)) {\
+ before = textWithCursor(before, beforePosition); \
+ actual = textWithCursor(actual, afterPosition); \
+ } \
+ QString help = helpFormat \
+ .arg(_(cmd)) \
+ .arg(_(before.replace('\n', LINE_END LINE_START))) \
+ .arg(_(actual.replace('\n', LINE_END LINE_START))) \
+ .arg(_(expected.replace('\n', LINE_END LINE_START))); \
+ QVERIFY2(actual == expected, help.toLatin1().constData()); \
+ } while (false)
+
+// Send keys and check if the expected result is same as document contents.
+// Escape is always prepended to keys so that previous command is cancelled.
+#define KEYS(keys, expected) \
+ do { \
+ QByteArray beforeText(data.text()); \
+ int beforePosition = data.position(); \
+ data.doKeys("<ESC>"); \
+ data.doKeys(keys); \
+ COMPARE(beforeText, beforePosition, data.text(), data.position(), (expected), (keys)); \
+ } while (false)
+
+// Run Ex command and check if the expected result is same as document contents.
+#define COMMAND(cmd, expected) \
+ do { \
+ QByteArray beforeText(data.text()); \
+ int beforePosition = data.position(); \
+ data.doCommand(cmd); \
+ COMPARE(beforeText, beforePosition, data.text(), data.position(), (expected), (":" cmd)); \
+ } while (false)
+
+// Test undo, redo and repeat of last single command. This doesn't test cursor position.
+// Set afterEnd to true if cursor position after undo and redo differs at the end of line
+// (e.g. undoing 'A' operation moves cursor at the end of line and redo moves it one char right).
+#define INTEGRITY(afterEnd) \
+ do { \
+ data.doKeys("<ESC>"); \
+ const int newPosition = data.position(); \
+ const int oldPosition = data.oldPosition; \
+ const QByteArray redo = data.text(); \
+ KEYS("u", data.oldText); \
+ const QTextCursor tc = data.cursor(); \
+ const int pos = tc.position(); \
+ const int col = tc.positionInBlock() \
+ + ((afterEnd && tc.positionInBlock() + 2 == tc.block().length()) ? 1 : 0); \
+ const int line = tc.block().blockNumber(); \
+ const QTextDocument *doc = data.editor()->document(); \
+ KEYS("<c-r>", textWithCursor(redo, doc->findBlockByNumber(line), col)); \
+ KEYS("u", textWithCursor(data.oldText, pos)); \
+ data.setPosition(oldPosition); \
+ KEYS(".", textWithCursor(redo, newPosition)); \
+ } while (false)
+
+using namespace FakeVim::Internal;
+using namespace TextEditor;
+
+static QByteArray textWithCursor(const QByteArray &text, int position)
+{
+ return (position == -1) ? text : (text.left(position) + X + text.mid(position));
+}
+
+static QByteArray textWithCursor(const QByteArray &text, const QTextBlock &block, int column)
+{
+ const int pos = block.position() + qMin(column, qMax(0, block.length() - 2));
+ return text.left(pos) + X + text.mid(pos);
+}
+
+const QByteArray testLines =
+ /* 0 1 2 3 4 */
+ /* 0123456789012345678901234567890123457890 */
+ "\n"
+ "#include <QtCore>\n"
+ "#include <QtGui>\n"
+ "\n"
+ "int main(int argc, char *argv[])\n"
+ "{\n"
+ " QApplication app(argc, argv);\n"
+ "\n"
+ " return app.exec();\n"
+ "}\n";
+
+const QList<QByteArray> l = testLines.split('\n');
+
+static QByteArray bajoin(const QList<QByteArray> &balist)
+{
+ QByteArray res;
+ for (int i = 0; i < balist.size(); ++i) {
+ if (i)
+ res += '\n';
+ res += balist.at(i);
+ }
+ return res;
+}
+
+// Insert cursor char at pos, negative counts from back.
+static QByteArray cursor(int line, int column)
+{
+ const int col = column >= 0 ? column : l[line].size() + column;
+ QList<QByteArray> res = l.mid(0, line) << textWithCursor(l[line], col);
+ res.append(l.mid(line + 1));
+ return bajoin(res);
+}
+
+static QByteArray lmid(int i, int n = -1) { return bajoin(l.mid(i, n)); }
+
+// Data for tests containing BaseTextEditorWidget and FakeVimHAndler.
+struct FakeVimPlugin::TestData
+{
+ FakeVimHandler *handler;
+ QWidget *edit;
+ QString title;
+
+ int oldPosition;
+ QByteArray oldText;
+
+ BaseTextEditorWidget *editor() const { return qobject_cast<BaseTextEditorWidget *>(edit); }
+
+ QTextCursor cursor() const { return editor()->textCursor(); }
+
+ int position() const
+ {
+ return cursor().position();
+ }
+
+ void setPosition(int position)
+ {
+ handler->setTextCursorPosition(position);
+ }
+
+ QByteArray text() const { return editor()->toPlainText().toUtf8(); }
+
+ void doCommand(const char *cmd) { handler->handleCommand(_(cmd)); }
+ void doKeys(const char *keys) { handler->handleInput(_(keys)); }
+
+ void setText(const char *text)
+ {
+ doKeys("<ESC>");
+ QByteArray str = text;
+ int i = str.indexOf(X);
+ if (i != -1)
+ str.remove(i, 1);
+ editor()->document()->setPlainText(_(str));
+ setPosition(i);
+ }
+
+ // Simulate text completion by inserting text directly to editor widget (bypassing FakeVim).
+ void completeText(const char *text)
+ {
+ QTextCursor tc = editor()->textCursor();
+ tc.insertText(_(text));
+ editor()->setTextCursor(tc);
+ }
+
+ // Simulate external position change.
+ void jump(const char *textWithCursorPosition)
+ {
+ int pos = QString(_(textWithCursorPosition)).indexOf(_(X));
+ QTextCursor tc = editor()->textCursor();
+ tc.setPosition(pos);
+ editor()->setTextCursor(tc);
+ QCOMPARE(QByteArray(textWithCursorPosition), textWithCursor(text(), position()));
+ }
+
+ int lines() const
+ {
+ QTextDocument *doc = editor()->document();
+ Q_ASSERT(doc != 0);
+ return doc->lineCount();
+ }
+
+ // Enter command mode and go to start.
+ void reset()
+ {
+ handler->handleInput(_("<ESC><ESC>gg0"));
+ }
+};
+
+void FakeVimPlugin::setup(TestData *data)
+{
+ setupTest(&data->title, &data->handler, &data->edit);
+ data->reset();
+}
+
+
+void FakeVimPlugin::cleanup()
+{
+ Core::EditorManager::instance()->closeAllEditors(false);
+}
+
+
+void FakeVimPlugin::test_vim_indentation()
+{
+ TestData data;
+ setup(&data);
+
+ data.doCommand("set expandtab");
+ data.doCommand("set tabstop=4");
+ data.doCommand("set shiftwidth=4");
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 6 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 4 + 3 * 4);
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 5 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 4 + 3 * 4);
+
+ QCOMPARE(data.handler->tabExpand(3), _(" "));
+ QCOMPARE(data.handler->tabExpand(4), _(" "));
+ QCOMPARE(data.handler->tabExpand(5), _(" "));
+ QCOMPARE(data.handler->tabExpand(6), _(" "));
+ QCOMPARE(data.handler->tabExpand(7), _(" "));
+ QCOMPARE(data.handler->tabExpand(8), _(" "));
+ QCOMPARE(data.handler->tabExpand(9), _(" "));
+
+ data.doCommand("set expandtab");
+ data.doCommand("set tabstop=8");
+ data.doCommand("set shiftwidth=4");
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 6 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 0 + 3 * 8);
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 5 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 0 + 3 * 8);
+
+ QCOMPARE(data.handler->tabExpand(3), _(" "));
+ QCOMPARE(data.handler->tabExpand(4), _(" "));
+ QCOMPARE(data.handler->tabExpand(5), _(" "));
+ QCOMPARE(data.handler->tabExpand(6), _(" "));
+ QCOMPARE(data.handler->tabExpand(7), _(" "));
+ QCOMPARE(data.handler->tabExpand(8), _(" "));
+ QCOMPARE(data.handler->tabExpand(9), _(" "));
+
+ data.doCommand("set noexpandtab");
+ data.doCommand("set tabstop=4");
+ data.doCommand("set shiftwidth=4");
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 6 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 4 + 3 * 4);
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 5 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 4 + 3 * 4);
+
+ QCOMPARE(data.handler->tabExpand(3), _(" "));
+ QCOMPARE(data.handler->tabExpand(4), _("\t"));
+ QCOMPARE(data.handler->tabExpand(5), _("\t "));
+ QCOMPARE(data.handler->tabExpand(6), _("\t "));
+ QCOMPARE(data.handler->tabExpand(7), _("\t "));
+ QCOMPARE(data.handler->tabExpand(8), _("\t\t"));
+ QCOMPARE(data.handler->tabExpand(9), _("\t\t "));
+
+ data.doCommand("set noexpandtab");
+ data.doCommand("set tabstop=8");
+ data.doCommand("set shiftwidth=4");
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 6 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 0 + 3 * 8);
+ QCOMPARE(data.handler->physicalIndentation(_(" \t\t\tx")), 5 + 3);
+ QCOMPARE(data.handler->logicalIndentation (_(" \t\t\tx")), 0 + 3 * 8);
+
+ QCOMPARE(data.handler->tabExpand(3), _(" "));
+ QCOMPARE(data.handler->tabExpand(4), _(" "));
+ QCOMPARE(data.handler->tabExpand(5), _(" "));
+ QCOMPARE(data.handler->tabExpand(6), _(" "));
+ QCOMPARE(data.handler->tabExpand(7), _(" "));
+ QCOMPARE(data.handler->tabExpand(8), _("\t"));
+ QCOMPARE(data.handler->tabExpand(9), _("\t "));
+}
+
+void FakeVimPlugin::test_vim_movement()
+{
+ TestData data;
+ setup(&data);
+
+ // vertical movement
+ data.setText("123" N "456" N "789" N "abc");
+ KEYS("", X "123" N "456" N "789" N "abc");
+ KEYS("j", "123" N X "456" N "789" N "abc");
+ KEYS("G", "123" N "456" N "789" N X "abc");
+ KEYS("k", "123" N "456" N X "789" N "abc");
+ KEYS("2k", X "123" N "456" N "789" N "abc");
+ KEYS("k", X "123" N "456" N "789" N "abc");
+ KEYS("jj", "123" N "456" N X "789" N "abc");
+ KEYS("gg", X "123" N "456" N "789" N "abc");
+
+ // horizontal movement
+ data.setText(" " X "x" "x" "x" "x");
+ KEYS("", " " X "x" "x" "x" "x");
+ KEYS("h", X " " "x" "x" "x" "x");
+ KEYS("l", " " X "x" "x" "x" "x");
+ KEYS("3l", " " "x" "x" "x" X "x");
+ KEYS("2h", " " "x" X "x" "x" "x");
+ KEYS("$", " " "x" "x" "x" X "x");
+ KEYS("^", " " X "x" "x" "x" "x");
+ KEYS("0", X " " "x" "x" "x" "x");
+
+ // skip words
+ data.setText("123 " "456" "." "789 " "abc");
+ KEYS("b", X "123 " "456" "." "789 " "abc");
+ KEYS("w", "123 " X "456" "." "789 " "abc");
+ KEYS("2w", "123 " "456" "." X "789 " "abc");
+ KEYS("3w", "123 " "456" "." "789 " "ab" X "c");
+ KEYS("3b", "123 " "456" X "." "789 " "abc");
+
+ data.setText("123 " "456.789 " "abc " "def");
+ KEYS("B", X "123 " "456.789 " "abc " "def");
+ KEYS("W", "123 " X "456.789 " "abc " "def");
+ KEYS("2W", "123 " "456.789 " "abc " X "def");
+ KEYS("B", "123 " "456.789 " X "abc " "def");
+ KEYS("2B", X "123 " "456.789 " "abc " "def");
+ KEYS("4W", "123 " "456.789 " "abc " "de" X "f");
+
+ data.setText("123" N "45." "6" N "" N " " N "789");
+ KEYS("3w", "123" N "45." X "6" N "" N " " N "789");
+ // From Vim help (motion.txt): An empty line is also considered to be a word.
+ KEYS("w", "123" N "45." "6" N X "" N " " N "789");
+ KEYS("w", "123" N "45." "6" N "" N " " N X "789");
+
+ KEYS("b", "123" N "45." "6" N X "" N " " N "789");
+ KEYS("4b", X "123" N "45." "6" N "" N " " N "789");
+
+ KEYS("3e", "123" N "45" X "." "6" N "" N " " N "789");
+ KEYS("e", "123" N "45" "." X "6" N "" N " " N "789");
+ // Command "e" does not stop on empty lines ("ge" does).
+ KEYS("e", "123" N "45" "." "6" N "" N " " N "78" X "9");
+ KEYS("ge", "123" N "45" "." "6" N X "" N " " N "789");
+ KEYS("2ge", "123" N "45" X "." "6" N "" N " " N "789");
+
+ // do not move behind end of line in normal mode
+ data.setText("abc def" N "ghi");
+ KEYS("$h", "abc d" X "ef" N "ghi");
+ data.setText("abc def" N "ghi");
+ KEYS("4e", "abc def" N "gh" X "i");
+ data.setText("abc def" N "ghi");
+ KEYS("$i", "abc de" X "f" N "ghi");
+
+ // move behind end of line in insert mode
+ data.setText("abc def" N "ghi");
+ KEYS("i<end>", "abc def" X N "ghi");
+ data.setText("abc def" N "ghi");
+ KEYS("A", "abc def" X N "ghi");
+ data.setText("abc def" N "ghi");
+ KEYS("$a", "abc def" X N "ghi");
+
+ data.setText("abc" N "def ghi");
+ KEYS("i<end><down>", "abc" N "def ghi" X);
+ data.setText("abc" N "def ghi");
+ KEYS("<end>i<down>", "abc" N "de" X "f ghi");
+ data.setText("abc" N "def ghi");
+ KEYS("<end>a<down>", "abc" N "def" X " ghi");
+
+ // paragraph movement
+ data.setText("abc" N N "def");
+ KEYS("}", "abc" N X N "def");
+ KEYS("}", "abc" N N "de" X "f");
+ KEYS("{", "abc" N X N "def");
+ KEYS("{", X "abc" N N "def");
+
+ data.setText("abc" N N N N "def");
+ KEYS("}", "abc" N X N N N "def");
+ KEYS("}", "abc" N N N N "de" X "f");
+ KEYS("3{", "abc" N N N N "de" X "f");
+ KEYS("{", "abc" N N N X N "def");
+ KEYS("{", X "abc" N N N N "def");
+ KEYS("3}", X "abc" N N N N "def");
+
+ data.setText("abc def");
+ KEYS("}", "abc de" X "f");
+ KEYS("{", X "abc def");
+}
+
+void FakeVimPlugin::test_vim_insert()
+{
+ TestData data;
+ setup(&data);
+
+ // basic insert text
+ data.setText("ab" X "c" N "def");
+ KEYS("i 123", "ab 123" X "c" N "def");
+ INTEGRITY(false);
+
+ data.setText("ab" X "c" N "def");
+ KEYS("a 123", "abc 123" X N "def");
+ INTEGRITY(true);
+
+ data.setText("ab" X "c" N "def");
+ KEYS("I 123", " 123" X "abc" N "def");
+ INTEGRITY(false);
+
+ data.setText("abc" N "def");
+ KEYS("A 123", "abc 123" X N "def");
+ INTEGRITY(true);
+
+ data.setText("abc" N "def");
+ KEYS("o 123", "abc" N " 123" X N "def");
+ INTEGRITY(false);
+
+ data.setText("abc" N "def");
+ KEYS("O 123", " 123" X N "abc" N "def");
+ INTEGRITY(false);
+
+ // insert text [count] times
+ data.setText("ab" X "c" N "def");
+ KEYS("3i 123<esc>", "ab 123 123 12" X "3c" N "def");
+ INTEGRITY(false);
+
+ data.setText("ab" X "c" N "def");
+ KEYS("3a 123<esc>", "abc 123 123 12" X "3" N "def");
+ INTEGRITY(true);
+
+ data.setText("ab" X "c" N "def");
+ KEYS("3I 123<esc>", " 123 123 12" X "3abc" N "def");
+ INTEGRITY(false);
+
+ data.setText("abc" N "def");
+ KEYS("3A 123<esc>", "abc 123 123 12" X "3" N "def");
+ INTEGRITY(true);
+
+ data.setText("abc" N "def");
+ KEYS("3o 123<esc>", "abc" N " 123" N " 123" N " 12" X "3" N "def");
+ INTEGRITY(false);
+
+ data.setText("abc" N "def");
+ KEYS("3O 123<esc>", " 123" N " 123" N " 12" X "3" N "abc" N "def");
+ INTEGRITY(false);
+
+ // <C-O>
+ data.setText("abc" N "d" X "ef");
+ KEYS("i<c-o>xX", "abc" N "dX" X "f");
+ KEYS("i<c-o><end>", "abc" N "dXf" X);
+ data.setText("ab" X "c" N "def");
+ KEYS("i<c-o>rX", "ab" X "X" N "def");
+ data.setText("abc" N "def");
+ KEYS("A<c-o>x", "ab" X N "def");
+ data.setText("abc" N "de" X "f");
+ KEYS("i<c-o>0x", "abc" N "x" X "def");
+ data.setText("abc" N "de" X "f");
+ KEYS("i<c-o>ggx", "x" X "abc" N "def");
+
+ // <INSERT> to toggle between insert and replace mode
+ data.setText("abc" N "def");
+ KEYS("<insert>XYZ<insert>xyz<esc>", "XYZxy" X "z" N "def");
+ KEYS("<insert><insert>" "<c-o>0<c-o>j" "XY<insert>Z", "XYZxyz" N "XYZ" X "f");
+
+ // dot command for insert
+ data.setText("abc" N "def");
+ KEYS("ix<insert>X<insert>y<esc>", "xX" X "ybc" N "def");
+ KEYS("0j.", "xXybc" N "xX" X "yef");
+
+ data.setText("abc" N "def");
+ KEYS("<insert>x<insert>X<right>Y<esc>", "xXb" X "Y" N "def");
+ KEYS("0j.", "xXbY" N X "Yef");
+
+ data.setText("abc" N "def");
+ KEYS("<insert>x<insert>X<left><left><down><esc>", "xXbc" N X "def");
+ KEYS(".", "xXbc" N "x" X "Xef");
+
+ // delete in insert mode is part of dot command
+ data.setText("abc" N "def");
+ KEYS("iX<delete>Y", "XY" X "bc" N "def");
+ KEYS("0j.", "XYbc" N "X" X "Yef");
+
+ data.setText("abc" N "def");
+ KEYS("2iX<delete>Y<esc>", "XYX" X "Yc" N "def");
+ KEYS("0j.", "XYXYc" N "XYX" X "Yf");
+
+ data.setText("abc" N "def");
+ KEYS("i<delete>XY", "XY" X "bc" N "def");
+ KEYS("0j.", "XYbc" N "X" X "Yef");
+
+ data.setText("ab" X "c" N "def");
+ KEYS("i<bs>XY", "aXY" X "c" N "def");
+ KEYS("j.", "aXYc" N "dX" X "Yf");
+
+ // insert in visual block mode
+ data.setText("abc" N "d" X "ef" N "jkl" N "mno" N "pqr");
+ KEYS("<c-v>2j" "2I" "XYZ<esc>", "abc" N "d" X "XYZXYZef" N "jXYZXYZkl" N "mXYZXYZno" N "pqr");
+ INTEGRITY(false);
+
+ data.setText("abc" N "d" X "ef" N "jkl" N "mno" N "pqr");
+ KEYS("<c-v>2j" "2A" "XYZ<esc>", "abc" N "d" X "eXYZXYZf" N "jkXYZXYZl" N "mnXYZXYZo" N "pqr");
+ INTEGRITY(false);
+
+ data.setText("abc" N "de" X "f" N "" N "jkl" N "mno");
+ KEYS("<c-v>2jh" "2I" "XYZ<esc>", "abc" N "d" X "XYZXYZef" N "" N "jXYZXYZkl" N "mno");
+ INTEGRITY(false);
+
+ // repeat insert with special characters
+ data.setText("ab" X "c" N "def");
+ KEYS("2i<lt>down><esc>", "ab<down><down" X ">c" N "def");
+ INTEGRITY(false);
+
+ data.setText(" ab" X "c" N " def");
+ KEYS("2I<lt>end><esc>", " <end><end" X ">abc" N " def");
+ KEYS("u", " " X "abc" N " def");
+ KEYS(".", " <end><end" X ">abc" N " def");
+}
+
+void FakeVimPlugin::test_vim_fFtT()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("123()456" N "a(b(c)d)e");
+ KEYS("t(", "12" X "3()456" N "a(b(c)d)e");
+ KEYS("lt(", "123" X "()456" N "a(b(c)d)e");
+ KEYS("0j2t(", "123()456" N "a(" X "b(c)d)e");
+ KEYS("l2T(", "123()456" N "a(b" X "(c)d)e");
+ KEYS("l2T(", "123()456" N "a(" X "b(c)d)e");
+ KEYS("T(", "123()456" N "a(" X "b(c)d)e");
+
+ KEYS("ggf(", "123" X "()456" N "a(b(c)d)e");
+ KEYS("lf(", "123(" X ")456" N "a(b(c)d)e");
+ KEYS("0j2f(", "123()456" N "a(b" X "(c)d)e");
+ KEYS("2F(", "123()456" N "a(b" X "(c)d)e");
+ KEYS("l2F(", "123()456" N "a" X "(b(c)d)e");
+ KEYS("F(", "123()456" N "a" X "(b(c)d)e");
+}
+
+void FakeVimPlugin::test_vim_transform_numbers()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("8");
+ KEYS("<c-a>", X "9");
+ INTEGRITY(false);
+ KEYS("<c-x>", X "8");
+ INTEGRITY(false);
+ KEYS("<c-a>", X "9");
+ KEYS("<c-a>", "1" X "0");
+ KEYS("<c-a>", "1" X "1");
+ KEYS("5<c-a>", "1" X "6");
+ INTEGRITY(false);
+ KEYS("10<c-a>", "2" X "6");
+ KEYS("h100<c-a>", "12" X "6");
+ KEYS("100<c-x>", "2" X "6");
+ INTEGRITY(false);
+ KEYS("10<c-x>", "1" X "6");
+ KEYS("5<c-x>", "1" X "1");
+ KEYS("5<c-x>", X "6");
+ KEYS("6<c-x>", X "0");
+ KEYS("<c-x>", "-" X "1");
+ KEYS("h10<c-x>", "-1" X "1");
+ KEYS("h100<c-x>", "-11" X "1");
+ KEYS("h889<c-x>", "-100" X "0");
+
+ // increase nearest number
+ data.setText("x-x+x: 1 2 3 -4 5");
+ KEYS("8<c-a>", "x-x+x: " X "9 2 3 -4 5");
+ KEYS("l8<c-a>", "x-x+x: 9 1" X "0 3 -4 5");
+ KEYS("l8<c-a>", "x-x+x: 9 10 1" X "1 -4 5");
+ KEYS("l16<c-a>", "x-x+x: 9 10 11 1" X "2 5");
+ KEYS("w18<c-x>", "x-x+x: 9 10 11 12 -1" X "3");
+ KEYS("hh13<c-a>", "x-x+x: 9 10 11 12 " X "0");
+ KEYS("B12<c-x>", "x-x+x: 9 10 11 " X "0 0");
+ KEYS("B11<c-x>", "x-x+x: 9 10 " X "0 0 0");
+ KEYS("B10<c-x>", "x-x+x: 9 " X "0 0 0 0");
+ KEYS("B9<c-x>", "x-x+x: " X "0 0 0 0 0");
+ KEYS("B9<c-x>", "x-x+x: -" X "9 0 0 0 0");
+
+ data.setText("-" X "- 1 --");
+ KEYS("<c-x>", "-- " X "0 --");
+ KEYS("u", "-" X "- 1 --");
+ KEYS("<c-r>", "-" X "- 0 --");
+ KEYS("<c-x><c-x>", "-- -" X "2 --");
+ KEYS("2<c-a><c-a>", "-- " X "1 --");
+ KEYS("<c-a>2<c-a>", "-- " X "4 --");
+ KEYS(".", "-- " X "6 --");
+ KEYS("u", "-- " X "4 --");
+ KEYS("<c-r>", "-- " X "6 --");
+
+ // hexadecimal and octal numbers
+ data.setText("0x0 0x1 -1 07 08");
+ KEYS("3<c-a>", "0x" X "3 0x1 -1 07 08");
+ KEYS("7<c-a>", "0x" X "a 0x1 -1 07 08");
+ KEYS("9<c-a>", "0x1" X "3 0x1 -1 07 08");
+ // if last letter in hexadecimal number is capital then all letters are capital
+ KEYS("ifA<esc>", "0x1f" X "A3 0x1 -1 07 08");
+ KEYS("9<c-a>", "0x1FA" X "C 0x1 -1 07 08");
+ KEYS("w1022<c-a>", "0x1FAC 0x3f" X "f -1 07 08");
+ KEYS("w.", "0x1FAC 0x3ff 102" X "1 07 08");
+ // octal number
+ KEYS("w.", "0x1FAC 0x3ff 1021 0200" X "5 08");
+ // non-octal number with leading zeroes
+ KEYS("w.", "0x1FAC 0x3ff 1021 02005 103" X "0");
+
+ // preserve width of hexadecimal and octal numbers
+ data.setText("0x0001");
+ KEYS("<c-a>", "0x000" X "2");
+ KEYS("10<c-a>", "0x000" X "c");
+ KEYS(".", "0x001" X "6");
+ KEYS("999<c-a>", "0x03f" X "d");
+ KEYS("99999<c-a>", "0x18a9" X "c");
+ data.setText("0001");
+ KEYS("<c-a>", "000" X "2");
+ KEYS("10<c-a>", "001" X "4");
+ KEYS("999<c-a>", "0176" X "3");
+ data.setText("0x0100");
+ KEYS("<c-x>", "0x00f" X "f");
+ data.setText("0100");
+ KEYS("<c-x>", "007" X "7");
+}
+
+void FakeVimPlugin::test_vim_delete()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("123" N "456");
+ KEYS("x", "23" N "456");
+ INTEGRITY(false);
+ KEYS("dd", "456");
+ INTEGRITY(false);
+ KEYS("2x", "6");
+ INTEGRITY(false);
+ KEYS("dd", "");
+ INTEGRITY(false);
+
+ data.setText("void main()");
+ KEYS("dt(", "()");
+ INTEGRITY(false);
+
+ data.setText("void main()");
+ KEYS("df(", ")");
+ INTEGRITY(false);
+
+ data.setText("void " X "main()");
+ KEYS("D", "void ");
+ INTEGRITY(false);
+ KEYS("ggd$", "");
+
+ data.setText("abc def ghi");
+ KEYS("2dw", X "ghi");
+ INTEGRITY(false);
+ data.setText("abc def ghi");
+ KEYS("d2w", X "ghi");
+ INTEGRITY(false);
+
+ data.setText("abc " N " def" N " ghi" N "jkl");
+ KEYS("3dw", X "jkl");
+ data.setText("abc " N " def" N " ghi" N "jkl");
+ KEYS("d3w", X "jkl");
+
+ // delete empty line
+ data.setText("a" N X "" N " b");
+ KEYS("dd", "a" N " " X "b");
+
+ // delete on an empty line
+ data.setText("a" N X "" N " b");
+ KEYS("d$", "a" N X "" N " b");
+ INTEGRITY(false);
+
+ // delete in empty document
+ data.setText("");
+ KEYS("dd", X);
+
+ // delete to start of line
+ data.setText(" abc" N " de" X "f" N " ghi");
+ KEYS("d0", " abc" N X "f" N " ghi");
+ INTEGRITY(false);
+ data.setText(" abc" N " de" X "f" N " ghi");
+ KEYS("d^", " abc" N " " X "f" N " ghi");
+ INTEGRITY(false);
+
+ // delete to mark
+ data.setText("abc " X "def ghi");
+ KEYS("ma" "3l" "d`a", "abc " X " ghi");
+ KEYS("u" "gg" "d`a", X "def ghi");
+
+ // delete lines
+ data.setText(" abc" N " de" X "f" N " ghi" N " jkl");
+ KEYS("dj", " abc" N " " X "jkl");
+ INTEGRITY(false);
+ data.setText(" abc" N " def" N " gh" X "i" N " jkl");
+ KEYS("dk", " abc" N " " X "jkl");
+ INTEGRITY(false);
+}
+
+void FakeVimPlugin::test_vim_delete_inner_word()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc def ghi");
+ KEYS("wlldiw", "abc " X " ghi");
+
+ data.setText("abc def ghi jkl");
+ KEYS("3diw", X " ghi jkl");
+ INTEGRITY(false);
+
+ data.setText("abc " X " def");
+ KEYS("diw", "abc" X "def");
+ INTEGRITY(false);
+ KEYS("diw", "");
+
+ data.setText("abc " N " def");
+ KEYS("3diw", X "def");
+
+ data.setText("abc " N " def" N " ghi");
+ KEYS("4diw", " " X "ghi");
+ data.setText("ab" X "c " N " def" N " ghi");
+ KEYS("4diw", " " X "ghi");
+ data.setText("a b" X "c " N " def" N " ghi");
+ KEYS("4diw", "a" X " " N " ghi");
+
+ data.setText("abc def" N "ghi");
+ KEYS("2diw", X "def" N "ghi");
+ data.setText("abc def" N "ghi");
+ KEYS("3diw", X "" N "ghi");
+
+ data.setText("x" N X "" N "" N " ");
+ KEYS("diw", "x" N X "" N "" N " ");
+ data.setText("x" N X "" N "" N " ");
+ KEYS("2diw", "x" N " " X " ");
+ data.setText("x" N X "" N "" N "" N "" N " ");
+ KEYS("3diw", "x" N " " X " ");
+ data.setText("x" N X "" N "" N "" N "" N "" N " ");
+ KEYS("3diw", "x" N X "" N " ");
+ data.setText("x" N X "" N "" N "" N "" N "" N "" N " ");
+ KEYS("4diw", "x" N X "" N " ");
+
+ // delete single-character-word
+ data.setText("a " X "b c");
+ KEYS("diw", "a " X " c");
+}
+
+void FakeVimPlugin::test_vim_delete_a_word()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc def ghi");
+ KEYS("wlldaw", "abc " X "ghi");
+
+ data.setText("abc def ghi jkl");
+ KEYS("wll2daw", "abc " X "jkl");
+
+ data.setText("abc" X " def ghi");
+ KEYS("daw", "abc" X " ghi");
+ INTEGRITY(false);
+ KEYS("daw", "ab" X "c");
+ INTEGRITY(false);
+ KEYS("daw", "");
+
+ data.setText(X " ghi jkl");
+ KEYS("daw", X " jkl");
+ KEYS("ldaw", X " ");
+
+ data.setText("abc def ghi jkl");
+ KEYS("3daw", X "jkl");
+ INTEGRITY(false);
+
+ // remove trailing spaces
+ data.setText("abc " N " def" N " ghi" N "jkl");
+ KEYS("3daw", X "jkl");
+
+ data.setText("abc " N " def" N " ghi" N "jkl");
+ KEYS("3daw", X "jkl");
+
+ data.setText("abc def" N "ghi");
+ KEYS("2daw", X "" N "ghi");
+
+ data.setText("x" N X "" N "" N " ");
+ KEYS("daw", "x" N " " X " ");
+ data.setText("x" N X "" N "" N "" N "" N " ");
+ KEYS("2daw", "x" N " " X " ");
+ data.setText("x" N X "" N "" N "" N "" N "" N " ");
+ KEYS("2daw", "x" N X "" N " ");
+ data.setText("x" N X "" N "" N "" N "" N "" N "" N " ");
+ KEYS("3daw", "x" N " " X " ");
+
+ // delete single-character-word
+ data.setText("a," X "b,c");
+ KEYS("daw", "a," X ",c");
+
+ // delete a word with visual selection
+ data.setText(X "a" N "" N "b");
+ KEYS("vawd", X "" N "" N "b");
+ data.setText(X "a" N "" N "b");
+ KEYS("Vawd", X "" N "" N "b");
+
+ data.setText("abc def g" X "hi");
+ KEYS("vawd", "abc de" X "f");
+ KEYS("u", "abc def" X " ghi");
+
+ // backward visual selection
+ data.setText("abc def g" X "hi");
+ KEYS("vhawd", "abc " X "i");
+
+ data.setText("abc def gh" X "i");
+ KEYS("vhawd", "abc de" X "f");
+
+ data.setText("abc def gh" X "i");
+ KEYS("vh2awd", "ab" X "c");
+}
+
+void FakeVimPlugin::test_vim_change_a_word()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc " X "def ghi");
+ KEYS("caw#", "abc #" X "ghi");
+ INTEGRITY(false);
+ data.setText("abc d" X "ef ghi");
+ KEYS("caw#", "abc #" X "ghi");
+ data.setText("abc de" X "f ghi");
+ KEYS("caw#", "abc #" X "ghi");
+
+ data.setText("abc de" X "f ghi jkl");
+ KEYS("2caw#", "abc #" X "jkl");
+ INTEGRITY(false);
+
+ data.setText("abc" X " def ghi jkl");
+ KEYS("2caw#", "abc#" X " jkl");
+
+ data.setText("abc " X " def ghi jkl");
+ KEYS("2caw#", "abc#" X " jkl");
+
+ data.setText(" abc " N " def" N " ghi" N " jkl");
+ KEYS("3caw#", "#" X N " jkl");
+
+ // change single-character-word
+ data.setText("a " X "b c");
+ KEYS("ciwX<esc>", "a " X "X c");
+ KEYS("cawZ<esc>", "a " X "Zc");
+}
+
+void FakeVimPlugin::test_vim_change_replace()
+{
+ TestData data;
+ setup(&data);
+
+ // preserve lines in replace mode
+ data.setText("abc" N "def");
+ KEYS("llvjhrX", "ab" X "X" N "XXf");
+
+ // change empty line
+ data.setText("a" N X "" N " b");
+ KEYS("ccABC", "a" N "ABC" X N " b");
+ INTEGRITY(false);
+
+ // change on empty line
+ data.setText("a" N X "" N " b");
+ KEYS("c$ABC<esc>", "a" N "AB" X "C" N " b");
+ INTEGRITY(false);
+ KEYS("u", "a" N X "" N " b");
+ KEYS("rA", "a" N X "" N " b");
+
+ // change in empty document
+ data.setText("");
+ KEYS("ccABC", "ABC" X);
+ KEYS("u", "");
+ KEYS("SABC", "ABC" X);
+ KEYS("u", "");
+ KEYS("sABC", "ABC" X);
+ KEYS("u", "");
+ KEYS("rA", "" X);
+
+ // indentation with change
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=2");
+ data.setText("int main()" N
+ "{" N
+ " " X " return 0;" N
+ "}" N
+ "");
+
+ KEYS("cc" "int i = 0;",
+ "int main()" N
+ "{" N
+ " int i = 0;" X N
+ "}" N
+ "");
+ INTEGRITY(false);
+
+ KEYS("uS" "int i = 0;" N "int j = 1;",
+ "int main()" N
+ "{" N
+ " int i = 0;" N
+ " int j = 1;" X N
+ "}" N
+ "");
+
+ // change to start of line
+ data.setText(" abc" N " de" X "f" N " ghi");
+ KEYS("c0123<ESC>", " abc" N "12" X "3f" N " ghi");
+ INTEGRITY(false);
+ data.setText(" abc" N " de" X "f" N " ghi");
+ KEYS("c^123<ESC>", " abc" N " 12" X "3f" N " ghi");
+ INTEGRITY(false);
+
+ // change to mark
+ data.setText("abc " X "def ghi");
+ KEYS("ma" "3l" "c`a123<ESC>", "abc 12" X "3 ghi");
+ KEYS("u" "gg" "c`a123<ESC>", "12" X "3def ghi");
+
+ // change lines
+ data.setText(" abc" N " de" X "f" N " ghi" N " jkl");
+ KEYS("cj123<ESC>", " abc" N " 12" X "3" N " jkl");
+ INTEGRITY(false);
+ data.setText(" abc" N " def" N " gh" X "i" N " jkl");
+ KEYS("ck123<ESC>", " abc" N " 12" X "3" N " jkl");
+ INTEGRITY(false);
+
+ data.setText("abc" N X "def");
+ KEYS("sXYZ", "abc" N "XYZ" X "ef");
+ INTEGRITY(false);
+
+ data.setText("abc" N X "def");
+ KEYS("2sXYZ<ESC>", "abc" N "XY" X "Zf");
+ INTEGRITY(false);
+
+ data.setText("abc" N X "def");
+ KEYS("6sXYZ<ESC>", "abc" N "XY" X "Z");
+ INTEGRITY(false);
+
+ // insert in visual block mode
+ data.setText("abc" N "d" X "ef" N "jkl" N "mno" N "pqr");
+ KEYS("<c-v>2j" "2s" "XYZ<esc>", "abc" N "d" X "XYZf" N "jXYZl" N "mXYZo" N "pqr");
+ INTEGRITY(false);
+
+ data.setText("abc" N "de" X "f" N "" N "jkl" N "mno");
+ KEYS("<c-v>2jh" "2s" "XYZ<esc>", "abc" N "d" X "XYZ" N "" N "jXYZ" N "mno");
+ INTEGRITY(false);
+}
+
+void FakeVimPlugin::test_vim_block_selection()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("int main(int /* (unused) */, char *argv[]);");
+ KEYS("f(", "int main" X "(int /* (unused) */, char *argv[]);");
+ KEYS("da(", "int main" X ";");
+ INTEGRITY(false);
+
+ data.setText("int main(int /* (unused) */, char *argv[]);");
+ KEYS("f(", "int main" X "(int /* (unused) */, char *argv[]);");
+ KEYS("di(", "int main(" X ");");
+ INTEGRITY(false);
+
+ data.setText("int main(int /* (unused) */, char *argv[]);");
+ KEYS("2f)", "int main(int /* (unused) */, char *argv[]" X ");");
+ KEYS("da(", "int main" X ";");
+
+ data.setText("int main(int /* (unused) */, char *argv[]);");
+ KEYS("2f)", "int main(int /* (unused) */, char *argv[]" X ");");
+ KEYS("di(", "int main(" X ");");
+
+ data.setText("{ { { } } }");
+ KEYS("2f{l", "{ { {" X " } } }");
+ KEYS("da{", "{ { " X " } }");
+ KEYS("da{", "{ " X " }");
+ INTEGRITY(false);
+
+ data.setText("{ { { } } }");
+ KEYS("2f{l", "{ { {" X " } } }");
+ KEYS("2da{", "{ " X " }");
+ INTEGRITY(false);
+
+ data.setText("{" N " { " N " } " N "}");
+ KEYS("di{", "{" N "}");
+
+ data.setText("(" X "())");
+ KEYS("di(", "((" X "))");
+ data.setText("\"\"");
+ KEYS("di\"", "\"" X "\"");
+
+ // visual selection
+ data.setText("(abc()" X "(def))");
+ KEYS("vi(d", "(abc()(" X "))");
+ KEYS("u", "(abc()(" X "def))");
+ KEYS("<c-r>", "(abc()(" X "))");
+ KEYS("va(d", "(abc()" X ")");
+ KEYS("u", "(abc()" X "())");
+ KEYS("<c-r>", "(abc()" X ")");
+
+ data.setText("\"abc" X "\"\"def\"");
+ KEYS("vi\"d", "\"" X "\"\"def\"");
+
+ // repeat change inner
+ data.setText("(abc)" N "def" N "(ghi)");
+ KEYS("ci(xyz<esc>", "(xy" X "z)" N "def" N "(ghi)");
+ KEYS("j.", "(xyz)" N "de" X "f" N "(ghi)");
+ KEYS("j.", "(xyz)" N "def" N "(xy" X "z)");
+
+ // quoted string
+ data.setText("\"abc" X "\"\"def\"");
+ KEYS("di\"", "\"" X "\"\"def\"");
+ KEYS("u", "\"" X "abc\"\"def\"");
+ KEYS("<c-r>", "\"" X "\"\"def\"");
+
+ NOT_IMPLEMENTED
+ // quoted string with escaped character
+ data.setText("\"abc\"");
+ KEYS("di\"", "\"abc\"\"" X "\"");
+ KEYS("u", "\"abc\"\"" X "def\"");
+}
+
+void FakeVimPlugin::test_vim_repeat()
+{
+ TestData data;
+ setup(&data);
+
+ // delete line
+ data.setText("abc" N "def" N "ghi");
+ KEYS("dd", X "def" N "ghi");
+ KEYS(".", X "ghi");
+ INTEGRITY(false);
+
+ // delete to next word
+ data.setText("abc def ghi jkl");
+ KEYS("dw", X "def ghi jkl");
+ KEYS("w.", "def " X "jkl");
+ KEYS("gg.", X "jkl");
+
+ // change in word
+ data.setText("WORD text");
+ KEYS("ciwWORD<esc>", "WOR" X "D text");
+ KEYS("w.", "WORD WOR" X "D");
+
+ /* QTCREATORBUG-7248 */
+ data.setText("test tex" X "t");
+ KEYS("vbcWORD<esc>", "test " "WOR" X "D");
+ KEYS("bb.", "WOR" X "D WORD");
+
+ // delete selected range
+ data.setText("abc def ghi jkl");
+ KEYS("viwd", X " def ghi jkl");
+ KEYS(".", X "f ghi jkl");
+ KEYS(".", X "hi jkl");
+
+ // delete two lines
+ data.setText("abc" N "def" N "ghi" N "jkl" N "mno");
+ KEYS("Vjx", X "ghi" N "jkl" N "mno");
+ KEYS(".", X "mno");
+
+ // delete three lines
+ data.setText("abc" N "def" N "ghi" N "jkl" N "mno" N "pqr" N "stu");
+ KEYS("d2j", X "jkl" N "mno" N "pqr" N "stu");
+ KEYS(".", X "stu");
+
+ // replace block selection
+ data.setText("abcd" N "d" X "efg" N "ghij" N "jklm");
+ KEYS("<c-v>jlrX", "abcd" N "d" X "XXg" N "gXXj" N "jklm");
+ KEYS("gg.", "XXcd" N "XXXg" N "gXXj" N "jklm");
+}
+
+void FakeVimPlugin::test_vim_search()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc" N "def" N "ghi");
+ KEYS("/ghi<CR>", "abc" N "def" N X "ghi");
+ KEYS("gg/\\w\\{3}<CR>", "abc" N X "def" N "ghi");
+ KEYS("n", "abc" N "def" N X "ghi");
+ KEYS("N", "abc" N X "def" N "ghi");
+ KEYS("N", X "abc" N "def" N "ghi");
+
+ // return to search-start position on escape or not found
+ KEYS("/def<ESC>", X "abc" N "def" N "ghi");
+ KEYS("/x", X "abc" N "def" N "ghi");
+ KEYS("/x<CR>", X "abc" N "def" N "ghi");
+ KEYS("/x<ESC>", X "abc" N "def" N "ghi");
+ KEYS("/ghX", X "abc" N "def" N "ghi");
+
+ KEYS("?def<ESC>", X "abc" N "def" N "ghi");
+ KEYS("?x", X "abc" N "def" N "ghi");
+ KEYS("?x<CR>", X "abc" N "def" N "ghi");
+ KEYS("?x<ESC>", X "abc" N "def" N "ghi");
+
+ // search [count] times
+ data.setText("abc" N "def" N "ghi");
+ KEYS("/\\w\\{3}<CR>", "abc" N X "def" N "ghi");
+ KEYS("2n", X "abc" N "def" N "ghi");
+ KEYS("2N", "abc" N X "def" N "ghi");
+ KEYS("2/\\w\\{3}<CR>", X "abc" N "def" N "ghi");
+
+ // set wrapscan (search wraps at end of file)
+ data.doCommand("set ws");
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl");
+ KEYS("*", "abc" N "def" N X "abc" N "ghi abc jkl");
+ KEYS("*", "abc" N "def" N "abc" N "ghi " X "abc jkl");
+ KEYS("2*", "abc" N "def" N X "abc" N "ghi abc jkl");
+ KEYS("#", X "abc" N "def" N "abc" N "ghi abc jkl");
+ KEYS("#", "abc" N "def" N "abc" N "ghi " X "abc jkl");
+ KEYS("#", "abc" N "def" N X "abc" N "ghi abc jkl");
+ KEYS("2#", "abc" N "def" N "abc" N "ghi " X "abc jkl");
+
+ data.doCommand("set nows");
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl");
+ KEYS("*", "abc" N "def" N X "abc" N "ghi abc jkl");
+ KEYS("*", "abc" N "def" N "abc" N "ghi " X "abc jkl");
+ KEYS("*", "abc" N "def" N "abc" N "ghi " X "abc jkl");
+ KEYS("#", "abc" N "def" N X "abc" N "ghi abc jkl");
+ KEYS("#", X "abc" N "def" N "abc" N "ghi abc jkl");
+ KEYS("#", X "abc" N "def" N "abc" N "ghi abc jkl");
+
+ data.setText("abc" N "def" N "ab" X "c" N "ghi abc jkl");
+ KEYS("#", X "abc" N "def" N "abc" N "ghi abc jkl");
+
+ // search with g* and g#
+ data.doCommand("set nows");
+ data.setText("bc" N "abc" N "abcd" N "bc" N "b");
+ KEYS("g*", "bc" N "a" X "bc" N "abcd" N "bc" N "b");
+ KEYS("n", "bc" N "abc" N "a" X "bcd" N "bc" N "b");
+ KEYS("n", "bc" N "abc" N "abcd" N X "bc" N "b");
+ KEYS("n", "bc" N "abc" N "abcd" N X "bc" N "b");
+ KEYS("g#", "bc" N "abc" N "a" X "bcd" N "bc" N "b");
+ KEYS("n", "bc" N "a" X "bc" N "abcd" N "bc" N "b");
+ KEYS("N", "bc" N "abc" N "a" X "bcd" N "bc" N "b");
+ KEYS("3n", "bc" N "abc" N "a" X "bcd" N "bc" N "b");
+ KEYS("2n", X "bc" N "abc" N "abcd" N "bc" N "b");
+
+ /* QTCREATORBUG-7251 */
+ data.setText("abc abc abc abc");
+ KEYS("$?abc<CR>", "abc abc abc " X "abc");
+ KEYS("2?abc<CR>", "abc " X "abc abc abc");
+ KEYS("n", X "abc abc abc abc");
+ KEYS("N", "abc " X "abc abc abc");
+
+ // search is greedy
+ data.doCommand("set ws");
+ data.setText("abc" N "def" N "abc" N "ghi abc jkl");
+ KEYS("/[a-z]*<CR>", "abc" N X "def" N "abc" N "ghi abc jkl");
+ KEYS("2n", "abc" N "def" N "abc" N X "ghi abc jkl");
+ KEYS("3n", "abc" N "def" N "abc" N "ghi abc" X " jkl");
+ KEYS("3N", "abc" N "def" N "abc" N X "ghi abc jkl");
+ KEYS("2N", "abc" N X "def" N "abc" N "ghi abc jkl");
+
+ data.setText("a.b.c" N "" N "d.e.f");
+ KEYS("/[a-z]*<CR>", "a" X ".b.c" N "" N "d.e.f");
+ KEYS("n", "a." X "b.c" N "" N "d.e.f");
+ KEYS("2n", "a.b." X "c" N "" N "d.e.f");
+ KEYS("n", "a.b.c" N X "" N "d.e.f");
+ KEYS("n", "a.b.c" N "" N X "d.e.f");
+ KEYS("2N", "a.b." X "c" N "" N "d.e.f");
+ KEYS("2n", "a.b.c" N "" N X "d.e.f");
+
+ // find same stuff forward and backward,
+ // i.e. '<ab>c' forward but not 'a<bc>' backward
+ data.setText("abc" N "def" N "ghi");
+ KEYS("/\\w\\{2}<CR>", "abc" N X "def" N "ghi");
+ KEYS("n", "abc" N "def" N X "ghi");
+ KEYS("N", "abc" N X "def" N "ghi");
+ KEYS("N", X "abc" N "def" N "ghi");
+ KEYS("2n2N", X "abc" N "def" N "ghi");
+}
+
+void FakeVimPlugin::test_vim_indent()
+{
+ TestData data;
+ setup(&data);
+
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=4");
+
+ data.setText(
+ "abc" N
+ "def" N
+ "ghi" N
+ "jkl" N
+ "mno");
+ KEYS("j3>>",
+ "abc" N
+ " " X "def" N
+ " ghi" N
+ " jkl" N
+ "mno");
+ KEYS("j2>>",
+ "abc" N
+ " def" N
+ " " X "ghi" N
+ " jkl" N
+ "mno");
+
+ KEYS("2<<",
+ "abc" N
+ " def" N
+ " " X "ghi" N
+ " jkl" N
+ "mno");
+ INTEGRITY(false);
+ KEYS("k3<<",
+ "abc" N
+ X "def" N
+ "ghi" N
+ "jkl" N
+ "mno");
+
+ data.setText(
+ "abc" N
+ "def" N
+ "ghi" N
+ "jkl" N
+ "mno");
+ KEYS("jj>j",
+ "abc" N
+ "def" N
+ " " X "ghi" N
+ " jkl" N
+ "mno");
+
+ data.setText("abc");
+ KEYS(">>", " " X "abc");
+ INTEGRITY(false);
+
+ data.setText("abc");
+ data.doCommand("set shiftwidth=2");
+ KEYS(">>", " " X "abc");
+
+ data.setText("abc");
+ data.doCommand("set noexpandtab");
+ data.doCommand("set tabstop=2");
+ data.doCommand("set shiftwidth=7");
+ // shiftwidth = TABS * tabstop + SPACES
+ // 7 = 3 * 2 + 1
+ KEYS(">>", "\t\t\t abc");
+
+ data.doCommand("set tabstop=3");
+ data.doCommand("set shiftwidth=7");
+ data.setText("abc");
+ KEYS(">>", "\t\t abc");
+ INTEGRITY(false);
+}
+
+void FakeVimPlugin::test_vim_marks()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(" abc" N " def" N " ghi");
+ data.doKeys("ma");
+ data.doKeys("ma");
+ data.doKeys("jmb");
+ data.doKeys("j^mc");
+ KEYS("'a", " " X "abc" N " " "def" N " " "ghi");
+ KEYS("`a", X " " "abc" N " " "def" N " " "ghi");
+ KEYS("`b", " " "abc" N X " " "def" N " " "ghi");
+ KEYS("'b", " " "abc" N " " X "def" N " " "ghi");
+ KEYS("`c", " " "abc" N " " "def" N " " X "ghi");
+ KEYS("'c", " " "abc" N " " "def" N " " X "ghi");
+
+ KEYS("`b", " " "abc" N X " " "def" N " " "ghi");
+ KEYS("'c", " " "abc" N " " "def" N " " X "ghi");
+
+ KEYS("`'", " " "abc" N X " " "def" N " " "ghi");
+ KEYS("`a", X " " "abc" N " " "def" N " " "ghi");
+ KEYS("''", " " "abc" N " " X "def" N " " "ghi");
+ KEYS("`'", X " " "abc" N " " "def" N " " "ghi");
+ KEYS("`'", " " "abc" N " " X "def" N " " "ghi");
+
+ // new mark isn't lost on undo
+ data.setText( "abc" N "d" X "ef" N "ghi");
+ KEYS("x" "mx" "gg", X "abc" N "df" N "ghi");
+ KEYS("ugg" "`x", "abc" N "d" X "ef" N "ghi");
+
+ // previous value of mark is restored on undo/redo
+ data.setText( "abc" N "d" X "ef" N "ghi");
+ KEYS("mx" "x" "ggl", "a" X "bc" N "df" N "ghi");
+ KEYS("mx" "uG" "`x", "abc" N "d" X "ef" N "ghi");
+ KEYS("<c-r>G" "`x", "a" X "bc" N "df" N "ghi");
+ KEYS("uG" "`x", "abc" N "d" X "ef" N "ghi");
+ KEYS("<c-r>G" "`x", "a" X "bc" N "df" N "ghi");
+}
+
+void FakeVimPlugin::test_vim_jumps()
+{
+ TestData data;
+ setup(&data);
+
+ // last position
+ data.setText(" abc" N " def" N " ghi");
+ KEYS("G", " abc" N " def" N " " X "ghi");
+ KEYS("`'", X " abc" N " def" N " ghi");
+ KEYS("`'", " abc" N " def" N " " X "ghi");
+ KEYS("''", " " X "abc" N " def" N " ghi");
+ KEYS("<C-O>", " abc" N " def" N " " X "ghi");
+ KEYS("<C-I>", " " X "abc" N " def" N " ghi");
+
+ KEYS("lgUlhj", " aBc" N " " X "def" N " ghi");
+ KEYS("`.", " a" X "Bc" N " def" N " ghi");
+ KEYS("`'", " aBc" N " " X "def" N " ghi");
+ KEYS("'.", " " X "aBc" N " def" N " ghi");
+ KEYS("G", " aBc" N " def" N " " X "ghi");
+ KEYS("u", " a" X "bc" N " def" N " ghi");
+ KEYS("`'", " abc" N " def" N " " X "ghi");
+ KEYS("<c-r>", " a" X "Bc" N " def" N " ghi");
+ KEYS("jd$", " aBc" N " " X "d" N " ghi");
+ KEYS("''", " aBc" N " d" N " " X "ghi");
+ KEYS("`'", " aBc" N " " X "d" N " ghi");
+ KEYS("u", " aBc" N " d" X "ef" N " ghi");
+ KEYS("''", " aBc" N " " X "def" N " ghi");
+ KEYS("`'", " aBc" N " d" X "ef" N " ghi");
+
+ // record external position changes
+ data.setText("abc" N "def" N "g" X "hi");
+ data.jump("abc" N "de" X "f" N "ghi");
+ KEYS("<C-O>", "abc" N "def" N "g" X "hi");
+ KEYS("<C-I>", "abc" N "de" X "f" N "ghi");
+ data.jump("ab" X "c" N "def" N "ghi");
+ KEYS("<C-O>", "abc" N "de" X "f" N "ghi");
+ KEYS("<C-O>", "abc" N "def" N "g" X "hi");
+}
+
+void FakeVimPlugin::test_vim_current_column()
+{
+ // Check if column is correct after command and vertical cursor movement.
+ TestData data;
+ setup(&data);
+
+ // always at end of line after <end>
+ data.setText(" abc" N " def 123" N "" N " ghi");
+ KEYS("<end><down>", " abc" N " def 12" X "3" N "" N " ghi");
+ KEYS("<down><down>", " abc" N " def 123" N "" N " gh" X "i");
+ KEYS("<up>", " abc" N " def 123" N X "" N " ghi");
+ KEYS("<up>", " abc" N " def 12" X "3" N "" N " ghi");
+ // ... in insert
+ KEYS("i<end><up>", " abc" X N " def 123" N "" N " ghi");
+ KEYS("<down>i<end><up><down>", " abc" N " def 123" X N "" N " ghi");
+
+ // vertical movement doesn't reset column
+ data.setText(" abc" N " def 1" X "23" N "" N " ghi");
+ KEYS("<up>", " ab" X "c" N " def 123" N "" N " ghi");
+ KEYS("<down>", " abc" N " def 1" X "23" N "" N " ghi");
+ KEYS("<down><down>", " abc" N " def 123" N "" N " gh" X "i");
+ KEYS("<up><up>", " abc" N " def 1" X "23" N "" N " ghi");
+ KEYS("^jj", " abc" N " def 123" N "" N " " X "ghi");
+ KEYS("kk", " abc" N " " X "def 123" N "" N " ghi");
+
+ // yiw, yaw
+ data.setText(" abc" N " def" N " ghi");
+ KEYS("e<down>", " abc" N " de" X "f" N " ghi");
+ KEYS("b<down>", " abc" N " def" N " " X "ghi");
+ KEYS("ll<up>", " abc" N " de" X "f" N " ghi");
+ KEYS("<down>yiw<up>", " abc" N " " X "def" N " ghi");
+ KEYS("llyaw<up>", " " X "abc" N " def" N " ghi");
+
+ // insert
+ data.setText(" abc" N " def" N " ghi");
+ KEYS("lljj", " abc" N " def" N " " X "ghi");
+ KEYS("i123<up>", " abc" N " def" X N " 123ghi");
+ KEYS("a456<up><down>", " abc" N " def456" X N " 123ghi");
+
+ data.setText(" abc" N X " def 123" N "" N " ghi");
+ KEYS("A<down><down>", " abc" N " def 123" N "" N " ghi" X);
+ KEYS("A<up><up>", " abc" N " def" X " 123" N "" N " ghi");
+ KEYS("A<down><down><up><up>", " abc" N " def 123" X N "" N " ghi");
+
+ data.setText(" abc" N X " def 123" N "" N " ghi");
+ KEYS("I<down><down>", " abc" N " def 123" N "" N " " X "ghi");
+
+ // change
+ data.setText(" abc" N " d" X "ef" N " ghi");
+ KEYS("cc<up>", " " X "abc" N " " N " ghi");
+ data.setText(" abc" N " d" X "ef" N " ghi");
+ KEYS("cc<up>x<down><down>", " xabc" N " " N " g" X "hi");
+}
+
+void FakeVimPlugin::test_vim_copy_paste()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("123" N "456");
+ KEYS("llyy2P", X "123" N "123" N "123" N "456");
+
+ data.setText("123" N "456");
+ KEYS("yyp", "123" N X "123" N "456");
+ KEYS("2p", "123" N "123" N X "123" N "123" N "456");
+ INTEGRITY(false);
+
+ data.setText("123 456");
+ KEYS("yw2P", "123 123" X " 123 456");
+ KEYS("2p", "123 123 123 123" X " 123 456");
+
+ data.setText("123" N "456");
+ KEYS("2yyp", "123" N X "123" N "456" N "456");
+
+ data.setText("123" N "456");
+ KEYS("2yyP", X "123" N "456" N "123" N "456");
+
+ data.setText("123" N "456" N "789");
+ KEYS("ddp", "456" N X "123" N "789");
+
+ // block-select middle column, copy and paste twice
+ data.setText("123" N "456");
+ KEYS("l<C-v>j\"xy2\"xp", "12" X "223" N "45556");
+
+ data.setText("123" N "456" N "789");
+ KEYS("wyiw" "wviwp", "123" N "456" N "45" X "6");
+
+ // QTCREATORBUG-8148
+ data.setText("abc");
+ KEYS("yyp", "abc" N X "abc");
+ KEYS("4p", "abc" N "abc" N X "abc" N "abc" N "abc" N "abc");
+
+ // cursor position after yank
+ data.setText("ab" X "c" N "def");
+ KEYS("Vjy", X "abc" N "def");
+ data.setText("ab" X "c" N "def");
+ KEYS("<c-v>jhhy", X "abc" N "def");
+ data.setText("ab" X "c" N "def");
+ KEYS("yj", "ab" X "c" N "def");
+ data.setText("abc" N "de" X "f");
+ KEYS("yk", "ab" X "c" N "def");
+
+ // copy empty line
+ data.setText(X "a" N "" N "b");
+ KEYS("Vjy", X "a" N "" N "b");
+ KEYS("p", "a" N X "a" N "" N "" N "b");
+}
+
+void FakeVimPlugin::test_vim_undo_redo()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc def" N "xyz" N "123");
+ KEYS("ddu", X "abc def" N "xyz" N "123");
+ COMMAND("redo", X "xyz" N "123");
+ COMMAND("undo", X "abc def" N "xyz" N "123");
+ COMMAND("redo", X "xyz" N "123");
+ KEYS("dd", X "123");
+ KEYS("3x", X "");
+ KEYS("uuu", X "abc def" N "xyz" N "123");
+ KEYS("<C-r>", X "xyz" N "123");
+ KEYS("2<C-r>", X "");
+ KEYS("3u", X "abc def" N "xyz" N "123");
+
+ KEYS("wved", "abc" X " " N "xyz" N "123");
+ KEYS("2w", "abc " N "xyz" N X "123");
+ KEYS("u", "abc " X "def" N "xyz" N "123");
+ KEYS("<C-r>", "abc" X " " N "xyz" N "123");
+ KEYS("10ugg", X "abc def" N "xyz" N "123");
+
+ KEYS("A xxx<ESC>", "abc def xx" X "x" N "xyz" N "123");
+ KEYS("A yyy<ESC>", "abc def xxx yy" X "y" N "xyz" N "123");
+ KEYS("u", "abc def xx" X "x" N "xyz" N "123");
+ KEYS("u", "abc de" X "f" N "xyz" N "123");
+ KEYS("<C-r>", "abc def" X " xxx" N "xyz" N "123");
+ KEYS("<C-r>", "abc def xxx" X " yyy" N "xyz" N "123");
+
+ KEYS("izzz<ESC>", "abc def xxxzz" X "z yyy" N "xyz" N "123");
+ KEYS("<C-r>", "abc def xxxzz" X "z yyy" N "xyz" N "123");
+ KEYS("u", "abc def xxx" X " yyy" N "xyz" N "123");
+
+ data.setText("abc" N X "def");
+ KEYS("oxyz<ESC>", "abc" N "def" N "xy" X "z");
+ KEYS("u", "abc" N X "def");
+
+ // undo paste lines
+ data.setText("abc" N);
+ KEYS("yy2p", "abc" N X "abc" N "abc" N);
+ KEYS("yy3p", "abc" N "abc" N X "abc" N "abc" N "abc" N "abc" N);
+ KEYS("u", "abc" N X "abc" N "abc" N);
+ KEYS("u", X "abc" N);
+ KEYS("<C-r>", X "abc" N "abc" N "abc" N);
+ KEYS("<C-r>", "abc" N X "abc" N "abc" N "abc" N "abc" N "abc" N);
+ KEYS("u", "abc" N X "abc" N "abc" N);
+ KEYS("u", X "abc" N);
+
+ // undo paste block
+ data.setText("abc" N "def" N "ghi");
+ KEYS("<C-v>jyp", "a" X "abc" N "ddef" N "ghi");
+ KEYS("2p", "aa" X "aabc" N "ddddef" N "ghi");
+ KEYS("3p", "aaa" X "aaaabc" N "dddddddef" N "ghi");
+ KEYS("u", "aa" X "aabc" N "ddddef" N "ghi");
+ KEYS("u", "a" X "abc" N "ddef" N "ghi");
+
+ // undo indent
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=4");
+ data.setText("abc" N "def");
+ KEYS(">>", " " X "abc" N "def");
+ KEYS(">>", " " X "abc" N "def");
+ KEYS("<<", " " X "abc" N "def");
+ KEYS("<<", X "abc" N "def");
+ KEYS("u", " " X "abc" N "def");
+ KEYS("u", " " X "abc" N "def");
+ KEYS("u", " " X "abc" N "def");
+ KEYS("u", X "abc" N "def");
+ KEYS("<C-r>", X " abc" N "def");
+ KEYS("<C-r>", " " X " abc" N "def");
+ KEYS("<C-r>", " ab" X "c" N "def");
+ KEYS("<C-r>", "ab" X "c" N "def");
+ KEYS("<C-r>", "ab" X "c" N "def");
+
+ data.setText("abc" N "def");
+ KEYS("2>>", " " X "abc" N " def");
+ KEYS("u", X "abc" N "def");
+ KEYS("<c-r>", X " abc" N " def");
+ KEYS("u", X "abc" N "def");
+ KEYS(">j", " " X "abc" N " def");
+ KEYS("u", X "abc" N "def");
+ KEYS("<c-r>", X " abc" N " def");
+
+ // undo replace line
+ data.setText("abc" N " def" N "ghi");
+ KEYS("jlllSxyz<ESC>", "abc" N "xyz" N "ghi");
+ KEYS("u", "abc" N " " X "def" N "ghi");
+}
+
+void FakeVimPlugin::test_vim_letter_case()
+{
+ TestData data;
+ setup(&data);
+
+ // upper- and lower-case
+ data.setText("abc DEF");
+ KEYS("lv3l~", "a" X "BC dEF");
+ KEYS("v4lU", "a" X "BC DEF");
+ KEYS("v4$u", "a" X "bc def");
+ KEYS("v4$gU", "a" X "BC DEF");
+ KEYS("gu$", "a" X "bc def");
+ KEYS("lg~~", X "ABC DEF");
+ KEYS(".", X "abc def");
+ KEYS("gUiw", X "ABC def");
+
+ data.setText(" ab" X "c" N "def");
+ KEYS("2gUU", " " X "ABC" N "DEF");
+ KEYS("u", " " X "abc" N "def");
+ KEYS("<c-r>", " " X "ABC" N "DEF");
+}
+
+void FakeVimPlugin::test_vim_code_autoindent()
+{
+ TestData data;
+ setup(&data);
+
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=3");
+
+ data.setText("int main()" N
+ X "{" N
+ "}" N
+ "");
+ KEYS("o" "return 0;",
+ "int main()" N
+ "{" N
+ " return 0;" X N
+ "}" N
+ "");
+ INTEGRITY(false);
+ KEYS("O" "int i = 0;",
+ "int main()" N
+ "{" N
+ " int i = 0;" X N
+ " return 0;" N
+ "}" N
+ "");
+ INTEGRITY(false);
+ KEYS("ddO" "int i = 0;" N "int j = 0;",
+ "int main()" N
+ "{" N
+ " int i = 0;" N
+ " int j = 0;" X N
+ " return 0;" N
+ "}" N
+ "");
+ KEYS("^i" "int x = 1;" N,
+ "int main()" N
+ "{" N
+ " int i = 0;" N
+ " int x = 1;" N
+ " " X "int j = 0;" N
+ " return 0;" N
+ "}" N
+ "");
+ KEYS("c2k" "if (true) {" N ";" N "}",
+ "int main()" N
+ "{" N
+ " if (true) {" N
+ " ;" N
+ " }" X N
+ " return 0;" N
+ "}" N
+ "");
+ KEYS("jci{" "return 1;",
+ "int main()" N
+ "{" N
+ " return 1;" X N
+ "}" N
+ "");
+ KEYS("di{",
+ "int main()" N
+ "{" N
+ X "}" N
+ "");
+ INTEGRITY(false);
+
+ // autoindent
+ data.doCommand("set nosmartindent");
+ data.setText("abc" N "def");
+ KEYS("3o 123<esc>", "abc" N " 123" N " 123" N " 12" X "3" N "def");
+ INTEGRITY(false);
+
+ data.setText("abc" N "def");
+ KEYS("3O 123<esc>", " 123" N " 123" N " 12" X "3" N "abc" N "def");
+ INTEGRITY(false);
+ data.doCommand("set smartindent");
+}
+
+void FakeVimPlugin::test_vim_code_folding()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("int main()" N "{" N " return 0;" N "}" N "");
+
+ // fold/unfold function block
+ data.doKeys("zc");
+ QCOMPARE(data.lines(), 2);
+ data.doKeys("zo");
+ QCOMPARE(data.lines(), 5);
+ data.doKeys("za");
+ QCOMPARE(data.lines(), 2);
+
+ // delete whole block
+ KEYS("dd", "");
+
+ // undo/redo
+ KEYS("u", "int main()" N "{" N " return 0;" N "}" N "");
+ KEYS("<c-r>", "");
+
+ // change block
+ KEYS("uggzo", X "int main()" N "{" N " return 0;" N "}" N "");
+ KEYS("ccvoid f()<esc>", "void f(" X ")" N "{" N " return 0;" N "}" N "");
+ KEYS("uzc.", "void f(" X ")" N "");
+
+ // open/close folds recursively
+ data.setText("int main()" N
+ "{" N
+ " if (true) {" N
+ " return 0;" N
+ " } else {" N
+ " // comment" N
+ " " X "return 2" N
+ " }" N
+ "}" N
+ "");
+ int lines = data.lines();
+ // close else block
+ data.doKeys("zc");
+ QCOMPARE(data.lines(), lines - 3);
+ // close function block
+ data.doKeys("zc");
+ QCOMPARE(data.lines(), lines - 8);
+ // jumping to a line opens all its parent folds
+ data.doKeys("6gg");
+ QCOMPARE(data.lines(), lines);
+
+ // close recursively
+ data.doKeys("zC");
+ QCOMPARE(data.lines(), lines - 8);
+ data.doKeys("za");
+ QCOMPARE(data.lines(), lines - 3);
+ data.doKeys("6gg");
+ QCOMPARE(data.lines(), lines);
+ data.doKeys("zA");
+ QCOMPARE(data.lines(), lines - 8);
+ data.doKeys("za");
+ QCOMPARE(data.lines(), lines - 3);
+
+ // close all folds
+ data.doKeys("zM");
+ QCOMPARE(data.lines(), lines - 8);
+ data.doKeys("zo");
+ QCOMPARE(data.lines(), lines - 4);
+ data.doKeys("zM");
+ QCOMPARE(data.lines(), lines - 8);
+
+ // open all folds
+ data.doKeys("zR");
+ QCOMPARE(data.lines(), lines);
+
+ // delete folded lined if deleting to the end of the first folding line
+ data.doKeys("zMgg");
+ QCOMPARE(data.lines(), lines - 8);
+ KEYS("wwd$", "int main" N "");
+
+ // undo
+ KEYS("u", "int main" X "()" N
+ "{" N
+ " if (true) {" N
+ " return 0;" N
+ " } else {" N
+ " // comment" N
+ " return 2" N
+ " }" N
+ "}" N
+ "");
+
+ NOT_IMPLEMENTED
+ // Opening folds recursively isn't supported (previous position in fold isn't restored).
+}
+
+void FakeVimPlugin::test_vim_code_completion()
+{
+ // Test completion by simply bypassing FakeVim and inserting text directly in editor widget.
+ TestData data;
+ setup(&data);
+ data.setText(
+ "int test1Var;" N
+ "int test2Var;" N
+ "int main() {" N
+ " " X ";" N
+ "}" N
+ "");
+
+ data.doKeys("i" "te");
+ data.completeText("st");
+ data.doKeys("1");
+ data.completeText("Var");
+ data.doKeys(" = 0");
+ KEYS("",
+ "int test1Var;" N
+ "int test2Var;" N
+ "int main() {" N
+ " test1Var = " X "0;" N
+ "}" N
+ "");
+
+ data.doKeys("o" "te");
+ data.completeText("st");
+ data.doKeys("2");
+ data.completeText("Var");
+ data.doKeys(" = 1;");
+ KEYS("",
+ "int test1Var;" N
+ "int test2Var;" N
+ "int main() {" N
+ " test1Var = 0;" N
+ " test2Var = 1" X ";" N
+ "}" N
+ "");
+
+ // repeat text insertion with completion
+ KEYS(".",
+ "int test1Var;" N
+ "int test2Var;" N
+ "int main() {" N
+ " test1Var = 0;" N
+ " test2Var = 1;" N
+ " test2Var = 1" X ";" N
+ "}" N
+ "");
+}
+
+void FakeVimPlugin::test_vim_substitute()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abcabc");
+ COMMAND("s/abc/123/", X "123abc");
+ COMMAND("u", X "abcabc");
+ COMMAND("s/abc/123/g", X "123123");
+ COMMAND("u", X "abcabc");
+
+ data.setText("abc" N "def");
+ COMMAND("%s/^/ -- /", " -- abc" N " " X "-- def");
+ COMMAND("u", X "abc" N "def");
+
+ data.setText(" abc" N " def");
+ COMMAND("%s/$/./", " abc." N " " X "def.");
+
+ data.setText("abc" N "def");
+ COMMAND("%s/.*/(&)", "(abc)" N X "(def)");
+ COMMAND("u", X "abc" N "def");
+ COMMAND("%s/.*/X/g", "X" N X "X");
+
+ data.setText("abc" N "" N "def");
+ COMMAND("%s/^\\|$/--", "--abc" N "--" N X "--def");
+ COMMAND("u", X "abc" N "" N "def");
+ COMMAND("%s/^\\|$/--/g", "--abc--" N "--" N X "--def--");
+
+ // captures
+ data.setText("abc def ghi");
+ COMMAND("s/\\w\\+/'&'/g", X "'abc' 'def' 'ghi'");
+ COMMAND("u", X "abc def ghi");
+ COMMAND("s/\\w\\+/'\\&'/g", X "'&' '&' '&'");
+ COMMAND("u", X "abc def ghi");
+ COMMAND("s/\\(\\w\\{3}\\)/(\\1)/g", X "(abc) (def) (ghi)");
+ COMMAND("u", X "abc def ghi");
+ COMMAND("s/\\(\\w\\{3}\\) \\(\\w\\{3\\}\\)/\\2 \\1 \\\\1/g", X "def abc \\1 ghi");
+
+ // case-insensitive
+ data.setText("abc ABC abc");
+ COMMAND("s/ABC/123/gi", X "123 123 123");
+
+ // replace on a line
+ data.setText("abc" N "def" N "ghi");
+ COMMAND("2s/^/ + /", "abc" N " " X "+ def" N "ghi");
+ COMMAND("1s/^/ * /", " " X "* abc" N " + def" N "ghi");
+ COMMAND("$s/^/ - /", " * abc" N " + def" N " " X "- ghi");
+
+ // replace on lines
+ data.setText("abc" N "def" N "ghi");
+ COMMAND("2,$s/^/ + /", "abc" N " + def" N " " X "+ ghi");
+ COMMAND("1,2s/^/ * /", " * abc" N " " X "* + def" N " + ghi");
+ COMMAND("3,3s/^/ - /", " * abc" N " * + def" N " " X "- + ghi");
+ COMMAND("%s/\\( \\S \\)*//g", "abc" N "def" N X "ghi");
+
+ // last substitution
+ data.setText("abc" N "def" N "ghi");
+ COMMAND("%s/DEF/+&/i", "abc" N X "+def" N "ghi");
+ COMMAND("&&", "abc" N X "++def" N "ghi");
+ COMMAND("&", "abc" N X "++def" N "ghi");
+ COMMAND("&&", "abc" N X "++def" N "ghi");
+ COMMAND("&i", "abc" N X "+++def" N "ghi");
+ COMMAND("s", "abc" N X "+++def" N "ghi");
+ COMMAND("&&i", "abc" N X "++++def" N "ghi");
+
+ // search for last substitute pattern
+ data.setText("abc" N "def" N "ghi");
+ COMMAND("%s/def/def", "abc" N X "def" N "ghi");
+ KEYS("gg", X "abc" N "def" N "ghi");
+ COMMAND("\\&", "abc" N X "def" N "ghi");
+
+ // substitute last selection
+ data.setText("abc" N "def" N "ghi" N "jkl");
+ KEYS("jVj:s/^/*<CR>", "abc" N "*def" N X "*ghi" N "jkl");
+ COMMAND("'<,'>s/^/*", "abc" N "**def" N X "**ghi" N "jkl");
+ KEYS("ugv:s/^/+<CR>", "abc" N "+*def" N X "+*ghi" N "jkl");
+}
+
+void FakeVimPlugin::test_vim_ex_yank()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc" N "def");
+ COMMAND("y x", X "abc" N "def");
+ KEYS("\"xp", "abc" N X "abc" N "def");
+ COMMAND("u", X "abc" N "def");
+ COMMAND("redo", X "abc" N "abc" N "def");
+
+ KEYS("uw", "abc" N X "def");
+ COMMAND("1y y", "abc" N X "def");
+ KEYS("\"yP", "abc" N X "abc" N "def");
+ COMMAND("u", "abc" N X "def");
+
+ COMMAND("-1,$y x", "abc" N X "def");
+ KEYS("\"xP", "abc" N X "abc" N "def" N "def");
+ COMMAND("u", "abc" N X "def");
+
+ COMMAND("$-1y", "abc" N X "def");
+ KEYS("P", "abc" N X "abc" N "def");
+ COMMAND("u", "abc" N X "def");
+}
+
+void FakeVimPlugin::test_vim_ex_delete()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc" N X "def" N "ghi" N "jkl");
+ COMMAND("d", "abc" N X "ghi" N "jkl");
+ COMMAND("1,2d", X "jkl");
+ COMMAND("u", X "abc" N "ghi" N "jkl");
+ COMMAND("u", "abc" N X "def" N "ghi" N "jkl");
+ KEYS("p", "abc" N "def" N X "abc" N "ghi" N "ghi" N "jkl");
+ COMMAND("set ws|" "/abc/,/ghi/d|" "set nows", X "ghi" N "jkl");
+ COMMAND("u", X "abc" N "def" N "abc" N "ghi" N "ghi" N "jkl");
+ COMMAND("2,/abc/d3", "abc" N "def" N X "jkl");
+ COMMAND("u", "abc" N "def" N X "abc" N "ghi" N "ghi" N "jkl");
+ COMMAND("5,.+1d", "abc" N "def" N "abc" N X "jkl");
+}
+
+void FakeVimPlugin::test_vim_ex_change()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc" N X "def" N "ghi" N "jkl");
+ KEYS(":c<CR>xxx<ESC>0", "abc" N X "xxx" N "ghi" N "jkl");
+ KEYS(":-1,+1c<CR>XXX<ESC>0", X "XXX" N "jkl");
+}
+
+void FakeVimPlugin::test_vim_ex_shift()
+{
+ TestData data;
+ setup(&data);
+
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=2");
+
+ data.setText("abc" N X "def" N "ghi" N "jkl");
+ COMMAND(">", "abc" N " " X "def" N "ghi" N "jkl");
+ COMMAND(">>", "abc" N " " X "def" N "ghi" N "jkl");
+ COMMAND("<", "abc" N " " X "def" N "ghi" N "jkl");
+ COMMAND("<<", "abc" N X "def" N "ghi" N "jkl");
+}
+
+void FakeVimPlugin::test_vim_ex_move()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc" N "def" N "ghi" N "jkl");
+ COMMAND("m +1", "def" N X "abc" N "ghi" N "jkl");
+ COMMAND("u", X "abc" N "def" N "ghi" N "jkl");
+ COMMAND("redo", X "def" N "abc" N "ghi" N "jkl");
+ COMMAND("m -2", X "def" N "abc" N "ghi" N "jkl");
+ COMMAND("2m0", X "abc" N "def" N "ghi" N "jkl");
+
+ COMMAND("m $-2", "def" N X "abc" N "ghi" N "jkl");
+ KEYS("`'", X "def" N "abc" N "ghi" N "jkl");
+ KEYS("Vj:m+2<cr>", "ghi" N "def" N X "abc" N "jkl");
+ KEYS("u", X "def" N "abc" N "ghi" N "jkl");
+
+ // move visual selection with indentation
+ data.doCommand("set expandtab");
+ data.doCommand("set shiftwidth=2");
+ data.doCommand("vnoremap <C-S-J> :m'>+<CR>gv=");
+ data.doCommand("vnoremap <C-S-K> :m-2<CR>gv=");
+ data.setText(
+ "int x;" N
+ "int y;" N
+ "int main() {" N
+ " if (true) {" N
+ " }" N
+ "}" N
+ "");
+ KEYS("Vj<C-S-J>",
+ "int main() {" N
+ " int x;" N
+ " int y;" N
+ " if (true) {" N
+ " }" N
+ "}" N
+ "");
+ KEYS("gv<C-S-J>",
+ "int main() {" N
+ " if (true) {" N
+ " int x;" N
+ " int y;" N
+ " }" N
+ "}" N
+ "");
+ KEYS("gv<C-S-K>",
+ "int main() {" N
+ " int x;" N
+ " int y;" N
+ " if (true) {" N
+ " }" N
+ "}" N
+ "");
+ data.doCommand("vunmap <C-S-K>");
+ data.doCommand("vunmap <C-S-J>");
+}
+
+void FakeVimPlugin::test_vim_ex_join()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(" abc" N X " def" N " ghi" N " jkl");
+ COMMAND("j", " abc" N " " X "def ghi" N " jkl");
+ COMMAND("u", " abc" N X " def" N " ghi" N " jkl");
+ COMMAND("1j3", " " X "abc def ghi" N " jkl");
+ COMMAND("u", X " abc" N " def" N " ghi" N " jkl");
+}
+
+void FakeVimPlugin::test_advanced_commands()
+{
+ TestData data;
+ setup(&data);
+
+ // subcommands
+ data.setText("abc" N " xxx" N " xxx" N "def");
+ COMMAND("%s/xxx/ZZZ/g|%s/ZZZ/OOO/g", "abc" N " OOO" N " " X "OOO" N "def");
+
+ // undo/redo all subcommands
+ COMMAND(":undo", "abc" N X " xxx" N " xxx" N "def");
+ COMMAND(":redo", "abc" N X " OOO" N " OOO" N "def");
+
+ // redundant characters
+ COMMAND(" ::: %s/\\S\\S\\S/ZZZ/g |"
+ " :: : : %s/ZZZ/XXX/g ", "XXX" N " XXX" N " XXX" N X "XXX");
+
+ // bar character in regular expression is not command separator
+ data.setText("abc");
+ COMMAND("%s/a\\|b\\||/X/g|%s/[^X]/Y/g", "XXY");
+}
+
+void FakeVimPlugin::test_map()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText("abc def");
+ data.doCommand("map C i<space>x<space><esc>");
+ data.doCommand("map c iXXX");
+ data.doCommand("imap c YYY<space>");
+ KEYS("C", " x" X " abc def");
+ data.doCommand("map C <nop>");
+ KEYS("C", " x" X " abc def");
+ data.doCommand("map C i<bs><esc><right>");
+ KEYS("C", " " X " abc def");
+ KEYS("ccc<esc>", " XXXYYY YYY" X " abc def");
+ // unmap
+ KEYS(":unmap c<cr>ccc<esc>", "YYY" X " ");
+ KEYS(":iunmap c<cr>ccc<esc>", X "c");
+ data.doCommand("unmap C");
+
+ data.setText("abc def");
+ data.doCommand("imap x (((<space><right><right>)))<esc>");
+ KEYS("x", X "bc def");
+ KEYS("ix", "((( bc))" X ") def");
+ data.doCommand("iunmap x");
+
+ data.setText("abc def");
+ data.doCommand("map <c-right> 3l");
+ KEYS("<C-Right>", "abc" X " def");
+ KEYS("<C-Right>", "abc de" X "f");
+
+ // map vs. noremap
+ data.setText("abc def");
+ data.doCommand("map x 3l");
+ data.doCommand("map X x");
+ KEYS("X", "abc" X " def");
+ data.doCommand("noremap X x");
+ KEYS("X", "abc" X "def");
+ data.doCommand("unmap X");
+ data.doCommand("unmap x");
+
+ // limit number of recursions in mappings
+ data.doCommand("map X Y");
+ data.doCommand("map Y Z");
+ data.doCommand("map Z X");
+ KEYS("X", "abc" X "def");
+ data.doCommand("map Z i<space><esc>");
+ KEYS("X", "abc" X " def");
+ data.doCommand("unmap X");
+ data.doCommand("unmap Y");
+ data.doCommand("unmap Z");
+
+ // imcomplete mapping
+ data.setText("abc");
+ data.doCommand("map Xa ia<esc>");
+ data.doCommand("map Xb ib<esc>");
+ data.doCommand("map X ic<esc>");
+ KEYS("Xa", X "aabc");
+ KEYS("Xb", X "baabc");
+ KEYS("Xic<esc>", X "ccbaabc");
+
+ // unmap
+ data.doCommand("unmap Xa");
+ KEYS("Xa<esc>", X "cccbaabc");
+ data.doCommand("unmap Xb");
+ KEYS("Xb", X "ccccbaabc");
+ data.doCommand("unmap X");
+ KEYS("Xb", X "ccccbaabc");
+ KEYS("X<esc>", X "ccccbaabc");
+
+ // recursive mapping
+ data.setText("abc");
+ data.doCommand("map X Y");
+ data.doCommand("map XXX i1<esc>");
+ data.doCommand("map Y i2<esc>");
+ data.doCommand("map YZ i3<esc>");
+ data.doCommand("map _ i <esc>");
+ KEYS("_XXX_", X " 1 abc");
+ KEYS("XX_0", X " 22 1 abc");
+ KEYS("XXXXZ_0", X " 31 22 1 abc");
+ KEYS("XXXXX_0", X " 221 31 22 1 abc");
+ KEYS("XXZ", X "32 221 31 22 1 abc");
+ data.doCommand("unmap X");
+ data.doCommand("unmap XXX");
+ data.doCommand("unmap Y");
+ data.doCommand("unmap YZ");
+ data.doCommand("unmap _");
+
+ // shift modifier
+ data.setText("abc");
+ data.doCommand("map x i1<esc>");
+ data.doCommand("map X i2<esc>");
+ KEYS("x", X "1abc");
+ KEYS("X", X "21abc");
+ data.doCommand("map <S-X> i3<esc>");
+ KEYS("X", X "321abc");
+ data.doCommand("map X i4<esc>");
+ KEYS("X", X "4321abc");
+ KEYS("x", X "14321abc");
+ data.doCommand("unmap x");
+ data.doCommand("unmap X");
+
+ // undo/redo mapped input
+ data.setText("abc def ghi");
+ data.doCommand("map X dwea xyz<esc>3l");
+ KEYS("X", "def xyz g" X "hi");
+ KEYS("u", X "abc def ghi");
+ KEYS("<C-r>", X "def xyz ghi");
+ data.doCommand("unmap X");
+
+ data.setText("abc" N " def" N " ghi");
+ data.doCommand("map X jdd");
+ KEYS("X", "abc" N " " X "ghi");
+ KEYS("u", "abc" N X " def" N " ghi");
+ KEYS("<c-r>", "abc" N X " ghi");
+ data.doCommand("unmap X");
+
+ data.setText("abc" N "def" N "ghi");
+ data.doCommand("map X jAxxx<cr>yyy<esc>");
+ KEYS("X", "abc" N "defxxx" N "yy" X "y" N "ghi");
+ KEYS("u", "abc" N "de" X "f" N "ghi");
+ KEYS("<c-r>", "abc" N "def" X "xxx" N "yyy" N "ghi");
+ data.doCommand("unmap X");
+
+ /* QTCREATORBUG-7913 */
+ data.setText("");
+ data.doCommand("noremap l k|noremap k j|noremap j h");
+ KEYS("ikkk<esc>", "kk" X "k");
+ KEYS("rj", "kk" X "j");
+ data.doCommand("unmap l|unmap k|unmap j");
+
+ // bad mapping
+ data.setText(X "abc" N "def");
+ data.doCommand("map X Zxx");
+ KEYS("X", X "abc" N "def");
+ // cancelled mapping
+ data.doCommand("map X fxxx");
+ KEYS("X", X "abc" N "def");
+ data.doCommand("map X ciXxx");
+ KEYS("X", X "abc" N "def");
+ data.doCommand("map Y Xxx");
+ KEYS("Y", X "abc" N "def");
+ data.doCommand("unmap X|unmap Y");
+
+ // <C-o>
+ data.setText("abc def");
+ data.doCommand("imap X <c-o>:%s/def/xxx/<cr>");
+ KEYS("iX", "abc xxx");
+}
+
+void FakeVimPlugin::test_vim_command_cc()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText( "|123" N "456" N "789" N "abc");
+ KEYS("cc456<ESC>", "45|6" N "456" N "789" N "abc");
+ KEYS("ccabc<Esc>", "ab|c" N "456" N "789" N "abc");
+ KEYS(".", "ab|c" N "456" N "789" N "abc");
+ KEYS("j", "abc" N "45|6" N "789" N "abc");
+ KEYS(".", "abc" N "ab|c" N "789" N "abc");
+ KEYS("kkk", "ab|c" N "abc" N "789" N "abc");
+ KEYS("3ccxyz<Esc>", "xy|z" N "abc");
+}
+
+void FakeVimPlugin::test_vim_command_cw()
+{
+ TestData data;
+ setup(&data);
+ data.setText(X "123 456");
+ KEYS("cwx<Esc>", X "x 456");
+}
+
+void FakeVimPlugin::test_vim_command_cj()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("cj<Esc>", l[0]+"\n|" + "\n" + lmid(3));
+ KEYS("P", lmid(0,1)+"\n" + "|"+lmid(1,2)+"\n" + "\n" + lmid(3));
+ KEYS("u", l[0]+"\n|" + "\n" + lmid(3));
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("cjabc<Esc>", l[0]+"\nab|c\n" + lmid(3));
+ KEYS("u", cursor(2, 0));
+ KEYS("gg", cursor(0, 0));
+ KEYS(".", "ab|c\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_ck()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("ck<Esc>", "|\n" + lmid(2));
+ KEYS("P", "|" + lmid(0,2)+"\n" + "\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_c_dollar()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", cursor(1, 0));
+ KEYS("$", cursor(1, -1));
+ KEYS("c$<Esc>", l[0]+"\n" + l[1].left(l[1].length()-2)+"|"+l[1][l[1].length()-2]+"\n" + lmid(2));
+ KEYS("c$<Esc>", l[0]+"\n" + l[1].left(l[1].length()-3)+"|"+l[1][l[1].length()-3]+"\n" + lmid(2));
+ KEYS("0c$abc<Esc>", l[0]+"\n" + "ab|c\n" + lmid(2));
+ KEYS("0c$abc<Esc>", l[0]+"\n" + "ab|c\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_C()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", cursor(1, 0));
+ KEYS("Cabc<Esc>", l[0] + "\nab|c\n" + lmid(2));
+ KEYS("Cabc<Esc>", l[0] + "\nabab|c\n" + lmid(2));
+ KEYS("$Cabc<Esc>", l[0] + "\nababab|c\n" + lmid(2));
+ KEYS("0C<Esc>", l[0] + "\n|\n" + lmid(2));
+ KEYS("0Cabc<Esc>", l[0] + "\nab|c\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_dw()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("dw", "|#include <QtCore>\n" + lmid(2));
+ KEYS("dw", "|include <QtCore>\n" + lmid(2));
+ KEYS("dw", "|<QtCore>\n" + lmid(2));
+ KEYS("dw", "|QtCore>\n" + lmid(2));
+ KEYS("dw", "|>\n" + lmid(2));
+ KEYS("dw", "|\n" + lmid(2)); // Real vim has this intermediate step, too
+ KEYS("dw", "|#include <QtGui>\n" + lmid(3));
+ KEYS("dw", "|include <QtGui>\n" + lmid(3));
+ KEYS("dw", "|<QtGui>\n" + lmid(3));
+ KEYS("dw", "|QtGui>\n" + lmid(3));
+ KEYS("dw", "|>\n" + lmid(3));
+}
+
+void FakeVimPlugin::test_vim_command_dd()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", cursor(1, 0));
+ KEYS("dd", l[0] + "\n|" + lmid(2));
+ KEYS(".", l[0] + "\n|" + lmid(3));
+ KEYS("3dd", l[0] + "\n |QApplication app(argc, argv);\n" + lmid(7));
+ KEYS("4l", l[0] + "\n QApp|lication app(argc, argv);\n" + lmid(7));
+ KEYS("dd", l[0] + "\n|" + lmid(7));
+ KEYS(".", l[0] + "\n |return app.exec();\n" + lmid(9));
+ KEYS("dd", l[0] + "\n|" + lmid(9));
+}
+
+void FakeVimPlugin::test_vim_command_dd_2()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", cursor(1, 0));
+ KEYS("dd", l[0] + "\n|" + lmid(2));
+ KEYS("p", l[0] + "\n" + l[2] + "\n|" + l[1] + "\n" + lmid(3));
+ KEYS("u", l[0] + "\n|" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_d_dollar()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("$d$", l[0]+"\n" + l[1].left(l[1].length()-2)+"|"+l[1][l[1].length()-2]+"\n" + lmid(2));
+ KEYS("0d$", l[0] + "\n"+"|\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_dj()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("dj", l[0]+"\n|" + lmid(3));
+ KEYS("P", lmid(0,1)+"\n" + "|"+lmid(1));
+ KEYS("0", lmid(0,1)+"\n" + "|"+lmid(1));
+ KEYS("dj", l[0]+"\n|" + lmid(3));
+ KEYS("P", lmid(0,1)+"\n" + "|"+lmid(1));
+ KEYS("05l", l[0]+"\n" + l[1].left(5) + "|" + l[1].mid(5)+"\n" + lmid(2));
+ KEYS("dj", l[0]+"\n|" + lmid(3));
+ KEYS("P", lmid(0,1)+"\n" + "|"+lmid(1));
+ KEYS("dj", l[0]+"\n|" + lmid(3));
+ KEYS("p", lmid(0,1)+"\n" + lmid(3,1)+"\n" + "|"+lmid(1,2)+"\n" + lmid(4));
+}
+
+void FakeVimPlugin::test_vim_command_dk()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("dk", "|" + lmid(2));
+ KEYS("P", "|" + lmid(0));
+ KEYS("j0", l[0]+ "\n|" + lmid(1));
+ KEYS("dk", "|" + lmid(2));
+ KEYS("P", "|" + lmid(0));
+ KEYS("j05l", l[0]+"\n" + l[1].left(5) + "|" + l[1].mid(5)+"\n" + lmid(2));
+ KEYS("dk", "|" + lmid(2));
+ KEYS("P", "|" + lmid(0));
+ KEYS("j05l", l[0]+"\n" + l[1].left(5) + "|" + l[1].mid(5)+"\n" + lmid(2));
+ KEYS("dk", "|" + lmid(2));
+ KEYS("p", lmid(2,1)+"\n" + "|" + lmid(0,2)+"\n" + lmid(3));
+}
+
+void FakeVimPlugin::test_vim_command_dgg()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("G", lmid(0, l.size()-2)+"\n" "|"+lmid(l.size()-2));
+ KEYS("dgg", "|");
+ KEYS("u", "|" + lmid(0));
+}
+
+void FakeVimPlugin::test_vim_command_dG()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("dG", "|");
+ KEYS("u", "|" + lmid(0));
+ KEYS("j", cursor(1, 0));
+ KEYS("dG", lmid(0,1)+"\n" + "|");
+ KEYS("u", l[0]+"\n" + "|" + lmid(1));
+ KEYS("G", lmid(0, l.size()-2)+"\n" + "|"+lmid(l.size()-2));
+
+ NOT_IMPLEMENTED
+ // include movement to first column, as otherwise the result depends on the 'startofline' setting
+ KEYS("dG0", lmid(0, l.size()-2)+"\n" + "|"+lmid(l.size()-2,1));
+ KEYS("dG0", lmid(0, l.size()-3)+"\n" + "|"+lmid(l.size()-3,1));
+}
+
+void FakeVimPlugin::test_vim_command_D()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", cursor(1, 0));
+ KEYS("$D", l[0]+"\n" + l[1].left(l[1].length()-2)+"|"+l[1][l[1].length()-2]+"\n" + lmid(2));
+ KEYS("0D", l[0] + "\n|\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_dollar()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("j$", cursor(2, -1));
+ KEYS("2j", cursor(4, -1));
+}
+
+void FakeVimPlugin::test_vim_command_down()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", l[0]+ "\n|" + lmid(1));
+ KEYS("3j", lmid(0,4)+"\n" + "|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("4j", lmid(0,8)+"\n" + "| return app.exec();\n" + lmid(9));
+}
+
+void FakeVimPlugin::test_vim_command_dfx_down()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j4l", l[0] + "\n#inc|lude <QtCore>\n" + lmid(2));
+
+ //NOT_IMPLEMENTED
+ KEYS("df ", l[0] + "\n#inc|<QtCore>\n" + lmid(2));
+ KEYS("j", l[0] + "\n#inc<QtCore>\n#inc|lude <QtGui>\n" + lmid(3));
+ KEYS(".", l[0] + "\n#inc<QtCore>\n#inc|<QtGui>\n" + lmid(3));
+ KEYS("u", l[0] + "\n#inc<QtCore>\n#inc|lude <QtGui>\n" + lmid(3));
+ KEYS("u", l[0] + "\n#inc|lude <QtCore>\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_Cxx_down_dot()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j4l", l[0] + "\n#inc|lude <QtCore>\n" + lmid(2));
+ KEYS("Cxx<Esc>", l[0] + "\n#incx|x\n" + lmid(2));
+ KEYS("j", l[0] + "\n#incxx\n#incl|ude <QtGui>\n" + lmid(3));
+ KEYS(".", l[0] + "\n#incxx\n#inclx|x\n" + lmid(3));
+}
+
+void FakeVimPlugin::test_vim_command_e()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("e", lmid(0,1)+"\n" + "|#include <QtCore>\n" + lmid(2));
+ KEYS("e", lmid(0,1)+"\n" + "#includ|e <QtCore>\n" + lmid(2));
+ KEYS("e", lmid(0,1)+"\n" + "#include |<QtCore>\n" + lmid(2));
+ KEYS("3e", lmid(0,2)+"\n" + "|#include <QtGui>\n" + lmid(3));
+ KEYS("e", lmid(0,2)+"\n" + "#includ|e <QtGui>\n" + lmid(3));
+ KEYS("e", lmid(0,2)+"\n" + "#include |<QtGui>\n" + lmid(3));
+ KEYS("e", lmid(0,2)+"\n" + "#include <QtGu|i>\n" + lmid(3));
+ KEYS("4e", lmid(0,4)+"\n" + "int main|(int argc, char *argv[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(in|t argc, char *argv[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(int arg|c, char *argv[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(int argc|, char *argv[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(int argc, cha|r *argv[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(int argc, char |*argv[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(int argc, char *arg|v[])\n" + lmid(5));
+ KEYS("e", lmid(0,4)+"\n" + "int main(int argc, char *argv[]|)\n" + lmid(5));
+ KEYS("e", lmid(0,5)+"\n" + "|{\n" + lmid(6));
+ KEYS("10k","|\n" + lmid(1)); // home.
+}
+
+void FakeVimPlugin::test_vim_command_i()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+
+ // empty insertion at start of document
+ KEYS("i<Esc>", "|" + testLines);
+ KEYS("u", "|" + testLines);
+
+ // small insertion at start of document
+ KEYS("ix<Esc>", "|x" + testLines);
+ KEYS("u", "|" + testLines);
+ COMMAND("redo", "|x" + testLines);
+ KEYS("u", "|" + testLines);
+
+ // small insertion at start of document
+ KEYS("ixxx<Esc>", "xx|x" + testLines);
+ KEYS("u", "|" + testLines);
+
+ // combine insertions
+ KEYS("i1<Esc>", "|1" + testLines);
+ KEYS("i2<Esc>", "|21" + testLines);
+ KEYS("i3<Esc>", "|321" + testLines);
+ KEYS("u", "|21" + testLines);
+ KEYS("u", "|1" + testLines);
+ KEYS("u", "|" + testLines);
+ KEYS("ia<Esc>", "|a" + testLines);
+ KEYS("ibx<Esc>", "b|xa" + testLines);
+ KEYS("icyy<Esc>", "bcy|yxa" + testLines);
+ KEYS("u", "b|xa" + testLines);
+ KEYS("u", "|a" + testLines);
+ COMMAND("redo", "|bxa" + testLines);
+ KEYS("u", "|a" + testLines);
+}
+
+void FakeVimPlugin::test_vim_command_left()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("h", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("$", lmid(0, 4) + "\nint main(int argc, char *argv[]|)\n" + lmid(5));
+ KEYS("h", lmid(0, 4) + "\nint main(int argc, char *argv[|])\n" + lmid(5));
+ KEYS("3h", lmid(0, 4) + "\nint main(int argc, char *ar|gv[])\n" + lmid(5));
+ KEYS("50h", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+}
+
+void FakeVimPlugin::test_vim_command_r()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("$", lmid(0, 4) + "\nint main(int argc, char *argv[]|)\n" + lmid(5));
+ KEYS("rx", lmid(0, 4) + "\nint main(int argc, char *argv[]|x\n" + lmid(5));
+ KEYS("2h", lmid(0, 4) + "\nint main(int argc, char *argv|[]x\n" + lmid(5));
+ KEYS("4ra", lmid(0, 4) + "\nint main(int argc, char *argv|[]x\n" + lmid(5));
+ KEYS("3rb", lmid(0, 4) + "\nint main(int argc, char *argvbb|b\n" + lmid(5));
+ KEYS("2rc", lmid(0, 4) + "\nint main(int argc, char *argvbb|b\n" + lmid(5));
+ KEYS("h2rc",lmid(0, 4) + "\nint main(int argc, char *argvbc|c\n" + lmid(5));
+}
+
+void FakeVimPlugin::test_vim_command_right()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("l", lmid(0, 4) + "\ni|nt main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("3l", lmid(0, 4) + "\nint |main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("50l", lmid(0, 4) + "\nint main(int argc, char *argv[]|)\n" + lmid(5));
+}
+
+void FakeVimPlugin::test_vim_command_up()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("9j", lmid(0, 9) + "\n|}\n");
+ KEYS("k", lmid(0, 8) + "\n| return app.exec();\n" + lmid(9));
+ KEYS("4k", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("3k", lmid(0, 1) + "\n|#include <QtCore>\n" + lmid(2));
+ KEYS("k", cursor(0, 0));
+ KEYS("2k", cursor(0, 0));
+}
+
+void FakeVimPlugin::test_vim_command_w()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("w", lmid(0,1)+"\n" + "|#include <QtCore>\n" + lmid(2));
+ KEYS("w", lmid(0,1)+"\n" + "#|include <QtCore>\n" + lmid(2));
+ KEYS("w", lmid(0,1)+"\n" + "#include |<QtCore>\n" + lmid(2));
+ KEYS("3w", lmid(0,2)+"\n" + "|#include <QtGui>\n" + lmid(3));
+ KEYS("w", lmid(0,2)+"\n" + "#|include <QtGui>\n" + lmid(3));
+ KEYS("w", lmid(0,2)+"\n" + "#include |<QtGui>\n" + lmid(3));
+ KEYS("w", lmid(0,2)+"\n" + "#include <|QtGui>\n" + lmid(3));
+ KEYS("4w", lmid(0,4)+"\n" + "int |main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main|(int argc, char *argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(|int argc, char *argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(int |argc, char *argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(int argc|, char *argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(int argc, |char *argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(int argc, char |*argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(int argc, char *|argv[])\n" + lmid(5));
+ KEYS("w", lmid(0,4)+"\n" + "int main(int argc, char *argv|[])\n" + lmid(5));
+ KEYS("w", lmid(0,5)+"\n" + "|{\n" + lmid(6));
+}
+
+void FakeVimPlugin::test_vim_command_yyp()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("yyp", lmid(0, 4) + "\n" + lmid(4, 1) + "\n|" + lmid(4));
+}
+
+void FakeVimPlugin::test_vim_command_y_dollar()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", l[0]+"\n|" + lmid(1));
+ KEYS("$y$p", l[0]+"\n"+ l[1]+"|>\n" + lmid(2));
+ KEYS("$y$p", l[0]+"\n"+ l[1]+">|>\n" + lmid(2));
+ KEYS("$y$P", l[0]+"\n"+ l[1]+">|>>\n" + lmid(2));
+ KEYS("$y$P", l[0]+"\n"+ l[1]+">>|>>\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_Yp()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("Yp", lmid(0, 4) + "\n" + lmid(4, 1) + "\n|" + lmid(4));
+}
+
+void FakeVimPlugin::test_vim_command_ma_yank()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("ygg", "|" + lmid(0));
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("p", lmid(0,5) + "\n|" + lmid(0,4) +"\n" + lmid(4));
+
+ data.setText(testLines);
+
+ KEYS("gg", "|" + lmid(0));
+ KEYS("ma", "|" + lmid(0));
+ KEYS("4j", lmid(0, 4) + "\n|int main(int argc, char *argv[])\n" + lmid(5));
+ KEYS("mb", lmid(0,4) + "\n|" + lmid(4));
+ KEYS("\"ay'a", "|" + lmid(0));
+ KEYS("'b", lmid(0,4) + "\n|" + lmid(4));
+ KEYS("\"ap", lmid(0,5) + "\n|" + lmid(0,4) +"\n" + lmid(4));
+}
+
+void FakeVimPlugin::test_vim_command_Gyyp()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("G", lmid(0, l.size()-2) + "\n|" + lmid(l.size()-2));
+ KEYS("yyp", lmid(0) + "|" + lmid(9, 1)+"\n");
+}
+
+void FakeVimPlugin::test_i_cw_i()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j", l[0] + "\n|" + lmid(1));
+ KEYS("ixx<Esc>", l[0] + "\nx|x" + lmid(1));
+ KEYS("cwyy<Esc>", l[0] + "\nxy|y" + lmid(1));
+ KEYS("iaa<Esc>", l[0] + "\nxya|ay" + lmid(1));
+}
+
+void FakeVimPlugin::test_vim_command_J()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("4j4l", lmid(0, 4) + "\nint |main(int argc, char *argv[])\n" + lmid(5));
+
+ KEYS("J", lmid(0, 5) + "| " + lmid(5));
+ KEYS("u", lmid(0, 4) + "\nint |main(int argc, char *argv[])\n" + lmid(5));
+ COMMAND("redo", lmid(0, 4) + "\nint |main(int argc, char *argv[]) " + lmid(5));
+
+ KEYS("3J", lmid(0, 5) + " " + lmid(5, 1) + " " + lmid(6, 1).mid(4) + "| " + lmid(7));
+ KEYS("uu", lmid(0, 4) + "\nint |main(int argc, char *argv[])\n" + lmid(5));
+ COMMAND("redo", lmid(0, 4) + "\nint |main(int argc, char *argv[]) " + lmid(5));
+}
+
+void FakeVimPlugin::test_vim_command_put_at_eol()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("j$", cursor(1, -1));
+ KEYS("y$", cursor(1, -1));
+ KEYS("p", lmid(0,2)+"|>\n" + lmid(2));
+ KEYS("p", lmid(0,2)+">|>\n" + lmid(2));
+ KEYS("$", lmid(0,2)+">|>\n" + lmid(2));
+ KEYS("P", lmid(0,2)+">|>>\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_command_oO()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("gg", "|" + lmid(0));
+ KEYS("Ol1<Esc>", "l|1\n" + lmid(0));
+ KEYS("gg", "|l1\n" + lmid(0));
+ KEYS("ol2<Esc>", "l1\n" "l|2\n" + lmid(0));
+ KEYS("G", "l1\n" "l2\n" + lmid(0,l.size()-2)+"\n" + "|"+lmid(l.size()-2));
+ KEYS("G$", "l1\n" "l2\n" + lmid(0,l.size()-2)+"\n" + "|"+lmid(l.size()-2));
+ KEYS("ol-1<Esc>", "l1\n" "l2\n" + lmid(0) + "l-|1\n");
+ KEYS("G", "l1\n" "l2\n" + lmid(0) + "|l-1\n");
+ KEYS("Ol-2<Esc>", "l1\n" "l2\n" + lmid(0) + "l-|2\n" + "l-1\n");
+}
+
+void FakeVimPlugin::test_vim_command_x()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("x", "|" + lmid(0));
+ KEYS("j$", cursor(1, -1));
+ KEYS("x", lmid(0,1)+"\n" + l[1].left(l[1].length()-2)+"|"+l[1].mid(l[1].length()-2,1)+"\n" + lmid(2));
+}
+
+void FakeVimPlugin::test_vim_visual_d()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("vd", "|" + lmid(1));
+ KEYS("u", "|" + lmid(0));
+ KEYS("vx", "|" + lmid(1));
+ KEYS("u", "|" + lmid(0));
+ KEYS("vjd", "|" + lmid(1).mid(1));
+ KEYS("u", "|" + lmid(0));
+ KEYS("j", lmid(0, 1)+"\n" + "|" + lmid(1));
+ KEYS("vd", lmid(0, 1)+"\n" + "|" + lmid(1).mid(1));
+ KEYS("u", lmid(0, 1)+"\n" + "|" + lmid(1));
+ KEYS("vx", lmid(0, 1)+"\n" + "|" + lmid(1).mid(1));
+ KEYS("u", lmid(0, 1)+"\n" + "|" + lmid(1));
+ KEYS("vhx", lmid(0, 1)+"\n" + "|" + lmid(1).mid(1));
+ KEYS("u", lmid(0, 1)+"\n" + "|" + lmid(1));
+ KEYS("vlx", lmid(0, 1)+"\n" + "|" + lmid(1).mid(2));
+ KEYS("P", lmid(0, 1)+"\n" + lmid(1).left(1)+"|"+lmid(1).mid(1));
+ KEYS("vhd", lmid(0, 1)+"\n" + "|" + lmid(1).mid(2));
+ KEYS("u", lmid(0, 1)+"\n" + "|" + lmid(1));
+
+ KEYS("v$d", lmid(0, 1)+"\n" + "|" + lmid(2));
+ NOT_IMPLEMENTED
+ KEYS("v$od", lmid(0, 1)+"\n" + "|" + lmid(3));
+ KEYS("$v$x", lmid(0, 1)+"\n" + lmid(3,1) + "|" + lmid(4));
+ KEYS("0v$d", lmid(0, 1)+"\n" + "|" + lmid(5));
+ KEYS("$v0d", lmid(0, 1)+"\n" + "|\n" + lmid(6));
+ KEYS("v$o0k$d", lmid(0, 1)+"\n" + "|" + lmid(6).mid(1));
+}
+
+void FakeVimPlugin::test_vim_Visual_d()
+{
+ TestData data;
+ setup(&data);
+
+ data.setText(testLines);
+ KEYS("Vd", "|" + lmid(1));
+ KEYS("V2kd", "|" + lmid(2));
+ KEYS("u", "|" + lmid(1));
+ KEYS("u", "|" + lmid(0));
+ KEYS("j", lmid(0,1)+"\n" + "|" + lmid(1));
+ KEYS("V$d", lmid(0,1)+"\n" + "|" + lmid(2));
+ KEYS("$V$$d", lmid(0,1)+"\n" + "|" + lmid(3));
+ KEYS("Vkx", "|" + lmid(4));
+ KEYS("P", "|" + lmid(0,1)+"\n" + lmid(3));
+}
diff --git a/src/plugins/fakevim/fakevimactions.cpp b/src/plugins/fakevim/fakevimactions.cpp
index e820c5cf4c..071a42a127 100644
--- a/src/plugins/fakevim/fakevimactions.cpp
+++ b/src/plugins/fakevim/fakevimactions.cpp
@@ -70,9 +70,8 @@ void FakeVimSettings::insertItem(int code, SavedAction *item,
m_nameToCode[longName] = code;
m_codeToName[code] = longName;
}
- if (!shortName.isEmpty()) {
+ if (!shortName.isEmpty())
m_nameToCode[shortName] = code;
- }
}
void FakeVimSettings::readSettings(QSettings *settings)
@@ -218,6 +217,13 @@ FakeVimSettings *theFakeVimSettings()
instance->insertItem(ConfigSmartCase, item, _("smartcase"), _("scs"));
item = new SavedAction(instance);
+ item->setDefaultValue(true);
+ item->setValue(true);
+ item->setSettingsKey(group, _("WrapScan")); item->setCheckable(true);
+ item->setCheckable(true);
+ instance->insertItem(ConfigWrapScan, item, _("wrapscan"), _("ws"));
+
+ item = new SavedAction(instance);
item->setDefaultValue(_("indent,eol,start"));
item->setSettingsKey(group, _("Backspace"));
instance->insertItem(ConfigBackspace, item, _("backspace"), _("bs"));
@@ -249,6 +255,13 @@ FakeVimSettings *theFakeVimSettings()
item->setCheckable(true);
instance->insertItem(ConfigClipboard, item, _("clipboard"), _("cb"));
+ item = new SavedAction(instance);
+ item->setDefaultValue(true);
+ item->setValue(true);
+ item->setSettingsKey(group, _("ShowCmd")); item->setCheckable(true);
+ item->setCheckable(true);
+ instance->insertItem(ConfigShowCmd, item, _("showcmd"), _("sc"));
+
return instance;
}
diff --git a/src/plugins/fakevim/fakevimactions.h b/src/plugins/fakevim/fakevimactions.h
index ccd5c412ab..13774b0e9d 100644
--- a/src/plugins/fakevim/fakevimactions.h
+++ b/src/plugins/fakevim/fakevimactions.h
@@ -52,9 +52,11 @@ enum FakeVimSettingsCode
ConfigExpandTab,
ConfigAutoIndent,
ConfigSmartIndent,
+
ConfigIncSearch,
ConfigUseCoreSearch,
ConfigSmartCase,
+ ConfigWrapScan,
// indent allow backspacing over autoindent
// eol allow backspacing over line breaks (join lines)
@@ -68,7 +70,8 @@ enum FakeVimSettingsCode
// other actions
ConfigShowMarks,
ConfigPassControlKey,
- ConfigClipboard
+ ConfigClipboard,
+ ConfigShowCmd
};
class FakeVimSettings : public QObject
diff --git a/src/plugins/fakevim/fakevimhandler.cpp b/src/plugins/fakevim/fakevimhandler.cpp
index aa1a36b992..9ca9d6377b 100644
--- a/src/plugins/fakevim/fakevimhandler.cpp
+++ b/src/plugins/fakevim/fakevimhandler.cpp
@@ -59,6 +59,7 @@
#include "fakevimhandler.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -98,7 +99,7 @@
//#define DEBUG_UNDO 1
#if DEBUG_UNDO
-# define UNDO_DEBUG(s) qDebug() << << document()->availableUndoSteps() << s
+# define UNDO_DEBUG(s) qDebug() << << revision() << s
#else
# define UNDO_DEBUG(s)
#endif
@@ -125,25 +126,18 @@ namespace Internal {
#define EndOfDocument QTextCursor::End
#define StartOfDocument QTextCursor::Start
+#define ParagraphSeparator QChar::ParagraphSeparator
+
#define EDITOR(s) (m_textedit ? m_textedit->s : m_plaintextedit->s)
-enum {
-#ifdef Q_OS_MAC
- RealControlModifier = Qt::MetaModifier
-#else
- RealControlModifier = Qt::ControlModifier
-#endif
-};
-// Enforce use of RealControlModifier by breaking the compilation.
-#define MetaModifier // Use RealControlModifier instead
-#define ControlModifier // Use RealControlModifier instead
+#define MetaModifier // Use HostOsInfo::controlModifier() instead
+#define ControlModifier // Use HostOsInfo::controlModifier() instead
-const int ParagraphSeparator = 0x00002029;
typedef QLatin1String _;
/* Clipboard MIME types used by Vim. */
-static const QString vimMimeText = "_VIM_TEXT";
-static const QString vimMimeTextEncoded = "_VIMENC_TEXT";
+static const QString vimMimeText = _("_VIM_TEXT");
+static const QString vimMimeTextEncoded = _("_VIMENC_TEXT");
using namespace Qt;
@@ -171,14 +165,14 @@ enum SubMode
RegisterSubMode, // Used for "
ShiftLeftSubMode, // Used for <
ShiftRightSubMode, // Used for >
- TransformSubMode, // Used for ~/gu/gU
+ InvertCaseSubMode, // Used for g~
+ DownCaseSubMode, // Used for gu
+ UpCaseSubMode, // Used for gU
WindowSubMode, // Used for Ctrl-w
YankSubMode, // Used for y
ZSubMode, // Used for z
CapitalZSubMode, // Used for Z
- ReplaceSubMode, // Used for r
- OpenSquareSubMode, // Used for [
- CloseSquareSubMode // Used for ]
+ ReplaceSubMode // Used for r
};
/*! A \e SubSubMode is used for things that require one more data item
@@ -187,14 +181,14 @@ enum SubMode
enum SubSubMode
{
NoSubSubMode,
- FtSubSubMode, // Used for f, F, t, T.
- MarkSubSubMode, // Used for m.
- BackTickSubSubMode, // Used for `.
- TickSubSubMode, // Used for '.
- InvertCaseSubSubMode, // Used for ~.
- DownCaseSubSubMode, // Used for gu.
- UpCaseSubSubMode, // Used for gU.
- TextObjectSubSubMode, // Used for thing like iw, aW, as etc.
+ FtSubSubMode, // Used for f, F, t, T.
+ MarkSubSubMode, // Used for m.
+ BackTickSubSubMode, // Used for `.
+ TickSubSubMode, // Used for '.
+ TextObjectSubSubMode, // Used for thing like iw, aW, as etc.
+ ZSubSubMode, // Used for zj, zk
+ OpenSquareSubSubMode, // Used for [{, {(, [z
+ CloseSquareSubSubMode, // Used for ]}, ]), ]z
SearchSubSubMode
};
@@ -239,9 +233,67 @@ enum EventResult
{
EventHandled,
EventUnhandled,
+ EventCancelled, // Event is handled but a sub mode was cancelled.
EventPassedToCore
};
+struct CursorPosition
+{
+ CursorPosition() : line(-1), column(-1) {}
+ CursorPosition(int block, int column) : line(block), column(column) {}
+ explicit CursorPosition(const QTextCursor &tc)
+ : line(tc.block().blockNumber()), column(tc.positionInBlock()) {}
+ CursorPosition(const QTextDocument *document, int position)
+ {
+ QTextBlock block = document->findBlock(position);
+ line = block.blockNumber();
+ column = position - block.position();
+ }
+ bool isValid() const { return line >= 0 && column >= 0; }
+ bool operator>(const CursorPosition &other) const
+ { return line > other.line || column > other.column; }
+ bool operator==(const CursorPosition &other) const
+ { return line == other.line && column == other.column; }
+ bool operator!=(const CursorPosition &other) const { return !operator==(other); }
+
+ int line; // Line in document (from 0, folded lines included).
+ int column; // Position on line.
+};
+
+struct Mark
+{
+ Mark(const CursorPosition &pos = CursorPosition(), const QString &fileName = QString())
+ : position(pos), fileName(fileName) {}
+
+ bool isValid() const { return position.isValid(); }
+
+ bool isLocal(const QString &localFileName) const
+ {
+ return fileName.isEmpty() || fileName == localFileName;
+ }
+
+ CursorPosition position;
+ QString fileName;
+};
+typedef QHash<QChar, Mark> Marks;
+typedef QHashIterator<QChar, Mark> MarksIterator;
+
+struct State
+{
+ State() : revision(-1), position(), marks(), lastVisualMode(NoVisualMode),
+ lastVisualModeInverted(false) {}
+ State(int revision, const CursorPosition &position, const Marks &marks,
+ VisualMode lastVisualMode, bool lastVisualModeInverted) : revision(revision),
+ position(position), marks(marks), lastVisualMode(lastVisualMode),
+ lastVisualModeInverted(lastVisualModeInverted) {}
+
+ int revision;
+ CursorPosition position;
+ Marks marks;
+ VisualMode lastVisualMode;
+ bool lastVisualModeInverted;
+};
+
struct Column
{
Column(int p, int l) : physical(p), logical(l) {}
@@ -254,15 +306,6 @@ QDebug operator<<(QDebug ts, const Column &col)
return ts << "(p: " << col.physical << ", l: " << col.logical << ")";
}
-struct CursorPosition
-{
- // for jump history
- CursorPosition() : position(-1), scrollLine(-1) {}
- CursorPosition(int pos, int line) : position(pos), scrollLine(line) {}
- int position; // Position in document
- int scrollLine; // First visible line
-};
-
struct Register
{
Register() : rangemode(RangeCharMode) {}
@@ -282,21 +325,26 @@ struct SearchData
SearchData()
{
forward = true;
- mustMove = true;
highlightMatches = true;
- highlightCursor = true;
}
QString needle;
bool forward;
- bool mustMove;
bool highlightMatches;
- bool highlightCursor;
};
+// If string begins with given prefix remove it with trailing spaces and return true.
+static bool eatString(const char *prefix, QString *str)
+{
+ if (!str->startsWith(_(prefix)))
+ return false;
+ *str = str->mid(strlen(prefix)).trimmed();
+ return true;
+}
+
static QRegExp vimPatternToQtPattern(QString needle, bool smartcase)
{
- /* Trasformations (Vim regexp -> QRegExp):
+ /* Transformations (Vim regexp -> QRegExp):
* \a -> [A-Za-z]
* \A -> [^A-Za-z]
* \h -> [A-Za-z_]
@@ -325,27 +373,53 @@ static QRegExp vimPatternToQtPattern(QString needle, bool smartcase)
* \c - set ignorecase for rest
* \C - set noignorecase for rest
*/
- bool ignorecase = smartcase && !needle.contains(QRegExp("[A-Z]"));
+ bool ignorecase = smartcase && !needle.contains(QRegExp(_("[A-Z]")));
QString pattern;
pattern.reserve(2 * needle.size());
bool escape = false;
bool brace = false;
+ bool embraced = false;
+ bool range = false;
bool curly = false;
foreach (const QChar &c, needle) {
if (brace) {
brace = false;
- if (c == ']') {
+ if (c == QLatin1Char(']')) {
pattern.append(_("\\[\\]"));
continue;
- } else {
- pattern.append('[');
}
+ pattern.append(QLatin1Char('['));
+ escape = true;
+ embraced = true;
}
- if (QString("(){}+|?").indexOf(c) != -1) {
- if (c == '{') {
+ if (embraced) {
+ if (range) {
+ QChar c2 = pattern[pattern.size() - 2];
+ pattern.remove(pattern.size() - 2, 2);
+ pattern.append(c2.toUpper() + QLatin1Char('-') + c.toUpper());
+ pattern.append(c2.toLower() + QLatin1Char('-') + c.toLower());
+ range = false;
+ } else if (escape) {
+ escape = false;
+ pattern.append(c);
+ } else if (c == QLatin1Char('\\')) {
+ escape = true;
+ } else if (c == QLatin1Char(']')) {
+ pattern.append(QLatin1Char(']'));
+ embraced = false;
+ } else if (c == QLatin1Char('-')) {
+ range = ignorecase && pattern[pattern.size() - 1].isLetter();
+ pattern.append(QLatin1Char('-'));
+ } else if (c.isLetter() && ignorecase) {
+ pattern.append(c.toLower()).append(c.toUpper());
+ } else {
+ pattern.append(c);
+ }
+ } else if (QString::fromLatin1("(){}+|?").indexOf(c) != -1) {
+ if (c == QLatin1Char('{')) {
curly = escape;
- } else if (c == '}' && curly) {
+ } else if (c == QLatin1Char('}') && curly) {
curly = false;
escape = true;
}
@@ -353,63 +427,203 @@ static QRegExp vimPatternToQtPattern(QString needle, bool smartcase)
if (escape)
escape = false;
else
- pattern.append('\\');
+ pattern.append(QLatin1Char('\\'));
pattern.append(c);
} else if (escape) {
// escape expression
escape = false;
- if (c == '<' || c == '>')
+ if (c == QLatin1Char('<') || c == QLatin1Char('>'))
pattern.append(_("\\b"));
- else if (c == 'a')
+ else if (c == QLatin1Char('a'))
pattern.append(_("[a-zA-Z]"));
- else if (c == 'A')
+ else if (c == QLatin1Char('A'))
pattern.append(_("[^a-zA-Z]"));
- else if (c == 'h')
+ else if (c == QLatin1Char('h'))
pattern.append(_("[A-Za-z_]"));
- else if (c == 'H')
+ else if (c == QLatin1Char('H'))
pattern.append(_("[^A-Za-z_]"));
- else if (c == 'c' || c == 'C')
- ignorecase = (c == 'c');
- else if (c == 'l')
+ else if (c == QLatin1Char('c') || c == QLatin1Char('C'))
+ ignorecase = (c == QLatin1Char('c'));
+ else if (c == QLatin1Char('l'))
pattern.append(_("[a-z]"));
- else if (c == 'L')
+ else if (c == QLatin1Char('L'))
pattern.append(_("[^a-z]"));
- else if (c == 'o')
+ else if (c == QLatin1Char('o'))
pattern.append(_("[0-7]"));
- else if (c == 'O')
+ else if (c == QLatin1Char('O'))
pattern.append(_("[^0-7]"));
- else if (c == 'u')
+ else if (c == QLatin1Char('u'))
pattern.append(_("[A-Z]"));
- else if (c == 'U')
+ else if (c == QLatin1Char('U'))
pattern.append(_("[^A-Z]"));
- else if (c == 'x')
+ else if (c == QLatin1Char('x'))
pattern.append(_("[0-9A-Fa-f]"));
- else if (c == 'X')
+ else if (c == QLatin1Char('X'))
pattern.append(_("[^0-9A-Fa-f]"));
- else if (c == '=')
+ else if (c == QLatin1Char('='))
pattern.append(_("?"));
else
- pattern.append('\\' + c);
+ pattern.append(QLatin1Char('\\') + c);
} else {
// unescaped expression
- if (c == '\\')
+ if (c == QLatin1Char('\\'))
escape = true;
- else if (c == '[')
+ else if (c == QLatin1Char('['))
brace = true;
else if (c.isLetter() && ignorecase)
- pattern.append('[' + c.toLower() + c.toUpper() + ']');
+ pattern.append(QLatin1Char('[') + c.toLower() + c.toUpper() + QLatin1Char(']'));
else
pattern.append(c);
}
}
if (escape)
- pattern.append('\\');
+ pattern.append(QLatin1Char('\\'));
else if (brace)
- pattern.append('[');
+ pattern.append(QLatin1Char('['));
return QRegExp(pattern);
}
+static bool afterEndOfLine(const QTextDocument *doc, int position)
+{
+ return doc->characterAt(position) == ParagraphSeparator
+ && doc->findBlock(position).length() > 1;
+}
+
+static void searchForward(QTextCursor *tc, QRegExp &needleExp, int *repeat)
+{
+ const QTextDocument *doc = tc->document();
+ const int startPos = tc->position();
+
+ // Search from beginning of line so that matched text is the same.
+ tc->movePosition(StartOfLine);
+
+ // forward to current position
+ *tc = doc->find(needleExp, *tc);
+ while (!tc->isNull() && tc->anchor() < startPos) {
+ if (!tc->hasSelection())
+ tc->movePosition(Right);
+ if (tc->atBlockEnd())
+ tc->movePosition(Right);
+ *tc = doc->find(needleExp, *tc);
+ }
+
+ if (tc->isNull())
+ return;
+
+ --*repeat;
+
+ while (*repeat > 0) {
+ if (!tc->hasSelection())
+ tc->movePosition(Right);
+ if (tc->atBlockEnd())
+ tc->movePosition(Right);
+ *tc = doc->find(needleExp, *tc);
+ if (tc->isNull())
+ return;
+ --*repeat;
+ }
+
+ if (!tc->isNull() && afterEndOfLine(doc, tc->anchor()))
+ tc->movePosition(Left);
+}
+
+static void searchBackward(QTextCursor *tc, QRegExp &needleExp, int *repeat)
+{
+ // Search from beginning of line so that matched text is the same.
+ QTextBlock block = tc->block();
+ QString line = block.text();
+
+ int i = line.indexOf(needleExp, 0);
+ while (i != -1 && i < tc->positionInBlock()) {
+ --*repeat;
+ i = line.indexOf(needleExp, i + qMax(1, needleExp.matchedLength()));
+ if (i == line.size())
+ i = -1;
+ }
+
+ if (i == tc->positionInBlock())
+ --*repeat;
+
+ while (*repeat > 0) {
+ block = block.previous();
+ if (!block.isValid())
+ break;
+ line = block.text();
+ i = line.indexOf(needleExp, 0);
+ while (i != -1) {
+ --*repeat;
+ i = line.indexOf(needleExp, i + qMax(1, needleExp.matchedLength()));
+ if (i == line.size())
+ i = -1;
+ }
+ }
+
+ if (!block.isValid()) {
+ *tc = QTextCursor();
+ return;
+ }
+
+ i = line.indexOf(needleExp, 0);
+ while (*repeat < 0) {
+ i = line.indexOf(needleExp, i + qMax(1, needleExp.matchedLength()));
+ ++*repeat;
+ }
+ tc->setPosition(block.position() + i);
+}
+
+static bool substituteText(QString *text, QRegExp &pattern, const QString &replacement,
+ bool global)
+{
+ bool substituted = false;
+ int pos = 0;
+ while (true) {
+ pos = pattern.indexIn(*text, pos, QRegExp::CaretAtZero);
+ if (pos == -1)
+ break;
+ substituted = true;
+ QString matched = text->mid(pos, pattern.cap(0).size());
+ QString repl;
+ bool escape = false;
+ // insert captured texts
+ for (int i = 0; i < replacement.size(); ++i) {
+ const QChar &c = replacement[i];
+ if (escape) {
+ escape = false;
+ if (c.isDigit()) {
+ if (c.digitValue() <= pattern.captureCount())
+ repl += pattern.cap(c.digitValue());
+ } else {
+ repl += c;
+ }
+ } else {
+ if (c == QLatin1Char('\\'))
+ escape = true;
+ else if (c == QLatin1Char('&'))
+ repl += pattern.cap(0);
+ else
+ repl += c;
+ }
+ }
+ text->replace(pos, matched.size(), repl);
+ pos += qMax(1, repl.size());
+
+ if (pos >= text->size() || !global)
+ break;
+ }
+
+ return substituted;
+}
+
+static int findUnescaped(QChar c, const QString &line, int from)
+{
+ for (int i = from; i < line.size(); ++i) {
+ if (line.at(i) == c && (i == 0 || line.at(i - 1) != QLatin1Char('\\')))
+ return i;
+ }
+ return -1;
+}
+
static void setClipboardData(const QString &content, RangeMode mode,
QClipboard::Mode clipboardMode)
{
@@ -433,6 +647,96 @@ static void setClipboardData(const QString &content, RangeMode mode,
clipboard->setMimeData(data, clipboardMode);
}
+static const QMap<QString, int> &vimKeyNames()
+{
+ static QMap<QString, int> k;
+ if (!k.isEmpty())
+ return k;
+
+ // FIXME: Should be value of mapleader.
+ k.insert(_("LEADER"), Key_Backslash);
+
+ k.insert(_("SPACE"), Key_Space);
+ k.insert(_("TAB"), Key_Tab);
+ k.insert(_("NL"), Key_Return);
+ k.insert(_("NEWLINE"), Key_Return);
+ k.insert(_("LINEFEED"), Key_Return);
+ k.insert(_("LF"), Key_Return);
+ k.insert(_("CR"), Key_Return);
+ k.insert(_("RETURN"), Key_Return);
+ k.insert(_("ENTER"), Key_Return);
+ k.insert(_("BS"), Key_Backspace);
+ k.insert(_("BACKSPACE"), Key_Backspace);
+ k.insert(_("ESC"), Key_Escape);
+ k.insert(_("BAR"), Key_Bar);
+ k.insert(_("BSLASH"), Key_Backslash);
+ k.insert(_("DEL"), Key_Delete);
+ k.insert(_("DELETE"), Key_Delete);
+ k.insert(_("KDEL"), Key_Delete);
+ k.insert(_("UP"), Key_Up);
+ k.insert(_("DOWN"), Key_Down);
+ k.insert(_("LEFT"), Key_Left);
+ k.insert(_("RIGHT"), Key_Right);
+
+ k.insert(_("LT"), Key_Less);
+
+ k.insert(_("F1"), Key_F1);
+ k.insert(_("F2"), Key_F2);
+ k.insert(_("F3"), Key_F3);
+ k.insert(_("F4"), Key_F4);
+ k.insert(_("F5"), Key_F5);
+ k.insert(_("F6"), Key_F6);
+ k.insert(_("F7"), Key_F7);
+ k.insert(_("F8"), Key_F8);
+ k.insert(_("F9"), Key_F9);
+ k.insert(_("F10"), Key_F10);
+
+ k.insert(_("F11"), Key_F11);
+ k.insert(_("F12"), Key_F12);
+ k.insert(_("F13"), Key_F13);
+ k.insert(_("F14"), Key_F14);
+ k.insert(_("F15"), Key_F15);
+ k.insert(_("F16"), Key_F16);
+ k.insert(_("F17"), Key_F17);
+ k.insert(_("F18"), Key_F18);
+ k.insert(_("F19"), Key_F19);
+ k.insert(_("F20"), Key_F20);
+
+ k.insert(_("F21"), Key_F21);
+ k.insert(_("F22"), Key_F22);
+ k.insert(_("F23"), Key_F23);
+ k.insert(_("F24"), Key_F24);
+ k.insert(_("F25"), Key_F25);
+ k.insert(_("F26"), Key_F26);
+ k.insert(_("F27"), Key_F27);
+ k.insert(_("F28"), Key_F28);
+ k.insert(_("F29"), Key_F29);
+ k.insert(_("F30"), Key_F30);
+
+ k.insert(_("F31"), Key_F31);
+ k.insert(_("F32"), Key_F32);
+ k.insert(_("F33"), Key_F33);
+ k.insert(_("F34"), Key_F34);
+ k.insert(_("F35"), Key_F35);
+
+ k.insert(_("INSERT"), Key_Insert);
+ k.insert(_("INS"), Key_Insert);
+ k.insert(_("KINSERT"), Key_Insert);
+ k.insert(_("HOME"), Key_Home);
+ k.insert(_("END"), Key_End);
+ k.insert(_("PAGEUP"), Key_PageUp);
+ k.insert(_("PAGEDOWN"), Key_PageDown);
+
+ k.insert(_("KPLUS"), Key_Plus);
+ k.insert(_("KMINUS"), Key_Minus);
+ k.insert(_("KDIVIDE"), Key_Slash);
+ k.insert(_("KMULTIPLY"), Key_Asterisk);
+ k.insert(_("KENTER"), Key_Enter);
+ k.insert(_("KPOINT"), Key_Period);
+
+ return k;
+}
+
Range::Range()
: beginPos(-1), endPos(-1), rangemode(RangeCharMode)
@@ -444,7 +748,7 @@ Range::Range(int b, int e, RangeMode m)
QString Range::toString() const
{
- return QString("%1-%2 (mode: %3)").arg(beginPos).arg(endPos)
+ return QString::fromLatin1("%1-%2 (mode: %3)").arg(beginPos).arg(endPos)
.arg(rangemode);
}
@@ -463,17 +767,6 @@ bool ExCommand::matches(const QString &min, const QString &full) const
return cmd.startsWith(min) && full.startsWith(cmd);
}
-void ExCommand::setContentsFromLine(const QString &line)
-{
- cmd = line.section(' ', 0, 0);
- args = line.mid(cmd.size() + 1).trimmed();
- while (cmd.startsWith(QLatin1Char(':')))
- cmd.remove(0, 1);
- hasBang = cmd.endsWith('!');
- if (hasBang)
- cmd.chop(1);
-}
-
QDebug operator<<(QDebug ts, const ExCommand &cmd)
{
return ts << cmd.cmd << ' ' << cmd.args << ' ' << cmd.range;
@@ -494,10 +787,10 @@ QString quoteUnprintable(const QString &ba)
const int cc = c.unicode();
if (c.isPrint())
res += c;
- else if (cc == '\n')
+ else if (cc == QLatin1Char('\n'))
res += _("<CR>");
else
- res += QString("\\x%1").arg(c.unicode(), 2, 16, QLatin1Char('0'));
+ res += QString::fromLatin1("\\x%1").arg(c.unicode(), 2, 16, QLatin1Char('0'));
}
return res;
}
@@ -507,7 +800,7 @@ static bool startsWithWhitespace(const QString &str, int col)
QTC_ASSERT(str.size() >= col, return false);
for (int i = 0; i < col; ++i) {
uint u = str.at(i).unicode();
- if (u != ' ' && u != '\t')
+ if (u != QLatin1Char(' ') && u != QLatin1Char('\t'))
return false;
}
return true;
@@ -528,9 +821,15 @@ public:
: m_key(0), m_xkey(0), m_modifiers(0) {}
explicit Input(QChar x)
- : m_key(x.unicode()), m_xkey(x.unicode()), m_modifiers(0), m_text(x) {}
+ : m_key(x.unicode()), m_xkey(x.unicode()), m_modifiers(0), m_text(x)
+ {
+ if (x.isUpper())
+ m_modifiers = Qt::ShiftModifier;
+ else if (x.isLower())
+ m_key = x.toUpper().unicode();
+ }
- Input(int k, int m, const QString &t)
+ Input(int k, int m, const QString &t = QString())
: m_key(k), m_modifiers(cleanModifier(m)), m_text(t)
{
// On Mac, QKeyEvent::text() returns non-empty strings for
@@ -539,13 +838,25 @@ public:
// FIXME: Check the real conditions.
if (m_text.size() == 1 && m_text.at(0).unicode() < ' ')
m_text.clear();
+
+ // Set text only if input is ascii key without control modifier.
+ if (m_text.isEmpty() && k <= 0x7f && (m & (HostOsInfo::controlModifier())) == 0) {
+ QChar c = QChar::fromAscii(k);
+ m_text = QString((m & ShiftModifier) != 0 ? c.toUpper() : c.toLower());
+ }
+
// m_xkey is only a cache.
m_xkey = (m_text.size() == 1 ? m_text.at(0).unicode() : m_key);
}
+ bool isValid() const
+ {
+ return m_key != 0 || !m_text.isNull();
+ }
+
bool isDigit() const
{
- return m_xkey >= '0' && m_xkey <= '9';
+ return m_xkey >= QLatin1Char('0') && m_xkey <= QLatin1Char('9');
}
bool isKey(int c) const
@@ -560,7 +871,7 @@ public:
bool isReturn() const
{
- return m_key == Key_Return || m_key == Key_Enter;
+ return m_key == QLatin1Char('\n') || m_key == Key_Return || m_key == Key_Enter;
}
bool isEscape() const
@@ -571,12 +882,12 @@ public:
bool is(int c) const
{
- return m_xkey == c && m_modifiers != RealControlModifier;
+ return m_xkey == c && m_modifiers != int(HostOsInfo::controlModifier());
}
bool isControl(int c) const
{
- return m_modifiers == RealControlModifier
+ return m_modifiers == int(HostOsInfo::controlModifier())
&& (m_xkey == c || m_xkey + 32 == c || m_xkey + 64 == c || m_xkey + 96 == c);
}
@@ -585,16 +896,20 @@ public:
return m_modifiers == Qt::ShiftModifier && m_xkey == c;
}
- bool operator==(const Input &a) const
+ bool operator<(const Input &a) const
{
- return a.m_key == m_key && a.m_modifiers == m_modifiers
- && m_text == a.m_text;
+ if (m_key != a.m_key)
+ return m_key < a.m_key;
+ // Text for some mapped key cannot be determined (e.g. <C-J>) so if text is not set for
+ // one of compared keys ignore it.
+ if (!m_text.isEmpty() && !a.m_text.isEmpty())
+ return m_text < a.m_text;
+ return m_modifiers < a.m_modifiers;
}
- // Ignore e.g. ShiftModifier, which is not available in sourced data.
- bool matchesForMap(const Input &a) const
+ bool operator==(const Input &a) const
{
- return (a.m_key == m_key || a.m_xkey == m_xkey) && m_text == a.m_text;
+ return !(*this < a || a < *this);
}
bool operator!=(const Input &a) const { return !operator==(a); }
@@ -611,12 +926,23 @@ public:
QChar raw() const
{
if (m_key == Key_Tab)
- return '\t';
+ return QLatin1Char('\t');
if (m_key == Key_Return)
- return '\n';
+ return QLatin1Char('\n');
return m_key;
}
+ QString toString() const
+ {
+ bool hasCtrl = m_modifiers & int(HostOsInfo::controlModifier());
+ QString key = vimKeyNames().key(m_key);
+ if (key.isEmpty())
+ key = QChar(m_xkey);
+ else
+ key = QLatin1Char('<') + key + QLatin1Char('>');
+ return (hasCtrl ? QString::fromLatin1("^") : QString()) + key;
+ }
+
QDebug dump(QDebug ts) const
{
return ts << m_key << '-' << m_modifiers << '-'
@@ -629,87 +955,199 @@ private:
QString m_text;
};
+// mapping to <Nop> (do nothing)
+static const Input Nop(-1, -1, QString());
+
QDebug operator<<(QDebug ts, const Input &input) { return input.dump(ts); }
class Inputs : public QVector<Input>
{
public:
- Inputs() {}
- explicit Inputs(const QString &str) { parseFrom(str); }
+ Inputs() : m_noremap(true), m_silent(false) {}
+
+ explicit Inputs(const QString &str, bool noremap = true, bool silent = false)
+ : m_noremap(noremap), m_silent(silent)
+ {
+ parseFrom(str);
+ }
+
+ bool noremap() const { return m_noremap; }
+
+ bool silent() const { return m_silent; }
+
+private:
void parseFrom(const QString &str);
+
+ bool m_noremap;
+ bool m_silent;
};
-static bool iss(char a, char b)
+static Input parseVimKeyName(const QString &keyName)
{
- if (a >= 'a')
- a -= 'a' - 'A';
- if (b >= 'a')
- b -= 'a' - 'A';
- return a == b;
+ if (keyName.length() == 1)
+ return Input(keyName.at(0));
+
+ const QStringList keys = keyName.split(QLatin1Char('-'));
+ const int len = keys.length();
+
+ if (len == 1 && keys.at(0) == _("nop"))
+ return Nop;
+
+ int mods = NoModifier;
+ for (int i = 0; i < len - 1; ++i) {
+ const QString &key = keys[i].toUpper();
+ if (key == _("S"))
+ mods |= Qt::ShiftModifier;
+ else if (key == _("C"))
+ mods |= HostOsInfo::controlModifier();
+ else
+ return Input();
+ }
+
+ if (!keys.isEmpty()) {
+ const QString key = keys.last();
+ if (key.length() == 1) {
+ // simple character
+ QChar c = key.at(0).toUpper();
+ return Input(c.unicode(), mods);
+ }
+
+ // find key name
+ QMap<QString, int>::ConstIterator it = vimKeyNames().constFind(key.toUpper());
+ if (it != vimKeyNames().end())
+ return Input(*it, mods);
+ }
+
+ return Input();
}
void Inputs::parseFrom(const QString &str)
{
const int n = str.size();
for (int i = 0; i < n; ++i) {
- uint c0 = str.at(i).unicode(), c1 = 0, c2 = 0, c3 = 0, c4 = 0;
- if (i + 1 < n)
- c1 = str.at(i + 1).unicode();
- if (i + 2 < n)
- c2 = str.at(i + 2).unicode();
- if (i + 3 < n)
- c3 = str.at(i + 3).unicode();
- if (i + 4 < n)
- c4 = str.at(i + 4).unicode();
- if (c0 == '<') {
- if (iss(c1, 'C') && c2 == '-' && c4 == '>') {
- uint c = (c3 < 90 ? c3 : c3 - 32);
- append(Input(c, RealControlModifier, QString(QChar(c - 64))));
- i += 4;
- } else if (iss(c1, 'C') && iss(c2, 'R') && c3 == '>') {
- append(Input(Key_Return, Qt::NoModifier, QString(QChar(13))));
- i += 3;
- } else if (iss(c1, 'E') && iss(c2, 'S') && iss(c3, 'C') && c4 == '>') {
- append(Input(Key_Escape, Qt::NoModifier, QString(QChar(27))));
- i += 4;
+ uint c = str.at(i).unicode();
+ if (c == QLatin1Char('<')) {
+ int j = str.indexOf(QLatin1Char('>'), i);
+ Input input;
+ if (j != -1) {
+ const QString key = str.mid(i+1, j - i - 1);
+ if (!key.contains(QLatin1Char('<')))
+ input = parseVimKeyName(key);
+ }
+ if (input.isValid()) {
+ append(input);
+ i = j;
} else {
- append(Input(QLatin1Char(c0)));
+ append(Input(QLatin1Char(c)));
}
} else {
- append(Input(QLatin1Char(c0)));
+ append(Input(QLatin1Char(c)));
}
}
}
-// This wraps a string and a "cursor position".
+class History
+{
+public:
+ History() : m_items(QString()), m_index(0) {}
+ void append(const QString &item);
+ const QString &move(const QStringRef &prefix, int skip);
+ const QString &current() const { return m_items[m_index]; }
+ const QStringList &items() const { return m_items; }
+ void restart() { m_index = m_items.size() - 1; }
+
+private:
+ // Last item is always empty or current search prefix.
+ QStringList m_items;
+ int m_index;
+};
+
+void History::append(const QString &item)
+{
+ if (item.isEmpty())
+ return;
+ m_items.pop_back();
+ m_items.removeAll(item);
+ m_items << item << QString();
+ restart();
+}
+
+const QString &History::move(const QStringRef &prefix, int skip)
+{
+ if (!current().startsWith(prefix))
+ restart();
+
+ if (m_items.last() != prefix)
+ m_items[m_items.size() - 1] = prefix.toString();
+
+ int i = m_index + skip;
+ if (!prefix.isEmpty())
+ for (; i >= 0 && i < m_items.size() && !m_items[i].startsWith(prefix); i += skip);
+ if (i >= 0 && i < m_items.size())
+ m_index = i;
+
+ return current();
+}
+
+// Command line buffer with prompt (i.e. :, / or ? characters), text contents and cursor position.
class CommandBuffer
{
public:
- CommandBuffer() : m_pos(0) {}
+ CommandBuffer() : m_pos(0), m_anchor(0), m_userPos(0), m_historyAutoSave(true) {}
- void clear() { m_buffer.clear(); m_pos = 0; }
- void setContents(const QString &s) { m_buffer = s; m_pos = s.size(); }
- QString contents() const { return m_buffer; }
+ void setPrompt(const QChar &prompt) { m_prompt = prompt; }
+ void setContents(const QString &s) { m_buffer = s; m_anchor = m_pos = s.size(); }
+
+ void setContents(const QString &s, int pos, int anchor = -1)
+ {
+ m_buffer = s; m_pos = m_userPos = pos; m_anchor = anchor >= 0 ? anchor : pos;
+ }
+
+ QStringRef userContents() const { return m_buffer.leftRef(m_userPos); }
+ const QChar &prompt() const { return m_prompt; }
+ const QString &contents() const { return m_buffer; }
bool isEmpty() const { return m_buffer.isEmpty(); }
int cursorPos() const { return m_pos; }
+ int anchorPos() const { return m_anchor; }
+ bool hasSelection() const { return m_pos != m_anchor; }
+
+ void insertChar(QChar c) { m_buffer.insert(m_pos++, c); m_anchor = m_userPos = m_pos; }
+ void insertText(const QString &s)
+ {
+ m_buffer.insert(m_pos, s); m_anchor = m_userPos = m_pos = m_pos + s.size();
+ }
+ void deleteChar() { if (m_pos) m_buffer.remove(--m_pos, 1); m_anchor = m_userPos = m_pos; }
+
+ void moveLeft() { if (m_pos) m_userPos = --m_pos; }
+ void moveRight() { if (m_pos < m_buffer.size()) m_userPos = ++m_pos; }
+ void moveStart() { m_userPos = m_pos = 0; }
+ void moveEnd() { m_userPos = m_pos = m_buffer.size(); }
- void insertChar(QChar c) { m_buffer.insert(m_pos++, c); }
- void insertText(const QString &s) { m_buffer.insert(m_pos, s); m_pos += s.size(); }
- void deleteChar() { if (m_pos) m_buffer.remove(--m_pos, 1); }
+ void setHistoryAutoSave(bool autoSave) { m_historyAutoSave = autoSave; }
+ void historyDown() { setContents(m_history.move(userContents(), 1)); }
+ void historyUp() { setContents(m_history.move(userContents(), -1)); }
+ const QStringList &historyItems() const { return m_history.items(); }
+ void historyPush(const QString &item = QString())
+ {
+ m_history.append(item.isNull() ? contents() : item);
+ }
- void moveLeft() { if (m_pos) --m_pos; }
- void moveRight() { if (m_pos < m_buffer.size()) ++m_pos; }
- void moveStart() { m_pos = 0; }
- void moveEnd() { m_pos = m_buffer.size(); }
+ void clear()
+ {
+ if (m_historyAutoSave)
+ historyPush();
+ m_buffer.clear();
+ m_anchor = m_userPos = m_pos = 0;
+ }
QString display() const
{
- QString msg;
+ QString msg(m_prompt);
for (int i = 0; i != m_buffer.size(); ++i) {
const QChar c = m_buffer.at(i);
if (c.unicode() < 32) {
- msg += '^';
- msg += QChar(c.unicode() + 64);
+ msg += QLatin1Char('^');
+ msg += QLatin1Char(c.unicode() + 64);
} else {
msg += c;
}
@@ -717,20 +1155,55 @@ public:
return msg;
}
+ void deleteSelected()
+ {
+ if (m_pos < m_anchor) {
+ m_buffer.remove(m_pos, m_anchor - m_pos);
+ m_anchor = m_pos;
+ } else {
+ m_buffer.remove(m_anchor, m_pos - m_anchor);
+ m_pos = m_anchor;
+ }
+ }
+
bool handleInput(const Input &input)
{
- if (input.isKey(Key_Left)) {
+ if (input.isShift(Key_Left)) {
+ moveLeft();
+ } else if (input.isShift(Key_Right)) {
+ moveRight();
+ } else if (input.isShift(Key_Home)) {
+ moveStart();
+ } else if (input.isShift(Key_End)) {
+ moveEnd();
+ } else if (input.isKey(Key_Left)) {
moveLeft();
+ m_anchor = m_pos;
} else if (input.isKey(Key_Right)) {
moveRight();
+ m_anchor = m_pos;
} else if (input.isKey(Key_Home)) {
moveStart();
+ m_anchor = m_pos;
} else if (input.isKey(Key_End)) {
moveEnd();
+ m_anchor = m_pos;
+ } else if (input.isKey(Key_Up) || input.isKey(Key_PageUp)) {
+ historyUp();
+ } else if (input.isKey(Key_Down) || input.isKey(Key_PageDown)) {
+ historyDown();
} else if (input.isKey(Key_Delete)) {
- if (m_pos < m_buffer.size())
- m_buffer.remove(m_pos, 1);
+ if (hasSelection()) {
+ deleteSelected();
+ } else {
+ if (m_pos < m_buffer.size())
+ m_buffer.remove(m_pos, 1);
+ else
+ deleteChar();
+ }
} else if (!input.text().isEmpty()) {
+ if (hasSelection())
+ deleteSelected();
insertText(input.text());
} else {
return false;
@@ -740,100 +1213,156 @@ public:
private:
QString m_buffer;
+ QChar m_prompt;
+ History m_history;
int m_pos;
+ int m_anchor;
+ int m_userPos; // last position of inserted text (for retrieving history items)
+ bool m_historyAutoSave; // store items to history on clear()?
};
-
-class History
+// Mappings for a specific mode (trie structure)
+class ModeMapping : public QMap<Input, ModeMapping>
{
public:
- History() : m_index(0) {}
- void append(const QString &item);
- void down() { m_index = qMin(m_index + 1, m_items.size()); }
- void up() { m_index = qMax(m_index - 1, 0); }
- void restart() { m_index = m_items.size(); }
- QString current() const { return m_items.value(m_index, QString()); }
- QStringList items() const { return m_items; }
-
+ const Inputs &value() const { return m_value; }
+ void setValue(const Inputs &value) { m_value = value; }
private:
- QStringList m_items;
- int m_index;
+ Inputs m_value;
};
-void History::append(const QString &item)
-{
- if (item.isEmpty())
- return;
- m_items.removeAll(item);
- m_items.append(item); m_index = m_items.size() - 1;
-}
+// Mappings for all modes
+typedef QHash<char, ModeMapping> Mappings;
-// Mappings for a specific mode.
-class ModeMapping : public QList<QPair<Inputs, Inputs> >
+// Iterator for mappings
+class MappingsIterator : public QVector<ModeMapping::Iterator>
{
public:
- ModeMapping() { test(); }
-
- void test()
+ MappingsIterator(Mappings *mappings, char mode = -1, const Inputs &inputs = Inputs())
+ : m_parent(mappings)
{
- //insert(Inputs() << Input('A') << Input('A'),
- // Inputs() << Input('x') << Input('x'));
+ reset(mode);
+ walk(inputs);
}
- void insert(const Inputs &from, const Inputs &to)
+ // Reset iterator state. Keep previous mode if 0.
+ void reset(char mode = 0)
{
- for (int i = 0; i != size(); ++i)
- if (at(i).first == from) {
- (*this)[i].second = to;
- return;
- }
- append(QPair<Inputs, Inputs>(from, to));
+ clear();
+ m_lastValid = -1;
+ m_invalidInputCount = 0;
+ if (mode != 0) {
+ m_mode = mode;
+ if (mode != -1)
+ m_modeMapping = m_parent->find(mode);
+ }
}
- void remove(const Inputs &from)
- {
- for (int i = 0; i != size(); ++i)
- if (at(i).first == from) {
- removeAt(i);
- return;
- }
- }
+ bool isValid() const { return !empty(); }
+
+ // Return true if mapping can be extended.
+ bool canExtend() const { return isValid() && !last()->empty(); }
+
+ // Return true if this mapping can be used.
+ bool isComplete() const { return m_lastValid != -1; }
+
+ // Return size of current map.
+ int mapLength() const { return m_lastValid + 1; }
- // Returns 'false' if more input is needed to decide whether a mapping
- // needs to be applied. If a decision can be made, return 'true',
- // and replace *input with the mapped data.
- bool mappingDone(Inputs *inputs) const
+ int invalidInputCount() const { return m_invalidInputCount; }
+
+ bool walk(const Input &input)
{
- // FIXME: inefficient.
- for (int i = 0; i != size(); ++i) {
- const Inputs &haystack = at(i).first;
- // A mapping
- if (couldTriggerMap(haystack, *inputs)) {
- if (haystack.size() != inputs->size())
- return false; // This can be extended.
- // Actual mapping.
- *inputs = at(i).second;
- return true;
- }
+ if (m_modeMapping == m_parent->end())
+ return false;
+
+ if (!input.isValid()) {
+ m_invalidInputCount += 1;
+ return true;
}
- // No extensible mapping found. Use inputs as-is.
+
+ ModeMapping::Iterator it;
+ if (isValid()) {
+ it = last()->find(input);
+ if (it == last()->end())
+ return false;
+ } else {
+ it = m_modeMapping->find(input);
+ if (it == m_modeMapping->end())
+ return false;
+ }
+
+ if (!it->value().isEmpty())
+ m_lastValid = size();
+ append(it);
+
return true;
}
-private:
- static bool couldTriggerMap(const Inputs &haystack, const Inputs &needle)
+ bool walk(const Inputs &inputs)
{
- // Input is already too long.
- if (needle.size() > haystack.size())
- return false;
- for (int i = 0; i != needle.size(); ++i) {
- if (!needle.at(i).matchesForMap(haystack.at(i)))
+ foreach (const Input &input, inputs) {
+ if (!walk(input))
return false;
}
return true;
}
+
+ // Return current mapped value. Iterator must be valid.
+ const Inputs &inputs() const
+ {
+ return at(m_lastValid)->value();
+ }
+
+ void remove()
+ {
+ if (isValid()) {
+ if (canExtend()) {
+ last()->setValue(Inputs());
+ } else {
+ if (size() > 1) {
+ while (last()->empty()) {
+ at(size() - 2)->erase(last());
+ pop_back();
+ if (size() == 1 || !last()->value().isEmpty())
+ break;
+ }
+ if (last()->empty() && last()->value().isEmpty())
+ m_modeMapping->erase(last());
+ } else if (last()->empty() && !last()->value().isEmpty()) {
+ m_modeMapping->erase(last());
+ }
+ }
+ }
+ }
+
+ void setInputs(const Inputs &key, const Inputs &inputs, bool unique = false)
+ {
+ ModeMapping *current = &(*m_parent)[m_mode];
+ foreach (const Input &input, key)
+ current = &(*current)[input];
+ if (!unique || current->value().isEmpty())
+ current->setValue(inputs);
+ }
+
+private:
+ Mappings *m_parent;
+ Mappings::Iterator m_modeMapping;
+ int m_lastValid;
+ int m_invalidInputCount;
+ char m_mode;
};
+// state of current mapping
+struct MappingState {
+ MappingState()
+ : maxMapDepth(1000), noremap(false), silent(false) {}
+ MappingState(int depth, bool noremap, bool silent)
+ : maxMapDepth(depth), noremap(noremap), silent(silent) {}
+ int maxMapDepth;
+ bool noremap;
+ bool silent;
+};
class FakeVimHandler::Private : public QObject
{
@@ -844,6 +1373,10 @@ public:
EventResult handleEvent(QKeyEvent *ev);
bool wantsOverride(QKeyEvent *ev);
+ bool parseExCommmand(QString *line, ExCommand *cmd);
+ bool parseLineRange(QString *line, ExCommand *cmd);
+ int parseLineAddress(QString *cmd);
+ void parseRangeCount(const QString &line, Range *range) const;
void handleCommand(const QString &cmd); // Sets m_tc + handleExCommand
void handleExCommand(const QString &cmd);
@@ -855,26 +1388,50 @@ public:
friend class FakeVimHandler;
void init();
- EventResult handleKey(const Input &);
- Q_SLOT EventResult handleKey2();
+ void focus();
+
+ void enterFakeVim(); // Call before any FakeVim processing (import cursor position from editor)
+ void leaveFakeVim(); // Call after any FakeVim processing (export cursor position to editor)
+
+ EventResult handleKey(const Input &input);
+ EventResult handleDefaultKey(const Input &input);
+ void handleMappedKeys();
+ void unhandleMappedKeys();
EventResult handleInsertMode(const Input &);
EventResult handleReplaceMode(const Input &);
+
EventResult handleCommandMode(const Input &);
- EventResult handleCommandMode1(const Input &);
- EventResult handleCommandMode2(const Input &);
- EventResult handleRegisterMode(const Input &);
+
+ // return true only if input in current mode and sub-mode was correctly handled
+ bool handleEscape();
+ bool handleNoSubMode(const Input &);
+ bool handleChangeDeleteSubModes(const Input &);
+ bool handleReplaceSubMode(const Input &);
+ bool handleFilterSubMode(const Input &);
+ bool handleRegisterSubMode(const Input &);
+ bool handleShiftSubMode(const Input &);
+ bool handleChangeCaseSubMode(const Input &);
+ bool handleWindowSubMode(const Input &);
+ bool handleYankSubMode(const Input &);
+ bool handleZSubMode(const Input &);
+ bool handleCapitalZSubMode(const Input &);
+
+ bool handleMovement(const Input &);
+
EventResult handleExMode(const Input &);
- EventResult handleOpenSquareSubMode(const Input &);
- EventResult handleCloseSquareSubMode(const Input &);
EventResult handleSearchSubSubMode(const Input &);
- EventResult handleCommandSubSubMode(const Input &);
- void finishMovement(const QString &dotCommand = QString());
- void finishMovement(const QString &dotCommand, int count);
+ bool handleCommandSubSubMode(const Input &);
+ void fixSelection(); // Fix selection according to current range, move and command modes.
+ void finishMovement(const QString &dotCommandMovement = QString());
+ void finishMovement(const QString &dotCommandMovement, int count);
void resetCommandMode();
- void search(const SearchData &sd);
+ QTextCursor search(const SearchData &sd, int startPos, int count, bool showMessages);
+ void search(const SearchData &sd, bool showMessages = true);
+ void searchNext(bool forward = true);
void searchBalanced(bool forward, QChar needle, QChar other);
void highlightMatches(const QString &needle);
void stopIncrementalFind();
+ void updateFind(bool isComplete);
int mvCount() const { return m_mvcount.isEmpty() ? 1 : m_mvcount.toInt(); }
int opCount() const { return m_opcount.isEmpty() ? 1 : m_opcount.toInt(); }
@@ -882,17 +1439,29 @@ public:
QTextBlock block() const { return cursor().block(); }
int leftDist() const { return position() - block().position(); }
int rightDist() const { return block().length() - leftDist() - 1; }
+ bool atBlockStart() const { return cursor().atBlockStart(); }
bool atBlockEnd() const { return cursor().atBlockEnd(); }
bool atEndOfLine() const { return atBlockEnd() && block().length() > 1; }
-
- int lastPositionInDocument() const; // Returns last valid position in doc.
- int firstPositionInLine(int line) const; // 1 based line, 0 based pos
- int lastPositionInLine(int line) const; // 1 based line, 0 based pos
+ bool atDocumentEnd() const { return position() >= lastPositionInDocument(); }
+ bool atDocumentStart() const { return cursor().atStart(); }
+
+ bool atEmptyLine(const QTextCursor &tc = QTextCursor()) const;
+ bool atBoundary(bool end, bool simple, bool onlyWords = false,
+ const QTextCursor &tc = QTextCursor()) const;
+ bool atWordBoundary(bool end, bool simple, const QTextCursor &tc = QTextCursor()) const;
+ bool atWordStart(bool simple, const QTextCursor &tc = QTextCursor()) const;
+ bool atWordEnd(bool simple, const QTextCursor &tc = QTextCursor()) const;
+ bool isFirstNonBlankOnLine(int pos);
+
+ int lastPositionInDocument(bool ignoreMode = false) const; // Returns last valid position in doc.
+ int firstPositionInLine(int line, bool onlyVisibleLines = true) const; // 1 based line, 0 based pos
+ int lastPositionInLine(int line, bool onlyVisibleLines = true) const; // 1 based line, 0 based pos
int lineForPosition(int pos) const; // 1 based line, 0 based pos
QString lineContents(int line) const; // 1 based line
void setLineContents(int line, const QString &contents); // 1 based line
int blockBoundary(const QString &left, const QString &right,
bool end, int count) const; // end or start position of current code block
+ int lineNumber(const QTextBlock &block) const;
int linesOnScreen() const;
int columnsOnScreen() const;
@@ -901,6 +1470,7 @@ public:
// The following use all zero-based counting.
int cursorLineOnScreen() const;
int cursorLine() const;
+ int cursorBlockNumber() const; // "." address
int physicalCursorColumn() const; // as stored in the data
int logicalCursorColumn() const; // as visible on screen
int physicalToLogicalColumn(int physical, const QString &text) const;
@@ -910,11 +1480,11 @@ public:
void scrollToLine(int line);
void scrollUp(int count);
void scrollDown(int count) { scrollUp(-count); }
+ void alignViewportToCursor(Qt::AlignmentFlag align, int line = -1,
+ bool moveToNonBlank = false);
- CursorPosition cursorPosition() const
- { return CursorPosition(position(), firstVisibleLine()); }
- void setCursorPosition(const CursorPosition &p)
- { setPosition(p.position); scrollToLine(p.scrollLine); }
+ void setCursorPosition(const CursorPosition &p);
+ void setCursorPosition(QTextCursor *tc, const CursorPosition &p);
// Helper functions for indenting/
bool isElectricCharacter(QChar c) const;
@@ -924,15 +1494,25 @@ public:
void shiftRegionRight(int repeat = 1);
void moveToFirstNonBlankOnLine();
+ void moveToFirstNonBlankOnLine(QTextCursor *tc);
void moveToTargetColumn();
void setTargetColumn() {
m_targetColumn = logicalCursorColumn();
m_visualTargetColumn = m_targetColumn;
//qDebug() << "TARGET: " << m_targetColumn;
}
- void moveToNextWord(bool simple, bool deleteWord = false);
void moveToMatchingParanthesis();
- void moveToWordBoundary(bool simple, bool forward, bool changeWord = false);
+ void moveToBoundary(bool simple, bool forward = true);
+ void moveToNextBoundary(bool end, int count, bool simple, bool forward);
+ void moveToNextBoundaryStart(int count, bool simple, bool forward = true);
+ void moveToNextBoundaryEnd(int count, bool simple, bool forward = true);
+ void moveToBoundaryStart(int count, bool simple, bool forward = true);
+ void moveToBoundaryEnd(int count, bool simple, bool forward = true);
+ void moveToNextWord(bool end, int count, bool simple, bool forward, bool emptyLines);
+ void moveToNextWordStart(int count, bool simple, bool forward = true, bool emptyLines = true);
+ void moveToNextWordEnd(int count, bool simple, bool forward = true, bool emptyLines = true);
+ void moveToWordStart(int count, bool simple, bool forward = true, bool emptyLines = true);
+ void moveToWordEnd(int count, bool simple, bool forward = true, bool emptyLines = true);
// Convenience wrappers to reduce line noise.
void moveToStartOfLine();
@@ -951,6 +1531,8 @@ public:
QTextCursor tc = cursor();
tc.movePosition(Right, KeepAnchor, n);
setCursor(tc);
+ if (atEndOfLine())
+ emit q->fold(1, false);
//dump("RIGHT 2");
}
void moveLeft(int n = 1) {
@@ -980,30 +1562,38 @@ public:
tc.setPosition(position, KeepAnchor);
setCursor(tc);
}
- QTextCursor cursor() const { return EDITOR(textCursor()); }
- void setCursor(const QTextCursor &tc) {
- // Workaround for crash when in edit block and adding text to last empty line.
- if (m_editBlockLevel > 0)
- cursor().endEditBlock();
- EDITOR(setTextCursor(tc));
+
+ // Workaround for occational crash when setting text cursor while in edit block.
+ QTextCursor m_cursor;
+
+ QTextCursor cursor() const {
if (m_editBlockLevel > 0)
- cursor().joinPreviousEditBlock();
+ return m_cursor;
+ return EDITOR(textCursor());
}
- bool handleFfTt(QString key);
+ void setCursor(const QTextCursor &tc) {
+ m_cursor = tc;
+ if (m_editBlockLevel == 0)
+ EDITOR(setTextCursor(tc));
+ }
- // Helper function for handleExCommand returning 1 based line index.
- int readLineCode(QString &cmd);
+ bool moveToPreviousParagraph(int count) { return moveToNextParagraph(-count); }
+ bool moveToNextParagraph(int count);
+
+ bool handleFfTt(QString key);
void enterInsertMode();
+ void initVisualBlockInsertMode(QChar command);
void enterReplaceMode();
- void enterCommandMode();
- void enterExMode();
- void showRedMessage(const QString &msg);
- void showBlackMessage(const QString &msg);
+ void enterCommandMode(Mode returnToMode = CommandMode);
+ void enterExMode(const QString &contents = QString());
+ void showMessage(MessageLevel level, const QString &msg);
+ void clearMessage() { showMessage(MessageInfo, QString()); }
void notImplementedYet();
void updateMiniBuffer();
void updateSelection();
+ void updateHighlights();
void updateCursorShape();
QWidget *editor() const;
QTextDocument *document() const { return EDITOR(document()); }
@@ -1011,54 +1601,34 @@ public:
{ return document()->characterAt(position()); }
int m_editBlockLevel; // current level of edit blocks
-
- void beginEditBlock()
- {
- UNDO_DEBUG("BEGIN EDIT BLOCK");
- ++m_editBlockLevel;
- cursor().beginEditBlock();
- }
- void endEditBlock()
- {
- UNDO_DEBUG("END EDIT BLOCK");
- QTC_ASSERT(m_editBlockLevel > 0,
- qDebug() << "beginEditBlock() not called before endEditBlock()!"; return);
- --m_editBlockLevel;
- cursor().endEditBlock();
- }
- void joinPreviousEditBlock()
- {
- UNDO_DEBUG("JOIN");
- ++m_editBlockLevel;
- cursor().joinPreviousEditBlock();
- }
- void breakEditBlock() {
- QTextCursor tc = cursor();
- tc.clearSelection();
- tc.beginEditBlock();
- tc.insertText("x");
- tc.deletePreviousChar();
- tc.endEditBlock();
- setCursor(tc);
- }
+ void joinPreviousEditBlock();
+ void beginEditBlock(bool rememberPosition = true);
+ void beginLargeEditBlock() { beginEditBlock(false); }
+ void endEditBlock();
+ void breakEditBlock() { m_breakEditBlock = true; }
bool isVisualMode() const { return m_visualMode != NoVisualMode; }
bool isNoVisualMode() const { return m_visualMode == NoVisualMode; }
bool isVisualCharMode() const { return m_visualMode == VisualCharMode; }
bool isVisualLineMode() const { return m_visualMode == VisualLineMode; }
bool isVisualBlockMode() const { return m_visualMode == VisualBlockMode; }
+ char currentModeCode() const;
void updateEditor();
+ void selectTextObject(bool simple, bool inner);
void selectWordTextObject(bool inner);
void selectWORDTextObject(bool inner);
void selectSentenceTextObject(bool inner);
void selectParagraphTextObject(bool inner);
- void selectBlockTextObject(bool inner, char left, char right);
- void changeNumberTextObject(bool doIncrement);
- void selectQuotedStringTextObject(bool inner, const QString &quote);
+ bool changeNumberTextObject(int count);
+ // return true only if cursor is in a block delimited with correct characters
+ bool selectBlockTextObject(bool inner, char left, char right);
+ bool selectQuotedStringTextObject(bool inner, const QString &quote);
Q_SLOT void importSelection();
void exportSelection();
+ void recordInsertion(const QString &insert = QString());
+ void ensureCursorVisible();
void insertInInsertMode(const QString &text);
public:
@@ -1069,7 +1639,6 @@ public:
FakeVimHandler *q;
Mode m_mode;
bool m_passing; // let the core see the next event
- bool m_firstKeyPending;
SubMode m_submode;
SubSubMode m_subsubmode;
Input m_subsubdata;
@@ -1083,7 +1652,7 @@ public:
QString m_opcount;
MoveType m_movetype;
RangeMode m_rangemode;
- int m_visualInsertCount;
+ bool m_visualBlockInsert;
bool m_fakeEnd;
bool m_anchorPastEnd;
@@ -1091,16 +1660,12 @@ public:
int m_gflag; // whether current command started with 'g'
- QString m_commandPrefix;
- CommandBuffer m_commandBuffer;
QString m_currentFileName;
- QString m_currentMessage;
- bool m_lastSearchForward;
- bool m_findPending;
int m_findStartPosition;
QString m_lastInsertion;
- QString m_lastDeletion;
+
+ bool m_breakEditBlock;
int anchor() const { return cursor().anchor(); }
int position() const { return cursor().position(); }
@@ -1137,22 +1702,28 @@ public:
QString selectText(const Range &range) const;
void setCurrentRange(const Range &range);
Range currentRange() const { return Range(position(), anchor(), m_rangemode); }
- Range rangeFromCurrentLine() const;
void yankText(const Range &range, int toregister = '"');
void pasteText(bool afterCursor);
+ void joinLines(int count, bool preserveSpace = false);
+
// undo handling
+ int revision() const { return document()->availableUndoSteps(); }
+ void undoRedo(bool undo);
void undo();
void redo();
- void setUndoPosition();
- QMap<int, int> m_undoCursorPosition; // revision -> position
+ void setUndoPosition(bool overwrite = true);
+ // revision -> state
+ QStack<State> m_undo;
+ QStack<State> m_redo;
// extra data for '.'
- void replay(const QString &text, int count);
+ void replay(const QString &text);
void setDotCommand(const QString &cmd) { g.dotCommand = cmd; }
void setDotCommand(const QString &cmd, int n) { g.dotCommand = cmd.arg(n); }
+ QString visualDotCommand() const;
// extra data for ';'
QString m_semicolonCount;
@@ -1163,20 +1734,23 @@ public:
void toggleVisualMode(VisualMode visualMode);
void leaveVisualMode();
VisualMode m_visualMode;
- VisualMode m_oldVisualMode;
-
- // marks as lines
- int mark(int code) const;
- void setMark(int code, int position);
- typedef QHash<int, QTextCursor> Marks;
- typedef QHashIterator<int, QTextCursor> MarksIterator;
- Marks m_marks;
+ VisualMode m_lastVisualMode;
+ bool m_lastVisualModeInverted;
+
+ // marks
+ Mark mark(QChar code) const;
+ void setMark(QChar code, CursorPosition position);
+ // jump to valid mark return true if mark is valid and local
+ bool jumpToMark(QChar mark, bool backTickMode);
+ // update marks on undo/redo
+ void updateMarks(const Marks &newMarks);
+ Marks m_marks; // local marks
// vi style configuration
QVariant config(int code) const { return theFakeVimSetting(code)->value(); }
bool hasConfig(int code) const { return config(code).toBool(); }
bool hasConfig(int code, const char *value) const // FIXME
- { return config(code).toString().contains(value); }
+ { return config(code).toString().contains(_(value)); }
int m_targetColumn; // -1 if past end of line
int m_visualTargetColumn; // 'l' can move past eol in visual mode only
@@ -1196,24 +1770,25 @@ public:
RangeMode registerRangeMode(int reg) const;
void getRegisterType(int reg, bool *isClipboard, bool *isSelection) const;
- void recordJump();
- QVector<CursorPosition> m_jumpListUndo;
- QVector<CursorPosition> m_jumpListRedo;
- int m_lastChangePosition;
+ void recordJump(int position = -1);
+ void jump(int distance);
+ QStack<CursorPosition> m_jumpListUndo;
+ QStack<CursorPosition> m_jumpListRedo;
+ CursorPosition m_lastChangePosition;
- QList<QTextEdit::ExtraSelection> m_searchSelections;
+ QList<QTextEdit::ExtraSelection> m_extraSelections;
QTextCursor m_searchCursor;
+ int m_searchStartPosition;
+ int m_searchFromScreenLine;
QString m_oldNeedle;
- QString m_lastSubstituteFlags;
- QRegExp m_lastSubstitutePattern;
- QString m_lastSubstituteReplacement;
- QTextCursor m_lastSelectionCursor;
- VisualMode m_lastSelectionMode;
- bool handleExCommandHelper(const ExCommand &cmd); // Returns success.
+ bool handleExCommandHelper(ExCommand &cmd); // Returns success.
bool handleExPluginCommand(const ExCommand &cmd); // Handled by plugin?
bool handleExBangCommand(const ExCommand &cmd);
- bool handleExDeleteCommand(const ExCommand &cmd);
+ bool handleExYankDeleteCommand(const ExCommand &cmd);
+ bool handleExChangeCommand(const ExCommand &cmd);
+ bool handleExMoveCommand(const ExCommand &cmd);
+ bool handleExJoinCommand(const ExCommand &cmd);
bool handleExGotoCommand(const ExCommand &cmd);
bool handleExHistoryCommand(const ExCommand &cmd);
bool handleExRegisterCommand(const ExCommand &cmd);
@@ -1221,7 +1796,7 @@ public:
bool handleExNohlsearchCommand(const ExCommand &cmd);
bool handleExNormalCommand(const ExCommand &cmd);
bool handleExReadCommand(const ExCommand &cmd);
- bool handleExRedoCommand(const ExCommand &cmd);
+ bool handleExUndoRedoCommand(const ExCommand &cmd);
bool handleExSetCommand(const ExCommand &cmd);
bool handleExShiftCommand(const ExCommand &cmd);
bool handleExSourceCommand(const ExCommand &cmd);
@@ -1236,31 +1811,57 @@ public:
signed char m_charClass[256];
bool m_ctrlVActive;
+ void miniBufferTextEdited(const QString &text, int cursorPos, int anchorPos);
+
static struct GlobalData
{
GlobalData()
+ : mappings(), currentMap(&mappings), inputTimer(-1), currentMessageLevel(MessageInfo),
+ lastSearchForward(false), findPending(false), returnToMode(CommandMode)
{
- inputTimer = -1;
+ // default mapping state - shouldn't be removed
+ mapStates << MappingState();
+ commandBuffer.setPrompt(QLatin1Char(':'));
}
+ // Repetition.
+ QString dotCommand;
+
+ QHash<int, Register> registers;
+
+ // All mappings.
+ Mappings mappings;
+
// Input.
Inputs pendingInput;
+ MappingsIterator currentMap;
int inputTimer;
+ QStack<MappingState> mapStates;
- // Repetition.
- QString dotCommand;
+ // Command line buffers.
+ CommandBuffer commandBuffer;
+ CommandBuffer searchBuffer;
- // History for searches.
- History searchHistory;
+ // Current mini buffer message.
+ QString currentMessage;
+ MessageLevel currentMessageLevel;
+ QString currentCommand;
- // History for :ex commands.
- History commandHistory;
+ // Search state.
+ QString lastSearch;
+ bool lastSearchForward;
+ bool findPending;
- QHash<int, Register> registers;
+ // Last substitution command.
+ QString lastSubstituteFlags;
+ QString lastSubstitutePattern;
+ QString lastSubstituteReplacement;
- // All mappings.
- typedef QHash<char, ModeMapping> Mappings;
- Mappings mappings;
+ // Global marks.
+ Marks marks;
+
+ // Return to insert/replace mode after single command (<C-O>).
+ Mode returnToMode;
} g;
};
@@ -1282,17 +1883,18 @@ void FakeVimHandler::Private::init()
m_submode = NoSubMode;
m_subsubmode = NoSubSubMode;
m_passing = false;
- m_firstKeyPending = false;
- m_findPending = false;
+ g.findPending = false;
m_findStartPosition = -1;
+ m_visualBlockInsert = false;
m_fakeEnd = false;
m_positionPastEnd = false;
m_anchorPastEnd = false;
- m_lastSearchForward = true;
+ g.lastSearchForward = true;
m_register = '"';
m_gflag = false;
m_visualMode = NoVisualMode;
- m_oldVisualMode = NoVisualMode;
+ m_lastVisualMode = NoVisualMode;
+ m_lastVisualModeInverted = false;
m_targetColumn = 0;
m_visualTargetColumn = 0;
m_movetype = MoveInclusive;
@@ -1304,12 +1906,70 @@ void FakeVimHandler::Private::init()
m_oldExternalAnchor = -1;
m_oldExternalPosition = -1;
m_oldPosition = -1;
- m_lastChangePosition = -1;
+ m_breakEditBlock = false;
+ m_searchStartPosition = 0;
+ m_searchFromScreenLine = 0;
m_editBlockLevel = 0;
setupCharClass();
}
+void FakeVimHandler::Private::focus()
+{
+ stopIncrementalFind();
+ if (m_mode == CommandMode && g.returnToMode != CommandMode && g.currentCommand.isEmpty()) {
+ // Return to insert mode.
+ resetCommandMode();
+ updateMiniBuffer();
+ updateCursorShape();
+ }
+}
+
+void FakeVimHandler::Private::enterFakeVim()
+{
+ importSelection();
+
+ QTextCursor tc = cursor();
+
+ // Position changed externally, e.g. by code completion.
+ if (tc.position() != m_oldPosition) {
+ // record external jump to different line
+ if (m_oldPosition != -1 && lineForPosition(m_oldPosition) != lineForPosition(tc.position()))
+ recordJump(m_oldPosition);
+ setTargetColumn();
+ if (atEndOfLine() && !isVisualMode() && m_mode != InsertMode && m_mode != ReplaceMode)
+ moveLeft();
+ }
+
+ tc.setVisualNavigation(true);
+ setCursor(tc);
+
+ if (m_fakeEnd)
+ moveRight();
+}
+
+void FakeVimHandler::Private::leaveFakeVim()
+{
+ // The command might have destroyed the editor.
+ if (m_textedit || m_plaintextedit) {
+ // We fake vi-style end-of-line behaviour
+ m_fakeEnd = atEndOfLine() && m_mode == CommandMode && !isVisualBlockMode();
+
+ //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
+ // || !atBlockEnd() || block().length() <= 1,
+ // qDebug() << "Cursor at EOL after key handler");
+ if (m_fakeEnd)
+ moveLeft();
+
+ m_oldPosition = position();
+ if (hasConfig(ConfigShowMarks))
+ updateSelection();
+
+ exportSelection();
+ updateCursorShape();
+ }
+}
+
bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
{
const int key = ev->key();
@@ -1323,14 +1983,14 @@ bool FakeVimHandler::Private::wantsOverride(QKeyEvent *ev)
if (isNoVisualMode()
&& m_mode == CommandMode
&& m_submode == NoSubMode
- && m_opcount.isEmpty()
- && m_mvcount.isEmpty())
+ && g.currentCommand.isEmpty()
+ && g.returnToMode == CommandMode)
return false;
return true;
}
// We are interested in overriding most Ctrl key combinations.
- if (mods == RealControlModifier
+ if (mods == int(HostOsInfo::controlModifier())
&& !config(ConfigPassControlKey).toBool()
&& ((key >= Key_A && key <= Key_Z && key != Key_K)
|| key == Key_BracketLeft || key == Key_BracketRight)) {
@@ -1392,37 +2052,6 @@ EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
//if (0 && hasBlock) {
// (pos > anc) ? --pos : --anc;
- importSelection();
-
- // Position changed externally, e.g. by code completion.
- if (position() != m_oldPosition) {
- setTargetColumn();
- //qDebug() << "POSITION CHANGED EXTERNALLY";
- if (m_mode == InsertMode) {
- int dist = position() - m_oldPosition;
- // Try to compensate for code completion
- if (dist > 0 && dist <= physicalCursorColumn()) {
- Range range(m_oldPosition, position());
- m_lastInsertion.append(selectText(range));
- }
- } else if (!isVisualMode()) {
- if (atEndOfLine())
- moveLeft();
- }
- }
-
- QTextCursor tc = cursor();
- tc.setVisualNavigation(true);
- setCursor(tc);
-
- if (m_firstKeyPending) {
- m_firstKeyPending = false;
- recordJump();
- }
-
- if (m_fakeEnd)
- moveRight();
-
//if ((mods & RealControlModifier) != 0) {
// if (key >= Key_A && key <= Key_Z)
// key = shift(key); // make it lower case
@@ -1435,26 +2064,9 @@ EventResult FakeVimHandler::Private::handleEvent(QKeyEvent *ev)
// || !atBlockEnd() || block().length() <= 1,
// qDebug() << "Cursor at EOL before key handler");
+ enterFakeVim();
EventResult result = handleKey(Input(key, mods, ev->text()));
-
- // The command might have destroyed the editor.
- if (m_textedit || m_plaintextedit) {
- // We fake vi-style end-of-line behaviour
- m_fakeEnd = atEndOfLine() && m_mode == CommandMode && !isVisualBlockMode();
-
- //QTC_ASSERT(m_mode == InsertMode || m_mode == ReplaceMode
- // || !atBlockEnd() || block().length() <= 1,
- // qDebug() << "Cursor at EOL after key handler");
- if (m_fakeEnd)
- moveLeft();
-
- m_oldPosition = position();
- if (hasConfig(ConfigShowMarks))
- updateSelection();
-
- exportSelection();
- updateCursorShape();
- }
+ leaveFakeVim();
return result;
}
@@ -1467,32 +2079,46 @@ void FakeVimHandler::Private::installEventFilter()
void FakeVimHandler::Private::setupWidget()
{
- enterCommandMode();
- if (m_textedit) {
+ m_mode = CommandMode;
+ resetCommandMode();
+ if (m_textedit)
m_textedit->setLineWrapMode(QTextEdit::NoWrap);
- } else if (m_plaintextedit) {
+ else if (m_plaintextedit)
m_plaintextedit->setLineWrapMode(QPlainTextEdit::NoWrap);
- }
m_wasReadOnly = EDITOR(isReadOnly());
- m_firstKeyPending = true;
updateEditor();
importSelection();
updateMiniBuffer();
updateCursorShape();
+
+ recordJump();
+ setTargetColumn();
+ if (atEndOfLine() && !isVisualMode() && m_mode != InsertMode && m_mode != ReplaceMode)
+ moveLeft();
}
void FakeVimHandler::Private::exportSelection()
{
int pos = position();
- int anc = anchor();
+ int anc = isVisualMode() ? anchor() : position();
+
m_oldInternalPosition = pos;
m_oldInternalAnchor = anc;
+
if (isVisualMode()) {
- if (pos >= anc)
- setAnchorAndPosition(anc, pos + 1);
- else
+ bool visualBlockInverted;
+ if (m_visualMode == VisualBlockMode) {
+ const int col1 = anc - document()->findBlock(anc).position();
+ const int col2 = pos - document()->findBlock(pos).position();
+ visualBlockInverted = col1 > col2;
+ } else {
+ visualBlockInverted = anc > pos;
+ }
+ if (visualBlockInverted)
setAnchorAndPosition(anc + 1, pos);
+ else
+ setAnchorAndPosition(anc, pos + 1);
if (m_visualMode == VisualBlockMode) {
emit q->requestSetBlockSelection(false);
@@ -1507,18 +2133,87 @@ void FakeVimHandler::Private::exportSelection()
pos = firstPositionInLine(posLine);
anc = lastPositionInLine(ancLine);
}
+ // putting cursor on folded line will unfold the line, so move the cursor a bit
+ if (!document()->findBlock(pos).isVisible())
+ ++pos;
setAnchorAndPosition(anc, pos);
} else if (m_visualMode == VisualCharMode) {
/* Nothing */
} else {
QTC_CHECK(false);
}
+
+ setMark(QLatin1Char('<'), mark(QLatin1Char('<')).position);
+ setMark(QLatin1Char('>'), mark(QLatin1Char('>')).position);
} else {
- setAnchorAndPosition(pos, pos);
+ if (m_subsubmode == SearchSubSubMode && !m_searchCursor.isNull())
+ setCursor(m_searchCursor);
+ else
+ setAnchorAndPosition(pos, pos);
}
m_oldExternalPosition = position();
m_oldExternalAnchor = anchor();
- m_oldVisualMode = m_visualMode;
+}
+
+void FakeVimHandler::Private::recordInsertion(const QString &insert)
+{
+ const int pos = position();
+
+ if (insert.isNull()) {
+ const int dist = pos - m_oldPosition;
+
+ if (dist > 0) {
+ Range range(m_oldPosition, pos);
+ QString text = selectText(range);
+ // escape text like <ESC>
+ text.replace(_("<"), _("<LT>"));
+ m_lastInsertion.append(text);
+ } else if (dist < 0) {
+ m_lastInsertion.resize(m_lastInsertion.size() + dist);
+ }
+ } else {
+ m_lastInsertion += insert;
+ }
+
+ if (m_oldPosition != pos) {
+ m_oldPosition = pos;
+ setTargetColumn();
+ }
+}
+
+void FakeVimHandler::Private::ensureCursorVisible()
+{
+ int pos = position();
+ int anc = isVisualMode() ? anchor() : position();
+
+ // fix selection so it is outside folded block
+ int start = qMin(pos, anc);
+ int end = qMax(pos, anc) + 1;
+ QTextBlock block = document()->findBlock(start);
+ QTextBlock block2 = document()->findBlock(end);
+ if (!block.isVisible() || !block2.isVisible()) {
+ // FIXME: Moving cursor left/right or unfolding block immediately after block is folded
+ // should restore cursor position inside block.
+ // Changing cursor position after folding is not Vim behavior so at least record the jump.
+ if (block.isValid() && !block.isVisible())
+ recordJump();
+
+ pos = start;
+ while (block.isValid() && !block.isVisible())
+ block = block.previous();
+ if (block.isValid())
+ pos = block.position() + qMin(m_targetColumn, block.length() - 2);
+
+ if (isVisualMode()) {
+ anc = end;
+ while (block2.isValid() && !block2.isVisible()) {
+ anc = block2.position() + block2.length() - 2;
+ block2 = block2.next();
+ }
+ }
+
+ setAnchorAndPosition(anc, pos);
+ }
}
void FakeVimHandler::Private::importSelection()
@@ -1529,15 +2224,12 @@ void FakeVimHandler::Private::importSelection()
if (position() == m_oldExternalPosition
&& anchor() == m_oldExternalAnchor) {
// Undo drawing correction.
- m_visualMode = m_oldVisualMode;
setAnchorAndPosition(m_oldInternalAnchor, m_oldInternalPosition);
- //setMark('<', m_oldInternalAnchor);
- //setMark('>', m_oldInternalPosition);
} else {
// Import new selection.
Qt::KeyboardModifiers mods = QApplication::keyboardModifiers();
if (cursor().hasSelection()) {
- if (mods & RealControlModifier)
+ if (mods & HostOsInfo::controlModifier())
m_visualMode = VisualBlockMode;
else if (mods & Qt::AltModifier)
m_visualMode = VisualBlockMode;
@@ -1545,29 +2237,27 @@ void FakeVimHandler::Private::importSelection()
m_visualMode = VisualLineMode;
else
m_visualMode = VisualCharMode;
+ m_lastVisualMode = m_visualMode;
} else {
m_visualMode = NoVisualMode;
}
- //dump("IS @");
- //setMark('<', tc.anchor());
- //setMark('>', tc.position());
}
}
void FakeVimHandler::Private::updateEditor()
{
- const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
+ const int charWidth = QFontMetrics(EDITOR(font())).width(QLatin1Char(' '));
EDITOR(setTabStopWidth(charWidth * config(ConfigTabStop).toInt()));
setupCharClass();
}
void FakeVimHandler::Private::restoreWidget(int tabSize)
{
- //showBlackMessage(QString());
+ //clearMessage();
//updateMiniBuffer();
//EDITOR(removeEventFilter(q));
//EDITOR(setReadOnly(m_wasReadOnly));
- const int charWidth = QFontMetrics(EDITOR(font())).width(QChar(' '));
+ const int charWidth = QFontMetrics(EDITOR(font())).width(QLatin1Char(' '));
EDITOR(setTabStopWidth(charWidth * tabSize));
m_visualMode = NoVisualMode;
// Force "ordinary" cursor.
@@ -1576,72 +2266,162 @@ void FakeVimHandler::Private::restoreWidget(int tabSize)
m_subsubmode = NoSubSubMode;
updateCursorShape();
updateSelection();
+ updateHighlights();
}
EventResult FakeVimHandler::Private::handleKey(const Input &input)
{
KEY_DEBUG("HANDLE INPUT: " << input << " MODE: " << mode);
- if (m_mode == ExMode)
- return handleExMode(input);
- if (m_subsubmode == SearchSubSubMode)
- return handleSearchSubSubMode(input);
- if (m_mode == InsertMode || m_mode == ReplaceMode || m_mode == CommandMode) {
+
+ bool handleMapped = true;
+ bool hasInput = input.isValid();
+
+ if (hasInput)
g.pendingInput.append(input);
- const char code = m_mode == InsertMode ? 'i' : 'n';
- if (g.mappings.value(code).mappingDone(&g.pendingInput))
- return handleKey2();
- if (g.inputTimer != -1)
- killTimer(g.inputTimer);
- g.inputTimer = startTimer(1000);
- return EventHandled;
+
+ // Waiting on input to complete mapping?
+ if (g.inputTimer != -1) {
+ killTimer(g.inputTimer);
+ g.inputTimer = -1;
+ // If there is a new input add it to incomplete input or
+ // if the mapped input can be completed complete.
+ if (hasInput && g.currentMap.walk(input)) {
+ if (g.currentMap.canExtend()) {
+ g.currentCommand.append(input.toString());
+ updateMiniBuffer();
+ g.inputTimer = startTimer(1000);
+ return EventHandled;
+ } else {
+ hasInput = false;
+ handleMappedKeys();
+ }
+ } else if (g.currentMap.isComplete()) {
+ handleMappedKeys();
+ } else {
+ g.currentMap.reset();
+ handleMapped = false;
+ }
+ g.currentCommand.clear();
+ updateMiniBuffer();
}
+
+ EventResult r = EventUnhandled;
+ while (!g.pendingInput.isEmpty()) {
+ const Input &in = g.pendingInput.front();
+
+ // invalid input is used to pop mapping state
+ if (!in.isValid()) {
+ unhandleMappedKeys();
+ } else {
+ if (handleMapped && !g.mapStates.last().noremap && m_subsubmode != SearchSubSubMode) {
+ if (!g.currentMap.isValid()) {
+ g.currentMap.reset(currentModeCode());
+ if (!g.currentMap.walk(g.pendingInput) && g.currentMap.isComplete()) {
+ handleMappedKeys();
+ continue;
+ }
+ }
+
+ // handle user mapping
+ if (g.currentMap.canExtend()) {
+ g.currentCommand.append(in.toString());
+ updateMiniBuffer();
+ // wait for user to press any key or trigger complete mapping after interval
+ g.inputTimer = startTimer(1000);
+ return EventHandled;
+ } else if (g.currentMap.isComplete()) {
+ handleMappedKeys();
+ continue;
+ }
+ }
+
+ r = handleDefaultKey(in);
+ if (r != EventHandled) {
+ // clear bad mapping
+ const int index = g.pendingInput.lastIndexOf(Input());
+ if (index != -1)
+ g.pendingInput.remove(0, index - 1);
+ }
+ }
+ handleMapped = true;
+ g.pendingInput.pop_front();
+ }
+
+ return r;
+}
+
+EventResult FakeVimHandler::Private::handleDefaultKey(const Input &input)
+{
+ if (input == Nop)
+ return EventHandled;
+ else if (m_subsubmode == SearchSubSubMode)
+ return handleSearchSubSubMode(input);
+ else if (m_mode == CommandMode)
+ return handleCommandMode(input);
+ else if (m_mode == InsertMode)
+ return handleInsertMode(input);
+ else if (m_mode == ReplaceMode)
+ return handleReplaceMode(input);
+ else if (m_mode == ExMode)
+ return handleExMode(input);
return EventUnhandled;
}
-EventResult FakeVimHandler::Private::handleKey2()
+void FakeVimHandler::Private::handleMappedKeys()
{
- Inputs pendingInput = g.pendingInput;
- g.pendingInput.clear();
- if (m_mode == InsertMode) {
- EventResult result = EventUnhandled;
- foreach (const Input &in, pendingInput) {
- EventResult r = handleInsertMode(in);
- if (r == EventHandled)
- result = EventHandled;
- }
- return result;
- }
- if (m_mode == ReplaceMode) {
- EventResult result = EventUnhandled;
- foreach (const Input &in, pendingInput) {
- EventResult r = handleReplaceMode(in);
- if (r == EventHandled)
- result = EventHandled;
- }
- return result;
- }
- if (m_mode == CommandMode) {
- EventResult result = EventUnhandled;
- foreach (const Input &in, pendingInput) {
- EventResult r = handleCommandMode(in);
- if (r == EventHandled)
- result = EventHandled;
- }
- return result;
+ int maxMapDepth = g.mapStates.last().maxMapDepth - 1;
+
+ int invalidCount = g.currentMap.invalidInputCount();
+ if (invalidCount > 0) {
+ g.mapStates.remove(g.mapStates.size() - invalidCount, invalidCount);
+ QTC_CHECK(!g.mapStates.empty());
+ for (int i = 0; i < invalidCount; ++i)
+ endEditBlock();
}
- return EventUnhandled;
+
+ if (maxMapDepth <= 0) {
+ showMessage(MessageError, tr("recursive mapping"));
+ g.pendingInput.remove(0, g.currentMap.mapLength() + invalidCount);
+ } else {
+ const Inputs &inputs = g.currentMap.inputs();
+ QVector<Input> rest = g.pendingInput.mid(g.currentMap.mapLength() + invalidCount);
+ g.pendingInput.clear();
+ g.pendingInput << inputs << Input() << rest;
+ g.mapStates << MappingState(maxMapDepth, inputs.noremap(), inputs.silent());
+ g.commandBuffer.setHistoryAutoSave(false);
+ beginLargeEditBlock();
+ }
+ g.currentMap.reset();
+}
+
+void FakeVimHandler::Private::unhandleMappedKeys()
+{
+ if (g.mapStates.size() == 1)
+ return;
+ g.mapStates.pop_back();
+ endEditBlock();
+ if (g.mapStates.size() == 1)
+ g.commandBuffer.setHistoryAutoSave(true);
+ if (m_mode == ExMode || m_subsubmode == SearchSubSubMode)
+ updateMiniBuffer(); // update cursor position on command line
}
void FakeVimHandler::Private::timerEvent(QTimerEvent *ev)
{
- Q_UNUSED(ev);
- handleKey2();
+ if (ev->timerId() == g.inputTimer) {
+ if (g.currentMap.isComplete())
+ handleMappedKeys();
+
+ enterFakeVim();
+ handleKey(Input());
+ leaveFakeVim();
+ }
}
void FakeVimHandler::Private::stopIncrementalFind()
{
- if (m_findPending) {
- m_findPending = false;
+ if (g.findPending) {
+ g.findPending = false;
QTextCursor tc = cursor();
setAnchorAndPosition(m_findStartPosition, tc.selectionStart());
finishMovement();
@@ -1649,46 +2429,165 @@ void FakeVimHandler::Private::stopIncrementalFind()
}
}
-void FakeVimHandler::Private::setUndoPosition()
+void FakeVimHandler::Private::updateFind(bool isComplete)
+{
+ if (!isComplete && !hasConfig(ConfigIncSearch))
+ return;
+
+ g.currentMessage.clear();
+
+ const QString &needle = g.searchBuffer.contents();
+ SearchData sd;
+ sd.needle = needle;
+ sd.forward = g.lastSearchForward;
+ sd.highlightMatches = isComplete;
+ if (isComplete) {
+ setPosition(m_searchStartPosition);
+ recordJump();
+ }
+ search(sd, isComplete);
+}
+
+bool FakeVimHandler::Private::atEmptyLine(const QTextCursor &tc) const
+{
+ if (tc.isNull())
+ return atEmptyLine(cursor());
+ return tc.block().length() == 1;
+}
+
+bool FakeVimHandler::Private::atBoundary(bool end, bool simple, bool onlyWords,
+ const QTextCursor &tc) const
+{
+ if (tc.isNull())
+ return atBoundary(end, simple, onlyWords, cursor());
+ if (atEmptyLine(tc))
+ return true;
+ int pos = tc.position();
+ QChar c1 = document()->characterAt(pos);
+ QChar c2 = document()->characterAt(pos + (end ? 1 : -1));
+ int thisClass = charClass(c1, simple);
+ return (!onlyWords || thisClass != 0)
+ && (c2.isNull() || c2 == ParagraphSeparator || thisClass != charClass(c2, simple));
+}
+
+bool FakeVimHandler::Private::atWordBoundary(bool end, bool simple, const QTextCursor &tc) const
+{
+ return atBoundary(end, simple, true, tc);
+}
+
+bool FakeVimHandler::Private::atWordStart(bool simple, const QTextCursor &tc) const
+{
+ return atWordBoundary(false, simple, tc);
+}
+
+bool FakeVimHandler::Private::atWordEnd(bool simple, const QTextCursor &tc) const
+{
+ return atWordBoundary(true, simple, tc);
+}
+
+bool FakeVimHandler::Private::isFirstNonBlankOnLine(int pos)
+{
+ for (int i = document()->findBlock(pos).position(); i < pos; ++i) {
+ if (!document()->characterAt(i).isSpace())
+ return false;
+ }
+ return true;
+}
+
+void FakeVimHandler::Private::setUndoPosition(bool overwrite)
{
- int pos = qMin(position(), anchor());
- if (m_visualMode == VisualLineMode)
- pos = firstPositionInLine(lineForPosition(pos));
- const int rev = document()->availableUndoSteps();
- m_undoCursorPosition[rev] = pos;
+ const int rev = revision();
+ if (!overwrite && !m_undo.empty() && m_undo.top().revision >= rev)
+ return;
+
+ int pos = position();
+ if (m_mode != InsertMode && m_mode != ReplaceMode) {
+ if (isVisualMode() || m_submode == DeleteSubMode) {
+ pos = qMin(pos, anchor());
+ if (isVisualLineMode())
+ pos = firstPositionInLine(lineForPosition(pos));
+ } else if (m_movetype == MoveLineWise && hasConfig(ConfigStartOfLine)) {
+ QTextCursor tc = cursor();
+ if (m_submode == ShiftLeftSubMode || m_submode == ShiftRightSubMode
+ || m_submode == IndentSubMode) {
+ pos = qMin(pos, anchor());
+ }
+ tc.setPosition(pos);
+ moveToFirstNonBlankOnLine(&tc);
+ pos = qMin(pos, tc.position());
+ }
+ }
+
+ m_redo.clear();
+ while (!m_undo.empty() && m_undo.top().revision >= rev)
+ m_undo.pop();
+ m_lastChangePosition = CursorPosition(document(), pos);
+ if (isVisualMode()) {
+ setMark(QLatin1Char('<'), mark(QLatin1Char('<')).position);
+ setMark(QLatin1Char('>'), mark(QLatin1Char('>')).position);
+ }
+ m_undo.push(
+ State(rev, m_lastChangePosition, m_marks, m_lastVisualMode, m_lastVisualModeInverted));
}
void FakeVimHandler::Private::moveDown(int n)
{
-#if 0
- // does not work for "hidden" documents like in the autotests
- tc.movePosition(Down, MoveAnchor, n);
-#else
- const int col = position() - block().position();
- const int lastLine = document()->lastBlock().blockNumber();
- const int targetLine = qMax(0, qMin(lastLine, block().blockNumber() + n));
- const QTextBlock &block = document()->findBlockByNumber(targetLine);
- const int pos = block.position();
- setPosition(pos + qMax(0, qMin(block.length() - 2, col)));
+ QTextBlock block = cursor().block();
+ const int col = position() - block.position();
+ const int targetLine = qMax(0, lineNumber(block) + n);
+
+ block = document()->findBlockByLineNumber(qMax(0, targetLine - 1));
+ if (!block.isValid())
+ block = document()->lastBlock();
+ setPosition(block.position() + qMax(0, qMin(block.length() - 2, col)));
moveToTargetColumn();
-#endif
+}
+
+bool FakeVimHandler::Private::moveToNextParagraph(int count)
+{
+ const bool forward = count > 0;
+ int repeat = forward ? count : -count;
+ QTextBlock block = this->block();
+
+ if (block.isValid() && block.length() == 1)
+ ++repeat;
+
+ for (; block.isValid(); block = forward ? block.next() : block.previous()) {
+ if (block.length() == 1) {
+ if (--repeat == 0)
+ break;
+ while (block.isValid() && block.length() == 1)
+ block = forward ? block.next() : block.previous();
+ }
+ }
+
+ if (repeat == 0)
+ setPosition(block.position());
+ else if (repeat == 1)
+ setPosition(forward ? lastPositionInDocument() : 0);
+ else
+ return false;
+
+ setTargetColumn();
+ m_movetype = MoveExclusive;
+
+ return true;
}
void FakeVimHandler::Private::moveToEndOfLine()
{
-#if 0
- // does not work for "hidden" documents like in the autotests
- tc.movePosition(EndOfLine, MoveAnchor);
-#else
- const int pos = block().position() + block().length() - 2;
- setPosition(qMax(block().position(), pos));
-#endif
+ // Additionally select (in visual mode) or apply current command on hidden lines following
+ // the current line.
+ bool onlyVisibleLines = isVisualMode() || m_submode != NoSubMode;
+ const int id = onlyVisibleLines ? lineNumber(block()) : block().blockNumber() + 1;
+ setPosition(lastPositionInLine(id, onlyVisibleLines));
}
void FakeVimHandler::Private::moveBehindEndOfLine()
{
+ emit q->fold(1, false);
int pos = qMin(block().position() + block().length() - 1,
- lastPositionInDocument());
+ lastPositionInDocument() + 1);
setPosition(pos);
}
@@ -1702,63 +2601,103 @@ void FakeVimHandler::Private::moveToStartOfLine()
#endif
}
-void FakeVimHandler::Private::finishMovement(const QString &dotCommand, int count)
+void FakeVimHandler::Private::fixSelection()
{
- finishMovement(dotCommand.arg(count));
+ if (m_rangemode == RangeBlockMode)
+ return;
+
+ if (m_movetype == MoveExclusive) {
+ if (anchor() < position() && atBlockStart()) {
+ // Exlusive motion ending at the beginning of line
+ // becomes inclusive and end is moved to end of previous line.
+ m_movetype = MoveInclusive;
+ moveToStartOfLine();
+ moveLeft();
+
+ // Exclusive motion ending at the beginning of line and
+ // starting at or before first non-blank on a line becomes linewise.
+ if (anchor() < block().position() && isFirstNonBlankOnLine(anchor()))
+ m_movetype = MoveLineWise;
+ }
+ }
+
+ if (m_movetype == MoveLineWise)
+ m_rangemode = (m_submode == ChangeSubMode)
+ ? RangeLineModeExclusive
+ : RangeLineMode;
+
+ if (m_movetype == MoveInclusive) {
+ if (anchor() <= position()) {
+ if (!atBlockEnd())
+ setPosition(position() + 1); // correction
+
+ // Omit first character in selection if it's line break on non-empty line.
+ int start = anchor();
+ int end = position();
+ if (afterEndOfLine(document(), start) && start > 0) {
+ start = qMin(start + 1, end);
+ if (m_submode == DeleteSubMode && !atDocumentEnd())
+ setAnchorAndPosition(start, end + 1);
+ else
+ setAnchorAndPosition(start, end);
+ }
+
+ // If more than one line is selected and all are selected completely
+ // movement becomes linewise.
+ if (start < block().position() && isFirstNonBlankOnLine(start) && atBlockEnd()) {
+ if (m_submode != ChangeSubMode) {
+ moveRight();
+ if (atEmptyLine())
+ moveRight();
+ }
+ m_movetype = MoveLineWise;
+ }
+ } else {
+ setAnchorAndPosition(anchor() + 1, position());
+ }
+ }
+
+ if (m_positionPastEnd) {
+ const int anc = anchor();
+ moveBehindEndOfLine();
+ moveRight();
+ setAnchorAndPosition(anc, position());
+ }
+
+ if (m_anchorPastEnd)
+ setAnchorAndPosition(anchor() + 1, position());
+}
+
+void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement, int count)
+{
+ finishMovement(dotCommandMovement.arg(count));
}
-void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
+void FakeVimHandler::Private::finishMovement(const QString &dotCommandMovement)
{
//dump("FINISH MOVEMENT");
if (m_submode == FilterSubMode) {
int beginLine = lineForPosition(anchor());
int endLine = lineForPosition(position());
setPosition(qMin(anchor(), position()));
- enterExMode();
- m_currentMessage.clear();
- m_commandBuffer.setContents(QString(".,+%1!").arg(qAbs(endLine - beginLine)));
- //g.commandHistory.append(QString());
- updateMiniBuffer();
+ enterExMode(QString::fromLatin1(".,+%1!").arg(qAbs(endLine - beginLine)));
return;
}
- //if (isVisualMode())
- // setMark('>', position());
-
if (m_submode == ChangeSubMode
|| m_submode == DeleteSubMode
|| m_submode == YankSubMode
- || m_submode == TransformSubMode) {
-
+ || m_submode == InvertCaseSubMode
+ || m_submode == DownCaseSubMode
+ || m_submode == UpCaseSubMode) {
if (m_submode != YankSubMode)
beginEditBlock();
- if (m_movetype == MoveLineWise)
- m_rangemode = (m_submode == ChangeSubMode)
- ? RangeLineModeExclusive
- : RangeLineMode;
-
- if (m_movetype == MoveInclusive) {
- if (anchor() <= position()) {
- if (!cursor().atBlockEnd())
- setPosition(position() + 1); // correction
- } else {
- setAnchorAndPosition(anchor() + 1, position());
- }
- }
-
- if (m_positionPastEnd) {
- const int anc = anchor();
- moveBehindEndOfLine();
- moveRight();
- setAnchorAndPosition(anc, position());
- }
-
- if (m_anchorPastEnd) {
- setAnchorAndPosition(anchor() + 1, position());
- }
+ fixSelection();
- if (m_submode != TransformSubMode) {
+ if (m_submode != InvertCaseSubMode
+ && m_submode != DownCaseSubMode
+ && m_submode != UpCaseSubMode) {
yankText(currentRange(), m_register);
if (m_movetype == MoveLineWise)
setRegister(m_register, registerContents(m_register), RangeLineMode);
@@ -1767,86 +2706,93 @@ void FakeVimHandler::Private::finishMovement(const QString &dotCommand)
m_positionPastEnd = m_anchorPastEnd = false;
}
+ QString dotCommand;
if (m_submode == ChangeSubMode) {
- if (m_rangemode == RangeLineMode)
- m_rangemode = RangeLineModeExclusive;
+ if (m_rangemode != RangeLineModeExclusive)
+ setUndoPosition();
removeText(currentRange());
- if (!dotCommand.isEmpty())
- setDotCommand(QLatin1Char('c') + dotCommand);
+ dotCommand = _("c");
if (m_movetype == MoveLineWise)
insertAutomaticIndentation(true);
endEditBlock();
- enterInsertMode();
- m_submode = NoSubMode;
+ setTargetColumn();
+ m_lastInsertion.clear();
+ g.returnToMode = InsertMode;
} else if (m_submode == DeleteSubMode) {
- removeText(currentRange());
- if (!dotCommand.isEmpty())
- setDotCommand(QLatin1Char('d') + dotCommand);
+ setUndoPosition();
+ const int pos = position();
+ // Always delete something (e.g. 'dw' on an empty line deletes the line).
+ if (pos == anchor() && m_movetype == MoveInclusive)
+ removeText(Range(pos, pos + 1));
+ else
+ removeText(currentRange());
+ dotCommand = _("d");
if (m_movetype == MoveLineWise)
handleStartOfLine();
- m_submode = NoSubMode;
if (atEndOfLine())
moveLeft();
else
setTargetColumn();
endEditBlock();
} else if (m_submode == YankSubMode) {
- m_submode = NoSubMode;
- const int la = lineForPosition(anchor());
- const int lp = lineForPosition(position());
- if (m_register != '"') {
- setPosition(mark(m_register));
- moveToStartOfLine();
+ const QTextCursor tc = cursor();
+ if (m_rangemode == RangeBlockMode) {
+ const int pos1 = tc.block().position();
+ const int pos2 = document()->findBlock(tc.anchor()).position();
+ const int col = qMin(tc.position() - pos1, tc.anchor() - pos2);
+ setPosition(qMin(pos1, pos2) + col);
} else {
- if (anchor() <= position())
- setPosition(anchor());
+ setPosition(qMin(position(), anchor()));
+ if (m_rangemode == RangeLineMode) {
+ if (isVisualMode())
+ moveToStartOfLine();
+ }
}
- if (la != lp)
- showBlackMessage(QString("%1 lines yanked").arg(qAbs(la - lp) + 1));
- } else if (m_submode == TransformSubMode) {
- if (m_subsubmode == InvertCaseSubSubMode) {
+ leaveVisualMode();
+ setTargetColumn();
+ } else if (m_submode == InvertCaseSubMode
+ || m_submode == UpCaseSubMode
+ || m_submode == DownCaseSubMode) {
+ if (m_submode == InvertCaseSubMode) {
invertCase(currentRange());
- if (!dotCommand.isEmpty())
- setDotCommand(QLatin1Char('~') + dotCommand);
- } else if (m_subsubmode == UpCaseSubSubMode) {
- upCase(currentRange());
- if (!dotCommand.isEmpty())
- setDotCommand("gU" + dotCommand);
- } else if (m_subsubmode == DownCaseSubSubMode) {
+ dotCommand = QString::fromLatin1("g~");
+ } else if (m_submode == DownCaseSubMode) {
downCase(currentRange());
- if (!dotCommand.isEmpty())
- setDotCommand("gu" + dotCommand);
+ dotCommand = QString::fromLatin1("gu");
+ } else if (m_submode == UpCaseSubMode) {
+ upCase(currentRange());
+ dotCommand = QString::fromLatin1("gU");
}
- m_submode = NoSubMode;
- m_subsubmode = NoSubSubMode;
- setPosition(qMin(anchor(), position()));
if (m_movetype == MoveLineWise)
handleStartOfLine();
endEditBlock();
- } else if (m_submode == IndentSubMode) {
- setUndoPosition();
- recordJump();
- indentSelectedText();
- m_submode = NoSubMode;
- } else if (m_submode == ShiftRightSubMode) {
- setUndoPosition();
+ } else if (m_submode == IndentSubMode
+ || m_submode == ShiftRightSubMode
+ || m_submode == ShiftLeftSubMode) {
recordJump();
- shiftRegionRight(1);
- m_submode = NoSubMode;
- } else if (m_submode == ShiftLeftSubMode) {
setUndoPosition();
- recordJump();
- shiftRegionLeft(1);
- m_submode = NoSubMode;
+ if (m_submode == IndentSubMode) {
+ indentSelectedText();
+ dotCommand = _("=");
+ } else if (m_submode == ShiftRightSubMode) {
+ shiftRegionRight(1);
+ dotCommand = _(">");
+ } else if (m_submode == ShiftLeftSubMode) {
+ shiftRegionLeft(1);
+ dotCommand = _("<");
+ }
}
+ if (!dotCommand.isEmpty() && !dotCommandMovement.isEmpty())
+ setDotCommand(dotCommand + dotCommandMovement);
+
resetCommandMode();
- updateSelection();
- updateMiniBuffer();
}
void FakeVimHandler::Private::resetCommandMode()
{
+ m_subsubmode = NoSubSubMode;
+ m_submode = NoSubMode;
m_movetype = MoveInclusive;
m_mvcount.clear();
m_opcount.clear();
@@ -1854,27 +2800,31 @@ void FakeVimHandler::Private::resetCommandMode()
m_register = '"';
//m_tc.clearSelection();
m_rangemode = RangeCharMode;
+ g.currentCommand.clear();
+ if (g.returnToMode != CommandMode) {
+ const QString lastInsertion = m_lastInsertion;
+ if (g.returnToMode == InsertMode)
+ enterInsertMode();
+ else
+ enterReplaceMode();
+ m_lastInsertion = lastInsertion;
+ moveToTargetColumn();
+ }
+ if (isNoVisualMode())
+ setAnchor();
}
void FakeVimHandler::Private::updateSelection()
{
- QList<QTextEdit::ExtraSelection> selections = m_searchSelections;
- if (!m_searchCursor.isNull()) {
- QTextEdit::ExtraSelection sel;
- sel.cursor = m_searchCursor;
- sel.format = m_searchCursor.blockCharFormat();
- sel.format.setForeground(Qt::white);
- sel.format.setBackground(Qt::black);
- selections.append(sel);
- }
+ QList<QTextEdit::ExtraSelection> selections = m_extraSelections;
if (hasConfig(ConfigShowMarks)) {
for (MarksIterator it(m_marks); it.hasNext(); ) {
it.next();
QTextEdit::ExtraSelection sel;
- const int pos = it.value().position();
sel.cursor = cursor();
- sel.cursor.setPosition(pos, MoveAnchor);
- sel.cursor.setPosition(pos + 1, KeepAnchor);
+ setCursorPosition(&sel.cursor, it.value().position);
+ sel.cursor.setPosition(sel.cursor.position(), MoveAnchor);
+ sel.cursor.movePosition(Right, KeepAnchor);
sel.format = cursor().blockCharFormat();
sel.format.setForeground(Qt::blue);
sel.format.setBackground(Qt::green);
@@ -1885,6 +2835,12 @@ void FakeVimHandler::Private::updateSelection()
emit q->selectionChanged(selections);
}
+void FakeVimHandler::Private::updateHighlights()
+{
+ if (!hasConfig(ConfigUseCoreSearch))
+ emit q->highlightMatches(m_oldNeedle);
+}
+
void FakeVimHandler::Private::updateMiniBuffer()
{
if (!m_textedit && !m_plaintextedit)
@@ -1892,34 +2848,58 @@ void FakeVimHandler::Private::updateMiniBuffer()
QString msg;
int cursorPos = -1;
+ int anchorPos = -1;
+ MessageLevel messageLevel = MessageMode;
+
+ if (g.mapStates.last().silent && g.currentMessageLevel < MessageInfo)
+ g.currentMessage.clear();
+
if (m_passing) {
- msg = "-- PASSING -- ";
- } else if (!m_currentMessage.isEmpty()) {
- msg = m_currentMessage;
- } else if (m_mode == CommandMode && isVisualMode()) {
- if (isVisualCharMode()) {
- msg = "-- VISUAL --";
- } else if (isVisualLineMode()) {
- msg = "-- VISUAL LINE --";
- } else if (isVisualBlockMode()) {
- msg = "-- VISUAL BLOCK --";
+ msg = _("PASSING");
+ } else if (m_subsubmode == SearchSubSubMode) {
+ msg = g.searchBuffer.display();
+ if (g.mapStates.size() == 1) {
+ cursorPos = g.searchBuffer.cursorPos() + 1;
+ anchorPos = g.searchBuffer.anchorPos() + 1;
}
+ } else if (m_mode == ExMode) {
+ msg = g.commandBuffer.display();
+ if (g.mapStates.size() == 1) {
+ cursorPos = g.commandBuffer.cursorPos() + 1;
+ anchorPos = g.commandBuffer.anchorPos() + 1;
+ }
+ } else if (!g.currentMessage.isEmpty()) {
+ msg = g.currentMessage;
+ g.currentMessage.clear();
+ messageLevel = g.currentMessageLevel;
+ } else if (g.mapStates.size() > 1 && !g.mapStates.last().silent) {
+ // Do not reset previous message when after running a mapped command.
+ return;
+ } else if (m_mode == CommandMode && !g.currentCommand.isEmpty() && hasConfig(ConfigShowCmd)) {
+ msg = g.currentCommand;
+ messageLevel = MessageShowCmd;
+ } else if (m_mode == CommandMode && isVisualMode()) {
+ if (isVisualCharMode())
+ msg = _("VISUAL");
+ else if (isVisualLineMode())
+ msg = _("VISUAL LINE");
+ else if (isVisualBlockMode())
+ msg = _("VISUAL BLOCK");
} else if (m_mode == InsertMode) {
- msg = "-- INSERT --";
+ msg = _("INSERT");
} else if (m_mode == ReplaceMode) {
- msg = "-- REPLACE --";
- } else if (!m_commandPrefix.isEmpty()) {
- //QTC_ASSERT(m_mode == ExMode || m_subsubmode == SearchSubSubMode,
- // qDebug() << "MODE: " << m_mode << m_subsubmode);
- msg = m_commandPrefix + m_commandBuffer.display();
- if (m_mode != CommandMode)
- cursorPos = m_commandPrefix.size() + m_commandBuffer.cursorPos();
+ msg = _("REPLACE");
} else {
QTC_CHECK(m_mode == CommandMode && m_subsubmode != SearchSubSubMode);
- msg = "-- COMMAND --";
+ if (g.returnToMode == CommandMode)
+ msg = _("COMMAND");
+ else if (g.returnToMode == InsertMode)
+ msg = _("(insert)");
+ else
+ msg = _("(replace)");
}
- emit q->commandBufferChanged(msg, cursorPos);
+ emit q->commandBufferChanged(msg, cursorPos, anchorPos, messageLevel, q);
int linesInDoc = linesInDocument();
int l = cursorLine();
@@ -1927,33 +2907,24 @@ void FakeVimHandler::Private::updateMiniBuffer()
const QString pos = QString::fromLatin1("%1,%2")
.arg(l + 1).arg(physicalCursorColumn() + 1);
// FIXME: physical "-" logical
- if (linesInDoc != 0) {
+ if (linesInDoc != 0)
status = FakeVimHandler::tr("%1%2%").arg(pos, -10).arg(l * 100 / linesInDoc, 4);
- } else {
+ else
status = FakeVimHandler::tr("%1All").arg(pos, -10);
- }
emit q->statusDataChanged(status);
}
-void FakeVimHandler::Private::showRedMessage(const QString &msg)
-{
- //qDebug() << "MSG: " << msg;
- m_currentMessage = msg;
- updateMiniBuffer();
-}
-
-void FakeVimHandler::Private::showBlackMessage(const QString &msg)
+void FakeVimHandler::Private::showMessage(MessageLevel level, const QString &msg)
{
//qDebug() << "MSG: " << msg;
- m_commandBuffer.setContents(msg);
- updateMiniBuffer();
+ g.currentMessage = msg;
+ g.currentMessageLevel = level;
}
void FakeVimHandler::Private::notImplementedYet()
{
qDebug() << "Not implemented in FakeVim";
- showRedMessage(FakeVimHandler::tr("Not implemented in FakeVim"));
- updateMiniBuffer();
+ showMessage(MessageError, FakeVimHandler::tr("Not implemented in FakeVim"));
}
void FakeVimHandler::Private::passShortcuts(bool enable)
@@ -1966,20 +2937,10 @@ void FakeVimHandler::Private::passShortcuts(bool enable)
QCoreApplication::instance()->removeEventFilter(q);
}
-static bool subModeCanUseTextObjects(int submode)
-{
- return submode == DeleteSubMode
- || submode == YankSubMode
- || submode == ChangeSubMode
- || submode == IndentSubMode
- || submode == ShiftLeftSubMode
- || submode == ShiftRightSubMode;
-}
-
-EventResult FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
+bool FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
{
//const int key = input.key;
- EventResult handled = EventHandled;
+ bool handled = true;
if (m_subsubmode == FtSubSubMode) {
m_semicolonType = m_subsubdata;
m_semicolonKey = input.text();
@@ -1987,14 +2948,16 @@ EventResult FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
m_subsubmode = NoSubSubMode;
if (!valid) {
m_submode = NoSubMode;
- finishMovement();
+ resetCommandMode();
+ handled = false;
} else {
- finishMovement(QString("%1%2%3")
+ finishMovement(QString::fromLatin1("%1%2%3")
.arg(count())
.arg(m_semicolonType.text())
.arg(m_semicolonKey));
}
} else if (m_subsubmode == TextObjectSubSubMode) {
+ bool ok = true;
if (input.is('w'))
selectWordTextObject(m_subsubdata.is('i'));
else if (input.is('W'))
@@ -2004,245 +2967,99 @@ EventResult FakeVimHandler::Private::handleCommandSubSubMode(const Input &input)
else if (input.is('p'))
selectParagraphTextObject(m_subsubdata.is('i'));
else if (input.is('[') || input.is(']'))
- selectBlockTextObject(m_subsubdata.is('i'), '[', ']');
+ ok = selectBlockTextObject(m_subsubdata.is('i'), '[', ']');
else if (input.is('(') || input.is(')') || input.is('b'))
- selectBlockTextObject(m_subsubdata.is('i'), '(', ')');
+ ok = selectBlockTextObject(m_subsubdata.is('i'), '(', ')');
else if (input.is('<') || input.is('>'))
- selectBlockTextObject(m_subsubdata.is('i'), '<', '>');
+ ok = selectBlockTextObject(m_subsubdata.is('i'), '<', '>');
else if (input.is('{') || input.is('}') || input.is('B'))
- selectBlockTextObject(m_subsubdata.is('i'), '{', '}');
+ ok = selectBlockTextObject(m_subsubdata.is('i'), '{', '}');
else if (input.is('"') || input.is('\'') || input.is('`'))
- selectQuotedStringTextObject(m_subsubdata.is('i'), input.asChar());
+ ok = selectQuotedStringTextObject(m_subsubdata.is('i'), input.asChar());
+ else
+ ok = false;
m_subsubmode = NoSubSubMode;
- finishMovement(QString("%1%2%3")
- .arg(count())
- .arg(m_subsubdata.text())
- .arg(input.text()));
+ if (ok) {
+ finishMovement(QString::fromLatin1("%1%2%3")
+ .arg(count())
+ .arg(m_subsubdata.text())
+ .arg(input.text()));
+ } else {
+ resetCommandMode();
+ handled = false;
+ }
} else if (m_subsubmode == MarkSubSubMode) {
- setMark(input.asChar().unicode(), position());
+ setMark(input.asChar(), CursorPosition(cursor()));
m_subsubmode = NoSubSubMode;
} else if (m_subsubmode == BackTickSubSubMode
|| m_subsubmode == TickSubSubMode) {
- int m = mark(input.asChar().unicode());
- if (m != -1) {
- setPosition(m);
- if (m_subsubmode == TickSubSubMode)
- moveToFirstNonBlankOnLine();
+ if (jumpToMark(input.asChar(), m_subsubmode == BackTickSubSubMode)) {
finishMovement();
} else {
- showRedMessage(msgMarkNotSet(input.text()));
+ resetCommandMode();
+ handled = false;
}
m_subsubmode = NoSubSubMode;
+ } else if (m_subsubmode == ZSubSubMode) {
+ handled = false;
+ if (input.is('j') || input.is('k')) {
+ int pos = position();
+ emit q->foldGoTo(input.is('j') ? count() : -count(), false);
+ if (pos != position()) {
+ handled = true;
+ finishMovement(QString::fromLatin1("%1z%2")
+ .arg(count())
+ .arg(input.text()));
+ }
+ }
+ } else if (m_subsubmode == OpenSquareSubSubMode || CloseSquareSubSubMode) {
+ int pos = position();
+ if ((input.is('{') && m_subsubmode == OpenSquareSubSubMode))
+ searchBalanced(false, QLatin1Char('{'), QLatin1Char('}'));
+ else if ((input.is('}') && m_subsubmode == CloseSquareSubSubMode))
+ searchBalanced(true, QLatin1Char('}'), QLatin1Char('{'));
+ else if ((input.is('(') && m_subsubmode == OpenSquareSubSubMode))
+ searchBalanced(false, QLatin1Char('('), QLatin1Char(')'));
+ else if ((input.is(')') && m_subsubmode == CloseSquareSubSubMode))
+ searchBalanced(true, QLatin1Char(')'), QLatin1Char('('));
+ else if (input.is('z'))
+ emit q->foldGoTo(m_subsubmode == OpenSquareSubSubMode ? -count() : count(), true);
+ handled = pos != position();
+ if (handled) {
+ finishMovement(QString::fromLatin1("%1%2%3")
+ .arg(count())
+ .arg(m_subsubmode == OpenSquareSubSubMode ? '[' : ']')
+ .arg(input.text()));
+ }
} else {
- handled = EventUnhandled;
- }
- return handled;
-}
-
-EventResult FakeVimHandler::Private::handleOpenSquareSubMode(const Input &input)
-{
- EventResult handled = EventHandled;
- m_submode = NoSubMode;
- if (input.is('{')) {
- searchBalanced(false, '{', '}');
- } else if (input.is('(')) {
- searchBalanced(false, '(', ')');
- } else {
- handled = EventUnhandled;
- }
- return handled;
-}
-
-EventResult FakeVimHandler::Private::handleCloseSquareSubMode(const Input &input)
-{
- EventResult handled = EventHandled;
- m_submode = NoSubMode;
- if (input.is('}')) {
- searchBalanced(true, '}', '{');
- } else if (input.is(')')) {
- searchBalanced(true, ')', '(');
- } else {
- handled = EventUnhandled;
+ handled = false;
}
return handled;
}
-EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
+bool FakeVimHandler::Private::handleMovement(const Input &input)
{
- EventResult handled = EventHandled;
+ bool handled = true;
+ QString movement;
+ int count = this->count();
- if (input.isEscape()) {
- if (isVisualMode()) {
- leaveVisualMode();
- } else if (m_submode != NoSubMode) {
- m_submode = NoSubMode;
- m_subsubmode = NoSubSubMode;
- finishMovement();
- } else {
- resetCommandMode();
- updateSelection();
- updateMiniBuffer();
- }
- } else if (m_subsubmode != NoSubSubMode) {
- handleCommandSubSubMode(input);
- } else if (m_submode == OpenSquareSubMode) {
- handled = handleOpenSquareSubMode(input);
- } else if (m_submode == CloseSquareSubMode) {
- handled = handleCloseSquareSubMode(input);
- } else if (m_submode == WindowSubMode) {
- emit q->windowCommandRequested(input.key());
- m_submode = NoSubMode;
- } else if (m_submode == RegisterSubMode) {
- m_register = input.asChar().unicode();
- m_submode = NoSubMode;
- m_rangemode = RangeLineMode;
- } else if (m_submode == ReplaceSubMode) {
- if (isVisualMode()) {
- setUndoPosition();
- m_lastChangePosition = position();
- if (isVisualLineMode())
- m_rangemode = RangeLineMode;
- else if (isVisualBlockMode())
- m_rangemode = RangeBlockMode;
- else
- m_rangemode = RangeCharMode;
- leaveVisualMode();
- Range range = currentRange();
- Transformation tr =
- &FakeVimHandler::Private::replaceByCharTransform;
- transformText(range, tr, input.asChar());
- setPosition(range.beginPos);
- } else if (count() <= rightDist()) {
- setUndoPosition();
- m_lastChangePosition = position();
- setAnchor();
- moveRight(count());
- Range range = currentRange();
- if (input.isReturn()) {
- beginEditBlock();
- replaceText(range, QString());
- insertText(QString("\n"));
- endEditBlock();
- } else {
- replaceText(range, QString(count(), input.asChar()));
- moveLeft();
- }
- setTargetColumn();
- setDotCommand("%1r" + input.text(), count());
- }
- m_submode = NoSubMode;
- finishMovement();
- } else if (m_submode == ChangeSubMode && input.is('c')) { // tested
- setUndoPosition();
- m_lastChangePosition = position();
- moveToStartOfLine();
- setAnchor();
- moveDown(count() - 1);
- moveToEndOfLine();
- m_movetype = MoveLineWise;
- m_lastInsertion.clear();
- setDotCommand("%1cc", count());
- finishMovement();
- } else if (m_submode == DeleteSubMode && input.is('d')) { // tested
- setUndoPosition();
- m_lastChangePosition = position();
- m_movetype = MoveLineWise;
- int endPos = firstPositionInLine(lineForPosition(position()) + count() - 1);
- Range range(position(), endPos, RangeLineMode);
- yankText(range);
- removeText(range);
- setDotCommand("%1dd", count());
- m_submode = NoSubMode;
- handleStartOfLine();
- setTargetColumn();
- finishMovement();
- } else if ((subModeCanUseTextObjects(m_submode) || isVisualMode())
- && (input.is('a') || input.is('i'))) {
- m_subsubmode = TextObjectSubSubMode;
- m_subsubdata = input;
- } else if (m_submode == ShiftLeftSubMode && input.is('<')) {
- m_lastChangePosition = position();
- setAnchor();
- moveDown(count() - 1);
- m_movetype = MoveLineWise;
- setDotCommand("%1<<", count());
- finishMovement();
- } else if (m_submode == ShiftRightSubMode && input.is('>')) {
- m_lastChangePosition = position();
- setAnchor();
- moveDown(count() - 1);
- m_movetype = MoveLineWise;
- setDotCommand("%1>>", count());
- finishMovement();
- } else if (m_submode == IndentSubMode && input.is('=')) {
- m_lastChangePosition = position();
- setAnchor();
- moveDown(count() - 1);
- m_movetype = MoveLineWise;
- setDotCommand("%1==", count());
- finishMovement();
- } else if (m_submode == ZSubMode) {
- //qDebug() << "Z_MODE " << cursorLine() << linesOnScreen();
- if (input.isReturn() || input.is('t')) {
- // Cursor line to top of window.
- if (!m_mvcount.isEmpty())
- setPosition(firstPositionInLine(count()));
- scrollUp(- cursorLineOnScreen());
- if (input.isReturn())
- moveToFirstNonBlankOnLine();
- finishMovement();
- } else if (input.is('.') || input.is('z')) {
- // Cursor line to center of window.
- if (!m_mvcount.isEmpty())
- setPosition(firstPositionInLine(count()));
- scrollUp(linesOnScreen() / 2 - cursorLineOnScreen());
- if (input.is('.'))
- moveToFirstNonBlankOnLine();
- finishMovement();
- } else if (input.is('-') || input.is('b')) {
- // Cursor line to bottom of window.
- if (!m_mvcount.isEmpty())
- setPosition(firstPositionInLine(count()));
- scrollUp(linesOnScreen() - cursorLineOnScreen());
- if (input.is('-'))
- moveToFirstNonBlankOnLine();
- finishMovement();
- } else {
- qDebug() << "IGNORED Z_MODE " << input.key() << input.text();
- }
- m_submode = NoSubMode;
- } else if (m_submode == CapitalZSubMode) {
- // Recognize ZZ and ZQ as aliases for ":x" and ":q!".
- m_submode = NoSubMode;
- if (input.is('Z'))
- handleExCommand(QString(QLatin1Char('x')));
- else if (input.is('Q'))
- handleExCommand("q!");
- } else if (input.isDigit()) {
+ if (input.isDigit()) {
if (input.is('0') && m_mvcount.isEmpty()) {
m_movetype = MoveExclusive;
moveToStartOfLine();
setTargetColumn();
- finishMovement(QString(QLatin1Char('0')));
+ count = 1;
} else {
m_mvcount.append(input.text());
+ return true;
}
- } else {
- handled = handleCommandMode1(input);
- }
-
- return handled;
-}
-
-EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
-{
- EventResult handled = EventHandled;
-
- if (input.is('^') || input.is('_')) {
+ } else if (input.is('a') || input.is('i')) {
+ m_subsubmode = TextObjectSubSubMode;
+ m_subsubdata = input;
+ } else if (input.is('^') || input.is('_')) {
moveToFirstNonBlankOnLine();
setTargetColumn();
m_movetype = MoveExclusive;
- finishMovement(input.text());
} else if (0 && input.is(',')) {
// FIXME: fakevim uses ',' by itself, so it is incompatible
m_subsubmode = FtSubSubMode;
@@ -2250,120 +3067,380 @@ EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
//m_subsubdata = m_semicolonType ^ 32;
handleFfTt(m_semicolonKey);
m_subsubmode = NoSubSubMode;
- finishMovement();
} else if (input.is(';')) {
m_subsubmode = FtSubSubMode;
m_subsubdata = m_semicolonType;
handleFfTt(m_semicolonKey);
m_subsubmode = NoSubSubMode;
- finishMovement();
- } else if (input.is('&')) {
- handleExCommand(m_gflag ? "%s//~/&" : "s");
- } else if (input.is(':')) {
- enterExMode();
- g.commandHistory.restart();
- m_currentMessage.clear();
- m_commandBuffer.clear();
- if (isVisualMode())
- m_commandBuffer.setContents("'<,'>");
- updateMiniBuffer();
} else if (input.is('/') || input.is('?')) {
- m_lastSearchForward = input.is('/');
- g.searchHistory.restart();
+ g.lastSearchForward = input.is('/');
if (hasConfig(ConfigUseCoreSearch)) {
// re-use the core dialog.
- m_findPending = true;
+ g.findPending = true;
m_findStartPosition = position();
m_movetype = MoveExclusive;
setAnchor(); // clear selection: otherwise, search is restricted to selection
- emit q->findRequested(!m_lastSearchForward);
+ emit q->findRequested(!g.lastSearchForward);
} else {
// FIXME: make core find dialog sufficiently flexible to
// produce the "default vi" behaviour too. For now, roll our own.
- m_currentMessage.clear();
+ g.currentMessage.clear();
m_movetype = MoveExclusive;
m_subsubmode = SearchSubSubMode;
- m_commandPrefix = QLatin1Char(m_lastSearchForward ? '/' : '?');
- m_commandBuffer.clear();
- updateMiniBuffer();
+ g.searchBuffer.setPrompt(g.lastSearchForward ? QLatin1Char('/') : QLatin1Char('?'));
+ m_searchStartPosition = position();
+ m_searchFromScreenLine = firstVisibleLine();
+ m_searchCursor = QTextCursor();
+ g.searchBuffer.clear();
}
} else if (input.is('`')) {
m_subsubmode = BackTickSubSubMode;
- if (m_submode != NoSubMode)
- m_movetype = MoveLineWise;
} else if (input.is('#') || input.is('*')) {
// FIXME: That's not proper vim behaviour
QString needle;
QTextCursor tc = cursor();
tc.select(QTextCursor::WordUnderCursor);
- needle = "\\<" + tc.selection().toPlainText() + "\\>";
+ needle = QRegExp::escape(tc.selection().toPlainText());
+ if (!m_gflag)
+ needle = _("\\<") + needle + _("\\>");
setAnchorAndPosition(tc.position(), tc.anchor());
- g.searchHistory.append(needle);
- m_lastSearchForward = input.is('*');
- m_currentMessage.clear();
- m_commandPrefix = QLatin1Char(m_lastSearchForward ? '/' : '?');
- m_commandBuffer.setContents(needle);
- SearchData sd;
- sd.needle = needle;
- sd.forward = m_lastSearchForward;
- sd.highlightCursor = false;
- sd.highlightMatches = true;
- search(sd);
- //m_searchCursor = QTextCursor();
- //updateSelection();
- //updateMiniBuffer();
+ g.searchBuffer.historyPush(needle);
+ g.lastSearch = needle;
+ g.lastSearchForward = input.is('*');
+ searchNext();
} else if (input.is('\'')) {
m_subsubmode = TickSubSubMode;
if (m_submode != NoSubMode)
m_movetype = MoveLineWise;
} else if (input.is('|')) {
moveToStartOfLine();
- moveRight(qMin(count(), rightDist()) - 1);
+ moveRight(qMin(count, rightDist()) - 1);
setTargetColumn();
- finishMovement();
- } else if (input.is('!') && isNoVisualMode()) {
- m_submode = FilterSubMode;
- } else if (input.is('!') && isVisualMode()) {
- enterExMode();
- m_currentMessage.clear();
- m_commandBuffer.setContents("'<,'>!");
- //g.commandHistory.append(QString());
- updateMiniBuffer();
- } else if (input.is('"')) {
- m_submode = RegisterSubMode;
+ } else if (input.is('}')) {
+ handled = moveToNextParagraph(count);
+ } else if (input.is('{')) {
+ handled = moveToPreviousParagraph(count);
} else if (input.isReturn()) {
moveToStartOfLine();
moveDown();
moveToFirstNonBlankOnLine();
m_movetype = MoveLineWise;
- finishMovement("%1j", count());
} else if (input.is('-')) {
moveToStartOfLine();
- moveUp(count());
+ moveUp(count);
moveToFirstNonBlankOnLine();
m_movetype = MoveLineWise;
- finishMovement("%1-", count());
} else if (input.is('+')) {
moveToStartOfLine();
- moveDown(count());
+ moveDown(count);
moveToFirstNonBlankOnLine();
m_movetype = MoveLineWise;
- finishMovement("%1+", count());
} else if (input.isKey(Key_Home)) {
moveToStartOfLine();
setTargetColumn();
- finishMovement();
+ movement = _("<HOME>");
} else if (input.is('$') || input.isKey(Key_End)) {
- if (count() > 1)
- moveDown(count() - 1);
+ if (count > 1)
+ moveDown(count - 1);
moveToEndOfLine();
- m_movetype = MoveInclusive;
+ m_movetype = atEmptyLine() ? MoveExclusive : MoveInclusive;
setTargetColumn();
if (m_submode == NoSubMode)
m_targetColumn = -1;
if (isVisualMode())
m_visualTargetColumn = -1;
- finishMovement("%1$", count());
+ movement = _("$");
+ } else if (input.is('%')) {
+ recordJump();
+ if (m_mvcount.isEmpty()) {
+ moveToMatchingParanthesis();
+ m_movetype = MoveInclusive;
+ } else {
+ // set cursor position in percentage - formula taken from Vim help
+ setPosition(firstPositionInLine((count * linesInDocument() + 99) / 100));
+ moveToTargetColumn();
+ handleStartOfLine();
+ m_movetype = MoveLineWise;
+ }
+ } else if (input.is('b') || input.isShift(Key_Left)) {
+ m_movetype = MoveExclusive;
+ moveToNextWordStart(count, false, false);
+ setTargetColumn();
+ movement = _("b");
+ } else if (input.is('B')) {
+ m_movetype = MoveExclusive;
+ moveToNextWordStart(count, true, false);
+ setTargetColumn();
+ } else if (input.is('e') && m_gflag) {
+ m_movetype = MoveInclusive;
+ moveToNextWordEnd(count, false, false);
+ setTargetColumn();
+ } else if (input.is('e') || input.isShift(Key_Right)) {
+ m_movetype = MoveInclusive;
+ moveToNextWordEnd(count, false, true, false);
+ setTargetColumn();
+ movement = _("e");
+ } else if (input.is('E') && m_gflag) {
+ m_movetype = MoveInclusive;
+ moveToNextWordEnd(count, true, false);
+ setTargetColumn();
+ } else if (input.is('E')) {
+ m_movetype = MoveInclusive;
+ moveToNextWordEnd(count, true, true, false);
+ setTargetColumn();
+ } else if (input.isControl('e')) {
+ // FIXME: this should use the "scroll" option, and "count"
+ if (cursorLineOnScreen() == 0)
+ moveDown(1);
+ scrollDown(1);
+ movement = _("<C-E>");
+ } else if (input.is('f')) {
+ m_subsubmode = FtSubSubMode;
+ m_movetype = MoveInclusive;
+ m_subsubdata = input;
+ } else if (input.is('F')) {
+ m_subsubmode = FtSubSubMode;
+ m_movetype = MoveExclusive;
+ m_subsubdata = input;
+ } else if (!m_gflag && input.is('g')) {
+ m_gflag = true;
+ return true;
+ } else if (input.is('g') || input.is('G')) {
+ QString dotCommand = QString::fromLatin1("%1G").arg(count);
+ recordJump();
+ if (input.is('G') && m_mvcount.isEmpty())
+ dotCommand = QString(QLatin1Char('G'));
+ int n = (input.is('g')) ? 1 : linesInDocument();
+ n = m_mvcount.isEmpty() ? n : count;
+ if (m_submode == NoSubMode || m_submode == ZSubMode
+ || m_submode == CapitalZSubMode || m_submode == RegisterSubMode) {
+ setPosition(firstPositionInLine(n, false));
+ handleStartOfLine();
+ } else {
+ m_movetype = MoveLineWise;
+ m_rangemode = RangeLineMode;
+ setAnchor();
+ setPosition(firstPositionInLine(n, false));
+ }
+ setTargetColumn();
+ } else if (input.is('h') || input.isKey(Key_Left) || input.isBackspace()) {
+ m_movetype = MoveExclusive;
+ int n = qMin(count, leftDist());
+ if (m_fakeEnd && block().length() > 1)
+ ++n;
+ moveLeft(n);
+ setTargetColumn();
+ movement = _("h");
+ } else if (input.is('H')) {
+ setCursor(EDITOR(cursorForPosition(QPoint(0, 0))));
+ moveDown(qMax(count - 1, 0));
+ handleStartOfLine();
+ } else if (input.is('j') || input.isKey(Key_Down)
+ || input.isControl('j') || input.isControl('n')) {
+ m_movetype = MoveLineWise;
+ moveDown(count);
+ movement = _("j");
+ } else if (input.is('k') || input.isKey(Key_Up) || input.isControl('p')) {
+ m_movetype = MoveLineWise;
+ moveUp(count);
+ movement = _("k");
+ } else if (input.is('l') || input.isKey(Key_Right) || input.is(' ')) {
+ m_movetype = MoveExclusive;
+ bool pastEnd = count >= rightDist() - 1;
+ moveRight(qMax(0, qMin(count, rightDist() - (m_submode == NoSubMode))));
+ setTargetColumn();
+ if (pastEnd && isVisualMode())
+ m_visualTargetColumn = -1;
+ } else if (input.is('L')) {
+ QTextCursor tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()))));
+ setCursor(tc);
+ moveUp(qMax(count, 1));
+ handleStartOfLine();
+ } else if (m_gflag && input.is('m')) {
+ moveToStartOfLine();
+ moveRight(qMin(columnsOnScreen() / 2, rightDist()) - 1);
+ setTargetColumn();
+ } else if (input.is('M')) {
+ QTextCursor tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()) / 2)));
+ setCursor(tc);
+ handleStartOfLine();
+ } else if (input.is('n') || input.is('N')) {
+ if (hasConfig(ConfigUseCoreSearch)) {
+ bool forward = (input.is('n')) ? g.lastSearchForward : !g.lastSearchForward;
+ int pos = position();
+ emit q->findNextRequested(!forward);
+ if (forward && pos == cursor().selectionStart()) {
+ // if cursor is already positioned at the start of a find result, this is returned
+ emit q->findNextRequested(false);
+ }
+ setPosition(cursor().selectionStart());
+ } else {
+ searchNext(input.is('n'));
+ }
+ } else if (input.is('t')) {
+ m_movetype = MoveInclusive;
+ m_subsubmode = FtSubSubMode;
+ m_subsubdata = input;
+ } else if (input.is('T')) {
+ m_movetype = MoveExclusive;
+ m_subsubmode = FtSubSubMode;
+ m_subsubdata = input;
+ } else if (input.is('w') || input.is('W')) { // tested
+ // Special case: "cw" and "cW" work the same as "ce" and "cE" if the
+ // cursor is on a non-blank - except if the cursor is on the last
+ // character of a word: only the current word will be changed
+ bool simple = input.is('W');
+ if (m_submode == ChangeSubMode) {
+ moveToWordEnd(count, simple, true);
+ m_movetype = MoveInclusive;
+ } else {
+ moveToNextWordStart(count, simple, true);
+ m_movetype = MoveExclusive;
+ }
+ setTargetColumn();
+ } else if (input.is('z')) {
+ m_movetype = MoveLineWise;
+ m_subsubmode = ZSubSubMode;
+ } else if (input.is('[')) {
+ m_subsubmode = OpenSquareSubSubMode;
+ } else if (input.is(']')) {
+ m_subsubmode = CloseSquareSubSubMode;
+ } else if (input.isKey(Key_PageDown) || input.isControl('f')) {
+ moveDown(count * (linesOnScreen() - 2) - cursorLineOnScreen());
+ scrollToLine(cursorLine());
+ handleStartOfLine();
+ movement = _("f");
+ } else if (input.isKey(Key_PageUp) || input.isControl('b')) {
+ moveUp(count * (linesOnScreen() - 2) + cursorLineOnScreen());
+ scrollToLine(cursorLine() + linesOnScreen() - 2);
+ handleStartOfLine();
+ movement = _("b");
+ } else if (input.isKey(Key_BracketLeft) || input.isKey(Key_BracketRight)) {
+
+ } else {
+ handled = false;
+ }
+
+ if (handled && m_subsubmode == NoSubSubMode) {
+ if (m_submode == NoSubMode) {
+ resetCommandMode();
+ } else {
+ // finish movement for sub modes
+ const QString dotMovement =
+ (count > 1 ? QString::number(count) : QString())
+ + _(m_gflag ? "g" : "")
+ + (movement.isNull() ? QString(input.asChar()) : movement);
+ finishMovement(dotMovement);
+ setTargetColumn();
+ }
+ }
+
+ return handled;
+}
+
+EventResult FakeVimHandler::Private::handleCommandMode(const Input &input)
+{
+ bool handled = false;
+
+ bool clearGflag = m_gflag;
+ bool clearRegister = m_submode != RegisterSubMode;
+ bool clearCount = m_submode != RegisterSubMode && !input.isDigit();
+
+ // Process input for a sub-mode.
+ if (input.isEscape()) {
+ handled = handleEscape();
+ } else if (m_subsubmode != NoSubSubMode) {
+ handled = handleCommandSubSubMode(input);
+ } else if (m_submode == NoSubMode) {
+ handled = handleNoSubMode(input);
+ } else if (m_submode == ChangeSubMode || m_submode == DeleteSubMode) {
+ handled = handleChangeDeleteSubModes(input);
+ } else if (m_submode == ReplaceSubMode) {
+ handled = handleReplaceSubMode(input);
+ } else if (m_submode == FilterSubMode) {
+ handled = handleFilterSubMode(input);
+ } else if (m_submode == RegisterSubMode) {
+ handled = handleRegisterSubMode(input);
+ } else if (m_submode == WindowSubMode) {
+ handled = handleWindowSubMode(input);
+ } else if (m_submode == YankSubMode) {
+ handled = handleYankSubMode(input);
+ } else if (m_submode == ZSubMode) {
+ handled = handleZSubMode(input);
+ } else if (m_submode == CapitalZSubMode) {
+ handled = handleCapitalZSubMode(input);
+ } else if (m_submode == ShiftLeftSubMode
+ || m_submode == ShiftRightSubMode
+ || m_submode == IndentSubMode) {
+ handled = handleShiftSubMode(input);
+ } else if (m_submode == InvertCaseSubMode
+ || m_submode == DownCaseSubMode
+ || m_submode == UpCaseSubMode) {
+ handled = handleChangeCaseSubMode(input);
+ }
+
+ // Clear state and display incomplete command if necessary.
+ if (handled) {
+ bool noMode =
+ (m_mode == CommandMode && m_submode == NoSubMode && m_subsubmode == NoSubSubMode);
+ clearCount = clearCount && noMode && !m_gflag;
+ if (clearCount && clearRegister) {
+ resetCommandMode();
+ } else {
+ // Use gflag only for next input.
+ if (clearGflag)
+ m_gflag = false;
+ // Clear [count] and [register] if its no longer needed.
+ if (clearCount) {
+ m_mvcount.clear();
+ m_opcount.clear();
+ }
+ // Show or clear current command on minibuffer (showcmd).
+ if (input.isEscape() || m_mode != CommandMode || clearCount)
+ g.currentCommand.clear();
+ else
+ g.currentCommand.append(input.toString());
+ }
+ } else {
+ resetCommandMode();
+ //qDebug() << "IGNORED IN COMMAND MODE: " << key << text
+ // << " VISUAL: " << m_visualMode;
+
+ // if a key which produces text was pressed, don't mark it as unhandled
+ // - otherwise the text would be inserted while being in command mode
+ if (input.text().isEmpty())
+ handled = EventUnhandled;
+ }
+
+ updateMiniBuffer();
+
+ m_positionPastEnd = (m_visualTargetColumn == -1) && isVisualMode();
+
+ return handled ? EventHandled : EventCancelled;
+}
+
+bool FakeVimHandler::Private::handleEscape()
+{
+ if (isVisualMode())
+ leaveVisualMode();
+ resetCommandMode();
+ return true;
+}
+
+bool FakeVimHandler::Private::handleNoSubMode(const Input &input)
+{
+ bool handled = true;
+
+ if (input.is('&')) {
+ handleExCommand(m_gflag ? _("%s//~/&") : _("s"));
+ } else if (input.is(':')) {
+ enterExMode();
+ } else if (input.is('!') && isNoVisualMode()) {
+ m_submode = FilterSubMode;
+ } else if (input.is('!') && isVisualMode()) {
+ enterExMode(QString::fromLatin1("!"));
+ } else if (input.is('"')) {
+ m_submode = RegisterSubMode;
} else if (input.is(',')) {
passShortcuts(true);
} else if (input.is('.')) {
@@ -2371,74 +3448,62 @@ EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
// << input;
QString savedCommand = g.dotCommand;
g.dotCommand.clear();
- replay(savedCommand, count());
- enterCommandMode();
+ replay(savedCommand);
+ resetCommandMode();
g.dotCommand = savedCommand;
- } else if (input.is('<')) {
- setUndoPosition();
- if (isNoVisualMode()) {
- m_submode = ShiftLeftSubMode;
- } else {
- shiftRegionLeft(count());
- leaveVisualMode();
- }
- } else if (input.is('>')) {
- setUndoPosition();
- if (isNoVisualMode()) {
- m_submode = ShiftRightSubMode;
- } else {
- shiftRegionRight(count());
- leaveVisualMode();
- }
- } else if (input.is('=')) {
- setUndoPosition();
+ } else if (input.is('<') || input.is('>') || input.is('=')) {
if (isNoVisualMode()) {
- m_submode = IndentSubMode;
+ if (input.is('<'))
+ m_submode = ShiftLeftSubMode;
+ else if (input.is('>'))
+ m_submode = ShiftRightSubMode;
+ else
+ m_submode = IndentSubMode;
+ setAnchor();
} else {
- indentSelectedText();
leaveVisualMode();
+ const int lines = qAbs(lineForPosition(position()) - lineForPosition(anchor())) + 1;
+ const int repeat = count();
+ if (input.is('<'))
+ shiftRegionLeft(repeat);
+ else if (input.is('>'))
+ shiftRegionRight(repeat);
+ else
+ indentSelectedText();
+ const QString selectDotCommand =
+ (lines > 1) ? QString::fromLatin1("V%1j").arg(lines - 1): QString();
+ setDotCommand(selectDotCommand + QString::fromLatin1("%1%2%2").arg(repeat).arg(input.raw()));
}
- } else if (input.is('%')) {
- moveToMatchingParanthesis();
- finishMovement();
} else if ((!isVisualMode() && input.is('a')) || (isVisualMode() && input.is('A'))) {
- leaveVisualMode();
- setUndoPosition();
+ if (isVisualBlockMode())
+ initVisualBlockInsertMode(QLatin1Char('A'));
+ else
+ setDotCommand(_("%1a"), count());
+ if (!atEndOfLine() && !atEmptyLine())
+ moveRight();
breakEditBlock();
enterInsertMode();
- m_lastInsertion.clear();
- if (!atEndOfLine())
- moveRight();
- updateMiniBuffer();
- } else if (input.is('A')) {
setUndoPosition();
+ } else if (input.is('A')) {
breakEditBlock();
moveBehindEndOfLine();
+ setUndoPosition();
setAnchor();
enterInsertMode();
- setDotCommand(QString(QLatin1Char('A')));
- m_lastInsertion.clear();
- updateMiniBuffer();
- } else if (input.isControl('a')) {
- changeNumberTextObject(true);
- } else if (input.is('b') || input.isShift(Key_Left)) {
- m_movetype = MoveExclusive;
- moveToWordBoundary(false, false);
- setTargetColumn();
- finishMovement();
- } else if (input.is('B')) {
- m_movetype = MoveExclusive;
- moveToWordBoundary(true, false);
setTargetColumn();
- finishMovement();
- } else if (input.is('c') && isNoVisualMode()) {
- setUndoPosition();
- if (atEndOfLine())
- moveLeft();
+ setDotCommand(_("%1A"), count());
+ } else if (input.isControl('a')) {
+ if (changeNumberTextObject(count()))
+ setDotCommand(_("%1<c-a>"), count());
+ } else if ((input.is('c') || input.is('d')) && isNoVisualMode()) {
setAnchor();
- m_submode = ChangeSubMode;
+ m_opcount = m_mvcount;
+ m_mvcount.clear();
+ m_movetype = MoveExclusive;
+ m_submode = input.is('c') ? ChangeSubMode : DeleteSubMode;
} else if ((input.is('c') || input.is('C') || input.is('s') || input.is('R'))
&& (isVisualCharMode() || isVisualLineMode())) {
+ setDotCommand(visualDotCommand() + input.asChar());
if ((input.is('c')|| input.is('s')) && isVisualCharMode()) {
leaveVisualMode();
m_rangemode = RangeCharMode;
@@ -2458,23 +3523,13 @@ EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
finishMovement();
} else if (input.isControl('c')) {
if (isNoVisualMode())
- showBlackMessage("Type Alt-v,Alt-v to quit FakeVim mode");
+ showMessage(MessageInfo, tr("Type Alt-v,Alt-v to quit FakeVim mode"));
else
leaveVisualMode();
- } else if (input.is('d') && isNoVisualMode()) {
- if (m_rangemode == RangeLineMode) {
- int pos = position();
- moveToEndOfLine();
- setAnchor();
- setPosition(pos);
- } else {
- setAnchor();
- }
- m_opcount = m_mvcount;
- m_mvcount.clear();
- m_submode = DeleteSubMode;
} else if ((input.is('d') || input.is('x') || input.isKey(Key_Delete))
&& isVisualMode()) {
+ setUndoPosition();
+ setDotCommand(visualDotCommand() + QLatin1Char('x'));
if (isVisualCharMode()) {
leaveVisualMode();
m_submode = DeleteSubMode;
@@ -2493,17 +3548,18 @@ EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
setPosition(qMin(position(), anchor()));
}
} else if (input.is('D') && isNoVisualMode()) {
+ setUndoPosition();
if (atEndOfLine())
moveLeft();
m_submode = DeleteSubMode;
- setAnchor();
- moveDown(qMax(count() - 1, 0));
m_movetype = MoveInclusive;
- moveToEndOfLine();
+ setAnchorAndPosition(position(), lastPositionInLine(cursorLine() + count()));
setDotCommand(QString(QLatin1Char('D')));
finishMovement();
+ setTargetColumn();
} else if ((input.is('D') || input.is('X')) &&
(isVisualCharMode() || isVisualLineMode())) {
+ setDotCommand(visualDotCommand() + QLatin1Char('X'));
leaveVisualMode();
m_rangemode = RangeLineMode;
m_submode = NoSubMode;
@@ -2511,6 +3567,7 @@ EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
removeText(currentRange());
moveToFirstNonBlankOnLine();
} else if ((input.is('D') || input.is('X')) && isVisualBlockMode()) {
+ setDotCommand(visualDotCommand() + QLatin1Char('X'));
leaveVisualMode();
m_rangemode = RangeBlockAndTailMode;
yankText(currentRange(), m_register);
@@ -2522,187 +3579,43 @@ EventResult FakeVimHandler::Private::handleCommandMode1(const Input &input)
moveDown(linesOnScreen() / 2);
handleStartOfLine();
scrollToLine(cursorLine() - sline);
- finishMovement();
- } else if (input.is('e') || input.isShift(Key_Right)) {
- m_movetype = MoveInclusive;
- moveToWordBoundary(false, true);
- setTargetColumn();
- finishMovement("%1e", count());
- } else if (input.is('E')) {
- m_movetype = MoveInclusive;
- moveToWordBoundary(true, true);
- setTargetColumn();
- finishMovement("%1E", count());
- } else if (input.isControl('e')) {
- // FIXME: this should use the "scroll" option, and "count"
- if (cursorLineOnScreen() == 0)
- moveDown(1);
- scrollDown(1);
- finishMovement();
- } else if (input.is('f')) {
- m_subsubmode = FtSubSubMode;
- m_movetype = MoveInclusive;
- m_subsubdata = input;
- } else if (input.is('F')) {
- m_subsubmode = FtSubSubMode;
- m_movetype = MoveExclusive;
- m_subsubdata = input;
- } else if (input.is('g') && !m_gflag) {
+ } else if (!m_gflag && input.is('g')) {
m_gflag = true;
- } else if (input.is('g') || input.is('G')) {
- QString dotCommand = QString("%1G").arg(count());
- if (input.is('G') && m_mvcount.isEmpty())
- dotCommand = QString(QLatin1Char('G'));
- if (input.is('g'))
- m_gflag = false;
- int n = (input.is('g')) ? 1 : linesInDocument();
- n = m_mvcount.isEmpty() ? n : count();
- if (m_submode == NoSubMode || m_submode == ZSubMode
- || m_submode == CapitalZSubMode || m_submode == RegisterSubMode) {
- setPosition(firstPositionInLine(n));
- handleStartOfLine();
- } else {
- m_movetype = MoveLineWise;
- m_rangemode = RangeLineMode;
- setAnchor();
- setPosition(firstPositionInLine(n));
- }
- finishMovement(dotCommand);
- } else if (input.is('h') || input.isKey(Key_Left) || input.isBackspace()) {
- m_movetype = MoveExclusive;
- int n = qMin(count(), leftDist());
- if (m_fakeEnd && block().length() > 1)
- ++n;
- moveLeft(n);
- setTargetColumn();
- finishMovement("%1h", count());
- } else if (input.is('H')) {
- setCursor(EDITOR(cursorForPosition(QPoint(0, 0))));
- moveDown(qMax(count() - 1, 0));
- handleStartOfLine();
- finishMovement();
} else if (!isVisualMode() && (input.is('i') || input.isKey(Key_Insert))) {
- setDotCommand(QString(QLatin1Char('i'))); // setDotCommand("%1i", count());
- setUndoPosition();
+ setDotCommand(_("%1i"), count());
breakEditBlock();
enterInsertMode();
- updateMiniBuffer();
if (atEndOfLine())
moveLeft();
- } else {
- handled = handleCommandMode2(input);
- }
- return handled;
-}
-
-EventResult FakeVimHandler::Private::handleCommandMode2(const Input &input)
-{
- EventResult handled = EventHandled;
-
- if (input.is('I')) {
- setUndoPosition();
- setDotCommand(QString(QLatin1Char('I'))); // setDotCommand("%1I", count());
+ } else if (input.is('I')) {
if (isVisualMode()) {
- int beginLine = lineForPosition(anchor());
- int endLine = lineForPosition(position());
- m_visualInsertCount = qAbs(endLine - beginLine);
- setPosition(qMin(position(), anchor()));
+ initVisualBlockInsertMode(QLatin1Char('I'));
} else {
+ setDotCommand(_("%1I"), count());
if (m_gflag)
moveToStartOfLine();
else
moveToFirstNonBlankOnLine();
- m_gflag = false;
//m_tc.clearSelection();
}
+ setUndoPosition();
breakEditBlock();
enterInsertMode();
+ setTargetColumn();
} else if (input.isControl('i')) {
- if (!m_jumpListRedo.isEmpty()) {
- m_jumpListUndo.append(cursorPosition());
- setCursorPosition(m_jumpListRedo.last());
- m_jumpListRedo.pop_back();
- }
- } else if (input.is('j') || input.isKey(Key_Down)
- || input.isControl('j') || input.isControl('n')) {
- m_movetype = MoveLineWise;
- moveDown(count());
- finishMovement("%1j", count());
+ jump(count());
} else if (input.is('J')) {
- setDotCommand("%1J", count());
+ setUndoPosition();
+ moveBehindEndOfLine();
beginEditBlock();
- if (m_submode == NoSubMode) {
- for (int i = qMax(count(), 2) - 1; --i >= 0; ) {
- moveBehindEndOfLine();
- setAnchor();
- moveRight();
- if (m_gflag) {
- removeText(currentRange());
- } else {
- while (characterAtCursor() == ' '
- || characterAtCursor() == '\t')
- moveRight();
- removeText(currentRange());
- cursor().insertText(QString(QLatin1Char(' ')));
- }
- }
- if (!m_gflag)
- moveLeft();
- }
+ if (m_submode == NoSubMode)
+ joinLines(count(), m_gflag);
endEditBlock();
- finishMovement();
- } else if (input.is('k') || input.isKey(Key_Up) || input.isControl('p')) {
- m_movetype = MoveLineWise;
- moveUp(count());
- finishMovement("%1k", count());
- } else if (input.is('l') || input.isKey(Key_Right) || input.is(' ')) {
- m_movetype = MoveExclusive;
- bool pastEnd = count() >= rightDist() - 1;
- moveRight(qMax(0, qMin(count(), rightDist() - (m_submode == NoSubMode))));
- setTargetColumn();
- if (pastEnd && isVisualMode())
- m_visualTargetColumn = -1;
- finishMovement("%1l", count());
- } else if (input.is('L')) {
- QTextCursor tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()))));
- setCursor(tc);
- moveUp(qMax(count(), 1));
- handleStartOfLine();
- finishMovement();
+ setDotCommand(_("%1J"), count());
} else if (input.isControl('l')) {
// screen redraw. should not be needed
} else if (input.is('m')) {
- if (m_gflag) {
- moveToStartOfLine();
- moveRight(qMin(columnsOnScreen() / 2, rightDist()) - 1);
- setTargetColumn();
- finishMovement();
- } else {
- m_subsubmode = MarkSubSubMode;
- }
- } else if (input.is('M')) {
- QTextCursor tc = EDITOR(cursorForPosition(QPoint(0, EDITOR(height()) / 2)));
- setCursor(tc);
- handleStartOfLine();
- finishMovement();
- } else if (input.is('n') || input.is('N')) {
- if (hasConfig(ConfigUseCoreSearch)) {
- bool forward = (input.is('n')) ? m_lastSearchForward : !m_lastSearchForward;
- int pos = position();
- emit q->findNextRequested(!forward);
- if (forward && pos == cursor().selectionStart()) {
- // if cursor is already positioned at the start of a find result, this is returned
- emit q->findNextRequested(false);
- }
- setPosition(cursor().selectionStart());
- } else {
- SearchData sd;
- sd.needle = g.searchHistory.current();
- sd.forward = input.is('n') ? m_lastSearchForward : !m_lastSearchForward;
- sd.highlightCursor = false;
- sd.highlightMatches = true;
- search(sd);
- }
+ m_subsubmode = MarkSubSubMode;
} else if (isVisualMode() && (input.is('o') || input.is('O'))) {
int pos = position();
setAnchorAndPosition(pos, anchor());
@@ -2710,62 +3623,54 @@ EventResult FakeVimHandler::Private::handleCommandMode2(const Input &input)
setTargetColumn();
if (m_positionPastEnd)
m_visualTargetColumn = -1;
- updateSelection();
- } else if (input.is('o')) {
- setDotCommand("%1o", count());
+ } else if (input.is('o') || input.is('O')) {
+ bool insertAfter = input.is('o');
+ setDotCommand(_(insertAfter ? "%1o" : "%1O"), count());
setUndoPosition();
- breakEditBlock();
- enterInsertMode();
- beginEditBlock();
- moveToFirstNonBlankOnLine();
- moveBehindEndOfLine();
- insertText(QString("\n"));
- insertAutomaticIndentation(true);
- endEditBlock();
- } else if (input.is('O')) {
- setDotCommand("%1O", count());
- setUndoPosition();
- breakEditBlock();
enterInsertMode();
+ // Insert new line so that command can be repeated [count] times inserting new line
+ // each time without unfolding any lines.
+ QTextBlock block = cursor().block();
+ bool appendLine = false;
+ if (insertAfter) {
+ const int line = lineNumber(block);
+ appendLine = line >= document()->lineCount();
+ setPosition(appendLine ? lastPositionInLine(line) : firstPositionInLine(line + 1));
+ } else {
+ setPosition(block.position());
+ }
beginEditBlock();
- moveToFirstNonBlankOnLine();
- moveToStartOfLine();
- insertText(QString("\n"));
- moveUp();
- insertAutomaticIndentation(false);
+ insertText(QString::fromLatin1("\n"));
+ if (!appendLine)
+ moveUp();
+ insertAutomaticIndentation(insertAfter);
+ recordInsertion(QString::fromLatin1("\n"));
+ setTargetColumn();
endEditBlock();
} else if (input.isControl('o')) {
- if (!m_jumpListUndo.isEmpty()) {
- m_jumpListRedo.append(cursorPosition());
- setCursorPosition(m_jumpListUndo.last());
- m_jumpListUndo.pop_back();
- }
+ jump(-count());
} else if (input.is('p') || input.is('P')) {
pasteText(input.is('p'));
setTargetColumn();
- setDotCommand("%1p", count());
+ setDotCommand(_("%1p"), count());
finishMovement();
} else if (input.is('r')) {
- setUndoPosition();
m_submode = ReplaceSubMode;
} else if (!isVisualMode() && input.is('R')) {
setUndoPosition();
breakEditBlock();
enterReplaceMode();
- updateMiniBuffer();
} else if (input.isControl('r')) {
- redo();
+ int repeat = count();
+ while (--repeat >= 0)
+ redo();
} else if (input.is('s') && isVisualBlockMode()) {
+ m_opcount.clear();
+ m_mvcount.clear();
setUndoPosition();
- Range range(position(), anchor(), RangeBlockMode);
- int beginLine = lineForPosition(anchor());
- int endLine = lineForPosition(position());
- m_visualInsertCount = qAbs(endLine - beginLine);
- setPosition(qMin(position(), anchor()));
- yankText(range, m_register);
- removeText(range);
- setDotCommand("%1s", count());
- breakEditBlock();
+ beginEditBlock();
+ initVisualBlockInsertMode(QLatin1Char('s'));
+ endEditBlock();
enterInsertMode();
} else if (input.is('s')) {
setUndoPosition();
@@ -2774,58 +3679,46 @@ EventResult FakeVimHandler::Private::handleCommandMode2(const Input &input)
moveLeft();
setAnchor();
moveRight(qMin(count(), rightDist()));
- yankText(currentRange(), m_register);
- removeText(currentRange());
- setDotCommand("%1s", count());
- m_opcount.clear();
- m_mvcount.clear();
- breakEditBlock();
- enterInsertMode();
+ setDotCommand(_("%1s"), count());
+ m_submode = ChangeSubMode;
+ m_movetype = MoveExclusive;
+ finishMovement();
} else if (input.is('S')) {
+ m_movetype = MoveLineWise;
setUndoPosition();
- beginEditBlock();
if (!isVisualMode()) {
const int line = cursorLine() + 1;
const int anc = firstPositionInLine(line);
const int pos = lastPositionInLine(line + count() - 1);
setAnchorAndPosition(anc, pos);
}
- setDotCommand("%1S", count());
- breakEditBlock();
- enterInsertMode();
+ setDotCommand(_("%1S"), count());
m_submode = ChangeSubMode;
- m_movetype = MoveLineWise;
- endEditBlock();
finishMovement();
} else if (m_gflag && input.is('t')) {
- m_gflag = false;
- handleExCommand("tabnext");
- } else if (input.is('t')) {
- m_movetype = MoveInclusive;
- m_subsubmode = FtSubSubMode;
- m_subsubdata = input;
+ handleExCommand(_("tabnext"));
} else if (m_gflag && input.is('T')) {
- m_gflag = false;
- handleExCommand("tabprev");
- } else if (input.is('T')) {
- m_movetype = MoveExclusive;
- m_subsubmode = FtSubSubMode;
- m_subsubdata = input;
+ handleExCommand(_("tabprev"));
} else if (input.isControl('t')) {
- handleExCommand("pop");
- } else if (!m_gflag && input.is('u')) {
- undo();
+ handleExCommand(_("pop"));
+ } else if (!m_gflag && input.is('u') && !isVisualMode()) {
+ int repeat = count();
+ while (--repeat >= 0)
+ undo();
} else if (input.isControl('u')) {
int sline = cursorLineOnScreen();
// FIXME: this should use the "scroll" option, and "count"
moveUp(linesOnScreen() / 2);
handleStartOfLine();
scrollToLine(cursorLine() - sline);
- finishMovement();
} else if (m_gflag && input.is('v')) {
- if (m_lastSelectionCursor.hasSelection()) {
- toggleVisualMode(m_lastSelectionMode);
- setCursor(m_lastSelectionCursor);
+ if (m_lastVisualMode != NoVisualMode) {
+ CursorPosition from = mark(QLatin1Char('<')).position;
+ CursorPosition to = mark(QLatin1Char('>')).position;
+ toggleVisualMode(m_lastVisualMode);
+ setCursorPosition(m_lastVisualModeInverted ? to : from);
+ setAnchor();
+ setCursorPosition(m_lastVisualModeInverted ? from : to);
}
} else if (input.is('v')) {
toggleVisualMode(VisualCharMode);
@@ -2833,40 +3726,18 @@ EventResult FakeVimHandler::Private::handleCommandMode2(const Input &input)
toggleVisualMode(VisualLineMode);
} else if (input.isControl('v')) {
toggleVisualMode(VisualBlockMode);
- } else if (input.is('w')) { // tested
- // Special case: "cw" and "cW" work the same as "ce" and "cE" if the
- // cursor is on a non-blank - except if the cursor is on the last
- // character of a word: only the current word will be changed
- if (m_submode == ChangeSubMode) {
- moveToWordBoundary(false, true, true);
- setTargetColumn();
- m_movetype = MoveInclusive;
- } else {
- moveToNextWord(false, m_submode == DeleteSubMode);
- m_movetype = MoveExclusive;
- }
- finishMovement("%1w", count());
- } else if (input.is('W')) {
- if (m_submode == ChangeSubMode) {
- moveToWordBoundary(true, true, true);
- setTargetColumn();
- m_movetype = MoveInclusive;
- } else {
- moveToNextWord(true, m_submode == DeleteSubMode);
- m_movetype = MoveExclusive;
- }
- finishMovement("%1W", count());
} else if (input.isControl('w')) {
m_submode = WindowSubMode;
- } else if (input.is('x') && isNoVisualMode()) { // = "dl"
+ } else if (input.is('x') && isNoVisualMode()) { // = _("dl")
m_movetype = MoveExclusive;
m_submode = DeleteSubMode;
const int n = qMin(count(), rightDist());
setAnchorAndPosition(position(), position() + n);
- setDotCommand("%1x", count());
+ setDotCommand(_("%1x"), count());
finishMovement();
} else if (input.isControl('x')) {
- changeNumberTextObject(false);
+ if (changeNumberTextObject(-count()))
+ setDotCommand(_("%1<c-x>"), count());
} else if (input.is('X')) {
if (leftDist() > 0) {
setAnchor();
@@ -2874,151 +3745,327 @@ EventResult FakeVimHandler::Private::handleCommandMode2(const Input &input)
yankText(currentRange(), m_register);
removeText(currentRange());
}
- finishMovement();
- } else if ((m_submode == YankSubMode && input.is('y'))
- || (input.is('Y') && isNoVisualMode())) {
- setAnchor();
- if (count() > 1)
- moveDown(count()-1);
- m_rangemode = RangeLineMode;
- m_movetype = MoveLineWise;
- m_submode = YankSubMode;
- finishMovement();
+ } else if (input.is('Y') && isNoVisualMode()) {
+ handleYankSubMode(Input(QLatin1Char('y')));
} else if (input.isControl('y')) {
// FIXME: this should use the "scroll" option, and "count"
if (cursorLineOnScreen() == linesOnScreen() - 1)
moveUp(1);
scrollUp(1);
- finishMovement();
} else if (input.is('y') && isNoVisualMode()) {
setAnchor();
+ m_movetype = MoveExclusive;
m_submode = YankSubMode;
} else if (input.is('y') && isVisualCharMode()) {
- Range range(position(), anchor(), RangeCharMode);
- range.endPos++; // MoveInclusive
- yankText(range, m_register);
- setPosition(qMin(position(), anchor()));
- leaveVisualMode();
+ m_rangemode = RangeCharMode;
+ m_movetype = MoveInclusive;
+ m_submode = YankSubMode;
finishMovement();
} else if ((input.is('y') && isVisualLineMode())
|| (input.is('Y') && isVisualLineMode())
|| (input.is('Y') && isVisualCharMode())) {
m_rangemode = RangeLineMode;
- yankText(currentRange(), m_register);
- setPosition(qMin(position(), anchor()));
- moveToStartOfLine();
- leaveVisualMode();
+ m_movetype = MoveLineWise;
+ m_submode = YankSubMode;
finishMovement();
} else if ((input.is('y') || input.is('Y')) && isVisualBlockMode()) {
m_rangemode = RangeBlockMode;
- yankText(currentRange(), m_register);
- setPosition(qMin(position(), anchor()));
- leaveVisualMode();
+ m_movetype = MoveInclusive;
+ m_submode = YankSubMode;
finishMovement();
} else if (input.is('z')) {
m_submode = ZSubMode;
} else if (input.is('Z')) {
m_submode = CapitalZSubMode;
- } else if (!m_gflag && input.is('~') && !isVisualMode()) {
+ } else if ((input.is('~') || input.is('u') || input.is('U'))) {
m_movetype = MoveExclusive;
- if (!atEndOfLine()) {
- beginEditBlock();
+ if (isVisualMode()) {
+ if (isVisualLineMode())
+ m_rangemode = RangeLineMode;
+ else if (isVisualBlockMode())
+ m_rangemode = RangeBlockMode;
+ leaveVisualMode();
+ if (input.is('~'))
+ m_submode = InvertCaseSubMode;
+ else if (input.is('u'))
+ m_submode = DownCaseSubMode;
+ else if (input.is('U'))
+ m_submode = UpCaseSubMode;
+ finishMovement();
+ } else if (m_gflag) {
+ setUndoPosition();
+ if (atEndOfLine())
+ moveLeft();
setAnchor();
- moveRight(qMin(count(), rightDist()));
- if (input.is('~')) {
- invertCase(currentRange());
- setDotCommand("%1~", count());
- } else if (input.is('u')) {
- downCase(currentRange());
- setDotCommand("%1gu", count());
- } else if (input.is('U')) {
- upCase(currentRange());
- setDotCommand("%1gU", count());
+ if (input.is('~'))
+ m_submode = InvertCaseSubMode;
+ else if (input.is('u'))
+ m_submode = DownCaseSubMode;
+ else if (input.is('U'))
+ m_submode = UpCaseSubMode;
+ } else {
+ if (!atEndOfLine()) {
+ beginEditBlock();
+ setAnchor();
+ moveRight(qMin(count(), rightDist()));
+ if (input.is('~'))
+ invertCase(currentRange());
+ else if (input.is('u'))
+ downCase(currentRange());
+ else if (input.is('U'))
+ upCase(currentRange());
+ setDotCommand(QString::fromLatin1("%1%2").arg(count()).arg(input.raw()));
+ endEditBlock();
}
- endEditBlock();
}
- finishMovement();
- } else if ((m_gflag && input.is('~') && !isVisualMode())
- || (m_gflag && input.is('u') && !isVisualMode())
- || (m_gflag && input.is('U') && !isVisualMode())) {
- m_gflag = false;
- m_movetype = MoveExclusive;
+ } else if (input.isKey(Key_Delete)) {
+ setAnchor();
+ moveRight(qMin(1, rightDist()));
+ removeText(currentRange());
if (atEndOfLine())
moveLeft();
- setAnchor();
- m_submode = TransformSubMode;
- if (input.is('~'))
- m_subsubmode = InvertCaseSubSubMode;
- if (input.is('u'))
- m_subsubmode = DownCaseSubSubMode;
- else if (input.is('U'))
- m_subsubmode = UpCaseSubSubMode;
- } else if ((input.is('~') && isVisualMode())
- || (m_gflag && input.is('u') && isVisualMode())
- || (m_gflag && input.is('U') && isVisualMode())) {
- m_gflag = false;
- m_movetype = MoveExclusive;
+ } else if (input.isControl(Key_BracketRight)) {
+ handleExCommand(_("tag"));
+ } else if (handleMovement(input)) {
+ // movement handled
+ } else {
+ handled = false;
+ }
+
+ return handled;
+}
+
+bool FakeVimHandler::Private::handleChangeDeleteSubModes(const Input &input)
+{
+ bool handled = false;
+
+ if ((m_submode == ChangeSubMode && input.is('c'))
+ || (m_submode == DeleteSubMode && input.is('d'))) {
+ m_movetype = MoveLineWise;
+ setUndoPosition();
+ const int line = cursorLine() + 1;
+ const int anc = firstPositionInLine(line);
+ const int pos = lastPositionInLine(line + count() - 1);
+ setAnchorAndPosition(anc, pos);
+ if (m_submode == ChangeSubMode)
+ setDotCommand(_("%1cc"), count());
+ else
+ setDotCommand(_("%1dd"), count());
+ finishMovement();
+ m_submode = NoSubMode;
+ handled = true;
+ } else {
+ handled = handleMovement(input);
+ }
+
+ return handled;
+}
+
+bool FakeVimHandler::Private::handleReplaceSubMode(const Input &input)
+{
+ bool handled = true;
+
+ setDotCommand(visualDotCommand() + QLatin1Char('r') + input.asChar());
+ if (isVisualMode()) {
+ setUndoPosition();
if (isVisualLineMode())
m_rangemode = RangeLineMode;
else if (isVisualBlockMode())
m_rangemode = RangeBlockMode;
+ else
+ m_rangemode = RangeCharMode;
leaveVisualMode();
- m_submode = TransformSubMode;
- if (input.is('~'))
- m_subsubmode = InvertCaseSubSubMode;
- else if (input.is('u'))
- m_subsubmode = DownCaseSubSubMode;
- else if (input.is('U'))
- m_subsubmode = UpCaseSubSubMode;
- finishMovement();
- } else if (input.is('[')) {
- m_submode = OpenSquareSubMode;
- } else if (input.is(']')) {
- m_submode = CloseSquareSubMode;
- } else if (input.isKey(Key_PageDown) || input.isControl('f')) {
- moveDown(count() * (linesOnScreen() - 2) - cursorLineOnScreen());
- scrollToLine(cursorLine());
- handleStartOfLine();
- finishMovement();
- } else if (input.isKey(Key_PageUp) || input.isControl('b')) {
- moveUp(count() * (linesOnScreen() - 2) + cursorLineOnScreen());
- scrollToLine(cursorLine() + linesOnScreen() - 2);
- handleStartOfLine();
- finishMovement();
- } else if (input.isKey(Key_Delete)) {
+ Range range = currentRange();
+ if (m_rangemode == RangeCharMode)
+ ++range.endPos;
+ Transformation tr =
+ &FakeVimHandler::Private::replaceByCharTransform;
+ transformText(range, tr, input.asChar());
+ } else if (count() <= rightDist()) {
+ setUndoPosition();
setAnchor();
- moveRight(qMin(1, rightDist()));
- removeText(currentRange());
- if (atEndOfLine())
- moveLeft();
- } else if (input.isKey(Key_BracketLeft) || input.isKey(Key_BracketRight)) {
+ moveRight(count());
+ Range range = currentRange();
+ if (input.isReturn()) {
+ beginEditBlock();
+ replaceText(range, QString());
+ insertText(QString::fromLatin1("\n"));
+ endEditBlock();
+ } else {
+ replaceText(range, QString(count(), input.asChar()));
+ moveRight(count() - 1);
+ }
+ setTargetColumn();
+ setDotCommand(_("%1r") + input.text(), count());
+ } else {
+ handled = false;
+ }
+ m_submode = NoSubMode;
+ finishMovement();
- } else if (input.isControl(Key_BracketRight)) {
- handleExCommand("tag");
+ return handled;
+}
+
+bool FakeVimHandler::Private::handleFilterSubMode(const Input &input)
+{
+ return handleMovement(input);
+}
+
+bool FakeVimHandler::Private::handleRegisterSubMode(const Input &input)
+{
+ bool handled = false;
+
+ QChar reg = input.asChar();
+ if (QString::fromLatin1("*+.%#:-\"").contains(reg) || reg.isLetterOrNumber()) {
+ m_register = reg.unicode();
+ m_rangemode = RangeLineMode;
+ handled = true;
+ }
+ m_submode = NoSubMode;
+
+ return handled;
+}
+
+bool FakeVimHandler::Private::handleShiftSubMode(const Input &input)
+{
+ bool handled = false;
+ if ((m_submode == ShiftLeftSubMode && input.is('<'))
+ || (m_submode == ShiftRightSubMode && input.is('>'))
+ || (m_submode == IndentSubMode && input.is('='))) {
+ m_movetype = MoveLineWise;
+ setUndoPosition();
+ moveDown(count() - 1);
+ setDotCommand(QString::fromLatin1("%2%1%1").arg(input.asChar()), count());
+ finishMovement();
+ handled = true;
+ m_submode = NoSubMode;
} else {
- //qDebug() << "IGNORED IN COMMAND MODE: " << key << text
- // << " VISUAL: " << m_visualMode;
+ handled = handleMovement(input);
+ }
+ return handled;
+}
- // if a key which produces text was pressed, don't mark it as unhandled
- // - otherwise the text would be inserted while being in command mode
- if (input.text().isEmpty()) {
- handled = EventUnhandled;
+bool FakeVimHandler::Private::handleChangeCaseSubMode(const Input &input)
+{
+ bool handled = false;
+ if ((m_submode == InvertCaseSubMode && input.is('~'))
+ || (m_submode == DownCaseSubMode && input.is('u'))
+ || (m_submode == UpCaseSubMode && input.is('U'))) {
+ if (!isFirstNonBlankOnLine(position())) {
+ moveToStartOfLine();
+ moveToFirstNonBlankOnLine();
}
+ setTargetColumn();
+ setUndoPosition();
+ setAnchor();
+ setPosition(lastPositionInLine(cursorLine() + count()) + 1);
+ finishMovement(QString::fromLatin1("%1%2").arg(count()).arg(input.raw()));
+ handled = true;
+ m_submode = NoSubMode;
+ } else {
+ handled = handleMovement(input);
}
+ return handled;
+}
- m_positionPastEnd = (m_visualTargetColumn == -1) && isVisualMode();
+bool FakeVimHandler::Private::handleWindowSubMode(const Input &input)
+{
+ emit q->windowCommandRequested(input.key());
+ m_submode = NoSubMode;
+ return EventHandled;
+}
+
+bool FakeVimHandler::Private::handleYankSubMode(const Input &input)
+{
+ bool handled = false;
+ if (input.is('y')) {
+ m_movetype = MoveLineWise;
+ int endPos = firstPositionInLine(lineForPosition(position()) + count() - 1);
+ Range range(position(), endPos, RangeLineMode);
+ yankText(range);
+ m_submode = NoSubMode;
+ handled = true;
+ } else {
+ handled = handleMovement(input);
+ }
+ return handled;
+}
+
+bool FakeVimHandler::Private::handleZSubMode(const Input &input)
+{
+ bool handled = true;
+ bool foldMaybeClosed = false;
+ if (input.isReturn() || input.is('t')
+ || input.is('-') || input.is('b')
+ || input.is('.') || input.is('z')) {
+ // Cursor line to top/center/bottom of window.
+ Qt::AlignmentFlag align;
+ if (input.isReturn() || input.is('t'))
+ align = Qt::AlignTop;
+ else if (input.is('.') || input.is('z'))
+ align = Qt::AlignBottom;
+ else
+ align = Qt::AlignVCenter;
+ const bool moveToNonBlank = (input.is('.') || input.isReturn() || input.is('-'));
+ const int line = m_mvcount.isEmpty() ? -1 : firstPositionInLine(count());
+ alignViewportToCursor(align, line, moveToNonBlank);
+ } else if (input.is('o') || input.is('c')) {
+ // Open/close current fold.
+ foldMaybeClosed = input.is('c');
+ emit q->fold(count(), foldMaybeClosed);
+ } else if (input.is('O') || input.is('C')) {
+ // Recursively open/close current fold.
+ foldMaybeClosed = input.is('C');
+ emit q->fold(-1, foldMaybeClosed);
+ } else if (input.is('a') || input.is('A')) {
+ // Toggle current fold.
+ foldMaybeClosed = true;
+ emit q->foldToggle(input.is('a') ? count() : -1);
+ } else if (input.is('R') || input.is('M')) {
+ // Open/close all folds in document.
+ foldMaybeClosed = input.is('M');
+ emit q->foldAll(foldMaybeClosed);
+ } else if (input.is('j') || input.is('k')) {
+ emit q->foldGoTo(input.is('j') ? count() : -count(), false);
+ } else {
+ handled = false;
+ }
+ if (foldMaybeClosed)
+ ensureCursorVisible();
+ m_submode = NoSubMode;
+ return handled;
+}
+bool FakeVimHandler::Private::handleCapitalZSubMode(const Input &input)
+{
+ // Recognize ZZ and ZQ as aliases for ":x" and ":q!".
+ bool handled = true;
+ if (input.is('Z'))
+ handleExCommand(QString(QLatin1Char('x')));
+ else if (input.is('Q'))
+ handleExCommand(_("q!"));
+ else
+ handled = false;
+ m_submode = NoSubMode;
return handled;
}
EventResult FakeVimHandler::Private::handleReplaceMode(const Input &input)
{
+ bool clearLastInsertion = m_breakEditBlock;
+ if (m_oldPosition != position()) {
+ if (clearLastInsertion) {
+ clearLastInsertion = false;
+ m_lastInsertion = _("<INSERT>");
+ }
+ recordInsertion();
+ }
+
if (input.isEscape()) {
moveLeft(qMin(1, leftDist()));
- setTargetColumn();
- m_submode = NoSubMode;
- m_mode = CommandMode;
- finishMovement();
+ enterCommandMode();
+ g.dotCommand += m_lastInsertion;
+ g.dotCommand += QChar(27);
} else if (input.isKey(Key_Left)) {
breakEditBlock();
moveLeft(1);
@@ -3030,130 +4077,156 @@ EventResult FakeVimHandler::Private::handleReplaceMode(const Input &input)
} else if (input.isKey(Key_Up)) {
breakEditBlock();
moveUp(1);
- setTargetColumn();
} else if (input.isKey(Key_Down)) {
breakEditBlock();
moveDown(1);
+ } else if (input.isKey(Key_Insert)) {
+ m_mode = InsertMode;
+ recordInsertion(_("<INSERT>"));
+ } else if (input.isControl('o')) {
+ enterCommandMode(ReplaceMode);
} else {
+ if (clearLastInsertion)
+ m_lastInsertion = _("<INSERT>");
joinPreviousEditBlock();
if (!atEndOfLine()) {
setAnchor();
moveRight();
- m_lastDeletion += selectText(Range(position(), anchor()));
removeText(currentRange());
}
const QString text = input.text();
- m_lastInsertion += text;
setAnchor();
insertText(text);
endEditBlock();
- setTargetColumn();
+ recordInsertion();
}
+ m_oldPosition = position();
+ updateMiniBuffer();
+
return EventHandled;
}
EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
{
- //const int key = input.key;
- //const QString &text = input.text;
+ bool clearLastInsertion = m_breakEditBlock;
+ if (m_oldPosition != position()) {
+ if (clearLastInsertion) {
+ clearLastInsertion = false;
+ m_lastInsertion.clear();
+ }
+ recordInsertion();
+ }
+ QString insert;
+ bool move = false;
if (input.isEscape()) {
- if (isVisualBlockMode() && !m_lastInsertion.contains('\n')) {
- leaveVisualMode();
- joinPreviousEditBlock();
- moveLeft(m_lastInsertion.size());
- setAnchor();
- int pos = position();
- setTargetColumn();
- for (int i = 0; i < m_visualInsertCount; ++i) {
- moveDown();
- insertText(m_lastInsertion);
+ // Repeat insertion [count] times.
+ // One instance was already physically inserted while typing.
+ const QString text = m_lastInsertion;
+ const int repeat = count();
+ m_lastInsertion.clear();
+ joinPreviousEditBlock();
+ replay(text.repeated(repeat - 1));
+
+ if (m_visualBlockInsert && !text.contains(QLatin1Char('\n'))) {
+ const CursorPosition lastAnchor = mark(QLatin1Char('<')).position;
+ const CursorPosition lastPosition = mark(QLatin1Char('>')).position;
+ CursorPosition startPos(lastAnchor.line, qMin(lastPosition.column, lastAnchor.column));
+ CursorPosition pos = startPos;
+ if (g.dotCommand.endsWith(QLatin1Char('A')))
+ pos.column = qMax(lastPosition.column, lastAnchor.column) + 1;
+ while (pos.line < lastPosition.line) {
+ ++pos.line;
+ QTextCursor tc = cursor();
+ setCursorPosition(&tc, pos);
+ if (pos.line != tc.blockNumber())
+ break;
+ setCursor(tc);
+ if (tc.positionInBlock() == pos.column)
+ replay(text.repeated(repeat));
}
- moveLeft(1);
- Range range(pos, position(), RangeBlockMode);
- yankText(range);
- setPosition(pos);
- setDotCommand("p");
- endEditBlock();
+
+ setCursorPosition(startPos);
} else {
- // Normal insertion. Start with '1', as one instance was
- // already physically inserted while typing.
- QString data;
- for (int i = 1; i < count(); ++i)
- data += m_lastInsertion;
- insertText(data);
moveLeft(qMin(1, leftDist()));
- setTargetColumn();
- leaveVisualMode();
- breakEditBlock();
+ leaveVisualMode(); // TODO: Remove! Should not be requiered here!
}
- g.dotCommand += m_lastInsertion;
- g.dotCommand += QChar(27);
+
+ endEditBlock();
+ breakEditBlock();
+
+ m_lastInsertion = text;
+ // If command is 'o' or 'O' don't include the first line feed in dot command.
+ if (g.dotCommand.endsWith(QLatin1Char('o'), Qt::CaseInsensitive))
+ m_lastInsertion.remove(0, 1);
+ g.dotCommand += m_lastInsertion + _("<ESC>");
enterCommandMode();
- m_submode = NoSubMode;
m_ctrlVActive = false;
- m_opcount.clear();
- m_mvcount.clear();
+ m_visualBlockInsert = false;
} else if (m_ctrlVActive) {
insertInInsertMode(input.raw());
+ } else if (input.isControl('o')) {
+ enterCommandMode(InsertMode);
} else if (input.isControl('v')) {
m_ctrlVActive = true;
+ insert = _("<C-V>");
} else if (input.isControl('w')) {
- int endPos = position();
- moveToWordBoundary(false, false, false);
- setTargetColumn();
- int beginPos = position();
+ const int blockNumber = cursor().blockNumber();
+ const int endPos = position();
+ moveToNextWordStart(count(), false, false);
+ if (blockNumber != cursor().blockNumber())
+ moveToEndOfLine();
+ const int beginPos = position();
Range range(beginPos, endPos, RangeCharMode);
removeText(range);
+ insert = _("<C-W>");
} else if (input.isKey(Key_Insert)) {
- if (m_mode == ReplaceMode)
- m_mode = InsertMode;
- else
- m_mode = ReplaceMode;
+ m_mode = ReplaceMode;
+ insert = _("<INSERT>");
} else if (input.isKey(Key_Left)) {
moveLeft(count());
+ move = true;
setTargetColumn();
- m_lastInsertion.clear();
} else if (input.isControl(Key_Left)) {
- moveToWordBoundary(false, false);
+ moveToNextWordStart(count(), false, false);
+ move = true;
setTargetColumn();
- m_lastInsertion.clear();
} else if (input.isKey(Key_Down)) {
//removeAutomaticIndentation();
m_submode = NoSubMode;
moveDown(count());
- m_lastInsertion.clear();
+ move = true;
} else if (input.isKey(Key_Up)) {
//removeAutomaticIndentation();
m_submode = NoSubMode;
moveUp(count());
- m_lastInsertion.clear();
+ move = true;
} else if (input.isKey(Key_Right)) {
moveRight(count());
+ move = true;
setTargetColumn();
- m_lastInsertion.clear();
} else if (input.isControl(Key_Right)) {
- moveToWordBoundary(false, true);
+ moveToNextWordStart(count(), false, true);
moveRight(); // we need one more move since we are in insert mode
+ move = true;
setTargetColumn();
- m_lastInsertion.clear();
} else if (input.isKey(Key_Home)) {
moveToStartOfLine();
+ move = true;
setTargetColumn();
- m_lastInsertion.clear();
} else if (input.isKey(Key_End)) {
if (count() > 1)
moveDown(count() - 1);
moveBehindEndOfLine();
+ move = true;
setTargetColumn();
- m_lastInsertion.clear();
- } else if (input.isReturn()) {
+ m_targetColumn = -1;
+ } else if (input.isReturn() || input.isControl('j') || input.isControl('m')) {
joinPreviousEditBlock();
m_submode = NoSubMode;
- insertText(QString("\n"));
- m_lastInsertion += '\n';
+ insertText(QString::fromLatin1("\n"));
+ insert = _("\n");
insertAutomaticIndentation(true);
- setTargetColumn();
endEditBlock();
} else if (input.isBackspace()) {
joinPreviousEditBlock();
@@ -3173,39 +4246,38 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
setLineContents(line, prefix + data.mid(col.physical));
moveToStartOfLine();
moveRight(prefix.size());
- m_lastInsertion.clear(); // FIXME
} else {
setAnchor();
cursor().deletePreviousChar();
- m_lastInsertion.chop(1);
}
- setTargetColumn();
}
+ insert = _("<BS>");
endEditBlock();
} else if (input.isKey(Key_Delete)) {
- setAnchor();
+ joinPreviousEditBlock();
cursor().deleteChar();
- m_lastInsertion.clear();
+ insert = _("<DELETE>");
+ endEditBlock();
} else if (input.isKey(Key_PageDown) || input.isControl('f')) {
removeAutomaticIndentation();
moveDown(count() * (linesOnScreen() - 2));
- m_lastInsertion.clear();
+ move = true;
} else if (input.isKey(Key_PageUp) || input.isControl('b')) {
removeAutomaticIndentation();
moveUp(count() * (linesOnScreen() - 2));
- m_lastInsertion.clear();
+ move = true;
} else if (input.isKey(Key_Tab)) {
m_justAutoIndented = 0;
if (hasConfig(ConfigExpandTab)) {
const int ts = config(ConfigTabStop).toInt();
const int col = logicalCursorColumn();
- QString str = QString(ts - col % ts, ' ');
+ QString str = QString(ts - col % ts, QLatin1Char(' '));
m_lastInsertion.append(str);
insertText(str);
- setTargetColumn();
} else {
insertInInsertMode(input.raw());
}
+ insert = _("\t");
} else if (input.isControl('d')) {
// remove one level of indentation from the current line
int shift = config(ConfigShiftWidth).toInt();
@@ -3216,29 +4288,46 @@ EventResult FakeVimHandler::Private::handleInsertMode(const Input &input)
int amount = 0;
int i = 0;
for (; i < text.size() && amount < shift; ++i) {
- if (text.at(i) == ' ')
+ if (text.at(i) == QLatin1Char(' '))
++amount;
- else if (text.at(i) == '\t')
+ else if (text.at(i) == QLatin1Char('\t'))
amount += tab; // FIXME: take position into consideration
else
break;
}
removeText(Range(pos, pos+i));
+ insert = _("<C-D>");
//} else if (key >= control('a') && key <= control('z')) {
// // ignore these
} else if (input.isControl('p') || input.isControl('n')) {
- QTextCursor tc = EDITOR(textCursor());
- moveToWordBoundary(false, false);
+ QTextCursor tc = cursor();
+ moveToNextWordStart(count(), false, false);
QString str = selectText(Range(position(), tc.position()));
setCursor(tc);
emit q->simpleCompletionRequested(str, input.isControl('n'));
+ if (input.isControl('p'))
+ insert = _("<C-P>");
+ else
+ insert = _("<C-N>");
} else if (!input.text().isEmpty()) {
- insertInInsertMode(input.text());
+ insert = input.text();
+ insertInInsertMode(insert);
+ insert.replace(_("<"), _("<LT>"));
} else {
// We don't want fancy stuff in insert mode.
return EventHandled;
}
+
+ if (move) {
+ breakEditBlock();
+ m_oldPosition = position();
+ } else {
+ if (clearLastInsertion)
+ m_lastInsertion.clear();
+ recordInsertion(insert);
+ }
updateMiniBuffer();
+
return EventHandled;
}
@@ -3246,7 +4335,6 @@ void FakeVimHandler::Private::insertInInsertMode(const QString &text)
{
joinPreviousEditBlock();
m_justAutoIndented = 0;
- m_lastInsertion.append(text);
insertText(text);
if (hasConfig(ConfigSmartIndent) && isElectricCharacter(text.at(0))) {
const QString leftText = block().text()
@@ -3264,201 +4352,175 @@ void FakeVimHandler::Private::insertInInsertMode(const QString &text)
EventResult FakeVimHandler::Private::handleExMode(const Input &input)
{
if (input.isEscape()) {
- m_commandBuffer.clear();
- enterCommandMode();
- updateMiniBuffer();
+ g.commandBuffer.clear();
+ enterCommandMode(g.returnToMode);
+ resetCommandMode();
m_ctrlVActive = false;
} else if (m_ctrlVActive) {
- m_commandBuffer.insertChar(input.raw());
+ g.commandBuffer.insertChar(input.raw());
m_ctrlVActive = false;
} else if (input.isControl('v')) {
m_ctrlVActive = true;
+ return EventHandled;
} else if (input.isBackspace()) {
- if (m_commandBuffer.isEmpty()) {
- m_commandPrefix.clear();
- enterCommandMode();
+ if (g.commandBuffer.isEmpty()) {
+ enterCommandMode(g.returnToMode);
+ resetCommandMode();
+ } else if (g.commandBuffer.hasSelection()) {
+ g.commandBuffer.deleteSelected();
} else {
- m_commandBuffer.deleteChar();
+ g.commandBuffer.deleteChar();
}
- updateMiniBuffer();
} else if (input.isKey(Key_Tab)) {
- QStringList completions;
- foreach (const QString &entry, g.commandHistory.items()) {
- if (entry.startsWith(m_commandBuffer.contents()))
- completions.append(entry);
- }
- qDebug() << completions;
- } else if (input.isKey(Key_Left)) {
- m_commandBuffer.moveLeft();
- updateMiniBuffer();
+ // FIXME: Complete actual commands.
+ g.commandBuffer.historyUp();
} else if (input.isReturn()) {
- if (!m_commandBuffer.isEmpty()) {
- //g.commandHistory.takeLast();
- g.commandHistory.append(m_commandBuffer.contents());
- handleExCommand(m_commandBuffer.contents());
- if (m_textedit || m_plaintextedit)
- leaveVisualMode();
- }
- updateMiniBuffer();
- } else if (input.isKey(Key_Up) || input.isKey(Key_PageUp)) {
- g.commandHistory.up();
- m_commandBuffer.setContents(g.commandHistory.current());
- updateMiniBuffer();
- } else if (input.isKey(Key_Down) || input.isKey(Key_PageDown)) {
- g.commandHistory.down();
- m_commandBuffer.setContents(g.commandHistory.current());
- updateMiniBuffer();
- } else if (m_commandBuffer.handleInput(input)) {
- updateMiniBuffer();
- } else {
+ showMessage(MessageCommand, g.commandBuffer.display());
+ handleExCommand(g.commandBuffer.contents());
+ g.commandBuffer.clear();
+ if (m_textedit || m_plaintextedit)
+ leaveVisualMode();
+ } else if (!g.commandBuffer.handleInput(input)) {
qDebug() << "IGNORED IN EX-MODE: " << input.key() << input.text();
return EventUnhandled;
}
+ updateMiniBuffer();
return EventHandled;
}
EventResult FakeVimHandler::Private::handleSearchSubSubMode(const Input &input)
{
+ EventResult handled = EventHandled;
+
if (input.isEscape()) {
- m_commandBuffer.clear();
- g.searchHistory.append(m_searchCursor.selectedText());
- m_searchCursor = QTextCursor();
- updateSelection();
- enterCommandMode();
- updateMiniBuffer();
+ g.currentMessage.clear();
+ g.searchBuffer.clear();
+ setAnchorAndPosition(m_searchStartPosition, m_searchStartPosition);
+ scrollToLine(m_searchFromScreenLine);
+ enterCommandMode(g.returnToMode);
+ resetCommandMode();
} else if (input.isBackspace()) {
- if (m_commandBuffer.isEmpty()) {
- m_commandPrefix.clear();
- m_searchCursor = QTextCursor();
- enterCommandMode();
- } else {
- m_commandBuffer.deleteChar();
- }
- updateMiniBuffer();
- } else if (input.isKey(Key_Left)) {
- m_commandBuffer.moveLeft();
- updateMiniBuffer();
- } else if (input.isKey(Key_Right)) {
- m_commandBuffer.moveRight();
- updateMiniBuffer();
+ if (g.searchBuffer.isEmpty())
+ resetCommandMode();
+ else
+ g.searchBuffer.deleteChar();
} else if (input.isReturn()) {
- m_searchCursor = QTextCursor();
- QString needle = m_commandBuffer.contents();
- if (!needle.isEmpty()) {
- g.searchHistory.append(needle);
- if (!hasConfig(ConfigIncSearch)) {
- SearchData sd;
- sd.needle = needle;
- sd.forward = m_lastSearchForward;
- sd.highlightCursor = false;
- sd.highlightMatches = true;
- search(sd);
- }
- finishMovement(m_commandPrefix + needle + '\n');
+ const QString &needle = g.searchBuffer.contents();
+ if (!needle.isEmpty())
+ g.lastSearch = needle;
+ else
+ g.searchBuffer.setContents(g.lastSearch);
+ if (!g.lastSearch.isEmpty()) {
+ updateFind(true);
+ finishMovement(g.searchBuffer.prompt() + g.lastSearch + QLatin1Char('\n'));
+ } else {
+ finishMovement();
}
- enterCommandMode();
- highlightMatches(needle);
- updateMiniBuffer();
- } else if (input.isKey(Key_Up) || input.isKey(Key_PageUp)) {
- // FIXME: This and the three cases below are wrong as vim
- // takes only matching entries in the history into account.
- g.searchHistory.up();
- showBlackMessage(g.searchHistory.current());
- } else if (input.isKey(Key_Down) || input.isKey(Key_PageDown)) {
- g.searchHistory.down();
- showBlackMessage(g.searchHistory.current());
+ if (g.currentMessage.isEmpty())
+ showMessage(MessageCommand, g.searchBuffer.display());
+ else
+ handled = EventCancelled;
+ enterCommandMode(g.returnToMode);
+ resetCommandMode();
+ g.searchBuffer.clear();
} else if (input.isKey(Key_Tab)) {
- m_commandBuffer.insertChar(QChar(9));
- updateMiniBuffer();
- } else if (m_commandBuffer.handleInput(input)) {
- updateMiniBuffer();
+ g.searchBuffer.insertChar(QChar(9));
+ } else if (!g.searchBuffer.handleInput(input)) {
+ //qDebug() << "IGNORED IN SEARCH MODE: " << input.key() << input.text();
+ return EventUnhandled;
}
- if (hasConfig(ConfigIncSearch) && !input.isReturn() && !input.isEscape()) {
- SearchData sd;
- sd.needle = m_commandBuffer.contents();
- sd.forward = m_lastSearchForward;
- sd.mustMove = false;
- sd.highlightCursor = true;
- sd.highlightMatches = false;
- search(sd);
- }
+ updateMiniBuffer();
- //else {
- // qDebug() << "IGNORED IN SEARCH MODE: " << input.key() << input.text();
- // return EventUnhandled;
- //}
- return EventHandled;
+ if (!input.isReturn() && !input.isEscape())
+ updateFind(false);
+
+ return handled;
}
-// This uses 1 based line counting.
-int FakeVimHandler::Private::readLineCode(QString &cmd)
+// This uses 0 based line counting (hidden lines included).
+int FakeVimHandler::Private::parseLineAddress(QString *cmd)
{
//qDebug() << "CMD: " << cmd;
- if (cmd.isEmpty())
+ if (cmd->isEmpty())
return -1;
- QChar c = cmd.at(0);
- cmd = cmd.mid(1);
- if (c == '.') {
- if (cmd.isEmpty())
- return cursorLine() + 1;
- QChar c1 = cmd.at(0);
- if (c1 == '+' || c1 == '-') {
- // Repeat for things like .+4
- cmd = cmd.mid(1);
- return cursorLine() + readLineCode(cmd);
- }
- return cursorLine() + 1;
- }
- if (c == '$')
- return linesInDocument();
- if (c == '\'' && !cmd.isEmpty()) {
- if (cmd.isEmpty()) {
- showRedMessage(msgMarkNotSet(QString()));
+
+ int result = -1;
+ QChar c = cmd->at(0);
+ if (c == QLatin1Char('.')) { // current line
+ result = cursorBlockNumber();
+ cmd->remove(0, 1);
+ } else if (c == QLatin1Char('$')) { // last line
+ result = document()->blockCount() - 1;
+ cmd->remove(0, 1);
+ } else if (c == QLatin1Char('\'')) { // mark
+ cmd->remove(0, 1);
+ if (cmd->isEmpty()) {
+ showMessage(MessageError, msgMarkNotSet(QString()));
return -1;
}
- int m = mark(cmd.at(0).unicode());
- if (m == -1) {
- showRedMessage(msgMarkNotSet(cmd.at(0)));
- cmd = cmd.mid(1);
+ c = cmd->at(0);
+ Mark m = mark(c);
+ if (!m.isValid() || !m.isLocal(m_currentFileName)) {
+ showMessage(MessageError, msgMarkNotSet(c));
return -1;
}
- cmd = cmd.mid(1);
- return lineForPosition(m);
- }
- if (c == '-') {
- int n = readLineCode(cmd);
- return cursorLine() + 1 - (n == -1 ? 1 : n);
- }
- if (c == '+') {
- int n = readLineCode(cmd);
- return cursorLine() + 1 + (n == -1 ? 1 : n);
- }
- if (c == '\'' && !cmd.isEmpty()) {
- int pos = mark(cmd.at(0).unicode());
- if (pos == -1) {
- showRedMessage(msgMarkNotSet(cmd.at(0)));
- cmd = cmd.mid(1);
- return -1;
+ cmd->remove(0, 1);
+ result = m.position.line;
+ } else if (c.isDigit()) { // line with given number
+ result = 0;
+ } else if (c == QLatin1Char('-') || c == QLatin1Char('+')) { // add or subtract from current line number
+ result = cursorBlockNumber();
+ } else if (c == QLatin1Char('/') || c == QLatin1Char('?')
+ || (c == QLatin1Char('\\') && cmd->size() > 1 && QString::fromLatin1("/?&").contains(cmd->at(1)))) {
+ // search for expression
+ SearchData sd;
+ if (c == QLatin1Char('/') || c == QLatin1Char('?')) {
+ const int end = findUnescaped(c, *cmd, 1);
+ if (end == -1)
+ return -1;
+ sd.needle = cmd->mid(1, end - 1);
+ cmd->remove(0, end + 1);
+ } else {
+ c = cmd->at(1);
+ cmd->remove(0, 2);
+ sd.needle = (c == QLatin1Char('&')) ? g.lastSubstitutePattern : g.lastSearch;
}
- cmd = cmd.mid(1);
- return lineForPosition(pos);
- }
- if (c.isDigit()) {
- int n = c.unicode() - '0';
- while (!cmd.isEmpty()) {
- c = cmd.at(0);
- if (!c.isDigit())
- break;
- cmd = cmd.mid(1);
- n = n * 10 + (c.unicode() - '0');
+ sd.forward = (c != QLatin1Char('?'));
+ const QTextBlock b = block();
+ const int pos = b.position() + (sd.forward ? b.length() - 1 : 0);
+ QTextCursor tc = search(sd, pos, 1, true);
+ g.lastSearch = sd.needle;
+ if (tc.isNull())
+ return -1;
+ result = tc.block().blockNumber();
+ } else {
+ return cursorBlockNumber();
+ }
+
+ // basic arithmetic ("-3+5" or "++" means "+2" etc.)
+ int n = 0;
+ bool add = true;
+ int i = 0;
+ for (; i < cmd->size(); ++i) {
+ c = cmd->at(i);
+ if (c == QLatin1Char('-') || c == QLatin1Char('+')) {
+ if (n != 0)
+ result = result + (add ? n - 1 : -(n - 1));
+ add = c == QLatin1Char('+');
+ result = result + (add ? 1 : -1);
+ n = 0;
+ } else if (c.isDigit()) {
+ n = n * 10 + c.digitValue();
+ } else if (!c.isSpace()) {
+ break;
}
- //qDebug() << "N: " << n;
- return n;
}
- // Parsing failed.
- cmd = c + cmd;
- return -1;
+ if (n != 0)
+ result = result + (add ? n - 1 : -(n - 1));
+ *cmd = cmd->mid(i).trimmed();
+
+ return result;
}
void FakeVimHandler::Private::setCurrentRange(const Range &range)
@@ -3467,13 +4529,100 @@ void FakeVimHandler::Private::setCurrentRange(const Range &range)
m_rangemode = range.rangemode;
}
-Range FakeVimHandler::Private::rangeFromCurrentLine() const
+bool FakeVimHandler::Private::parseExCommmand(QString *line, ExCommand *cmd)
{
- Range range;
- int line = cursorLine() + 1;
- range.beginPos = firstPositionInLine(line);
- range.endPos = lastPositionInLine(line);
- return range;
+ *cmd = ExCommand();
+ if (line->isEmpty())
+ return false;
+
+ // remove leading colons and spaces
+ line->remove(QRegExp(_("^\\s*(:+\\s*)*")));
+
+ // parse range first
+ if (!parseLineRange(line, cmd))
+ return false;
+
+ // get first command from command line
+ QChar close;
+ bool subst = false;
+ int i = 0;
+ for (; i < line->size(); ++i) {
+ const QChar &c = line->at(i);
+ if (c == QLatin1Char('\\')) {
+ ++i; // skip escaped character
+ } else if (close.isNull()) {
+ if (c == QLatin1Char('|')) {
+ // split on |
+ break;
+ } else if (c == QLatin1Char('/')) {
+ subst = i > 0 && (line->at(i - 1) == QLatin1Char('s'));
+ close = c;
+ } else if (c == QLatin1Char('"') || c == QLatin1Char('\'')) {
+ close = c;
+ }
+ } else if (c == close) {
+ if (subst)
+ subst = false;
+ else
+ close = QChar();
+ }
+ }
+
+ cmd->cmd = line->mid(0, i).trimmed();
+
+ // command arguments starts with first non-letter character
+ cmd->args = cmd->cmd.section(QRegExp(_("(?=[^a-zA-Z])")), 1);
+ if (!cmd->args.isEmpty()) {
+ cmd->cmd.chop(cmd->args.size());
+ cmd->args = cmd->args.trimmed();
+
+ // '!' at the end of command
+ cmd->hasBang = cmd->args.startsWith(QLatin1Char('!'));
+ if (cmd->hasBang)
+ cmd->args = cmd->args.mid(1).trimmed();
+ }
+
+ // remove the first command from command line
+ line->remove(0, i + 1);
+
+ return true;
+}
+
+bool FakeVimHandler::Private::parseLineRange(QString *line, ExCommand *cmd)
+{
+ // FIXME: that seems to be different for %w and %s
+ if (line->startsWith(QLatin1Char('%')))
+ line->replace(0, 1, _("1,$"));
+
+ int beginLine = parseLineAddress(line);
+ int endLine;
+ if (line->startsWith(QLatin1Char(','))) {
+ *line = line->mid(1).trimmed();
+ endLine = parseLineAddress(line);
+ } else {
+ endLine = beginLine;
+ }
+ if (beginLine == -1 || endLine == -1)
+ return false;
+
+ const int beginPos = firstPositionInLine(qMin(beginLine, endLine) + 1, false);
+ const int endPos = lastPositionInLine(qMax(beginLine, endLine) + 1, false);
+ cmd->range = Range(beginPos, endPos, RangeLineMode);
+ cmd->count = beginLine;
+
+ return true;
+}
+
+void FakeVimHandler::Private::parseRangeCount(const QString &line, Range *range) const
+{
+ bool ok;
+ const int count = qAbs(line.trimmed().toInt(&ok));
+ if (ok) {
+ const int beginLine = document()->findBlock(range->endPos).blockNumber() + 1;
+ const int endLine = qMin(beginLine + count - 1, document()->blockCount());
+ range->beginPos = firstPositionInLine(beginLine, false);
+ range->endPos = lastPositionInLine(endLine, false);
+ }
}
// use handleExCommand for invoking commands that might move the cursor
@@ -3483,127 +4632,93 @@ void FakeVimHandler::Private::handleCommand(const QString &cmd)
}
bool FakeVimHandler::Private::handleExSubstituteCommand(const ExCommand &cmd)
- // :substitute
{
- QString flags;
- QRegExp pattern;
- QString replacement;
- int count = 0;
-
- if (cmd.cmd.startsWith("&&")) {
- flags = cmd.cmd.mid(2);
- if (flags.isEmpty())
- flags = m_lastSubstituteFlags;
- pattern = m_lastSubstitutePattern;
- replacement = m_lastSubstituteReplacement;
- count = cmd.args.section(QLatin1Char(' '), 1, 1).toInt();
- } else if (cmd.cmd.startsWith(QLatin1Char('&'))) {
- flags = cmd.cmd.mid(1);
- if (flags.isEmpty())
- flags = m_lastSubstituteFlags;
- pattern = m_lastSubstitutePattern;
- replacement = m_lastSubstituteReplacement;
- count = cmd.args.section(QLatin1Char(' '), 1, 1).toInt();
- } else if (cmd.matches("s", "substitute")) {
- flags = m_lastSubstituteFlags;
- if (flags.isEmpty())
- flags = m_lastSubstituteFlags;
- pattern = m_lastSubstitutePattern;
- replacement = m_lastSubstituteReplacement;
- count = cmd.args.section(QLatin1Char(' '), 2, 2).toInt();
- } else {
- QString line = cmd.cmd + ' ' + cmd.args;
- line = line.trimmed();
- if (line.startsWith(_("substitute")))
- line = line.mid(10);
- else if (line.startsWith('s') && line.size() > 1
- && !isalpha(line.at(1).unicode()))
- line = line.mid(1);
- else
- return false;
- // we have /{pattern}/{string}/[flags] now
- if (line.isEmpty())
- return false;
- const QChar separator = line.at(0);
- int pos1 = -1;
- int pos2 = -1;
- int i;
- for (i = 1; i < line.size(); ++i) {
- if (line.at(i) == separator && line.at(i - 1) != '\\') {
- pos1 = i;
- break;
- }
- }
- if (pos1 == -1)
- return false;
- for (++i; i < line.size(); ++i) {
- if (line.at(i) == separator && line.at(i - 1) != '\\') {
- pos2 = i;
- break;
- }
- }
- if (pos2 == -1)
- pos2 = line.size();
+ // :substitute
+ if (!cmd.matches(_("s"), _("substitute"))
+ && !(cmd.cmd.isEmpty() && !cmd.args.isEmpty() && QString::fromLatin1("&~").contains(cmd.args[0]))) {
+ return false;
+ }
- QString needle = line.mid(1, pos1 - 1);
- replacement = line.mid(pos1 + 1, pos2 - pos1 - 1);
- flags = line.mid(pos2 + 1);
+ int count = 1;
+ QString line = cmd.args;
+ const int countIndex = line.lastIndexOf(QRegExp(_("\\d+$")));
+ if (countIndex != -1) {
+ count = line.mid(countIndex).toInt();
+ line = line.mid(0, countIndex).trimmed();
+ }
- needle.replace('$', '\n');
- needle.replace("\\\n", "\\$");
- pattern = vimPatternToQtPattern(needle, hasConfig(ConfigSmartCase));
+ if (cmd.cmd.isEmpty()) {
+ // keep previous substitution flags on '&&' and '~&'
+ if (line.size() > 1 && line[1] == QLatin1Char('&'))
+ g.lastSubstituteFlags += line.mid(2);
+ else
+ g.lastSubstituteFlags = line.mid(1);
+ if (line[0] == QLatin1Char('~'))
+ g.lastSubstitutePattern = g.lastSearch;
+ } else {
+ if (line.isEmpty()) {
+ g.lastSubstituteFlags.clear();
+ } else {
+ // we have /{pattern}/{string}/[flags] now
+ const QChar separator = line.at(0);
+ int pos1 = findUnescaped(separator, line, 1);
+ if (pos1 == -1)
+ return false;
+ int pos2 = findUnescaped(separator, line, pos1 + 1);;
+ if (pos2 == -1)
+ pos2 = line.size();
- m_lastSubstituteFlags = flags;
- m_lastSubstitutePattern = pattern;
- m_lastSubstituteReplacement = replacement;
+ g.lastSubstitutePattern = line.mid(1, pos1 - 1);
+ g.lastSubstituteReplacement = line.mid(pos1 + 1, pos2 - pos1 - 1);
+ g.lastSubstituteFlags = line.mid(pos2 + 1);
+ }
}
- if (count == 0)
- count = 1;
+ count = qMax(1, count);
+ QString needle = g.lastSubstitutePattern;
- if (flags.contains('i'))
- pattern.setCaseSensitivity(Qt::CaseInsensitive);
+ if (g.lastSubstituteFlags.contains(QLatin1Char('i')))
+ needle.prepend(_("\\c"));
- beginEditBlock();
- const bool global = flags.contains('g');
+ QRegExp pattern = vimPatternToQtPattern(needle, hasConfig(ConfigSmartCase));
+
+ QTextBlock lastBlock;
+ QTextBlock firstBlock;
+ const bool global = g.lastSubstituteFlags.contains(QLatin1Char('g'));
for (int a = 0; a != count; ++a) {
- const Range range = cmd.range.endPos == 0 ? rangeFromCurrentLine() : cmd.range;
- const int beginLine = lineForPosition(range.beginPos);
- const int endLine = lineForPosition(range.endPos);
- for (int line = endLine; line >= beginLine; --line) {
- QString origText = lineContents(line);
- QString text = origText;
- int pos = 0;
- while (true) {
- pos = pattern.indexIn(text, pos, QRegExp::CaretAtZero);
- if (pos == -1)
- break;
- if (pattern.cap(0).isEmpty())
- break;
- QStringList caps = pattern.capturedTexts();
- QString matched = text.mid(pos, caps.at(0).size());
- QString repl = replacement;
- for (int i = 1; i < caps.size(); ++i)
- repl.replace("\\" + QString::number(i), caps.at(i));
- for (int i = 0; i < repl.size(); ++i) {
- if (repl.at(i) == '&' && (i == 0 || repl.at(i - 1) != '\\')) {
- repl.replace(i, 1, caps.at(0));
- i += caps.at(0).size();
- }
+ for (QTextBlock block = document()->findBlock(cmd.range.endPos);
+ block.isValid() && block.position() + block.length() > cmd.range.beginPos;
+ block = block.previous()) {
+ QString text = block.text();
+ if (substituteText(&text, pattern, g.lastSubstituteReplacement, global)) {
+ firstBlock = block;
+ if (!lastBlock.isValid()) {
+ lastBlock = block;
+ beginEditBlock();
}
- repl.replace("\\&", "&");
- text = text.left(pos) + repl + text.mid(pos + matched.size());
- pos += repl.size();
- if (!global)
- break;
+ QTextCursor tc = cursor();
+ const int pos = block.position();
+ const int anchor = pos + block.length() - 1;
+ tc.setPosition(anchor);
+ tc.setPosition(pos, KeepAnchor);
+ tc.insertText(text);
}
- if (text != origText)
- setLineContents(line, text);
}
}
- moveToStartOfLine();
- setTargetColumn();
- endEditBlock();
+
+ if (lastBlock.isValid()) {
+ State &state = m_undo.top();
+ state.position = CursorPosition(firstBlock.blockNumber(), 0);
+
+ leaveVisualMode();
+ setPosition(lastBlock.position());
+ setAnchor();
+ moveToFirstNonBlankOnLine();
+ setTargetColumn();
+
+ endEditBlock();
+ }
+
return true;
}
@@ -3650,31 +4765,49 @@ bool FakeVimHandler::Private::handleExMapCommand(const ExCommand &cmd0) // :map
else
return false;
- const int pos = cmd0.args.indexOf(QLatin1Char(' '));
- if (pos == -1) {
+ QString args = cmd0.args;
+ bool silent = false;
+ bool unique = false;
+ forever {
+ if (eatString("<silent>", &args)) {
+ silent = true;
+ } else if (eatString("<unique>", &args)) {
+ continue;
+ } else if (eatString("<special>", &args)) {
+ continue;
+ } else if (eatString("<buffer>", &args)) {
+ notImplementedYet();
+ continue;
+ } else if (eatString("<script>", &args)) {
+ notImplementedYet();
+ continue;
+ } else if (eatString("<expr>", &args)) {
+ notImplementedYet();
+ return true;
+ }
+ break;
+ }
+
+ const QString lhs = args.section(QRegExp(_("\\s+")), 0, 0);
+ const QString rhs = args.section(QRegExp(_("\\s+")), 1);
+ if ((rhs.isNull() && type != Unmap) || (!rhs.isNull() && type == Unmap)) {
// FIXME: Dump mappings here.
//qDebug() << g.mappings;
return true;
}
- QString lhs = cmd0.args.left(pos);
- QString rhs = cmd0.args.mid(pos + 1);
- Inputs key;
- key.parseFrom(lhs);
+ Inputs key(lhs);
//qDebug() << "MAPPING: " << modes << lhs << rhs;
switch (type) {
case Unmap:
foreach (char c, modes)
- if (g.mappings.contains(c))
- g.mappings[c].remove(key);
+ MappingsIterator(&g.mappings, c, key).remove();
break;
- case Map:
- rhs = rhs; // FIXME: expand rhs.
- // Fall through.
+ case Map: // fall through
case Noremap: {
- Inputs inputs(rhs);
+ Inputs inputs(rhs, type == Noremap, silent);
foreach (char c, modes)
- g.mappings[c].insert(key, inputs);
+ MappingsIterator(&g.mappings, c).setInputs(key, inputs, unique);
break;
}
}
@@ -3684,16 +4817,16 @@ bool FakeVimHandler::Private::handleExMapCommand(const ExCommand &cmd0) // :map
bool FakeVimHandler::Private::handleExHistoryCommand(const ExCommand &cmd)
{
// :his[tory]
- if (!cmd.matches("his", "history"))
+ if (!cmd.matches(_("his"), _("history")))
return false;
if (cmd.args.isEmpty()) {
QString info;
- info += "# command history\n";
+ info += _("# command history\n");
int i = 0;
- foreach (const QString &item, g.commandHistory.items()) {
+ foreach (const QString &item, g.commandBuffer.historyItems()) {
++i;
- info += QString("%1 %2\n").arg(i, -8).arg(item);
+ info += QString::fromLatin1("%1 %2\n").arg(i, -8).arg(item);
}
emit q->extraInformationChanged(info);
} else {
@@ -3706,7 +4839,7 @@ bool FakeVimHandler::Private::handleExHistoryCommand(const ExCommand &cmd)
bool FakeVimHandler::Private::handleExRegisterCommand(const ExCommand &cmd)
{
// :reg[isters] and :di[splay]
- if (!cmd.matches("reg", "registers") && !cmd.matches("di", "display"))
+ if (!cmd.matches(_("reg"), _("registers")) && !cmd.matches(_("di"), _("display")))
return false;
QByteArray regs = cmd.args.toLatin1();
@@ -3720,10 +4853,10 @@ bool FakeVimHandler::Private::handleExRegisterCommand(const ExCommand &cmd)
}
}
QString info;
- info += "--- Registers ---\n";
+ info += _("--- Registers ---\n");
foreach (char reg, regs) {
QString value = quoteUnprintable(registerContents(reg));
- info += QString("\"%1 %2\n").arg(reg).arg(value);
+ info += QString::fromLatin1("\"%1 %2\n").arg(reg).arg(value);
}
emit q->extraInformationChanged(info);
updateMiniBuffer();
@@ -3733,13 +4866,13 @@ bool FakeVimHandler::Private::handleExRegisterCommand(const ExCommand &cmd)
bool FakeVimHandler::Private::handleExSetCommand(const ExCommand &cmd)
{
// :se[t]
- if (!cmd.matches("se", "set"))
+ if (!cmd.matches(_("se"), _("set")))
return false;
- showBlackMessage(QString());
+ clearMessage();
SavedAction *act = theFakeVimSettings()->item(cmd.args);
QTC_CHECK(!cmd.args.isEmpty()); // Handled by plugin.
- if (act && act->value().type() == QVariant::Bool) {
+ if (act && act->value().canConvert(QVariant::Bool)) {
// Boolean config to be switched on.
bool oldValue = act->value().toBool();
if (oldValue == false)
@@ -3748,7 +4881,7 @@ bool FakeVimHandler::Private::handleExSetCommand(const ExCommand &cmd)
{} // nothing to do
} else if (act) {
// Non-boolean to show.
- showBlackMessage(cmd.args + '=' + act->value().toString());
+ showMessage(MessageInfo, cmd.args + QLatin1Char('=') + act->value().toString());
} else if (cmd.args.startsWith(_("no"))
&& (act = theFakeVimSettings()->item(cmd.args.mid(2)))) {
// Boolean config to be switched off.
@@ -3757,15 +4890,15 @@ bool FakeVimHandler::Private::handleExSetCommand(const ExCommand &cmd)
act->setValue(false);
else if (oldValue == false)
{} // nothing to do
- } else if (cmd.args.contains('=')) {
+ } else if (cmd.args.contains(QLatin1Char('='))) {
// Non-boolean config to set.
- int p = cmd.args.indexOf('=');
+ int p = cmd.args.indexOf(QLatin1Char('='));
QString error = theFakeVimSettings()
->trySetValue(cmd.args.left(p), cmd.args.mid(p + 1));
if (!error.isEmpty())
- showRedMessage(error);
+ showMessage(MessageError, error);
} else {
- showRedMessage(FakeVimHandler::tr("Unknown option: ") + cmd.args);
+ showMessage(MessageError, FakeVimHandler::tr("Unknown option: ") + cmd.args);
}
updateMiniBuffer();
updateEditor();
@@ -3775,28 +4908,157 @@ bool FakeVimHandler::Private::handleExSetCommand(const ExCommand &cmd)
bool FakeVimHandler::Private::handleExNormalCommand(const ExCommand &cmd)
{
// :norm[al]
- if (!cmd.matches("norm", "normal"))
+ if (!cmd.matches(_("norm"), _("normal")))
return false;
//qDebug() << "REPLAY NORMAL: " << quoteUnprintable(reNormal.cap(3));
- replay(cmd.args, 1);
+ replay(cmd.args);
return true;
}
-bool FakeVimHandler::Private::handleExDeleteCommand(const ExCommand &cmd)
+bool FakeVimHandler::Private::handleExYankDeleteCommand(const ExCommand &cmd)
{
- // :d[elete]
- if (!cmd.matches("d", "delete"))
+ // :[range]d[elete] [x] [count]
+ // :[range]y[ank] [x] [count]
+ const bool remove = cmd.matches(_("d"), _("delete"));
+ if (!remove && !cmd.matches(_("y"), _("yank")))
return false;
- Range range = cmd.range.endPos == 0 ? rangeFromCurrentLine() : cmd.range;
- setCurrentRange(range);
- QString reg = cmd.args;
- QString text = selectText(range);
+ // get register from arguments
+ const bool hasRegisterArg = !cmd.args.isEmpty() && !cmd.args.at(0).isDigit();
+ const int r = hasRegisterArg ? cmd.args.at(0).unicode() : m_register;
+
+ // get [count] from arguments
+ Range range = cmd.range;
+ parseRangeCount(cmd.args.mid(hasRegisterArg ? 1 : 0).trimmed(), &range);
+
+ yankText(range, r);
+
+ if (remove) {
+ leaveVisualMode();
+ setPosition(range.beginPos);
+ setUndoPosition();
+ setCurrentRange(range);
+ removeText(currentRange());
+ }
+
+ return true;
+}
+
+bool FakeVimHandler::Private::handleExChangeCommand(const ExCommand &cmd)
+{
+ // :[range]c[hange]
+ if (!cmd.matches(_("c"), _("change")))
+ return false;
+
+ const bool oldAutoIndent = hasConfig(ConfigAutoIndent);
+ // Temporarily set autoindent if ! is present.
+ if (cmd.hasBang)
+ theFakeVimSetting(ConfigAutoIndent)->setValue(true, false);
+
+ Range range = cmd.range;
+ range.rangemode = RangeLineModeExclusive;
+ removeText(range);
+ insertAutomaticIndentation(true);
+
+ // FIXME: In Vim same or less number of lines can be inserted and position after insertion is
+ // beginning of last inserted line.
+ enterInsertMode();
+
+ if (cmd.hasBang && !oldAutoIndent)
+ theFakeVimSetting(ConfigAutoIndent)->setValue(false, false);
+
+ return true;
+}
+
+bool FakeVimHandler::Private::handleExMoveCommand(const ExCommand &cmd)
+{
+ // :[range]m[ove] {address}
+ if (!cmd.matches(_("m"), _("move")))
+ return false;
+
+ QString lineCode = cmd.args;
+
+ const int startLine = document()->findBlock(cmd.range.beginPos).blockNumber();
+ const int endLine = document()->findBlock(cmd.range.endPos).blockNumber();
+ const int lines = endLine - startLine + 1;
+
+ int targetLine = lineCode == _("0") ? -1 : parseLineAddress(&lineCode);
+ if (targetLine >= startLine && targetLine < endLine) {
+ showMessage(MessageError, FakeVimHandler::tr("Move lines into themselves"));
+ return true;
+ }
+
+ CursorPosition lastAnchor = mark(QLatin1Char('<')).position;
+ CursorPosition lastPosition = mark(QLatin1Char('>')).position;
+
+ recordJump();
+ setPosition(cmd.range.beginPos);
+ setUndoPosition();
+
+ setCurrentRange(cmd.range);
+ QString text = selectText(cmd.range);
removeText(currentRange());
- if (!reg.isEmpty()) {
- const int r = reg.at(0).unicode();
- setRegister(r, text, RangeLineMode);
+
+ const bool insertAtEnd = targetLine == document()->blockCount();
+ if (targetLine >= startLine)
+ targetLine -= lines;
+ QTextBlock block = document()->findBlockByNumber(insertAtEnd ? targetLine : targetLine + 1);
+ setPosition(block.position());
+ setAnchor();
+
+ if (insertAtEnd) {
+ moveBehindEndOfLine();
+ text.chop(1);
+ insertText(QString::fromLatin1("\n"));
+ }
+ insertText(text);
+
+ if (!insertAtEnd)
+ moveUp(1);
+ if (hasConfig(ConfigStartOfLine))
+ moveToFirstNonBlankOnLine();
+
+ // correct last selection
+ leaveVisualMode();
+ if (lastAnchor.line >= startLine && lastAnchor.line <= endLine)
+ lastAnchor.line += targetLine - startLine + 1;
+ if (lastPosition.line >= startLine && lastPosition.line <= endLine)
+ lastPosition.line += targetLine - startLine + 1;
+ setMark(QLatin1Char('<'), lastAnchor);
+ setMark(QLatin1Char('>'), lastPosition);
+
+ if (lines > 2)
+ showMessage(MessageInfo, FakeVimHandler::tr("%n lines moved", 0, lines));
+
+ return true;
+}
+
+bool FakeVimHandler::Private::handleExJoinCommand(const ExCommand &cmd)
+{
+ // :[range]j[oin][!] [count]
+ // FIXME: Argument [count] can follow immediately.
+ if (!cmd.matches(_("j"), _("join")))
+ return false;
+
+ // get [count] from arguments
+ bool ok;
+ int count = cmd.args.toInt(&ok);
+
+ if (ok) {
+ setPosition(cmd.range.endPos);
+ } else {
+ setPosition(cmd.range.beginPos);
+ const int startLine = document()->findBlock(cmd.range.beginPos).blockNumber();
+ const int endLine = document()->findBlock(cmd.range.endPos).blockNumber();
+ count = endLine - startLine + 1;
}
+
+ moveToStartOfLine();
+ setUndoPosition();
+ joinLines(count, cmd.hasBang);
+
+ moveToFirstNonBlankOnLine();
+
return true;
}
@@ -3804,7 +5066,7 @@ bool FakeVimHandler::Private::handleExWriteCommand(const ExCommand &cmd)
{
// :w, :x, :wq, ...
//static QRegExp reWrite("^[wx]q?a?!?( (.*))?$");
- if (cmd.cmd != "w" && cmd.cmd != "x" && cmd.cmd != "wq")
+ if (cmd.cmd != _("w") && cmd.cmd != _("x") && cmd.cmd != _("wq"))
return false;
int beginLine = lineForPosition(cmd.range.beginPos);
@@ -3817,15 +5079,15 @@ bool FakeVimHandler::Private::handleExWriteCommand(const ExCommand &cmd)
//qDebug() << "LINES: " << beginLine << endLine;
//QString prefix = cmd.args;
const bool forced = cmd.hasBang;
- //const bool quit = prefix.contains(QChar('q')) || prefix.contains(QChar('x'));
- //const bool quitAll = quit && prefix.contains(QChar('a'));
+ //const bool quit = prefix.contains(QLatin1Char('q')) || prefix.contains(QLatin1Char('x'));
+ //const bool quitAll = quit && prefix.contains(QLatin1Char('a'));
QString fileName = cmd.args;
if (fileName.isEmpty())
fileName = m_currentFileName;
QFile file1(fileName);
const bool exists = file1.exists();
if (exists && !forced && !noArgs) {
- showRedMessage(FakeVimHandler::tr
+ showMessage(MessageError, FakeVimHandler::tr
("File \"%1\" exists (add ! to override)").arg(fileName));
} else if (file1.open(QIODevice::ReadWrite)) {
// Nobody cared, so act ourselves.
@@ -3839,22 +5101,22 @@ bool FakeVimHandler::Private::handleExWriteCommand(const ExCommand &cmd)
QTextStream ts(&file2);
ts << contents;
} else {
- showRedMessage(FakeVimHandler::tr
+ showMessage(MessageError, FakeVimHandler::tr
("Cannot open file \"%1\" for writing").arg(fileName));
}
// Check result by reading back.
QFile file3(fileName);
file3.open(QIODevice::ReadOnly);
QByteArray ba = file3.readAll();
- showBlackMessage(FakeVimHandler::tr("\"%1\" %2 %3L, %4C written")
- .arg(fileName).arg(exists ? " " : tr(" [New] "))
+ showMessage(MessageInfo, FakeVimHandler::tr("\"%1\" %2 %3L, %4C written")
+ .arg(fileName).arg(exists ? _(" ") : tr(" [New] "))
.arg(ba.count('\n')).arg(ba.size()));
//if (quitAll)
// passUnknownExCommand(forced ? "qa!" : "qa");
//else if (quit)
// passUnknownExCommand(forced ? "q!" : "q");
} else {
- showRedMessage(FakeVimHandler::tr
+ showMessage(MessageError, FakeVimHandler::tr
("Cannot open file \"%1\" for reading").arg(fileName));
}
return true;
@@ -3863,7 +5125,7 @@ bool FakeVimHandler::Private::handleExWriteCommand(const ExCommand &cmd)
bool FakeVimHandler::Private::handleExReadCommand(const ExCommand &cmd)
{
// :r[ead]
- if (!cmd.matches("r", "read"))
+ if (!cmd.matches(_("r"), _("read")))
return false;
beginEditBlock();
@@ -3877,26 +5139,25 @@ bool FakeVimHandler::Private::handleExReadCommand(const ExCommand &cmd)
QString data = ts.readAll();
insertText(data);
endEditBlock();
- showBlackMessage(FakeVimHandler::tr("\"%1\" %2L, %3C")
- .arg(m_currentFileName).arg(data.count('\n')).arg(data.size()));
+ showMessage(MessageInfo, FakeVimHandler::tr("\"%1\" %2L, %3C")
+ .arg(m_currentFileName).arg(data.count(QLatin1Char('\n'))).arg(data.size()));
return true;
}
bool FakeVimHandler::Private::handleExBangCommand(const ExCommand &cmd) // :!
{
- if (!cmd.cmd.startsWith(QLatin1Char('!')))
+ if (!cmd.cmd.isEmpty() || !cmd.hasBang)
return false;
setCurrentRange(cmd.range);
int targetPosition = firstPositionInLine(lineForPosition(cmd.range.beginPos));
- QString command = QString(cmd.cmd.mid(1) + ' ' + cmd.args).trimmed();
+ QString command = QString(cmd.cmd.mid(1) + QLatin1Char(' ') + cmd.args).trimmed();
QString text = selectText(cmd.range);
QProcess proc;
proc.start(command);
proc.waitForStarted();
-#ifdef Q_OS_WIN
- text.replace(_("\n"), _("\r\n"));
-#endif
+ if (Utils::HostOsInfo::isWindowsHost())
+ text.replace(_("\n"), _("\r\n"));
proc.write(text.toUtf8());
proc.closeWriteChannel();
proc.waitForFinished();
@@ -3911,101 +5172,128 @@ bool FakeVimHandler::Private::handleExBangCommand(const ExCommand &cmd) // :!
endEditBlock();
leaveVisualMode();
//qDebug() << "FILTER: " << command;
- showBlackMessage(FakeVimHandler::tr("%n lines filtered", 0,
- text.count('\n')));
+ showMessage(MessageInfo, FakeVimHandler::tr("%n lines filtered", 0,
+ text.count(QLatin1Char('\n'))));
}
return true;
}
bool FakeVimHandler::Private::handleExShiftCommand(const ExCommand &cmd)
{
- if (cmd.cmd != "<" && cmd.cmd != ">")
+ // :[range]{<|>}* [count]
+ if (!cmd.cmd.isEmpty() || (!cmd.args.startsWith(QLatin1Char('<')) && !cmd.args.startsWith(QLatin1Char('>'))))
return false;
+ const QChar c = cmd.args.at(0);
+
+ // get number of repetition
+ int repeat = 1;
+ int i = 1;
+ for (; i < cmd.args.size(); ++i) {
+ const QChar c2 = cmd.args.at(i);
+ if (c2 == c)
+ ++repeat;
+ else if (!c2.isSpace())
+ break;
+ }
+
+ // get [count] from arguments
Range range = cmd.range;
- if (cmd.range.endPos == 0)
- range = rangeFromCurrentLine();
+ parseRangeCount(cmd.args.mid(i), &range);
+
setCurrentRange(range);
- int count = qMax(1, cmd.args.toInt());
- if (cmd.cmd == "<")
- shiftRegionLeft(count);
+ if (c == QLatin1Char('<'))
+ shiftRegionLeft(repeat);
else
- shiftRegionRight(count);
+ shiftRegionRight(repeat);
+
leaveVisualMode();
- const int beginLine = lineForPosition(range.beginPos);
- const int endLine = lineForPosition(range.endPos);
- showBlackMessage(FakeVimHandler::tr("%n lines %1ed %2 time", 0,
- (endLine - beginLine + 1)).arg(cmd.cmd).arg(count));
+
return true;
}
bool FakeVimHandler::Private::handleExNohlsearchCommand(const ExCommand &cmd)
{
// :nohlsearch
- if (!cmd.cmd.startsWith("noh"))
+ if (!cmd.cmd.startsWith(_("noh")))
return false;
- m_searchSelections.clear();
- updateSelection();
+ highlightMatches(QString());
return true;
}
-bool FakeVimHandler::Private::handleExRedoCommand(const ExCommand &cmd)
+bool FakeVimHandler::Private::handleExUndoRedoCommand(const ExCommand &cmd)
{
+ // :undo
// :redo
- if (cmd.cmd != "red" && cmd.cmd != "redo")
+ bool undo = (cmd.cmd == _("u") || cmd.cmd == _("un") || cmd.cmd == _("undo"));
+ if (!undo && cmd.cmd != _("red") && cmd.cmd != _("redo"))
return false;
- redo();
+ undoRedo(undo);
updateMiniBuffer();
return true;
}
bool FakeVimHandler::Private::handleExGotoCommand(const ExCommand &cmd)
{
- // :<nr>
- if (!cmd.cmd.isEmpty())
+ // :{address}
+ if (!cmd.cmd.isEmpty() || !cmd.args.isEmpty())
return false;
- const int beginLine = lineForPosition(cmd.range.beginPos);
+ const int beginLine = lineForPosition(cmd.range.endPos);
setPosition(firstPositionInLine(beginLine));
- showBlackMessage(QString());
+ clearMessage();
return true;
}
bool FakeVimHandler::Private::handleExSourceCommand(const ExCommand &cmd)
{
// :source
- if (cmd.cmd != "so" && cmd.cmd != "source")
+ if (cmd.cmd != _("so") && cmd.cmd != _("source"))
return false;
QString fileName = cmd.args;
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly)) {
- showRedMessage(FakeVimHandler::tr("Cannot open file %1").arg(fileName));
+ showMessage(MessageError, FakeVimHandler::tr("Cannot open file %1").arg(fileName));
return true;
}
bool inFunction = false;
- while (!file.atEnd()) {
- QByteArray line = file.readLine();
- line = line.trimmed();
+ QByteArray line;
+ while (!file.atEnd() || !line.isEmpty()) {
+ QByteArray nextline = !file.atEnd() ? file.readLine() : QByteArray();
+
+ // remove comment
+ int i = nextline.lastIndexOf('"');
+ if (i != -1)
+ nextline = nextline.remove(i, nextline.size() - i);
+
+ nextline = nextline.trimmed();
+
+ // multi-line command?
+ if (nextline.startsWith('\\')) {
+ line += nextline.mid(1);
+ continue;
+ }
+
if (line.startsWith("function")) {
//qDebug() << "IGNORING FUNCTION" << line;
inFunction = true;
} else if (inFunction && line.startsWith("endfunction")) {
inFunction = false;
- } else if (line.startsWith("function")) {
- //qDebug() << "IGNORING FUNCTION" << line;
- inFunction = true;
- } else if (line.startsWith('"')) {
- // A comment.
} else if (!line.isEmpty() && !inFunction) {
//qDebug() << "EXECUTING: " << line;
ExCommand cmd;
- cmd.setContentsFromLine(QString::fromLocal8Bit(line));
- handleExCommandHelper(cmd);
+ QString commandLine = QString::fromLocal8Bit(line);
+ while (parseExCommmand(&commandLine, &cmd)) {
+ if (!handleExCommandHelper(cmd))
+ break;
+ }
}
+
+ line = nextline;
}
file.close();
return true;
@@ -4014,9 +5302,9 @@ bool FakeVimHandler::Private::handleExSourceCommand(const ExCommand &cmd)
bool FakeVimHandler::Private::handleExEchoCommand(const ExCommand &cmd)
{
// :echo
- if (cmd.cmd != "echo")
+ if (cmd.cmd != _("echo"))
return false;
- m_currentMessage = cmd.args;
+ showMessage(MessageInfo, cmd.args);
return true;
}
@@ -4028,51 +5316,45 @@ void FakeVimHandler::Private::handleExCommand(const QString &line0)
line.chop(1);
int percent = line.toInt();
setPosition(firstPositionInLine(percent * linesInDocument() / 100));
- showBlackMessage(QString());
+ clearMessage();
return;
}
- // FIXME: that seems to be different for %w and %s
- if (line.startsWith(QLatin1Char('%')))
- line = "1,$" + line.mid(1);
+ //qDebug() << "CMD: " << cmd;
- const int beginLine = readLineCode(line);
- int endLine = -1;
- if (line.startsWith(',')) {
- line = line.mid(1);
- endLine = readLineCode(line);
- }
- if (beginLine != -1 && endLine == -1)
- endLine = beginLine;
+ enterCommandMode(g.returnToMode);
+
+ beginLargeEditBlock();
ExCommand cmd;
- cmd.setContentsFromLine(line);
- if (beginLine != -1) {
- const int beginPos = firstPositionInLine(beginLine);
- const int endPos = lastPositionInLine(endLine);
- cmd.range = Range(beginPos, endPos, RangeLineMode);
- cmd.count = beginLine;
+ QString lastCommand = line;
+ while (parseExCommmand(&line, &cmd)) {
+ if (!handleExCommandHelper(cmd)) {
+ showMessage(MessageError, tr("Not an editor command: %1").arg(lastCommand));
+ break;
+ }
+ lastCommand = line;
}
- //qDebug() << "CMD: " << cmd;
+ endEditBlock();
- enterCommandMode();
- showBlackMessage(QString());
- if (!handleExCommandHelper(cmd))
- showRedMessage(tr("Not an editor command: %1").arg(cmd.cmd));
+ resetCommandMode();
}
-bool FakeVimHandler::Private::handleExCommandHelper(const ExCommand &cmd)
+bool FakeVimHandler::Private::handleExCommandHelper(ExCommand &cmd)
{
return handleExPluginCommand(cmd)
|| handleExGotoCommand(cmd)
|| handleExBangCommand(cmd)
|| handleExHistoryCommand(cmd)
|| handleExRegisterCommand(cmd)
- || handleExDeleteCommand(cmd)
+ || handleExYankDeleteCommand(cmd)
+ || handleExChangeCommand(cmd)
+ || handleExMoveCommand(cmd)
+ || handleExJoinCommand(cmd)
|| handleExMapCommand(cmd)
|| handleExNohlsearchCommand(cmd)
|| handleExNormalCommand(cmd)
|| handleExReadCommand(cmd)
- || handleExRedoCommand(cmd)
+ || handleExUndoRedoCommand(cmd)
|| handleExSetCommand(cmd)
|| handleExShiftCommand(cmd)
|| handleExSourceCommand(cmd)
@@ -4111,123 +5393,147 @@ void FakeVimHandler::Private::searchBalanced(bool forward, QChar needle, QChar o
// Making this unconditional feels better, but is not "vim like".
if (oldLine != cursorLine() - cursorLineOnScreen())
scrollToLine(cursorLine() - linesOnScreen() / 2);
+ recordJump();
setPosition(pos);
setTargetColumn();
- updateSelection();
- recordJump();
return;
}
}
}
-void FakeVimHandler::Private::search(const SearchData &sd)
+QTextCursor FakeVimHandler::Private::search(const SearchData &sd, int startPos, int count,
+ bool showMessages)
{
- if (sd.needle.isEmpty())
- return;
-
- const bool incSearch = hasConfig(ConfigIncSearch);
- QTextDocument::FindFlags flags = QTextDocument::FindCaseSensitively;
- if (!sd.forward)
- flags |= QTextDocument::FindBackward;
-
QRegExp needleExp = vimPatternToQtPattern(sd.needle, hasConfig(ConfigSmartCase));
+ if (!needleExp.isValid()) {
+ if (showMessages) {
+ QString error = needleExp.errorString();
+ showMessage(MessageError,
+ FakeVimHandler::tr("Invalid regular expression: %1").arg(error));
+ }
+ if (sd.highlightMatches)
+ highlightMatches(QString());
+ return QTextCursor();
+ }
- const int oldLine = cursorLine() - cursorLineOnScreen();
+ int repeat = count;
+ const int pos = startPos + (sd.forward ? 1 : -1);
+
+ QTextCursor tc;
+ if (pos >= 0 && pos < document()->characterCount()) {
+ tc = QTextCursor(document());
+ tc.setPosition(pos);
+ if (sd.forward && afterEndOfLine(document(), pos))
+ tc.movePosition(Right);
- int startPos = position();
- if (sd.mustMove)
- sd.forward ? ++startPos : --startPos;
+ if (!tc.isNull()) {
+ if (sd.forward)
+ searchForward(&tc, needleExp, &repeat);
+ else
+ searchBackward(&tc, needleExp, &repeat);
+ }
+ }
- m_searchCursor = QTextCursor();
- QTextCursor tc = document()->find(needleExp, startPos, flags);
if (tc.isNull()) {
- int startPos = sd.forward ? 0 : lastPositionInDocument();
- tc = document()->find(needleExp, startPos, flags);
- if (tc.isNull()) {
- if (!incSearch) {
- highlightMatches(QString());
- showRedMessage(FakeVimHandler::tr("Pattern not found: %1")
- .arg(needleExp.pattern()));
+ if (hasConfig(ConfigWrapScan)) {
+ tc = QTextCursor(document());
+ tc.movePosition(sd.forward ? StartOfDocument : EndOfDocument);
+ if (sd.forward)
+ searchForward(&tc, needleExp, &repeat);
+ else
+ searchBackward(&tc, needleExp, &repeat);
+ if (tc.isNull()) {
+ if (showMessages) {
+ showMessage(MessageError,
+ FakeVimHandler::tr("Pattern not found: %1").arg(sd.needle));
+ }
+ } else if (showMessages) {
+ QString msg = sd.forward
+ ? FakeVimHandler::tr("search hit BOTTOM, continuing at TOP")
+ : FakeVimHandler::tr("search hit TOP, continuing at BOTTOM");
+ showMessage(MessageWarning, msg);
}
- updateSelection();
- return;
- }
- if (!incSearch) {
+ } else if (showMessages) {
QString msg = sd.forward
- ? FakeVimHandler::tr("search hit BOTTOM, continuing at TOP")
- : FakeVimHandler::tr("search hit TOP, continuing at BOTTOM");
- showRedMessage(msg);
+ ? FakeVimHandler::tr("search hit BOTTOM without match for: %1")
+ : FakeVimHandler::tr("search hit TOP without match for: %1");
+ showMessage(MessageError, msg.arg(sd.needle));
}
}
- // Set Cursor. In contrast to the main editor we have the cursor
- // position before the anchor position.
- setAnchorAndPosition(tc.position(), tc.anchor());
+ if (sd.highlightMatches)
+ highlightMatches(needleExp.pattern());
+
+ return tc;
+}
+
+void FakeVimHandler::Private::search(const SearchData &sd, bool showMessages)
+{
+ const int oldLine = cursorLine() - cursorLineOnScreen();
+
+ QTextCursor tc = search(sd, m_searchStartPosition, count(), showMessages);
+ if (tc.isNull()) {
+ tc = cursor();
+ tc.setPosition(m_searchStartPosition);
+ }
+
+ if (isVisualMode()) {
+ int d = tc.anchor() - tc.position();
+ setPosition(tc.position() + d);
+ } else {
+ // Set Cursor. In contrast to the main editor we have the cursor
+ // position before the anchor position.
+ setAnchorAndPosition(tc.position(), tc.anchor());
+ }
// Making this unconditional feels better, but is not "vim like".
if (oldLine != cursorLine() - cursorLineOnScreen())
scrollToLine(cursorLine() - linesOnScreen() / 2);
- if (incSearch && sd.highlightCursor)
- m_searchCursor = cursor();
+ m_searchCursor = cursor();
setTargetColumn();
+}
- if (sd.highlightMatches)
- highlightMatches(sd.needle);
- updateSelection();
+void FakeVimHandler::Private::searchNext(bool forward)
+{
+ SearchData sd;
+ sd.needle = g.lastSearch;
+ sd.forward = forward ? g.lastSearchForward : !g.lastSearchForward;
+ sd.highlightMatches = true;
+ m_searchStartPosition = position();
+ showMessage(MessageCommand, QLatin1Char(g.lastSearchForward ? '/' : '?') + sd.needle);
recordJump();
+ search(sd);
}
void FakeVimHandler::Private::highlightMatches(const QString &needle)
{
- if (!hasConfig(ConfigHlSearch))
- return;
- if (needle == m_oldNeedle)
+ if (!hasConfig(ConfigHlSearch) || needle == m_oldNeedle)
return;
m_oldNeedle = needle;
- m_searchSelections.clear();
- if (!needle.isEmpty()) {
- QTextCursor tc = cursor();
- tc.movePosition(StartOfDocument, MoveAnchor);
-
- QRegExp needleExp = vimPatternToQtPattern(needle, hasConfig(ConfigSmartCase));
- if (!needleExp.isValid()) {
- QString error = needleExp.errorString();
- showRedMessage(
- FakeVimHandler::tr("Invalid regular expression: %1").arg(error));
- return;
- }
- while (!tc.atEnd()) {
- tc = tc.document()->find(needleExp, tc.position());
- if (tc.isNull())
- break;
- if (!tc.hasSelection())
- tc.movePosition(Right, KeepAnchor, 1);
- QTextEdit::ExtraSelection sel;
- sel.cursor = tc;
- sel.format = tc.blockCharFormat();
- sel.format.setBackground(QColor(177, 177, 0));
- m_searchSelections.append(sel);
- if (document()->characterAt(tc.position()) == ParagraphSeparator)
- tc.movePosition(Right, MoveAnchor);
- }
- }
- updateSelection();
+ updateHighlights();
}
void FakeVimHandler::Private::moveToFirstNonBlankOnLine()
{
- QTextDocument *doc = document();
- int firstPos = block().position();
+ QTextCursor tc2 = cursor();
+ moveToFirstNonBlankOnLine(&tc2);
+ setPosition(tc2.position());
+}
+
+void FakeVimHandler::Private::moveToFirstNonBlankOnLine(QTextCursor *tc)
+{
+ QTextDocument *doc = tc->document();
+ int firstPos = tc->block().position();
for (int i = firstPos, n = firstPos + block().length(); i < n; ++i) {
if (!doc->characterAt(i).isSpace() || i == n - 1) {
- setPosition(i);
+ tc->setPosition(i);
return;
}
}
- setPosition(block().position());
+ tc->setPosition(block().position());
}
void FakeVimHandler::Private::indentSelectedText(QChar typedChar)
@@ -4243,21 +5549,21 @@ void FakeVimHandler::Private::indentSelectedText(QChar typedChar)
setPosition(firstPositionInLine(beginLine));
handleStartOfLine();
setTargetColumn();
- setDotCommand("%1==", endLine - beginLine + 1);
+ setDotCommand(_("%1=="), endLine - beginLine + 1);
endEditBlock();
+
+ const int lines = endLine - beginLine + 1;
+ if (lines > 2)
+ showMessage(MessageInfo, FakeVimHandler::tr("%n lines indented", 0, lines));
}
void FakeVimHandler::Private::indentText(const Range &range, QChar typedChar)
{
- int beginLine = lineForPosition(range.beginPos);
- int endLine = lineForPosition(range.endPos);
- if (beginLine > endLine)
- qSwap(beginLine, endLine);
-
- // LineForPosition has returned 1-based line numbers.
- emit q->indentRegion(beginLine - 1, endLine - 1, typedChar);
- if (beginLine != endLine)
- showBlackMessage("MARKS ARE OFF NOW");
+ int beginBlock = document()->findBlock(range.beginPos).blockNumber();
+ int endBlock = document()->findBlock(range.endPos).blockNumber();
+ if (beginBlock > endBlock)
+ qSwap(beginBlock, endBlock);
+ emit q->indentRegion(beginBlock, endBlock, typedChar);
}
bool FakeVimHandler::Private::isElectricCharacter(QChar c) const
@@ -4280,58 +5586,35 @@ void FakeVimHandler::Private::shiftRegionRight(int repeat)
targetPos = firstPositionInLine(beginLine);
const int sw = config(ConfigShiftWidth).toInt();
+ m_movetype = MoveLineWise;
beginEditBlock();
- for (int line = beginLine; line <= endLine; ++line) {
- QString data = lineContents(line);
- const Column col = indentation(data);
- data = tabExpand(col.logical + sw * repeat) + data.mid(col.physical);
- setLineContents(line, data);
+ QTextBlock block = document()->findBlockByLineNumber(beginLine - 1);
+ while (block.isValid() && lineNumber(block) <= endLine) {
+ const Column col = indentation(block.text());
+ QTextCursor tc = cursor();
+ tc.setPosition(block.position());
+ if (col.physical > 0)
+ tc.setPosition(tc.position() + col.physical, KeepAnchor);
+ tc.insertText(tabExpand(col.logical + sw * repeat));
+ block = block.next();
}
endEditBlock();
setPosition(targetPos);
handleStartOfLine();
setTargetColumn();
- setDotCommand("%1>>", endLine - beginLine + 1);
+
+ const int lines = endLine - beginLine + 1;
+ if (lines > 2) {
+ showMessage(MessageInfo,
+ FakeVimHandler::tr("%n lines %1ed %2 time", 0, lines)
+ .arg(repeat > 0 ? '>' : '<').arg(qAbs(repeat)));
+ }
}
void FakeVimHandler::Private::shiftRegionLeft(int repeat)
{
- int beginLine = lineForPosition(anchor());
- int endLine = lineForPosition(position());
- int targetPos = anchor();
- if (beginLine > endLine) {
- qSwap(beginLine, endLine);
- targetPos = position();
- }
- const int shift = config(ConfigShiftWidth).toInt() * repeat;
- const int tab = config(ConfigTabStop).toInt();
- if (hasConfig(ConfigStartOfLine))
- targetPos = firstPositionInLine(beginLine);
-
- beginEditBlock();
- for (int line = endLine; line >= beginLine; --line) {
- int pos = firstPositionInLine(line);
- const QString text = lineContents(line);
- int amount = 0;
- int i = 0;
- for (; i < text.size() && amount < shift; ++i) {
- if (text.at(i) == ' ')
- amount++;
- else if (text.at(i) == '\t')
- amount += tab; // FIXME: take position into consideration
- else
- break;
- }
- removeText(Range(pos, pos + i));
- setPosition(pos);
- }
- endEditBlock();
-
- setPosition(targetPos);
- handleStartOfLine();
- setTargetColumn();
- setDotCommand("%1<<", endLine - beginLine + 1);
+ shiftRegionRight(-repeat);
}
void FakeVimHandler::Private::moveToTargetColumn()
@@ -4339,17 +5622,14 @@ void FakeVimHandler::Private::moveToTargetColumn()
const QTextBlock &bl = block();
//Column column = cursorColumn();
//int logical = logical
- const int maxcol = bl.length() - 2;
+ const int pos = lastPositionInLine(bl.blockNumber() + 1, false);
if (m_targetColumn == -1) {
- setPosition(bl.position() + qMax(0, maxcol));
+ setPosition(pos);
return;
}
- const int physical = logicalToPhysicalColumn(m_targetColumn, bl.text());
+ const int physical = bl.position() + logicalToPhysicalColumn(m_targetColumn, bl.text());
//qDebug() << "CORRECTING COLUMN FROM: " << logical << "TO" << m_targetColumn;
- if (physical >= maxcol)
- setPosition(bl.position() + qMax(0, maxcol));
- else
- setPosition(bl.position() + physical);
+ setPosition(qMin(pos, physical));
}
/* if simple is given:
@@ -4369,16 +5649,49 @@ int FakeVimHandler::Private::charClass(QChar c, bool simple) const
// FIXME: This means that only characters < 256 in the
// ConfigIsKeyword setting are handled properly.
if (c.unicode() < 256) {
- //int old = (c.isLetterOrNumber() || c.unicode() == '_') ? 2
+ //int old = (c.isLetterOrNumber() || c.unicode() == QLatin1Char('_')) ? 2
// : c.isSpace() ? 0 : 1;
//qDebug() << c.unicode() << old << m_charClass[c.unicode()];
return m_charClass[c.unicode()];
}
- if (c.isLetterOrNumber() || c.unicode() == '_')
+ if (c.isLetterOrNumber() || c.unicode() == QLatin1Char('_'))
return 2;
return c.isSpace() ? 0 : 1;
}
+void FakeVimHandler::Private::miniBufferTextEdited(const QString &text, int cursorPos,
+ int anchorPos)
+{
+ if (m_subsubmode != SearchSubSubMode && m_mode != ExMode) {
+ editor()->setFocus();
+ } else if (text.isEmpty()) {
+ // editing cancelled
+ handleDefaultKey(Input(Qt::Key_Escape, Qt::NoModifier, QString()));
+ editor()->setFocus();
+ updateCursorShape();
+ } else {
+ CommandBuffer &cmdBuf = (m_mode == ExMode) ? g.commandBuffer : g.searchBuffer;
+ int pos = qMax(1, cursorPos);
+ int anchor = anchorPos == -1 ? pos : qMax(1, anchorPos);
+ QString buffer = text;
+ // prepend prompt character if missing
+ if (!buffer.startsWith(cmdBuf.prompt())) {
+ buffer.prepend(cmdBuf.prompt());
+ ++pos;
+ ++anchor;
+ }
+ // update command/search buffer
+ cmdBuf.setContents(buffer.mid(1), pos - 1, anchor - 1);
+ if (pos != cursorPos || anchor != anchorPos || buffer != text)
+ emit q->commandBufferChanged(buffer, pos, anchor, 0, q);
+ // update search expression
+ if (m_subsubmode == SearchSubSubMode) {
+ updateFind(false);
+ exportSelection();
+ }
+ }
+}
+
// Helper to parse a-z,A-Z,48-57,_
static int someInt(const QString &str)
{
@@ -4408,36 +5721,93 @@ void FakeVimHandler::Private::setupCharClass()
}
}
-void FakeVimHandler::Private::moveToWordBoundary(bool simple, bool forward, bool changeWord)
+void FakeVimHandler::Private::moveToBoundary(bool simple, bool forward)
{
- int repeat = count();
QTextDocument *doc = document();
- int n = forward ? lastPositionInDocument() : 0;
- int lastClass = -1;
- if (changeWord) {
- lastClass = charClass(characterAtCursor(), simple);
- --repeat;
- if (changeWord && block().length() == 1) // empty line
- --repeat;
- }
- while (repeat >= 0) {
- QChar c = doc->characterAt(position() + (forward ? 1 : -1));
+ QTextCursor tc(doc);
+ tc.setPosition(position());
+ if (forward ? tc.atBlockEnd() : tc.atBlockStart())
+ return;
+
+ QChar c = document()->characterAt(tc.position() + (forward ? -1 : 1));
+ int lastClass = tc.atStart() ? -1 : charClass(c, simple);
+ QTextCursor::MoveOperation op = forward ? Right : Left;
+ while (true) {
+ c = doc->characterAt(tc.position());
int thisClass = charClass(c, simple);
- if (thisClass != lastClass && (lastClass != 0 || changeWord))
- --repeat;
- if (repeat == -1)
+ if (thisClass != lastClass || (forward ? tc.atBlockEnd() : tc.atBlockStart())) {
+ if (tc != cursor())
+ tc.movePosition(forward ? Left : Right);
break;
+ }
lastClass = thisClass;
- if (position() == n)
- break;
- forward ? moveRight() : moveLeft();
- if (changeWord && block().length() == 1) // empty line
+ tc.movePosition(op);
+ }
+ setPosition(tc.position());
+}
+
+void FakeVimHandler::Private::moveToNextBoundary(bool end, int count, bool simple, bool forward)
+{
+ int repeat = count;
+ while (repeat > 0 && !(forward ? atDocumentEnd() : atDocumentStart())) {
+ setPosition(position() + (forward ? 1 : -1));
+ moveToBoundary(simple, forward);
+ if (atBoundary(end, simple))
--repeat;
- if (repeat == -1)
- break;
}
}
+void FakeVimHandler::Private::moveToNextBoundaryStart(int count, bool simple, bool forward)
+{
+ moveToNextBoundary(false, count, simple, forward);
+}
+
+void FakeVimHandler::Private::moveToNextBoundaryEnd(int count, bool simple, bool forward)
+{
+ moveToNextBoundary(true, count, simple, forward);
+}
+
+void FakeVimHandler::Private::moveToBoundaryStart(int count, bool simple, bool forward)
+{
+ moveToNextBoundaryStart(atBoundary(false, simple) ? count - 1 : count, simple, forward);
+}
+
+void FakeVimHandler::Private::moveToBoundaryEnd(int count, bool simple, bool forward)
+{
+ moveToNextBoundaryEnd(atBoundary(true, simple) ? count - 1 : count, simple, forward);
+}
+
+void FakeVimHandler::Private::moveToNextWord(bool end, int count, bool simple, bool forward, bool emptyLines)
+{
+ int repeat = count;
+ while (repeat > 0 && !(forward ? atDocumentEnd() : atDocumentStart())) {
+ setPosition(position() + (forward ? 1 : -1));
+ moveToBoundary(simple, forward);
+ if (atWordBoundary(end, simple) && (emptyLines || !atEmptyLine()) )
+ --repeat;
+ }
+}
+
+void FakeVimHandler::Private::moveToNextWordStart(int count, bool simple, bool forward, bool emptyLines)
+{
+ moveToNextWord(false, count, simple, forward, emptyLines);
+}
+
+void FakeVimHandler::Private::moveToNextWordEnd(int count, bool simple, bool forward, bool emptyLines)
+{
+ moveToNextWord(true, count, simple, forward, emptyLines);
+}
+
+void FakeVimHandler::Private::moveToWordStart(int count, bool simple, bool forward, bool emptyLines)
+{
+ moveToNextWordStart(atWordStart(simple) ? count - 1 : count, simple, forward, emptyLines);
+}
+
+void FakeVimHandler::Private::moveToWordEnd(int count, bool simple, bool forward, bool emptyLines)
+{
+ moveToNextWordEnd(atWordEnd(simple) ? count - 1 : count, simple, forward, emptyLines);
+}
+
bool FakeVimHandler::Private::handleFfTt(QString key)
{
int key0 = key.size() == 1 ? key.at(0).unicode() : 0;
@@ -4480,35 +5850,6 @@ bool FakeVimHandler::Private::handleFfTt(QString key)
return false;
}
-void FakeVimHandler::Private::moveToNextWord(bool simple, bool deleteWord)
-{
- int repeat = count();
- int n = lastPositionInDocument();
- int lastClass = charClass(characterAtCursor(), simple);
- while (true) {
- QChar c = characterAtCursor();
- int thisClass = charClass(c, simple);
- if (thisClass != lastClass && thisClass != 0)
- --repeat;
- if (repeat == 0)
- break;
- lastClass = thisClass;
- moveRight();
- if (deleteWord) {
- if (atBlockEnd())
- --repeat;
- } else {
- if (block().length() == 1) // empty line
- --repeat;
- }
- if (repeat == 0)
- break;
- if (position() == n)
- break;
- }
- setTargetColumn();
-}
-
void FakeVimHandler::Private::moveToMatchingParanthesis()
{
bool moved = false;
@@ -4550,7 +5891,12 @@ int FakeVimHandler::Private::columnsOnScreen() const
int FakeVimHandler::Private::cursorLine() const
{
- return block().blockNumber();
+ return lineForPosition(position()) - 1;
+}
+
+int FakeVimHandler::Private::cursorBlockNumber() const
+{
+ return document()->findBlock(qMin(anchor(), position())).blockNumber();
}
int FakeVimHandler::Private::physicalCursorColumn() const
@@ -4642,10 +5988,48 @@ void FakeVimHandler::Private::scrollUp(int count)
scrollToLine(cursorLine() - cursorLineOnScreen() - count);
}
-int FakeVimHandler::Private::lastPositionInDocument() const
+void FakeVimHandler::Private::alignViewportToCursor(AlignmentFlag align, int line,
+ bool moveToNonBlank)
+{
+ if (line > 0)
+ setPosition(firstPositionInLine(line));
+ if (moveToNonBlank)
+ moveToFirstNonBlankOnLine();
+
+ if (align == Qt::AlignTop)
+ scrollUp(- cursorLineOnScreen());
+ else if (align == Qt::AlignVCenter)
+ scrollUp(linesOnScreen() / 2 - cursorLineOnScreen());
+ else if (align == Qt::AlignBottom)
+ scrollUp(linesOnScreen() - cursorLineOnScreen());
+}
+
+void FakeVimHandler::Private::setCursorPosition(const CursorPosition &p)
+{
+ const int firstLine = firstVisibleLine();
+ const int firstBlock = document()->findBlockByLineNumber(firstLine).blockNumber();
+ const int lastBlock =
+ document()->findBlockByLineNumber(firstLine + linesOnScreen() - 2).blockNumber();
+ bool isLineVisible = firstBlock <= p.line && p.line <= lastBlock;
+ QTextCursor tc = cursor();
+ setCursorPosition(&tc, p);
+ setCursor(tc);
+ if (!isLineVisible)
+ alignViewportToCursor(Qt::AlignVCenter);
+}
+
+void FakeVimHandler::Private::setCursorPosition(QTextCursor *tc, const CursorPosition &p)
+{
+ const int line = qMin(document()->blockCount() - 1, p.line);
+ QTextBlock block = document()->findBlockByNumber(line);
+ const int column = qMin(p.column, block.length() - 1);
+ tc->setPosition(block.position() + column, KeepAnchor);
+}
+
+int FakeVimHandler::Private::lastPositionInDocument(bool ignoreMode) const
{
- QTextBlock block = document()->lastBlock();
- return block.position() + block.length() - 1;
+ return document()->characterCount()
+ - (ignoreMode || isVisualMode() || m_mode == InsertMode || m_mode == ReplaceMode ? 1 : 2);
}
QString FakeVimHandler::Private::selectText(const Range &range) const
@@ -4660,11 +6044,11 @@ QString FakeVimHandler::Private::selectText(const Range &range) const
QTextCursor tc(document());
int firstPos = firstPositionInLine(lineForPosition(range.beginPos));
int lastLine = lineForPosition(range.endPos);
- bool endOfDoc = lastLine == document()->lastBlock().blockNumber() + 1;
- int lastPos = endOfDoc ? lastPositionInDocument() : firstPositionInLine(lastLine + 1);
+ bool endOfDoc = lastLine == lineNumber(document()->lastBlock());
+ int lastPos = endOfDoc ? lastPositionInDocument(true) : firstPositionInLine(lastLine + 1);
tc.setPosition(firstPos, MoveAnchor);
tc.setPosition(lastPos, KeepAnchor);
- return tc.selection().toPlainText() + QString((endOfDoc? "\n" : ""));
+ return tc.selection().toPlainText() + _(endOfDoc? "\n" : "");
}
// FIXME: Performance?
int beginLine = lineForPosition(range.beginPos);
@@ -4679,17 +6063,17 @@ QString FakeVimHandler::Private::selectText(const Range &range) const
}
int len = endColumn - beginColumn + 1;
QString contents;
- QTextBlock block = document()->findBlockByNumber(beginLine - 1);
+ QTextBlock block = document()->findBlockByLineNumber(beginLine - 1);
for (int i = beginLine; i <= endLine && block.isValid(); ++i) {
QString line = block.text();
if (range.rangemode == RangeBlockMode) {
line = line.mid(beginColumn, len);
if (line.size() < len)
- line += QString(len - line.size(), QChar(' '));
+ line += QString(len - line.size(), QLatin1Char(' '));
}
contents += line;
- if (!contents.endsWith('\n'))
- contents += '\n';
+ if (!contents.endsWith(QLatin1Char('\n')))
+ contents += QLatin1Char('\n');
block = block.next();
}
//qDebug() << "SELECTED: " << contents;
@@ -4699,12 +6083,18 @@ QString FakeVimHandler::Private::selectText(const Range &range) const
void FakeVimHandler::Private::yankText(const Range &range, int reg)
{
setRegister(reg, selectText(range), range.rangemode);
+
+ const int lines = document()->findBlock(range.endPos).blockNumber()
+ - document()->findBlock(range.beginPos).blockNumber() + 1;
+ if (lines > 2)
+ showMessage(MessageInfo, FakeVimHandler::tr("%n lines yanked", 0, lines));
}
void FakeVimHandler::Private::transformText(const Range &range,
Transformation transformFunc, const QVariant &extra)
{
QTextCursor tc = cursor();
+ int posAfter = range.beginPos;
switch (range.rangemode) {
case RangeCharMode: {
// This can span multiple lines.
@@ -4713,10 +6103,9 @@ void FakeVimHandler::Private::transformText(const Range &range,
tc.setPosition(range.endPos, KeepAnchor);
TransformationData td(tc.selectedText(), extra);
(this->*transformFunc)(&td);
- tc.removeSelectedText();
tc.insertText(td.to);
endEditBlock();
- return;
+ break;
}
case RangeLineMode:
case RangeLineModeExclusive: {
@@ -4744,10 +6133,10 @@ void FakeVimHandler::Private::transformText(const Range &range,
}
TransformationData td(tc.selectedText(), extra);
(this->*transformFunc)(&td);
- tc.removeSelectedText();
+ posAfter = tc.anchor();
tc.insertText(td.to);
endEditBlock();
- return;
+ break;
}
case RangeBlockAndTailMode:
case RangeBlockMode: {
@@ -4759,7 +6148,7 @@ void FakeVimHandler::Private::transformText(const Range &range,
int endColumn = qMax(column1, column2);
if (range.rangemode == RangeBlockAndTailMode)
endColumn = INT_MAX - 1;
- QTextBlock block = document()->findBlockByNumber(endLine - 1);
+ QTextBlock block = document()->findBlockByLineNumber(endLine - 1);
beginEditBlock();
for (int i = beginLine; i <= endLine && block.isValid(); ++i) {
int bCol = qMin(beginColumn, block.length() - 1);
@@ -4768,13 +6157,16 @@ void FakeVimHandler::Private::transformText(const Range &range,
tc.setPosition(block.position() + eCol, KeepAnchor);
TransformationData td(tc.selectedText(), extra);
(this->*transformFunc)(&td);
- tc.removeSelectedText();
tc.insertText(td.to);
block = block.previous();
}
endEditBlock();
+ break;
}
}
+
+ setPosition(posAfter);
+ setTargetColumn();
}
void FakeVimHandler::Private::insertText(const Register &reg)
@@ -4783,7 +6175,6 @@ void FakeVimHandler::Private::insertText(const Register &reg)
qDebug() << "WRONG INSERT MODE: " << reg.rangemode; return);
setAnchor();
cursor().insertText(reg.contents);
- m_lastChangePosition = cursor().position();
//dump("AFTER INSERT");
}
@@ -4842,7 +6233,13 @@ void FakeVimHandler::Private::replaceByStringTransform(TransformationData *td)
void FakeVimHandler::Private::replaceByCharTransform(TransformationData *td)
{
- td->to = QString(td->from.size(), td->extraData.toChar());
+ // Replace each character but preserve lines.
+ const int len = td->from.size();
+ td->to = QString(len, td->extraData.toChar());
+ for (int i = 0; i < len; ++i) {
+ if (td->from.at(i) == ParagraphSeparator)
+ td->to[i] = ParagraphSeparator;
+ }
}
void FakeVimHandler::Private::pasteText(bool afterCursor)
@@ -4883,12 +6280,14 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
switch (rangeMode) {
case RangeCharMode: {
m_targetColumn = 0;
+ const int pos = position() + 1;
if (pasteAfter && rightDist() > 0)
moveRight();
insertText(text.repeated(count()));
- if (!pasteAfter && atEndOfLine())
+ if (text.contains(QLatin1Char('\n')))
+ setPosition(pos);
+ else
moveLeft();
- moveLeft();
break;
}
case RangeLineMode:
@@ -4899,8 +6298,9 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
else
moveToStartOfLine();
m_targetColumn = 0;
+ bool lastLine = false;
if (pasteAfter) {
- bool lastLine = document()->lastBlock() == this->block();
+ lastLine = document()->lastBlock() == this->block();
if (lastLine) {
tc.movePosition(EndOfLine, MoveAnchor);
tc.insertBlock();
@@ -4908,7 +6308,10 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
moveDown();
}
const int pos = position();
- insertText(text.repeated(count()));
+ if (lastLine)
+ insertText(text.repeated(count()).left(text.size() * count() - 1));
+ else
+ insertText(text.repeated(count()));
setPosition(pos);
moveToFirstNonBlankOnLine();
break;
@@ -4921,7 +6324,7 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
QTextCursor tc = cursor();
const int col = tc.columnNumber();
QTextBlock block = tc.block();
- const QStringList lines = text.split(QChar('\n'));
+ const QStringList lines = text.split(QLatin1Char('\n'));
for (int i = 0; i < lines.size() - 1; ++i) {
if (!block.isValid()) {
tc.movePosition(EndOfDocument);
@@ -4934,7 +6337,7 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
int begin = block.position();
if (col >= length) {
tc.setPosition(begin + length - 1);
- tc.insertText(QString(col - length + 1, QChar(' ')));
+ tc.insertText(QString(col - length + 1, QLatin1Char(' ')));
} else {
tc.setPosition(begin + col);
}
@@ -4956,20 +6359,39 @@ void FakeVimHandler::Private::pasteText(bool afterCursor)
endEditBlock();
}
+void FakeVimHandler::Private::joinLines(int count, bool preserveSpace)
+{
+ int pos = position();
+ const int blockNumber = cursor().blockNumber();
+ for (int i = qMax(count - 2, 0); i >= 0 && blockNumber < document()->blockCount(); --i) {
+ moveBehindEndOfLine();
+ pos = position();
+ setAnchor();
+ moveRight();
+ if (preserveSpace) {
+ removeText(currentRange());
+ } else {
+ while (characterAtCursor() == QLatin1Char(' ') || characterAtCursor() == QLatin1Char('\t'))
+ moveRight();
+ cursor().insertText(QString(QLatin1Char(' ')));
+ }
+ }
+ setPosition(pos);
+}
+
QString FakeVimHandler::Private::lineContents(int line) const
{
- return document()->findBlockByNumber(line - 1).text();
+ return document()->findBlockByLineNumber(line - 1).text();
}
void FakeVimHandler::Private::setLineContents(int line, const QString &contents)
{
- QTextBlock block = document()->findBlockByNumber(line - 1);
+ QTextBlock block = document()->findBlockByLineNumber(line - 1);
QTextCursor tc = cursor();
const int begin = block.position();
const int len = block.length();
tc.setPosition(begin);
tc.setPosition(begin + len - 1, KeepAnchor);
- tc.removeSelectedText();
tc.insertText(contents);
}
@@ -5042,23 +6464,51 @@ int FakeVimHandler::Private::blockBoundary(const QString &left,
return tc2.position() - end.size();
}
+int FakeVimHandler::Private::lineNumber(const QTextBlock &block) const
+{
+ if (block.isVisible())
+ return block.firstLineNumber() + 1;
+
+ // Folded block has line number of the nearest previous visible line.
+ QTextBlock block2 = block;
+ while (block2.isValid() && !block2.isVisible())
+ block2 = block2.previous();
+ return block2.firstLineNumber() + 1;
+}
-int FakeVimHandler::Private::firstPositionInLine(int line) const
+int FakeVimHandler::Private::firstPositionInLine(int line, bool onlyVisibleLines) const
{
- return document()->findBlockByNumber(line - 1).position();
+ QTextBlock block = onlyVisibleLines ? document()->findBlockByLineNumber(line - 1)
+ : document()->findBlockByNumber(line - 1);
+ return block.position();
}
-int FakeVimHandler::Private::lastPositionInLine(int line) const
+int FakeVimHandler::Private::lastPositionInLine(int line, bool onlyVisibleLines) const
{
- QTextBlock block = document()->findBlockByNumber(line - 1);
- return block.position() + block.length() - 1;
+ QTextBlock block;
+ if (onlyVisibleLines) {
+ // respect folds
+ block = document()->findBlockByLineNumber(line);
+ if (block.isValid()) {
+ if (line > 0)
+ block = block.previous();
+ } else {
+ block = document()->lastBlock();
+ }
+ } else {
+ block = document()->findBlockByNumber(line - 1);
+ }
+
+ const int position = block.position() + block.length() - 1;
+ if (block.length() > 1 && !isVisualMode() && m_mode != InsertMode && m_mode != ReplaceMode)
+ return position - 1;
+ return position;
}
int FakeVimHandler::Private::lineForPosition(int pos) const
{
- QTextCursor tc = cursor();
- tc.setPosition(pos);
- return tc.block().blockNumber() + 1;
+ QTextBlock block = document()->findBlock(pos);
+ return lineNumber(block);
}
void FakeVimHandler::Private::toggleVisualMode(VisualMode visualMode)
@@ -5069,33 +6519,28 @@ void FakeVimHandler::Private::toggleVisualMode(VisualMode visualMode)
m_positionPastEnd = false;
m_anchorPastEnd = false;
m_visualMode = visualMode;
+ m_lastVisualMode = visualMode;
const int pos = position();
setAnchorAndPosition(pos, pos);
updateMiniBuffer();
- updateSelection();
}
}
void FakeVimHandler::Private::leaveVisualMode()
{
- if (isVisualMode()) {
- m_lastSelectionCursor = cursor();
- m_lastSelectionMode = m_visualMode;
- int from = m_lastSelectionCursor.anchor();
- int to = m_lastSelectionCursor.position();
- if (from > to)
- qSwap(from, to);
- setMark('<', from);
- setMark('>', to);
- if (isVisualLineMode())
- m_movetype = MoveLineWise;
- else if (isVisualCharMode())
- m_movetype = MoveInclusive;
- }
+ if (!isVisualMode())
+ return;
+
+ setMark(QLatin1Char('<'), mark(QLatin1Char('<')).position);
+ setMark(QLatin1Char('>'), mark(QLatin1Char('>')).position);
+ m_lastVisualModeInverted = anchor() > position();
+ if (isVisualLineMode())
+ m_movetype = MoveLineWise;
+ else if (isVisualCharMode())
+ m_movetype = MoveInclusive;
m_visualMode = NoVisualMode;
updateMiniBuffer();
- updateSelection();
}
QWidget *FakeVimHandler::Private::editor() const
@@ -5105,39 +6550,114 @@ QWidget *FakeVimHandler::Private::editor() const
: static_cast<QWidget *>(m_plaintextedit);
}
-void FakeVimHandler::Private::undo()
+void FakeVimHandler::Private::joinPreviousEditBlock()
+{
+ UNDO_DEBUG("JOIN");
+ if (m_breakEditBlock) {
+ beginEditBlock();
+ } else {
+ if (m_editBlockLevel == 0)
+ m_cursor = cursor();
+ ++m_editBlockLevel;
+ cursor().joinPreviousEditBlock();
+ }
+}
+
+void FakeVimHandler::Private::beginEditBlock(bool rememberPosition)
+{
+ UNDO_DEBUG("BEGIN EDIT BLOCK");
+ if (m_editBlockLevel == 0)
+ m_cursor = cursor();
+ ++m_editBlockLevel;
+ cursor().beginEditBlock();
+ if (rememberPosition)
+ setUndoPosition(false);
+ m_breakEditBlock = false;
+}
+
+void FakeVimHandler::Private::endEditBlock()
+{
+ UNDO_DEBUG("END EDIT BLOCK");
+ QTC_ASSERT(m_editBlockLevel > 0,
+ qDebug() << "beginEditBlock() not called before endEditBlock()!"; return);
+ --m_editBlockLevel;
+ cursor().endEditBlock();
+ if (m_editBlockLevel == 0)
+ setCursor(m_cursor);
+}
+
+char FakeVimHandler::Private::currentModeCode() const
+{
+ if (m_submode != NoSubMode)
+ return ' ';
+ else if (m_mode == ExMode)
+ return 'c';
+ else if (isVisualMode())
+ return 'v';
+ else if (m_mode == CommandMode)
+ return 'n';
+ else
+ return 'i';
+}
+
+void FakeVimHandler::Private::undoRedo(bool undo)
{
// FIXME: That's only an approximaxtion. The real solution might
// be to store marks and old userData with QTextBlock setUserData
// and retrieve them afterward.
- const int current = document()->availableUndoSteps();
- EDITOR(undo());
- const int rev = document()->availableUndoSteps();
- if (current == rev)
- showBlackMessage(FakeVimHandler::tr("Already at oldest change"));
+ QStack<State> &stack = undo ? m_undo : m_redo;
+ QStack<State> &stack2 = undo ? m_redo : m_undo;
+
+ CursorPosition lastPos(cursor());
+ const int current = revision();
+ if (undo)
+ EDITOR(undo());
else
- showBlackMessage(QString());
+ EDITOR(redo());
+ const int rev = revision();
+
+ // rewind/forward to last saved revision
+ while (!stack.empty() && stack.top().revision > rev)
+ stack.pop();
+
+ if (current == rev) {
+ const QString msg = undo ? FakeVimHandler::tr("Already at oldest change")
+ : FakeVimHandler::tr("Already at newest change");
+ showMessage(MessageInfo, msg);
+ return;
+ }
+ clearMessage();
+
+ if (!stack.empty()) {
+ State &state = stack.top();
+ if (state.revision == rev) {
+ m_lastChangePosition = state.position;
+ Marks marks = m_marks;
+ marks.swap(state.marks);
+ updateMarks(marks);
+ m_lastVisualMode = state.lastVisualMode;
+ m_lastVisualModeInverted = state.lastVisualModeInverted;
+ setMark(QLatin1Char('\''), lastPos);
+ setCursorPosition(m_lastChangePosition);
+ setAnchor();
+ state.revision = current;
+ stack2.push(stack.pop());
+ }
+ }
- if (m_undoCursorPosition.contains(rev))
- setPosition(m_undoCursorPosition[rev]);
setTargetColumn();
if (atEndOfLine())
moveLeft();
}
-void FakeVimHandler::Private::redo()
+void FakeVimHandler::Private::undo()
{
- const int current = document()->availableUndoSteps();
- EDITOR(redo());
- const int rev = document()->availableUndoSteps();
- if (rev == current)
- showBlackMessage(FakeVimHandler::tr("Already at newest change"));
- else
- showBlackMessage(QString());
+ undoRedo(true);
+}
- if (m_undoCursorPosition.contains(rev))
- setPosition(m_undoCursorPosition[rev]);
- setTargetColumn();
+void FakeVimHandler::Private::redo()
+{
+ undoRedo(false);
}
void FakeVimHandler::Private::updateCursorShape()
@@ -5155,9 +6675,9 @@ void FakeVimHandler::Private::enterReplaceMode()
m_mode = ReplaceMode;
m_submode = NoSubMode;
m_subsubmode = NoSubSubMode;
- m_commandPrefix.clear();
m_lastInsertion.clear();
- m_lastDeletion.clear();
+ m_oldPosition = position();
+ g.returnToMode = ReplaceMode;
}
void FakeVimHandler::Private::enterInsertMode()
@@ -5165,36 +6685,85 @@ void FakeVimHandler::Private::enterInsertMode()
m_mode = InsertMode;
m_submode = NoSubMode;
m_subsubmode = NoSubSubMode;
- m_commandPrefix.clear();
m_lastInsertion.clear();
- m_lastDeletion.clear();
+ m_oldPosition = position();
+ if (g.returnToMode != InsertMode) {
+ g.returnToMode = InsertMode;
+ // If entering insert mode from command mode, m_targetColumn shouldn't be -1 (end of line).
+ if (m_targetColumn == -1)
+ setTargetColumn();
+ }
+}
+
+void FakeVimHandler::Private::initVisualBlockInsertMode(QChar command)
+{
+ m_visualBlockInsert = true;
+
+ setDotCommand(visualDotCommand() + QString::number(count()) + command);
+
+ leaveVisualMode();
+ const CursorPosition lastAnchor = mark(QLatin1Char('<')).position;
+ const CursorPosition lastPosition = mark(QLatin1Char('>')).position;
+ CursorPosition pos(lastAnchor.line,
+ command == QLatin1Char('A') ? qMax(lastPosition.column, lastAnchor.column)
+ : qMin(lastPosition.column, lastAnchor.column));
+
+ if (command == QLatin1Char('s')) {
+ Range range(position(), anchor(), RangeBlockMode);
+ yankText(range, m_register);
+ removeText(range);
+ }
+
+ setCursorPosition(pos);
}
-void FakeVimHandler::Private::enterCommandMode()
+void FakeVimHandler::Private::enterCommandMode(Mode returnToMode)
{
if (atEndOfLine())
moveLeft();
m_mode = CommandMode;
m_submode = NoSubMode;
m_subsubmode = NoSubSubMode;
- m_commandPrefix.clear();
+ g.returnToMode = returnToMode;
}
-void FakeVimHandler::Private::enterExMode()
+void FakeVimHandler::Private::enterExMode(const QString &contents)
{
+ g.currentMessage.clear();
+ if (isVisualMode())
+ g.commandBuffer.setContents(QString::fromLatin1("'<,'>") + contents, contents.size() + 5);
+ else
+ g.commandBuffer.setContents(contents, contents.size());
m_mode = ExMode;
m_submode = NoSubMode;
m_subsubmode = NoSubSubMode;
- m_commandPrefix = ':';
}
-void FakeVimHandler::Private::recordJump()
+void FakeVimHandler::Private::recordJump(int position)
{
- m_jumpListUndo.append(cursorPosition());
+ CursorPosition pos = position >= 0 ? CursorPosition(document(), position)
+ : CursorPosition(cursor());
+ setMark(QLatin1Char('\''), pos);
+ if (m_jumpListUndo.isEmpty() || m_jumpListUndo.top() != pos)
+ m_jumpListUndo.push(pos);
m_jumpListRedo.clear();
UNDO_DEBUG("jumps: " << m_jumpListUndo);
}
+void FakeVimHandler::Private::jump(int distance)
+{
+ QStack<CursorPosition> &from = (distance > 0) ? m_jumpListRedo : m_jumpListUndo;
+ QStack<CursorPosition> &to = (distance > 0) ? m_jumpListUndo : m_jumpListRedo;
+ int len = qMin(qAbs(distance), from.size());
+ CursorPosition m(cursor());
+ setMark(QLatin1Char('\''), m);
+ for (int i = 0; i < len; ++i) {
+ to.push(m);
+ setCursorPosition(from.top());
+ from.pop();
+ }
+}
+
Column FakeVimHandler::Private::indentation(const QString &line) const
{
int ts = config(ConfigTabStop).toInt();
@@ -5267,43 +6836,150 @@ void FakeVimHandler::Private::handleStartOfLine()
moveToFirstNonBlankOnLine();
}
-void FakeVimHandler::Private::replay(const QString &command, int n)
+void FakeVimHandler::Private::replay(const QString &command)
{
//qDebug() << "REPLAY: " << quoteUnprintable(command);
- for (int i = n; --i >= 0; ) {
- foreach (QChar c, command) {
- //qDebug() << " REPLAY: " << c.unicode();
- handleKey(Input(c));
+ Inputs inputs(command);
+ foreach (Input in, inputs) {
+ if (handleDefaultKey(in) != EventHandled)
+ break;
+ }
+}
+
+QString FakeVimHandler::Private::visualDotCommand() const
+{
+ QTextCursor start(cursor());
+ QTextCursor end(start);
+ end.setPosition(end.anchor());
+
+ QString command;
+
+ if (isVisualCharMode())
+ command = _("v");
+ else if (isVisualLineMode())
+ command = _("V");
+ else if (isVisualBlockMode())
+ command = _("<c-v>");
+ else
+ return QString();
+
+ const int down = qAbs(start.blockNumber() - end.blockNumber());
+ if (down != 0)
+ command.append(QString::fromLatin1("%1j").arg(down));
+
+ const int right = start.positionInBlock() - end.positionInBlock();
+ if (right != 0) {
+ command.append(QString::number(qAbs(right)));
+ command.append(QLatin1Char(right < 0 && isVisualBlockMode() ? 'h' : 'l'));
+ }
+
+ return command;
+}
+
+void FakeVimHandler::Private::selectTextObject(bool simple, bool inner)
+{
+ const int position1 = this->position();
+ const int anchor1 = this->anchor();
+ bool setupAnchor = (position1 == anchor1);
+ bool forward = anchor1 <= position1;
+ const int repeat = count();
+
+ // set anchor if not already set
+ if (setupAnchor) {
+ // Select nothing with 'inner' on empty line.
+ if (inner && atEmptyLine() && repeat == 1) {
+ m_movetype = MoveExclusive;
+ return;
}
+ moveToBoundaryStart(1, simple, false);
+ setAnchor();
+ } else if (forward) {
+ moveRight();
+ if (atEndOfLine())
+ moveRight();
+ } else {
+ moveLeft();
+ if (atBlockStart())
+ moveLeft();
}
+
+ if (inner) {
+ moveToBoundaryEnd(repeat, simple);
+ } else {
+ const int direction = forward ? 1 : -1;
+ for (int i = 0; i < repeat; ++i) {
+ // select leading spaces
+ bool leadingSpace = characterAtCursor().isSpace();
+ if (leadingSpace) {
+ if (forward)
+ moveToNextBoundaryStart(1, simple);
+ else
+ moveToNextBoundaryEnd(1, simple, false);
+ }
+
+ // select word
+ if (forward)
+ moveToWordEnd(1, simple);
+ else
+ moveToWordStart(1, simple, false);
+
+ // select trailing spaces if no leading space
+ if (!leadingSpace && document()->characterAt(position() + direction).isSpace()
+ && !atBlockStart()) {
+ if (forward)
+ moveToNextBoundaryEnd(1, simple);
+ else
+ moveToNextBoundaryStart(1, simple, false);
+ }
+
+ // if there are no trailing spaces in selection select all leading spaces
+ // after previous character
+ if (setupAnchor && (!characterAtCursor().isSpace() || atBlockEnd())) {
+ int min = block().position();
+ int pos = anchor();
+ while (pos >= min && document()->characterAt(--pos).isSpace()) {}
+ if (pos >= min)
+ setAnchorAndPosition(pos + 1, position());
+ }
+
+ if (i + 1 < repeat) {
+ if (forward) {
+ moveRight();
+ if (atEndOfLine())
+ moveRight();
+ } else {
+ moveLeft();
+ if (atBlockStart())
+ moveLeft();
+ }
+ }
+ }
+ }
+
+ if (inner) {
+ m_movetype = MoveInclusive;
+ } else {
+ m_movetype = MoveExclusive;
+ if (isNoVisualMode()) {
+ moveRight();
+ if (atEndOfLine())
+ moveRight();
+ } else if (isVisualLineMode()) {
+ m_visualMode = VisualCharMode;
+ }
+ }
+
+ setTargetColumn();
}
void FakeVimHandler::Private::selectWordTextObject(bool inner)
{
- Q_UNUSED(inner); // FIXME
- m_movetype = MoveExclusive;
- moveToWordBoundary(false, false, true);
- setAnchor();
- // FIXME: Rework the 'anchor' concept.
- //if (isVisualMode())
- // setMark('<', cursor().position());
- moveToWordBoundary(false, true, true);
- setTargetColumn();
- m_movetype = MoveInclusive;
+ selectTextObject(false, inner);
}
void FakeVimHandler::Private::selectWORDTextObject(bool inner)
{
- Q_UNUSED(inner); // FIXME
- m_movetype = MoveExclusive;
- moveToWordBoundary(true, false, true);
- setAnchor();
- // FIXME: Rework the 'anchor' concept.
- //if (isVisualMode())
- // setMark('<', cursor().position());
- moveToWordBoundary(true, true, true);
- setTargetColumn();
- m_movetype = MoveInclusive;
+ selectTextObject(true, inner);
}
void FakeVimHandler::Private::selectSentenceTextObject(bool inner)
@@ -5316,7 +6992,7 @@ void FakeVimHandler::Private::selectParagraphTextObject(bool inner)
Q_UNUSED(inner);
}
-void FakeVimHandler::Private::selectBlockTextObject(bool inner,
+bool FakeVimHandler::Private::selectBlockTextObject(bool inner,
char left, char right)
{
QString sleft = QString(QLatin1Char(left));
@@ -5324,63 +7000,92 @@ void FakeVimHandler::Private::selectBlockTextObject(bool inner,
int p1 = blockBoundary(sleft, sright, false, count());
if (p1 == -1)
- return;
+ return false;
int p2 = blockBoundary(sleft, sright, true, count());
if (p2 == -1)
- return;
+ return false;
- if (inner) {
+ if (inner)
p1 += sleft.size();
+ else
+ p2 -= sright.size() - 2;
+
+ if (isVisualMode())
--p2;
- } else {
- p2 -= sright.size() - 1;
- }
setAnchorAndPosition(p1, p2);
- m_movetype = MoveInclusive;
-}
+ m_movetype = MoveExclusive;
-static bool isSign(const QChar c)
-{
- return c.unicode() == '-' || c.unicode() == '+';
+ return true;
}
-void FakeVimHandler::Private::changeNumberTextObject(bool doIncrement)
+bool FakeVimHandler::Private::changeNumberTextObject(int count)
{
- QTextCursor tc = cursor();
- int pos = tc.position();
- const int n = lastPositionInDocument();
- QTextDocument *doc = document();
- QChar c = doc->characterAt(pos);
- if (!c.isNumber()) {
- if (pos == n || !isSign(c))
- return;
+ const QTextBlock block = this->block();
+ const QString lineText = block.text();
+ const int posMin = cursor().positionInBlock() + 1;
+
+ // find first decimal, hexadecimal or octal number under or after cursor position
+ QRegExp re(_("(0[xX])(0*[0-9a-fA-F]+)|(0)(0*[0-7]+)(?=\\D|$)|(\\d+)"));
+ int pos = 0;
+ while ((pos = re.indexIn(lineText, pos)) != -1 && pos + re.matchedLength() < posMin)
++pos;
- c = doc->characterAt(pos);
- if (!c.isNumber())
- return;
+ if (pos == -1)
+ return false;
+ int len = re.matchedLength();
+ QString prefix = re.cap(1) + re.cap(3);
+ bool hex = prefix.length() >= 2 && (prefix[1].toLower() == QLatin1Char('x'));
+ bool octal = !hex && !prefix.isEmpty();
+ const QString num = hex ? re.cap(2) : octal ? re.cap(4) : re.cap(5);
+
+ // parse value
+ bool ok;
+ int base = hex ? 16 : octal ? 8 : 10;
+ qlonglong value = 0; // decimal value
+ qlonglong uvalue = 0; // hexadecimal or octal value (only unsigned)
+ if (hex || octal)
+ uvalue = num.toULongLong(&ok, base);
+ else
+ value = num.toLongLong(&ok, base);
+ QTC_ASSERT(ok, qDebug() << "Cannot parse number:" << num << "base:" << base; return false);
+
+ // negative decimal number
+ if (!octal && !hex && pos > 0 && lineText[pos - 1] == QLatin1Char('-')) {
+ value = -value;
+ --pos;
+ ++len;
}
- int p1 = pos;
- while (p1 >= 1 && doc->characterAt(p1 - 1).isNumber())
- --p1;
- if (p1 >= 1 && isSign(doc->characterAt(p1 - 1)))
- --p1;
- int p2 = pos;
- while (p2 <= n - 1 && doc->characterAt(p2 + 1).isNumber())
- ++p2;
- ++p2;
- setAnchorAndPosition(p2, p1);
-
- QString orig = selectText(currentRange());
- int value = orig.toInt();
- value = doIncrement ? value + 1 : value - 1;
- QString repl = QString::fromLatin1("%1").arg(value, orig.size(), 10, QLatin1Char('0'));
+
+ // result to string
+ QString repl;
+ if (hex || octal)
+ repl = QString::number(uvalue + count, base);
+ else
+ repl = QString::number(value + count, base);
+
+ // convert hexadecimal number to upper-case if last letter was upper-case
+ if (hex) {
+ const int lastLetter = num.lastIndexOf(QRegExp(_("[a-fA-F]")));
+ if (lastLetter != -1 && num[lastLetter].isUpper())
+ repl = repl.toUpper();
+ }
+
+ // preserve leading zeroes
+ if ((octal || hex) && repl.size() < num.size())
+ prefix.append(QString::fromLatin1("0").repeated(num.size() - repl.size()));
+ repl.prepend(prefix);
+
+ pos += block.position();
+ setUndoPosition();
+ setAnchorAndPosition(pos, pos + len);
replaceText(currentRange(), repl);
- moveLeft();
+ setPosition(pos + repl.size() - 1);
+
+ return true;
}
-void FakeVimHandler::Private::selectQuotedStringTextObject(bool inner,
+bool FakeVimHandler::Private::selectQuotedStringTextObject(bool inner,
const QString &quote)
{
QTextCursor tc = cursor();
@@ -5391,49 +7096,87 @@ void FakeVimHandler::Private::selectQuotedStringTextObject(bool inner,
while (tc2 <= tc) {
tc1 = document()->find(quote, tc2);
if (tc1.isNull() || tc1.anchor() > tc.position())
- return;
+ return false;
tc2 = document()->find(quote, tc1);
if (tc2.isNull())
- return;
+ return false;
}
int p1 = tc1.position();
int p2 = tc2.position();
if (inner) {
- p2 -= sz + 1;
+ p2 = qMax(p1, p2 - sz);
if (document()->characterAt(p1) == ParagraphSeparator)
++p1;
} else {
p1 -= sz;
- p2 -= sz;
+ p2 -= sz - 1;
}
+ if (isVisualMode())
+ --p2;
+
setAnchorAndPosition(p1, p2);
- m_movetype = MoveInclusive;
+ m_movetype = MoveExclusive;
+
+ return true;
}
-int FakeVimHandler::Private::mark(int code) const
+Mark FakeVimHandler::Private::mark(QChar code) const
{
- // FIXME: distinguish local and global marks.
- //qDebug() << "MARK: " << code << m_marks.value(code, -1) << m_marks;
if (isVisualMode()) {
- if (code == '<')
- return position();
- if (code == '>')
- return anchor();
+ if (code == QLatin1Char('<'))
+ return CursorPosition(document(), qMin(anchor(), position()));
+ if (code == QLatin1Char('>'))
+ return CursorPosition(document(), qMax(anchor(), position()));
}
- if (code == '.')
+ if (code == QLatin1Char('.'))
return m_lastChangePosition;
- QTextCursor tc = m_marks.value(code);
- return tc.isNull() ? -1 : tc.position();
+ if (code.isUpper())
+ return g.marks.value(code);
+
+ return m_marks.value(code);
}
-void FakeVimHandler::Private::setMark(int code, int position)
+void FakeVimHandler::Private::setMark(QChar code, CursorPosition position)
{
- // FIXME: distinguish local and global marks.
- QTextCursor tc = cursor();
- tc.setPosition(position, MoveAnchor);
- m_marks[code] = tc;
+ if (code.isUpper())
+ g.marks[code] = Mark(position, m_currentFileName);
+ else
+ m_marks[code] = Mark(position);
+}
+
+bool FakeVimHandler::Private::jumpToMark(QChar mark, bool backTickMode)
+{
+ Mark m = this->mark(mark);
+ if (!m.isValid()) {
+ showMessage(MessageError, msgMarkNotSet(mark));
+ return false;
+ }
+ if (!m.isLocal(m_currentFileName)) {
+ emit q->jumpToGlobalMark(mark, backTickMode, m.fileName);
+ return false;
+ }
+
+ if (mark == QLatin1Char('\'') && !m_jumpListUndo.isEmpty())
+ m_jumpListUndo.pop();
+ recordJump();
+ setCursorPosition(m.position);
+ if (!backTickMode)
+ moveToFirstNonBlankOnLine();
+ if (m_submode == NoSubMode)
+ setAnchor();
+ setTargetColumn();
+
+ return true;
+}
+
+void FakeVimHandler::Private::updateMarks(const Marks &newMarks)
+{
+ for (MarksIterator it(newMarks); it.hasNext(); ) {
+ it.next();
+ m_marks[it.key()] = it.value();
+ }
}
RangeMode FakeVimHandler::Private::registerRangeMode(int reg) const
@@ -5458,7 +7201,7 @@ RangeMode FakeVimHandler::Private::registerRangeMode(int reg) const
// - return RangeLineMode if text ends with new line char,
// - return RangeCharMode otherwise.
QString text = clipboard->text(mode);
- return (text.endsWith('\n') || text.endsWith('\r')) ? RangeLineMode : RangeCharMode;
+ return (text.endsWith(QLatin1Char('\n')) || text.endsWith(QLatin1Char('\r'))) ? RangeLineMode : RangeCharMode;
}
return g.registers[reg].rangemode;
@@ -5470,13 +7213,17 @@ void FakeVimHandler::Private::setRegister(int reg, const QString &contents, Rang
bool copyToSelection;
getRegisterType(reg, &copyToClipboard, &copyToSelection);
+ QString contents2 = contents;
+ if (mode == RangeLineMode && !contents2.endsWith(QLatin1Char('\n')))
+ contents2.append(QLatin1Char('\n'));
+
if (copyToClipboard || copyToSelection) {
if (copyToClipboard)
- setClipboardData(contents, mode, QClipboard::Clipboard);
+ setClipboardData(contents2, mode, QClipboard::Clipboard);
if (copyToSelection)
- setClipboardData(contents, mode, QClipboard::Selection);
+ setClipboardData(contents2, mode, QClipboard::Selection);
} else {
- g.registers[reg].contents = contents;
+ g.registers[reg].contents = contents2;
g.registers[reg].rangemode = mode;
}
}
@@ -5503,13 +7250,13 @@ void FakeVimHandler::Private::getRegisterType(int reg, bool *isClipboard, bool *
bool clipboard = false;
bool selection = false;
- if (reg == '"') {
- QStringList list = config(ConfigClipboard).toString().split(',');
- clipboard = list.contains(QString("unnamedplus"));
- selection = list.contains(QString("unnamed"));
- } else if (reg == '+') {
+ if (reg == QLatin1Char('"')) {
+ QStringList list = config(ConfigClipboard).toString().split(QLatin1Char(','));
+ clipboard = list.contains(_("unnamedplus"));
+ selection = list.contains(_("unnamed"));
+ } else if (reg == QLatin1Char('+')) {
clipboard = true;
- } else if (reg == '*') {
+ } else if (reg == QLatin1Char('*')) {
selection = true;
}
@@ -5567,10 +7314,8 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
}
if (active && ev->type() == QEvent::MouseButtonPress) {
QMouseEvent *mev = static_cast<QMouseEvent *>(ev);
- if (mev->button() == Qt::LeftButton) {
+ if (mev->button() == Qt::LeftButton)
d->m_visualMode = NoVisualMode;
- d->updateSelection();
- }
}
return QObject::eventFilter(ob, ev);
}
@@ -5592,10 +7337,11 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
int key = commitString.size() == 1 ? commitString.at(0).unicode() : 0;
QKeyEvent kev(QEvent::KeyPress, key, Qt::KeyboardModifiers(), commitString);
EventResult res = d->handleEvent(&kev);
- return res == EventHandled;
+ return res == EventHandled || res == EventCancelled;
}
- if (active && ev->type() == QEvent::KeyPress && ob == d->editor()) {
+ if (active && ev->type() == QEvent::KeyPress &&
+ (ob == d->editor() || (d->m_mode == ExMode || d->m_subsubmode == SearchSubSubMode))) {
QKeyEvent *kev = static_cast<QKeyEvent *>(ev);
KEY_DEBUG("KEYPRESS" << kev->key() << kev->text() << QChar(kev->key()));
EventResult res = d->handleEvent(kev);
@@ -5605,7 +7351,7 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
//KEY_DEBUG("HANDLED CODE:" << res);
//return res != EventPassedToCore;
//return true;
- return res == EventHandled;
+ return res == EventHandled || res == EventCancelled;
}
if (active && ev->type() == QEvent::ShortcutOverride && ob == d->editor()) {
@@ -5619,9 +7365,8 @@ bool FakeVimHandler::eventFilter(QObject *ob, QEvent *ev)
return true;
}
- if (active && ev->type() == QEvent::FocusIn && ob == d->editor()) {
- d->stopIncrementalFind();
- }
+ if (active && ev->type() == QEvent::FocusIn && ob == d->editor())
+ d->focus();
return QObject::eventFilter(ob, ev);
}
@@ -5643,23 +7388,25 @@ void FakeVimHandler::restoreWidget(int tabSize)
void FakeVimHandler::handleCommand(const QString &cmd)
{
+ d->enterFakeVim();
d->handleCommand(cmd);
+ d->leaveFakeVim();
}
void FakeVimHandler::handleReplay(const QString &keys)
{
- d->replay(keys, 1);
+ d->enterFakeVim();
+ d->replay(keys);
+ d->leaveFakeVim();
}
void FakeVimHandler::handleInput(const QString &keys)
{
- Mode oldMode = d->m_mode;
- d->m_mode = CommandMode;
- Inputs inputs;
- inputs.parseFrom(keys);
+ Inputs inputs(keys);
+ d->enterFakeVim();
foreach (const Input &input, inputs)
d->handleKey(input);
- d->m_mode = oldMode;
+ d->leaveFakeVim();
}
void FakeVimHandler::setCurrentFileName(const QString &fileName)
@@ -5672,14 +7419,9 @@ QString FakeVimHandler::currentFileName() const
return d->m_currentFileName;
}
-void FakeVimHandler::showBlackMessage(const QString &msg)
-{
- d->showBlackMessage(msg);
-}
-
-void FakeVimHandler::showRedMessage(const QString &msg)
+void FakeVimHandler::showMessage(MessageLevel level, const QString &msg)
{
- d->showRedMessage(msg);
+ d->showMessage(level, msg);
}
QWidget *FakeVimHandler::widget()
@@ -5705,6 +7447,26 @@ QString FakeVimHandler::tabExpand(int n) const
return d->tabExpand(n);
}
+void FakeVimHandler::miniBufferTextEdited(const QString &text, int cursorPos, int anchorPos)
+{
+ d->miniBufferTextEdited(text, cursorPos, anchorPos);
+}
+
+void FakeVimHandler::setTextCursorPosition(int position)
+{
+ int pos = qMax(0, qMin(position, d->lastPositionInDocument()));
+ if (d->isVisualMode())
+ d->setPosition(pos);
+ else
+ d->setAnchorAndPosition(pos, pos);
+ d->setTargetColumn();
+}
+
+bool FakeVimHandler::jumpToLocalMark(QChar mark, bool backTickMode)
+{
+ return d->jumpToMark(mark, backTickMode);
+}
+
} // namespace Internal
} // namespace FakeVim
diff --git a/src/plugins/fakevim/fakevimhandler.h b/src/plugins/fakevim/fakevimhandler.h
index f4fb225613..8999747530 100644
--- a/src/plugins/fakevim/fakevimhandler.h
+++ b/src/plugins/fakevim/fakevimhandler.h
@@ -67,7 +67,6 @@ struct ExCommand
const Range &range = Range());
bool matches(const QString &min, const QString &full) const;
- void setContentsFromLine(const QString &line);
QString cmd;
bool hasBang;
@@ -76,6 +75,17 @@ struct ExCommand
int count;
};
+// message levels sorted by severity
+enum MessageLevel
+{
+ MessageMode, // show current mode (format "-- %1 --")
+ MessageCommand, // show last Ex command or search
+ MessageInfo, // result of a command
+ MessageWarning, // warning
+ MessageError, // error
+ MessageShowCmd // partial command
+};
+
class FakeVimHandler : public QObject
{
Q_OBJECT
@@ -93,8 +103,7 @@ public slots:
void setCurrentFileName(const QString &fileName);
QString currentFileName() const;
- void showBlackMessage(const QString &msg);
- void showRedMessage(const QString &msg);
+ void showMessage(MessageLevel level, const QString &msg);
// This executes an "ex" style command taking context
// information from the current widget.
@@ -113,11 +122,20 @@ public slots:
int logicalIndentation(const QString &line) const;
QString tabExpand(int n) const;
+ void miniBufferTextEdited(const QString &text, int cursorPos, int anchorPos);
+
+ // Set text cursor position. Keeps anchor if in visual mode.
+ void setTextCursorPosition(int position);
+
+ bool jumpToLocalMark(QChar mark, bool backTickMode);
+
signals:
- void commandBufferChanged(const QString &msg, int pos);
+ void commandBufferChanged(const QString &msg, int cursorPos,
+ int anchorPos, int messageLevel, QObject *eventFilter);
void statusDataChanged(const QString &msg);
void extraInformationChanged(const QString &msg);
void selectionChanged(const QList<QTextEdit::ExtraSelection> &selection);
+ void highlightMatches(const QString &needle);
void writeAllRequested(QString *error);
void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
void checkForElectricCharacter(bool *result, QChar c);
@@ -130,6 +148,11 @@ signals:
void handleExCommandRequested(bool *handled, const ExCommand &cmd);
void requestSetBlockSelection(bool on);
void requestHasBlockSelection(bool *on);
+ void foldToggle(int depth);
+ void foldAll(bool fold);
+ void fold(int depth, bool fold);
+ void foldGoTo(int count, bool current);
+ void jumpToGlobalMark(QChar mark, bool backTickMode, const QString &fileName);
public:
class Private;
diff --git a/src/plugins/fakevim/fakevimoptions.ui b/src/plugins/fakevim/fakevimoptions.ui
index 0bfcb92342..f8275b8aca 100644
--- a/src/plugins/fakevim/fakevimoptions.ui
+++ b/src/plugins/fakevim/fakevimoptions.ui
@@ -7,10 +7,10 @@
<x>0</x>
<y>0</y>
<width>513</width>
- <height>449</height>
+ <height>464</height>
</rect>
</property>
- <layout class="QVBoxLayout" name="verticalLayout">
+ <layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QCheckBox" name="checkBoxUseFakeVim">
<property name="text">
@@ -23,14 +23,14 @@
<property name="title">
<string>Vim Behavior</string>
</property>
- <property name="checkable">
- <bool>false</bool>
- </property>
<layout class="QGridLayout" name="gridLayout">
- <item row="2" column="2">
- <widget class="QCheckBox" name="checkBoxSmartCase">
+ <item row="5" column="2">
+ <widget class="QCheckBox" name="checkBoxPassControlKey">
+ <property name="toolTip">
+ <string>Pass key sequences like Ctrl-S to Qt Creator core instead of interpreting them in FakeVim. This gives easier access to Qt Creator core functionality at the price of losing some features of FakeVim.</string>
+ </property>
<property name="text">
- <string>Use smartcase</string>
+ <string>Pass control key</string>
</property>
</widget>
</item>
@@ -41,20 +41,17 @@
</property>
</widget>
</item>
- <item row="4" column="2">
- <widget class="QCheckBox" name="checkBoxPassControlKey">
- <property name="toolTip">
- <string>Pass key sequences like Ctrl-S to Qt Creator core instead of interpreting them in FakeVim. This gives easier access to Qt Creator core functionality at the price of losing some features of FakeVim.</string>
- </property>
+ <item row="5" column="0" colspan="2">
+ <widget class="QCheckBox" name="checkBoxIncSearch">
<property name="text">
- <string>Pass control key</string>
+ <string>Incremental search</string>
</property>
</widget>
</item>
- <item row="5" column="0" colspan="2">
- <widget class="QCheckBox" name="checkBoxIncSearch">
+ <item row="0" column="2">
+ <widget class="QCheckBox" name="checkBoxStartOfLine">
<property name="text">
- <string>Incremental search</string>
+ <string>Start of line</string>
</property>
</widget>
</item>
@@ -65,31 +62,27 @@
</property>
</widget>
</item>
- <item row="11" column="0" colspan="3">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QPushButton" name="pushButtonCopyTextEditorSettings">
- <property name="text">
- <string>Copy Text Editor Settings</string>
- </property>
- </widget>
- </item>
+ <item row="0" column="0" colspan="2">
+ <widget class="QCheckBox" name="checkBoxAutoIndent">
+ <property name="text">
+ <string>Automatic indentation</string>
+ </property>
+ </widget>
+ </item>
+ <item row="8" column="1" colspan="2">
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
- <widget class="QPushButton" name="pushButtonSetQtStyle">
- <property name="text">
- <string>Set Qt Style</string>
+ <widget class="QSpinBox" name="spinBoxTabStop">
+ <property name="minimum">
+ <number>1</number>
</property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="pushButtonSetPlainStyle">
- <property name="text">
- <string>Set Plain Style</string>
+ <property name="maximum">
+ <number>80</number>
</property>
</widget>
</item>
<item>
- <spacer name="horizontalSpacer">
+ <spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
@@ -103,7 +96,24 @@
</item>
</layout>
</item>
- <item row="7" column="0">
+ <item row="9" column="0">
+ <widget class="QLabel" name="labelBackspace">
+ <property name="text">
+ <string>Backspace:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="9" column="1" colspan="2">
+ <widget class="QLineEdit" name="lineEditBackspace"/>
+ </item>
+ <item row="10" column="0">
+ <widget class="QLabel" name="labelIsKeyword">
+ <property name="text">
+ <string>Keyword characters:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="8" column="0">
<widget class="QLabel" name="labelTabulator">
<property name="toolTip">
<string>Vim tabstop option</string>
@@ -113,20 +123,31 @@
</property>
</widget>
</item>
- <item row="6" column="1" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item row="12" column="0" colspan="3">
+ <layout class="QHBoxLayout" name="horizontalLayout">
<item>
- <widget class="QSpinBox" name="spinBoxShiftWidth">
- <property name="minimum">
- <number>1</number>
+ <widget class="QPushButton" name="pushButtonCopyTextEditorSettings">
+ <property name="text">
+ <string>Copy Text Editor Settings</string>
</property>
- <property name="maximum">
- <number>80</number>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="pushButtonSetQtStyle">
+ <property name="text">
+ <string>Set Qt Style</string>
</property>
</widget>
</item>
<item>
- <spacer name="horizontalSpacer_2">
+ <widget class="QPushButton" name="pushButtonSetPlainStyle">
+ <property name="text">
+ <string>Set Plain Style</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
@@ -140,31 +161,24 @@
</item>
</layout>
</item>
- <item row="3" column="2">
- <widget class="QCheckBox" name="checkBoxShowMarks">
- <property name="text">
- <string>Show position of text marks</string>
- </property>
- </widget>
- </item>
- <item row="1" column="2">
- <widget class="QCheckBox" name="checkBoxUseCoreSearch">
+ <item row="7" column="0">
+ <widget class="QLabel" name="labelShiftWidth">
<property name="text">
- <string>Use search dialog</string>
+ <string>Shift width:</string>
</property>
</widget>
</item>
- <item row="9" column="0">
- <widget class="QLabel" name="labelIsKeyword">
+ <item row="2" column="0" colspan="2">
+ <widget class="QCheckBox" name="checkBoxExpandTab">
<property name="text">
- <string>Keyword characters:</string>
+ <string>Expand tabulators</string>
</property>
</widget>
</item>
- <item row="0" column="0" colspan="2">
- <widget class="QCheckBox" name="checkBoxAutoIndent">
+ <item row="4" column="2">
+ <widget class="QCheckBox" name="checkBoxShowMarks">
<property name="text">
- <string>Automatic indentation</string>
+ <string>Show position of text marks</string>
</property>
</widget>
</item>
@@ -175,17 +189,10 @@
</property>
</widget>
</item>
- <item row="8" column="0">
- <widget class="QLabel" name="labelBackspace">
- <property name="text">
- <string>Backspace:</string>
- </property>
- </widget>
- </item>
- <item row="8" column="1" colspan="2">
- <widget class="QLineEdit" name="lineEditBackspace"/>
+ <item row="10" column="1" colspan="2">
+ <widget class="QLineEdit" name="lineEditIsKeyword"/>
</item>
- <item row="10" column="0">
+ <item row="11" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
@@ -201,10 +208,31 @@
</property>
</spacer>
</item>
+ <item row="1" column="2">
+ <widget class="QCheckBox" name="checkBoxUseCoreSearch">
+ <property name="text">
+ <string>Use search dialog</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="2">
+ <widget class="QCheckBox" name="checkBoxSmartCase">
+ <property name="text">
+ <string>Use smartcase</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="2">
+ <widget class="QCheckBox" name="checkBoxWrapScan">
+ <property name="text">
+ <string>Use wrapscan</string>
+ </property>
+ </widget>
+ </item>
<item row="7" column="1" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
- <widget class="QSpinBox" name="spinBoxTabStop">
+ <widget class="QSpinBox" name="spinBoxShiftWidth">
<property name="minimum">
<number>1</number>
</property>
@@ -214,7 +242,7 @@
</widget>
</item>
<item>
- <spacer name="horizontalSpacer_3">
+ <spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
@@ -228,31 +256,14 @@
</item>
</layout>
</item>
- <item row="9" column="1" colspan="2">
- <widget class="QLineEdit" name="lineEditIsKeyword"/>
- </item>
- <item row="2" column="0" colspan="2">
- <widget class="QCheckBox" name="checkBoxExpandTab">
- <property name="text">
- <string>Expand tabulators</string>
- </property>
- </widget>
- </item>
<item row="6" column="0">
- <widget class="QLabel" name="labelShiftWidth">
+ <widget class="QCheckBox" name="checkBoxShowCmd">
<property name="text">
- <string>Shift width:</string>
+ <string>Show partial command</string>
</property>
</widget>
</item>
- <item row="0" column="2">
- <widget class="QCheckBox" name="checkBoxStartOfLine">
- <property name="text">
- <string>Start of line</string>
- </property>
- </widget>
- </item>
- <item row="5" column="2">
+ <item row="6" column="2">
<widget class="QCheckBox" name="checkBoxReadVimRc">
<property name="text">
<string>Read .vimrc</string>
@@ -277,6 +288,29 @@
</item>
</layout>
</widget>
+ <tabstops>
+ <tabstop>checkBoxUseFakeVim</tabstop>
+ <tabstop>checkBoxAutoIndent</tabstop>
+ <tabstop>checkBoxSmartIndent</tabstop>
+ <tabstop>checkBoxExpandTab</tabstop>
+ <tabstop>checkBoxSmartTab</tabstop>
+ <tabstop>checkBoxHlSearch</tabstop>
+ <tabstop>checkBoxIncSearch</tabstop>
+ <tabstop>checkBoxShowCmd</tabstop>
+ <tabstop>checkBoxStartOfLine</tabstop>
+ <tabstop>checkBoxUseCoreSearch</tabstop>
+ <tabstop>checkBoxSmartCase</tabstop>
+ <tabstop>checkBoxWrapScan</tabstop>
+ <tabstop>checkBoxShowMarks</tabstop>
+ <tabstop>checkBoxPassControlKey</tabstop>
+ <tabstop>spinBoxShiftWidth</tabstop>
+ <tabstop>spinBoxTabStop</tabstop>
+ <tabstop>lineEditBackspace</tabstop>
+ <tabstop>lineEditIsKeyword</tabstop>
+ <tabstop>pushButtonCopyTextEditorSettings</tabstop>
+ <tabstop>pushButtonSetQtStyle</tabstop>
+ <tabstop>pushButtonSetPlainStyle</tabstop>
+ </tabstops>
<resources/>
<connections/>
</ui>
diff --git a/src/plugins/fakevim/fakevimplugin.cpp b/src/plugins/fakevim/fakevimplugin.cpp
index 1254208cc5..b172cec5c2 100644
--- a/src/plugins/fakevim/fakevimplugin.cpp
+++ b/src/plugins/fakevim/fakevimplugin.cpp
@@ -69,6 +69,7 @@
#include <find/findplugin.h>
#include <find/textfindconstants.h>
+#include <find/ifindsupport.h>
#include <utils/qtcassert.h>
#include <utils/savedaction.h>
@@ -77,12 +78,15 @@
#include <cpptools/cpptoolsconstants.h>
+#include <extensionsystem/pluginmanager.h>
+
#include <QAbstractTableModel>
#include <QDebug>
#include <QFile>
#include <QtPlugin>
#include <QObject>
#include <QSettings>
+#include <QStackedWidget>
#include <QTextStream>
#include <QDesktopServices>
@@ -107,50 +111,115 @@ const char SETTINGS_CATEGORY_FAKEVIM_ICON[] = ":/core/images/category_fakevim.pn
const char SETTINGS_ID[] = "A.General";
const char SETTINGS_EX_CMDS_ID[] = "B.ExCommands";
const char SETTINGS_USER_CMDS_ID[] = "C.UserCommands";
+typedef QLatin1String _;
-class MiniBuffer : public QLabel
+class MiniBuffer : public QStackedWidget
{
Q_OBJECT
public:
- void setContents(const QString &contents, int cursorPos)
+ MiniBuffer() : m_label(new QLabel(this)), m_edit(new QLineEdit(this)), m_eventFilter(0)
{
- QString msg = contents;
- if (cursorPos != -1)
- msg = contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
- setText(" " + msg);
+ m_edit->installEventFilter(this);
+ connect(m_edit, SIGNAL(textEdited(QString)), SLOT(changed()));
+ connect(m_edit, SIGNAL(cursorPositionChanged(int,int)), SLOT(changed()));
+ connect(m_edit, SIGNAL(selectionChanged()), SLOT(changed()));
+ m_label->setTextInteractionFlags(Qt::TextSelectableByMouse);
+
+ addWidget(m_label);
+ addWidget(m_edit);
}
-};
-class MiniBuffer1 : public QLineEdit
-{
- Q_OBJECT
+ void setContents(const QString &contents, int cursorPos, int anchorPos,
+ int messageLevel, QObject *eventFilter)
+ {
+ if (cursorPos != -1) {
+ m_edit->blockSignals(true);
+ m_label->clear();
+ m_edit->setText(contents);
+ if (anchorPos != -1 && anchorPos != cursorPos)
+ m_edit->setSelection(anchorPos, cursorPos - anchorPos);
+ else
+ m_edit->setCursorPosition(cursorPos);
+ m_edit->blockSignals(false);
+ setCurrentWidget(m_edit);
+ m_edit->setFocus();
+ } else if (contents.isEmpty() && messageLevel != MessageShowCmd) {
+ hide();
+ } else {
+ show();
+ m_label->setText(messageLevel == MessageMode ? _("-- ") + contents + _(" --") : contents);
+
+ QString css;
+ if (messageLevel == MessageError) {
+ css = _("border:1px solid rgba(255,255,255,150);"
+ "background-color:rgba(255,0,0,100);");
+ } else if (messageLevel == MessageWarning) {
+ css = _("border:1px solid rgba(255,255,255,120);"
+ "background-color:rgba(255,255,0,20);");
+ } else if (messageLevel == MessageShowCmd) {
+ css = _("border:1px solid rgba(255,255,255,120);"
+ "background-color:rgba(100,255,100,30);");
+ }
+ m_label->setStyleSheet(QString::fromLatin1(
+ "*{border-radius:2px;padding-left:4px;padding-right:4px;%1}").arg(css));
-public:
- MiniBuffer1()
+ if (m_edit->hasFocus())
+ emit edited(QString(), -1, -1);
+
+ setCurrentWidget(m_label);
+ }
+
+ if (m_eventFilter != eventFilter) {
+ if (m_eventFilter != 0) {
+ m_edit->removeEventFilter(m_eventFilter);
+ disconnect(SIGNAL(edited(QString,int,int)));
+ }
+ if (eventFilter != 0) {
+ m_edit->installEventFilter(eventFilter);
+ connect(this, SIGNAL(edited(QString,int,int)),
+ eventFilter, SLOT(miniBufferTextEdited(QString,int,int)));
+ }
+ m_eventFilter = eventFilter;
+ }
+ }
+
+ QSize sizeHint() const
{
- setFrame(false);
+ QSize size = QWidget::sizeHint();
+ // reserve maximal width for line edit widget
+ return currentWidget() == m_edit ? QSize(maximumWidth(), size.height()) : size;
}
- void showEvent(QShowEvent *ev)
+
+signals:
+ void edited(const QString &text, int cursorPos, int anchorPos);
+
+private slots:
+ void changed()
{
- QLineEdit::showEvent(ev);
- QColor color = Qt::black;
- QPalette pal = parentWidget()->palette();
- pal.setBrush(QPalette::All, QPalette::WindowText, color);
- pal.setBrush(QPalette::All, QPalette::ButtonText, color);
- pal.setBrush(QPalette::All, QPalette::Foreground, color);
- pal.setBrush(QPalette::All, QPalette::Background, color);
- //color.setAlpha(100);
- //pal.setBrush(QPalette::Disabled, QPalette::WindowText, color);
- //pal.setBrush(QPalette::Disabled, QPalette::ButtonText, color);
- //pal.setBrush(QPalette::Disabled, QPalette::Foreground, color);
- setPalette(pal);
+ const int cursorPos = m_edit->cursorPosition();
+ int anchorPos = m_edit->selectionStart();
+ if (anchorPos == cursorPos)
+ anchorPos = cursorPos + m_edit->selectedText().length();
+ emit edited(m_edit->text(), cursorPos, anchorPos);
}
- void setContents(const QString &contents, int cursorPos)
+
+ bool eventFilter(QObject *ob, QEvent *ev)
{
- setText(contents);
- setCursorPosition(cursorPos);
+ // cancel editing on escape
+ if (m_eventFilter != 0 && ob == m_edit && ev->type() == QEvent::ShortcutOverride
+ && static_cast<QKeyEvent*>(ev)->key() == Qt::Key_Escape) {
+ emit edited(QString(), -1, -1);
+ ev->accept();
+ return true;
+ }
+ return false;
}
+
+private:
+ QLabel *m_label;
+ QLineEdit *m_edit;
+ QObject *m_eventFilter;
};
///////////////////////////////////////////////////////////////////////
@@ -161,7 +230,6 @@ public:
typedef QMap<QString, QRegExp> ExCommandMap;
typedef QMap<int, QString> UserCommandMap;
-typedef QLatin1String _;
class FakeVimOptionPage : public IOptionsPage
{
@@ -170,9 +238,9 @@ class FakeVimOptionPage : public IOptionsPage
public:
FakeVimOptionPage()
{
- setId(_(SETTINGS_ID));
+ setId(SETTINGS_ID);
setDisplayName(tr("General"));
- setCategory(_(SETTINGS_CATEGORY));
+ setCategory(SETTINGS_CATEGORY);
setDisplayCategory(tr("FakeVim"));
setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
}
@@ -231,12 +299,18 @@ QWidget *FakeVimOptionPage::createPage(QWidget *parent)
m_ui.checkBoxAutoIndent);
m_group.insert(theFakeVimSetting(ConfigSmartIndent),
m_ui.checkBoxSmartIndent);
+
m_group.insert(theFakeVimSetting(ConfigIncSearch),
m_ui.checkBoxIncSearch);
m_group.insert(theFakeVimSetting(ConfigUseCoreSearch),
m_ui.checkBoxUseCoreSearch);
m_group.insert(theFakeVimSetting(ConfigSmartCase),
m_ui.checkBoxSmartCase);
+ m_group.insert(theFakeVimSetting(ConfigWrapScan),
+ m_ui.checkBoxWrapScan);
+
+ m_group.insert(theFakeVimSetting(ConfigShowCmd),
+ m_ui.checkBoxShowCmd);
connect(m_ui.pushButtonCopyTextEditorSettings, SIGNAL(clicked()),
SLOT(copyTextEditorSettings()));
@@ -331,9 +405,9 @@ public:
FakeVimExCommandsPage(FakeVimPluginPrivate *q)
: m_q(q)
{
- setId(_(SETTINGS_EX_CMDS_ID));
+ setId(SETTINGS_EX_CMDS_ID);
setDisplayName(tr("Ex Command Mapping"));
- setCategory(_(SETTINGS_CATEGORY));
+ setCategory(SETTINGS_CATEGORY);
setDisplayCategory(tr("FakeVim"));
setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
}
@@ -553,9 +627,9 @@ public:
FakeVimUserCommandsPage(FakeVimPluginPrivate *q)
: m_q(q)
{
- setId(_(SETTINGS_USER_CMDS_ID));
+ setId(SETTINGS_USER_CMDS_ID);
setDisplayName(tr("User Command Mapping"));
- setCategory(_(SETTINGS_CATEGORY));
+ setCategory(SETTINGS_CATEGORY);
setDisplayCategory(tr("FakeVim"));
setCategoryIcon(_(SETTINGS_CATEGORY_FAKEVIM_ICON));
}
@@ -786,17 +860,25 @@ private slots:
void windowCommand(int key);
void find(bool reverse);
void findNext(bool reverse);
+ void foldToggle(int depth);
+ void foldAll(bool fold);
+ void fold(int depth, bool fold);
+ void foldGoTo(int count, bool current);
+ void jumpToGlobalMark(QChar mark, bool backTickMode, const QString &fileName);
void showSettingsDialog();
void maybeReadVimRc();
void setBlockSelection(bool);
void hasBlockSelection(bool*);
- void showCommandBuffer(const QString &contents, int cursorPos);
+ void resetCommandBuffer();
+ void showCommandBuffer(const QString &contents, int cursorPos, int anchorPos,
+ int messageLevel, QObject *eventFilter);
void showExtraInformation(const QString &msg);
void changeSelection(const QList<QTextEdit::ExtraSelection> &selections);
+ void highlightMatches(const QString &needle);
void moveToMatchingParenthesis(bool *moved, bool *forward, QTextCursor *cursor);
void checkForElectricCharacter(bool *result, QChar c);
- void indentRegion(int beginLine, int endLine, QChar typedChar);
+ void indentRegion(int beginBlock, int endBlock, QChar typedChar);
void handleExCommand(bool *handled, const ExCommand &cmd);
void writeSettings();
@@ -874,18 +956,18 @@ FakeVimPluginPrivate::FakeVimPluginPrivate(FakeVimPlugin *plugin)
m_fakeVimOptionsPage = 0;
m_fakeVimExCommandsPage = 0;
m_fakeVimUserCommandsPage = 0;
- defaultExCommandMap()[CppTools::Constants::SWITCH_HEADER_SOURCE] =
- QRegExp("^A$");
- defaultExCommandMap()["Coreplugin.OutputPane.previtem"] =
- QRegExp("^(cN(ext)?|cp(revious)?)!?( (.*))?$");
- defaultExCommandMap()["Coreplugin.OutputPane.nextitem"] =
- QRegExp("^cn(ext)?!?( (.*))?$");
- defaultExCommandMap()[TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR] =
- QRegExp("^tag?$");
- defaultExCommandMap()[Core::Constants::GO_BACK] =
- QRegExp("^pop?$");
+ defaultExCommandMap()[_(CppTools::Constants::SWITCH_HEADER_SOURCE)] =
+ QRegExp(_("^A$"));
+ defaultExCommandMap()[_("Coreplugin.OutputPane.previtem")] =
+ QRegExp(_("^(cN(ext)?|cp(revious)?)!?( (.*))?$"));
+ defaultExCommandMap()[_("Coreplugin.OutputPane.nextitem")] =
+ QRegExp(_("^cn(ext)?!?( (.*))?$"));
+ defaultExCommandMap()[_(TextEditor::Constants::FOLLOW_SYMBOL_UNDER_CURSOR)] =
+ QRegExp(_("^tag?$"));
+ defaultExCommandMap()[_(Core::Constants::GO_BACK)] =
+ QRegExp(_("^pop?$"));
defaultExCommandMap()[_("QtCreator.Locate")] =
- QRegExp("^e$");
+ QRegExp(_("^e$"));
for (int i = 1; i < 10; ++i) {
QString cmd = QString::fromLatin1(":echo User command %1 executed.<CR>");
@@ -966,7 +1048,7 @@ bool FakeVimPluginPrivate::initialize()
QAction *act = new QAction(this);
act->setText(tr("Execute User Action #%1").arg(i));
act->setData(i);
- QString id = QString("FakeVim.UserAction%1").arg(i);
+ QString id = QString::fromLatin1("FakeVim.UserAction%1").arg(i);
cmd = ActionManager::registerAction(act, Id(id), globalcontext);
cmd->setDefaultKeySequence(QKeySequence((UseMacShortcuts ? tr("Meta+V,%1") : tr("Alt+V,%1")).arg(i)));
connect(act, SIGNAL(triggered()), SLOT(userActionTriggered()));
@@ -990,7 +1072,10 @@ bool FakeVimPluginPrivate::initialize()
this, SLOT(handleDelayedQuit(bool,Core::IEditor*)), Qt::QueuedConnection);
connect(this, SIGNAL(delayedQuitAllRequested(bool)),
this, SLOT(handleDelayedQuitAll(bool)), Qt::QueuedConnection);
- maybeReadVimRc();
+
+ // Vimrc can break test so don't source it if running tests.
+ if (!ExtensionSystem::PluginManager::runningTests())
+ maybeReadVimRc();
// << "MODE: " << theFakeVimSetting(ConfigUseFakeVim)->value();
return true;
@@ -1102,19 +1187,19 @@ void FakeVimPluginPrivate::maybeReadVimRc()
return;
QString fileName =
QDesktopServices::storageLocation(QDesktopServices::HomeLocation)
- + "/.vimrc";
+ + _("/.vimrc");
//qDebug() << "READING VIMRC: " << fileName;
// Read it into a temporary handler for effects modifying global state.
QPlainTextEdit editor;
FakeVimHandler handler(&editor);
- handler.handleCommand("source " + fileName);
+ handler.handleCommand(_("source ") + fileName);
//writeSettings();
//qDebug() << theFakeVimSetting(ConfigShiftWidth)->value();
}
void FakeVimPluginPrivate::showSettingsDialog()
{
- ICore::showOptionsDialog(_(SETTINGS_CATEGORY), _(SETTINGS_ID));
+ ICore::showOptionsDialog(SETTINGS_CATEGORY, SETTINGS_ID);
}
void FakeVimPluginPrivate::triggerAction(const Id &id)
@@ -1285,6 +1370,164 @@ void FakeVimPluginPrivate::findNext(bool reverse)
triggerAction(Find::Constants::FIND_NEXT);
}
+void FakeVimPluginPrivate::foldToggle(int depth)
+{
+ IEditor *ieditor = EditorManager::currentEditor();
+ BaseTextEditorWidget *editor = qobject_cast<BaseTextEditorWidget *>(ieditor->widget());
+ QTC_ASSERT(editor != 0, return);
+
+ QTextBlock block = editor->textCursor().block();
+ fold(depth, !BaseTextDocumentLayout::isFolded(block));
+}
+
+void FakeVimPluginPrivate::foldAll(bool fold)
+{
+ IEditor *ieditor = EditorManager::currentEditor();
+ BaseTextEditorWidget *editor = qobject_cast<BaseTextEditorWidget *>(ieditor->widget());
+ QTC_ASSERT(editor != 0, return);
+
+ QTextDocument *doc = editor->document();
+ BaseTextDocumentLayout *documentLayout =
+ qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
+ QTC_ASSERT(documentLayout != 0, return);
+
+ QTextBlock block = editor->document()->firstBlock();
+ while (block.isValid()) {
+ BaseTextDocumentLayout::doFoldOrUnfold(block, !fold);
+ block = block.next();
+ }
+
+ documentLayout->requestUpdate();
+ documentLayout->emitDocumentSizeChanged();
+}
+
+void FakeVimPluginPrivate::fold(int depth, bool fold)
+{
+ IEditor *ieditor = EditorManager::currentEditor();
+ BaseTextEditorWidget *editor = qobject_cast<BaseTextEditorWidget *>(ieditor->widget());
+ QTC_ASSERT(editor != 0, return);
+
+ QTextDocument *doc = editor->document();
+ BaseTextDocumentLayout *documentLayout =
+ qobject_cast<BaseTextDocumentLayout*>(doc->documentLayout());
+ QTC_ASSERT(documentLayout != 0, return);
+
+ QTextBlock block = editor->textCursor().block();
+ int indent = BaseTextDocumentLayout::foldingIndent(block);
+ if (fold) {
+ if (BaseTextDocumentLayout::isFolded(block)) {
+ while (block.isValid() && (BaseTextDocumentLayout::foldingIndent(block) >= indent
+ || !block.isVisible())) {
+ block = block.previous();
+ }
+ }
+ if (BaseTextDocumentLayout::canFold(block))
+ ++indent;
+ while (depth != 0 && block.isValid()) {
+ const int indent2 = BaseTextDocumentLayout::foldingIndent(block);
+ if (BaseTextDocumentLayout::canFold(block) && indent2 < indent) {
+ BaseTextDocumentLayout::doFoldOrUnfold(block, false);
+ if (depth > 0)
+ --depth;
+ indent = indent2;
+ }
+ block = block.previous();
+ }
+ } else {
+ if (BaseTextDocumentLayout::isFolded(block)) {
+ if (depth < 0) {
+ // recursively open fold
+ while (depth < 0 && block.isValid()
+ && BaseTextDocumentLayout::foldingIndent(block) >= indent) {
+ if (BaseTextDocumentLayout::canFold(block)) {
+ BaseTextDocumentLayout::doFoldOrUnfold(block, true);
+ if (depth > 0)
+ --depth;
+ }
+ block = block.next();
+ }
+ } else {
+ if (BaseTextDocumentLayout::canFold(block)) {
+ BaseTextDocumentLayout::doFoldOrUnfold(block, true);
+ if (depth > 0)
+ --depth;
+ }
+ }
+ }
+ }
+
+ documentLayout->requestUpdate();
+ documentLayout->emitDocumentSizeChanged();
+}
+
+void FakeVimPluginPrivate::foldGoTo(int count, bool current)
+{
+ IEditor *ieditor = EditorManager::currentEditor();
+ BaseTextEditorWidget *editor = qobject_cast<BaseTextEditorWidget *>(ieditor->widget());
+ QTC_ASSERT(editor != 0, return);
+
+ QTextCursor tc = editor->textCursor();
+ QTextBlock block = tc.block();
+
+ int pos = -1;
+ if (count > 0) {
+ int repeat = count;
+ block = block.next();
+ QTextBlock prevBlock = block;
+ int indent = BaseTextDocumentLayout::foldingIndent(block);
+ block = block.next();
+ while (block.isValid()) {
+ int newIndent = BaseTextDocumentLayout::foldingIndent(block);
+ if (current ? indent > newIndent : indent < newIndent) {
+ if (prevBlock.isVisible()) {
+ pos = prevBlock.position();
+ if (--repeat <= 0)
+ break;
+ } else if (current) {
+ indent = newIndent;
+ }
+ }
+ if (!current)
+ indent = newIndent;
+ prevBlock = block;
+ block = block.next();
+ }
+ } else if (count < 0) {
+ int repeat = -count;
+ int indent = BaseTextDocumentLayout::foldingIndent(block);
+ block = block.previous();
+ while (block.isValid()) {
+ int newIndent = BaseTextDocumentLayout::foldingIndent(block);
+ if (current ? indent > newIndent : indent < newIndent) {
+ while (block.isValid() && !block.isVisible())
+ block = block.previous();
+ pos = block.position();
+ if (--repeat <= 0)
+ break;
+ }
+ if (!current)
+ indent = newIndent;
+ block = block.previous();
+ }
+ }
+
+ if (pos != -1) {
+ tc.setPosition(pos, QTextCursor::KeepAnchor);
+ editor->setTextCursor(tc);
+ }
+}
+
+void FakeVimPluginPrivate::jumpToGlobalMark(QChar mark, bool backTickMode,
+ const QString &fileName)
+{
+ Core::IEditor *iedit = Core::EditorManager::openEditor(fileName);
+ if (!iedit)
+ return;
+ FakeVimHandler *handler = m_editorToHandler.value(iedit, 0);
+ if (handler)
+ handler->jumpToLocalMark(mark, backTickMode);
+}
+
// This class defers deletion of a child FakeVimHandler using deleteLater().
class DeferredDeleter : public QObject
{
@@ -1331,10 +1574,12 @@ void FakeVimPluginPrivate::editorOpened(IEditor *editor)
connect(handler, SIGNAL(extraInformationChanged(QString)),
SLOT(showExtraInformation(QString)));
- connect(handler, SIGNAL(commandBufferChanged(QString,int)),
- SLOT(showCommandBuffer(QString,int)));
+ connect(handler, SIGNAL(commandBufferChanged(QString,int,int,int,QObject*)),
+ SLOT(showCommandBuffer(QString,int,int,int,QObject*)));
connect(handler, SIGNAL(selectionChanged(QList<QTextEdit::ExtraSelection>)),
SLOT(changeSelection(QList<QTextEdit::ExtraSelection>)));
+ connect(handler, SIGNAL(highlightMatches(QString)),
+ SLOT(highlightMatches(QString)));
connect(handler, SIGNAL(moveToMatchingParenthesis(bool*,bool*,QTextCursor*)),
SLOT(moveToMatchingParenthesis(bool*,bool*,QTextCursor*)));
connect(handler, SIGNAL(indentRegion(int,int,QChar)),
@@ -1355,6 +1600,16 @@ void FakeVimPluginPrivate::editorOpened(IEditor *editor)
SLOT(find(bool)));
connect(handler, SIGNAL(findNextRequested(bool)),
SLOT(findNext(bool)));
+ connect(handler, SIGNAL(foldToggle(int)),
+ SLOT(foldToggle(int)));
+ connect(handler, SIGNAL(foldAll(bool)),
+ SLOT(foldAll(bool)));
+ connect(handler, SIGNAL(fold(int,bool)),
+ SLOT(fold(int,bool)));
+ connect(handler, SIGNAL(foldGoTo(int, bool)),
+ SLOT(foldGoTo(int, bool)));
+ connect(handler, SIGNAL(jumpToGlobalMark(QChar,bool,QString)),
+ SLOT(jumpToGlobalMark(QChar,bool,QString)));
connect(handler, SIGNAL(handleExCommandRequested(bool*,ExCommand)),
SLOT(handleExCommand(bool*,ExCommand)));
@@ -1367,7 +1622,7 @@ void FakeVimPluginPrivate::editorOpened(IEditor *editor)
// pop up the bar
if (theFakeVimSetting(ConfigUseFakeVim)->value().toBool()) {
- showCommandBuffer(QString(), -1);
+ resetCommandBuffer();
handler->setupWidget();
}
}
@@ -1399,7 +1654,7 @@ void FakeVimPluginPrivate::setUseFakeVimInternal(bool on)
//ICore *core = ICore::instance();
//core->updateAdditionalContexts(Context(),
// Context(FAKEVIM_CONTEXT));
- showCommandBuffer(QString(), -1);
+ resetCommandBuffer();
foreach (IEditor *editor, m_editorToHandler.keys()) {
if (BaseTextEditorWidget *textEditor =
qobject_cast<BaseTextEditorWidget *>(editor->widget())) {
@@ -1465,7 +1720,7 @@ void FakeVimPluginPrivate::handleExCommand(bool *handled, const ExCommand &cmd)
return;
*handled = true;
- if (cmd.matches("w", "write") || cmd.cmd == "wq") {
+ if (cmd.matches(_("w"), _("write")) || cmd.cmd == _("wq")) {
// :w[rite]
IEditor *editor = m_editorToHandler.key(handler);
const QString fileName = handler->currentFileName();
@@ -1476,70 +1731,70 @@ void FakeVimPluginPrivate::handleExCommand(bool *handled, const ExCommand &cmd)
QFile file3(fileName);
file3.open(QIODevice::ReadOnly);
QByteArray ba = file3.readAll();
- handler->showBlackMessage(FakeVimHandler::tr("\"%1\" %2 %3L, %4C written")
- .arg(fileName).arg(" ")
+ handler->showMessage(MessageInfo, FakeVimHandler::tr("\"%1\" %2 %3L, %4C written")
+ .arg(fileName).arg(QLatin1Char(' '))
.arg(ba.count('\n')).arg(ba.size()));
- if (cmd.cmd == "wq")
+ if (cmd.cmd == _("wq"))
delayedQuitRequested(cmd.hasBang, m_editorToHandler.key(handler));
} else {
- handler->showRedMessage(tr("File not saved"));
+ handler->showMessage(MessageError, tr("File not saved"));
}
- } else if (cmd.matches("wa", "wall")) {
+ } else if (cmd.matches(_("wa"), _("wall"))) {
// :w[all]
QList<IDocument *> toSave = DocumentManager::modifiedDocuments();
QList<IDocument *> failed = DocumentManager::saveModifiedDocumentsSilently(toSave);
if (failed.isEmpty())
- handler->showBlackMessage(tr("Saving succeeded"));
+ handler->showMessage(MessageInfo, tr("Saving succeeded"));
else
- handler->showRedMessage(tr("%n files not saved", 0, failed.size()));
- } else if (cmd.matches("q", "quit")) {
+ handler->showMessage(MessageError, tr("%n files not saved", 0, failed.size()));
+ } else if (cmd.matches(_("q"), _("quit"))) {
// :q[uit]
emit delayedQuitRequested(cmd.hasBang, m_editorToHandler.key(handler));
- } else if (cmd.matches("qa", "qall")) {
+ } else if (cmd.matches(_("qa"), _("qall"))) {
// :qa[ll]
emit delayedQuitAllRequested(cmd.hasBang);
- } else if (cmd.matches("sp", "split")) {
+ } else if (cmd.matches(_("sp"), _("split"))) {
// :sp[lit]
triggerAction(Core::Constants::SPLIT);
- } else if (cmd.matches("vs", "vsplit")) {
+ } else if (cmd.matches(_("vs"), _("vsplit"))) {
// :vs[plit]
triggerAction(Core::Constants::SPLIT_SIDE_BY_SIDE);
- } else if (cmd.matches("mak", "make")) {
+ } else if (cmd.matches(_("mak"), _("make"))) {
// :mak[e][!] [arguments]
triggerAction(ProjectExplorer::Constants::BUILD);
- } else if (cmd.matches("se", "set")) {
+ } else if (cmd.matches(_("se"), _("set"))) {
if (cmd.args.isEmpty()) {
// :se[t]
showSettingsDialog();
- } else if (cmd.args == "ic" || cmd.args == "ignorecase") {
+ } else if (cmd.args == _("ic") || cmd.args == _("ignorecase")) {
// :set nc
setActionChecked(Find::Constants::CASE_SENSITIVE, false);
- } else if (cmd.args == "noic" || cmd.args == "noignorecase") {
+ } else if (cmd.args == _("noic") || cmd.args == _("noignorecase")) {
// :set noic
setActionChecked(Find::Constants::CASE_SENSITIVE, true);
} else {
*handled = false; // Let the handler see it as well.
}
- } else if (cmd.matches("n", "next")) {
+ } else if (cmd.matches(_("n"), _("next"))) {
// :n[ext]
switchToFile(currentFile() + cmd.count);
- } else if (cmd.matches("prev", "previous") || cmd.matches("N", "Next")) {
+ } else if (cmd.matches(_("prev"), _("previous")) || cmd.matches(_("N"), _("Next"))) {
// :prev[ious], :N[ext]
switchToFile(currentFile() - cmd.count);
- } else if (cmd.matches("bn", "bnext")) {
+ } else if (cmd.matches(_("bn"), _("bnext"))) {
// :bn[ext]
switchToFile(currentFile() + cmd.count);
- } else if (cmd.matches("bp", "bprevious") || cmd.matches("bN", "bNext")) {
+ } else if (cmd.matches(_("bp"), _("bprevious")) || cmd.matches(_("bN"), _("bNext"))) {
// :bp[revious], :bN[ext]
switchToFile(currentFile() - cmd.count);
- } else if (cmd.matches("on", "only")) {
+ } else if (cmd.matches(_("on"), _("only"))) {
// :on[ly]
//triggerAction(Core::Constants::REMOVE_ALL_SPLITS);
triggerAction(Core::Constants::REMOVE_CURRENT_SPLIT);
- } else if (cmd.cmd == "AS") {
+ } else if (cmd.cmd == _("AS")) {
triggerAction(Core::Constants::SPLIT);
triggerAction(CppTools::Constants::SWITCH_HEADER_SOURCE);
- } else if (cmd.cmd == "AV") {
+ } else if (cmd.cmd == _("AV")) {
triggerAction(Core::Constants::SPLIT_SIDE_BY_SIDE);
triggerAction(CppTools::Constants::SWITCH_HEADER_SOURCE);
} else {
@@ -1614,7 +1869,7 @@ void FakeVimPluginPrivate::moveToMatchingParenthesis(bool *moved, bool *forward,
}
}
-void FakeVimPluginPrivate::indentRegion(int beginLine, int endLine,
+void FakeVimPluginPrivate::indentRegion(int beginBlock, int endBlock,
QChar typedChar)
{
FakeVimHandler *handler = qobject_cast<FakeVimHandler *>(sender());
@@ -1632,14 +1887,14 @@ void FakeVimPluginPrivate::indentRegion(int beginLine, int endLine,
? TabSettings::SpacesOnlyTabPolicy : TabSettings::TabsOnlyTabPolicy;
QTextDocument *doc = bt->document();
- QTextBlock startBlock = doc->findBlockByNumber(beginLine);
+ QTextBlock startBlock = doc->findBlockByNumber(beginBlock);
// Record line lenghts for mark adjustments
- QVector<int> lineLengths(endLine - beginLine + 1);
+ QVector<int> lineLengths(endBlock - beginBlock + 1);
QTextBlock block = startBlock;
- for (int i = beginLine; i <= endLine; ++i) {
- lineLengths[i - beginLine] = block.text().length();
+ for (int i = beginBlock; i <= endBlock; ++i) {
+ lineLengths[i - beginBlock] = block.text().length();
if (typedChar == 0 && block.text().simplified().isEmpty()) {
// clear empty lines
QTextCursor cursor(block);
@@ -1657,11 +1912,17 @@ void FakeVimPluginPrivate::quitFakeVim()
theFakeVimSetting(ConfigUseFakeVim)->setValue(false);
}
-void FakeVimPluginPrivate::showCommandBuffer(const QString &contents, int cursorPos)
+void FakeVimPluginPrivate::resetCommandBuffer()
+{
+ showCommandBuffer(QString(), -1, -1, 0, 0);
+}
+
+void FakeVimPluginPrivate::showCommandBuffer(const QString &contents,
+ int cursorPos, int anchorPos, int messageLevel, QObject *eventFilter)
{
//qDebug() << "SHOW COMMAND BUFFER" << contents;
if (MiniBuffer *w = qobject_cast<MiniBuffer *>(m_statusBar->widget()))
- w->setContents(contents, cursorPos);
+ w->setContents(contents, cursorPos, anchorPos, messageLevel, eventFilter);
}
void FakeVimPluginPrivate::showExtraInformation(const QString &text)
@@ -1671,14 +1932,22 @@ void FakeVimPluginPrivate::showExtraInformation(const QString &text)
QMessageBox::information(handler->widget(), tr("FakeVim Information"), text);
}
-void FakeVimPluginPrivate::changeSelection
- (const QList<QTextEdit::ExtraSelection> &selection)
+void FakeVimPluginPrivate::changeSelection(const QList<QTextEdit::ExtraSelection> &selection)
{
if (FakeVimHandler *handler = qobject_cast<FakeVimHandler *>(sender()))
if (BaseTextEditorWidget *bt = qobject_cast<BaseTextEditorWidget *>(handler->widget()))
bt->setExtraSelections(BaseTextEditorWidget::FakeVimSelection, selection);
}
+void FakeVimPluginPrivate::highlightMatches(const QString &needle)
+{
+ IEditor *editor = EditorManager::currentEditor();
+ QWidget *w = editor->widget();
+ Find::IFindSupport *find = Aggregation::query<Find::IFindSupport>(w);
+ if (find != 0)
+ find->highlightAll(needle, Find::FindRegularExpression | Find::FindCaseSensitively);
+}
+
int FakeVimPluginPrivate::currentFile() const
{
OpenEditorsModel *model = EditorManager::instance()->openedEditorsModel();
@@ -1754,6 +2023,48 @@ void FakeVimPlugin::extensionsInitialized()
addAutoReleasedObject(d->m_statusBar);
}
+#ifdef WITH_TESTS
+void FakeVimPlugin::setupTest(QString *title, FakeVimHandler **handler, QWidget **edit)
+{
+ *title = QString::fromLatin1("test.cpp");
+ Core::IEditor *iedit = Core::EditorManager::openEditorWithContents(Core::Id(), title);
+ Core::EditorManager::activateEditor(iedit);
+ *edit = iedit->widget();
+ *handler = d->m_editorToHandler.value(iedit, 0);
+ (*handler)->handleCommand(_("set startofline"));
+
+// *handler = 0;
+// m_statusMessage.clear();
+// m_statusData.clear();
+// m_infoMessage.clear();
+// if (m_textedit) {
+// m_textedit->setPlainText(lines);
+// QTextCursor tc = m_textedit->textCursor();
+// tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
+// m_textedit->setTextCursor(tc);
+// m_textedit->setPlainText(lines);
+// *handler = new FakeVimHandler(m_textedit);
+// } else {
+// m_plaintextedit->setPlainText(lines);
+// QTextCursor tc = m_plaintextedit->textCursor();
+// tc.movePosition(QTextCursor::Start, QTextCursor::MoveAnchor);
+// m_plaintextedit->setTextCursor(tc);
+// m_plaintextedit->setPlainText(lines);
+// *handler = new FakeVimHandler(m_plaintextedit);
+// }
+
+// QObject::connect(*handler, SIGNAL(commandBufferChanged(QString,int)),
+// this, SLOT(changeStatusMessage(QString,int)));
+// QObject::connect(*handler, SIGNAL(extraInformationChanged(QString)),
+// this, SLOT(changeExtraInformation(QString)));
+// QObject::connect(*handler, SIGNAL(statusDataChanged(QString)),
+// this, SLOT(changeStatusData(QString)));
+
+// QCOMPARE(EDITOR(toPlainText()), lines);
+ (*handler)->handleCommand(_("set iskeyword=@,48-57,_,192-255,a-z,A-Z"));
+}
+#endif
+
} // namespace Internal
} // namespace FakeVim
diff --git a/src/plugins/fakevim/fakevimplugin.h b/src/plugins/fakevim/fakevimplugin.h
index 45b34bd852..2ade5e54fc 100644
--- a/src/plugins/fakevim/fakevimplugin.h
+++ b/src/plugins/fakevim/fakevimplugin.h
@@ -56,6 +56,106 @@ private:
private:
friend class FakeVimPluginPrivate;
FakeVimPluginPrivate *d;
+
+#ifdef WITH_TESTS
+private slots:
+ void cleanup();
+ void test_vim_movement();
+ void test_vim_insert();
+ void test_vim_fFtT();
+ void test_vim_transform_numbers();
+ void test_vim_delete();
+ void test_vim_delete_inner_word();
+ void test_vim_delete_a_word();
+ void test_vim_change_a_word();
+ void test_vim_change_replace();
+ void test_vim_block_selection();
+ void test_vim_repeat();
+ void test_vim_search();
+ void test_vim_indent();
+ void test_vim_marks();
+ void test_vim_jumps();
+ void test_vim_current_column();
+ void test_vim_copy_paste();
+ void test_vim_undo_redo();
+ void test_vim_letter_case();
+ void test_vim_code_autoindent();
+ void test_vim_code_folding();
+ void test_vim_code_completion();
+ void test_vim_substitute();
+ void test_vim_ex_yank();
+ void test_vim_ex_delete();
+ void test_vim_ex_change();
+ void test_vim_ex_shift();
+ void test_vim_ex_move();
+ void test_vim_ex_join();
+ void test_advanced_commands();
+
+//public slots:
+// void changeStatusData(const QString &info) { m_statusData = info; }
+// void changeStatusMessage(const QString &info, int) { m_statusMessage = info; }
+// void changeExtraInformation(const QString &info) { m_infoMessage = info; }
+
+//private slots:
+// // functional tests
+ void test_vim_indentation();
+
+ // command mode
+ void test_vim_command_oO();
+ void test_vim_command_put_at_eol();
+ void test_vim_command_Cxx_down_dot();
+ void test_vim_command_Gyyp();
+ void test_vim_command_J();
+ void test_vim_command_Yp();
+ void test_vim_command_cc();
+ void test_vim_command_cw();
+ void test_vim_command_cj();
+ void test_vim_command_ck();
+ void test_vim_command_c_dollar();
+ void test_vim_command_C();
+ void test_vim_command_dd();
+ void test_vim_command_dd_2();
+ void test_vim_command_d_dollar();
+ void test_vim_command_dgg();
+ void test_vim_command_dG();
+ void test_vim_command_dj();
+ void test_vim_command_dk();
+ void test_vim_command_D();
+ void test_vim_command_dfx_down();
+ void test_vim_command_dollar();
+ void test_vim_command_down();
+ void test_vim_command_dw();
+ void test_vim_command_e();
+ void test_vim_command_i();
+ void test_vim_command_left();
+ void test_vim_command_ma_yank();
+ void test_vim_command_r();
+ void test_vim_command_right();
+ void test_vim_command_up();
+ void test_vim_command_w();
+ void test_vim_command_x();
+ void test_vim_command_yyp();
+ void test_vim_command_y_dollar();
+
+ void test_vim_visual_d();
+ void test_vim_Visual_d();
+
+ // special tests
+ void test_i_cw_i();
+
+ // map test should be last one since it changes default behaviour
+ void test_map();
+
+//private:
+// QString m_statusMessage;
+// QString m_statusData;
+// QString m_infoMessage;
+
+private:
+ struct TestData;
+ void setup(TestData *data);
+ void setupTest(QString *title, FakeVimHandler **handler, QWidget **edit);
+#endif
};
} // namespace Internal
diff --git a/src/plugins/find/basetextfind.cpp b/src/plugins/find/basetextfind.cpp
index a5149993a2..1b2226dddc 100644
--- a/src/plugins/find/basetextfind.cpp
+++ b/src/plugins/find/basetextfind.cpp
@@ -124,7 +124,8 @@ bool BaseTextFind::supportsReplace() const
Find::FindFlags BaseTextFind::supportedFindFlags() const
{
return Find::FindBackward | Find::FindCaseSensitively
- | Find::FindRegularExpression | Find::FindWholeWords;
+ | Find::FindRegularExpression | Find::FindWholeWords
+ | Find::FindPreserveCase;
}
void BaseTextFind::resetIncrementalSearch()
@@ -141,9 +142,8 @@ void BaseTextFind::clearResults()
QString BaseTextFind::currentFindString() const
{
QTextCursor cursor = textCursor();
- if (cursor.hasSelection() && cursor.block() != cursor.document()->findBlock(cursor.anchor())) {
+ if (cursor.hasSelection() && cursor.block() != cursor.document()->findBlock(cursor.anchor()))
return QString(); // multi block selection
- }
if (cursor.hasSelection())
return cursor.selectedText();
@@ -216,12 +216,19 @@ QTextCursor BaseTextFind::replaceInternal(const QString &before, const QString &
{
QTextCursor cursor = textCursor();
bool usesRegExp = (findFlags & Find::FindRegularExpression);
+ bool preserveCase = (findFlags & Find::FindPreserveCase);
QRegExp regexp(before,
(findFlags & Find::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive,
usesRegExp ? QRegExp::RegExp : QRegExp::FixedString);
if (regexp.exactMatch(cursor.selectedText())) {
- QString realAfter = usesRegExp ? Utils::expandRegExpReplacement(after, regexp.capturedTexts()) : after;
+ QString realAfter;
+ if (usesRegExp)
+ realAfter = Utils::expandRegExpReplacement(after, regexp.capturedTexts());
+ else if (preserveCase)
+ realAfter = Utils::matchCaseReplacement(cursor.selectedText(), after);
+ else
+ realAfter = after;
int start = cursor.selectionStart();
cursor.insertText(realAfter);
if ((findFlags&Find::FindBackward) != 0)
@@ -252,17 +259,40 @@ int BaseTextFind::replaceAll(const QString &before, const QString &after,
editCursor.beginEditBlock();
int count = 0;
bool usesRegExp = (findFlags & Find::FindRegularExpression);
+ bool preserveCase = (findFlags & Find::FindPreserveCase);
QRegExp regexp(before);
regexp.setPatternSyntax(usesRegExp ? QRegExp::RegExp : QRegExp::FixedString);
regexp.setCaseSensitivity((findFlags & Find::FindCaseSensitively) ? Qt::CaseSensitive : Qt::CaseInsensitive);
QTextCursor found = findOne(regexp, editCursor, Find::textDocumentFlagsForFindFlags(findFlags));
- while (!found.isNull() && found.selectionStart() < found.selectionEnd()
- && inScope(found.selectionStart(), found.selectionEnd())) {
+ bool first = true;
+ while (!found.isNull() && inScope(found.selectionStart(), found.selectionEnd())) {
+ if (found == editCursor && !first) {
+ if (editCursor.atEnd())
+ break;
+ // If the newly found QTextCursor is the same as recently edit one we have to move on,
+ // otherwise we would run into an endless loop for some regular expressions
+ // like ^ or \b.
+ QTextCursor newPosCursor = editCursor;
+ newPosCursor.movePosition(findFlags & Find::FindBackward ?
+ QTextCursor::PreviousCharacter :
+ QTextCursor::NextCharacter);
+ found = findOne(regexp, newPosCursor, Find::textDocumentFlagsForFindFlags(findFlags));
+ continue;
+ }
+ if (first)
+ first = false;
++count;
editCursor.setPosition(found.selectionStart());
editCursor.setPosition(found.selectionEnd(), QTextCursor::KeepAnchor);
regexp.exactMatch(found.selectedText());
- QString realAfter = usesRegExp ? Utils::expandRegExpReplacement(after, regexp.capturedTexts()) : after;
+
+ QString realAfter;
+ if (usesRegExp)
+ realAfter = Utils::expandRegExpReplacement(after, regexp.capturedTexts());
+ else if (preserveCase)
+ realAfter = Utils::matchCaseReplacement(found.selectedText(), after);
+ else
+ realAfter = after;
editCursor.insertText(realAfter);
found = findOne(regexp, editCursor, Find::textDocumentFlagsForFindFlags(findFlags));
}
@@ -313,9 +343,8 @@ bool BaseTextFind::find(const QString &txt, Find::FindFlags findFlags,
*wrapped = true;
}
}
- if (!found.isNull()) {
+ if (!found.isNull())
setTextCursor(found);
- }
return true;
}
diff --git a/src/plugins/find/currentdocumentfind.cpp b/src/plugins/find/currentdocumentfind.cpp
index d78abd068f..c6b7e2940e 100644
--- a/src/plugins/find/currentdocumentfind.cpp
+++ b/src/plugins/find/currentdocumentfind.cpp
@@ -230,9 +230,8 @@ bool CurrentDocumentFind::setFocusToCurrentFindSupport()
bool CurrentDocumentFind::eventFilter(QObject *obj, QEvent *event)
{
if (m_currentWidget && obj == m_currentWidget) {
- if (event->type() == QEvent::Hide || event->type() == QEvent::Show) {
+ if (event->type() == QEvent::Hide || event->type() == QEvent::Show)
emit changed();
- }
}
return QObject::eventFilter(obj, event);
}
diff --git a/src/plugins/find/find.pro b/src/plugins/find/find.pro
index 0f71955f91..59e6f32d93 100644
--- a/src/plugins/find/find.pro
+++ b/src/plugins/find/find.pro
@@ -12,6 +12,7 @@ HEADERS += findtoolwindow.h \
find_global.h \
findtoolbar.h \
findplugin.h \
+ searchresultcolor.h \
searchresulttreeitemdelegate.h \
searchresulttreeitemroles.h \
searchresulttreeitems.h \
@@ -38,4 +39,3 @@ FORMS += findwidget.ui \
finddialog.ui
RESOURCES += find.qrc
-
diff --git a/src/plugins/find/find.qbs b/src/plugins/find/find.qbs
index 560bb28fda..7b8287e5be 100644
--- a/src/plugins/find/find.qbs
+++ b/src/plugins/find/find.qbs
@@ -9,24 +9,19 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
- "..",
+ cpp.includePaths: base.concat([
"generichighlighter",
"tooltip",
"snippets",
- "codeassist",
- "../../libs",
- buildDirectory
- ]
+ "codeassist"
+ ])
files: [
- "find.qrc",
- "findwidget.ui",
"basetextfind.cpp",
"basetextfind.h",
"currentdocumentfind.cpp",
"currentdocumentfind.h",
+ "find.qrc",
"find_global.h",
"finddialog.ui",
"findplugin.cpp",
@@ -35,10 +30,12 @@ QtcPlugin {
"findtoolbar.h",
"findtoolwindow.cpp",
"findtoolwindow.h",
+ "findwidget.ui",
"ifindfilter.cpp",
"ifindfilter.h",
"ifindsupport.cpp",
"ifindsupport.h",
+ "searchresultcolor.h",
"searchresulttreeitemdelegate.cpp",
"searchresulttreeitemdelegate.h",
"searchresulttreeitemroles.h",
@@ -54,7 +51,6 @@ QtcPlugin {
"searchresultwindow.h",
"textfindconstants.h",
"treeviewfind.cpp",
- "treeviewfind.h"
+ "treeviewfind.h",
]
}
-
diff --git a/src/plugins/find/find.qrc b/src/plugins/find/find.qrc
index 52d7a810bf..0c4e128101 100644
--- a/src/plugins/find/find.qrc
+++ b/src/plugins/find/find.qrc
@@ -5,5 +5,6 @@
<file>images/regexp.png</file>
<file>images/expand.png</file>
<file>images/wrapindicator.png</file>
+ <file>images/preservecase.png</file>
</qresource>
</RCC>
diff --git a/src/plugins/find/findplugin.cpp b/src/plugins/find/findplugin.cpp
index 74bc68c93d..dde1b4d82b 100644
--- a/src/plugins/find/findplugin.cpp
+++ b/src/plugins/find/findplugin.cpp
@@ -234,7 +234,8 @@ void FindPlugin::setupFilterMenuItems()
haveEnabledFilters = true;
action->setEnabled(isEnabled);
action->setData(qVariantFromValue(filter));
- cmd = Core::ActionManager::registerAction(action, Core::Id(QLatin1String("FindFilter.")+filter->id()), globalcontext);
+ cmd = Core::ActionManager::registerAction(action,
+ Core::Id::fromString(QLatin1String("FindFilter.")+filter->id()), globalcontext);
cmd->setDefaultKeySequence(filter->defaultShortcut());
mfindadvanced->addAction(cmd);
d->m_filterActions.insert(filter, action);
@@ -270,6 +271,11 @@ void FindPlugin::setRegularExpression(bool regExp)
setFindFlag(Find::FindRegularExpression, regExp);
}
+void FindPlugin::setPreserveCase(bool preserveCase)
+{
+ setFindFlag(Find::FindPreserveCase, preserveCase);
+}
+
void FindPlugin::setFindFlag(Find::FindFlag flag, bool enabled)
{
bool hasFlag = hasFindFlag(flag);
@@ -296,6 +302,7 @@ void FindPlugin::writeSettings()
settings->setValue(QLatin1String("CaseSensitively"), hasFindFlag(Find::FindCaseSensitively));
settings->setValue(QLatin1String("WholeWords"), hasFindFlag(Find::FindWholeWords));
settings->setValue(QLatin1String("RegularExpression"), hasFindFlag(Find::FindRegularExpression));
+ settings->setValue(QLatin1String("PreserveCase"), hasFindFlag(Find::FindPreserveCase));
settings->setValue(QLatin1String("FindStrings"), d->m_findCompletions);
settings->setValue(QLatin1String("ReplaceStrings"), d->m_replaceCompletions);
settings->endGroup();
@@ -312,6 +319,7 @@ void FindPlugin::readSettings()
setCaseSensitive(settings->value(QLatin1String("CaseSensitively"), false).toBool());
setWholeWord(settings->value(QLatin1String("WholeWords"), false).toBool());
setRegularExpression(settings->value(QLatin1String("RegularExpression"), false).toBool());
+ setPreserveCase(settings->value(QLatin1String("PreserveCase"), false).toBool());
blockSignals(block);
d->m_findCompletions = settings->value(QLatin1String("FindStrings")).toStringList();
d->m_replaceCompletions = settings->value(QLatin1String("ReplaceStrings")).toStringList();
diff --git a/src/plugins/find/findplugin.h b/src/plugins/find/findplugin.h
index a492f86225..46e3953c76 100644
--- a/src/plugins/find/findplugin.h
+++ b/src/plugins/find/findplugin.h
@@ -83,6 +83,7 @@ public slots:
void setWholeWord(bool wholeOnly);
void setBackward(bool backward);
void setRegularExpression(bool regExp);
+ void setPreserveCase(bool preserveCase);
signals:
void findFlagsChanged();
diff --git a/src/plugins/find/findtoolbar.cpp b/src/plugins/find/findtoolbar.cpp
index 29fbd998c5..ec4d673a69 100644
--- a/src/plugins/find/findtoolbar.cpp
+++ b/src/plugins/find/findtoolbar.cpp
@@ -43,6 +43,7 @@
#include <extensionsystem/pluginmanager.h>
+#include <utils/hostosinfo.h>
#include <utils/stylehelper.h>
#include <utils/flowlayout.h>
@@ -249,6 +250,15 @@ FindToolBar::FindToolBar(FindPlugin *plugin, CurrentDocumentFind *currentDocumen
connect(m_regularExpressionAction, SIGNAL(triggered(bool)), this, SLOT(setRegularExpressions(bool)));
lineEditMenu->addAction(m_regularExpressionAction);
+ m_preserveCaseAction = new QAction(tr("Preserve Case when Replacing"), this);
+ m_preserveCaseAction->setIcon(QPixmap(QLatin1String(":/find/images/preservecase.png")));
+ m_preserveCaseAction->setCheckable(true);
+ m_preserveCaseAction->setChecked(false);
+ cmd = Core::ActionManager::registerAction(m_preserveCaseAction, Constants::PRESERVE_CASE, globalcontext);
+ mfind->addAction(cmd, Constants::G_FIND_FLAGS);
+ connect(m_preserveCaseAction, SIGNAL(triggered(bool)), this, SLOT(setPreserveCase(bool)));
+ lineEditMenu->addAction(m_preserveCaseAction);
+
connect(m_currentDocumentFind, SIGNAL(candidateChanged()), this, SLOT(adaptToCandidate()));
connect(m_currentDocumentFind, SIGNAL(changed()), this, SLOT(updateToolBar()));
updateToolBar();
@@ -295,11 +305,7 @@ bool FindToolBar::eventFilter(QObject *obj, QEvent *event)
if ((obj == m_ui.findEdit || obj == m_findCompleter->popup())
&& event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
-#ifdef Q_OS_MAC
- if (ke->key() == Qt::Key_Space && (ke->modifiers() & Qt::MetaModifier)) {
-#else
- if (ke->key() == Qt::Key_Space && (ke->modifiers() & Qt::ControlModifier)) {
-#endif
+ if (ke->key() == Qt::Key_Space && (ke->modifiers() & Utils::HostOsInfo::controlModifier())) {
QString completedText = m_currentDocumentFind->completedFindString();
if (!completedText.isEmpty()) {
setFindText(completedText);
@@ -316,19 +322,14 @@ bool FindToolBar::eventFilter(QObject *obj, QEvent *event)
event->accept();
return true;
}
-#ifdef Q_OS_MAC
- } else if (ke->key() == Qt::Key_Space && (ke->modifiers() & Qt::MetaModifier)) {
-#else
- } else if (ke->key() == Qt::Key_Space && (ke->modifiers() & Qt::ControlModifier)) {
-#endif
+ } else if (ke->key() == Qt::Key_Space && (ke->modifiers() & Utils::HostOsInfo::controlModifier())) {
event->accept();
return true;
}
} else if (obj == this && event->type() == QEvent::Hide) {
invokeClearResults();
- if (m_currentDocumentFind->isEnabled()) {
+ if (m_currentDocumentFind->isEnabled())
m_currentDocumentFind->clearFindScope();
- }
}
return Utils::StyledBar::eventFilter(obj, event);
}
@@ -336,9 +337,8 @@ bool FindToolBar::eventFilter(QObject *obj, QEvent *event)
void FindToolBar::adaptToCandidate()
{
updateFindAction();
- if (findToolBarPlaceHolder() == Core::FindToolBarPlaceHolder::getCurrent()) {
+ if (findToolBarPlaceHolder() == Core::FindToolBarPlaceHolder::getCurrent())
m_currentDocumentFind->acceptCandidate();
- }
}
void FindToolBar::updateFindAction()
@@ -364,6 +364,7 @@ void FindToolBar::updateToolBar()
m_caseSensitiveAction->setEnabled(enabled);
m_wholeWordAction->setEnabled(enabled);
m_regularExpressionAction->setEnabled(enabled);
+ m_preserveCaseAction->setEnabled(replaceEnabled && !hasFindFlag(Find::FindRegularExpression));
if (QApplication::clipboard()->supportsFindBuffer())
m_enterFindStringAction->setEnabled(enabled);
bool replaceFocus = m_ui.replaceEdit->hasFocus();
@@ -396,16 +397,14 @@ void FindToolBar::invokeFindEnter()
void FindToolBar::invokeReplaceEnter()
{
- if (m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace()) {
+ if (m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace())
invokeReplaceNext();
- }
}
void FindToolBar::invokeClearResults()
{
- if (m_currentDocumentFind->isEnabled()) {
+ if (m_currentDocumentFind->isEnabled())
m_currentDocumentFind->clearResults();
- }
}
@@ -509,9 +508,8 @@ void FindToolBar::invokeReplaceAll()
{
m_plugin->updateFindCompletion(getFindText());
m_plugin->updateReplaceCompletion(getReplaceText());
- if (m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace()) {
+ if (m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace())
m_currentDocumentFind->replaceAll(getFindText(), getReplaceText(), effectiveFindFlags());
- }
}
void FindToolBar::invokeResetIncrementalSearch()
@@ -545,9 +543,8 @@ void FindToolBar::findFlagsChanged()
updateIcons();
updateFlagMenus();
invokeClearResults();
- if (isVisible()) {
+ if (isVisible())
m_currentDocumentFind->highlightAll(getFindText(), effectiveFindFlags());
- }
}
void FindToolBar::updateIcons()
@@ -556,7 +553,8 @@ void FindToolBar::updateIcons()
bool casesensitive = effectiveFlags & Find::FindCaseSensitively;
bool wholewords = effectiveFlags & Find::FindWholeWords;
bool regexp = effectiveFlags & Find::FindRegularExpression;
- if (!casesensitive && !wholewords && !regexp) {
+ bool preserveCase = effectiveFlags & Find::FindPreserveCase;
+ if (!casesensitive && !wholewords && !regexp && !preserveCase) {
QPixmap pixmap(17, 17);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
@@ -572,10 +570,15 @@ void FindToolBar::updateIcons()
Find::FindFlags FindToolBar::effectiveFindFlags()
{
Find::FindFlags supportedFlags;
- if (m_currentDocumentFind->isEnabled())
+ bool supportsReplace = true;
+ if (m_currentDocumentFind->isEnabled()) {
supportedFlags = m_currentDocumentFind->supportedFindFlags();
- else
+ supportsReplace = m_currentDocumentFind->supportsReplace();
+ } else {
supportedFlags = (Find::FindFlags)0xFFFFFF;
+ }
+ if (!supportsReplace || m_findFlags & Find::FindRegularExpression)
+ supportedFlags &= ~Find::FindPreserveCase;
return supportedFlags & m_findFlags;
}
@@ -584,18 +587,23 @@ void FindToolBar::updateFlagMenus()
bool wholeOnly = ((m_findFlags & Find::FindWholeWords));
bool sensitive = ((m_findFlags & Find::FindCaseSensitively));
bool regexp = ((m_findFlags & Find::FindRegularExpression));
+ bool preserveCase = ((m_findFlags & Find::FindPreserveCase));
if (m_wholeWordAction->isChecked() != wholeOnly)
m_wholeWordAction->setChecked(wholeOnly);
if (m_caseSensitiveAction->isChecked() != sensitive)
m_caseSensitiveAction->setChecked(sensitive);
if (m_regularExpressionAction->isChecked() != regexp)
m_regularExpressionAction->setChecked(regexp);
+ if (m_preserveCaseAction->isChecked() != preserveCase)
+ m_preserveCaseAction->setChecked(preserveCase);
Find::FindFlags supportedFlags;
if (m_currentDocumentFind->isEnabled())
supportedFlags = m_currentDocumentFind->supportedFindFlags();
m_wholeWordAction->setEnabled(supportedFlags & Find::FindWholeWords);
m_caseSensitiveAction->setEnabled(supportedFlags & Find::FindCaseSensitively);
m_regularExpressionAction->setEnabled(supportedFlags & Find::FindRegularExpression);
+ bool replaceEnabled = m_currentDocumentFind->isEnabled() && m_currentDocumentFind->supportsReplace();
+ m_preserveCaseAction->setEnabled((supportedFlags & Find::FindPreserveCase) && !regexp && replaceEnabled);
}
bool FindToolBar::setFocusToCurrentFindSupport()
@@ -689,6 +697,7 @@ void FindToolBar::writeSettings()
settings->setValue(QLatin1String("CaseSensitively"), QVariant((m_findFlags & Find::FindCaseSensitively) != 0));
settings->setValue(QLatin1String("WholeWords"), QVariant((m_findFlags & Find::FindWholeWords) != 0));
settings->setValue(QLatin1String("RegularExpression"), QVariant((m_findFlags & Find::FindRegularExpression) != 0));
+ settings->setValue(QLatin1String("PreserveCase"), QVariant((m_findFlags & Find::FindPreserveCase) != 0));
settings->endGroup();
settings->endGroup();
}
@@ -707,6 +716,8 @@ void FindToolBar::readSettings()
flags |= Find::FindWholeWords;
if (settings->value(QLatin1String("RegularExpression"), false).toBool())
flags |= Find::FindRegularExpression;
+ if (settings->value(QLatin1String("PreserveCase"), false).toBool())
+ flags |= Find::FindPreserveCase;
settings->endGroup();
settings->endGroup();
m_findFlags = flags;
@@ -751,6 +762,11 @@ void FindToolBar::setRegularExpressions(bool regexp)
setFindFlag(Find::FindRegularExpression, regexp);
}
+void FindToolBar::setPreserveCase(bool preserveCase)
+{
+ setFindFlag(Find::FindPreserveCase, preserveCase);
+}
+
void FindToolBar::setBackward(bool backward)
{
setFindFlag(Find::FindBackward, backward);
diff --git a/src/plugins/find/findtoolbar.h b/src/plugins/find/findtoolbar.h
index 4720219e47..6a341b80b2 100644
--- a/src/plugins/find/findtoolbar.h
+++ b/src/plugins/find/findtoolbar.h
@@ -91,6 +91,7 @@ private slots:
void setCaseSensitive(bool sensitive);
void setWholeWord(bool wholeOnly);
void setRegularExpressions(bool regexp);
+ void setPreserveCase(bool preserveCase);
void adaptToCandidate();
@@ -132,6 +133,7 @@ private:
QAction *m_caseSensitiveAction;
QAction *m_wholeWordAction;
QAction *m_regularExpressionAction;
+ QAction *m_preserveCaseAction;
Find::FindFlags m_findFlags;
QTimer m_findIncrementalTimer;
diff --git a/src/plugins/find/findtoolwindow.cpp b/src/plugins/find/findtoolwindow.cpp
index 989845d536..1707eaeeda 100644
--- a/src/plugins/find/findtoolwindow.cpp
+++ b/src/plugins/find/findtoolwindow.cpp
@@ -165,9 +165,8 @@ void FindToolWindow::setCurrentFilter(IFindFilter *filter)
if (!filter)
filter = m_currentFilter;
int index = m_filters.indexOf(filter);
- if (index >= 0) {
+ if (index >= 0)
setCurrentFilter(index);
- }
updateFindFlags();
m_ui.searchTerm->setFocus();
m_ui.searchTerm->selectAll();
@@ -185,9 +184,8 @@ void FindToolWindow::setCurrentFilter(int index)
m_currentFilter = m_filters.at(i);
connect(m_currentFilter, SIGNAL(enabledChanged(bool)), this, SLOT(updateButtonStates()));
updateButtonStates();
- if (m_configWidget) {
+ if (m_configWidget)
m_ui.configWidget->layout()->addWidget(m_configWidget);
- }
} else {
if (configWidget)
configWidget->setParent(0);
@@ -258,9 +256,8 @@ void FindToolWindow::readSettings()
for (int i = 0; i < m_filters.size(); ++i) {
IFindFilter *filter = m_filters.at(i);
filter->readSettings(settings);
- if (filter->id() == currentFilter) {
+ if (filter->id() == currentFilter)
setCurrentFilter(i);
- }
}
settings->endGroup();
}
diff --git a/src/plugins/find/ifindfilter.cpp b/src/plugins/find/ifindfilter.cpp
index 239e99e363..4fd3e2e62a 100644
--- a/src/plugins/find/ifindfilter.cpp
+++ b/src/plugins/find/ifindfilter.cpp
@@ -225,13 +225,16 @@ QPixmap Find::IFindFilter::pixmapForFindFlags(Find::FindFlags flags)
static const QPixmap casesensitiveIcon = QPixmap(QLatin1String(":/find/images/casesensitively.png"));
static const QPixmap regexpIcon = QPixmap(QLatin1String(":/find/images/regexp.png"));
static const QPixmap wholewordsIcon = QPixmap(QLatin1String(":/find/images/wholewords.png"));
+ static const QPixmap preservecaseIcon = QPixmap(QLatin1String(":/find/images/preservecase.png"));
bool casesensitive = flags & Find::FindCaseSensitively;
bool wholewords = flags & Find::FindWholeWords;
bool regexp = flags & Find::FindRegularExpression;
+ bool preservecase = flags & Find::FindPreserveCase;
int width = 0;
if (casesensitive) width += 6;
if (wholewords) width += 6;
if (regexp) width += 6;
+ if (preservecase) width += 6;
if (width > 0) --width;
QPixmap pixmap(width, 17);
pixmap.fill(Qt::transparent);
@@ -248,7 +251,10 @@ QPixmap Find::IFindFilter::pixmapForFindFlags(Find::FindFlags flags)
}
if (regexp) {
painter.drawPixmap(x - 6, 0, regexpIcon);
+ x += 6;
}
+ if (preservecase)
+ painter.drawPixmap(x - 6, 0, preservecaseIcon);
return pixmap;
}
@@ -261,6 +267,8 @@ QString Find::IFindFilter::descriptionForFindFlags(Find::FindFlags flags)
flagStrings.append(tr("Whole words"));
if (flags & Find::FindRegularExpression)
flagStrings.append(tr("Regular expressions"));
+ if (flags & Find::FindPreserveCase)
+ flagStrings.append(tr("Preserve case"));
QString description = tr("Flags: %1");
if (flagStrings.isEmpty())
description = description.arg(tr("None"));
diff --git a/src/plugins/find/images/preservecase.png b/src/plugins/find/images/preservecase.png
new file mode 100644
index 0000000000..4869aabd71
--- /dev/null
+++ b/src/plugins/find/images/preservecase.png
Binary files differ
diff --git a/src/plugins/find/searchresultcolor.h b/src/plugins/find/searchresultcolor.h
new file mode 100644
index 0000000000..fab3e06bb2
--- /dev/null
+++ b/src/plugins/find/searchresultcolor.h
@@ -0,0 +1,20 @@
+#ifndef SEARCHRESULTCOLOR_H
+#define SEARCHRESULTCOLOR_H
+
+#include <QColor>
+
+namespace Find {
+namespace Internal {
+
+class SearchResultColor{
+public:
+ QColor textBackground;
+ QColor textForeground;
+ QColor highlightBackground;
+ QColor highlightForeground;
+};
+
+} // namespace Internal
+} // namespace Find
+
+#endif // SEARCHRESULTCOLOR_H
diff --git a/src/plugins/find/searchresulttreeitemdelegate.cpp b/src/plugins/find/searchresulttreeitemdelegate.cpp
index df530a7be3..cd4e5e3a66 100644
--- a/src/plugins/find/searchresulttreeitemdelegate.cpp
+++ b/src/plugins/find/searchresulttreeitemdelegate.cpp
@@ -78,9 +78,8 @@ void SearchResultTreeItemDelegate::paint(QPainter *painter, const QStyleOptionVi
// icon
QIcon icon = index.model()->data(index, ItemDataRoles::ResultIconRole).value<QIcon>();
- if (!icon.isNull()) {
+ if (!icon.isNull())
pixmapRect = QRect(0, 0, iconSize, iconSize);
- }
// text
textRect = opt.rect.adjusted(0, 0, checkRect.width() + pixmapRect.width(), 0);
@@ -97,19 +96,8 @@ void SearchResultTreeItemDelegate::paint(QPainter *painter, const QStyleOptionVi
int lineNumberAreaWidth = drawLineNumber(painter, opt, textRect, index);
textRect.adjust(lineNumberAreaWidth, 0, 0, 0);
- // selected text
- QString displayString = index.model()->data(index, Qt::DisplayRole).toString();
- drawMarker(painter, index, displayString, textRect);
-
- // show number of subresults in displayString
- if (index.model()->hasChildren(index)) {
- displayString += QString::fromLatin1(" (")
- + QString::number(index.model()->rowCount(index))
- + QLatin1Char(')');
- }
-
// text and focus/selection
- QItemDelegate::drawDisplay(painter, opt, textRect, displayString);
+ drawText(painter, opt, textRect, index);
QItemDelegate::drawFocus(painter, opt, opt.rect);
// check mark
@@ -159,20 +147,65 @@ int SearchResultTreeItemDelegate::drawLineNumber(QPainter *painter, const QStyle
return lineNumberAreaWidth;
}
-void SearchResultTreeItemDelegate::drawMarker(QPainter *painter, const QModelIndex &index, const QString text,
- const QRect &rect) const
+void SearchResultTreeItemDelegate::drawText(QPainter *painter,
+ const QStyleOptionViewItem &opt,
+ const QRect &rect,
+ const QModelIndex &index) const
{
- int searchTermStart = index.model()->data(index, ItemDataRoles::SearchTermStartRole).toInt();
+ QString text = index.model()->data(index, Qt::DisplayRole).toString();
+ // show number of subresults in displayString
+ if (index.model()->hasChildren(index)) {
+ text += QLatin1String(" (")
+ + QString::number(index.model()->rowCount(index))
+ + QLatin1Char(')');
+ }
+
+ const int searchTermStart = index.model()->data(index, ItemDataRoles::SearchTermStartRole).toInt();
int searchTermLength = index.model()->data(index, ItemDataRoles::SearchTermLengthRole).toInt();
- if (searchTermStart < 0 || searchTermStart >= text.length() || searchTermLength < 1)
+ if (searchTermStart < 0 || searchTermStart >= text.length() || searchTermLength < 1) {
+ QItemDelegate::drawDisplay(painter, opt, rect, text);
return;
+ }
// clip searchTermLength to end of line
searchTermLength = qMin(searchTermLength, text.length() - searchTermStart);
const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
int searchTermStartPixels = painter->fontMetrics().width(text.left(searchTermStart));
int searchTermLengthPixels = painter->fontMetrics().width(text.mid(searchTermStart, searchTermLength));
+
+ // Text before the highlighting
+ QRect beforeHighlightRect(rect);
+ beforeHighlightRect.setRight(beforeHighlightRect.left() + searchTermStartPixels);
+ QStyleOptionViewItem noHighlightOpt = opt;
+ noHighlightOpt.rect = beforeHighlightRect;
+ noHighlightOpt.textElideMode = Qt::ElideNone;
+ QItemDelegate::drawDisplay(painter, noHighlightOpt,
+ beforeHighlightRect, text.mid(0, searchTermStart));
+
+ // Highlight background
+ QRect highlightBackgroundRect(rect);
+ highlightBackgroundRect.setLeft(highlightBackgroundRect.left()
+ + searchTermStartPixels + textMargin - 1); // -1: Cosmetics
+ highlightBackgroundRect.setRight(highlightBackgroundRect.left()
+ + searchTermLengthPixels + 1); // +1: Cosmetics
+ const QColor highlightBackground =
+ index.model()->data(index, ItemDataRoles::ResultHighlightBackgroundColor).value<QColor>();
+ painter->fillRect(highlightBackgroundRect, QBrush(highlightBackground));
+
+ // Highlight text
QRect resultHighlightRect(rect);
- resultHighlightRect.setLeft(resultHighlightRect.left() + searchTermStartPixels + textMargin - 1); // -1: Cosmetics
- resultHighlightRect.setRight(resultHighlightRect.left() + searchTermLengthPixels + 1); // +1: Cosmetics
- painter->fillRect(resultHighlightRect, QBrush(qRgb(255, 240, 120)));
+ resultHighlightRect.setLeft(beforeHighlightRect.right());
+ resultHighlightRect.setRight(resultHighlightRect.left() + searchTermLengthPixels + textMargin);
+ QStyleOptionViewItem highlightOpt = noHighlightOpt;
+ const QColor highlightForeground =
+ index.model()->data(index, ItemDataRoles::ResultHighlightForegroundColor).value<QColor>();
+ highlightOpt.palette.setColor(QPalette::Text, highlightForeground);
+ QItemDelegate::drawDisplay(painter, highlightOpt, resultHighlightRect,
+ text.mid(searchTermStart, searchTermLength));
+
+ // Text after the Highlight
+ QRect afterHighlightRect(rect);
+ afterHighlightRect.setLeft(resultHighlightRect.right());
+ noHighlightOpt.rect = afterHighlightRect;
+ QItemDelegate::drawDisplay(painter, noHighlightOpt, afterHighlightRect,
+ text.mid(searchTermStart + searchTermLength));
}
diff --git a/src/plugins/find/searchresulttreeitemdelegate.h b/src/plugins/find/searchresulttreeitemdelegate.h
index 0646ced5d5..d1659df148 100644
--- a/src/plugins/find/searchresulttreeitemdelegate.h
+++ b/src/plugins/find/searchresulttreeitemdelegate.h
@@ -43,7 +43,8 @@ public:
private:
int drawLineNumber(QPainter *painter, const QStyleOptionViewItemV3 &option, const QRect &rect, const QModelIndex &index) const;
- void drawMarker(QPainter *painter, const QModelIndex &index, const QString text, const QRect &rect) const;
+ void drawText(QPainter *painter, const QStyleOptionViewItem &opt,
+ const QRect &rect, const QModelIndex &index) const;
static const int m_minimumLineNumberDigits = 6;
};
diff --git a/src/plugins/find/searchresulttreeitemroles.h b/src/plugins/find/searchresulttreeitemroles.h
index b638b97297..6e21a32d8e 100644
--- a/src/plugins/find/searchresulttreeitemroles.h
+++ b/src/plugins/find/searchresulttreeitemroles.h
@@ -42,6 +42,8 @@ enum Roles
ResultLineRole,
ResultLineNumberRole,
ResultIconRole,
+ ResultHighlightBackgroundColor,
+ ResultHighlightForegroundColor,
SearchTermStartRole,
SearchTermLengthRole,
IsGeneratedRole
diff --git a/src/plugins/find/searchresulttreeitems.cpp b/src/plugins/find/searchresulttreeitems.cpp
index b319cddd25..1503fa71e7 100644
--- a/src/plugins/find/searchresulttreeitems.cpp
+++ b/src/plugins/find/searchresulttreeitems.cpp
@@ -107,11 +107,10 @@ int SearchResultTreeItem::insertionIndex(const QString &text, SearchResultTreeIt
QList<SearchResultTreeItem *>::const_iterator insertionPosition =
qLowerBound(m_children.begin(), m_children.end(), text, lessThanByText);
if (existingItem) {
- if (insertionPosition != m_children.end() && (*insertionPosition)->item.text == text) {
+ if (insertionPosition != m_children.end() && (*insertionPosition)->item.text == text)
(*existingItem) = (*insertionPosition);
- } else {
+ else
*existingItem = 0;
- }
}
return insertionPosition - m_children.begin();
}
diff --git a/src/plugins/find/searchresulttreemodel.cpp b/src/plugins/find/searchresulttreemodel.cpp
index ad83e178b5..141ff24fa5 100644
--- a/src/plugins/find/searchresulttreemodel.cpp
+++ b/src/plugins/find/searchresulttreemodel.cpp
@@ -30,6 +30,7 @@
#include "searchresulttreemodel.h"
#include "searchresulttreeitems.h"
#include "searchresulttreeitemroles.h"
+#include "searchresultcolor.h"
#include <QApplication>
#include <QFont>
@@ -64,10 +65,11 @@ void SearchResultTreeModel::setShowReplaceUI(bool show)
m_showReplaceUI = show;
}
-void SearchResultTreeModel::setTextEditorFont(const QFont &font)
+void SearchResultTreeModel::setTextEditorFont(const QFont &font, const SearchResultColor color)
{
layoutAboutToBeChanged();
m_textEditorFont = font;
+ m_color = color;
layoutChanged();
}
@@ -77,9 +79,8 @@ Qt::ItemFlags SearchResultTreeModel::flags(const QModelIndex &idx) const
if (idx.isValid()) {
if (const SearchResultTreeItem *item = treeItemAtIndex(idx)) {
- if (item->isUserCheckable()) {
+ if (item->isUserCheckable())
flags |= Qt::ItemIsUserCheckable;
- }
}
}
@@ -200,13 +201,12 @@ bool SearchResultTreeModel::setCheckState(const QModelIndex &idx, Qt::CheckState
SearchResultTreeItem *child = parent->childAt(i);
if (!child->isUserCheckable())
continue;
- if (child->checkState() == Qt::Checked) {
+ if (child->checkState() == Qt::Checked)
hasChecked = true;
- } else if (child->checkState() == Qt::Unchecked) {
+ else if (child->checkState() == Qt::Unchecked)
hasUnchecked = true;
- } else if (child->checkState() == Qt::PartiallyChecked) {
+ else if (child->checkState() == Qt::PartiallyChecked)
hasChecked = hasUnchecked = true;
- }
}
if (hasChecked && hasUnchecked)
parent->setCheckState(Qt::PartiallyChecked);
@@ -251,6 +251,14 @@ QVariant SearchResultTreeModel::data(const SearchResultTreeItem *row, int role)
else
result = QVariant();
break;
+ case Qt::TextColorRole:
+ if (row->item.useTextEditorFont)
+ result = m_color.textForeground;
+ break;
+ case Qt::BackgroundRole:
+ if (row->item.useTextEditorFont)
+ result = m_color.textBackground;
+ break;
case ItemDataRoles::ResultLineRole:
case Qt::DisplayRole:
result = row->item.text;
@@ -264,6 +272,14 @@ QVariant SearchResultTreeModel::data(const SearchResultTreeItem *row, int role)
case ItemDataRoles::ResultIconRole:
result = row->item.icon;
break;
+ case ItemDataRoles::ResultHighlightBackgroundColor:
+ if (row->item.useTextEditorFont)
+ result = m_color.highlightBackground;
+ break;
+ case ItemDataRoles::ResultHighlightForegroundColor:
+ if (row->item.useTextEditorFont)
+ result = m_color.highlightForeground;
+ break;
case ItemDataRoles::SearchTermStartRole:
result = row->item.textMarkPos;
break;
@@ -410,10 +426,11 @@ QList<QModelIndex> SearchResultTreeModel::addResults(const QList<SearchResultIte
void SearchResultTreeModel::clear()
{
+ beginResetModel();
m_currentParent = NULL;
m_rootItem->clearChildren();
m_editorFontIsUsed = false;
- reset();
+ endResetModel();
}
QModelIndex SearchResultTreeModel::nextIndex(const QModelIndex &idx, bool *wrapped) const
diff --git a/src/plugins/find/searchresulttreemodel.h b/src/plugins/find/searchresulttreemodel.h
index a6075bf699..d52326dc14 100644
--- a/src/plugins/find/searchresulttreemodel.h
+++ b/src/plugins/find/searchresulttreemodel.h
@@ -31,6 +31,7 @@
#define SEARCHRESULTTREEMODEL_H
#include "searchresultwindow.h"
+#include "searchresultcolor.h"
#include <QAbstractItemModel>
#include <QRegExp>
@@ -51,7 +52,7 @@ public:
~SearchResultTreeModel();
void setShowReplaceUI(bool show);
- void setTextEditorFont(const QFont &font);
+ void setTextEditorFont(const QFont &font, const SearchResultColor color);
Qt::ItemFlags flags(const QModelIndex &index) const;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
@@ -86,6 +87,7 @@ private:
SearchResultTreeItem *m_rootItem;
SearchResultTreeItem *m_currentParent;
+ SearchResultColor m_color;
QModelIndex m_currentIndex;
QStringList m_currentPath; // the path that belongs to the current parent
QFont m_textEditorFont;
diff --git a/src/plugins/find/searchresulttreeview.cpp b/src/plugins/find/searchresulttreeview.cpp
index dd04b096a6..2fa0df8856 100644
--- a/src/plugins/find/searchresulttreeview.cpp
+++ b/src/plugins/find/searchresulttreeview.cpp
@@ -31,6 +31,7 @@
#include "searchresulttreeitemroles.h"
#include "searchresulttreemodel.h"
#include "searchresulttreeitemdelegate.h"
+#include "searchresultcolor.h"
#include <QHeaderView>
#include <QKeyEvent>
@@ -57,9 +58,9 @@ void SearchResultTreeView::setAutoExpandResults(bool expand)
m_autoExpandResults = expand;
}
-void SearchResultTreeView::setTextEditorFont(const QFont &font)
+void SearchResultTreeView::setTextEditorFont(const QFont &font, const SearchResultColor color)
{
- m_model->setTextEditorFont(font);
+ m_model->setTextEditorFont(font, color);
}
void SearchResultTreeView::clear()
diff --git a/src/plugins/find/searchresulttreeview.h b/src/plugins/find/searchresulttreeview.h
index cec2a8c59e..4b4a3d205e 100644
--- a/src/plugins/find/searchresulttreeview.h
+++ b/src/plugins/find/searchresulttreeview.h
@@ -38,6 +38,7 @@ namespace Find {
namespace Internal {
class SearchResultTreeModel;
+class SearchResultColor;
class SearchResultTreeView : public QTreeView
{
@@ -47,7 +48,7 @@ public:
explicit SearchResultTreeView(QWidget *parent = 0);
void setAutoExpandResults(bool expand);
- void setTextEditorFont(const QFont &font);
+ void setTextEditorFont(const QFont &font, const SearchResultColor color);
SearchResultTreeModel *model() const;
void addResults(const QList<Find::SearchResultItem> &items, SearchResult::AddMode mode);
diff --git a/src/plugins/find/searchresultwidget.cpp b/src/plugins/find/searchresultwidget.cpp
index 65ae397310..bc7aa6e549 100644
--- a/src/plugins/find/searchresultwidget.cpp
+++ b/src/plugins/find/searchresultwidget.cpp
@@ -32,8 +32,10 @@
#include "searchresulttreemodel.h"
#include "searchresulttreeitems.h"
#include "searchresulttreeitemroles.h"
+#include "searchresultcolor.h"
#include "ifindsupport.h"
+#include "findplugin.h"
#include "treeviewfind.h"
#include <aggregation/aggregate.h>
@@ -78,8 +80,6 @@ using namespace Find::Internal;
SearchResultWidget::SearchResultWidget(QWidget *parent) :
QWidget(parent),
m_count(0),
- m_sizeWarningActive(false),
- m_sizeWarningOverridden(false),
m_isShowingReplaceUI(false),
m_searchAgainSupported(false)
{
@@ -162,6 +162,14 @@ SearchResultWidget::SearchResultWidget(QWidget *parent) :
m_replaceButton->setText(tr("Replace"));
m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
m_replaceButton->setEnabled(false);
+ m_preserveCaseCheck = new QCheckBox(topWidget);
+ m_preserveCaseCheck->setText(tr("Preserve case"));
+ m_preserveCaseCheck->setEnabled(false);
+
+ if (FindPlugin * plugin = FindPlugin::instance()) {
+ m_preserveCaseCheck->setChecked(plugin->hasFindFlag(Find::FindPreserveCase));
+ connect(m_preserveCaseCheck, SIGNAL(clicked(bool)), plugin, SLOT(setPreserveCase(bool)));
+ }
m_matchesFoundLabel = new QLabel(topWidget);
updateMatchesFoundLabel();
@@ -172,6 +180,7 @@ SearchResultWidget::SearchResultWidget(QWidget *parent) :
topLayout->addWidget(m_replaceLabel);
topLayout->addWidget(m_replaceTextEdit);
topLayout->addWidget(m_replaceButton);
+ topLayout->addWidget(m_preserveCaseCheck);
topLayout->addStretch(2);
topLayout->addWidget(m_matchesFoundLabel);
topWidget->setMinimumHeight(m_cancelButton->sizeHint().height()
@@ -187,7 +196,7 @@ SearchResultWidget::SearchResultWidget(QWidget *parent) :
SearchResultWidget::~SearchResultWidget()
{
- if (m_sizeWarningActive)
+ if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID)))
cancelAfterSizeWarning();
}
@@ -221,10 +230,13 @@ void SearchResultWidget::addResults(const QList<SearchResultItem> &items, Search
m_searchResultTreeView->addResults(items, mode);
updateMatchesFoundLabel();
if (firstItems) {
- if (showWarningMessage()) {
- Core::InfoBarEntry info(QLatin1String(UNDO_WARNING_ID), tr("This change cannot be undone."));
- info.setCustomButtonInfo(tr("Do not warn again"), this, SLOT(hideNoUndoWarning()));
- m_infoBar.addInfo(info);
+ if (!m_dontAskAgainGroup.isEmpty()) {
+ Core::Id undoWarningId(QByteArray(UNDO_WARNING_ID) + '/' + m_dontAskAgainGroup.toLatin1());
+ if (m_infoBar.canInfoBeAdded(undoWarningId)) {
+ Core::InfoBarEntry info(undoWarningId, tr("This change cannot be undone."),
+ Core::InfoBarEntry::GlobalSuppressionEnabled);
+ m_infoBar.addInfo(info);
+ }
}
m_replaceTextEdit->setEnabled(true);
@@ -237,10 +249,14 @@ void SearchResultWidget::addResults(const QList<SearchResultItem> &items, Search
}
m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select);
emit navigateStateChanged();
- } else if (m_count > SEARCHRESULT_WARNING_LIMIT && !m_sizeWarningOverridden && !m_sizeWarningActive) {
- m_sizeWarningActive = true;
+ } else if (m_count <= SEARCHRESULT_WARNING_LIMIT) {
+ return;
+ } else {
+ Core::Id sizeWarningId(SIZE_WARNING_ID);
+ if (!m_infoBar.canInfoBeAdded(sizeWarningId))
+ return;
emit paused(true);
- Core::InfoBarEntry info(QLatin1String(SIZE_WARNING_ID),
+ Core::InfoBarEntry info(sizeWarningId,
tr("The search resulted in more than %n items, do you still want to continue?",
0, SEARCHRESULT_WARNING_LIMIT));
info.setCancelButtonInfo(tr("Cancel"), this, SLOT(cancelAfterSizeWarning()));
@@ -284,6 +300,7 @@ void SearchResultWidget::setShowReplaceUI(bool visible)
m_replaceLabel->setVisible(visible);
m_replaceTextEdit->setVisible(visible);
m_replaceButton->setVisible(visible);
+ m_preserveCaseCheck->setVisible(visible);
m_isShowingReplaceUI = visible;
}
@@ -318,9 +335,9 @@ void SearchResultWidget::notifyVisibilityChanged(bool visible)
emit visibilityChanged(visible);
}
-void SearchResultWidget::setTextEditorFont(const QFont &font)
+void SearchResultWidget::setTextEditorFont(const QFont &font, const SearchResultColor color)
{
- m_searchResultTreeView->setTextEditorFont(font);
+ m_searchResultTreeView->setTextEditorFont(font, color);
}
void SearchResultWidget::setAutoExpandResults(bool expand)
@@ -366,10 +383,9 @@ void SearchResultWidget::restart()
m_replaceButton->setEnabled(false);
m_searchResultTreeView->clear();
m_count = 0;
- if (m_sizeWarningActive)
- m_infoBar.removeInfo(QLatin1String(SIZE_WARNING_ID));
- m_sizeWarningActive = false;
- m_sizeWarningOverridden = false;
+ Core::Id sizeWarningId(SIZE_WARNING_ID);
+ m_infoBar.removeInfo(sizeWarningId);
+ m_infoBar.enableInfo(sizeWarningId);
m_cancelButton->setVisible(true);
m_searchAgainButton->setVisible(false);
m_messageWidget->setVisible(false);
@@ -390,12 +406,12 @@ void SearchResultWidget::setSearchAgainEnabled(bool enabled)
void SearchResultWidget::finishSearch(bool canceled)
{
- if (m_sizeWarningActive)
- m_infoBar.removeInfo(QLatin1String(SIZE_WARNING_ID));
- m_sizeWarningActive = false;
- m_sizeWarningOverridden = false;
+ Core::Id sizeWarningId(SIZE_WARNING_ID);
+ m_infoBar.removeInfo(sizeWarningId);
+ m_infoBar.enableInfo(sizeWarningId);
m_replaceTextEdit->setEnabled(m_count > 0);
m_replaceButton->setEnabled(m_count > 0);
+ m_preserveCaseCheck->setEnabled(m_count > 0);
m_cancelButton->setVisible(false);
m_messageWidget->setVisible(canceled);
m_searchAgainButton->setVisible(m_searchAgainSupported);
@@ -406,25 +422,15 @@ void SearchResultWidget::sendRequestPopup()
emit requestPopup(true/*focus*/);
}
-void SearchResultWidget::hideNoUndoWarning()
-{
- setShowWarningMessage(false);
- m_infoBar.removeInfo(QLatin1String(UNDO_WARNING_ID));
-}
-
void SearchResultWidget::continueAfterSizeWarning()
{
- m_sizeWarningOverridden = true;
- m_sizeWarningActive = false;
- m_infoBar.removeInfo(QLatin1String(SIZE_WARNING_ID));
+ m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID));
emit paused(false);
}
void SearchResultWidget::cancelAfterSizeWarning()
{
- m_infoBar.removeInfo(QLatin1String(SIZE_WARNING_ID));
- m_sizeWarningOverridden = true;
- m_sizeWarningActive = false;
+ m_infoBar.suppressInfo(Core::Id(SIZE_WARNING_ID));
emit cancelled();
emit paused(false);
}
@@ -440,14 +446,14 @@ void SearchResultWidget::handleReplaceButton()
// by pressing return in replace line edit
if (m_replaceButton->isEnabled()) {
m_infoBar.clear();
- emit replaceButtonClicked(m_replaceTextEdit->text(), checkedItems());
+ emit replaceButtonClicked(m_replaceTextEdit->text(), checkedItems(), m_preserveCaseCheck->isChecked());
}
}
void SearchResultWidget::cancel()
{
m_cancelButton->setVisible(false);
- if (m_sizeWarningActive)
+ if (m_infoBar.containsInfo(Core::Id(SIZE_WARNING_ID)))
cancelAfterSizeWarning();
else
emit cancelled();
@@ -458,31 +464,6 @@ void SearchResultWidget::searchAgain()
emit searchAgainRequested();
}
-bool SearchResultWidget::showWarningMessage() const
-{
- if (m_dontAskAgainGroup.isEmpty() || m_infoBar.containsInfo(QLatin1String(UNDO_WARNING_ID)))
- return false;
- // read settings
- QSettings *settings = Core::ICore::settings();
- settings->beginGroup(m_dontAskAgainGroup);
- settings->beginGroup(QLatin1String("Rename"));
- const bool showWarningMessage = settings->value(QLatin1String("ShowWarningMessage"), true).toBool();
- settings->endGroup();
- settings->endGroup();
- return showWarningMessage;
-}
-
-void SearchResultWidget::setShowWarningMessage(bool showWarningMessage)
-{
- // write to settings
- QSettings *settings = Core::ICore::settings();
- settings->beginGroup(m_dontAskAgainGroup);
- settings->beginGroup(QLatin1String("Rename"));
- settings->setValue(QLatin1String("ShowWarningMessage"), showWarningMessage);
- settings->endGroup();
- settings->endGroup();
-}
-
QList<SearchResultItem> SearchResultWidget::checkedItems() const
{
QList<SearchResultItem> result;
diff --git a/src/plugins/find/searchresultwidget.h b/src/plugins/find/searchresultwidget.h
index db49fb1543..a3cf60fbf5 100644
--- a/src/plugins/find/searchresultwidget.h
+++ b/src/plugins/find/searchresultwidget.h
@@ -39,11 +39,13 @@
#include <QLineEdit>
#include <QToolButton>
#include <QWidget>
+#include <QCheckBox>
namespace Find {
namespace Internal {
class SearchResultTreeView;
+class SearchResultColor;
class SearchResultWidget : public QWidget
{
@@ -73,7 +75,7 @@ public:
void notifyVisibilityChanged(bool visible);
- void setTextEditorFont(const QFont &font);
+ void setTextEditorFont(const QFont &font, const SearchResultColor color);
void setAutoExpandResults(bool expand);
void expandAll();
@@ -93,7 +95,7 @@ public slots:
signals:
void activated(const Find::SearchResultItem &item);
- void replaceButtonClicked(const QString &replaceText, const QList<Find::SearchResultItem> &checkedItems);
+ void replaceButtonClicked(const QString &replaceText, const QList<Find::SearchResultItem> &checkedItems, bool preserveCase);
void searchAgainRequested();
void cancelled();
void paused(bool paused);
@@ -104,7 +106,6 @@ signals:
void navigateStateChanged();
private slots:
- void hideNoUndoWarning();
void continueAfterSizeWarning();
void cancelAfterSizeWarning();
void handleJumpToSearchResult(const SearchResultItem &item);
@@ -113,15 +114,11 @@ private slots:
void searchAgain();
private:
- bool showWarningMessage() const;
- void setShowWarningMessage(bool showWarningMessage);
QList<SearchResultItem> checkedItems() const;
void updateMatchesFoundLabel();
SearchResultTreeView *m_searchResultTreeView;
int m_count;
- bool m_sizeWarningActive;
- bool m_sizeWarningOverridden;
QString m_dontAskAgainGroup;
QFrame *m_messageWidget;
Core::InfoBar m_infoBar;
@@ -131,6 +128,7 @@ private:
QLineEdit *m_replaceTextEdit;
QToolButton *m_replaceButton;
QToolButton *m_searchAgainButton;
+ QCheckBox *m_preserveCaseCheck;
bool m_searchAgainSupported;
QWidget *m_descriptionContainer;
QLabel *m_label;
diff --git a/src/plugins/find/searchresultwindow.cpp b/src/plugins/find/searchresultwindow.cpp
index 09ac977ca3..e47d493391 100644
--- a/src/plugins/find/searchresultwindow.cpp
+++ b/src/plugins/find/searchresultwindow.cpp
@@ -29,6 +29,7 @@
#include "searchresultwindow.h"
#include "searchresultwidget.h"
+#include "searchresultcolor.h"
#include "findtoolwindow.h"
#include <coreplugin/icore.h>
@@ -96,6 +97,7 @@ namespace Internal {
QList<SearchResult *> m_searchResults;
int m_currentIndex;
QFont m_font;
+ SearchResultColor m_color;
public slots:
void setCurrentIndex(int index);
@@ -216,7 +218,7 @@ using namespace Find::Internal;
*/
/*!
- \fn void SearchResult::replaceButtonClicked(const QString &replaceText, const QList<Find::SearchResultItem> &checkedItems)
+ \fn void SearchResult::replaceButtonClicked(const QString &replaceText, const QList<Find::SearchResultItem> &checkedItems, bool preserveCase)
\brief Sent when the user initiated a replace, e.g. by pressing the replace
all button.
@@ -398,7 +400,7 @@ SearchResult *SearchResultWindow::startNewSearch(const QString &label,
connect(widget, SIGNAL(navigateStateChanged()), this, SLOT(navigateStateChanged()));
connect(widget, SIGNAL(restarted()), d, SLOT(moveWidgetToTop()));
connect(widget, SIGNAL(requestPopup(bool)), d, SLOT(popupRequested(bool)));
- widget->setTextEditorFont(d->m_font);
+ widget->setTextEditorFont(d->m_font, d->m_color);
widget->setShowReplaceUI(searchOrSearchAndReplace != SearchOnly);
widget->setAutoExpandResults(d->m_expandCollapseAction->isChecked());
widget->setInfo(label, toolTip, searchTerm);
@@ -470,11 +472,25 @@ void SearchResultWindow::setFocus()
\fn void SearchResultWindow::setTextEditorFont(const QFont &font)
\internal
*/
-void SearchResultWindow::setTextEditorFont(const QFont &font)
+void SearchResultWindow::setTextEditorFont(const QFont &font,
+ const QColor &textForegroundColor,
+ const QColor &textBackgroundColor,
+ const QColor &highlightForegroundColor,
+ const QColor &highlightBackgroundColor)
{
d->m_font = font;
+ Internal::SearchResultColor color;
+ color.textBackground = textBackgroundColor;
+ color.textForeground = textForegroundColor;
+ color.highlightBackground = highlightBackgroundColor.isValid()
+ ? highlightBackgroundColor
+ : textBackgroundColor;
+ color.highlightForeground = highlightForegroundColor.isValid()
+ ? highlightForegroundColor
+ : textForegroundColor;
+ d->m_color = color;
foreach (Internal::SearchResultWidget *widget, d->m_searchResultWidgets)
- widget->setTextEditorFont(font);
+ widget->setTextEditorFont(font, color);
}
void SearchResultWindow::openNewSearchPanel()
@@ -598,8 +614,8 @@ SearchResult::SearchResult(SearchResultWidget *widget)
{
connect(widget, SIGNAL(activated(Find::SearchResultItem)),
this, SIGNAL(activated(Find::SearchResultItem)));
- connect(widget, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
- this, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)));
+ connect(widget, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)),
+ this, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)));
connect(widget, SIGNAL(cancelled()),
this, SIGNAL(cancelled()));
connect(widget, SIGNAL(paused(bool)),
diff --git a/src/plugins/find/searchresultwindow.h b/src/plugins/find/searchresultwindow.h
index 146b82b1cd..5715032476 100644
--- a/src/plugins/find/searchresultwindow.h
+++ b/src/plugins/find/searchresultwindow.h
@@ -110,7 +110,7 @@ public slots:
signals:
void activated(const Find::SearchResultItem &item);
- void replaceButtonClicked(const QString &replaceText, const QList<Find::SearchResultItem> &checkedItems);
+ void replaceButtonClicked(const QString &replaceText, const QList<Find::SearchResultItem> &checkedItems, bool preserveCase);
void cancelled();
void paused(bool paused);
void visibilityChanged(bool visible);
@@ -157,7 +157,11 @@ public:
void goToPrev();
bool canNavigate() const;
- void setTextEditorFont(const QFont &font);
+ void setTextEditorFont(const QFont &font,
+ const QColor &textForegroundColor,
+ const QColor &textBackgroundColor,
+ const QColor &highlightForegroundColor,
+ const QColor &highlightBackgroundColor);
void openNewSearchPanel();
// The search result window owns the returned SearchResult
diff --git a/src/plugins/find/textfindconstants.h b/src/plugins/find/textfindconstants.h
index d851c9ee3e..2383451a47 100644
--- a/src/plugins/find/textfindconstants.h
+++ b/src/plugins/find/textfindconstants.h
@@ -59,6 +59,7 @@ const char REPLACE_ALL[] = "Find.ReplaceAll";
const char CASE_SENSITIVE[] = "Find.CaseSensitive";
const char WHOLE_WORDS[] = "Find.WholeWords";
const char REGULAR_EXPRESSIONS[] = "Find.RegularExpressions";
+const char PRESERVE_CASE[] = "Find.PreserveCase";
const char TASK_SEARCH[] = "Find.Task.Search";
} // namespace Constants
@@ -67,7 +68,8 @@ enum FindFlag {
FindBackward = 0x01,
FindCaseSensitively = 0x02,
FindWholeWords = 0x04,
- FindRegularExpression = 0x08
+ FindRegularExpression = 0x08,
+ FindPreserveCase = 0x10
};
Q_DECLARE_FLAGS(FindFlags, FindFlag)
diff --git a/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp b/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp
index 2b47966674..9f8c714473 100644
--- a/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp
+++ b/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp
@@ -55,8 +55,8 @@ FilesSelectionWizardPage::FilesSelectionWizardPage(GenericProjectWizardDialog *g
hbox->addWidget(m_filterLabel);
m_filterLineEdit = new QLineEdit;
- const QString filter = Core::ICore::settings()->value(Constants::FILEFILTER_SETTING,
- Constants::FILEFILTER_DEFAULT).toString();
+ const QString filter = Core::ICore::settings()->value(QLatin1String(Constants::FILEFILTER_SETTING),
+ QLatin1String(Constants::FILEFILTER_DEFAULT)).toString();
m_filterLineEdit->setText(filter);
m_filterLineEdit->hide();
hbox->addWidget(m_filterLineEdit);
@@ -140,7 +140,7 @@ QStringList FilesSelectionWizardPage::selectedFiles() const
void FilesSelectionWizardPage::applyFilter()
{
const QString filter = m_filterLineEdit->text();
- Core::ICore::settings()->setValue(Constants::FILEFILTER_SETTING, filter);
+ Core::ICore::settings()->setValue(QLatin1String(Constants::FILEFILTER_SETTING), filter);
m_model->applyFilter(filter);
}
diff --git a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
index a07a572ecd..663552a635 100644
--- a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
+++ b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp
@@ -105,18 +105,11 @@ void GenericBuildConfiguration::setBuildDirectory(const QString &buildDirectory)
emit buildDirectoryChanged();
}
-BuildConfigWidget *GenericBuildConfiguration::createConfigWidget()
+NamedWidget *GenericBuildConfiguration::createConfigWidget()
{
- return new GenericBuildSettingsWidget;
+ return new GenericBuildSettingsWidget(this);
}
-IOutputParser *GenericBuildConfiguration::createOutputParser() const
-{
- ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit());
- return tc ? tc->outputParser() : 0;
-}
-
-
/*!
\class GenericBuildConfigurationFactory
*/
@@ -162,7 +155,7 @@ BuildConfiguration *GenericBuildConfigurationFactory::create(Target *parent, con
// wizards will show up, that incorporate choosing the nam
bool ok = true;
QString buildConfigurationName = name;
- if (buildConfigurationName.isEmpty())
+ if (buildConfigurationName.isNull())
buildConfigurationName = QInputDialog::getText(0,
tr("New Configuration"),
tr("New configuration name:"),
@@ -236,7 +229,8 @@ BuildConfiguration::BuildType GenericBuildConfiguration::buildType() const
// GenericBuildSettingsWidget
////////////////////////////////////////////////////////////////////////////////////
-GenericBuildSettingsWidget::GenericBuildSettingsWidget() : m_buildConfiguration(0)
+GenericBuildSettingsWidget::GenericBuildSettingsWidget(GenericBuildConfiguration *bc)
+ : m_buildConfiguration(0)
{
QFormLayout *fl = new QFormLayout(this);
fl->setContentsMargins(0, -1, 0, -1);
@@ -247,18 +241,11 @@ GenericBuildSettingsWidget::GenericBuildSettingsWidget() : m_buildConfiguration(
m_pathChooser->setEnabled(true);
fl->addRow(tr("Build directory:"), m_pathChooser);
connect(m_pathChooser, SIGNAL(changed(QString)), this, SLOT(buildDirectoryChanged()));
-}
-QString GenericBuildSettingsWidget::displayName() const
-{
- return tr("Generic Manager");
-}
-
-void GenericBuildSettingsWidget::init(BuildConfiguration *bc)
-{
- m_buildConfiguration = static_cast<GenericBuildConfiguration *>(bc);
+ m_buildConfiguration = bc;
m_pathChooser->setBaseDirectory(bc->target()->project()->projectDirectory());
m_pathChooser->setPath(m_buildConfiguration->rawBuildDirectory());
+ setDisplayName(tr("Generic Manager"));
}
void GenericBuildSettingsWidget::buildDirectoryChanged()
diff --git a/src/plugins/genericprojectmanager/genericbuildconfiguration.h b/src/plugins/genericprojectmanager/genericbuildconfiguration.h
index a3276be92c..996fa4ae42 100644
--- a/src/plugins/genericprojectmanager/genericbuildconfiguration.h
+++ b/src/plugins/genericprojectmanager/genericbuildconfiguration.h
@@ -31,7 +31,7 @@
#define GENERICBUILDCONFIGURATION_H
#include <projectexplorer/buildconfiguration.h>
-#include <projectexplorer/buildstep.h> // for BuildConfigWidget
+#include <projectexplorer/namedwidget.h>
namespace Utils { class PathChooser; }
@@ -49,14 +49,13 @@ class GenericBuildConfiguration : public ProjectExplorer::BuildConfiguration
public:
explicit GenericBuildConfiguration(ProjectExplorer::Target *parent);
- ProjectExplorer::BuildConfigWidget *createConfigWidget();
+ ProjectExplorer::NamedWidget *createConfigWidget();
QString buildDirectory() const;
QString rawBuildDirectory() const;
void setBuildDirectory(const QString &buildDirectory);
QVariantMap toMap() const;
- ProjectExplorer::IOutputParser *createOutputParser() const;
BuildType buildType() const;
protected:
@@ -90,16 +89,12 @@ private:
bool canHandle(const ProjectExplorer::Target *t) const;
};
-class GenericBuildSettingsWidget : public ProjectExplorer::BuildConfigWidget
+class GenericBuildSettingsWidget : public ProjectExplorer::NamedWidget
{
Q_OBJECT
public:
- GenericBuildSettingsWidget();
-
- QString displayName() const;
-
- void init(ProjectExplorer::BuildConfiguration *bc);
+ GenericBuildSettingsWidget(GenericBuildConfiguration *bc);
private slots:
void buildDirectoryChanged();
diff --git a/src/plugins/genericprojectmanager/genericmakestep.cpp b/src/plugins/genericprojectmanager/genericmakestep.cpp
index 766b3d67c2..e5ede7ab00 100644
--- a/src/plugins/genericprojectmanager/genericmakestep.cpp
+++ b/src/plugins/genericprojectmanager/genericmakestep.cpp
@@ -96,16 +96,11 @@ GenericMakeStep::~GenericMakeStep()
{
}
-GenericBuildConfiguration *GenericMakeStep::genericBuildConfiguration() const
-{
- return static_cast<GenericBuildConfiguration *>(buildConfiguration());
-}
-
bool GenericMakeStep::init()
{
- GenericBuildConfiguration *bc = genericBuildConfiguration();
+ BuildConfiguration *bc = buildConfiguration();
if (!bc)
- bc = static_cast<GenericBuildConfiguration *>(target()->activeBuildConfiguration());
+ bc = target()->activeBuildConfiguration();
m_tasks.clear();
ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit());
@@ -126,6 +121,7 @@ bool GenericMakeStep::init()
pp->setEnvironment(env);
pp->setCommand(makeCommand(bc->environment()));
pp->setArguments(allArguments());
+ pp->resolveAll();
// If we are cleaning, then make can fail with an error code, but that doesn't mean
// we should stop the clean queue
@@ -133,11 +129,9 @@ bool GenericMakeStep::init()
setIgnoreReturnValue(m_clean);
setOutputParser(new GnuMakeParser());
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- if (version)
- appendOutputParser(new QtSupport::QtParser);
- if (tc)
- appendOutputParser(tc->outputParser());
+ IOutputParser *parser = target()->kit()->createOutputParser();
+ if (parser)
+ appendOutputParser(parser);
outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());
return AbstractProcessStep::init();
@@ -230,7 +224,7 @@ void GenericMakeStep::setBuildTarget(const QString &target, bool on)
QStringList old = m_buildTargets;
if (on && !old.contains(target))
old << target;
- else if(!on && old.contains(target))
+ else if (!on && old.contains(target))
old.removeOne(target);
m_buildTargets = old;
@@ -291,18 +285,18 @@ QString GenericMakeStepConfigWidget::displayName() const
void GenericMakeStepConfigWidget::updateMakeOverrrideLabel()
{
- GenericBuildConfiguration *bc = m_makeStep->genericBuildConfiguration();
+ BuildConfiguration *bc = m_makeStep->buildConfiguration();
if (!bc)
- bc = static_cast<GenericBuildConfiguration *>(m_makeStep->target()->activeBuildConfiguration());
+ bc = m_makeStep->target()->activeBuildConfiguration();
m_ui->makeLabel->setText(tr("Override %1:").arg(m_makeStep->makeCommand(bc->environment())));
}
void GenericMakeStepConfigWidget::updateDetails()
{
- GenericBuildConfiguration *bc = m_makeStep->genericBuildConfiguration();
+ BuildConfiguration *bc = m_makeStep->buildConfiguration();
if (!bc)
- bc = static_cast<GenericBuildConfiguration *>(m_makeStep->target()->activeBuildConfiguration());
+ bc = m_makeStep->target()->activeBuildConfiguration();
ProcessParameters param;
param.setMacroExpander(bc->macroExpander());
diff --git a/src/plugins/genericprojectmanager/genericmakestep.h b/src/plugins/genericprojectmanager/genericmakestep.h
index c386b91079..046afe8384 100644
--- a/src/plugins/genericprojectmanager/genericmakestep.h
+++ b/src/plugins/genericprojectmanager/genericmakestep.h
@@ -39,7 +39,6 @@ QT_END_NAMESPACE
namespace GenericProjectManager {
namespace Internal {
-class GenericBuildConfiguration;
class GenericMakeStepConfigWidget;
class GenericMakeStepFactory;
namespace Ui { class GenericMakeStep; }
@@ -55,8 +54,6 @@ public:
GenericMakeStep(ProjectExplorer::BuildStepList *parent);
~GenericMakeStep();
- GenericBuildConfiguration *genericBuildConfiguration() const;
-
bool init();
void run(QFutureInterface<bool> &fi);
diff --git a/src/plugins/genericprojectmanager/genericproject.cpp b/src/plugins/genericprojectmanager/genericproject.cpp
index e72f809042..a1853024de 100644
--- a/src/plugins/genericprojectmanager/genericproject.cpp
+++ b/src/plugins/genericprojectmanager/genericproject.cpp
@@ -36,10 +36,11 @@
#include <coreplugin/documentmanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
+#include <cpptools/cpptoolsconstants.h>
#include <cpptools/ModelManagerInterface.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/abi.h>
-#include <projectexplorer/buildenvironmentwidget.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/kitinformation.h>
@@ -237,7 +238,7 @@ void GenericProject::refresh(RefreshOptions options)
parseProject(options);
if (options & Files)
- m_rootNode->refresh();
+ m_rootNode->refresh(oldFileList);
CPlusPlus::CppModelManagerInterface *modelManager =
CPlusPlus::CppModelManagerInterface::instance();
@@ -249,12 +250,12 @@ void GenericProject::refresh(RefreshOptions options)
new CPlusPlus::CppModelManagerInterface::ProjectPart);
Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::instance()->defaultKit();
- ToolChain *tc = k ? ToolChainKitInformation::toolChain(k) : 0;
- if (tc) {
- part->defines = tc->predefinedMacros(QStringList());
+ if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {
+ QStringList cxxflags; // FIXME: Can we do better?
+ part->defines = tc->predefinedMacros(cxxflags);
part->defines += '\n';
- foreach (const HeaderPath &headerPath, tc->systemHeaderPaths(SysRootKitInformation::sysRoot(k))) {
+ foreach (const HeaderPath &headerPath, tc->systemHeaderPaths(cxxflags, SysRootKitInformation::sysRoot(k))) {
if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
part->frameworkPaths.append(headerPath.path());
else
@@ -266,19 +267,32 @@ void GenericProject::refresh(RefreshOptions options)
part->defines += m_defines;
// ### add _defines.
- part->sourceFiles = files();
- part->sourceFiles += generated();
+
+ // Add any C/C++ files to be parsed
+ QStringList cppMimeTypes;
+ cppMimeTypes << QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)
+ << QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)
+ << QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)
+ << QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)
+ << QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE);
+
+ const Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
+ foreach (const QString &file, files()) {
+ const Core::MimeType mimeType = mimeDatabase->findByFile(QFileInfo(file));
+ if (cppMimeTypes.contains(mimeType.type()))
+ part->sourceFiles += file;
+ }
QStringList filesToUpdate;
if (options & Configuration) {
filesToUpdate = part->sourceFiles;
- filesToUpdate.append(QLatin1String("<configuration>")); // XXX don't hardcode configuration file name
+ filesToUpdate.append(CPlusPlus::CppModelManagerInterface::configurationFileName());
// Full update, if there's a code model update, cancel it
m_codeModelFuture.cancel();
} else if (options & Files) {
// Only update files that got added to the list
- QSet<QString> newFileList = m_files.toSet();
+ QSet<QString> newFileList = part->sourceFiles.toSet();
newFileList.subtract(oldFileList);
filesToUpdate.append(newFileList.toList());
}
@@ -360,11 +374,6 @@ QStringList GenericProject::files() const
return m_files;
}
-QStringList GenericProject::generated() const
-{
- return m_generated;
-}
-
QStringList GenericProject::includePaths() const
{
return m_includePaths;
@@ -400,13 +409,6 @@ IProjectManager *GenericProject::projectManager() const
return m_manager;
}
-QList<BuildConfigWidget*> GenericProject::subConfigWidgets()
-{
- QList<BuildConfigWidget*> list;
- list << new BuildEnvironmentWidget;
- return list;
-}
-
GenericProjectNode *GenericProject::rootProjectNode() const
{
return m_rootNode;
@@ -415,7 +417,7 @@ GenericProjectNode *GenericProject::rootProjectNode() const
QStringList GenericProject::files(FilesMode fileMode) const
{
Q_UNUSED(fileMode)
- return m_files; // ### TODO: handle generated files here.
+ return m_files;
}
QStringList GenericProject::buildTargets() const
@@ -488,7 +490,7 @@ QString GenericProjectFile::suggestedFileName() const
QString GenericProjectFile::mimeType() const
{
- return Constants::GENERICMIMETYPE;
+ return QLatin1String(Constants::GENERICMIMETYPE);
}
bool GenericProjectFile::isModified() const
diff --git a/src/plugins/genericprojectmanager/genericproject.h b/src/plugins/genericprojectmanager/genericproject.h
index 4e311a56d4..917a69482f 100644
--- a/src/plugins/genericprojectmanager/genericproject.h
+++ b/src/plugins/genericprojectmanager/genericproject.h
@@ -64,8 +64,6 @@ public:
Core::IDocument *document() const;
ProjectExplorer::IProjectManager *projectManager() const;
- QList<ProjectExplorer::BuildConfigWidget*> subConfigWidgets();
-
GenericProjectNode *rootProjectNode() const;
QStringList files(FilesMode fileMode) const;
@@ -91,7 +89,6 @@ public:
QStringList allIncludePaths() const;
QStringList projectIncludePaths() const;
QStringList files() const;
- QStringList generated() const;
protected:
bool fromMap(const QVariantMap &map);
@@ -115,7 +112,6 @@ private:
QStringList m_rawFileList;
QStringList m_files;
QHash<QString, QString> m_rawListEntries;
- QStringList m_generated;
QStringList m_includePaths;
QStringList m_projectIncludePaths;
QByteArray m_defines;
diff --git a/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp b/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp
index e4ab39d1e8..6cd7ffad71 100644
--- a/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectfileseditor.cpp
@@ -37,6 +37,7 @@
#include <texteditor/texteditorsettings.h>
#include <QCoreApplication>
+#include <QSharedPointer>
using namespace TextEditor;
@@ -72,7 +73,7 @@ QStringList ProjectFilesFactory::mimeTypes() const
Core::Id ProjectFilesFactory::id() const
{
- return Constants::FILES_EDITOR_ID;
+ return Core::Id(Constants::FILES_EDITOR_ID);
}
QString ProjectFilesFactory::displayName() const
@@ -94,7 +95,7 @@ ProjectFilesEditor::ProjectFilesEditor(ProjectFilesEditorWidget *editor)
Core::Id ProjectFilesEditor::id() const
{
- return Constants::FILES_EDITOR_ID;
+ return Core::Id(Constants::FILES_EDITOR_ID);
}
bool ProjectFilesEditor::duplicateSupported() const
@@ -124,7 +125,7 @@ ProjectFilesEditorWidget::ProjectFilesEditorWidget(QWidget *parent, ProjectFiles
m_factory(factory),
m_actionHandler(handler)
{
- BaseTextDocument *doc = new BaseTextDocument();
+ QSharedPointer<BaseTextDocument> doc(new BaseTextDocument());
setBaseTextDocument(doc);
handler->setupActions(this);
diff --git a/src/plugins/genericprojectmanager/genericprojectmanager.pro b/src/plugins/genericprojectmanager/genericprojectmanager.pro
index 02c60f9540..0a684bc7aa 100644
--- a/src/plugins/genericprojectmanager/genericprojectmanager.pro
+++ b/src/plugins/genericprojectmanager/genericprojectmanager.pro
@@ -2,6 +2,7 @@ TEMPLATE = lib
TARGET = GenericProjectManager
include(../../qtcreatorplugin.pri)
include(genericprojectmanager_dependencies.pri)
+
HEADERS = genericproject.h \
genericprojectplugin.h \
genericprojectmanager.h \
diff --git a/src/plugins/genericprojectmanager/genericprojectmanager.qbs b/src/plugins/genericprojectmanager/genericprojectmanager.qbs
index 9b47c6767b..8a47a547cb 100644
--- a/src/plugins/genericprojectmanager/genericprojectmanager.qbs
+++ b/src/plugins/genericprojectmanager/genericprojectmanager.qbs
@@ -15,39 +15,31 @@ QtcPlugin {
Depends { name: "Locator" }
Depends { name: "QtSupport" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
+ "filesselectionwizardpage.cpp",
+ "filesselectionwizardpage.h",
+ "genericbuildconfiguration.cpp",
+ "genericbuildconfiguration.h",
+ "genericmakestep.cpp",
+ "genericmakestep.h",
+ "genericmakestep.ui",
+ "genericproject.cpp",
"genericproject.h",
- "genericprojectplugin.h",
- "genericprojectmanager.h",
+ "genericproject.qrc",
"genericprojectconstants.h",
- "genericprojectnodes.h",
- "genericprojectwizard.h",
+ "genericprojectfileseditor.cpp",
"genericprojectfileseditor.h",
- "pkgconfigtool.h",
- "genericmakestep.h",
- "genericbuildconfiguration.h",
- "selectablefilesmodel.h",
- "filesselectionwizardpage.h",
- "genericproject.cpp",
- "genericprojectplugin.cpp",
"genericprojectmanager.cpp",
+ "genericprojectmanager.h",
"genericprojectnodes.cpp",
+ "genericprojectnodes.h",
+ "genericprojectplugin.cpp",
+ "genericprojectplugin.h",
"genericprojectwizard.cpp",
- "genericprojectfileseditor.cpp",
+ "genericprojectwizard.h",
"pkgconfigtool.cpp",
- "genericmakestep.cpp",
- "genericbuildconfiguration.cpp",
+ "pkgconfigtool.h",
"selectablefilesmodel.cpp",
- "filesselectionwizardpage.cpp",
- "genericmakestep.ui",
- "genericproject.qrc",
+ "selectablefilesmodel.h",
]
}
-
diff --git a/src/plugins/genericprojectmanager/genericprojectnodes.cpp b/src/plugins/genericprojectmanager/genericprojectnodes.cpp
index 5531ea2aad..4540bdaacc 100644
--- a/src/plugins/genericprojectmanager/genericprojectnodes.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectnodes.cpp
@@ -56,67 +56,78 @@ QString GenericProjectNode::projectFilePath() const
return m_projectFile->fileName();
}
-void GenericProjectNode::refresh()
+QHash<QString, QStringList> sortFilesIntoPaths(const QString &base, const QSet<QString> files)
{
- // remove the existing nodes.
- removeFileNodes(fileNodes(), this);
- removeFolderNodes(subFolderNodes(), this);
-
- //ProjectExplorerPlugin::instance()->setCurrentNode(0); // ### remove me
-
- FileNode *projectFilesNode = new FileNode(m_project->filesFileName(),
- ProjectFileType,
- /* generated = */ false);
-
- FileNode *projectIncludesNode = new FileNode(m_project->includesFileName(),
- ProjectFileType,
- /* generated = */ false);
-
- FileNode *projectConfigNode = new FileNode(m_project->configFileName(),
- ProjectFileType,
- /* generated = */ false);
-
- QStringList files = m_project->files();
- files.removeAll(m_project->filesFileName());
- files.removeAll(m_project->includesFileName());
- files.removeAll(m_project->configFileName());
-
- addFileNodes(QList<FileNode *>()
- << projectFilesNode
- << projectIncludesNode
- << projectConfigNode,
- this);
-
- QStringList filePaths;
QHash<QString, QStringList> filesInPath;
- const QString base = QFileInfo(path()).absolutePath();
const QDir baseDir(base);
foreach (const QString &absoluteFileName, files) {
QFileInfo fileInfo(absoluteFileName);
- const QString absoluteFilePath = fileInfo.path();
+ Utils::FileName absoluteFilePath = Utils::FileName::fromString(fileInfo.path());
QString relativeFilePath;
- if (absoluteFilePath.startsWith(base)) {
- relativeFilePath = absoluteFilePath.mid(base.length() + 1);
+ if (absoluteFilePath.isChildOf(baseDir)) {
+ relativeFilePath = absoluteFilePath.relativeChildPath(Utils::FileName::fromString(base)).toString();
} else {
// `file' is not part of the project.
- relativeFilePath = baseDir.relativeFilePath(absoluteFilePath);
+ relativeFilePath = baseDir.relativeFilePath(absoluteFilePath.toString());
}
- if (! filePaths.contains(relativeFilePath))
- filePaths.append(relativeFilePath);
-
filesInPath[relativeFilePath].append(absoluteFileName);
}
+ return filesInPath;
+}
+
+void GenericProjectNode::refresh(QSet<QString> oldFileList)
+{
+ if (oldFileList.isEmpty()) {
+ // Only do this once
+ FileNode *projectFilesNode = new FileNode(m_project->filesFileName(),
+ ProjectFileType,
+ /* generated = */ false);
+
+ FileNode *projectIncludesNode = new FileNode(m_project->includesFileName(),
+ ProjectFileType,
+ /* generated = */ false);
+
+ FileNode *projectConfigNode = new FileNode(m_project->configFileName(),
+ ProjectFileType,
+ /* generated = */ false);
+
+ addFileNodes(QList<FileNode *>()
+ << projectFilesNode
+ << projectIncludesNode
+ << projectConfigNode,
+ this);
+ }
- FolderByName folderByName;
- foreach (const QString &filePath, filePaths) {
- QStringList components = filePath.split(QLatin1Char('/'));
- FolderNode *folder = findOrCreateFolderByName(&folderByName, components, components.size());
+ // Do those separately
+ oldFileList.remove(m_project->filesFileName());
+ oldFileList.remove(m_project->includesFileName());
+ oldFileList.remove(m_project->configFileName());
+
+ QSet<QString> newFileList = m_project->files().toSet();
+ newFileList.remove(m_project->filesFileName());
+ newFileList.remove(m_project->includesFileName());
+ newFileList.remove(m_project->configFileName());
+
+ QSet<QString> removed = oldFileList;
+ removed.subtract(newFileList);
+ QSet<QString> added = newFileList;
+ added.subtract(oldFileList);
+
+ QString baseDir = QFileInfo(path()).absolutePath();
+ QHash<QString, QStringList> filesInPaths = sortFilesIntoPaths(baseDir, added);
+ foreach (const QString &filePath, filesInPaths.keys()) {
+ QStringList components;
+ if (!filePath.isEmpty())
+ components = filePath.split(QLatin1Char('/'));
+ FolderNode *folder = findFolderByName(components, components.size());
+ if (!folder)
+ folder = createFolderByName(components, components.size());
QList<FileNode *> fileNodes;
- foreach (const QString &file, filesInPath.value(filePath)) {
+ foreach (const QString &file, filesInPaths.value(filePath)) {
FileType fileType = SourceType; // ### FIXME
FileNode *fileNode = new FileNode(file, fileType, /*generated = */ false);
fileNodes.append(fileNode);
@@ -124,41 +135,86 @@ void GenericProjectNode::refresh()
addFileNodes(fileNodes, folder);
}
+
+ filesInPaths = sortFilesIntoPaths(baseDir, removed);
+ foreach (const QString &filePath, filesInPaths.keys()) {
+ QStringList components;
+ if (!filePath.isEmpty())
+ components = filePath.split(QLatin1Char('/'));
+ FolderNode *folder = findFolderByName(components, components.size());
+
+ QList<FileNode *> fileNodes;
+ foreach (const QString &file, filesInPaths.value(filePath)) {
+ foreach (FileNode *fn, folder->fileNodes())
+ if (fn->path() == file)
+ fileNodes.append(fn);
+ }
+
+ removeFileNodes(fileNodes, folder);
+ }
+
+ foreach (FolderNode *fn, subFolderNodes())
+ removeEmptySubFolders(this, fn);
+
}
-FolderNode *GenericProjectNode::findOrCreateFolderByName
- (FolderByName *folderByName, const QStringList &components, int end)
+void GenericProjectNode::removeEmptySubFolders(FolderNode *gparent, FolderNode *parent)
{
- if (!end)
- return 0;
+ foreach (FolderNode *fn, parent->subFolderNodes())
+ removeEmptySubFolders(parent, fn);
+
+ if (parent->subFolderNodes().isEmpty() && parent->fileNodes().isEmpty())
+ removeFolderNodes(QList<FolderNode*>() << parent, gparent);
+}
+
+FolderNode *GenericProjectNode::createFolderByName(const QStringList &components, int end)
+{
+ if (end == 0)
+ return this;
QString folderName;
for (int i = 0; i < end; ++i) {
folderName.append(components.at(i));
- folderName += QLatin1Char('/'); // ### FIXME
+ folderName += QLatin1Char('/');
}
const QString component = components.at(end - 1);
- if (component.isEmpty())
- return this;
-
- else if (FolderNode *folder = folderByName->value(folderName))
- return folder;
-
const QString baseDir = QFileInfo(path()).path();
FolderNode *folder = new FolderNode(baseDir + QLatin1Char('/') + folderName);
folder->setDisplayName(component);
- folderByName->insert(folderName, folder);
- FolderNode *parent = findOrCreateFolderByName(folderByName, components, end - 1);
+ FolderNode *parent = findFolderByName(components, end - 1);
if (!parent)
- parent = this;
+ parent = createFolderByName(components, end - 1);
addFolderNodes(QList<FolderNode*>() << folder, parent);
return folder;
}
+FolderNode *GenericProjectNode::findFolderByName(const QStringList &components, int end)
+{
+ if (end == 0)
+ return this;
+
+ QString folderName;
+ for (int i = 0; i < end; ++i) {
+ folderName.append(components.at(i));
+ folderName += QLatin1Char('/');
+ }
+
+ FolderNode *parent = findFolderByName(components, end - 1);
+
+ if (!parent)
+ return 0;
+
+ const QString baseDir = QFileInfo(path()).path();
+ foreach (FolderNode *fn, parent->subFolderNodes())
+ if (fn->path() == baseDir + QLatin1Char('/') + folderName)
+ return fn;
+ return 0;
+}
+
bool GenericProjectNode::hasBuildTargets() const
{
return true;
diff --git a/src/plugins/genericprojectmanager/genericprojectnodes.h b/src/plugins/genericprojectmanager/genericprojectnodes.h
index c2ffd41611..35d2465a5c 100644
--- a/src/plugins/genericprojectmanager/genericprojectnodes.h
+++ b/src/plugins/genericprojectmanager/genericprojectnodes.h
@@ -34,6 +34,7 @@
#include <QStringList>
#include <QHash>
+#include <QSet>
namespace Core {
class IDocument;
@@ -77,12 +78,13 @@ public:
QList<ProjectExplorer::RunConfiguration *> runConfigurationsFor(Node *node);
- void refresh();
+ void refresh(QSet<QString> oldFileList = QSet<QString>());
private:
typedef QHash<QString, FolderNode *> FolderByName;
- FolderNode *findOrCreateFolderByName(FolderByName *folderByName,
- const QStringList &components, int end);
+ FolderNode *createFolderByName(const QStringList &components, int end);
+ FolderNode *findFolderByName(const QStringList &components, int end);
+ void removeEmptySubFolders(FolderNode *gparent, FolderNode *parent);
private:
GenericProject *m_project;
diff --git a/src/plugins/genericprojectmanager/genericprojectplugin.cpp b/src/plugins/genericprojectmanager/genericprojectplugin.cpp
index d464649da9..13089935bc 100644
--- a/src/plugins/genericprojectmanager/genericprojectplugin.cpp
+++ b/src/plugins/genericprojectmanager/genericprojectplugin.cpp
@@ -119,9 +119,8 @@ void GenericProjectPlugin::editFiles()
GenericProject *genericProject = static_cast<GenericProject *>(m_contextMenuProject);
SelectableFilesDialog sfd(QFileInfo(genericProject->document()->fileName()).path(), genericProject->files(),
Core::ICore::mainWindow());
- if (sfd.exec() == QDialog::Accepted) {
+ if (sfd.exec() == QDialog::Accepted)
genericProject->setFiles(sfd.selectedFiles());
- }
}
} // namespace Internal
diff --git a/src/plugins/genericprojectmanager/selectablefilesmodel.cpp b/src/plugins/genericprojectmanager/selectablefilesmodel.cpp
index eb8e4ac192..7161739e26 100644
--- a/src/plugins/genericprojectmanager/selectablefilesmodel.cpp
+++ b/src/plugins/genericprojectmanager/selectablefilesmodel.cpp
@@ -49,7 +49,7 @@ SelectableFilesModel::SelectableFilesModel(const QString &baseDir, QObject *pare
{
// Dummy tree
m_root = new Tree;
- m_root->name = "/";
+ m_root->name = QLatin1String("/");
m_root->parent = 0;
m_root->fullPath = m_baseDir;
m_root->isDir = true;
@@ -59,7 +59,7 @@ void SelectableFilesModel::setInitialMarkedFiles(const QStringList &files)
{
m_files = files.toSet();
m_outOfBaseDirFiles.clear();
- QString base = m_baseDir + '/';
+ QString base = m_baseDir + QLatin1Char('/');
foreach (const QString &file, m_files)
if (!file.startsWith(base))
m_outOfBaseDirFiles.append(file);
@@ -75,7 +75,7 @@ void SelectableFilesModel::startParsing()
{
// Build a tree in a future
m_rootForFuture = new Tree;
- m_rootForFuture->name = "/";
+ m_rootForFuture->name = QLatin1String("/");
m_rootForFuture->parent = 0;
m_rootForFuture->fullPath = m_baseDir;
m_rootForFuture->isDir = true;
@@ -361,14 +361,15 @@ void SelectableFilesModel::collectFiles(Tree *root, QStringList *result) const
QList<Glob> SelectableFilesModel::parseFilter(const QString &filter)
{
QList<Glob> result;
- QStringList list = filter.split(';', QString::SkipEmptyParts);
+ QStringList list = filter.split(QLatin1Char(';'), QString::SkipEmptyParts);
foreach (const QString &e, list) {
QString entry = e.trimmed();
Glob g;
- if (entry.indexOf('*') == -1 && entry.indexOf('?') == -1) {
+ if (entry.indexOf(QLatin1Char('*')) == -1 && entry.indexOf(QLatin1Char('?')) == -1) {
g.mode = Glob::EXACT;
g.matchString = entry;
- } else if (entry.startsWith('*') && entry.indexOf('*', 1) == -1 && entry.indexOf('?', 1) == -1) {
+ } else if (entry.startsWith(QLatin1Char('*')) && entry.indexOf(QLatin1Char('*'), 1) == -1
+ && entry.indexOf(QLatin1Char('?'), 1) == -1) {
g.mode = Glob::ENDSWITH;
g.matchString = entry.mid(1);
} else {
@@ -518,8 +519,8 @@ SelectableFilesDialog::SelectableFilesDialog(const QString &path, const QStringL
hbox->addWidget(m_filterLabel);
m_filterLineEdit = new QLineEdit(this);
- const QString filter = Core::ICore::settings()->value(Constants::FILEFILTER_SETTING,
- Constants::FILEFILTER_DEFAULT).toString();
+ const QString filter = Core::ICore::settings()->value(QLatin1String(Constants::FILEFILTER_SETTING),
+ QLatin1String(Constants::FILEFILTER_DEFAULT)).toString();
m_filterLineEdit->setText(filter);
m_filterLineEdit->hide();
hbox->addWidget(m_filterLineEdit);
@@ -610,7 +611,7 @@ QStringList SelectableFilesDialog::selectedFiles() const
void SelectableFilesDialog::applyFilter()
{
const QString filter = m_filterLineEdit->text();
- Core::ICore::settings()->setValue(Constants::FILEFILTER_SETTING, filter);
+ Core::ICore::settings()->setValue(QLatin1String(Constants::FILEFILTER_SETTING), filter);
m_selectableFilesModel->applyFilter(filter);
}
diff --git a/src/plugins/git/annotationhighlighter.h b/src/plugins/git/annotationhighlighter.h
index f226428993..6c2539b6fb 100644
--- a/src/plugins/git/annotationhighlighter.h
+++ b/src/plugins/git/annotationhighlighter.h
@@ -44,7 +44,7 @@ public:
QTextDocument *document = 0);
private:
- virtual QString changeNumber(const QString &block) const;
+ QString changeNumber(const QString &block) const;
const QChar m_blank;
};
diff --git a/src/plugins/git/branchadddialog.cpp b/src/plugins/git/branchadddialog.cpp
index ce9d1e1d6f..bcb16b3925 100644
--- a/src/plugins/git/branchadddialog.cpp
+++ b/src/plugins/git/branchadddialog.cpp
@@ -30,14 +30,78 @@
#include "branchadddialog.h"
#include "ui_branchadddialog.h"
+#include <QPushButton>
+#include <QValidator>
+
namespace Git {
namespace Internal {
+/*!
+ * \brief Validates the corresponding string as a valid git branch name
+ *
+ * The class does this by a couple of rules that are applied on the string.
+ *
+ */
+class BranchNameValidator : public QValidator
+{
+public:
+ BranchNameValidator(QObject *parent = 0) :
+ QValidator(parent),
+ m_invalidChars(QLatin1String(
+ "\\s" // no whitespace
+ "|~" // no "~"
+ "|\\^" // no "^"
+ "|\\[" // no "["
+ "|\\.\\." // no ".."
+ "|/\\." // no slashdot
+ "|:" // no ":"
+ "|@\\{" // no "@{" sequence
+ "|\\\\" // no backslash
+ "|//" // no double slash
+ "|^/" // no leading slash
+ ))
+ {
+ }
+
+ ~BranchNameValidator() {}
+
+ State validate(QString &input, int &pos) const
+ {
+ Q_UNUSED(pos)
+
+ // NoGos
+
+ if (input.contains(m_invalidChars))
+ return Invalid;
+
+
+ // "Intermediate" patterns, may change to Acceptable when user edits further:
+
+ if (input.endsWith(QLatin1String(".lock"))) //..may not end with ".lock"
+ return Intermediate;
+
+ if (input.endsWith(QLatin1Char('.'))) // no dot at the end (but allowed in the middle)
+ return Intermediate;
+
+ if (input.endsWith(QLatin1Char('/'))) // no slash at the end (but allowed in the middle)
+ return Intermediate;
+
+ // is a valid branch name
+ return Acceptable;
+ }
+
+private:
+ const QRegExp m_invalidChars;
+};
+
+
BranchAddDialog::BranchAddDialog(QWidget *parent) :
QDialog(parent),
m_ui(new Ui::BranchAddDialog)
{
m_ui->setupUi(this);
+ m_ui->branchNameEdit->setValidator(new BranchNameValidator(this));
+ connect(m_ui->branchNameEdit, SIGNAL(textChanged(QString)), this, SLOT(updateButtonStatus()));
}
BranchAddDialog::~BranchAddDialog()
@@ -72,5 +136,11 @@ bool BranchAddDialog::track()
return m_ui->trackingCheckBox->isChecked();
}
+/*! Updates the ok button enabled state of the dialog according to the validity of the branch name. */
+void BranchAddDialog::updateButtonStatus()
+{
+ m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(m_ui->branchNameEdit->hasAcceptableInput());
+}
+
} // namespace Internal
} // namespace Git
diff --git a/src/plugins/git/branchadddialog.h b/src/plugins/git/branchadddialog.h
index 6b039ab7dc..ef1088795e 100644
--- a/src/plugins/git/branchadddialog.h
+++ b/src/plugins/git/branchadddialog.h
@@ -55,6 +55,9 @@ public:
bool track();
+private slots:
+ void updateButtonStatus();
+
private:
Ui::BranchAddDialog *m_ui;
};
diff --git a/src/plugins/git/branchcheckoutdialog.cpp b/src/plugins/git/branchcheckoutdialog.cpp
new file mode 100644
index 0000000000..fc0c34aefa
--- /dev/null
+++ b/src/plugins/git/branchcheckoutdialog.cpp
@@ -0,0 +1,88 @@
+#include "branchcheckoutdialog.h"
+#include "ui_branchcheckoutdialog.h"
+
+namespace Git {
+namespace Internal {
+
+BranchCheckoutDialog::BranchCheckoutDialog(QWidget *parent,
+ const QString& currentBranch,
+ const QString& nextBranch) :
+ QDialog(parent),
+ m_ui(new Ui::BranchCheckoutDialog),
+ m_foundStashForNextBranch(false),
+ m_hasLocalChanges(true)
+{
+ m_ui->setupUi(this);
+
+ setWindowTitle(tr("Checkout branch \"%1\"").arg(nextBranch));
+ m_ui->moveChangesRadioButton->setText(tr("Move Local Changes to \"%1\"").arg(nextBranch));
+ m_ui->popStashCheckBox->setText(tr("Pop Stash of \"%1\"").arg(nextBranch));
+
+ if (!currentBranch.isEmpty()) {
+ m_ui->makeStashRadioButton->setText(tr("Create Branch Stash for \"%1\"").arg(currentBranch));
+ } else {
+ m_ui->makeStashRadioButton->setText(tr("Create Branch Stash for Current Branch"));
+ foundNoLocalChanges();
+ }
+
+ connect(m_ui->moveChangesRadioButton, SIGNAL(toggled(bool)), this, SLOT(updatePopStashCheckBox(bool)));
+}
+
+BranchCheckoutDialog::~BranchCheckoutDialog()
+{
+ delete m_ui;
+}
+
+void BranchCheckoutDialog::foundNoLocalChanges()
+{
+ m_ui->discardChangesRadioButton->setChecked(true);
+ m_ui->localChangesGroupBox->setEnabled(false);
+ m_hasLocalChanges = false;
+}
+
+void BranchCheckoutDialog::foundStashForNextBranch()
+{
+ m_ui->popStashCheckBox->setChecked(true);
+ m_ui->popStashCheckBox->setEnabled(true);
+ m_foundStashForNextBranch = true;
+}
+
+bool BranchCheckoutDialog::makeStashOfCurrentBranch()
+{
+ return m_ui->makeStashRadioButton->isChecked();
+}
+
+bool BranchCheckoutDialog::moveLocalChangesToNextBranch()
+{
+ return m_ui->moveChangesRadioButton->isChecked();
+}
+
+bool BranchCheckoutDialog::discardLocalChanges()
+{
+ return m_ui->discardChangesRadioButton->isChecked() && m_ui->localChangesGroupBox->isEnabled();
+}
+
+bool BranchCheckoutDialog::popStashOfNextBranch()
+{
+ return m_ui->popStashCheckBox->isChecked();
+}
+
+bool BranchCheckoutDialog::hasStashForNextBranch()
+{
+ return m_foundStashForNextBranch;
+}
+
+bool BranchCheckoutDialog::hasLocalChanges()
+{
+ return m_hasLocalChanges;
+}
+
+void BranchCheckoutDialog::updatePopStashCheckBox(bool moveChangesChecked)
+{
+ m_ui->popStashCheckBox->setChecked(!moveChangesChecked && m_foundStashForNextBranch);
+ m_ui->popStashCheckBox->setEnabled(!moveChangesChecked && m_foundStashForNextBranch);
+}
+
+} // namespace Internal
+} // namespace Git
+
diff --git a/src/plugins/git/branchcheckoutdialog.h b/src/plugins/git/branchcheckoutdialog.h
new file mode 100644
index 0000000000..a794b8ef36
--- /dev/null
+++ b/src/plugins/git/branchcheckoutdialog.h
@@ -0,0 +1,45 @@
+#ifndef BRANCHCHECKOUTDIALOG_H
+#define BRANCHCHECKOUTDIALOG_H
+
+#include <QDialog>
+
+namespace Git {
+namespace Internal {
+
+namespace Ui {
+ class BranchCheckoutDialog;
+}
+
+class BranchCheckoutDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit BranchCheckoutDialog(QWidget *parent, const QString& currentBranch,
+ const QString& nextBranch);
+ ~BranchCheckoutDialog();
+
+ void foundNoLocalChanges();
+ void foundStashForNextBranch();
+
+ bool makeStashOfCurrentBranch();
+ bool moveLocalChangesToNextBranch();
+ bool discardLocalChanges();
+ bool popStashOfNextBranch();
+
+ bool hasStashForNextBranch();
+ bool hasLocalChanges();
+
+private slots:
+ void updatePopStashCheckBox(bool moveChangesChecked);
+
+private:
+ Ui::BranchCheckoutDialog *m_ui;
+ bool m_foundStashForNextBranch;
+ bool m_hasLocalChanges;
+};
+
+} // namespace Internal
+} // namespace Git
+
+#endif // BRANCHCHECKOUTDIALOG_H
diff --git a/src/plugins/git/branchcheckoutdialog.ui b/src/plugins/git/branchcheckoutdialog.ui
new file mode 100644
index 0000000000..b8cbc406a9
--- /dev/null
+++ b/src/plugins/git/branchcheckoutdialog.ui
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Git::Internal::BranchCheckoutDialog</class>
+ <widget class="QDialog" name="Git::Internal::BranchCheckoutDialog">
+ <property name="windowModality">
+ <enum>Qt::WindowModal</enum>
+ </property>
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>394</width>
+ <height>199</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Dialog</string>
+ </property>
+ <property name="modal">
+ <bool>true</bool>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="QGroupBox" name="localChangesGroupBox">
+ <property name="title">
+ <string>Local Changes Found. Choose Action:</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QRadioButton" name="makeStashRadioButton">
+ <property name="text">
+ <string>RadioButton</string>
+ </property>
+ <property name="checked">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QRadioButton" name="moveChangesRadioButton">
+ <property name="text">
+ <string>RadioButton</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QRadioButton" name="discardChangesRadioButton">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="text">
+ <string>Discard Local Changes</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="popStashCheckBox">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>CheckBox</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <tabstops>
+ <tabstop>discardChangesRadioButton</tabstop>
+ <tabstop>buttonBox</tabstop>
+ </tabstops>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>Git::Internal::BranchCheckoutDialog</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>227</x>
+ <y>219</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>157</x>
+ <y>179</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>Git::Internal::BranchCheckoutDialog</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>295</x>
+ <y>219</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>286</x>
+ <y>179</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/src/plugins/git/branchdialog.cpp b/src/plugins/git/branchdialog.cpp
index 4c27a6bbb0..781520e327 100644
--- a/src/plugins/git/branchdialog.cpp
+++ b/src/plugins/git/branchdialog.cpp
@@ -29,9 +29,11 @@
#include "branchdialog.h"
#include "branchadddialog.h"
+#include "branchcheckoutdialog.h"
#include "branchmodel.h"
#include "gitclient.h"
#include "gitplugin.h"
+#include "gitutils.h"
#include "ui_branchdialog.h"
#include "stashdialog.h" // Label helpers
@@ -42,6 +44,7 @@
#include <QItemSelectionModel>
#include <QPushButton>
#include <QMessageBox>
+#include <QList>
#include <QDebug>
@@ -65,6 +68,8 @@ BranchDialog::BranchDialog(QWidget *parent) :
connect(m_ui->removeButton, SIGNAL(clicked()), this, SLOT(remove()));
connect(m_ui->diffButton, SIGNAL(clicked()), this, SLOT(diff()));
connect(m_ui->logButton, SIGNAL(clicked()), this, SLOT(log()));
+ connect(m_ui->mergeButton, SIGNAL(clicked()), this, SLOT(merge()));
+ connect(m_ui->rebaseButton, SIGNAL(clicked()), this, SLOT(rebase()));
m_ui->branchView->setModel(m_model);
@@ -77,8 +82,6 @@ BranchDialog::BranchDialog(QWidget *parent) :
BranchDialog::~BranchDialog()
{
delete m_ui;
- delete m_model;
- m_model = 0;
}
void BranchDialog::refresh(const QString &repository, bool force)
@@ -102,11 +105,14 @@ void BranchDialog::enableButtons()
const bool currentSelected = hasSelection && idx == m_model->currentBranch();
const bool isLocal = m_model->isLocal(idx);
const bool isLeaf = m_model->isLeaf(idx);
+ const bool currentLocal = m_model->isLocal(m_model->currentBranch());
m_ui->removeButton->setEnabled(hasSelection && !currentSelected && isLocal && isLeaf);
m_ui->logButton->setEnabled(hasSelection && isLeaf);
m_ui->diffButton->setEnabled(hasSelection && isLeaf);
m_ui->checkoutButton->setEnabled(hasSelection && !currentSelected && isLeaf);
+ m_ui->rebaseButton->setEnabled(hasSelection && !currentSelected && isLeaf && currentLocal);
+ m_ui->mergeButton->setEnabled(hasSelection && !currentSelected && isLeaf && currentLocal);
}
void BranchDialog::refresh()
@@ -152,9 +158,57 @@ void BranchDialog::add()
void BranchDialog::checkout()
{
QModelIndex idx = selectedIndex();
- QTC_CHECK(m_model->isLocal(idx));
- m_model->checkoutBranch(idx);
+ const QString currentBranch = m_model->branchName(m_model->currentBranch());
+ const QString nextBranch = m_model->branchName(idx);
+ const QString popMessageStart = QCoreApplication::applicationName() +
+ QLatin1String(" ") + nextBranch + QLatin1String("-AutoStash ");
+
+ BranchCheckoutDialog branchCheckoutDialog(this, currentBranch, nextBranch);
+ GitClient *gitClient = GitPlugin::instance()->gitClient();
+
+ if (gitClient->gitStatus(m_repository, StatusMode(NoUntracked | NoSubmodules)) != GitClient::StatusChanged)
+ branchCheckoutDialog.foundNoLocalChanges();
+
+ QList<Stash> stashes;
+ gitClient->synchronousStashList(m_repository, &stashes);
+ foreach (const Stash &stash, stashes) {
+ if (stash.message.startsWith(popMessageStart)) {
+ branchCheckoutDialog.foundStashForNextBranch();
+ break;
+ }
+ }
+
+ if (!branchCheckoutDialog.hasLocalChanges() &&
+ !branchCheckoutDialog.hasStashForNextBranch()) {
+ // No local changes and no Auto Stash - no need to open dialog
+ m_model->checkoutBranch(idx);
+ } else if (branchCheckoutDialog.exec() == QDialog::Accepted && m_model) {
+
+ QString stashMessage;
+ if (branchCheckoutDialog.makeStashOfCurrentBranch()
+ || branchCheckoutDialog.moveLocalChangesToNextBranch()) {
+ gitClient->ensureStash(m_repository, currentBranch + QLatin1String("-AutoStash"), false, &stashMessage);
+ } else if (branchCheckoutDialog.discardLocalChanges()) {
+ gitClient->synchronousReset(m_repository);
+ }
+
+ m_model->checkoutBranch(idx);
+
+ QString stashName;
+ gitClient->synchronousStashList(m_repository, &stashes);
+ foreach (const Stash &stash, stashes) {
+ if (stash.message.startsWith(popMessageStart)) {
+ stashName = stash.name;
+ break;
+ }
+ }
+
+ if (!stashMessage.isEmpty() && branchCheckoutDialog.moveLocalChangesToNextBranch())
+ gitClient->stashPop(m_repository);
+ else if (branchCheckoutDialog.popStashOfNextBranch())
+ gitClient->synchronousStashRestore(m_repository, stashName, true);
+ }
enableButtons();
}
@@ -194,6 +248,30 @@ void BranchDialog::log()
GitPlugin::instance()->gitClient()->graphLog(m_repository, branchName);
}
+void BranchDialog::merge()
+{
+ QModelIndex idx = selectedIndex();
+ QTC_CHECK(m_model->isLocal(m_model->currentBranch())); // otherwise the button would not be enabled!
+ QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled!
+
+ const QString branch = m_model->branchName(idx);
+ GitClient::StashGuard stashGuard(m_repository, QLatin1String("merge"), false);
+ if (!GitPlugin::instance()->gitClient()->synchronousMerge(m_repository, branch))
+ stashGuard.preventPop();
+}
+
+void BranchDialog::rebase()
+{
+ QModelIndex idx = selectedIndex();
+ QTC_CHECK(m_model->isLocal(m_model->currentBranch())); // otherwise the button would not be enabled!
+ QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled!
+
+ const QString baseBranch = m_model->branchName(idx);
+ GitClient::StashGuard stashGuard(m_repository, QLatin1String("rebase"), false);
+ if (!GitPlugin::instance()->gitClient()->synchronousRebase(m_repository, baseBranch))
+ stashGuard.preventPop();
+}
+
void BranchDialog::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
diff --git a/src/plugins/git/branchdialog.h b/src/plugins/git/branchdialog.h
index 89089ea8bb..b5a673ec04 100644
--- a/src/plugins/git/branchdialog.h
+++ b/src/plugins/git/branchdialog.h
@@ -71,6 +71,8 @@ private slots:
void remove();
void diff();
void log();
+ void merge();
+ void rebase();
protected:
void changeEvent(QEvent *e);
diff --git a/src/plugins/git/branchdialog.ui b/src/plugins/git/branchdialog.ui
index 1689119b66..5c9f1fd462 100644
--- a/src/plugins/git/branchdialog.ui
+++ b/src/plugins/git/branchdialog.ui
@@ -51,17 +51,14 @@
<property name="title">
<string>Branches</string>
</property>
- <layout class="QGridLayout" name="gridLayout">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
<property name="topMargin">
<number>4</number>
</property>
<property name="bottomMargin">
<number>4</number>
</property>
- <property name="verticalSpacing">
- <number>9</number>
- </property>
- <item row="0" column="0" colspan="3">
+ <item>
<widget class="QTreeView" name="branchView">
<property name="rootIsDecorated">
<bool>false</bool>
@@ -74,40 +71,95 @@
</attribute>
</widget>
</item>
- <item row="1" column="0">
- <widget class="QPushButton" name="addButton">
- <property name="text">
- <string>&amp;Add...</string>
- </property>
- </widget>
- </item>
- <item row="1" column="2">
- <widget class="QPushButton" name="removeButton">
- <property name="text">
- <string>&amp;Remove</string>
- </property>
- </widget>
- </item>
- <item row="2" column="0">
- <widget class="QPushButton" name="diffButton">
- <property name="text">
- <string>&amp;Diff</string>
- </property>
- </widget>
- </item>
- <item row="2" column="2">
- <widget class="QPushButton" name="logButton">
- <property name="text">
- <string>&amp;Log</string>
- </property>
- </widget>
- </item>
- <item row="1" column="1">
- <widget class="QPushButton" name="checkoutButton">
- <property name="text">
- <string>&amp;Checkout</string>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <property name="spacing">
+ <number>15</number>
</property>
- </widget>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="addButton">
+ <property name="text">
+ <string>&amp;Add...</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeButton">
+ <property name="text">
+ <string>&amp;Remove</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="checkoutButton">
+ <property name="text">
+ <string>&amp;Checkout</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_4">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="diffButton">
+ <property name="text">
+ <string>&amp;Diff</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="logButton">
+ <property name="text">
+ <string>&amp;Log</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_5">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item>
+ <widget class="QPushButton" name="mergeButton">
+ <property name="text">
+ <string>&amp;Merge</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="rebaseButton">
+ <property name="text">
+ <string>Re&amp;base</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
</item>
</layout>
</widget>
@@ -126,11 +178,6 @@
</widget>
<tabstops>
<tabstop>branchView</tabstop>
- <tabstop>addButton</tabstop>
- <tabstop>checkoutButton</tabstop>
- <tabstop>removeButton</tabstop>
- <tabstop>diffButton</tabstop>
- <tabstop>logButton</tabstop>
<tabstop>buttonBox</tabstop>
<tabstop>refreshButton</tabstop>
</tabstops>
diff --git a/src/plugins/git/branchmodel.cpp b/src/plugins/git/branchmodel.cpp
index d5c35c7496..5807783179 100644
--- a/src/plugins/git/branchmodel.cpp
+++ b/src/plugins/git/branchmodel.cpp
@@ -48,16 +48,20 @@ class BranchNode
{
public:
BranchNode() :
- parent(0), current(false)
+ parent(0),
+ name(QLatin1String("<ROOT>"))
{ }
- BranchNode(const QString &n, const QString &s = QString(), bool c = false) :
- parent(0), current(c), name(n), sha(s)
+ BranchNode(const QString &n, const QString &s = QString()) :
+ parent(0), name(n), sha(s)
{ }
~BranchNode()
{
- qDeleteAll(children);
+ while (!children.isEmpty())
+ delete children.first();
+ if (parent)
+ parent->children.removeAll(this);
}
BranchNode *rootNode() const
@@ -152,10 +156,14 @@ public:
return QStringList(fullName().join(QString(QLatin1Char('/'))));
}
+ int rowOf(BranchNode *node)
+ {
+ return children.indexOf(node);
+ }
+
BranchNode *parent;
QList<BranchNode *> children;
- bool current;
QString name;
QString sha;
mutable QString toolTip;
@@ -168,7 +176,8 @@ public:
BranchModel::BranchModel(GitClient *client, QObject *parent) :
QAbstractItemModel(parent),
m_client(client),
- m_rootNode(new BranchNode)
+ m_rootNode(new BranchNode),
+ m_currentBranch(0)
{
QTC_CHECK(m_client);
m_rootNode->append(new BranchNode(tr("Local Branches")));
@@ -179,32 +188,34 @@ BranchModel::~BranchModel()
delete m_rootNode;
}
-QModelIndex BranchModel::index(int row, int column, const QModelIndex &parent) const
+QModelIndex BranchModel::index(int row, int column, const QModelIndex &parentIdx) const
{
- BranchNode *node = m_rootNode;
- if (parent.isValid())
- node = static_cast<BranchNode *>(parent.internalPointer());
- if (row >= node->count())
+ if (column != 0)
return QModelIndex();
- return createIndex(row, column, static_cast<void *>(node->children.at(row)));
+ BranchNode *parentNode = indexToNode(parentIdx);
+
+ if (row >= parentNode->count())
+ return QModelIndex();
+ return nodeToIndex(parentNode->children.at(row));
}
QModelIndex BranchModel::parent(const QModelIndex &index) const
{
- BranchNode *node = static_cast<BranchNode *>(index.internalPointer());
+ if (!index.isValid())
+ return QModelIndex();
+
+ BranchNode *node = indexToNode(index);
if (node->parent == m_rootNode)
return QModelIndex();
- int row = node->parent->children.indexOf(node);
- return createIndex(row, 0, static_cast<void *>(node->parent));
+ return nodeToIndex(node->parent);
}
-int BranchModel::rowCount(const QModelIndex &parent) const
+int BranchModel::rowCount(const QModelIndex &parentIdx) const
{
- if (!parent.isValid())
- return m_rootNode->count();
- if (parent.column() != 0)
+ if (parentIdx.column() > 0)
return 0;
- return static_cast<BranchNode *>(parent.internalPointer())->count();
+
+ return indexToNode(parentIdx)->count();
}
int BranchModel::columnCount(const QModelIndex &parent) const
@@ -215,7 +226,9 @@ int BranchModel::columnCount(const QModelIndex &parent) const
QVariant BranchModel::data(const QModelIndex &index, int role) const
{
- BranchNode *node = static_cast<BranchNode *>(index.internalPointer());
+ BranchNode *node = indexToNode(index);
+ if (!node)
+ return QVariant();
switch (role) {
case Qt::DisplayRole:
@@ -232,7 +245,7 @@ QVariant BranchModel::data(const QModelIndex &index, int role) const
QFont font;
if (!node->isLeaf()) {
font.setBold(true);
- } else if (node->current) {
+ } else if (node == m_currentBranch) {
font.setBold(true);
font.setUnderline(true);
}
@@ -247,7 +260,9 @@ bool BranchModel::setData(const QModelIndex &index, const QVariant &value, int r
{
if (role != Qt::EditRole)
return false;
- BranchNode *node = static_cast<BranchNode *>(index.internalPointer());
+ BranchNode *node = indexToNode(index);
+ if (!node)
+ return false;
const QString newName = value.toString();
if (newName.isEmpty())
@@ -278,7 +293,9 @@ bool BranchModel::setData(const QModelIndex &index, const QVariant &value, int r
Qt::ItemFlags BranchModel::flags(const QModelIndex &index) const
{
- BranchNode *node = static_cast<BranchNode *>(index.internalPointer());
+ BranchNode *node = indexToNode(index);
+ if (!node)
+ return Qt::NoItemFlags;
if (node->isLeaf() && node->isLocal())
return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
else
@@ -287,15 +304,13 @@ Qt::ItemFlags BranchModel::flags(const QModelIndex &index) const
void BranchModel::clear()
{
- while (m_rootNode->count() > 1) {
- BranchNode *n = m_rootNode->children.takeLast();
- delete n;
- }
+ while (m_rootNode->count() > 1)
+ delete m_rootNode->children.takeLast();
BranchNode *locals = m_rootNode->children.at(0);
- while (locals->count()) {
- BranchNode *n = locals->children.takeLast();
- delete n;
- }
+ while (locals->count())
+ delete locals->children.takeLast();
+
+ m_currentBranch = 0;
}
bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage)
@@ -307,13 +322,10 @@ bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage
branchArgs << QLatin1String(GitClient::noColorOption)
<< QLatin1String("-v") << QLatin1String("-a");
QString output;
- if (!m_client->synchronousBranchCmd(workingDirectory, branchArgs, &output, errorMessage)) {
+ if (!m_client->synchronousBranchCmd(workingDirectory, branchArgs, &output, errorMessage))
VcsBase::VcsBaseOutputWindow::instance()->appendError(*errorMessage);
- return false;
- }
beginResetModel();
-
clear();
m_workingDirectory = workingDirectory;
@@ -322,6 +334,7 @@ bool BranchModel::refresh(const QString &workingDirectory, QString *errorMessage
parseOutputLine(l);
endResetModel();
+
return true;
}
@@ -349,23 +362,17 @@ GitClient *BranchModel::client() const
QModelIndex BranchModel::currentBranch() const
{
- if (!m_rootNode || !m_rootNode->count())
+ if (!m_currentBranch)
return QModelIndex();
- BranchNode *localBranches = m_rootNode->children.at(0);
- QModelIndex localIdx = index(0, 0, QModelIndex());
- for (int i = 0; i < localBranches->count(); ++i) {
- if (localBranches->children.at(i)->current)
- return index(i, 0, localIdx);
- }
- return QModelIndex();
+ return nodeToIndex(m_currentBranch);
}
QString BranchModel::branchName(const QModelIndex &idx) const
{
if (!idx.isValid())
return QString();
- BranchNode *node = static_cast<BranchNode *>(idx.internalPointer());
- if (!node->isLeaf())
+ BranchNode *node = indexToNode(idx);
+ if (!node || !node->isLeaf())
return QString();
QStringList path = node->fullName();
return path.join(QString(QLatin1Char('/')));
@@ -383,7 +390,7 @@ QString BranchModel::sha(const QModelIndex &idx) const
{
if (!idx.isValid())
return QString();
- BranchNode *node = static_cast<BranchNode *>(idx.internalPointer());
+ BranchNode *node = indexToNode(idx);
return node->sha;
}
@@ -391,7 +398,7 @@ bool BranchModel::isLocal(const QModelIndex &idx) const
{
if (!idx.isValid())
return false;
- BranchNode *node = static_cast<BranchNode *>(idx.internalPointer());
+ BranchNode *node = indexToNode(idx);
return node->isLocal();
}
@@ -399,7 +406,7 @@ bool BranchModel::isLeaf(const QModelIndex &idx) const
{
if (!idx.isValid())
return false;
- BranchNode *node = static_cast<BranchNode *>(idx.internalPointer());
+ BranchNode *node = indexToNode(idx);
return node->isLeaf();
}
@@ -419,11 +426,15 @@ void BranchModel::removeBranch(const QModelIndex &idx)
return;
}
- QModelIndex parentIdx = parent(idx);
- beginRemoveRows(parentIdx, idx.row(), idx.row());
- static_cast<BranchNode *>(parentIdx.internalPointer())->children.removeAt(parentIdx.row());
- delete static_cast<BranchNode *>(idx.internalPointer());
- endRemoveRows();
+ QModelIndex tmp = idx; // tmp is a leaf, so count must be 0.
+ while (indexToNode(tmp)->count() == 0) {
+ QModelIndex tmpParent = parent(tmp);
+ beginRemoveRows(tmpParent, tmp.row(), tmp.row());
+ indexToNode(tmpParent)->children.removeAt(tmp.row());
+ delete indexToNode(tmp);
+ endRemoveRows();
+ tmp = tmpParent;
+ }
}
void BranchModel::checkoutBranch(const QModelIndex &idx)
@@ -432,26 +443,19 @@ void BranchModel::checkoutBranch(const QModelIndex &idx)
if (branch.isEmpty())
return;
- QString errorMessage;
- switch (m_client->ensureStash(m_workingDirectory, &errorMessage)) {
- case GitClient::StashUnchanged:
- case GitClient::Stashed:
- case GitClient::NotStashed:
- break;
- case GitClient::StashCanceled:
+ GitClient::StashGuard stashGuard(m_workingDirectory, QLatin1String("Branch-Checkout"));
+ if (stashGuard.stashingFailed(false))
return;
- case GitClient::StashFailed:
- VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
- return;
- }
- if (m_client->synchronousCheckoutBranch(m_workingDirectory, branch, &errorMessage)) {
+ stashGuard.preventPop();
+ QString errorMessage;
+ if (m_client->synchronousCheckout(m_workingDirectory, branch, &errorMessage)) {
if (errorMessage.isEmpty()) {
QModelIndex currentIdx = currentBranch();
if (currentIdx.isValid()) {
- static_cast<BranchNode *>(currentIdx.internalPointer())->current = false;
- emit dataChanged(currentBranch(), currentBranch());
+ m_currentBranch = 0;
+ emit dataChanged(currentIdx, currentIdx);
}
- static_cast<BranchNode *>(idx.internalPointer())->current = true;
+ m_currentBranch = indexToNode(idx);
emit dataChanged(idx, idx);
} else {
refresh(m_workingDirectory, &errorMessage); // not sure all went well... better refresh!
@@ -472,10 +476,8 @@ bool BranchModel::branchIsMerged(const QModelIndex &idx)
QStringList args;
args << QLatin1String("-a") << QLatin1String("--contains") << sha(idx);
- if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage)) {
+ if (!m_client->synchronousBranchCmd(m_workingDirectory, args, &output, &errorMessage))
VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
- return false;
- }
QStringList lines = output.split(QLatin1Char('\n'), QString::SkipEmptyParts);
foreach (const QString &l, lines) {
@@ -555,21 +557,38 @@ void BranchModel::parseOutputLine(const QString &line)
if (nameParts.count() < 1)
return;
+ if (nameParts.isEmpty() || nameParts.at(0) != QLatin1String("remotes"))
+ nameParts.prepend(m_rootNode->children.at(0)->name); // Insert the local designator
+ else
+ nameParts.removeFirst(); // remove "remotes"
+ while (nameParts.count() > 3) {
+ nameParts[2] = nameParts.at(2) + QLatin1Char('/') + nameParts.at(3);
+ nameParts.removeAt(3);
+ }
+
QString name = nameParts.last();
nameParts.removeLast();
- if (nameParts.isEmpty() || nameParts.at(0) != QLatin1String("remotes")) {
- // local branch:
- while (nameParts.count() > 2)
- nameParts[1] = nameParts.at(1) + QLatin1Char('/') + nameParts.at(2);
- m_rootNode->children.at(0)->insert(nameParts, new BranchNode(name, sha, current));
- } else {
- // remote branch:
- nameParts.removeFirst(); // remove "remotes"
- while (nameParts.count() > 2)
- nameParts[1] = nameParts.at(1) + QLatin1Char('/') + nameParts.at(2);
- m_rootNode->insert(nameParts, new BranchNode(name, sha, current));
- }
+ BranchNode *newNode = new BranchNode(name, sha);
+ m_rootNode->insert(nameParts, newNode);
+ if (current)
+ m_currentBranch = newNode;
+}
+
+BranchNode *BranchModel::indexToNode(const QModelIndex &index) const
+{
+ if (index.column() > 0)
+ return 0;
+ if (!index.isValid())
+ return m_rootNode;
+ return static_cast<BranchNode *>(index.internalPointer());
+}
+
+QModelIndex BranchModel::nodeToIndex(BranchNode *node) const
+{
+ if (node == m_rootNode)
+ return QModelIndex();
+ return createIndex(node->parent->rowOf(node), 0, static_cast<void *>(node));
}
QString BranchModel::toolTip(const QString &sha) const
diff --git a/src/plugins/git/branchmodel.h b/src/plugins/git/branchmodel.h
index ea6212dc9c..109262a48f 100644
--- a/src/plugins/git/branchmodel.h
+++ b/src/plugins/git/branchmodel.h
@@ -55,7 +55,7 @@ public:
// QAbstractItemModel
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int rowCount(const QModelIndex &parentIdx = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
@@ -83,12 +83,15 @@ public:
private:
void parseOutputLine(const QString &line);
+ BranchNode *indexToNode(const QModelIndex &index) const;
+ QModelIndex nodeToIndex(BranchNode *node) const;
QString toolTip(const QString &sha) const;
GitClient *m_client;
QString m_workingDirectory;
BranchNode *m_rootNode;
+ BranchNode *m_currentBranch;
};
} // namespace Internal
diff --git a/src/plugins/git/changeselectiondialog.cpp b/src/plugins/git/changeselectiondialog.cpp
index 2a3893d333..d818c964b5 100644
--- a/src/plugins/git/changeselectiondialog.cpp
+++ b/src/plugins/git/changeselectiondialog.cpp
@@ -33,17 +33,39 @@
#include <QFileDialog>
#include <QMessageBox>
+#include <QProcess>
namespace Git {
namespace Internal {
-ChangeSelectionDialog::ChangeSelectionDialog(QWidget *parent)
+ChangeSelectionDialog::ChangeSelectionDialog(const QString &workingDirectory, QWidget *parent)
: QDialog(parent)
+ , m_process(0)
{
m_ui.setupUi(this);
+ if (!workingDirectory.isEmpty()) {
+ setWorkingDirectory(workingDirectory);
+ m_ui.workingDirectoryButton->setEnabled(false);
+ m_ui.workingDirectoryEdit->setEnabled(false);
+ }
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
connect(m_ui.workingDirectoryButton, SIGNAL(clicked()), this, SLOT(selectWorkingDirectory()));
setWindowTitle(tr("Select a Git Commit"));
+
+ bool ok;
+ m_gitBinaryPath = GitPlugin::instance()->gitClient()->gitBinaryPath(&ok);
+ if (!ok)
+ return;
+
+ m_gitEnvironment = GitPlugin::instance()->gitClient()->processEnvironment();
+ connect(m_ui.changeNumberEdit, SIGNAL(textChanged(QString)),
+ this, SLOT(recalculateDetails(QString)));
+ recalculateDetails(m_ui.changeNumberEdit->text());
+}
+
+ChangeSelectionDialog::~ChangeSelectionDialog()
+{
+ delete m_process;
}
QString ChangeSelectionDialog::change() const
@@ -58,6 +80,8 @@ QString ChangeSelectionDialog::workingDirectory() const
void ChangeSelectionDialog::setWorkingDirectory(const QString &s)
{
+ if (s.isEmpty())
+ return;
m_ui.workingDirectoryEdit->setText(QDir::toNativeSeparators(s));
m_ui.changeNumberEdit->setFocus(Qt::ActiveWindowFocusReason);
m_ui.changeNumberEdit->setText(QLatin1String("HEAD"));
@@ -82,5 +106,39 @@ void ChangeSelectionDialog::selectWorkingDirectory()
tr("Selected directory is not a Git repository"));
}
+//! Set commit message in details
+void ChangeSelectionDialog::setDetails(int exitCode)
+{
+ if (exitCode == 0)
+ m_ui.detailsText->setPlainText(QString::fromUtf8(m_process->readAllStandardOutput()));
+ else
+ m_ui.detailsText->setPlainText(tr("Error: unknown reference"));
}
+
+void ChangeSelectionDialog::recalculateDetails(const QString &ref)
+{
+ if (m_process) {
+ m_process->kill();
+ m_process->waitForFinished();
+ delete m_process;
+ }
+
+ QStringList args;
+ args << QLatin1String("log") << QLatin1String("-n1") << ref;
+
+ m_process = new QProcess(this);
+ m_process->setWorkingDirectory(workingDirectory());
+ m_process->setProcessEnvironment(m_gitEnvironment);
+
+ connect(m_process, SIGNAL(finished(int)), this, SLOT(setDetails(int)));
+
+ m_process->start(m_gitBinaryPath, args);
+ m_process->closeWriteChannel();
+ if (!m_process->waitForStarted())
+ m_ui.detailsText->setPlainText(tr("Error: could not start git"));
+ else
+ m_ui.detailsText->setPlainText(tr("Fetching commit data..."));
}
+
+} // Internal
+} // Git
diff --git a/src/plugins/git/changeselectiondialog.h b/src/plugins/git/changeselectiondialog.h
index d178753eff..6a78093e29 100644
--- a/src/plugins/git/changeselectiondialog.h
+++ b/src/plugins/git/changeselectiondialog.h
@@ -31,6 +31,8 @@
#define CHANGESELECTIONDIALOG_H
#include <QDialog>
+#include <QProcessEnvironment>
+QT_FORWARD_DECLARE_CLASS(QProcess)
#include "ui_changeselectiondialog.h"
@@ -41,7 +43,8 @@ class ChangeSelectionDialog : public QDialog
{
Q_OBJECT
public:
- ChangeSelectionDialog(QWidget *parent = 0);
+ ChangeSelectionDialog(const QString &workingDirectory = QString(), QWidget *parent = 0);
+ ~ChangeSelectionDialog();
QString change() const;
@@ -51,8 +54,15 @@ public:
public slots:
void selectWorkingDirectory();
+private slots:
+ void setDetails(int exitCode);
+ void recalculateDetails(const QString &ref);
+
private:
Ui_ChangeSelectionDialog m_ui;
+ QProcess* m_process;
+ QString m_gitBinaryPath;
+ QProcessEnvironment m_gitEnvironment;
};
} // namespace Internal
diff --git a/src/plugins/git/changeselectiondialog.ui b/src/plugins/git/changeselectiondialog.ui
index 7cc88ec38b..f4167bbfa0 100644
--- a/src/plugins/git/changeselectiondialog.ui
+++ b/src/plugins/git/changeselectiondialog.ui
@@ -6,16 +6,26 @@
<rect>
<x>0</x>
<y>0</y>
- <width>359</width>
- <height>115</height>
+ <width>595</width>
+ <height>396</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
+ <item row="3" column="0" colspan="3">
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
<item row="0" column="0">
- <widget class="QLabel" name="label">
+ <widget class="QLabel" name="workingDirectoryLabel">
<property name="text">
<string>Working directory:</string>
</property>
@@ -32,22 +42,25 @@
</widget>
</item>
<item row="1" column="0">
- <widget class="QLabel" name="label_2">
+ <widget class="QLabel" name="changeLabel">
<property name="text">
<string>Change:</string>
</property>
</widget>
</item>
- <item row="1" column="1">
+ <item row="1" column="1" colspan="2">
<widget class="QLineEdit" name="changeNumberEdit"/>
</item>
<item row="2" column="0" colspan="3">
- <widget class="QDialogButtonBox" name="buttonBox">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
+ <widget class="QPlainTextEdit" name="detailsText">
+ <property name="undoRedoEnabled">
+ <bool>false</bool>
</property>
- <property name="standardButtons">
- <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ <property name="lineWrapMode">
+ <enum>QPlainTextEdit::NoWrap</enum>
+ </property>
+ <property name="readOnly">
+ <bool>true</bool>
</property>
</widget>
</item>
diff --git a/src/plugins/git/clonewizard.h b/src/plugins/git/clonewizard.h
index df13971d7d..f0c5af8adf 100644
--- a/src/plugins/git/clonewizard.h
+++ b/src/plugins/git/clonewizard.h
@@ -42,15 +42,15 @@ public:
explicit CloneWizard(QObject *parent = 0);
// IWizard
- virtual QIcon icon() const;
- virtual QString description() const;
- virtual QString displayName() const;
+ QIcon icon() const;
+ QString description() const;
+ QString displayName() const;
protected:
// BaseCheckoutWizard
- virtual QList<QWizardPage*> createParameterPages(const QString &path);
- virtual QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath);
+ QList<QWizardPage*> createParameterPages(const QString &path);
+ QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/git/clonewizardpage.cpp b/src/plugins/git/clonewizardpage.cpp
index bea49e857f..40cf166b9d 100644
--- a/src/plugins/git/clonewizardpage.cpp
+++ b/src/plugins/git/clonewizardpage.cpp
@@ -115,9 +115,8 @@ QString CloneWizardPage::directoryFromRepository(const QString &urlIn) const
if (url.endsWith(d->mainLinePostfix)) {
url.truncate(url.size() - d->mainLinePostfix.size());
} else {
- if (url.endsWith(d->gitPostFix)) {
+ if (url.endsWith(d->gitPostFix))
url.truncate(url.size() - d->gitPostFix.size());
- }
}
// Check for equal parts, something like "qt/qt" -> "qt"
const int slashPos = url.indexOf(slash);
diff --git a/src/plugins/git/clonewizardpage.h b/src/plugins/git/clonewizardpage.h
index c696e6c637..f7ad3a653b 100644
--- a/src/plugins/git/clonewizardpage.h
+++ b/src/plugins/git/clonewizardpage.h
@@ -49,13 +49,13 @@ class CloneWizardPage : public VcsBase::BaseCheckoutWizardPage
Q_PROPERTY(bool deleteMasterBranch READ deleteMasterBranch WRITE setDeleteMasterBranch)
public:
explicit CloneWizardPage(QWidget *parent = 0);
- virtual ~CloneWizardPage();
+ ~CloneWizardPage();
QSharedPointer<VcsBase::AbstractCheckoutJob> createCheckoutJob(QString *checkoutPath) const;
protected:
- virtual QString directoryFromRepository(const QString &r) const;
- virtual QStringList branches(const QString &repository, int *current);
+ QString directoryFromRepository(const QString &r) const;
+ QStringList branches(const QString &repository, int *current);
bool deleteMasterBranch() const;
void setDeleteMasterBranch(bool v);
diff --git a/src/plugins/git/commitdata.cpp b/src/plugins/git/commitdata.cpp
index 4ee06bbf9e..fb7092c7b8 100644
--- a/src/plugins/git/commitdata.cpp
+++ b/src/plugins/git/commitdata.cpp
@@ -40,14 +40,12 @@ namespace Internal {
void GitSubmitEditorPanelInfo::clear()
{
repository.clear();
- description.clear();
branch.clear();
}
QDebug operator<<(QDebug d, const GitSubmitEditorPanelInfo &data)
{
- d.nospace() << "Rep: " << data.repository << " Descr: " << data.description
- << " branch: " << data.branch;
+ d.nospace() << "Rep: " << data.repository << " branch: " << data.branch;
return d;
}
@@ -88,58 +86,77 @@ void CommitData::clear()
files.clear();
}
-static CommitData::FileState stateFor(const QChar &c)
+static FileStates stateFor(const QChar &c)
{
switch (c.unicode()) {
case ' ':
- return CommitData::UntrackedFile;
+ return UntrackedFile;
case 'M':
- return CommitData::ModifiedFile;
+ return ModifiedFile;
case 'A':
- return CommitData::AddedFile;
+ return AddedFile;
case 'D':
- return CommitData::DeletedFile;
+ return DeletedFile;
case 'R':
- return CommitData::RenamedFile;
+ return RenamedFile;
case 'C':
- return CommitData::CopiedFile;
+ return CopiedFile;
case 'U':
- return CommitData::UpdatedFile;
+ return UnmergedFile;
default:
- return CommitData::UnknownFileState;
+ return UnknownFileState;
}
}
-static bool checkLine(const QString &stateInfo, const QString &file, QList<CommitData::StateFilePair> *files)
+bool operator<(const CommitData::StateFilePair &a, const CommitData::StateFilePair &b)
+{
+ if ((a.first & UnmergedFile) && !(b.first & UnmergedFile))
+ return false;
+ if ((b.first & UnmergedFile) && !(a.first & UnmergedFile))
+ return true;
+ return a.second < b.second;
+}
+
+bool CommitData::checkLine(const QString &stateInfo, const QString &file)
{
QTC_ASSERT(stateInfo.count() == 2, return false);
- QTC_ASSERT(files, return false);
if (stateInfo == QLatin1String("??")) {
- files->append(qMakePair(CommitData::UntrackedFile, file));
+ files.append(qMakePair(FileStates(UntrackedFile), file));
return true;
}
- CommitData::FileState stagedState = stateFor(stateInfo.at(0));
- if (stagedState == CommitData::UnknownFileState)
+ FileStates xState = stateFor(stateInfo.at(0));
+ FileStates yState = stateFor(stateInfo.at(1));
+ if (xState == UnknownFileState || yState == UnknownFileState)
return false;
- stagedState = static_cast<CommitData::FileState>(stagedState | CommitData::StagedFile);
- if (stagedState != CommitData::StagedFile)
- files->append(qMakePair(stagedState, file));
-
- CommitData::FileState state = stateFor(stateInfo.at(1));
- if (state == CommitData::UnknownFileState)
- return false;
+ bool isMerge = (xState == UnmergedFile || yState == UnmergedFile ||
+ ((xState == yState) && (xState == AddedFile || xState == DeletedFile)));
+ if (isMerge) {
+ if (xState == yState) {
+ if (xState == UnmergedFile)
+ xState = ModifiedFile;
+ files.append(qMakePair(xState | UnmergedFile | UnmergedUs | UnmergedThem, file));
+ } else if (xState == UnmergedFile) {
+ files.append(qMakePair(yState | UnmergedFile | UnmergedThem, file));
+ } else {
+ files.append(qMakePair(xState | UnmergedFile | UnmergedUs, file));
+ }
+ } else {
+ xState |= StagedFile;
+ if (xState != StagedFile)
+ files.append(qMakePair(xState, file));
- if (state != CommitData::UntrackedFile) {
- QString newFile = file;
- if (stagedState == CommitData::RenamedStagedFile || stagedState == CommitData::CopiedStagedFile)
- newFile = file.mid(file.indexOf(QLatin1String(" -> ")) + 4);
+ if (yState != UntrackedFile) {
+ QString newFile = file;
+ if (xState & (RenamedFile | CopiedFile))
+ newFile = file.mid(file.indexOf(QLatin1String(" -> ")) + 4);
- files->append(qMakePair(state, newFile));
+ files.append(qMakePair(yState, newFile));
+ }
}
-
+ qSort(files);
return true;
}
@@ -165,24 +182,24 @@ bool CommitData::parseFilesFromStatus(const QString &output)
QString file = line.mid(3);
if (file.startsWith(QLatin1Char('"')))
file.remove(0, 1).chop(1);
- if (!checkLine(line.mid(0, 2), file, &files))
+ if (!checkLine(line.mid(0, 2), file))
return false;
}
return true;
}
-QStringList CommitData::filterFiles(const CommitData::FileState &state) const
+QStringList CommitData::filterFiles(const FileStates &state) const
{
QStringList result;
foreach (const StateFilePair &p, files) {
- if (state == AllStates || state == p.first)
+ if (state == p.first)
result.append(p.second);
}
return result;
}
-QString CommitData::stateDisplayName(const FileState &state)
+QString CommitData::stateDisplayName(const FileStates &state)
{
QString resultState;
if (state == UntrackedFile)
@@ -200,8 +217,14 @@ QString CommitData::stateDisplayName(const FileState &state)
resultState.append(QCoreApplication::translate("Git::Internal::CommitData", "renamed"));
else if (state & CopiedFile)
resultState.append(QCoreApplication::translate("Git::Internal::CommitData", "copied"));
- else if (state & UpdatedFile)
- resultState.append(QCoreApplication::translate("Git::Internal::CommitData", "updated"));
+ if (state & UnmergedUs) {
+ if (state & UnmergedThem)
+ resultState.append(QCoreApplication::translate("Git::Internal::CommitData", " by both"));
+ else
+ resultState.append(QCoreApplication::translate("Git::Internal::CommitData", " by us"));
+ } else if (state & UnmergedThem) {
+ resultState.append(QCoreApplication::translate("Git::Internal::CommitData", " by them"));
+ }
return resultState;
}
diff --git a/src/plugins/git/commitdata.h b/src/plugins/git/commitdata.h
index fd314a5ed3..40faabe4fa 100644
--- a/src/plugins/git/commitdata.h
+++ b/src/plugins/git/commitdata.h
@@ -45,7 +45,6 @@ struct GitSubmitEditorPanelInfo
{
void clear();
QString repository;
- QString description;
QString branch;
};
@@ -64,33 +63,29 @@ struct GitSubmitEditorPanelData
QDebug operator<<(QDebug d, const GitSubmitEditorPanelData &);
+enum FileState {
+ UntrackedFile = 0,
+
+ StagedFile = 0x01,
+ ModifiedFile = 0x02,
+ AddedFile = 0x04,
+ DeletedFile = 0x08,
+ RenamedFile = 0x10,
+ CopiedFile = 0x20,
+ UnmergedFile = 0x40,
+
+ UnmergedUs = 0x100,
+ UnmergedThem = 0x200,
+
+ UnknownFileState = 0x800
+};
+Q_DECLARE_FLAGS(FileStates, FileState)
+
class CommitData
{
public:
- enum FileState {
- UntrackedFile = 0,
-
- StagedFile = 0x01,
- ModifiedFile = 0x02,
- AddedFile = 0x04,
- DeletedFile = 0x08,
- RenamedFile = 0x10,
- CopiedFile = 0x20,
- UpdatedFile = 0x40,
-
- ModifiedStagedFile = StagedFile | ModifiedFile,
- AddedStagedFile = StagedFile | AddedFile,
- DeletedStagedFile = StagedFile | DeletedFile,
- RenamedStagedFile = StagedFile | RenamedFile,
- CopiedStagedFile = StagedFile | CopiedFile,
- UpdatedStagedFile = StagedFile | UpdatedFile,
-
- AllStates = UpdatedFile | CopiedFile | RenamedFile | DeletedFile | AddedFile | ModifiedFile | StagedFile,
- UnknownFileState
- };
-
// A pair of state string/file name ('modified', 'file.cpp').
- typedef QPair<FileState, QString> StateFilePair;
+ typedef QPair<FileStates, QString> StateFilePair;
void clear();
// Parse the files and the branch of panelInfo
@@ -99,9 +94,9 @@ public:
// Convenience to retrieve the file names from
// the specification list. Optionally filter for a certain state
- QStringList filterFiles(const FileState &state = AllStates) const;
+ QStringList filterFiles(const FileStates &state) const;
- static QString stateDisplayName(const FileState &state);
+ static QString stateDisplayName(const FileStates &state);
QString amendSHA1;
QString commitEncoding;
@@ -109,9 +104,24 @@ public:
GitSubmitEditorPanelData panelData;
QList<StateFilePair> files;
+
+private:
+ bool checkLine(const QString &stateInfo, const QString &file);
};
} // namespace Internal
} // namespace Git
+Q_DECLARE_OPERATORS_FOR_FLAGS(Git::Internal::FileStates)
+
+namespace Git {
+namespace Internal {
+
+// Must appear after Q_DECLARE_OPERATORS_FOR_FLAGS
+bool operator<(const CommitData::StateFilePair &a,
+ const CommitData::StateFilePair &b);
+
+} // namespace Internal
+} // namespace Git
+
#endif // COMMITDATA_H
diff --git a/src/plugins/git/gerrit/gerritdialog.cpp b/src/plugins/git/gerrit/gerritdialog.cpp
index 8e15ed37a9..01d19f99d7 100644
--- a/src/plugins/git/gerrit/gerritdialog.cpp
+++ b/src/plugins/git/gerrit/gerritdialog.cpp
@@ -104,6 +104,7 @@ GerritDialog::GerritDialog(const QSharedPointer<GerritParameters> &p,
, m_queryLineEdit(new QueryValidatingLineEdit)
, m_filterLineEdit(new Utils::FilterLineEdit)
, m_buttonBox(new QDialogButtonBox(QDialogButtonBox::Close))
+ , m_fetchRunning(false)
{
setWindowTitle(tr("Gerrit %1@%2").arg(p->user, p->host));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
@@ -266,6 +267,14 @@ const QStandardItem *GerritDialog::currentItem(int column) const
return 0;
}
+void GerritDialog::updateButtons()
+{
+ const bool enabled = !m_fetchRunning && m_treeView->selectionModel()->currentIndex().isValid();
+ m_displayButton->setEnabled(enabled);
+ m_applyButton->setEnabled(enabled);
+ m_checkoutButton->setEnabled(enabled);
+}
+
void GerritDialog::slotCurrentChanged()
{
const QModelIndex current = m_treeView->selectionModel()->currentIndex();
@@ -276,9 +285,27 @@ void GerritDialog::slotCurrentChanged()
} else {
m_detailsBrowser->setText(QString());
}
- m_displayButton->setEnabled(valid);
- m_applyButton->setEnabled(valid);
- m_checkoutButton->setEnabled(valid);
+ updateButtons();
+}
+
+void GerritDialog::fetchStarted(const QSharedPointer<Gerrit::Internal::GerritChange> &change)
+{
+ // Disable buttons to prevent parallel gerrit operations which can cause mix-ups.
+ m_fetchRunning = true;
+ updateButtons();
+ const QString toolTip = tr("Fetching \"%1\"...").arg(change->title);
+ m_displayButton->setToolTip(toolTip);
+ m_applyButton->setToolTip(toolTip);
+ m_checkoutButton->setToolTip(toolTip);
+}
+
+void GerritDialog::fetchFinished()
+{
+ m_fetchRunning = false;
+ updateButtons();
+ m_displayButton->setToolTip(QString());
+ m_applyButton->setToolTip(QString());
+ m_checkoutButton->setToolTip(QString());
}
} // namespace Internal
diff --git a/src/plugins/git/gerrit/gerritdialog.h b/src/plugins/git/gerrit/gerritdialog.h
index b78cd166eb..73a465948e 100644
--- a/src/plugins/git/gerrit/gerritdialog.h
+++ b/src/plugins/git/gerrit/gerritdialog.h
@@ -84,6 +84,10 @@ signals:
void fetchApply(const QSharedPointer<Gerrit::Internal::GerritChange> &);
void fetchCheckout(const QSharedPointer<Gerrit::Internal::GerritChange> &);
+public slots:
+ void fetchStarted(const QSharedPointer<Gerrit::Internal::GerritChange> &change);
+ void fetchFinished();
+
private slots:
void slotCurrentChanged();
void slotDoubleClicked(const QModelIndex &);
@@ -98,6 +102,7 @@ private:
const QStandardItem *currentItem(int column = 0) const;
QPushButton *addActionButton(const QString &text, const char *buttonSlot);
void updateCompletions(const QString &query);
+ void updateButtons();
const QSharedPointer<GerritParameters> m_parameters;
QSortFilterProxyModel *m_filterModel;
@@ -112,6 +117,7 @@ private:
QPushButton *m_applyButton;
QPushButton *m_checkoutButton;
QPushButton *m_refreshButton;
+ bool m_fetchRunning;
};
} // namespace Internal
diff --git a/src/plugins/git/gerrit/gerritmodel.cpp b/src/plugins/git/gerrit/gerritmodel.cpp
index 5b9795f32d..70e430781d 100644
--- a/src/plugins/git/gerrit/gerritmodel.cpp
+++ b/src/plugins/git/gerrit/gerritmodel.cpp
@@ -43,9 +43,14 @@
#include <QUrl>
#include <QTextStream>
#include <QDesktopServices>
+#include <QMessageBox>
+#include <QPushButton>
#include <QTextStream>
#include <QDebug>
#include <QScopedPointer>
+#include <QTimer>
+#include <QApplication>
+#include <QMessageBox>
#if QT_VERSION >= 0x050000
# include <QJsonDocument>
# include <QJsonValue>
@@ -258,6 +263,7 @@ private slots:
void processFinished(int exitCode, QProcess::ExitStatus);
void readyReadStandardError();
void readyReadStandardOutput();
+ void timeout();
private:
void startQuery(const QString &query);
@@ -266,6 +272,7 @@ private:
const QSharedPointer<GerritParameters> m_parameters;
const QStringList m_queries;
QProcess m_process;
+ QTimer m_timer;
QString m_binary;
QByteArray m_output;
int m_currentQuery;
@@ -273,6 +280,8 @@ private:
QStringList m_baseArguments;
};
+enum { timeOutMS = 30000 };
+
QueryContext::QueryContext(const QStringList &queries,
const QSharedPointer<GerritParameters> &p,
QObject *parent)
@@ -297,12 +306,18 @@ QueryContext::QueryContext(const QStringList &queries,
<< QLatin1String("--format=JSON");
m_binary = m_baseArguments.front();
m_baseArguments.pop_front();
+
+ m_timer.setInterval(timeOutMS);
+ m_timer.setSingleShot(true);
+ connect(&m_timer, SIGNAL(timeout()), this, SLOT(timeout()));
}
QueryContext::~QueryContext()
{
if (m_progress.isRunning())
m_progress.reportFinished();
+ if (m_timer.isActive())
+ m_timer.stop();
m_process.disconnect(this);
Utils::SynchronousProcess::stopProcess(m_process);
}
@@ -323,6 +338,7 @@ void QueryContext::startQuery(const QString &query)
arguments.push_back(query);
VcsBase::VcsBaseOutputWindow::instance()
->appendCommand(m_process.workingDirectory(), m_binary, arguments);
+ m_timer.start();
m_process.start(m_binary, arguments);
m_process.closeWriteChannel();
}
@@ -338,15 +354,16 @@ void QueryContext::errorTermination(const QString &msg)
void QueryContext::processError(QProcess::ProcessError e)
{
const QString msg = tr("Error running %1: %2").arg(m_binary, m_process.errorString());
- if (e == QProcess::FailedToStart) {
+ if (e == QProcess::FailedToStart)
errorTermination(msg);
- } else {
+ else
VcsBase::VcsBaseOutputWindow::instance()->appendError(msg);
- }
}
void QueryContext::processFinished(int exitCode, QProcess::ExitStatus es)
{
+ if (m_timer.isActive())
+ m_timer.stop();
if (es != QProcess::NormalExit) {
errorTermination(tr("%1 crashed.").arg(m_binary));
return;
@@ -376,6 +393,31 @@ void QueryContext::readyReadStandardOutput()
m_output.append(m_process.readAllStandardOutput());
}
+void QueryContext::timeout()
+{
+ if (m_process.state() != QProcess::Running)
+ return;
+
+ QWidget *parent = QApplication::activeModalWidget();
+ if (!parent)
+ parent = QApplication::activeWindow();
+ QMessageBox box(QMessageBox::Question, tr("Timeout"),
+ tr("The gerrit process has not responded within %1s.\n"
+ "Most likely this is caused by problems with SSH-authentication.\n"
+ "Would you like to terminate it?").
+ arg(timeOutMS / 1000), QMessageBox::NoButton, parent);
+ QPushButton *terminateButton = box.addButton(tr("Terminate"), QMessageBox::YesRole);
+ box.addButton(tr("Keep running"), QMessageBox::NoRole);
+ connect(&m_process, SIGNAL(finished(int)), &box, SLOT(reject()));
+ box.exec();
+ if (m_process.state() != QProcess::Running)
+ return;
+ if (box.clickedButton() == terminateButton)
+ Utils::SynchronousProcess::stopProcess(m_process);
+ else
+ m_timer.start();
+}
+
GerritModel::GerritModel(const QSharedPointer<GerritParameters> &p, QObject *parent)
: QStandardItemModel(0, ColumnCount, parent)
, m_parameters(p)
diff --git a/src/plugins/git/gerrit/gerritoptionspage.cpp b/src/plugins/git/gerrit/gerritoptionspage.cpp
index 83728021d9..f290ae2bcb 100644
--- a/src/plugins/git/gerrit/gerritoptionspage.cpp
+++ b/src/plugins/git/gerrit/gerritoptionspage.cpp
@@ -47,15 +47,10 @@ GerritOptionsPage::GerritOptionsPage(const QSharedPointer<GerritParameters> &p,
: VcsBase::VcsBaseOptionsPage(parent)
, m_parameters(p)
{
- setId(optionsId());
+ setId("Gerrit");
setDisplayName(tr("Gerrit"));
}
-QString GerritOptionsPage::optionsId()
-{
- return QLatin1String("Gerrit");
-}
-
QWidget *GerritOptionsPage::createPage(QWidget *parent)
{
GerritOptionsWidget *gow = new GerritOptionsWidget(parent);
diff --git a/src/plugins/git/gerrit/gerritoptionspage.h b/src/plugins/git/gerrit/gerritoptionspage.h
index e072e7d0c9..5a9fd079a2 100644
--- a/src/plugins/git/gerrit/gerritoptionspage.h
+++ b/src/plugins/git/gerrit/gerritoptionspage.h
@@ -34,7 +34,7 @@
#include <QWidget>
#include <QSharedPointer>
-#include <QWeakPointer>
+#include <QPointer>
QT_BEGIN_NAMESPACE
class QLineEdit;
@@ -75,8 +75,6 @@ public:
GerritOptionsPage(const QSharedPointer<GerritParameters> &p,
QObject *parent = 0);
- static QString optionsId();
-
QWidget *createPage(QWidget *parent);
void apply();
void finish() { }
@@ -84,7 +82,7 @@ public:
private:
const QSharedPointer<GerritParameters> &m_parameters;
- QWeakPointer<GerritOptionsWidget> m_widget;
+ QPointer<GerritOptionsWidget> m_widget;
};
} // namespace Internal
diff --git a/src/plugins/git/gerrit/gerritparameters.cpp b/src/plugins/git/gerrit/gerritparameters.cpp
index dc72bb9b66..3203295b50 100644
--- a/src/plugins/git/gerrit/gerritparameters.cpp
+++ b/src/plugins/git/gerrit/gerritparameters.cpp
@@ -35,6 +35,7 @@
#else
# include <utils/environment.h>
#endif
+#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <QDebug>
#include <QFileInfo>
@@ -71,16 +72,16 @@ static inline QString detectSsh()
#endif
if (!ssh.isEmpty())
return ssh;
-#ifdef Q_OS_WIN // Windows: Use ssh.exe from git if it cannot be found.
- const QString git = GerritPlugin::gitBinary();
- if (!git.isEmpty()) {
- // Is 'git\cmd' in the path (folder containing .bats)?
- QString path = QFileInfo(git).absolutePath();
- if (path.endsWith(QLatin1String("cmd"), Qt::CaseInsensitive))
- path.replace(path.size() - 3, 3, QLatin1String("bin"));
- ssh = path + QLatin1Char('/') + QLatin1String(defaultSshC);
+ if (Utils::HostOsInfo::isWindowsHost()) { // Windows: Use ssh.exe from git if it cannot be found.
+ const QString git = GerritPlugin::gitBinary();
+ if (!git.isEmpty()) {
+ // Is 'git\cmd' in the path (folder containing .bats)?
+ QString path = QFileInfo(git).absolutePath();
+ if (path.endsWith(QLatin1String("cmd"), Qt::CaseInsensitive))
+ path.replace(path.size() - 3, 3, QLatin1String("bin"));
+ ssh = path + QLatin1Char('/') + QLatin1String(defaultSshC);
+ }
}
-#endif
return ssh;
}
diff --git a/src/plugins/git/gerrit/gerritplugin.cpp b/src/plugins/git/gerrit/gerritplugin.cpp
index 5252c2fe37..410bcec8df 100644
--- a/src/plugins/git/gerrit/gerritplugin.cpp
+++ b/src/plugins/git/gerrit/gerritplugin.cpp
@@ -33,10 +33,10 @@
#include "gerritmodel.h"
#include "gerritoptionspage.h"
-#include <gitplugin.h>
-#include <gitclient.h>
-#include <gitversioncontrol.h>
-#include <gitconstants.h>
+#include "../gitplugin.h"
+#include "../gitclient.h"
+#include "../gitversioncontrol.h"
+#include "../gitconstants.h"
#include <vcsbase/vcsbaseconstants.h>
#include <vcsbase/vcsbaseeditor.h>
@@ -108,16 +108,13 @@ private:
{
FetchState, // Fetch patch
WritePatchFileState, // Write patch to a file
- CherryPickState, // Cherry-pick (apply) fetch-head
- CheckoutState, // Check out fetch-head
DoneState,
ErrorState
};
void handleError(const QString &message);
void startWritePatchFile();
- void startCherryPick();
- void startCheckout();
+ void cherryPick();
const QSharedPointer<GerritChange> m_change;
const QString m_repository;
@@ -199,12 +196,16 @@ void FetchContext::processFinished(int exitCode, QProcess::ExitStatus es)
startWritePatchFile();
break;
case FetchApply:
- m_state = CherryPickState;
- startCherryPick();
- break;
case FetchCheckout:
- m_state = CheckoutState;
- startCheckout();
+ if (m_fetchMode == FetchApply) {
+ cherryPick();
+ } else {
+ Git::Internal::GitPlugin::instance()->gitClient()->synchronousCheckout(
+ m_repository, QLatin1String("FETCH_HEAD"));
+ }
+ m_progress.reportFinished();
+ m_state = DoneState;
+ deleteLater();
break;
} // switch (m_fetchMode)
break;
@@ -231,11 +232,6 @@ void FetchContext::processFinished(int exitCode, QProcess::ExitStatus es)
break;
}
break;
- case CherryPickState:
- case CheckoutState:
- m_progress.reportFinished();
- m_state = DoneState;
- deleteLater();
}
}
@@ -243,21 +239,19 @@ void FetchContext::processReadyReadStandardError()
{
// Note: fetch displays progress on stderr.
const QString errorOutput = QString::fromLocal8Bit(m_process.readAllStandardError());
- if (m_state == FetchState || m_state == CheckoutState) {
+ if (m_state == FetchState)
VcsBase::VcsBaseOutputWindow::instance()->append(errorOutput);
- } else {
+ else
VcsBase::VcsBaseOutputWindow::instance()->appendError(errorOutput);
- }
}
void FetchContext::processReadyReadStandardOutput()
{
const QByteArray output = m_process.readAllStandardOutput();
- if (m_state == WritePatchFileState) {
+ if (m_state == WritePatchFileState)
m_patchFile->write(output);
- } else {
+ else
VcsBase::VcsBaseOutputWindow::instance()->append(QString::fromLocal8Bit(output));
- }
}
void FetchContext::handleError(const QString &e)
@@ -272,11 +266,10 @@ void FetchContext::handleError(const QString &e)
void FetchContext::processError(QProcess::ProcessError e)
{
const QString msg = tr("Error running %1: %2").arg(m_git, m_process.errorString());
- if (e == QProcess::FailedToStart) {
+ if (e == QProcess::FailedToStart)
handleError(msg);
- } else {
+ else
VcsBase::VcsBaseOutputWindow::instance()->appendError(msg);
- }
}
void FetchContext::startWritePatchFile()
@@ -306,27 +299,13 @@ void FetchContext::startWritePatchFile()
m_process.closeWriteChannel();
}
-void FetchContext::startCherryPick()
+void FetchContext::cherryPick()
{
// Point user to errors.
VcsBase::VcsBaseOutputWindow::instance()->popup(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus);
VcsBase::VcsBaseOutputWindow::instance()->append(tr("Cherry-picking %1...").arg(m_patchFileName));
- QStringList args;
- args << QLatin1String("cherry-pick") << QLatin1String("FETCH_HEAD");
- VcsBase::VcsBaseOutputWindow::instance()->appendCommand(m_repository, m_git, args);
- if (debug)
- qDebug() << m_git << args;
- m_process.start(m_git, args);
- m_process.closeWriteChannel();
-}
-
-void FetchContext::startCheckout()
-{
- QStringList args;
- args << QLatin1String("checkout") << QLatin1String("FETCH_HEAD");
- VcsBase::VcsBaseOutputWindow::instance()->appendCommand(m_repository, m_git, args);
- m_process.start(m_git, args);
- m_process.closeWriteChannel();
+ Git::Internal::GitPlugin::instance()->gitClient()->cherryPickCommit(
+ m_repository, QLatin1String("FETCH_HEAD"));
}
GerritPlugin::GerritPlugin(QObject *parent)
@@ -360,8 +339,8 @@ void GerritPlugin::openView()
{
if (m_dialog.isNull()) {
while (!m_parameters->isValid()) {
- const QString group = QLatin1String(VcsBase::Constants::VCS_SETTINGS_CATEGORY);
- if (!Core::ICore::instance()->showOptionsDialog(group, GerritOptionsPage::optionsId()))
+ const Core::Id group = VcsBase::Constants::VCS_SETTINGS_CATEGORY;
+ if (!Core::ICore::instance()->showOptionsDialog(group, Core::Id("Gerrit")))
return;
}
GerritDialog *gd = new GerritDialog(m_parameters, Core::ICore::mainWindow());
@@ -372,6 +351,9 @@ void GerritPlugin::openView()
this, SLOT(fetchApply(QSharedPointer<Gerrit::Internal::GerritChange>)));
connect(gd, SIGNAL(fetchCheckout(QSharedPointer<Gerrit::Internal::GerritChange>)),
this, SLOT(fetchCheckout(QSharedPointer<Gerrit::Internal::GerritChange>)));
+ connect(this, SIGNAL(fetchStarted(QSharedPointer<Gerrit::Internal::GerritChange>)),
+ gd, SLOT(fetchStarted(QSharedPointer<Gerrit::Internal::GerritChange>)));
+ connect(this, SIGNAL(fetchFinished()), gd, SLOT(fetchFinished()));
m_dialog = gd;
}
const Qt::WindowStates state = m_dialog.data()->windowState();
@@ -442,6 +424,8 @@ void GerritPlugin::fetch(const QSharedPointer<Gerrit::Internal::GerritChange> &c
FetchContext *fc = new FetchContext(change, repository, git,
m_parameters, FetchMode(mode), this);
+ connect(fc, SIGNAL(destroyed(QObject*)), this, SIGNAL(fetchFinished()));
+ emit fetchStarted(change);
fc->start();
}
diff --git a/src/plugins/git/gerrit/gerritplugin.h b/src/plugins/git/gerrit/gerritplugin.h
index 3e19660398..0e0109b1f6 100644
--- a/src/plugins/git/gerrit/gerritplugin.h
+++ b/src/plugins/git/gerrit/gerritplugin.h
@@ -31,8 +31,8 @@
#define GERRIT_INTERNAL_GERRITPLUGIN_H
#include <QObject>
+#include <QPointer>
#include <QSharedPointer>
-#include <QWeakPointer>
namespace Core {
class ActionContainer;
@@ -62,6 +62,10 @@ public slots:
void fetchApply(const QSharedPointer<Gerrit::Internal::GerritChange> &change);
void fetchCheckout(const QSharedPointer<Gerrit::Internal::GerritChange> &change);
+signals:
+ void fetchStarted(const QSharedPointer<Gerrit::Internal::GerritChange> &change);
+ void fetchFinished();
+
private slots:
void openView();
@@ -70,7 +74,7 @@ private:
void fetch(const QSharedPointer<Gerrit::Internal::GerritChange> &change, int mode);
QSharedPointer<GerritParameters> m_parameters;
- QWeakPointer<GerritDialog> m_dialog;
+ QPointer<GerritDialog> m_dialog;
};
} // namespace Internal
diff --git a/src/plugins/git/git.pro b/src/plugins/git/git.pro
index fb887a2e55..d562d567bd 100644
--- a/src/plugins/git/git.pro
+++ b/src/plugins/git/git.pro
@@ -1,6 +1,5 @@
TEMPLATE = lib
TARGET = Git
-DEFINES += QT_NO_CAST_FROM_ASCII
include(../../qtcreatorplugin.pri)
include(../../plugins/projectexplorer/projectexplorer.pri)
include(../../plugins/texteditor/texteditor.pri)
@@ -28,7 +27,9 @@ HEADERS += gitplugin.h \
remotemodel.h \
remotedialog.h \
branchadddialog.h \
- resetdialog.h
+ resetdialog.h \
+ mergetool.h \
+ branchcheckoutdialog.h
SOURCES += gitplugin.cpp \
gitclient.cpp \
@@ -50,7 +51,9 @@ SOURCES += gitplugin.cpp \
remotemodel.cpp \
remotedialog.cpp \
branchadddialog.cpp \
- resetdialog.cpp
+ resetdialog.cpp \
+ mergetool.cpp \
+ branchcheckoutdialog.cpp
FORMS += changeselectiondialog.ui \
settingspage.ui \
@@ -59,7 +62,8 @@ FORMS += changeselectiondialog.ui \
stashdialog.ui \
remotedialog.ui \
remoteadditiondialog.ui \
- branchadddialog.ui
+ branchadddialog.ui \
+ branchcheckoutdialog.ui
include(gitorious/gitorious.pri)
diff --git a/src/plugins/git/git.qbs b/src/plugins/git/git.qbs
index 64ce4ff905..91c2fa0700 100644
--- a/src/plugins/git/git.qbs
+++ b/src/plugins/git/git.qbs
@@ -12,30 +12,18 @@ QtcPlugin {
Depends { name: "VcsBase" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_NO_CAST_FROM_ASCII"])
- cpp.includePaths: [
- ".",
- "gitorious",
- "gerrit",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "branchadddialog.ui",
- "branchdialog.ui",
- "git.qrc",
- "gitsubmitpanel.ui",
- "remoteadditiondialog.ui",
- "stashdialog.ui",
"annotationhighlighter.cpp",
"annotationhighlighter.h",
"branchadddialog.cpp",
"branchadddialog.h",
+ "branchadddialog.ui",
+ "branchcheckoutdialog.cpp",
+ "branchcheckoutdialog.h",
+ "branchcheckoutdialog.ui",
"branchdialog.cpp",
"branchdialog.h",
+ "branchdialog.ui",
"branchmodel.cpp",
"branchmodel.h",
"changeselectiondialog.cpp",
@@ -47,6 +35,7 @@ QtcPlugin {
"clonewizardpage.h",
"commitdata.cpp",
"commitdata.h",
+ "git.qrc",
"gitclient.cpp",
"gitclient.h",
"gitconstants.h",
@@ -60,10 +49,14 @@ QtcPlugin {
"gitsubmiteditor.h",
"gitsubmiteditorwidget.cpp",
"gitsubmiteditorwidget.h",
+ "gitsubmitpanel.ui",
"gitutils.cpp",
"gitutils.h",
"gitversioncontrol.cpp",
"gitversioncontrol.h",
+ "mergetool.cpp",
+ "mergetool.h",
+ "remoteadditiondialog.ui",
"remotedialog.cpp",
"remotedialog.h",
"remotedialog.ui",
@@ -75,29 +68,30 @@ QtcPlugin {
"settingspage.h",
"settingspage.ui",
"stashdialog.cpp",
- "stashdialog.h"
+ "stashdialog.h",
+ "stashdialog.ui",
]
Group {
prefix: "gitorious/"
files: [
- "gitorioushostwidget.ui",
- "gitoriousprojectwidget.ui",
- "gitoriousrepositorywizardpage.ui",
"gitorious.cpp",
"gitorious.h",
"gitoriousclonewizard.cpp",
"gitoriousclonewizard.h",
"gitorioushostwidget.cpp",
"gitorioushostwidget.h",
+ "gitorioushostwidget.ui",
"gitorioushostwizardpage.cpp",
"gitorioushostwizardpage.h",
"gitoriousprojectwidget.cpp",
"gitoriousprojectwidget.h",
+ "gitoriousprojectwidget.ui",
"gitoriousprojectwizardpage.cpp",
"gitoriousprojectwizardpage.h",
"gitoriousrepositorywizardpage.cpp",
- "gitoriousrepositorywizardpage.h"
+ "gitoriousrepositorywizardpage.h",
+ "gitoriousrepositorywizardpage.ui",
]
}
@@ -113,8 +107,7 @@ QtcPlugin {
"gerritparameters.cpp",
"gerritparameters.h",
"gerritplugin.cpp",
- "gerritplugin.h"
+ "gerritplugin.h",
]
}
}
-
diff --git a/src/plugins/git/gitclient.cpp b/src/plugins/git/gitclient.cpp
index 4952821ec0..b5546cb993 100644
--- a/src/plugins/git/gitclient.cpp
+++ b/src/plugins/git/gitclient.cpp
@@ -35,6 +35,7 @@
#include "gitplugin.h"
#include "gitsubmiteditor.h"
#include "gitversioncontrol.h"
+#include "mergetool.h"
#include <vcsbase/submitfilemodel.h>
@@ -51,6 +52,7 @@
#include <coreplugin/variablemanager.h>
#include <texteditor/itexteditor.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <utils/synchronousprocess.h>
@@ -66,6 +68,7 @@
#include <QTime>
#include <QFileInfo>
#include <QDir>
+#include <QHash>
#include <QSignalMapper>
#include <QComboBox>
@@ -390,11 +393,18 @@ QString GitClient::findRepositoryForDirectory(const QString &dir)
QString GitClient::findGitDirForRepository(const QString &repositoryDir)
{
+ static QHash<QString, QString> repoDirCache;
+ QString &res = repoDirCache[repositoryDir];
+ if (!res.isEmpty())
+ return res;
QByteArray outputText;
QStringList arguments;
arguments << QLatin1String("rev-parse") << QLatin1String("--git-dir");
fullySynchronousGit(repositoryDir, arguments, &outputText, 0, false);
- return QString::fromLocal8Bit(outputText.trimmed());
+ res = QString::fromLocal8Bit(outputText.trimmed());
+ if (!QDir(res).isAbsolute())
+ res.prepend(repositoryDir + QLatin1Char('/'));
+ return res;
}
VcsBase::VcsBaseEditorWidget *GitClient::findExistingVCSEditor(const char *registerDynamicProperty,
@@ -571,6 +581,13 @@ void GitClient::diffBranch(const QString &workingDirectory,
executeGit(workingDirectory, cmdArgs, editor);
}
+void GitClient::merge(const QString &workingDirectory, const QStringList &unmergedFileNames)
+{
+ MergeTool *mergeTool = new MergeTool(this);
+ if (!mergeTool->start(workingDirectory, unmergedFileNames))
+ delete mergeTool;
+}
+
void GitClient::status(const QString &workingDirectory)
{
// @TODO: Use "--no-color" once it is supported
@@ -761,59 +778,48 @@ void GitClient::blame(const QString &workingDirectory,
executeGit(workingDirectory, arguments, editor, false, VcsBase::Command::NoReport, lineNumber);
}
-void GitClient::checkoutBranch(const QString &workingDirectory, const QString &branch)
-{
- QStringList arguments(QLatin1String("checkout"));
- arguments << branch;
- VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
- connectRepositoryChanged(workingDirectory, cmd);
-}
-
-bool GitClient::synchronousCheckoutBranch(const QString &workingDirectory,
- const QString &branch,
+bool GitClient::synchronousCheckout(const QString &workingDirectory,
+ const QString &ref,
QString *errorMessage /* = 0 */)
{
QByteArray outputText;
QByteArray errorText;
QStringList arguments;
- arguments << QLatin1String("checkout") << branch;
+ arguments << QLatin1String("checkout") << ref;
const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
const QString output = commandOutputFromLocal8Bit(outputText);
outputWindow()->append(output);
if (!rc) {
const QString stdErr = commandOutputFromLocal8Bit(errorText);
//: Meaning of the arguments: %1: Branch, %2: Repository, %3: Error message
- const QString msg = tr("Cannot checkout \"%1\" of \"%2\": %3").arg(branch, workingDirectory, stdErr);
- if (errorMessage) {
+ const QString msg = tr("Cannot checkout \"%1\" of \"%2\": %3").arg(ref, workingDirectory, stdErr);
+ if (errorMessage)
*errorMessage = msg;
- } else {
+ else
outputWindow()->appendError(msg);
- }
return false;
}
return true;
}
-void GitClient::checkout(const QString &workingDirectory, const QString &fileName)
+void GitClient::hardReset(const QString &workingDirectory, const QString &commit)
{
- // Passing an empty argument as the file name is very dangereous, since this makes
- // git checkout apply to all files. Almost looks like a bug in git.
- if (fileName.isEmpty())
- return;
-
QStringList arguments;
- arguments << QLatin1String("checkout") << QLatin1String("HEAD") << QLatin1String("--")
- << fileName;
+ arguments << QLatin1String("reset") << QLatin1String("--hard");
+ if (!commit.isEmpty())
+ arguments << commit;
- executeGit(workingDirectory, arguments, 0, true);
+ VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
+ connectRepositoryChanged(workingDirectory, cmd);
}
-void GitClient::hardReset(const QString &workingDirectory, const QString &commit)
+void GitClient::softReset(const QString &workingDirectory, const QString &commit)
{
+ if (commit.isEmpty())
+ return;
+
QStringList arguments;
- arguments << QLatin1String("reset") << QLatin1String("--hard");
- if (!commit.isEmpty())
- arguments << commit;
+ arguments << QLatin1String("reset") << QLatin1String("--soft") << commit;
VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
connectRepositoryChanged(workingDirectory, cmd);
@@ -842,11 +848,10 @@ bool GitClient::synchronousLog(const QString &workingDirectory, const QStringLis
const QString errorMessage = tr("Cannot obtain log of \"%1\": %2").
arg(QDir::toNativeSeparators(workingDirectory),
commandOutputFromLocal8Bit(errorText));
- if (errorMessageIn) {
+ if (errorMessageIn)
*errorMessageIn = errorMessage;
- } else {
+ else
outputWindow()->appendError(errorMessage);
- }
}
return rc;
}
@@ -937,11 +942,10 @@ bool GitClient::synchronousReset(const QString &workingDirectory,
tr("Cannot reset \"%1\": %2").arg(QDir::toNativeSeparators(workingDirectory), stdErr) :
tr("Cannot reset %n file(s) in \"%1\": %2", 0, files.size()).
arg(QDir::toNativeSeparators(workingDirectory), stdErr);
- if (errorMessage) {
+ if (errorMessage)
*errorMessage = msg;
- } else {
+ else
outputWindow()->appendError(msg);
- }
return false;
}
return true;
@@ -993,11 +997,10 @@ bool GitClient::synchronousCheckoutFiles(const QString &workingDirectory,
//: %4: Error message
const QString msg = tr("Cannot checkout \"%1\" of %2 in \"%3\": %4").
arg(revision, fileArg, workingDirectory, commandOutputFromLocal8Bit(errorText));
- if (errorMessage) {
+ if (errorMessage)
*errorMessage = msg;
- } else {
+ else
outputWindow()->appendError(msg);
- }
return false;
}
return true;
@@ -1097,64 +1100,106 @@ static inline QString msgCannotDetermineBranch(const QString &workingDirectory,
return GitClient::tr("Cannot retrieve branch of \"%1\": %2").arg(QDir::toNativeSeparators(workingDirectory), why);
}
-// Retrieve head revision/branch
-bool GitClient::synchronousTopRevision(const QString &workingDirectory, QString *revision,
- QString *branch, QString *errorMessageIn)
+struct TopicData
+{
+ QDateTime timeStamp;
+ QString topic;
+};
+
+// Retrieve topic (branch, tag or HEAD hash)
+QString GitClient::synchronousTopic(const QString &workingDirectory)
+{
+ static QHash<QString, TopicData> topicCache;
+ QString gitDir = findGitDirForRepository(workingDirectory);
+ if (gitDir.isEmpty())
+ return QString();
+ TopicData &data = topicCache[gitDir];
+ QDateTime lastModified = QFileInfo(gitDir + QLatin1String("/HEAD")).lastModified();
+ if (lastModified == data.timeStamp)
+ return data.topic;
+ data.timeStamp = lastModified;
+ QByteArray outputTextData;
+ QStringList arguments;
+ arguments << QLatin1String("symbolic-ref") << QLatin1String("HEAD");
+ // First try to find branch
+ if (fullySynchronousGit(workingDirectory, arguments, &outputTextData, 0, false)) {
+ QString branch = commandOutputFromLocal8Bit(outputTextData.trimmed());
+
+ // Must strip the "refs/heads/" prefix manually since the --short switch
+ // of git symbolic-ref only got introduced with git 1.7.10, which is not
+ // available for all popular Linux distributions yet.
+ const QString refsHeadsPrefix = QLatin1String("refs/heads/");
+ if (branch.startsWith(refsHeadsPrefix))
+ branch.remove(0, refsHeadsPrefix.count());
+
+ return data.topic = branch;
+ }
+
+ // Detached HEAD, try a tag
+ arguments.clear();
+ arguments << QLatin1String("describe") << QLatin1String("--tags")
+ << QLatin1String("--exact-match") << QLatin1String("HEAD");
+ if (fullySynchronousGit(workingDirectory, arguments, &outputTextData, 0, false))
+ return data.topic = commandOutputFromLocal8Bit(outputTextData.trimmed());
+
+ // No tag
+ return data.topic = tr("Detached HEAD");
+}
+
+// Retrieve head revision
+QString GitClient::synchronousTopRevision(const QString &workingDirectory, QString *errorMessageIn)
{
QByteArray outputTextData;
QByteArray errorText;
QStringList arguments;
QString errorMessage;
- do {
- // get revision
- if (revision) {
- revision->clear();
- arguments << QLatin1String("log") << QLatin1String(noColorOption)
- << QLatin1String("--max-count=1") << QLatin1String("--pretty=format:%H");
- if (!fullySynchronousGit(workingDirectory, arguments, &outputTextData, &errorText)) {
- errorMessage = tr("Cannot retrieve top revision of \"%1\": %2").arg(QDir::toNativeSeparators(workingDirectory), commandOutputFromLocal8Bit(errorText));
- break;
- }
- *revision = commandOutputFromLocal8Bit(outputTextData);
- revision->remove(QLatin1Char('\n'));
- } // revision desired
- // get branch
- if (branch) {
- branch->clear();
- arguments.clear();
- arguments << QLatin1String("branch") << QLatin1String(noColorOption);
- if (!fullySynchronousGit(workingDirectory, arguments, &outputTextData, &errorText)) {
- errorMessage = msgCannotDetermineBranch(workingDirectory, commandOutputFromLocal8Bit(errorText));
- break;
- }
- /* parse output for current branch: \code
-* master
- branch2
-\endcode */
- const QString branchPrefix = QLatin1String("* ");
- foreach(const QString &line, commandOutputLinesFromLocal8Bit(outputTextData)) {
- if (line.startsWith(branchPrefix)) {
- *branch = line;
- branch->remove(0, branchPrefix.size());
- break;
- }
- }
- if (branch->isEmpty()) {
- errorMessage = msgCannotDetermineBranch(workingDirectory,
- QString::fromLatin1("Internal error: Failed to parse output: %1").arg(commandOutputFromLocal8Bit(outputTextData)));
- break;
- }
- } // branch
- } while (false);
- const bool failed = (revision && revision->isEmpty()) || (branch && branch->isEmpty());
- if (failed && !errorMessage.isEmpty()) {
- if (errorMessageIn) {
+ // get revision
+ arguments << QLatin1String("rev-parse") << QLatin1String("HEAD");
+ if (!fullySynchronousGit(workingDirectory, arguments, &outputTextData, &errorText, false)) {
+ errorMessage = tr("Cannot retrieve top revision of \"%1\": %2")
+ .arg(QDir::toNativeSeparators(workingDirectory), commandOutputFromLocal8Bit(errorText));
+ return QString();
+ }
+ QString revision = commandOutputFromLocal8Bit(outputTextData);
+ revision.remove(QLatin1Char('\n'));
+ if (revision.isEmpty() && !errorMessage.isEmpty()) {
+ if (errorMessageIn)
*errorMessageIn = errorMessage;
- } else {
+ else
outputWindow()->appendError(errorMessage);
+ }
+ return revision;
+}
+
+void GitClient::synchronousTagsForCommit(const QString &workingDirectory, const QString &revision,
+ QByteArray &precedes, QByteArray &follows)
+{
+ QStringList arguments;
+ QByteArray parents;
+ arguments << QLatin1String("describe") << QLatin1String("--contains") << revision;
+ fullySynchronousGit(workingDirectory, arguments, &precedes, 0, false);
+ int tilde = precedes.indexOf('~');
+ if (tilde != -1)
+ precedes.truncate(tilde);
+ else
+ precedes = precedes.trimmed();
+
+ arguments.clear();
+ arguments << QLatin1String("log") << QLatin1String("-n1") << QLatin1String("--pretty=format:%P") << revision;
+ fullySynchronousGit(workingDirectory, arguments, &parents, 0, false);
+ foreach (const QByteArray &p, parents.split(' ')) {
+ QByteArray pf;
+ arguments.clear();
+ arguments << QLatin1String("describe") << QLatin1String("--tags")
+ << QLatin1String("--abbrev=0") << QLatin1String(p);
+ fullySynchronousGit(workingDirectory, arguments, &pf, 0, false);
+ pf.truncate(pf.lastIndexOf('\n'));
+ if (!pf.isEmpty()) {
+ if (!follows.isEmpty())
+ follows += ", ";
+ follows += pf;
}
}
- return !failed;
}
// Format an entry in a one-liner for selection list using git log.
@@ -1209,24 +1254,24 @@ QString GitClient::synchronousStash(const QString &workingDirectory, const QStri
bool success = false;
// Check for changes and stash
QString errorMessage;
- switch (gitStatus(workingDirectory, false, 0, &errorMessage)) {
+ switch (gitStatus(workingDirectory, StatusMode(NoUntracked | NoSubmodules), 0, &errorMessage)) {
case StatusChanged: {
- message = creatorStashMessage(messageKeyword);
- do {
- if ((flags & StashPromptDescription)) {
- if (!inputText(Core::ICore::mainWindow(),
- tr("Stash Description"), tr("Description:"), &message))
- break;
- }
- if (!executeSynchronousStash(workingDirectory, message))
- break;
- if ((flags & StashImmediateRestore)
- && !synchronousStashRestore(workingDirectory, QLatin1String("stash@{0}")))
+ message = creatorStashMessage(messageKeyword);
+ do {
+ if ((flags & StashPromptDescription)) {
+ if (!inputText(Core::ICore::mainWindow(),
+ tr("Stash Description"), tr("Description:"), &message))
break;
- success = true;
- } while (false);
- }
+ }
+ if (!executeSynchronousStash(workingDirectory, message))
+ break;
+ if ((flags & StashImmediateRestore)
+ && !synchronousStashRestore(workingDirectory, QLatin1String("stash@{0}")))
+ break;
+ success = true;
+ } while (false);
break;
+ }
case StatusUnchanged:
if (unchanged)
*unchanged = true;
@@ -1257,11 +1302,10 @@ bool GitClient::executeSynchronousStash(const QString &workingDirectory,
const QString msg = tr("Cannot stash in \"%1\": %2").
arg(QDir::toNativeSeparators(workingDirectory),
commandOutputFromLocal8Bit(errorText));
- if (errorMessage) {
+ if (errorMessage)
*errorMessage = msg;
- } else {
- outputWindow()->append(msg);
- }
+ else
+ outputWindow()->appendError(msg);
return false;
}
return true;
@@ -1289,11 +1333,10 @@ bool GitClient::stashNameFromMessage(const QString &workingDirectory,
}
//: Look-up of a stash via its descriptive message failed.
const QString msg = tr("Cannot resolve stash message \"%1\" in \"%2\".").arg(message, workingDirectory);
- if (errorMessage) {
+ if (errorMessage)
*errorMessage = msg;
- } else {
+ else
outputWindow()->append(msg);
- }
return false;
}
@@ -1304,11 +1347,11 @@ bool GitClient::synchronousBranchCmd(const QString &workingDirectory, QStringLis
QByteArray outputText;
QByteArray errorText;
const bool rc = fullySynchronousGit(workingDirectory, branchArgs, &outputText, &errorText);
+ *output = commandOutputFromLocal8Bit(outputText);
if (!rc) {
*errorMessage = tr("Cannot run \"git branch\" in \"%1\": %2").arg(QDir::toNativeSeparators(workingDirectory), commandOutputFromLocal8Bit(errorText));
return false;
}
- *output = commandOutputFromLocal8Bit(outputText);
return true;
}
@@ -1362,7 +1405,7 @@ bool GitClient::cleanList(const QString &workingDirectory, const QString &flag,
}
// Filter files that git would remove
const QString prefix = QLatin1String("Would remove ");
- foreach(const QString &line, commandOutputLinesFromLocal8Bit(outputText))
+ foreach (const QString &line, commandOutputLinesFromLocal8Bit(outputText))
if (line.startsWith(prefix))
files->push_back(line.mid(prefix.size()));
return true;
@@ -1439,18 +1482,17 @@ VcsBase::Command *GitClient::executeGit(const QString &workingDirectory,
QProcessEnvironment GitClient::processEnvironment() const
{
-
QProcessEnvironment environment = QProcessEnvironment::systemEnvironment();
QString gitPath = settings()->stringValue(GitSettings::pathKey);
if (!gitPath.isEmpty()) {
- gitPath += Utils::SynchronousProcess::pathSeparator();
+ gitPath += Utils::HostOsInfo::pathListSeparator();
gitPath += environment.value(QLatin1String("PATH"));
environment.insert(QLatin1String("PATH"), gitPath);
}
-#ifdef Q_OS_WIN
- if (settings()->boolValue(GitSettings::winSetHomeEnvironmentKey))
+ if (Utils::HostOsInfo::isWindowsHost()
+ && settings()->boolValue(GitSettings::winSetHomeEnvironmentKey)) {
environment.insert(QLatin1String("HOME"), QDir::toNativeSeparators(QDir::homePath()));
-#endif // Q_OS_WIN
+ }
// Set up SSH and C locale (required by git using perl).
VcsBase::VcsBasePlugin::setProcessEnvironment(&environment, false);
return environment;
@@ -1503,43 +1545,42 @@ static inline int askWithDetailedText(QWidget *parent,
return msgBox.exec();
}
-// Convenience that pops up an msg box.
-GitClient::StashResult GitClient::ensureStash(const QString &workingDirectory)
-{
- QString errorMessage;
- const StashResult sr = ensureStash(workingDirectory, &errorMessage);
- if (sr == StashFailed)
- outputWindow()->appendError(errorMessage);
- return sr;
-}
-
// Ensure that changed files are stashed before a pull or similar
-GitClient::StashResult GitClient::ensureStash(const QString &workingDirectory, QString *errorMessage)
+GitClient::StashResult GitClient::ensureStash(const QString &workingDirectory,
+ const QString &keyword,
+ bool askUser,
+ QString *message,
+ QString *errorMessage)
{
QString statusOutput;
- switch (gitStatus(workingDirectory, false, &statusOutput, errorMessage)) {
- case StatusChanged:
+ switch (gitStatus(workingDirectory, StatusMode(NoUntracked | NoSubmodules),
+ &statusOutput, errorMessage)) {
+ case StatusChanged:
break;
- case StatusUnchanged:
+ case StatusUnchanged:
return StashUnchanged;
- case StatusFailed:
+ case StatusFailed:
return StashFailed;
}
- const int answer = askWithDetailedText(Core::ICore::mainWindow(), tr("Changes"),
- tr("Would you like to stash your changes?"),
- statusOutput, QMessageBox::Yes, QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
- switch (answer) {
+ if (askUser) {
+ const int answer = askWithDetailedText(Core::ICore::mainWindow(), tr("Changes"),
+ tr("Would you like to stash your changes?"),
+ statusOutput, QMessageBox::Yes, QMessageBox::Yes|QMessageBox::No|QMessageBox::Cancel);
+ switch (answer) {
case QMessageBox::Cancel:
return StashCanceled;
- case QMessageBox::Yes:
- if (!executeSynchronousStash(workingDirectory, creatorStashMessage(QLatin1String("push")), errorMessage))
- return StashFailed;
- break;
case QMessageBox::No: // At your own risk, so.
return NotStashed;
+ default:
+ break;
}
-
+ }
+ const QString stashMessage = creatorStashMessage(keyword);
+ if (!executeSynchronousStash(workingDirectory, stashMessage, errorMessage))
+ return StashFailed;
+ if (message)
+ *message = stashMessage;
return Stashed;
}
@@ -1558,7 +1599,7 @@ static inline QString trimFileSpecification(QString fileSpec)
return fileSpec;
}
-GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, bool untracked,
+GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, StatusMode mode,
QString *output, QString *errorMessage)
{
// Run 'status'. Note that git returns exitcode 1 if there are no added files.
@@ -1566,8 +1607,12 @@ GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, bo
QByteArray errorText;
QStringList statusArgs(QLatin1String("status"));
- if (untracked)
- statusArgs << QLatin1String("-u");
+ if (mode & NoUntracked)
+ statusArgs << QLatin1String("--untracked-files=no");
+ else
+ statusArgs << QLatin1String("--untracked-files=normal");
+ if (mode & NoSubmodules)
+ statusArgs << QLatin1String("--ignore-submodules=all");
statusArgs << QLatin1String("-s") << QLatin1String("-b");
const bool statusRc = fullySynchronousGit(workingDirectory, statusArgs, &outputText, &errorText);
@@ -1588,7 +1633,7 @@ GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, bo
// Unchanged (output text depending on whether -u was passed)
QList<QByteArray> lines = outputText.split('\n');
foreach (const QByteArray &line, lines)
- if (!line.isEmpty() && !line.startsWith('#') && !line.startsWith('?'))
+ if (!line.isEmpty() && !line.startsWith('#'))
return StatusChanged;
return StatusUnchanged;
}
@@ -1596,8 +1641,10 @@ GitClient::StatusResult GitClient::gitStatus(const QString &workingDirectory, bo
// Quietly retrieve branch list of remote repository URL
//
// The branch HEAD is pointing to is always returned first.
-QStringList GitClient::synchronousRepositoryBranches(const QString &repositoryURL)
+QStringList GitClient::synchronousRepositoryBranches(const QString &repositoryURL, bool *isDetached)
{
+ if (isDetached)
+ *isDetached = true;
QStringList arguments(QLatin1String("ls-remote"));
arguments << repositoryURL << QLatin1String("HEAD") << QLatin1String("refs/heads/*");
const unsigned flags =
@@ -1606,43 +1653,44 @@ QStringList GitClient::synchronousRepositoryBranches(const QString &repositoryUR
VcsBase::VcsBasePlugin::SuppressFailMessageInLogWindow;
const Utils::SynchronousProcessResponse resp = synchronousGit(QString(), arguments, flags);
QStringList branches;
- branches << QLatin1String("<detached HEAD>");
+ branches << tr("<Detached HEAD>");
QString headSha;
- if (resp.result == Utils::SynchronousProcessResponse::Finished) {
- // split "82bfad2f51d34e98b18982211c82220b8db049b<tab>refs/heads/master"
- foreach(const QString &line, resp.stdOut.split(QLatin1Char('\n'))) {
- if (line.endsWith(QLatin1String("\tHEAD"))) {
- QTC_CHECK(headSha.isNull());
- headSha = line.left(line.indexOf(QLatin1Char('\t')));
- continue;
- }
+ // split "82bfad2f51d34e98b18982211c82220b8db049b<tab>refs/heads/master"
+ foreach (const QString &line, resp.stdOut.split(QLatin1Char('\n'))) {
+ if (line.endsWith(QLatin1String("\tHEAD"))) {
+ QTC_CHECK(headSha.isNull());
+ headSha = line.left(line.indexOf(QLatin1Char('\t')));
+ continue;
+ }
- const QString pattern = QLatin1String("\trefs/heads/");
- const int pos = line.lastIndexOf(pattern);
- if (pos != -1) {
- const QString branchName = line.mid(pos + pattern.count());
- if (line.startsWith(headSha))
- branches[0] = branchName;
- else
- branches.push_back(branchName);
+ const QString pattern = QLatin1String("\trefs/heads/");
+ const int pos = line.lastIndexOf(pattern);
+ if (pos != -1) {
+ const QString branchName = line.mid(pos + pattern.count());
+ if (line.startsWith(headSha)) {
+ branches[0] = branchName;
+ if (isDetached)
+ *isDetached = false;
+ } else {
+ branches.push_back(branchName);
}
}
}
return branches;
}
-void GitClient::launchGitK(const QString &workingDirectory)
+void GitClient::launchGitK(const QString &workingDirectory, const QString &fileName)
{
const QFileInfo binaryInfo(gitBinaryPath());
QDir foundBinDir(binaryInfo.dir());
const bool foundBinDirIsCmdDir = foundBinDir.dirName() == QLatin1String("cmd");
QProcessEnvironment env = processEnvironment();
- if (tryLauchingGitK(env, workingDirectory, foundBinDir.path(), foundBinDirIsCmdDir))
+ if (tryLauchingGitK(env, workingDirectory, fileName, foundBinDir.path(), foundBinDirIsCmdDir))
return;
if (!foundBinDirIsCmdDir)
return;
foundBinDir.cdUp();
- tryLauchingGitK(env, workingDirectory, foundBinDir.path() + QLatin1String("/bin"), false);
+ tryLauchingGitK(env, workingDirectory, fileName, foundBinDir.path() + QLatin1String("/bin"), false);
}
void GitClient::launchRepositoryBrowser(const QString &workingDirectory)
@@ -1654,22 +1702,26 @@ void GitClient::launchRepositoryBrowser(const QString &workingDirectory)
bool GitClient::tryLauchingGitK(const QProcessEnvironment &env,
const QString &workingDirectory,
+ const QString &fileName,
const QString &gitBinDirectory,
bool silent)
{
-#ifdef Q_OS_WIN
- // Launch 'wish' shell from git binary directory with the gitk located there
- const QString binary = gitBinDirectory + QLatin1String("/wish");
- QStringList arguments(gitBinDirectory + QLatin1String("/gitk"));
-#else
- // Simple: Run gitk from binary path
- const QString binary = gitBinDirectory + QLatin1String("/gitk");
+ QString binary = gitBinDirectory + QLatin1String("/gitk");
QStringList arguments;
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ // If git/bin is in path, use 'wish' shell to run. Otherwise (git/cmd), directly run gitk
+ QString wish = gitBinDirectory + QLatin1String("/wish");
+ if (QFileInfo(wish + QLatin1String(".exe")).exists()) {
+ arguments << binary;
+ binary = wish;
+ }
+ }
VcsBase::VcsBaseOutputWindow *outwin = VcsBase::VcsBaseOutputWindow::instance();
const QString gitkOpts = settings()->stringValue(GitSettings::gitkOptionsKey);
if (!gitkOpts.isEmpty())
arguments.append(Utils::QtcProcess::splitArgs(gitkOpts));
+ if (!fileName.isEmpty())
+ arguments << QLatin1String("--") << fileName;
outwin->appendCommand(workingDirectory, binary, arguments);
// This should always use QProcess::startDetached (as not to kill
// the child), but that does not have an environment parameter.
@@ -1725,18 +1777,9 @@ bool GitClient::getCommitData(const QString &workingDirectory,
return false;
}
- // Read description
- const QString descriptionFile = QDir(gitDir).absoluteFilePath(QLatin1String("description"));
- if (QFileInfo(descriptionFile).isFile()) {
- Utils::FileReader reader;
- if (!reader.fetch(descriptionFile, QIODevice::Text, errorMessage))
- return false;
- commitData->panelInfo.description = commandOutputFromLocal8Bit(reader.data()).trimmed();
- }
-
// Run status. Note that it has exitcode 1 if there are no added files.
QString output;
- const StatusResult status = gitStatus(repoDirectory, true, &output, errorMessage);
+ const StatusResult status = gitStatus(repoDirectory, ShowAll, &output, errorMessage);
switch (status) {
case StatusChanged:
break;
@@ -1762,13 +1805,13 @@ bool GitClient::getCommitData(const QString &workingDirectory,
}
// Filter out untracked files that are not part of the project
- QStringList untrackedFiles = commitData->filterFiles(CommitData::UntrackedFile);
+ QStringList untrackedFiles = commitData->filterFiles(UntrackedFile);
VcsBase::VcsBaseSubmitEditor::filterUntrackedFilesOfProject(repoDirectory, &untrackedFiles);
QList<CommitData::StateFilePair> filteredFiles;
QList<CommitData::StateFilePair>::const_iterator it = commitData->files.constBegin();
for ( ; it != commitData->files.constEnd(); ++it) {
- if (it->first == CommitData::UntrackedFile && !untrackedFiles.contains(it->second))
+ if (it->first == UntrackedFile && !untrackedFiles.contains(it->second))
continue;
filteredFiles.append(*it);
}
@@ -1848,47 +1891,41 @@ bool GitClient::addAndCommit(const QString &repositoryDirectory,
int commitCount = 0;
for (int i = 0; i < model->rowCount(); ++i) {
- const CommitData::FileState state = static_cast<CommitData::FileState>(model->extraData(i).toInt());
+ const FileStates state = static_cast<FileStates>(model->extraData(i).toInt());
QString file = model->file(i);
const bool checked = model->checked(i);
if (checked)
++commitCount;
- if (state == CommitData::UntrackedFile && checked)
+ if (state == UntrackedFile && checked)
filesToAdd.append(file);
- if (state == CommitData::ModifiedStagedFile && !checked) {
- filesToReset.append(file);
- } else if (state == CommitData::AddedStagedFile && !checked) {
- filesToReset.append(file);
- } else if (state == CommitData::DeletedStagedFile && !checked) {
- filesToReset.append(file);
- } else if (state == CommitData::RenamedStagedFile && !checked) {
- const int pos = file.indexOf(QLatin1String(" -> "));
- const QString newFile = file.mid(pos + 4);
- filesToReset.append(newFile);
- } else if (state == CommitData::CopiedStagedFile && !checked) {
- const QString newFile = file.mid(file.indexOf(renameSeparator) + renameSeparator.count());
- filesToReset.append(newFile);
- } else if (state == CommitData::UpdatedStagedFile && !checked) {
- QTC_ASSERT(false, continue); // There should not be updated files when commiting!
+ if ((state & StagedFile) && !checked) {
+ if (state & (AddedFile | DeletedFile)) {
+ filesToReset.append(file);
+ } else if (state & (RenamedFile | CopiedFile)) {
+ const QString newFile = file.mid(file.indexOf(renameSeparator) + renameSeparator.count());
+ filesToReset.append(newFile);
+ }
+ } else if (state & UnmergedFile && checked) {
+ QTC_ASSERT(false, continue); // There should not be unmerged files when commiting!
}
- if (state == CommitData::ModifiedFile && checked) {
+ if (state == ModifiedFile && checked) {
filesToReset.removeAll(file);
filesToAdd.append(file);
- } else if (state == CommitData::AddedFile && checked) {
+ } else if (state == AddedFile && checked) {
QTC_ASSERT(false, continue); // these should be untracked!
- } else if (state == CommitData::DeletedFile && checked) {
+ } else if (state == DeletedFile && checked) {
filesToReset.removeAll(file);
filesToRemove.append(file);
- } else if (state == CommitData::RenamedFile && checked) {
+ } else if (state == RenamedFile && checked) {
QTC_ASSERT(false, continue); // git mv directly stages.
- } else if (state == CommitData::CopiedFile && checked) {
+ } else if (state == CopiedFile && checked) {
QTC_ASSERT(false, continue); // only is noticed after adding a new file to the index
- } else if (state == CommitData::UpdatedFile && checked) {
- QTC_ASSERT(false, continue); // There should not be updated files when commiting!
+ } else if (state == UnmergedFile && checked) {
+ QTC_ASSERT(false, continue); // There should not be unmerged files when commiting!
}
}
@@ -1953,7 +1990,7 @@ GitClient::RevertResult GitClient::revertI(QStringList files,
// Check for changes
QString output;
- switch (gitStatus(repoDirectory, false, &output, errorMessage)) {
+ switch (gitStatus(repoDirectory, StatusMode(NoUntracked | NoSubmodules), &output, errorMessage)) {
case StatusChanged:
break;
case StatusUnchanged:
@@ -1977,8 +2014,8 @@ GitClient::RevertResult GitClient::revertI(QStringList files,
}
// From the status output, determine all modified [un]staged files.
- const QStringList allStagedFiles = data.filterFiles(CommitData::ModifiedStagedFile);
- const QStringList allUnstagedFiles = data.filterFiles(CommitData::ModifiedFile);
+ const QStringList allStagedFiles = data.filterFiles(StagedFile | ModifiedFile);
+ const QStringList allUnstagedFiles = data.filterFiles(ModifiedFile);
// Unless a directory was passed, filter all modified files for the
// argument file list.
QStringList stagedFiles = allStagedFiles;
@@ -2046,37 +2083,53 @@ bool GitClient::synchronousFetch(const QString &workingDirectory, const QString
return resp.result == Utils::SynchronousProcessResponse::Finished;
}
-bool GitClient::synchronousPull(const QString &workingDirectory)
-{
- return synchronousPull(workingDirectory, settings()->boolValue(GitSettings::pullRebaseKey));
-}
-
-bool GitClient::synchronousPull(const QString &workingDirectory, bool rebase)
+bool GitClient::executeAndHandleConflicts(const QString &workingDirectory, const QStringList &arguments, const QString &abortCommand)
{
- QStringList arguments(QLatin1String("pull"));
- if (rebase)
- arguments << QLatin1String("--rebase");
// Disable UNIX terminals to suppress SSH prompting.
const unsigned flags = VcsBase::VcsBasePlugin::SshPasswordPrompt|VcsBase::VcsBasePlugin::ShowStdOutInLogWindow;
const Utils::SynchronousProcessResponse resp = synchronousGit(workingDirectory, arguments, flags);
// Notify about changed files or abort the rebase.
const bool ok = resp.result == Utils::SynchronousProcessResponse::Finished;
- if (ok) {
+ if (ok)
GitPlugin::instance()->gitVersionControl()->emitRepositoryChanged(workingDirectory);
+ else if (resp.stdOut.contains(QLatin1String("CONFLICT"))
+ || resp.stdErr.contains(QLatin1String("conflict")))
+ handleMergeConflicts(workingDirectory, abortCommand);
+ return ok;
+}
+
+bool GitClient::synchronousPull(const QString &workingDirectory, bool rebase)
+{
+ QString abortCommand;
+ QStringList arguments(QLatin1String("pull"));
+ if (rebase) {
+ arguments << QLatin1String("--rebase");
+ abortCommand = QLatin1String("rebase");
} else {
- if (rebase)
- syncAbortPullRebase(workingDirectory);
+ abortCommand = QLatin1String("merge");
}
- return ok;
+
+ return executeAndHandleConflicts(workingDirectory, arguments, abortCommand);
+}
+
+bool GitClient::synchronousCommandContinue(const QString &workingDirectory, const QString &command)
+{
+ QStringList arguments;
+ arguments << command << QLatin1String("--continue");
+ return executeAndHandleConflicts(workingDirectory, arguments, command);
}
-void GitClient::syncAbortPullRebase(const QString &workingDir)
+void GitClient::synchronousAbortCommand(const QString &workingDir, const QString &abortCommand)
{
- // Abort rebase to clean if something goes wrong
+ // Abort to clean if something goes wrong
+ if (abortCommand.isEmpty()) {
+ // no abort command - checkout index to clean working copy.
+ synchronousCheckoutFiles(findRepositoryForDirectory(workingDir), QStringList(), QString(), 0, false);
+ return;
+ }
VcsBase::VcsBaseOutputWindow *outwin = VcsBase::VcsBaseOutputWindow::instance();
- outwin->appendError(tr("The command 'git pull --rebase' failed, aborting rebase."));
QStringList arguments;
- arguments << QLatin1String("rebase") << QLatin1String("--abort");
+ arguments << abortCommand << QLatin1String("--abort");
QByteArray stdOut;
QByteArray stdErr;
const bool rc = fullySynchronousGit(workingDir, arguments, &stdOut, &stdErr, true);
@@ -2085,6 +2138,23 @@ void GitClient::syncAbortPullRebase(const QString &workingDir)
outwin->appendError(commandOutputFromLocal8Bit(stdErr));
}
+void GitClient::handleMergeConflicts(const QString &workingDir, const QString &abortCommand)
+{
+ QMessageBox mergeOrAbort(QMessageBox::Question, tr("Conflicts detected"),
+ tr("Conflicts detected"), QMessageBox::Ignore | QMessageBox::Abort);
+ mergeOrAbort.addButton(tr("Run Merge Tool"), QMessageBox::ActionRole);
+ switch (mergeOrAbort.exec()) {
+ case QMessageBox::Abort: {
+ synchronousAbortCommand(workingDir, abortCommand);
+ break;
+ }
+ case QMessageBox::Ignore:
+ break;
+ default: // Merge
+ merge(workingDir);
+ }
+}
+
// Subversion: git svn
void GitClient::synchronousSubversionFetch(const QString &workingDirectory)
{
@@ -2130,27 +2200,75 @@ bool GitClient::synchronousPush(const QString &workingDirectory, const QString &
return resp.result == Utils::SynchronousProcessResponse::Finished;
}
+bool GitClient::synchronousMerge(const QString &workingDirectory, const QString &branch)
+{
+ QString command = QLatin1String("merge");
+ QStringList arguments;
+
+ arguments << command << branch;
+ return executeAndHandleConflicts(workingDirectory, arguments, command);
+}
+
+bool GitClient::synchronousRebase(const QString &workingDirectory, const QString &baseBranch,
+ const QString &topicBranch)
+{
+ QString command = QLatin1String("rebase");
+ QStringList arguments;
+
+ arguments << command << baseBranch;
+ if (!topicBranch.isEmpty())
+ arguments << topicBranch;
+
+ return executeAndHandleConflicts(workingDirectory, arguments, command);
+}
+
+bool GitClient::revertCommit(const QString &workingDirectory, const QString &commit)
+{
+ QStringList arguments;
+ QString command = QLatin1String("revert");
+ arguments << command << QLatin1String("--no-edit") << commit;
+
+ return executeAndHandleConflicts(workingDirectory, arguments, command);
+}
+
+bool GitClient::cherryPickCommit(const QString &workingDirectory, const QString &commit)
+{
+ QStringList arguments;
+ QString command = QLatin1String("cherry-pick");
+ arguments << command << commit;
+
+ return executeAndHandleConflicts(workingDirectory, arguments, command);
+}
+
QString GitClient::msgNoChangedFiles()
{
return tr("There are no modified files.");
}
-void GitClient::stashPop(const QString &workingDirectory)
+void GitClient::stashPop(const QString &workingDirectory, const QString &stash)
{
QStringList arguments(QLatin1String("stash"));
arguments << QLatin1String("pop");
+ if (!stash.isEmpty())
+ arguments << stash;
VcsBase::Command *cmd = executeGit(workingDirectory, arguments, 0, true);
connectRepositoryChanged(workingDirectory, cmd);
}
+void GitClient::stashPop(const QString &workingDirectory)
+{
+ stashPop(workingDirectory, QString());
+}
+
bool GitClient::synchronousStashRestore(const QString &workingDirectory,
const QString &stash,
+ bool pop,
const QString &branch /* = QString()*/,
QString *errorMessage)
{
QStringList arguments(QLatin1String("stash"));
if (branch.isEmpty())
- arguments << QLatin1String("apply") << stash;
+ arguments << QLatin1String(pop ? "pop" : "apply") << stash;
else
arguments << QLatin1String("branch") << branch << stash;
QByteArray outputText;
@@ -2182,11 +2300,10 @@ bool GitClient::synchronousStashRemove(const QString &workingDirectory,
QString *errorMessage /* = 0 */)
{
QStringList arguments(QLatin1String("stash"));
- if (stash.isEmpty()) {
+ if (stash.isEmpty())
arguments << QLatin1String("clear");
- } else {
+ else
arguments << QLatin1String("drop") << stash;
- }
QByteArray outputText;
QByteArray errorText;
const bool rc = fullySynchronousGit(workingDirectory, arguments, &outputText, &errorText);
@@ -2238,15 +2355,14 @@ bool GitClient::synchronousStashList(const QString &workingDirectory,
const QString msg = tr("Cannot retrieve stash list of \"%1\": %2").
arg(QDir::toNativeSeparators(workingDirectory),
commandOutputFromLocal8Bit(errorText));
- if (errorMessage) {
+ if (errorMessage)
*errorMessage = msg;
- } else {
+ else
outputWindow()->append(msg);
- }
return false;
}
Stash stash;
- foreach(const QString &line, commandOutputLinesFromLocal8Bit(outputText))
+ foreach (const QString &line, commandOutputLinesFromLocal8Bit(outputText))
if (stash.parseStashLine(line))
stashes->push_back(stash);
return true;
@@ -2392,6 +2508,41 @@ unsigned GitClient::synchronousGitVersion(QString *errorMessage) const
return version(major, minor, patch);
}
+GitClient::StashGuard::StashGuard(const QString &workingDirectory, const QString &keyword, bool askUser) :
+ pop(true),
+ workingDir(workingDirectory)
+{
+ client = GitPlugin::instance()->gitClient();
+ QString errorMessage;
+ stashResult = client->ensureStash(workingDir, keyword, askUser, &message, &errorMessage);
+ if (stashResult == GitClient::StashFailed)
+ VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage);
+}
+
+GitClient::StashGuard::~StashGuard()
+{
+ if (pop && stashResult == GitClient::Stashed)
+ client->stashPop(workingDir, message);
+}
+
+void GitClient::StashGuard::preventPop()
+{
+ pop = false;
+}
+
+bool GitClient::StashGuard::stashingFailed(bool includeNotStashed) const
+{
+ switch (stashResult) {
+ case GitClient::StashCanceled:
+ case GitClient::StashFailed:
+ return true;
+ case GitClient::NotStashed:
+ return includeNotStashed;
+ default:
+ return false;
+ }
+}
+
} // namespace Internal
} // namespace Git
diff --git a/src/plugins/git/gitclient.h b/src/plugins/git/gitclient.h
index c60624e1f5..220b1c3d3c 100644
--- a/src/plugins/git/gitclient.h
+++ b/src/plugins/git/gitclient.h
@@ -70,11 +70,39 @@ class CommitData;
struct GitSubmitEditorPanelData;
class Stash;
+enum StatusMode
+{
+ ShowAll = 0,
+ NoUntracked = 1,
+ NoSubmodules = 2
+};
+
class GitClient : public QObject
{
Q_OBJECT
public:
+ enum StashResult { StashUnchanged, StashCanceled, StashFailed,
+ Stashed, NotStashed /* User did not want it */ };
+
+ class StashGuard
+ {
+ public:
+ StashGuard(const QString &workingDirectory, const QString &keyword, bool askUser = true);
+ ~StashGuard();
+
+ void preventPop();
+ bool stashingFailed(bool includeNotStashed) const;
+ StashResult result() const { return stashResult; }
+
+ private:
+ bool pop;
+ StashResult stashResult;
+ QString message;
+ QString workingDir;
+ GitClient *client;
+ };
+
static const char *stashNamePrefix;
explicit GitClient(GitSettings *settings);
@@ -92,6 +120,7 @@ public:
void diffBranch(const QString &workingDirectory,
const QStringList &diffArgs,
const QString &branchName);
+ void merge(const QString &workingDirectory, const QStringList &unmergedFileNames = QStringList());
void status(const QString &workingDirectory);
void graphLog(const QString &workingDirectory) { graphLog(workingDirectory, QString()); }
@@ -100,9 +129,8 @@ public:
bool enableAnnotationContextMenu = false, const QStringList &args = QStringList());
void blame(const QString &workingDirectory, const QStringList &args, const QString &fileName,
const QString &revision = QString(), int lineNumber = -1);
- void checkout(const QString &workingDirectory, const QString &file);
- void checkoutBranch(const QString &workingDirectory, const QString &branch);
void hardReset(const QString &workingDirectory, const QString &commit = QString());
+ void softReset(const QString &workingDirectory, const QString &commit);
void addFile(const QString &workingDirectory, const QString &fileName);
bool synchronousLog(const QString &workingDirectory,
const QStringList &arguments,
@@ -128,7 +156,7 @@ public:
QString revision = QString(), QString *errorMessage = 0,
bool revertStaging = true);
// Checkout branch
- bool synchronousCheckoutBranch(const QString &workingDirectory, const QString &branch, QString *errorMessage = 0);
+ bool synchronousCheckout(const QString &workingDirectory, const QString &ref, QString *errorMessage = 0);
// Do a stash and return identier.
enum { StashPromptDescription = 0x1, StashImmediateRestore = 0x2, StashIgnoreUnchanged = 0x4 };
@@ -141,6 +169,7 @@ public:
QString *errorMessage = 0);
bool synchronousStashRestore(const QString &workingDirectory,
const QString &stash,
+ bool pop = false,
const QString &branch = QString(),
QString *errorMessage = 0);
bool synchronousStashRemove(const QString &workingDirectory,
@@ -160,20 +189,30 @@ public:
QString synchronousShortDescription(const QString &workingDirectory, const QString &revision);
QString synchronousShortDescription(const QString &workingDirectory, const QString &revision,
const QString &format);
- bool synchronousTopRevision(const QString &workingDirectory, QString *revision = 0,
- QString *branch = 0, QString *errorMessage = 0);
+ QString synchronousTopic(const QString &workingDirectory);
+ QString synchronousTopRevision(const QString &workingDirectory, QString *errorMessage = 0);
+ void synchronousTagsForCommit(const QString &workingDirectory, const QString &revision,
+ QByteArray &precedes, QByteArray &follows);
bool cloneRepository(const QString &directory, const QByteArray &url);
QString vcsGetRepositoryURL(const QString &directory);
bool synchronousFetch(const QString &workingDirectory, const QString &remote);
- bool synchronousPull(const QString &workingDirectory);
bool synchronousPull(const QString &workingDirectory, bool rebase);
+ bool synchronousCommandContinue(const QString &workingDirectory, const QString &command);
bool synchronousPush(const QString &workingDirectory, const QString &remote = QString());
+ bool synchronousMerge(const QString &workingDirectory, const QString &branch);
+ bool synchronousRebase(const QString &workingDirectory,
+ const QString &baseBranch,
+ const QString &topicBranch = QString());
+ bool revertCommit(const QString &workingDirectory, const QString &commit);
+ bool cherryPickCommit(const QString &workingDirectory, const QString &commit);
+ void synchronousAbortCommand(const QString &workingDir, const QString &abortCommand);
// git svn support (asynchronous).
void synchronousSubversionFetch(const QString &workingDirectory);
void subversionLog(const QString &workingDirectory);
+ void stashPop(const QString &workingDirectory, const QString &stash);
void stashPop(const QString &workingDirectory);
void revert(const QStringList &files, bool revertStaging);
void branchList(const QString &workingDirectory);
@@ -190,10 +229,8 @@ public:
QString readConfigValue(const QString &workingDirectory, const QString &configVar) const;
- enum StashResult { StashUnchanged, StashCanceled, StashFailed,
- Stashed, NotStashed /* User did not want it */ };
- StashResult ensureStash(const QString &workingDirectory, QString *errorMessage);
- StashResult ensureStash(const QString &workingDirectory);
+ StashResult ensureStash(const QString &workingDirectory, const QString &keyword, bool askUser,
+ QString *message, QString *errorMessage = 0);
bool getCommitData(const QString &workingDirectory, bool amend,
QString *commitTemplate, CommitData *commitData,
@@ -207,14 +244,16 @@ public:
enum StatusResult { StatusChanged, StatusUnchanged, StatusFailed };
StatusResult gitStatus(const QString &workingDirectory,
- bool untracked = false,
+ StatusMode mode,
QString *output = 0,
QString *errorMessage = 0);
- void launchGitK(const QString &workingDirectory);
+ void launchGitK(const QString &workingDirectory, const QString &fileName);
+ void launchGitK(const QString &workingDirectory) { launchGitK(workingDirectory, QString()); }
+
void launchRepositoryBrowser(const QString &workingDirectory);
- QStringList synchronousRepositoryBranches(const QString &repositoryURL);
+ QStringList synchronousRepositoryBranches(const QString &repositoryURL, bool *isDetached = 0);
GitSettings *settings() const;
@@ -266,7 +305,7 @@ private:
bool fullySynchronousGit(const QString &workingDirectory,
const QStringList &arguments,
QByteArray* outputText,
- QByteArray* errorText,
+ QByteArray* errorText = 0,
bool logCommandToWindow = true) const;
// Synchronous git execution using Utils::SynchronousProcess, with
@@ -284,9 +323,12 @@ private:
QString *errorMessage,
bool revertStaging);
void connectRepositoryChanged(const QString & repository, VcsBase::Command *cmd);
- void syncAbortPullRebase(const QString &workingDir);
+ bool executeAndHandleConflicts(const QString &workingDirectory, const QStringList &arguments,
+ const QString &abortCommand = QString());
+ void handleMergeConflicts(const QString &workingDir, const QString &abortCommand);
bool tryLauchingGitK(const QProcessEnvironment &env,
const QString &workingDirectory,
+ const QString &fileName,
const QString &gitBinDirectory,
bool silent);
bool cleanList(const QString &workingDirectory, const QString &flag, QStringList *files, QString *errorMessage);
diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp
index b29430dad1..31937000c4 100644
--- a/src/plugins/git/giteditor.cpp
+++ b/src/plugins/git/giteditor.cpp
@@ -66,8 +66,16 @@ GitEditor::GitEditor(const VcsBase::VcsBaseEditorParameters *type,
{
QTC_ASSERT(m_changeNumberPattern8.isValid(), return);
QTC_ASSERT(m_changeNumberPattern40.isValid(), return);
+ /* Diff format:
+ diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp
+ index 40997ff..4e49337 100644
+ --- a/src/plugins/git/giteditor.cpp
+ +++ b/src/plugins/git/giteditor.cpp
+ */
+ setDiffFilePattern(QRegExp(QLatin1String("^(?:diff --git a/|index |[+-]{3} (?:/dev/null|[ab]/(.+$)))")));
+ setLogEntryPattern(QRegExp(QLatin1String("^commit ([0-9a-f]{8})[0-9a-f]{32}")));
setAnnotateRevisionTextFormat(tr("Blame %1"));
- setAnnotatePreviousRevisionTextFormat(tr("Blame parent revision %1"));
+ setAnnotatePreviousRevisionTextFormat(tr("Blame Parent Revision %1"));
}
QSet<QString> GitEditor::annotationChanges() const
@@ -107,47 +115,12 @@ QString GitEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-VcsBase::DiffHighlighter *GitEditor::createDiffHighlighter() const
-{
- const QRegExp filePattern(QLatin1String("^(diff --git a/|index |[+-][+-][+-] [ab/]).*$"));
- return new VcsBase::DiffHighlighter(filePattern);
-}
-
VcsBase::BaseAnnotationHighlighter *GitEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new GitAnnotationHighlighter(changes, bg);
}
-QString GitEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
-{
- // Check for "+++ b/src/plugins/git/giteditor.cpp" (blame and diff)
- // as well as "--- a/src/plugins/git/giteditor.cpp".
- // Go back chunks.
- bool checkForOld = false;
-
- const QString oldFileIndicator = QLatin1String("--- a/");
- const QString newFileIndicator = QLatin1String("+++ ");
- for (QTextBlock block = inBlock; block.isValid(); block = block.previous()) {
- QString diffFileName = block.text();
- if (diffFileName.startsWith(oldFileIndicator) && checkForOld) {
- diffFileName.remove(0, oldFileIndicator.size());
- checkForOld = false;
- return diffFileName;
- } else if (diffFileName.startsWith(newFileIndicator)) {
- diffFileName.remove(0, newFileIndicator.size());
- if (diffFileName == QLatin1String("/dev/null")) {
- checkForOld = true;
- continue;
- }
- diffFileName.remove(0, 2); // remove "b/"
- return findDiffFile(diffFileName);
- }
- checkForOld = false;
- }
- return QString();
-}
-
/* Remove the date specification from annotation, which is tabular:
\code
8ca887aa (author YYYY-MM-DD HH:MM:SS <offset> <line>)<content>
@@ -207,11 +180,34 @@ static QByteArray removeAnnotationDate(const QByteArray &b)
void GitEditor::setPlainTextDataFiltered(const QByteArray &a)
{
QByteArray array = a;
+ GitPlugin *plugin = GitPlugin::instance();
// If desired, filter out the date from annotation
- const bool omitAnnotationDate = contentType() == VcsBase::AnnotateOutput
- && GitPlugin::instance()->settings().boolValue(GitSettings::omitAnnotationDateKey);
- if (omitAnnotationDate)
- array = removeAnnotationDate(a);
+ switch (contentType())
+ {
+ case VcsBase::AnnotateOutput: {
+ const bool omitAnnotationDate = plugin->settings().boolValue(GitSettings::omitAnnotationDateKey);
+ if (omitAnnotationDate)
+ array = removeAnnotationDate(a);
+ break;
+ }
+ case VcsBase::DiffOutput: {
+ const QFileInfo fi(source());
+ const QString workingDirectory = fi.absolutePath();
+ QByteArray precedes, follows;
+ if (array.startsWith("commit ")) { // show
+ int lastHeaderLine = array.indexOf("\n\n") + 1;
+ plugin->gitClient()->synchronousTagsForCommit(workingDirectory, QLatin1String(array.mid(7, 8)), precedes, follows);
+ if (!precedes.isEmpty())
+ array.insert(lastHeaderLine, "Precedes: " + precedes + '\n');
+ if (!follows.isEmpty())
+ array.insert(lastHeaderLine, "Follows: " + follows + '\n');
+ }
+ break;
+ }
+ default:
+ break;
+ }
+
setPlainTextData(array);
}
@@ -224,6 +220,20 @@ void GitEditor::commandFinishedGotoLine(bool ok, int /* exitCode */, const QVari
}
}
+void GitEditor::cherryPickChange()
+{
+ const QFileInfo fi(source());
+ const QString workingDirectory = fi.isDir() ? fi.absoluteFilePath() : fi.absolutePath();
+ GitPlugin::instance()->gitClient()->cherryPickCommit(workingDirectory, m_currentChange);
+}
+
+void GitEditor::revertChange()
+{
+ const QFileInfo fi(source());
+ const QString workingDirectory = fi.isDir() ? fi.absoluteFilePath() : fi.absolutePath();
+ GitPlugin::instance()->gitClient()->revertCommit(workingDirectory, m_currentChange);
+}
+
QString GitEditor::decorateVersion(const QString &revision) const
{
const QFileInfo fi(source());
@@ -254,6 +264,24 @@ bool GitEditor::isValidRevision(const QString &revision) const
return GitPlugin::instance()->gitClient()->isValidRevision(revision);
}
+void GitEditor::addChangeActions(QMenu *menu, const QString &change)
+{
+ m_currentChange = change;
+ menu->addAction(tr("Cherry-pick Change %1").arg(change), this, SLOT(cherryPickChange()));
+ menu->addAction(tr("Revert Change %1").arg(change), this, SLOT(revertChange()));
+}
+
+QString GitEditor::revisionSubject(const QTextBlock &inBlock) const
+{
+ for (QTextBlock block = inBlock.next(); block.isValid(); block = block.next()) {
+ const QString line = block.text().trimmed();
+ if (line.isEmpty()) {
+ block = block.next();
+ return block.text().trimmed();
+ }
+ }
+ return QString();
+}
+
} // namespace Internal
} // namespace Git
-
diff --git a/src/plugins/git/giteditor.h b/src/plugins/git/giteditor.h
index d2b07a6cce..e101bfb8ad 100644
--- a/src/plugins/git/giteditor.h
+++ b/src/plugins/git/giteditor.h
@@ -54,18 +54,23 @@ public slots:
// Matches the signature of the finished signal of GitCommand
void commandFinishedGotoLine(bool ok, int exitCode, const QVariant &v);
+private slots:
+ void cherryPickChange();
+ void revertChange();
+
private:
- virtual QSet<QString> annotationChanges() const;
- virtual QString changeUnderCursor(const QTextCursor &) const;
- virtual VcsBase::DiffHighlighter *createDiffHighlighter() const;
- virtual VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- virtual QString fileNameFromDiffSpecification(const QTextBlock &diffFileName) const;
- virtual QString decorateVersion(const QString &revision) const;
- virtual QStringList annotationPreviousVersions(const QString &revision) const;
- virtual bool isValidRevision(const QString &revision) const;
+ QSet<QString> annotationChanges() const;
+ QString changeUnderCursor(const QTextCursor &) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ QString decorateVersion(const QString &revision) const;
+ QStringList annotationPreviousVersions(const QString &revision) const;
+ bool isValidRevision(const QString &revision) const;
+ void addChangeActions(QMenu *menu, const QString &change);
+ QString revisionSubject(const QTextBlock &inBlock) const;
mutable QRegExp m_changeNumberPattern8;
mutable QRegExp m_changeNumberPattern40;
+ QString m_currentChange;
};
} // namespace Git
diff --git a/src/plugins/git/gitorious/gitorious.cpp b/src/plugins/git/gitorious/gitorious.cpp
index c37e3d9ddf..0d86e26ae3 100644
--- a/src/plugins/git/gitorious/gitorious.cpp
+++ b/src/plugins/git/gitorious/gitorious.cpp
@@ -121,7 +121,7 @@ QDebug operator<<(QDebug d, const GitoriousProject &p)
{
QDebug nospace = d.nospace();
nospace << " project=" << p.name << " description=" << p.description << '\n';
- foreach(const GitoriousRepository &r, p.repositories)
+ foreach (const GitoriousRepository &r, p.repositories)
nospace << " " << r << '\n';
return d;
}
@@ -136,9 +136,9 @@ QDebug operator<<(QDebug d, const GitoriousHost &h)
{
QDebug nospace = d.nospace();
nospace << " Host=" << h.hostName << " description=" << h.description << '\n';
- foreach(const QSharedPointer<GitoriousCategory> &c, h.categories)
+ foreach (const QSharedPointer<GitoriousCategory> &c, h.categories)
nospace << *c;
- foreach(const QSharedPointer<GitoriousProject> &p, h.projects)
+ foreach (const QSharedPointer<GitoriousProject> &p, h.projects)
nospace << *p;
return d;
}
@@ -207,11 +207,10 @@ GitoriousProjectReader::ProjectList GitoriousProjectReader::read(const QByteArra
while (!reader.atEnd()) {
reader.readNext();
if (reader.isStartElement()) {
- if (reader.name() == QLatin1String("projects")) {
+ if (reader.name() == QLatin1String("projects"))
readProjects(reader);
- } else {
+ else
readUnknownElement(reader);
- }
}
}
@@ -259,17 +258,16 @@ QSharedPointer<GitoriousProject> GitoriousProjectReader::readProject(QXmlStreamR
if (reader.isStartElement()) {
const QStringRef name = reader.name();
- if (name == QLatin1String("description")) {
+ if (name == QLatin1String("description"))
project->description = reader.readElementText();
- } else if (name == QLatin1String("title")) {
+ else if (name == QLatin1String("title"))
project->name = reader.readElementText();
- } else if (name == QLatin1String("slug") && project->name.isEmpty()) {
+ else if (name == QLatin1String("slug") && project->name.isEmpty())
project->name = reader.readElementText();
- } else if (name == QLatin1String("repositories")) {
+ else if (name == QLatin1String("repositories"))
project->repositories = readRepositories(reader);
- } else {
+ else
readUnknownElement(reader);
- }
}
}
return project;
@@ -287,24 +285,22 @@ QList<GitoriousRepository> GitoriousProjectReader::readRepositories(QXmlStreamRe
if (reader.isEndElement()) {
const QStringRef name = reader.name();
- if (name == m_mainLinesElement || name == m_clonesElement) {
+ if (name == m_mainLinesElement || name == m_clonesElement)
defaultType = -1;
- } else {
+ else
break;
- }
}
if (reader.isStartElement()) {
const QStringRef name = reader.name();
- if (reader.name() == QLatin1String("repository")) {
+ if (reader.name() == QLatin1String("repository"))
repositories.push_back(readRepository(reader, defaultType));
- } else if (name == m_mainLinesElement) {
+ else if (name == m_mainLinesElement)
defaultType = GitoriousRepository::MainLineRepository;
- } else if (name == m_clonesElement) {
+ else if (name == m_clonesElement)
defaultType = GitoriousRepository::CloneRepository;
- } else {
+ else
readUnknownElement(reader);
- }
}
}
return repositories;
@@ -324,23 +320,22 @@ GitoriousRepository GitoriousProjectReader::readRepository(QXmlStreamReader &rea
if (reader.isStartElement()) {
const QStringRef name = reader.name();
- if (name == QLatin1String("name")) {
+ if (name == QLatin1String("name"))
repository.name = reader.readElementText();
- } else if (name == QLatin1String("owner")) {
+ else if (name == QLatin1String("owner"))
repository.owner = reader.readElementText();
- } else if (name == QLatin1String("id")) {
+ else if (name == QLatin1String("id"))
repository.id = reader.readElementText().toInt();
- } else if (name == QLatin1String("description")) {
+ else if (name == QLatin1String("description"))
repository.description = reader.readElementText();
- } else if (name == QLatin1String("push_url")) {
+ else if (name == QLatin1String("push_url"))
repository.pushUrl = reader.readElementText();
- } else if (name == QLatin1String("clone_url")) {
+ else if (name == QLatin1String("clone_url"))
repository.cloneUrl = reader.readElementText();
- } else if (name == QLatin1String("namespace")) {
+ else if (name == QLatin1String("namespace"))
repository.type = repositoryType(reader.readElementText());
- } else {
+ else
readUnknownElement(reader);
- }
}
}
return repository;
@@ -568,7 +563,7 @@ void Gitorious::saveSettings(const QString &group, QSettings *s)
{
const QChar separator = QLatin1Char('|');
QStringList hosts;
- foreach(const GitoriousHost &h, m_hosts) {
+ foreach (const GitoriousHost &h, m_hosts) {
QString entry = h.hostName;
if (!h.description.isEmpty()) {
entry += separator;
@@ -588,11 +583,10 @@ void Gitorious::restoreSettings(const QString &group, const QSettings *s)
const QStringList hosts = s->value(group + QLatin1Char('/') + QLatin1String(settingsKeyC), QStringList()).toStringList();
foreach (const QString &h, hosts) {
const int sepPos = h.indexOf(separator);
- if (sepPos == -1) {
+ if (sepPos == -1)
addHost(GitoriousHost(h));
- } else {
+ else
addHost(GitoriousHost(h.mid(0, sepPos), h.mid(sepPos + 1)));
- }
}
}
diff --git a/src/plugins/git/gitorious/gitoriousclonewizard.cpp b/src/plugins/git/gitorious/gitoriousclonewizard.cpp
index 58b8d98e58..baa7cdb463 100644
--- a/src/plugins/git/gitorious/gitoriousclonewizard.cpp
+++ b/src/plugins/git/gitorious/gitoriousclonewizard.cpp
@@ -31,9 +31,9 @@
#include "gitorioushostwizardpage.h"
#include "gitoriousprojectwizardpage.h"
#include "gitoriousrepositorywizardpage.h"
-#include "clonewizardpage.h"
-#include <git/gitplugin.h>
+#include "../clonewizardpage.h"
+#include "../gitplugin.h"
#include <coreplugin/iversioncontrol.h>
#include <vcsbase/checkoutjobs.h>
@@ -53,7 +53,7 @@ namespace Internal {
class GitoriousCloneWizardPage : public Git::CloneWizardPage {
public:
explicit GitoriousCloneWizardPage(const GitoriousRepositoryWizardPage *rp, QWidget *parent = 0);
- virtual void initializePage();
+ void initializePage();
private:
const GitoriousRepositoryWizardPage *m_repositoryPage;
diff --git a/src/plugins/git/gitorious/gitoriousclonewizard.h b/src/plugins/git/gitorious/gitoriousclonewizard.h
index 0e927c360b..6f7b9418a4 100644
--- a/src/plugins/git/gitorious/gitoriousclonewizard.h
+++ b/src/plugins/git/gitorious/gitoriousclonewizard.h
@@ -44,15 +44,15 @@ public:
explicit GitoriousCloneWizard(QObject *parent = 0);
// IWizard
- virtual QIcon icon() const;
- virtual QString description() const;
- virtual QString displayName() const;
+ QIcon icon() const;
+ QString description() const;
+ QString displayName() const;
protected:
// BaseCheckoutWizard
- virtual QList<QWizardPage*> createParameterPages(const QString &path);
- virtual QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPages,
- QString *checkoutPath);
+ QList<QWizardPage*> createParameterPages(const QString &path);
+ QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPages,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/git/gitorious/gitorioushostwidget.cpp b/src/plugins/git/gitorious/gitorioushostwidget.cpp
index 5f2a876307..2fdc02d9f3 100644
--- a/src/plugins/git/gitorious/gitorioushostwidget.cpp
+++ b/src/plugins/git/gitorious/gitorioushostwidget.cpp
@@ -64,9 +64,8 @@ static QList<QStandardItem *> hostEntry(const QString &host,
// Empty for dummy, else "..." or count
QStandardItem *projectCountItem = 0;
QString countItemText;
- if (!isDummyEntry) {
+ if (!isDummyEntry)
countItemText = projectCount ? QString::number(projectCount) : QString(QLatin1String("..."));
- }
projectCountItem = new QStandardItem(countItemText);
projectCountItem->setFlags(nonEditableFlags);
QStandardItem *descriptionItem = new QStandardItem(description);
@@ -105,7 +104,7 @@ GitoriousHostWidget::GitoriousHostWidget(QWidget *parent) :
m_model->setHorizontalHeaderLabels(headers);
Gitorious &gitorious = Gitorious::instance();
- foreach( const GitoriousHost &gh, gitorious.hosts())
+ foreach (const GitoriousHost &gh, gitorious.hosts())
m_model->appendRow(hostEntry(gh));
appendNewDummyEntry();
connect(m_model, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(slotItemEdited(QStandardItem*)));
diff --git a/src/plugins/git/gitorious/gitorioushostwizardpage.h b/src/plugins/git/gitorious/gitorioushostwizardpage.h
index 43f20cb08d..a304cdbc0f 100644
--- a/src/plugins/git/gitorious/gitorioushostwizardpage.h
+++ b/src/plugins/git/gitorious/gitorioushostwizardpage.h
@@ -43,9 +43,9 @@ class GitoriousHostWizardPage : public QWizardPage {
Q_OBJECT
public:
GitoriousHostWizardPage(QWidget *parent = 0);
- virtual ~GitoriousHostWizardPage();
+ ~GitoriousHostWizardPage();
- virtual bool isComplete() const;
+ bool isComplete() const;
int selectedHostIndex() const;
diff --git a/src/plugins/git/gitorious/gitoriousprojectwidget.cpp b/src/plugins/git/gitorious/gitoriousprojectwidget.cpp
index 2f4feb7a16..523399493a 100644
--- a/src/plugins/git/gitorious/gitoriousprojectwidget.cpp
+++ b/src/plugins/git/gitorious/gitoriousprojectwidget.cpp
@@ -212,11 +212,10 @@ void GitoriousProjectWidget::setDescription(const QString &description,
descLine.truncate(newLinePos);
if (descLine.size() > MaxDescriptionLineLength) {
const int dotPos = descLine.lastIndexOf(QLatin1Char('.'), MaxDescriptionLineLength);
- if (dotPos != -1) {
+ if (dotPos != -1)
descLine.truncate(dotPos);
- } else {
+ else
descLine.truncate(MaxDescriptionLineLength);
- }
descLine += QLatin1String("...");
}
items->at(descriptionColumn)->setText(descLine);
@@ -230,11 +229,10 @@ void GitoriousProjectWidget::setDescription(const QString &description,
// Do not fall for "(http://XX)", strip special characters
static QRegExp urlRegExp(QLatin1String("(http://[\\w\\.-]+/[a-zA-Z0-9/\\-&]*)"));
QTC_CHECK(urlRegExp.isValid());
- if (urlRegExp.indexIn(description) != -1) {
+ if (urlRegExp.indexIn(description) != -1)
*url= urlRegExp.cap(1);
- } else {
+ else
url->clear();
- }
}
}
diff --git a/src/plugins/git/gitorious/gitoriousprojectwidget.h b/src/plugins/git/gitorious/gitoriousprojectwidget.h
index ba5e615249..b9dc642235 100644
--- a/src/plugins/git/gitorious/gitoriousprojectwidget.h
+++ b/src/plugins/git/gitorious/gitoriousprojectwidget.h
@@ -63,7 +63,7 @@ public:
QWidget *parent = 0);
~GitoriousProjectWidget();
- virtual bool isValid() const;
+ bool isValid() const;
QSharedPointer<GitoriousProject> project() const;
diff --git a/src/plugins/git/gitorious/gitoriousprojectwizardpage.cpp b/src/plugins/git/gitorious/gitoriousprojectwizardpage.cpp
index 4b8aa7507d..2a6c25816d 100644
--- a/src/plugins/git/gitorious/gitoriousprojectwizardpage.cpp
+++ b/src/plugins/git/gitorious/gitoriousprojectwizardpage.cpp
@@ -125,7 +125,7 @@ GitoriousProjectWidget *GitoriousProjectWizardPage::currentProjectWidget() const
int GitoriousProjectWizardPage::stackIndexOf(const QString &hostName) const
{
const int count = m_stackedWidget->count();
- for(int i = 0; i < count; i++)
+ for (int i = 0; i < count; i++)
if (projectWidgetAt(i)->hostName() == hostName)
return i;
return -1;
diff --git a/src/plugins/git/gitorious/gitoriousprojectwizardpage.h b/src/plugins/git/gitorious/gitoriousprojectwizardpage.h
index 89fab91279..0bdcf0e4df 100644
--- a/src/plugins/git/gitorious/gitoriousprojectwizardpage.h
+++ b/src/plugins/git/gitorious/gitoriousprojectwizardpage.h
@@ -61,8 +61,8 @@ public:
explicit GitoriousProjectWizardPage(const GitoriousHostWizardPage *hostPage,
QWidget *parent = 0);
- virtual void initializePage();
- virtual bool isComplete() const;
+ void initializePage();
+ bool isComplete() const;
QSharedPointer<GitoriousProject> project() const;
int selectedHostIndex() const;
diff --git a/src/plugins/git/gitorious/gitoriousrepositorywizardpage.cpp b/src/plugins/git/gitorious/gitoriousrepositorywizardpage.cpp
index beb3199ea7..33e58c9bb3 100644
--- a/src/plugins/git/gitorious/gitoriousrepositorywizardpage.cpp
+++ b/src/plugins/git/gitorious/gitoriousrepositorywizardpage.cpp
@@ -163,7 +163,7 @@ void GitoriousRepositoryWizardPage::initializePage()
qStableSort(repositories.begin(), repositories.end(), gitRepoLessThanByType);
const QString types[GitoriousRepository::PersonalRepository + 1] =
{ tr("Mainline Repositories"), tr("Clones"), tr("Baseline Repositories"), tr("Shared Project Repositories"), tr("Personal Repositories") };
- foreach(const GitoriousRepository &r, repositories) {
+ foreach (const GitoriousRepository &r, repositories) {
// New Header?
if (r.type != lastRepoType || !header) {
lastRepoType = r.type;
diff --git a/src/plugins/git/gitorious/gitoriousrepositorywizardpage.h b/src/plugins/git/gitorious/gitoriousrepositorywizardpage.h
index b4fc5d631f..be6b4d3953 100644
--- a/src/plugins/git/gitorious/gitoriousrepositorywizardpage.h
+++ b/src/plugins/git/gitorious/gitoriousrepositorywizardpage.h
@@ -58,8 +58,8 @@ public:
QWidget *parent = 0);
~GitoriousRepositoryWizardPage();
- virtual void initializePage();
- virtual bool isComplete() const;
+ void initializePage();
+ bool isComplete() const;
QString repositoryName() const;
QUrl repositoryURL() const;
diff --git a/src/plugins/git/gitplugin.cpp b/src/plugins/git/gitplugin.cpp
index b75f893799..ae6b106029 100644
--- a/src/plugins/git/gitplugin.cpp
+++ b/src/plugins/git/gitplugin.cpp
@@ -39,12 +39,13 @@
#include "branchdialog.h"
#include "remotedialog.h"
#include "clonewizard.h"
-#include "gitoriousclonewizard.h"
+#include "gitorious/gitoriousclonewizard.h"
#include "stashdialog.h"
#include "settingspage.h"
#include "resetdialog.h"
+#include "mergetool.h"
-#include <gerritplugin.h>
+#include "gerrit/gerritplugin.h"
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
@@ -174,7 +175,8 @@ static const VcsBase::VcsBaseSubmitEditorParameters submitParameters = {
Git::Constants::SUBMIT_MIMETYPE,
Git::Constants::GITSUBMITEDITOR_ID,
Git::Constants::GITSUBMITEDITOR_DISPLAY_NAME,
- Git::Constants::C_GITSUBMITEDITOR
+ Git::Constants::C_GITSUBMITEDITOR,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffRows
};
// Create a parameter action
@@ -292,9 +294,8 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
addAutoReleasedObject(new CloneWizard);
addAutoReleasedObject(new Gitorious::Internal::GitoriousCloneWizard);
- const QString description = QLatin1String("Git");
const QString prefix = QLatin1String("git");
- m_commandLocator = new Locator::CommandLocator(description, prefix, prefix);
+ m_commandLocator = new Locator::CommandLocator("Git", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
//register actions
@@ -306,58 +307,69 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
toolsContainer->addMenu(gitContainer);
m_menuAction = gitContainer->menu()->menuAction();
- ParameterActionCommandPair parameterActionCommand
- = createFileAction(gitContainer,
- tr("Blame Current File"), tr("Blame for \"%1\""),
- Core::Id("Git.Blame"),
- globalcontext, true, SLOT(blameFile()));
- parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+B") : tr("Alt+G,Alt+B")));
+ /* "Current File" menu */
+ Core::ActionContainer *currentFileMenu = Core::ActionManager::createMenu(Core::Id("Git.CurrentFileMenu"));
+ currentFileMenu->menu()->setTitle(tr("Current &File"));
+ gitContainer->addMenu(currentFileMenu);
- parameterActionCommand
- = createFileAction(gitContainer,
+ ParameterActionCommandPair parameterActionCommand
+ = createFileAction(currentFileMenu,
tr("Diff Current File"), tr("Diff of \"%1\""),
Core::Id("Git.Diff"), globalcontext, true,
SLOT(diffCurrentFile()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+D") : tr("Alt+G,Alt+D")));
parameterActionCommand
- = createFileAction(gitContainer,
+ = createFileAction(currentFileMenu,
tr("Log Current File"), tr("Log of \"%1\""),
Core::Id("Git.Log"), globalcontext, true, SLOT(logFile()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+L") : tr("Alt+G,Alt+L")));
+ parameterActionCommand
+ = createFileAction(currentFileMenu,
+ tr("Blame Current File"), tr("Blame for \"%1\""),
+ Core::Id("Git.Blame"),
+ globalcontext, true, SLOT(blameFile()));
+ parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+B") : tr("Alt+G,Alt+B")));
+
// ------
- gitContainer->addSeparator(globalcontext);
+ currentFileMenu->addSeparator(globalcontext);
parameterActionCommand
- = createFileAction(gitContainer,
+ = createFileAction(currentFileMenu,
tr("Stage File for Commit"), tr("Stage \"%1\" for Commit"),
Core::Id("Git.Stage"), globalcontext, true, SLOT(stageFile()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+A") : tr("Alt+G,Alt+A")));
parameterActionCommand
- = createFileAction(gitContainer,
+ = createFileAction(currentFileMenu,
tr("Unstage File from Commit"), tr("Unstage \"%1\" from Commit"),
Core::Id("Git.Unstage"), globalcontext, true, SLOT(unstageFile()));
parameterActionCommand
- = createFileAction(gitContainer,
+ = createFileAction(currentFileMenu,
tr("Undo Unstaged Changes"), tr("Undo Unstaged Changes for \"%1\""),
Core::Id("Git.UndoUnstaged"), globalcontext,
true, SLOT(undoUnstagedFileChanges()));
parameterActionCommand
- = createFileAction(gitContainer,
+ = createFileAction(currentFileMenu,
tr("Undo Uncommitted Changes"), tr("Undo Uncommitted Changes for \"%1\""),
Core::Id("Git.Undo"), globalcontext,
true, SLOT(undoFileChanges()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+U") : tr("Alt+G,Alt+U")));
+ /* \"Current File" menu */
+
// ------------
- gitContainer->addSeparator(globalcontext);
+
+ /* "Current Project" menu */
+ Core::ActionContainer *currentProjectMenu = Core::ActionManager::createMenu(Core::Id("Git.CurrentProjectMenu"));
+ currentProjectMenu->menu()->setTitle(tr("Current &Project"));
+ gitContainer->addMenu(currentProjectMenu);
parameterActionCommand
- = createProjectAction(gitContainer,
+ = createProjectAction(currentProjectMenu,
tr("Diff Current Project"), tr("Diff Project \"%1\""),
Core::Id("Git.DiffProject"),
globalcontext, true,
@@ -365,80 +377,83 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+Shift+D") : tr("Alt+G,Alt+Shift+D")));
parameterActionCommand
- = createProjectAction(gitContainer,
+ = createProjectAction(currentProjectMenu,
tr("Log Project"), tr("Log Project \"%1\""),
Core::Id("Git.LogProject"), globalcontext, true,
SLOT(logProject()));
parameterActionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+K") : tr("Alt+G,Alt+K")));
parameterActionCommand
- = createProjectAction(gitContainer,
+ = createProjectAction(currentProjectMenu,
tr("Clean Project..."), tr("Clean Project \"%1\"..."),
Core::Id("Git.CleanProject"), globalcontext,
true, SLOT(cleanProject()));
+ /* \"Current Project" menu */
// --------------
- gitContainer->addSeparator(globalcontext);
- createRepositoryAction(gitContainer,
+ /* "Local Repository" menu */
+ Core::ActionContainer *localRepositoryMenu = Core::ActionManager::createMenu(Core::Id("Git.LocalRepositoryMenu"));
+ localRepositoryMenu->menu()->setTitle(tr("&Local Repository"));
+ gitContainer->addMenu(localRepositoryMenu);
+
+ createRepositoryAction(localRepositoryMenu,
tr("Diff"), Core::Id("Git.DiffRepository"),
globalcontext, true, SLOT(diffRepository()));
- createRepositoryAction(gitContainer,
+ createRepositoryAction(localRepositoryMenu,
tr("Log"), Core::Id("Git.LogRepository"),
globalcontext, true, &GitClient::graphLog);
- createRepositoryAction(gitContainer,
+ createRepositoryAction(localRepositoryMenu,
+ tr("Clean..."), Core::Id("Git.CleanRepository"),
+ globalcontext, true, SLOT(cleanRepository()));
+
+ createRepositoryAction(localRepositoryMenu,
tr("Status"), Core::Id("Git.StatusRepository"),
globalcontext, true, &GitClient::status);
- createRepositoryAction(gitContainer,
- tr("Reset..."), Core::Id("Git.Reset"),
- globalcontext, false, SLOT(resetRepository()));
+ // --------------
+ localRepositoryMenu->addSeparator(globalcontext);
+ ActionCommandPair actionCommand = createRepositoryAction(localRepositoryMenu,
+ tr("Commit..."), Core::Id("Git.Commit"),
+ globalcontext, true, SLOT(startCommit()));
+ actionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+C") : tr("Alt+G,Alt+C")));
- createRepositoryAction(gitContainer,
- tr("Clean..."), Core::Id("Git.CleanRepository"),
- globalcontext, true, SLOT(cleanRepository()));
+ createRepositoryAction(localRepositoryMenu,
+ tr("Amend Last Commit..."), Core::Id("Git.AmendCommit"),
+ globalcontext, true, SLOT(startAmendCommit()));
+ // --------------
+ localRepositoryMenu->addSeparator(globalcontext);
- m_createRepositoryAction = new QAction(tr("Create Repository..."), this);
- Core::Command *createRepositoryCommand = Core::ActionManager::registerAction(m_createRepositoryAction, "Git.CreateRepository", globalcontext);
- connect(m_createRepositoryAction, SIGNAL(triggered()), this, SLOT(createRepository()));
- gitContainer->addAction(createRepositoryCommand);
+ createRepositoryAction(localRepositoryMenu,
+ tr("Reset..."), Core::Id("Git.Reset"),
+ globalcontext, false, SLOT(resetRepository()));
- // --------------
- gitContainer->addSeparator(globalcontext);
+ createRepositoryAction(localRepositoryMenu,
+ tr("Revert Single Commit..."), Core::Id("Git.Revert"),
+ globalcontext, true, SLOT(startRevertCommit()));
- createRepositoryAction(gitContainer,
- tr("Launch gitk"), Core::Id("Git.LaunchGitK"),
- globalcontext, true, &GitClient::launchGitK);
+ createRepositoryAction(localRepositoryMenu,
+ tr("Cherry-Pick Commit..."), Core::Id("Git.CherryPick"),
+ globalcontext, true, SLOT(startCherryPickCommit()));
- m_repositoryBrowserAction
- = createRepositoryAction(gitContainer,
- tr("Launch repository browser"), Core::Id("Git.LaunchRepositoryBrowser"),
- globalcontext, true, &GitClient::launchRepositoryBrowser).first;
+ // --------------
+ localRepositoryMenu->addSeparator(globalcontext);
- createRepositoryAction(gitContainer,
+ createRepositoryAction(localRepositoryMenu,
tr("Branches..."), Core::Id("Git.BranchList"),
globalcontext, true, SLOT(branchList()));
- createRepositoryAction(gitContainer,
- tr("Remotes..."), Core::Id("Git.RemoteList"),
- globalcontext, false, SLOT(remoteList()));
-
- m_showAction = new QAction(tr("Show..."), this);
- Core::Command *showCommitCommand = Core::ActionManager::registerAction(m_showAction, "Git.ShowCommit", globalcontext);
- connect(m_showAction, SIGNAL(triggered()), this, SLOT(showCommit()));
- gitContainer->addAction(showCommitCommand);
-
-
// --------------
- gitContainer->addSeparator(globalcontext);
+ localRepositoryMenu->addSeparator(globalcontext);
+ // "Patch" menu
Core::ActionContainer *patchMenu = Core::ActionManager::createMenu(Core::Id("Git.PatchMenu"));
- patchMenu->menu()->setTitle(tr("Patch"));
- gitContainer->addMenu(patchMenu);
+ patchMenu->menu()->setTitle(tr("&Patch"));
+ localRepositoryMenu->addMenu(patchMenu);
// Apply current file as patch is handled specially.
parameterActionCommand =
@@ -454,9 +469,10 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
tr("Apply from File..."), Core::Id("Git.ApplyPatch"),
globalcontext, true, SLOT(promptApplyPatch()));
+ // "Stash" menu
Core::ActionContainer *stashMenu = Core::ActionManager::createMenu(Core::Id("Git.StashMenu"));
- stashMenu->menu()->setTitle(tr("Stash"));
- gitContainer->addMenu(stashMenu);
+ stashMenu->menu()->setTitle(tr("&Stash"));
+ localRepositoryMenu->addMenu(stashMenu);
createRepositoryAction(stashMenu,
tr("Stashes..."), Core::Id("Git.StashList"),
@@ -464,10 +480,9 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
stashMenu->addSeparator(globalcontext);
- ActionCommandPair actionCommand =
- createRepositoryAction(stashMenu,
- tr("Stash"), Core::Id("Git.Stash"),
- globalcontext, true, SLOT(stash()));
+ actionCommand = createRepositoryAction(stashMenu,
+ tr("Stash"), Core::Id("Git.Stash"),
+ globalcontext, true, SLOT(stash()));
actionCommand.first->setToolTip(tr("Saves the current state of your work and resets the repository."));
actionCommand = createRepositoryAction(stashMenu,
@@ -482,9 +497,35 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
globalcontext, true, &GitClient::stashPop);
actionCommand.first->setToolTip(tr("Restores changes saved to the stash list using \"Stash\"."));
+
+ /* \"Local Repository" menu */
+
+ // --------------
+
+ /* "Remote Repository" menu */
+ Core::ActionContainer *remoteRepositoryMenu = Core::ActionManager::createMenu(Core::Id("Git.RemoteRepositoryMenu"));
+ remoteRepositoryMenu->menu()->setTitle(tr("&Remote Repository"));
+ gitContainer->addMenu(remoteRepositoryMenu);
+
+ createRepositoryAction(remoteRepositoryMenu,
+ tr("Fetch"), Core::Id("Git.Fetch"),
+ globalcontext, true, SLOT(fetch()));
+
+ createRepositoryAction(remoteRepositoryMenu,
+ tr("Pull"), Core::Id("Git.Pull"),
+ globalcontext, true, SLOT(pull()));
+
+ actionCommand = createRepositoryAction(remoteRepositoryMenu,
+ tr("Push"), Core::Id("Git.Push"),
+ globalcontext, true, SLOT(push()));
+
+ // --------------
+ remoteRepositoryMenu->addSeparator(globalcontext);
+
+ // "Subversion" menu
Core::ActionContainer *subversionMenu = Core::ActionManager::createMenu(Core::Id("Git.Subversion"));
- subversionMenu->menu()->setTitle(tr("Subversion"));
- gitContainer->addMenu(subversionMenu);
+ subversionMenu->menu()->setTitle(tr("&Subversion"));
+ remoteRepositoryMenu->addMenu(subversionMenu);
createRepositoryAction(subversionMenu,
tr("Log"), Core::Id("Git.Subversion.Log"),
@@ -494,34 +535,63 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
tr("Fetch"), Core::Id("Git.Subversion.Fetch"),
globalcontext, false, &GitClient::synchronousSubversionFetch);
- gitContainer->addSeparator(globalcontext);
+ // --------------
+ remoteRepositoryMenu->addSeparator(globalcontext);
- gitContainer->addSeparator(globalcontext);
+ createRepositoryAction(remoteRepositoryMenu,
+ tr("Manage Remotes..."), Core::Id("Git.RemoteList"),
+ globalcontext, false, SLOT(remoteList()));
- createRepositoryAction(gitContainer,
- tr("Fetch"), Core::Id("Git.Fetch"),
- globalcontext, true, SLOT(fetch()));
+ /* \"Remote Repository" menu */
- createRepositoryAction(gitContainer,
- tr("Pull"), Core::Id("Git.Pull"),
- globalcontext, true, SLOT(pull()));
+ // --------------
- actionCommand = createRepositoryAction(gitContainer,
- tr("Push"), Core::Id("Git.Push"),
- globalcontext, true, SLOT(push()));
+ /* "Git Tools" menu */
+ Core::ActionContainer *gitToolsMenu = Core::ActionManager::createMenu(Core::Id("Git.GitToolsMenu"));
+ gitToolsMenu->menu()->setTitle(tr("Git &Tools"));
+ gitContainer->addMenu(gitToolsMenu);
- actionCommand = createRepositoryAction(gitContainer,
- tr("Commit..."), Core::Id("Git.Commit"),
- globalcontext, true, SLOT(startCommit()));
- actionCommand.second->setDefaultKeySequence(QKeySequence(Core::UseMacShortcuts ? tr("Meta+G,Meta+C") : tr("Alt+G,Alt+C")));
+ createRepositoryAction(gitToolsMenu,
+ tr("Gitk"), Core::Id("Git.LaunchGitK"),
+ globalcontext, true, &GitClient::launchGitK);
- createRepositoryAction(gitContainer,
- tr("Amend Last Commit..."), Core::Id("Git.AmendCommit"),
- globalcontext, true, SLOT(startAmendCommit()));
+ parameterActionCommand
+ = createFileAction(gitToolsMenu,
+ tr("Gitk Current File"), tr("Gitk of \"%1\""),
+ Core::Id("Git.GitkFile"), globalcontext, true, SLOT(gitkForCurrentFile()));
- // Subversion in a submenu.
+ parameterActionCommand
+ = createFileAction(gitToolsMenu,
+ tr("Gitk for folder of Current File"), tr("Gitk for folder of \"%1\""),
+ Core::Id("Git.GitkFolder"), globalcontext, true, SLOT(gitkForCurrentFolder()));
+
+ // --------------
+ gitToolsMenu->addSeparator(globalcontext);
+
+ m_repositoryBrowserAction
+ = createRepositoryAction(gitToolsMenu,
+ tr("Repository Browser"), Core::Id("Git.LaunchRepositoryBrowser"),
+ globalcontext, true, &GitClient::launchRepositoryBrowser).first;
+
+ createRepositoryAction(gitToolsMenu,
+ tr("Merge Tool"), Core::Id("Git.MergeTool"),
+ globalcontext, true, SLOT(startMergeTool()));
+
+ /* \"Git Tools" menu */
+
+ // --------------
gitContainer->addSeparator(globalcontext);
+ m_showAction = new QAction(tr("Show..."), this);
+ Core::Command *showCommitCommand = Core::ActionManager::registerAction(m_showAction, "Git.ShowCommit", globalcontext);
+ connect(m_showAction, SIGNAL(triggered()), this, SLOT(showCommit()));
+ gitContainer->addAction(showCommitCommand);
+
+ m_createRepositoryAction = new QAction(tr("Create Repository..."), this);
+ Core::Command *createRepositoryCommand = Core::ActionManager::registerAction(m_createRepositoryAction, "Git.CreateRepository", globalcontext);
+ connect(m_createRepositoryAction, SIGNAL(triggered()), this, SLOT(createRepository()));
+ gitContainer->addAction(createRepositoryCommand);
+
if (0) {
const QList<QAction*> snapShotActions = createSnapShotTestActions();
const int count = snapShotActions.size();
@@ -551,8 +621,9 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage)
command = Core::ActionManager::registerAction(m_redoAction, Core::Constants::REDO, submitContext);
+ /* "Gerrit" */
Gerrit::Internal::GerritPlugin *gp = new Gerrit::Internal::GerritPlugin(this);
- return gp->initialize(gitContainer);
+ return gp->initialize(remoteRepositoryMenu);
}
GitVersionControl *GitPlugin::gitVersionControl() const
@@ -565,6 +636,11 @@ void GitPlugin::submitEditorDiff(const QStringList &unstaged, const QStringList
m_gitClient->diff(m_submitRepository, QStringList(), unstaged, staged);
}
+void GitPlugin::submitEditorMerge(const QStringList &unmerged)
+{
+ m_gitClient->merge(m_submitRepository, unmerged);
+}
+
void GitPlugin::diffCurrentFile()
{
const VcsBase::VcsBasePluginState state = currentState();
@@ -628,7 +704,50 @@ void GitPlugin::resetRepository()
ResetDialog dialog;
if (dialog.runDialog(state.topLevel()))
- m_gitClient->hardReset(state.topLevel(), dialog.commit());
+ switch (dialog.resetType()) {
+ case HardReset:
+ m_gitClient->hardReset(state.topLevel(), dialog.commit());
+ break;
+ case SoftReset:
+ m_gitClient->softReset(state.topLevel(), dialog.commit());
+ break;
+ }
+}
+
+void GitPlugin::startRevertCommit()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QString workingDirectory = state.currentDirectoryOrTopLevel();
+ if (workingDirectory.isEmpty())
+ return;
+ GitClient::StashGuard stashGuard(workingDirectory, QLatin1String("Revert"));
+ if (stashGuard.stashingFailed(true))
+ return;
+ ChangeSelectionDialog changeSelectionDialog(workingDirectory);
+
+ if (changeSelectionDialog.exec() != QDialog::Accepted)
+ return;
+ const QString change = changeSelectionDialog.change();
+ if (!change.isEmpty() && !m_gitClient->revertCommit(workingDirectory, change))
+ stashGuard.preventPop();
+}
+
+void GitPlugin::startCherryPickCommit()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QString workingDirectory = state.currentDirectoryOrTopLevel();
+ if (workingDirectory.isEmpty())
+ return;
+ GitClient::StashGuard stashGuard(state.topLevel(), QLatin1String("Cherry-pick"));
+ if (stashGuard.stashingFailed(true))
+ return;
+ ChangeSelectionDialog changeSelectionDialog(workingDirectory);
+
+ if (changeSelectionDialog.exec() != QDialog::Accepted)
+ return;
+ const QString change = changeSelectionDialog.change();
+ if (!change.isEmpty() && !m_gitClient->cherryPickCommit(workingDirectory, change))
+ stashGuard.preventPop();
}
void GitPlugin::stageFile()
@@ -645,6 +764,43 @@ void GitPlugin::unstageFile()
m_gitClient->synchronousReset(state.currentFileTopLevel(), QStringList(state.relativeCurrentFile()));
}
+void GitPlugin::gitkForCurrentFile()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasFile(), return);
+ m_gitClient->launchGitK(state.currentFileTopLevel(), state.relativeCurrentFile());
+}
+
+void GitPlugin::gitkForCurrentFolder()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasFile(), return);
+
+ /*
+ * entire lower part of the code can be easily replaced with one line:
+ *
+ * m_gitClient->launchGitK(dir.currentFileDirectory(), QLatin1String("."));
+ *
+ * However, there is a bug in gitk in version 1.7.9.5, and if you run above
+ * command, there will be no documents listed in lower right section.
+ *
+ * This is why I use lower combination in order to avoid this problems in gitk.
+ *
+ * Git version 1.7.10.4 does not have this issue, and it can easily use
+ * one line command mentioned above.
+ *
+ */
+ QDir dir(state.currentFileDirectory());
+ if (QFileInfo(dir,QLatin1String(".git")).exists() || dir.cd(QLatin1String(".git")))
+ m_gitClient->launchGitK(state.currentFileDirectory());
+ else {
+ QString folderName = dir.absolutePath();
+ dir.cdUp();
+ folderName = folderName.remove(0, dir.absolutePath().length() + 1);
+ m_gitClient->launchGitK(dir.absolutePath(), folderName);
+ }
+}
+
void GitPlugin::startAmendCommit()
{
startCommit(true);
@@ -705,9 +861,9 @@ Core::IEditor *GitPlugin::openSubmitEditor(const QString &fileName, const Commit
submitEditor->setCheckScriptWorkingDirectory(m_submitRepository);
const QString title = amend ? tr("Amend %1").arg(cd.amendSHA1) : tr("Git Commit");
submitEditor->setDisplayName(title);
- if (amend) // Allow for just correcting the message
- submitEditor->setEmptyFileListEnabled(true);
+ submitEditor->setAmend(amend);
connect(submitEditor, SIGNAL(diff(QStringList,QStringList)), this, SLOT(submitEditorDiff(QStringList,QStringList)));
+ connect(submitEditor, SIGNAL(merge(QStringList)), this, SLOT(submitEditorMerge(QStringList)));
return editor;
}
@@ -778,23 +934,23 @@ void GitPlugin::pull()
{
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- const bool rebase = m_gitClient->settings()->boolValue(GitSettings::pullRebaseKey);
-
- GitClient::StashResult stashResult = m_gitClient->ensureStash(state.topLevel());
- switch (stashResult) {
- case GitClient::StashUnchanged:
- case GitClient::Stashed:
- m_gitClient->synchronousPull(state.topLevel(), rebase);
- if (stashResult == GitClient::Stashed)
- m_gitClient->stashPop(state.topLevel());
- break;
- case GitClient::NotStashed:
- if (!rebase)
- m_gitClient->synchronousPull(state.topLevel(), false);
- break;
- default:
- break;
+ bool rebase = m_gitClient->settings()->boolValue(GitSettings::pullRebaseKey);
+
+ if (!rebase) {
+ bool isDetached;
+ QString branchRebaseConfig = m_gitClient->synchronousRepositoryBranches(state.topLevel(), &isDetached).at(0);
+ if (!isDetached) {
+ branchRebaseConfig.prepend(QLatin1String("branch."));
+ branchRebaseConfig.append(QLatin1String(".rebase"));
+ rebase = (m_gitClient->readConfigValue(state.topLevel(), branchRebaseConfig) == QLatin1String("true"));
+ }
}
+
+ GitClient::StashGuard stashGuard(state.topLevel(), QLatin1String("Pull"));
+ if (stashGuard.stashingFailed(false) || (rebase && (stashGuard.result() == GitClient::NotStashed)))
+ return;
+ if (!m_gitClient->synchronousPull(state.topLevel(), false))
+ stashGuard.preventPop();
}
void GitPlugin::push()
@@ -804,14 +960,21 @@ void GitPlugin::push()
m_gitClient->synchronousPush(state.topLevel());
}
+void GitPlugin::startMergeTool()
+{
+ const VcsBase::VcsBasePluginState state = currentState();
+ QTC_ASSERT(state.hasTopLevel(), return);
+ m_gitClient->merge(state.topLevel());
+}
+
// Retrieve member function of git client stored as user data of action
static inline GitClientMemberFunc memberFunctionFromAction(const QObject *o)
{
if (o) {
if (const QAction *action = qobject_cast<const QAction *>(o)) {
const QVariant v = action->data();
- if (qVariantCanConvert<GitClientMemberFunc>(v))
- return qVariantValue<GitClientMemberFunc>(v);
+ if (v.canConvert<GitClientMemberFunc>())
+ return qvariant_cast<GitClientMemberFunc>(v);
}
}
return 0;
@@ -904,14 +1067,9 @@ void GitPlugin::promptApplyPatch()
void GitPlugin::applyPatch(const QString &workingDirectory, QString file)
{
// Ensure user has been notified about pending changes
- switch (m_gitClient->ensureStash(workingDirectory)) {
- case GitClient::StashUnchanged:
- case GitClient::Stashed:
- case GitClient::NotStashed:
- break;
- default:
+ GitClient::StashGuard stashGuard(workingDirectory, QLatin1String("Apply-Patch"));
+ if (stashGuard.stashingFailed(false))
return;
- }
// Prompt for file
if (file.isEmpty()) {
const QString filter = tr("Patches (*.patch *.diff)");
@@ -925,11 +1083,10 @@ void GitPlugin::applyPatch(const QString &workingDirectory, QString file)
VcsBase::VcsBaseOutputWindow *outwin = VcsBase::VcsBaseOutputWindow::instance();
QString errorMessage;
if (m_gitClient->synchronousApplyPatch(workingDirectory, file, &errorMessage)) {
- if (errorMessage.isEmpty()) {
+ if (errorMessage.isEmpty())
outwin->append(tr("Patch %1 successfully applied to %2").arg(file, workingDirectory));
- } else {
+ else
outwin->append(errorMessage);
- }
} else {
outwin->appendError(errorMessage);
}
@@ -940,7 +1097,8 @@ void GitPlugin::stash()
// Simple stash without prompt, reset repo.
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- const QString id = m_gitClient->synchronousStash(state.topLevel(), QString(), 0);
+ QString id;
+ gitClient()->ensureStash(state.topLevel(), QString(), false, &id);
if (!id.isEmpty() && m_stashDialog)
m_stashDialog->refresh(state.topLevel(), true);
}
@@ -950,7 +1108,8 @@ void GitPlugin::stashSnapshot()
// Prompt for description, restore immediately and keep on working.
const VcsBase::VcsBasePluginState state = currentState();
QTC_ASSERT(state.hasTopLevel(), return);
- const QString id = m_gitClient->synchronousStash(state.topLevel(), QString(), GitClient::StashImmediateRestore|GitClient::StashPromptDescription);
+ const QString id = m_gitClient->synchronousStash(state.topLevel(), QString(),
+ GitClient::StashImmediateRestore|GitClient::StashPromptDescription);
if (!id.isEmpty() && m_stashDialog)
m_stashDialog->refresh(state.topLevel(), true);
}
@@ -1032,10 +1191,7 @@ void GitPlugin::showCommit()
if (!m_changeSelectionDialog)
m_changeSelectionDialog = new ChangeSelectionDialog();
- if (state.hasFile())
- m_changeSelectionDialog->setWorkingDirectory(state.currentFileDirectory());
- else if (state.hasTopLevel())
- m_changeSelectionDialog->setWorkingDirectory(state.topLevel());
+ m_changeSelectionDialog->setWorkingDirectory(state.currentDirectoryOrTopLevel());
if (m_changeSelectionDialog->exec() != QDialog::Accepted)
return;
@@ -1067,4 +1223,125 @@ GitClient *GitPlugin::gitClient() const
return m_gitClient;
}
+#ifdef WITH_TESTS
+#include "giteditor.h"
+
+#include <QTest>
+#include <QTextBlock>
+#include <QTextDocument>
+
+Q_DECLARE_METATYPE(FileStates)
+
+void GitPlugin::testStatusParsing_data()
+{
+ QTest::addColumn<FileStates>("first");
+ QTest::addColumn<FileStates>("second");
+
+ QTest::newRow(" M") << FileStates(ModifiedFile) << FileStates(UnknownFileState);
+ QTest::newRow(" D") << FileStates(DeletedFile) << FileStates(UnknownFileState);
+ QTest::newRow("M ") << (ModifiedFile | StagedFile) << FileStates(UnknownFileState);
+ QTest::newRow("MM") << (ModifiedFile | StagedFile) << FileStates(ModifiedFile);
+ QTest::newRow("MD") << (ModifiedFile | StagedFile) << FileStates(DeletedFile);
+ QTest::newRow("A ") << (AddedFile | StagedFile) << FileStates(UnknownFileState);
+ QTest::newRow("AM") << (AddedFile | StagedFile) << FileStates(ModifiedFile);
+ QTest::newRow("AD") << (AddedFile | StagedFile) << FileStates(DeletedFile);
+ QTest::newRow("D ") << (DeletedFile | StagedFile) << FileStates(UnknownFileState);
+ QTest::newRow("DM") << (DeletedFile | StagedFile) << FileStates(ModifiedFile);
+ QTest::newRow("R ") << (RenamedFile | StagedFile) << FileStates(UnknownFileState);
+ QTest::newRow("RM") << (RenamedFile | StagedFile) << FileStates(ModifiedFile);
+ QTest::newRow("RD") << (RenamedFile | StagedFile) << FileStates(DeletedFile);
+ QTest::newRow("C ") << (CopiedFile | StagedFile) << FileStates(UnknownFileState);
+ QTest::newRow("CM") << (CopiedFile | StagedFile) << FileStates(ModifiedFile);
+ QTest::newRow("CD") << (CopiedFile | StagedFile) << FileStates(DeletedFile);
+
+ // Merges
+ QTest::newRow("DD") << (DeletedFile | UnmergedFile | UnmergedUs | UnmergedThem) << FileStates(UnknownFileState);
+ QTest::newRow("AA") << (AddedFile | UnmergedFile | UnmergedUs | UnmergedThem) << FileStates(UnknownFileState);
+ QTest::newRow("UU") << (ModifiedFile | UnmergedFile | UnmergedUs | UnmergedThem) << FileStates(UnknownFileState);
+ QTest::newRow("AU") << (AddedFile | UnmergedFile | UnmergedUs) << FileStates(UnknownFileState);
+ QTest::newRow("UD") << (DeletedFile | UnmergedFile | UnmergedThem) << FileStates(UnknownFileState);
+ QTest::newRow("UA") << (AddedFile | UnmergedFile | UnmergedThem) << FileStates(UnknownFileState);
+ QTest::newRow("DU") << (DeletedFile | UnmergedFile | UnmergedUs) << FileStates(UnknownFileState);
+}
+
+void GitPlugin::testStatusParsing()
+{
+ CommitData data;
+ QFETCH(FileStates, first);
+ QFETCH(FileStates, second);
+ QString output = QLatin1String("## master...origin/master [ahead 1]\n");
+ output += QString::fromLatin1(QTest::currentDataTag()) + QLatin1String(" main.cpp\n");
+ data.parseFilesFromStatus(output);
+ QCOMPARE(data.files.at(0).first, first);
+ if (second == UnknownFileState)
+ QCOMPARE(data.files.size(), 1);
+ else
+ QCOMPARE(data.files.at(1).first, second);
+}
+
+void GitPlugin::testDiffFileResolving_data()
+{
+ QTest::addColumn<QByteArray>("header");
+ QTest::addColumn<QByteArray>("fileName");
+
+ QTest::newRow("New") << QByteArray(
+ "diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp\n"
+ "new file mode 100644\n"
+ "index 0000000..40997ff\n"
+ "--- /dev/null\n"
+ "+++ b/src/plugins/git/giteditor.cpp\n"
+ "@@ -0,0 +1,281 @@\n\n")
+ << QByteArray("src/plugins/git/giteditor.cpp");
+ QTest::newRow("Deleted") << QByteArray(
+ "diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp\n"
+ "deleted file mode 100644\n"
+ "index 40997ff..0000000\n"
+ "--- a/src/plugins/git/giteditor.cpp\n"
+ "+++ /dev/null\n"
+ "@@ -1,281 +0,0 @@\n\n")
+ << QByteArray("src/plugins/git/giteditor.cpp");
+ QTest::newRow("Normal") << QByteArray(
+ "diff --git a/src/plugins/git/giteditor.cpp b/src/plugins/git/giteditor.cpp\n"
+ "index 69e0b52..8fc974d 100644\n"
+ "--- a/src/plugins/git/giteditor.cpp\n"
+ "+++ b/src/plugins/git/giteditor.cpp\n"
+ "@@ -49,6 +49,8 @@\n\n")
+ << QByteArray("src/plugins/git/giteditor.cpp");
+}
+
+void GitPlugin::testDiffFileResolving()
+{
+ GitEditor editor(editorParameters + 3, 0);
+ editor.testDiffFileResolving();
+}
+
+void GitPlugin::testLogResolving()
+{
+ QByteArray data(
+ "commit 50a6b54c03219ad74b9f3f839e0321be18daeaf6 (HEAD, origin/master)\n"
+ "Merge: 3587b51 bc93ceb\n"
+ "Author: Junio C Hamano <gitster@pobox.com>\n"
+ "Date: Fri Jan 25 12:53:31 2013 -0800\n"
+ "\n"
+ " Merge branch 'for-junio' of git://bogomips.org/git-svn\n"
+ " \n"
+ " * 'for-junio' of git://bogomips.org/git-svn:\n"
+ " git-svn: Simplify calculation of GIT_DIR\n"
+ " git-svn: cleanup sprintf usage for uppercasing hex\n"
+ "\n"
+ "commit 3587b513bafd7a83d8c816ac1deed72b5e3a27e9\n"
+ "Author: Junio C Hamano <gitster@pobox.com>\n"
+ "Date: Fri Jan 25 12:52:55 2013 -0800\n"
+ "\n"
+ " Update draft release notes to 1.8.2\n"
+ " \n"
+ " Signed-off-by: Junio C Hamano <gitster@pobox.com>\n"
+ );
+ GitEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data,
+ "50a6b54c - Merge branch 'for-junio' of git://bogomips.org/git-svn",
+ "3587b513 - Update draft release notes to 1.8.2");
+}
+#endif
+
Q_EXPORT_PLUGIN(GitPlugin)
diff --git a/src/plugins/git/gitplugin.h b/src/plugins/git/gitplugin.h
index b817495178..4535ec5b6f 100644
--- a/src/plugins/git/gitplugin.h
+++ b/src/plugins/git/gitplugin.h
@@ -91,7 +91,7 @@ public:
static GitPlugin *instance();
- virtual bool initialize(const QStringList &arguments, QString *errorMessage);
+ bool initialize(const QStringList &arguments, QString *errorMessage);
GitVersionControl *gitVersionControl() const;
@@ -100,11 +100,15 @@ public:
GitClient *gitClient() const;
+public slots:
+ void startCommit();
+
private slots:
void diffCurrentFile();
void diffCurrentProject();
void diffRepository();
void submitEditorDiff(const QStringList &unstaged, const QStringList &staged);
+ void submitEditorMerge(const QStringList &unmerged);
void submitCurrentLog();
void logFile();
void blameFile();
@@ -112,8 +116,12 @@ private slots:
void undoFileChanges(bool revertStaging = true);
void undoUnstagedFileChanges();
void resetRepository();
+ void startRevertCommit();
+ void startCherryPickCommit();
void stageFile();
void unstageFile();
+ void gitkForCurrentFile();
+ void gitkForCurrentFolder();
void cleanProject();
void cleanRepository();
void applyCurrentFilePatch();
@@ -121,7 +129,6 @@ private slots:
void gitClientMemberFuncRepositoryAction();
void showCommit();
- void startCommit();
void startAmendCommit();
void stash();
void stashSnapshot();
@@ -131,10 +138,18 @@ private slots:
void fetch();
void pull();
void push();
-
+ void startMergeTool();
+
+#ifdef WITH_TESTS
+ void testStatusParsing_data();
+ void testStatusParsing();
+ void testDiffFileResolving_data();
+ void testDiffFileResolving();
+ void testLogResolving();
+#endif
protected:
- virtual void updateActions(VcsBase::VcsBasePlugin::ActionState);
- virtual bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
+ void updateActions(VcsBase::VcsBasePlugin::ActionState);
+ bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
private:
inline ParameterActionCommandPair
diff --git a/src/plugins/git/gitsettings.cpp b/src/plugins/git/gitsettings.cpp
index f82efe974a..d177bd7074 100644
--- a/src/plugins/git/gitsettings.cpp
+++ b/src/plugins/git/gitsettings.cpp
@@ -29,6 +29,7 @@
#include "gitsettings.h"
+#include <utils/hostosinfo.h>
#include <QCoreApplication>
namespace Git {
@@ -50,11 +51,7 @@ GitSettings::GitSettings()
setSettingsGroup(QLatin1String("Git"));
declareKey(binaryPathKey, QLatin1String("git"));
-#ifdef Q_OS_WIN
- declareKey(timeoutKey, 60);
-#else
- declareKey(timeoutKey, 30);
-#endif
+ declareKey(timeoutKey, Utils::HostOsInfo::isWindowsHost() ? 60 : 30);
declareKey(pullRebaseKey, false);
declareKey(omitAnnotationDateKey, false);
declareKey(ignoreSpaceChangesInDiffKey, true);
diff --git a/src/plugins/git/gitsubmiteditor.cpp b/src/plugins/git/gitsubmiteditor.cpp
index c111dfc9f7..5fdadf234e 100644
--- a/src/plugins/git/gitsubmiteditor.cpp
+++ b/src/plugins/git/gitsubmiteditor.cpp
@@ -27,13 +27,16 @@
**
****************************************************************************/
+#include "commitdata.h"
+#include "gitclient.h"
+#include "gitconstants.h"
+#include "gitplugin.h"
#include "gitsubmiteditor.h"
#include "gitsubmiteditorwidget.h"
-#include "gitconstants.h"
-#include "commitdata.h"
#include <utils/qtcassert.h>
#include <vcsbase/submitfilemodel.h>
+#include <vcsbase/vcsbaseoutputwindow.h>
#include <QDebug>
#include <QStringList>
@@ -42,6 +45,36 @@
namespace Git {
namespace Internal {
+class GitSubmitFileModel : public VcsBase::SubmitFileModel
+{
+public:
+ GitSubmitFileModel(QObject *parent = 0) : VcsBase::SubmitFileModel(parent)
+ { }
+
+ void updateSelections(SubmitFileModel *source)
+ {
+ int j = 0;
+ for (int i = 0; i < rowCount() && j < source->rowCount(); ++i) {
+ CommitData::StateFilePair stateFile = stateFilePair(i);
+ for (; j < source->rowCount(); ++j) {
+ CommitData::StateFilePair sourceStateFile = stateFilePair(j);
+ if (stateFile == sourceStateFile) {
+ setChecked(i, source->checked(j));
+ break;
+ } else if (stateFile < sourceStateFile) {
+ break;
+ }
+ }
+ }
+ }
+
+private:
+ CommitData::StateFilePair stateFilePair(int row)
+ {
+ return CommitData::StateFilePair(static_cast<FileStates>(extraData(row).toInt()), file(row));
+ }
+};
+
/* The problem with git is that no diff can be obtained to for a random
* multiselection of staged/unstaged files; it requires the --cached
* option for staged files. So, we sort apart the diff file lists
@@ -49,9 +82,10 @@ namespace Internal {
GitSubmitEditor::GitSubmitEditor(const VcsBase::VcsBaseSubmitEditorParameters *parameters, QWidget *parent) :
VcsBaseSubmitEditor(parameters, new GitSubmitEditorWidget(parent)),
- m_model(0)
+ m_model(0),
+ m_amend(false)
{
- connect(this, SIGNAL(diffSelectedFiles(QStringList)), this, SLOT(slotDiffSelected(QStringList)));
+ connect(this, SIGNAL(diffSelectedFiles(QList<int>)), this, SLOT(slotDiffSelected(QList<int>)));
}
GitSubmitEditorWidget *GitSubmitEditor::submitEditorWidget()
@@ -61,43 +95,75 @@ GitSubmitEditorWidget *GitSubmitEditor::submitEditorWidget()
void GitSubmitEditor::setCommitData(const CommitData &d)
{
- submitEditorWidget()->setPanelData(d.panelData);
- submitEditorWidget()->setPanelInfo(d.panelInfo);
+ GitSubmitEditorWidget *w = submitEditorWidget();
+ w->setPanelData(d.panelData);
+ w->setPanelInfo(d.panelInfo);
+ w->setHasUnmerged(false);
m_commitEncoding = d.commitEncoding;
+ m_workingDirectory = d.panelInfo.repository;
- m_model = new VcsBase::SubmitFileModel(this);
+ m_model = new GitSubmitFileModel(this);
if (!d.files.isEmpty()) {
for (QList<CommitData::StateFilePair>::const_iterator it = d.files.constBegin();
it != d.files.constEnd(); ++it) {
- const CommitData::FileState state = it->first;
+ const FileStates state = it->first;
const QString file = it->second;
- m_model->addFile(file, CommitData::stateDisplayName(state), state & CommitData::StagedFile,
+ VcsBase::CheckMode checkMode;
+ if (state & UnmergedFile) {
+ checkMode = VcsBase::Uncheckable;
+ w->setHasUnmerged(true);
+ } else if (state & StagedFile) {
+ checkMode = VcsBase::Checked;
+ } else {
+ checkMode = VcsBase::Unchecked;
+ }
+ m_model->addFile(file, CommitData::stateDisplayName(state), checkMode,
QVariant(static_cast<int>(state)));
}
}
setFileModel(m_model, d.panelInfo.repository);
}
-void GitSubmitEditor::slotDiffSelected(const QStringList &files)
+void GitSubmitEditor::setAmend(bool amend)
+{
+ m_amend = amend;
+ setEmptyFileListEnabled(amend); // Allow for just correcting the message
+}
+
+void GitSubmitEditor::slotDiffSelected(const QList<int> &rows)
{
- // Sort it apart into staged/unstaged files
+ // Sort it apart into unmerged/staged/unstaged files
+ QStringList unmergedFiles;
QStringList unstagedFiles;
QStringList stagedFiles;
- const int fileColumn = fileNameColumn();
- const int rowCount = m_model->rowCount();
- for (int r = 0; r < rowCount; r++) {
- const QString fileName = m_model->item(r, fileColumn)->text();
- if (files.contains(fileName)) {
- const CommitData::FileState state = static_cast<CommitData::FileState>(m_model->extraData(r).toInt());
- if (state & CommitData::StagedFile)
- stagedFiles.push_back(fileName);
- else if (state != CommitData::UntrackedFile)
- unstagedFiles.push_back(fileName);
- }
+ foreach (int row, rows) {
+ const QString fileName = m_model->file(row);
+ const FileStates state = static_cast<FileStates>(m_model->extraData(row).toInt());
+ if (state & UnmergedFile)
+ unmergedFiles.push_back(fileName);
+ else if (state & StagedFile)
+ stagedFiles.push_back(fileName);
+ else if (state != UntrackedFile)
+ unstagedFiles.push_back(fileName);
}
if (!unstagedFiles.empty() || !stagedFiles.empty())
emit diff(unstagedFiles, stagedFiles);
+ if (!unmergedFiles.empty())
+ emit merge(unmergedFiles);
+}
+
+void GitSubmitEditor::updateFileModel()
+{
+ if (m_workingDirectory.isEmpty())
+ return;
+ GitClient *client = GitPlugin::instance()->gitClient();
+ QString errorMessage, commitTemplate;
+ CommitData data;
+ if (client->getCommitData(m_workingDirectory, m_amend, &commitTemplate, &data, &errorMessage))
+ setCommitData(data);
+ else
+ VcsBase::VcsBaseOutputWindow::instance()->append(errorMessage);
}
GitSubmitEditorPanelData GitSubmitEditor::panelData() const
diff --git a/src/plugins/git/gitsubmiteditor.h b/src/plugins/git/gitsubmiteditor.h
index 9acc4b8fcb..7a581d1a2f 100644
--- a/src/plugins/git/gitsubmiteditor.h
+++ b/src/plugins/git/gitsubmiteditor.h
@@ -52,22 +52,27 @@ public:
explicit GitSubmitEditor(const VcsBase::VcsBaseSubmitEditorParameters *parameters, QWidget *parent);
void setCommitData(const CommitData &);
+ void setAmend(bool amend);
GitSubmitEditorPanelData panelData() const;
signals:
void diff(const QStringList &unstagedFiles, const QStringList &stagedFiles);
+ void merge(const QStringList &unmergedFiles);
protected:
QByteArray fileContents() const;
+ void updateFileModel();
private slots:
- void slotDiffSelected(const QStringList &);
+ void slotDiffSelected(const QList<int> &rows);
private:
inline GitSubmitEditorWidget *submitEditorWidget();
VcsBase::SubmitFileModel *m_model;
QString m_commitEncoding;
+ bool m_amend;
+ QString m_workingDirectory;
};
} // namespace Internal
diff --git a/src/plugins/git/gitsubmiteditorwidget.cpp b/src/plugins/git/gitsubmiteditorwidget.cpp
index 38f79cab06..319b6f81ff 100644
--- a/src/plugins/git/gitsubmiteditorwidget.cpp
+++ b/src/plugins/git/gitsubmiteditorwidget.cpp
@@ -61,7 +61,7 @@ static QTextCharFormat commentFormat()
class GitSubmitHighlighter : QSyntaxHighlighter {
public:
explicit GitSubmitHighlighter(QTextEdit *parent);
- virtual void highlightBlock(const QString &text);
+ void highlightBlock(const QString &text);
private:
enum State { Header, Comment, Other };
@@ -114,8 +114,9 @@ void GitSubmitHighlighter::highlightBlock(const QString &text)
// ------------------
GitSubmitEditorWidget::GitSubmitEditorWidget(QWidget *parent) :
- Utils::SubmitEditorWidget(parent),
- m_gitSubmitPanel(new QWidget)
+ VcsBase::SubmitEditorWidget(parent),
+ m_gitSubmitPanel(new QWidget),
+ m_hasUnmerged(false)
{
m_gitSubmitPanelUi.setupUi(m_gitSubmitPanel);
insertTopWidget(m_gitSubmitPanel);
@@ -139,6 +140,11 @@ void GitSubmitEditorWidget::setPanelInfo(const GitSubmitEditorPanelInfo &info)
m_gitSubmitPanelUi.branchLabel->setText(info.branch);
}
+void GitSubmitEditorWidget::setHasUnmerged(bool e)
+{
+ m_hasUnmerged = e;
+}
+
GitSubmitEditorPanelData GitSubmitEditorWidget::panelData() const
{
GitSubmitEditorPanelData rc;
@@ -159,7 +165,8 @@ void GitSubmitEditorWidget::setPanelData(const GitSubmitEditorPanelData &data)
bool GitSubmitEditorWidget::canSubmit() const
{
if (m_gitSubmitPanelUi.invalidAuthorLabel->isVisible()
- || m_gitSubmitPanelUi.invalidEmailLabel->isVisible())
+ || m_gitSubmitPanelUi.invalidEmailLabel->isVisible()
+ || m_hasUnmerged)
return false;
return SubmitEditorWidget::canSubmit();
}
@@ -174,11 +181,10 @@ QString GitSubmitEditorWidget::cleanupDescription(const QString &input) const
for (int pos = 0; pos < message.size(); ) {
const int newLinePos = message.indexOf(newLine, pos);
const int startOfNextLine = newLinePos == -1 ? message.size() : newLinePos + 1;
- if (message.at(pos) == hash) {
+ if (message.at(pos) == hash)
message.remove(pos, startOfNextLine - pos);
- } else {
+ else
pos = startOfNextLine;
- }
}
return message;
diff --git a/src/plugins/git/gitsubmiteditorwidget.h b/src/plugins/git/gitsubmiteditorwidget.h
index 9dd73cf69c..11cea18b6f 100644
--- a/src/plugins/git/gitsubmiteditorwidget.h
+++ b/src/plugins/git/gitsubmiteditorwidget.h
@@ -32,7 +32,7 @@
#include "ui_gitsubmitpanel.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
QT_BEGIN_NAMESPACE
class QValidator;
@@ -52,18 +52,17 @@ struct GitSubmitEditorPanelData;
* remaining un-added and untracked files will be added 'unchecked' for the
* user to click. */
-class GitSubmitEditorWidget : public Utils::SubmitEditorWidget
+class GitSubmitEditorWidget : public VcsBase::SubmitEditorWidget
{
Q_OBJECT
public:
explicit GitSubmitEditorWidget(QWidget *parent = 0);
-
GitSubmitEditorPanelData panelData() const;
void setPanelData(const GitSubmitEditorPanelData &data);
-
void setPanelInfo(const GitSubmitEditorPanelInfo &info);
+ void setHasUnmerged(bool e);
protected:
bool canSubmit() const;
@@ -78,6 +77,7 @@ private:
QWidget *m_gitSubmitPanel;
Ui::GitSubmitPanel m_gitSubmitPanelUi;
QValidator *m_emailValidator;
+ bool m_hasUnmerged;
};
} // namespace Internal
diff --git a/src/plugins/git/gitutils.cpp b/src/plugins/git/gitutils.cpp
index f932f225a3..99d4b15bb0 100644
--- a/src/plugins/git/gitutils.cpp
+++ b/src/plugins/git/gitutils.cpp
@@ -87,7 +87,7 @@ bool inputText(QWidget *parent, const QString &title, const QString &prompt, QSt
dialog.setLabelText(prompt);
dialog.setTextValue(*s);
// Nasty hack:
- if (QLineEdit *le = qFindChild<QLineEdit*>(&dialog))
+ if (QLineEdit *le = dialog.findChild<QLineEdit*>())
le->setMinimumWidth(500);
if (dialog.exec() != QDialog::Accepted)
return false;
diff --git a/src/plugins/git/gitversioncontrol.cpp b/src/plugins/git/gitversioncontrol.cpp
index 2f351b2839..85b94493ac 100644
--- a/src/plugins/git/gitversioncontrol.cpp
+++ b/src/plugins/git/gitversioncontrol.cpp
@@ -56,7 +56,7 @@ QString GitVersionControl::displayName() const
Core::Id GitVersionControl::id() const
{
- return VcsBase::Constants::VCS_ID_GIT;
+ return Core::Id(VcsBase::Constants::VCS_ID_GIT);
}
bool GitVersionControl::isConfigured() const
@@ -140,7 +140,12 @@ QString GitVersionControl::vcsGetRepositoryURL(const QString &directory)
return m_client->vcsGetRepositoryURL(directory);
}
-/* Snapshots are implement using stashes, relying on stash messages for
+QString GitVersionControl::vcsTopic(const QString &directory)
+{
+ return m_client->synchronousTopic(directory);
+}
+
+/* Snapshots are implemented using stashes, relying on stash messages for
* naming as the actual stash names (stash{n}) are rotated as one adds stashes.
* Note that the snapshot interface does not care whether we have an unmodified
* repository state, in which case git refuses to stash.
@@ -161,10 +166,10 @@ QString GitVersionControl::vcsCreateSnapshot(const QString &topLevel)
return stashMessage;
if (repositoryUnchanged) {
// For unchanged repository state: return identifier + top revision
- QString topRevision;
- QString branch;
- if (!m_client->synchronousTopRevision(topLevel, &topRevision, &branch))
+ QString topRevision = m_client->synchronousTopRevision(topLevel);
+ if (topRevision.isEmpty())
return QString();
+ QString branch = m_client->synchronousTopic(topLevel);
const QChar colon = QLatin1Char(':');
QString id = QLatin1String(stashRevisionIdC);
id += colon;
@@ -183,7 +188,7 @@ QStringList GitVersionControl::vcsSnapshots(const QString &topLevel)
return QStringList();
// Return the git stash 'message' as identifier, ignoring empty ones
QStringList rc;
- foreach(const Stash &s, stashes)
+ foreach (const Stash &s, stashes)
if (!s.message.isEmpty())
rc.push_back(s.message);
return rc;
@@ -201,15 +206,19 @@ bool GitVersionControl::vcsRestoreSnapshot(const QString &topLevel, const QStrin
break;
const QString branch = tokens.at(1);
const QString revision = tokens.at(2);
- success = m_client->synchronousReset(topLevel)
- && m_client->synchronousCheckoutBranch(topLevel, branch)
- && m_client->synchronousCheckoutFiles(topLevel, QStringList(), revision);
+ success = m_client->synchronousReset(topLevel);
+ if (success && !branch.isEmpty()) {
+ success = m_client->synchronousCheckout(topLevel, branch) &&
+ m_client->synchronousCheckoutFiles(topLevel, QStringList(), revision);
+ } else {
+ success = m_client->synchronousCheckout(topLevel, revision);
+ }
} else {
// Restore stash if it can be resolved.
QString stashName;
success = m_client->stashNameFromMessage(topLevel, name, &stashName)
&& m_client->synchronousReset(topLevel)
- && m_client->synchronousStashRestore(topLevel, stashName);
+ && m_client->synchronousStashRestore(topLevel, stashName, true);
}
} while (false);
return success;
diff --git a/src/plugins/git/gitversioncontrol.h b/src/plugins/git/gitversioncontrol.h
index 7251357804..6baa152077 100644
--- a/src/plugins/git/gitversioncontrol.h
+++ b/src/plugins/git/gitversioncontrol.h
@@ -64,6 +64,7 @@ public:
bool vcsRemoveSnapshot(const QString &topLevel, const QString &name);
bool vcsAnnotate(const QString &file, int line);
+ QString vcsTopic(const QString &directory);
void emitFilesChanged(const QStringList &);
void emitRepositoryChanged(const QString &);
diff --git a/src/plugins/git/mergetool.cpp b/src/plugins/git/mergetool.cpp
new file mode 100644
index 0000000000..d7b42a70b5
--- /dev/null
+++ b/src/plugins/git/mergetool.cpp
@@ -0,0 +1,308 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "gitclient.h"
+#include "gitplugin.h"
+#include "mergetool.h"
+
+#include <vcsbase/vcsbaseoutputwindow.h>
+
+#include <QFile>
+#include <QMessageBox>
+#include <QProcess>
+#include <QPushButton>
+
+namespace Git {
+namespace Internal {
+
+class MergeToolProcess : public QProcess
+{
+public:
+ MergeToolProcess(QObject *parent = 0) :
+ QProcess(parent),
+ m_window(VcsBase::VcsBaseOutputWindow::instance())
+ {
+ }
+
+protected:
+ qint64 readData(char *data, qint64 maxlen)
+ {
+ qint64 res = QProcess::readData(data, maxlen);
+ if (res > 0)
+ m_window->append(QString::fromLocal8Bit(data, res));
+ return res;
+ }
+
+ qint64 writeData(const char *data, qint64 len)
+ {
+ if (len > 0)
+ m_window->append(QString::fromLocal8Bit(data, len));
+ return QProcess::writeData(data, len);
+ }
+
+private:
+ VcsBase::VcsBaseOutputWindow *m_window;
+};
+
+MergeTool::MergeTool(QObject *parent) :
+ QObject(parent),
+ m_process(0),
+ m_gitClient(GitPlugin::instance()->gitClient())
+{
+}
+
+MergeTool::~MergeTool()
+{
+ delete m_process;
+}
+
+bool MergeTool::start(const QString &workingDirectory, const QStringList &files)
+{
+ QStringList arguments;
+ arguments << QLatin1String("mergetool") << QLatin1String("-y");
+ if (!files.isEmpty()) {
+ if (m_gitClient->gitVersion() < 0x010708) {
+ QMessageBox::warning(0, tr("Error"), tr("Files input for mergetool requires git >= 1.7.8"));
+ return false;
+ }
+ arguments << files;
+ }
+ m_process = new MergeToolProcess(this);
+ m_process->setWorkingDirectory(workingDirectory);
+ const QString binary = m_gitClient->gitBinaryPath();
+ VcsBase::VcsBaseOutputWindow::instance()->appendCommand(workingDirectory, binary, arguments);
+ m_process->start(binary, arguments);
+ if (m_process->waitForStarted()) {
+ connect(m_process, SIGNAL(finished(int)), this, SLOT(done()));
+ connect(m_process, SIGNAL(readyRead()), this, SLOT(readData()));
+ }
+ else {
+ delete m_process;
+ m_process = 0;
+ return false;
+ }
+ return true;
+}
+
+MergeTool::FileState MergeTool::waitAndReadStatus(QString &extraInfo)
+{
+ QByteArray state;
+ if (m_process->canReadLine() || (m_process->waitForReadyRead(500) && m_process->canReadLine())) {
+ state = m_process->readLine().trimmed();
+ // " {local}: modified file"
+ // " {remote}: deleted"
+ if (!state.isEmpty()) {
+ state = state.mid(state.indexOf(':') + 2);
+ if (state == "deleted")
+ return DeletedState;
+ if (state.startsWith("modified"))
+ return ModifiedState;
+ if (state.startsWith("created"))
+ return CreatedState;
+ QByteArray submodulePrefix("submodule commit ");
+ // " {local}: submodule commit <hash>"
+ if (state.startsWith(submodulePrefix)) {
+ extraInfo = QString::fromLocal8Bit(state.mid(submodulePrefix.size()));
+ return SubmoduleState;
+ }
+ // " {local}: a symbolic link -> 'foo.cpp'"
+ QByteArray symlinkPrefix("a symbolic link -> '");
+ if (state.startsWith(symlinkPrefix)) {
+ extraInfo = QString::fromLocal8Bit(state.mid(symlinkPrefix.size()));
+ extraInfo.chop(1); // remove last quote
+ return SymbolicLinkState;
+ }
+ }
+ }
+ return UnknownState;
+}
+
+static MergeTool::MergeType mergeType(const QByteArray &type)
+{
+ if (type == "Normal")
+ return MergeTool::NormalMerge;
+ if (type == "Deleted")
+ return MergeTool::DeletedMerge;
+ if (type == "Submodule")
+ return MergeTool::SubmoduleMerge;
+ else
+ return MergeTool::SymbolicLinkMerge;
+}
+
+QString MergeTool::mergeTypeName()
+{
+ switch (m_mergeType) {
+ case NormalMerge: return tr("Normal");
+ case SubmoduleMerge: return tr("Submodule");
+ case DeletedMerge: return tr("Deleted");
+ case SymbolicLinkMerge: return tr("Symbolic link");
+ }
+ return QString();
+}
+
+QString MergeTool::stateName(MergeTool::FileState state, const QString &extraInfo)
+{
+ switch (state) {
+ case ModifiedState: return tr("Modified");
+ case CreatedState: return tr("Created");
+ case DeletedState: return tr("Deleted");
+ case SubmoduleState: return tr("Submodule commit %1").arg(extraInfo);
+ case SymbolicLinkState: return tr("Symbolic link -> %1").arg(extraInfo);
+ default: break;
+ }
+ return QString();
+}
+
+void MergeTool::chooseAction()
+{
+ m_merging = (m_mergeType == NormalMerge);
+ if (m_merging)
+ return;
+ QMessageBox msgBox;
+ msgBox.setWindowTitle(tr("Merge Conflict"));
+ msgBox.setIcon(QMessageBox::Question);
+ msgBox.setStandardButtons(QMessageBox::Abort);
+ msgBox.setText(tr("%1 merge conflict for '%2'\nLocal: %3\nRemote: %4")
+ .arg(mergeTypeName())
+ .arg(m_fileName)
+ .arg(stateName(m_localState, m_localInfo))
+ .arg(stateName(m_remoteState, m_remoteInfo))
+ );
+ switch (m_mergeType) {
+ case SubmoduleMerge:
+ case SymbolicLinkMerge:
+ addButton(&msgBox, tr("&Local"), 'l');
+ addButton(&msgBox, tr("&Remote"), 'r');
+ break;
+ case DeletedMerge:
+ if (m_localState == CreatedState || m_remoteState == CreatedState)
+ addButton(&msgBox, tr("&Created"), 'c');
+ else
+ addButton(&msgBox, tr("&Modified"), 'm');
+ addButton(&msgBox, tr("&Deleted"), 'd');
+ break;
+ default:
+ break;
+ }
+
+ msgBox.exec();
+ QByteArray ba;
+ QVariant key;
+ QAbstractButton *button = msgBox.clickedButton();
+ if (button)
+ key = button->property("key");
+ // either the message box was closed without clicking anything, or abort was clicked
+ if (!key.isValid())
+ key = QVariant(QLatin1Char('a')); // abort
+ ba.append(key.toChar().toLatin1());
+ ba.append('\n');
+ m_process->write(ba);
+}
+
+void MergeTool::addButton(QMessageBox *msgBox, const QString &text, char key)
+{
+ msgBox->addButton(text, QMessageBox::AcceptRole)->setProperty("key", key);
+}
+
+void MergeTool::readData()
+{
+ while (m_process->bytesAvailable()) {
+ QByteArray line = m_process->canReadLine() ? m_process->readLine() : m_process->readAllStandardOutput();
+ // {Normal|Deleted|Submodule|Symbolic link} merge conflict for 'foo.cpp'
+ int index = line.indexOf(" merge conflict for ");
+ if (index != -1) {
+ m_mergeType = mergeType(line.left(index));
+ int quote = line.indexOf('\'');
+ m_fileName = QString::fromLocal8Bit(line.mid(quote + 1, line.lastIndexOf('\'') - quote - 1));
+ m_localState = waitAndReadStatus(m_localInfo);
+ m_remoteState = waitAndReadStatus(m_remoteInfo);
+ chooseAction();
+ } else if (m_merging && line.startsWith("Continue merging")) {
+ if (QMessageBox::question(0, tr("Continue Merging"),
+ tr("Continue merging other unresolved paths?"),
+ QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
+ m_process->write("y\n");
+ } else {
+ m_process->write("n\n");
+ }
+ }
+ }
+}
+
+void MergeTool::continuePreviousGitCommand(const QString &msgBoxTitle, const QString &msgBoxText,
+ const QString &buttonName, const QString &gitCommand)
+{
+ QString workingDirectory = m_process->workingDirectory();
+ QMessageBox msgBox;
+ QPushButton *commandButton = msgBox.addButton(buttonName, QMessageBox::AcceptRole);
+ QPushButton *abortButton = msgBox.addButton(QMessageBox::Abort);
+ msgBox.addButton(QMessageBox::Ignore);
+ msgBox.setIcon(QMessageBox::Question);
+ msgBox.setWindowTitle(msgBoxTitle);
+ msgBox.setText(msgBoxText);
+ msgBox.exec();
+
+ if (msgBox.clickedButton() == commandButton) { // Continue
+ if (gitCommand == QLatin1String("rebase"))
+ m_gitClient->synchronousCommandContinue(workingDirectory, gitCommand);
+ else
+ GitPlugin::instance()->startCommit();
+ } else if (msgBox.clickedButton() == abortButton) { // Abort
+ m_gitClient->synchronousAbortCommand(workingDirectory, gitCommand);
+ }
+}
+
+void MergeTool::done()
+{
+ VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
+ int exitCode = m_process->exitCode();
+ if (!exitCode) {
+ outputWindow->append(tr("Merge tool process finished successully"));
+ QString gitDir = m_gitClient->findGitDirForRepository(m_process->workingDirectory());
+
+ if (QFile::exists(gitDir + QLatin1String("/rebase-apply/rebasing"))) {
+ continuePreviousGitCommand(tr("Continue Rebase"), tr("Continue rebase?"),
+ tr("Continue"), QLatin1String("rebase"));
+ } else if (QFile::exists(gitDir + QLatin1String("/REVERT_HEAD"))) {
+ continuePreviousGitCommand(tr("Continue Revert"),
+ tr("You need to commit changes to finish revert.\nCommit now?"),
+ tr("Commit"), QLatin1String("revert"));
+ } else if (QFile::exists(gitDir + QLatin1String("/CHERRY_PICK_HEAD"))) {
+ continuePreviousGitCommand(tr("Continue Cherry-Pick"),
+ tr("You need to commit changes to finish cherry-pick.\nCommit now?"),
+ tr("Commit"), QLatin1String("cherry-pick"));
+ }
+ } else {
+ outputWindow->append(tr("Merge tool process terminated with exit code %1").arg(exitCode));
+ }
+ deleteLater();
+}
+
+} // namespace Internal
+} // namespace Git
diff --git a/src/plugins/git/mergetool.h b/src/plugins/git/mergetool.h
new file mode 100644
index 0000000000..37fbe75fb8
--- /dev/null
+++ b/src/plugins/git/mergetool.h
@@ -0,0 +1,98 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef MERGETOOL_H
+#define MERGETOOL_H
+
+#include <QObject>
+#include <QStringList>
+
+QT_BEGIN_NAMESPACE
+class QMessageBox;
+QT_END_NAMESPACE
+
+namespace Git {
+namespace Internal {
+
+class MergeToolProcess;
+class GitClient;
+
+class MergeTool : public QObject
+{
+ Q_OBJECT
+
+ enum FileState {
+ UnknownState,
+ ModifiedState,
+ CreatedState,
+ DeletedState,
+ SubmoduleState,
+ SymbolicLinkState
+ };
+
+public:
+ explicit MergeTool(QObject *parent = 0);
+ ~MergeTool();
+ bool start(const QString &workingDirectory, const QStringList &files = QStringList());
+
+ enum MergeType {
+ NormalMerge,
+ SubmoduleMerge,
+ DeletedMerge,
+ SymbolicLinkMerge
+ };
+
+private slots:
+ void readData();
+ void done();
+
+private:
+ FileState waitAndReadStatus(QString &extraInfo);
+ QString mergeTypeName();
+ QString stateName(FileState state, const QString &extraInfo);
+ void chooseAction();
+ void addButton(QMessageBox *msgBox, const QString &text, char key);
+ void continuePreviousGitCommand(const QString &msgBoxTitle, const QString &msgBoxText,
+ const QString &buttonName, const QString &gitCommand);
+
+ MergeToolProcess *m_process;
+ MergeType m_mergeType;
+ QString m_fileName;
+ FileState m_localState;
+ QString m_localInfo;
+ FileState m_remoteState;
+ QString m_remoteInfo;
+ GitClient *m_gitClient;
+ bool m_merging;
+};
+
+} // namespace Internal
+} // namespace Git
+
+#endif // MERGETOOL_H
diff --git a/src/plugins/git/remotedialog.h b/src/plugins/git/remotedialog.h
index 3e80a36a05..92ecdbdc94 100644
--- a/src/plugins/git/remotedialog.h
+++ b/src/plugins/git/remotedialog.h
@@ -89,7 +89,7 @@ public slots:
private slots:
protected:
- virtual void changeEvent(QEvent *e);
+ void changeEvent(QEvent *e);
private:
Ui::RemoteDialog *m_ui;
diff --git a/src/plugins/git/remotemodel.cpp b/src/plugins/git/remotemodel.cpp
index e327515ad8..9f6fa88af9 100644
--- a/src/plugins/git/remotemodel.cpp
+++ b/src/plugins/git/remotemodel.cpp
@@ -185,8 +185,9 @@ void RemoteModel::clear()
{
if (m_remotes.isEmpty())
return;
+ beginResetModel();
m_remotes.clear();
- reset();
+ endResetModel();
}
bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage)
@@ -199,6 +200,7 @@ bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage
return false;
// Parse output
m_workingDirectory = workingDirectory;
+ beginResetModel();
m_remotes.clear();
const QStringList lines = output.split(QLatin1Char('\n'));
for (int r = 0; r < lines.count(); ++r) {
@@ -206,7 +208,7 @@ bool RemoteModel::refresh(const QString &workingDirectory, QString *errorMessage
if (newRemote.parse(lines.at(r)))
m_remotes.push_back(newRemote);
}
- reset();
+ endResetModel();
return true;
}
diff --git a/src/plugins/git/resetdialog.cpp b/src/plugins/git/resetdialog.cpp
index 090b832748..cfcffec34d 100644
--- a/src/plugins/git/resetdialog.cpp
+++ b/src/plugins/git/resetdialog.cpp
@@ -33,11 +33,12 @@
#include <QTreeView>
#include <QLabel>
-#include <QDialogButtonBox>
#include <QPushButton>
#include <QStandardItemModel>
+#include <QDialogButtonBox>
#include <QItemSelectionModel>
#include <QVBoxLayout>
+#include <QComboBox>
#include <QDir>
namespace Git {
@@ -55,21 +56,31 @@ ResetDialog::ResetDialog(QWidget *parent)
, m_treeView(new QTreeView(this))
, m_model(new QStandardItemModel(0, ColumnCount, this))
, m_dialogButtonBox(new QDialogButtonBox(this))
+ , m_resetTypeComboBox(new QComboBox(this))
{
QStringList headers;
headers << tr("Sha1")<< tr("Subject");
m_model->setHorizontalHeaderLabels(headers);
QVBoxLayout *layout = new QVBoxLayout(this);
- layout->addWidget(new QLabel(tr("Reset to:")));
+ layout->addWidget(new QLabel(tr("Reset to:"), this));
m_treeView->setModel(m_model);
m_treeView->setMinimumWidth(300);
m_treeView->setUniformRowHeights(true);
m_treeView->setRootIsDecorated(false);
m_treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
layout->addWidget(m_treeView);
- layout->addWidget(m_dialogButtonBox);
+ QHBoxLayout *popUpLayout = new QHBoxLayout();
+ popUpLayout->addWidget(new QLabel(tr("Reset type:"), this));
+ m_resetTypeComboBox->addItem(tr("Hard Reset"), HardReset);
+ m_resetTypeComboBox->addItem(tr("Soft Reset"), SoftReset);
+ popUpLayout->addWidget(m_resetTypeComboBox);
+ popUpLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored));
+
+ popUpLayout->addWidget(m_dialogButtonBox);
m_dialogButtonBox->addButton(QDialogButtonBox::Cancel);
QPushButton *okButton = m_dialogButtonBox->addButton(QDialogButtonBox::Ok);
+ layout->addLayout(popUpLayout);
+
connect(m_treeView, SIGNAL(doubleClicked(QModelIndex)),
okButton, SLOT(animateClick()));
@@ -101,6 +112,11 @@ QString ResetDialog::commit() const
return QString();
}
+ResetType ResetDialog::resetType() const
+{
+ return static_cast<ResetType>(m_resetTypeComboBox->itemData(m_resetTypeComboBox->currentIndex()).toInt());
+}
+
bool ResetDialog::populateLog(const QString &repository)
{
if (const int rowCount = m_model->rowCount())
diff --git a/src/plugins/git/resetdialog.h b/src/plugins/git/resetdialog.h
index 9652eab281..5e781bb59f 100644
--- a/src/plugins/git/resetdialog.h
+++ b/src/plugins/git/resetdialog.h
@@ -35,6 +35,7 @@
QT_BEGIN_NAMESPACE
class QTreeView;
class QDialogButtonBox;
+class QComboBox;
class QStandardItemModel;
class QStandardItem;
QT_END_NAMESPACE
@@ -43,7 +44,12 @@ namespace Git {
namespace Internal {
// A dialog that lists SHA1 and subject of the changes
-// for reset --hard.
+// for reset --hard and --soft.
+
+enum ResetType {
+ HardReset,
+ SoftReset
+};
class ResetDialog : public QDialog
{
@@ -54,6 +60,7 @@ public:
bool runDialog(const QString &repository);
QString commit() const;
+ ResetType resetType() const;
private:
bool populateLog(const QString &repository);
@@ -62,6 +69,7 @@ private:
QTreeView *m_treeView;
QStandardItemModel *m_model;
QDialogButtonBox *m_dialogButtonBox;
+ QComboBox *m_resetTypeComboBox;
};
} // namespace Internal
diff --git a/src/plugins/git/settingspage.cpp b/src/plugins/git/settingspage.cpp
index 1dfe04f776..b017d5b748 100644
--- a/src/plugins/git/settingspage.cpp
+++ b/src/plugins/git/settingspage.cpp
@@ -33,6 +33,7 @@
#include "gitclient.h"
#include <vcsbase/vcsbaseconstants.h>
+#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <QCoreApplication>
@@ -50,19 +51,19 @@ SettingsPageWidget::SettingsPageWidget(QWidget *parent) :
QWidget(parent)
{
m_ui.setupUi(this);
-#ifdef Q_OS_WIN
- const QByteArray currentHome = qgetenv("HOME");
- const QString toolTip
- = tr("Set the environment variable HOME to '%1'\n(%2).\n"
- "This causes msysgit to look for the SSH-keys in that location\n"
- "instead of its installation directory when run outside git bash.").
- arg(QDir::homePath(),
- currentHome.isEmpty() ? tr("not currently set") :
- tr("currently set to '%1'").arg(QString::fromLocal8Bit(currentHome)));
- m_ui.winHomeCheckBox->setToolTip(toolTip);
-#else
- m_ui.winHomeCheckBox->setVisible(false);
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ const QByteArray currentHome = qgetenv("HOME");
+ const QString toolTip
+ = tr("Set the environment variable HOME to '%1'\n(%2).\n"
+ "This causes msysgit to look for the SSH-keys in that location\n"
+ "instead of its installation directory when run outside git bash.").
+ arg(QDir::homePath(),
+ currentHome.isEmpty() ? tr("not currently set") :
+ tr("currently set to '%1'").arg(QString::fromLocal8Bit(currentHome)));
+ m_ui.winHomeCheckBox->setToolTip(toolTip);
+ } else {
+ m_ui.winHomeCheckBox->setVisible(false);
+ }
m_ui.repBrowserCommandPathChooser->setExpectedKind(Utils::PathChooser::ExistingCommand);
m_ui.repBrowserCommandPathChooser->setPromptDialogTitle(tr("Git Repository Browser Command"));
}
@@ -118,7 +119,7 @@ QString SettingsPageWidget::searchKeywords() const
SettingsPage::SettingsPage() :
m_widget(0)
{
- setId(QLatin1String(VcsBase::Constants::VCS_ID_GIT));
+ setId(VcsBase::Constants::VCS_ID_GIT);
setDisplayName(tr("Git"));
}
diff --git a/src/plugins/git/settingspage.h b/src/plugins/git/settingspage.h
index fc67182fd1..e936eaf772 100644
--- a/src/plugins/git/settingspage.h
+++ b/src/plugins/git/settingspage.h
@@ -67,9 +67,6 @@ class SettingsPage : public VcsBase::VcsBaseOptionsPage
public:
SettingsPage();
- QString id() const;
- QString displayName() const;
-
QWidget *createPage(QWidget *parent);
void apply();
void finish() { }
diff --git a/src/plugins/git/stashdialog.cpp b/src/plugins/git/stashdialog.cpp
index 74dcc33040..dcbe06dc7e 100644
--- a/src/plugins/git/stashdialog.cpp
+++ b/src/plugins/git/stashdialog.cpp
@@ -95,7 +95,7 @@ void StashModel::setStashes(const QList<Stash> &stashes)
m_stashes = stashes;
if (const int rows = rowCount())
removeRows(0, rows);
- foreach(const Stash &s, stashes)
+ foreach (const Stash &s, stashes)
appendRow(stashModelRowItems(s));
}
@@ -185,7 +185,7 @@ void StashDialog::refresh(const QString &repository, bool force)
gitClient()->synchronousStashList(m_repository, &stashes);
m_model->setStashes(stashes);
if (!stashes.isEmpty()) {
- for(int c = 0; c < ColumnCount; c++)
+ for (int c = 0; c < ColumnCount; c++)
ui->stashView->resizeColumnToContents(c);
}
}
@@ -198,11 +198,10 @@ void StashDialog::deleteAll()
if (!ask(title, tr("Do you want to delete all stashes?")))
return;
QString errorMessage;
- if (gitClient()->synchronousStashRemove(m_repository, QString(), &errorMessage)) {
+ if (gitClient()->synchronousStashRemove(m_repository, QString(), &errorMessage))
refresh(m_repository, true);
- } else {
+ else
warning(title, errorMessage);
- }
}
void StashDialog::deleteSelection()
@@ -288,7 +287,7 @@ bool StashDialog::promptForRestore(QString *stash,
{
const QString stashIn = *stash;
bool modifiedPromptShown = false;
- switch (gitClient()->gitStatus(m_repository, false, 0, errorMessage)) {
+ switch (gitClient()->gitStatus(m_repository, StatusMode(NoUntracked | NoSubmodules), 0, errorMessage)) {
case GitClient::StatusFailed:
return false;
case GitClient::StatusChanged: {
@@ -339,7 +338,7 @@ void StashDialog::restoreCurrent()
// Make sure repository is not modified, restore. The command will
// output to window on success.
const bool success = promptForRestore(&name, 0, &errorMessage)
- && gitClient()->synchronousStashRestore(m_repository, name, QString(), &errorMessage);
+ && gitClient()->synchronousStashRestore(m_repository, name, false, QString(), &errorMessage);
if (success) {
refresh(m_repository, true); // Might have stashed away local changes.
} else {
@@ -356,7 +355,7 @@ void StashDialog::restoreCurrentInBranch()
QString branch;
QString name = m_model->at(index).name;
const bool success = promptForRestore(&name, &branch, &errorMessage)
- && gitClient()->synchronousStashRestore(m_repository, name, branch, &errorMessage);
+ && gitClient()->synchronousStashRestore(m_repository, name, false, branch, &errorMessage);
if (success) {
refresh(m_repository, true); // git deletes the stash, unfortunately.
} else {
@@ -379,7 +378,7 @@ int StashDialog::currentRow() const
QList<int> StashDialog::selectedRows() const
{
QList<int> rc;
- foreach(const QModelIndex &proxyIndex, ui->stashView->selectionModel()->selectedRows()) {
+ foreach (const QModelIndex &proxyIndex, ui->stashView->selectionModel()->selectedRows()) {
const QModelIndex index = m_proxyModel->mapToSource(proxyIndex);
if (index.isValid())
rc.push_back(index.row());
diff --git a/src/plugins/glsleditor/glslcompletionassist.cpp b/src/plugins/glsleditor/glslcompletionassist.cpp
index 4bd43a3dd2..ffbe19cee2 100644
--- a/src/plugins/glsleditor/glslcompletionassist.cpp
+++ b/src/plugins/glsleditor/glslcompletionassist.cpp
@@ -201,15 +201,15 @@ int GLSLFunctionHintProposalModel::activeArgument(const QString &prefix) const
// -----------------------------
GLSLCompletionAssistProcessor::GLSLCompletionAssistProcessor()
: m_startPosition(0)
- , m_keywordIcon(":/glsleditor/images/keyword.png")
- , m_varIcon(":/glsleditor/images/var.png")
- , m_functionIcon(":/glsleditor/images/func.png")
- , m_typeIcon(":/glsleditor/images/type.png")
- , m_constIcon(":/glsleditor/images/const.png")
- , m_attributeIcon(":/glsleditor/images/attribute.png")
- , m_uniformIcon(":/glsleditor/images/uniform.png")
- , m_varyingIcon(":/glsleditor/images/varying.png")
- , m_otherIcon(":/glsleditor/images/other.png")
+ , m_keywordIcon(QLatin1String(":/glsleditor/images/keyword.png"))
+ , m_varIcon(QLatin1String(":/glsleditor/images/var.png"))
+ , m_functionIcon(QLatin1String(":/glsleditor/images/func.png"))
+ , m_typeIcon(QLatin1String(":/glsleditor/images/type.png"))
+ , m_constIcon(QLatin1String(":/glsleditor/images/const.png"))
+ , m_attributeIcon(QLatin1String(":/glsleditor/images/attribute.png"))
+ , m_uniformIcon(QLatin1String(":/glsleditor/images/uniform.png"))
+ , m_varyingIcon(QLatin1String(":/glsleditor/images/varying.png"))
+ , m_otherIcon(QLatin1String(":/glsleditor/images/other.png"))
{}
GLSLCompletionAssistProcessor::~GLSLCompletionAssistProcessor()
diff --git a/src/plugins/glsleditor/glsleditor.cpp b/src/plugins/glsleditor/glsleditor.cpp
index 28790bc3b6..9e17f4121a 100644
--- a/src/plugins/glsleditor/glsleditor.cpp
+++ b/src/plugins/glsleditor/glsleditor.cpp
@@ -57,7 +57,6 @@
#include <texteditor/texteditorsettings.h>
#include <texteditor/syntaxhighlighter.h>
#include <texteditor/refactoroverlay.h>
-#include <texteditor/tooltip/tooltip.h>
#include <qmldesigner/qmldesignerconstants.h>
#include <utils/changeset.h>
#include <utils/uncommentselection.h>
@@ -73,6 +72,7 @@
#include <QInputDialog>
#include <QToolBar>
#include <QTreeView>
+#include <QSharedPointer>
using namespace GLSL;
using namespace GLSLEditor;
@@ -159,7 +159,7 @@ GLSLTextEditorWidget::GLSLTextEditorWidget(QWidget *parent) :
connect(this, SIGNAL(textChanged()), this, SLOT(updateDocument()));
- new Highlighter(baseTextDocument());
+ new Highlighter(baseTextDocument().data());
// if (m_modelManager) {
// m_semanticHighlighter->setModelManager(m_modelManager);
@@ -199,7 +199,7 @@ Core::IEditor *GLSLEditorEditable::duplicate(QWidget *parent)
Core::Id GLSLEditorEditable::id() const
{
- return GLSLEditor::Constants::C_GLSLEDITOR_ID;
+ return Core::Id(GLSLEditor::Constants::C_GLSLEDITOR_ID);
}
bool GLSLEditorEditable::open(QString *errorString, const QString &fileName, const QString &realFileName)
diff --git a/src/plugins/glsleditor/glsleditor.qbs b/src/plugins/glsleditor/glsleditor.qbs
index 3df8879e6f..6627277314 100644
--- a/src/plugins/glsleditor/glsleditor.qbs
+++ b/src/plugins/glsleditor/glsleditor.qbs
@@ -13,43 +13,34 @@ QtcPlugin {
Depends { name: "GLSL" }
Depends { name: "CPlusPlus" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "../..",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
+ "GLSLEditor.mimetypes.xml",
+ "glslautocompleter.cpp",
+ "glslautocompleter.h",
+ "glslcompletionassist.cpp",
+ "glslcompletionassist.h",
+ "glsleditor.cpp",
"glsleditor.h",
+ "glsleditor.qrc",
"glsleditor_global.h",
+ "glsleditoractionhandler.cpp",
"glsleditoractionhandler.h",
"glsleditorconstants.h",
+ "glsleditoreditable.cpp",
"glsleditoreditable.h",
+ "glsleditorfactory.cpp",
"glsleditorfactory.h",
+ "glsleditorplugin.cpp",
"glsleditorplugin.h",
+ "glslfilewizard.cpp",
"glslfilewizard.h",
+ "glslhighlighter.cpp",
"glslhighlighter.h",
- "glslautocompleter.h",
- "glslindenter.h",
+ "glslhoverhandler.cpp",
"glslhoverhandler.h",
- "glslcompletionassist.h",
- "reuse.h",
- "glsleditor.cpp",
- "glsleditoractionhandler.cpp",
- "glsleditoreditable.cpp",
- "glsleditorfactory.cpp",
- "glsleditorplugin.cpp",
- "glslfilewizard.cpp",
- "glslhighlighter.cpp",
- "glslautocompleter.cpp",
"glslindenter.cpp",
- "glslhoverhandler.cpp",
- "glslcompletionassist.cpp",
+ "glslindenter.h",
"reuse.cpp",
- "glsleditor.qrc",
- "GLSLEditor.mimetypes.xml"
+ "reuse.h",
]
}
-
diff --git a/src/plugins/glsleditor/glsleditorfactory.cpp b/src/plugins/glsleditor/glsleditorfactory.cpp
index d9c8d2f5de..7f221c698d 100644
--- a/src/plugins/glsleditor/glsleditorfactory.cpp
+++ b/src/plugins/glsleditor/glsleditorfactory.cpp
@@ -64,7 +64,7 @@ GLSLEditorFactory::GLSLEditorFactory(QObject *parent)
Core::Id GLSLEditorFactory::id() const
{
- return C_GLSLEDITOR_ID;
+ return Core::Id(C_GLSLEDITOR_ID);
}
QString GLSLEditorFactory::displayName() const
diff --git a/src/plugins/glsleditor/glsleditorplugin.cpp b/src/plugins/glsleditor/glsleditorplugin.cpp
index 605119e4b4..08d44956d5 100644
--- a/src/plugins/glsleditor/glsleditorplugin.cpp
+++ b/src/plugins/glsleditor/glsleditorplugin.cpp
@@ -65,9 +65,11 @@
#include <QMenu>
#include <QAction>
-using namespace GLSLEditor;
-using namespace GLSLEditor::Internal;
-using namespace GLSLEditor::Constants;
+using namespace Core;
+using namespace TextEditor;
+
+namespace GLSLEditor {
+namespace Internal {
GLSLEditorPlugin *GLSLEditorPlugin::m_instance = 0;
@@ -104,7 +106,7 @@ GLSLEditorPlugin::~GLSLEditorPlugin()
bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage)
{
- if (!Core::ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/glsleditor/GLSLEditor.mimetypes.xml"), errorMessage))
+ if (!ICore::mimeDatabase()->addMimeTypes(QLatin1String(":/glsleditor/GLSLEditor.mimetypes.xml"), errorMessage))
return false;
// m_modelManager = new ModelManager(this);
@@ -112,42 +114,40 @@ bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *er
addAutoReleasedObject(new GLSLHoverHandler(this));
- Core::Context context(GLSLEditor::Constants::C_GLSLEDITOR_ID);
-
m_editor = new GLSLEditorFactory(this);
addObject(m_editor);
addAutoReleasedObject(new GLSLCompletionAssistProvider);
- m_actionHandler = new TextEditor::TextEditorActionHandler(GLSLEditor::Constants::C_GLSLEDITOR_ID,
- TextEditor::TextEditorActionHandler::Format
- | TextEditor::TextEditorActionHandler::UnCommentSelection
- | TextEditor::TextEditorActionHandler::UnCollapseAll);
+ m_actionHandler = new TextEditorActionHandler(Constants::C_GLSLEDITOR_ID,
+ TextEditorActionHandler::Format
+ | TextEditorActionHandler::UnCommentSelection
+ | TextEditorActionHandler::UnCollapseAll);
m_actionHandler->initializeActions();
- Core::ActionContainer *contextMenu = Core::ActionManager::createMenu(GLSLEditor::Constants::M_CONTEXT);
- Core::ActionContainer *glslToolsMenu = Core::ActionManager::createMenu(Core::Id(Constants::M_TOOLS_GLSL));
- glslToolsMenu->setOnAllDisabledBehavior(Core::ActionContainer::Hide);
+ ActionContainer *contextMenu = ActionManager::createMenu(GLSLEditor::Constants::M_CONTEXT);
+ ActionContainer *glslToolsMenu = ActionManager::createMenu(Id(Constants::M_TOOLS_GLSL));
+ glslToolsMenu->setOnAllDisabledBehavior(ActionContainer::Hide);
QMenu *menu = glslToolsMenu->menu();
//: GLSL sub-menu in the Tools menu
menu->setTitle(tr("GLSL"));
- Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(glslToolsMenu);
+ ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(glslToolsMenu);
- Core::Command *cmd = 0;
+ Command *cmd = 0;
// Insert marker for "Refactoring" menu:
- Core::Context globalContext(Core::Constants::C_GLOBAL);
- Core::Command *sep = contextMenu->addSeparator(globalContext);
- sep->action()->setObjectName(Constants::M_REFACTORING_MENU_INSERTION_POINT);
+ Context globalContext(Core::Constants::C_GLOBAL);
+ Command *sep = contextMenu->addSeparator(globalContext);
+ sep->action()->setObjectName(QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT));
contextMenu->addSeparator(globalContext);
- cmd = Core::ActionManager::command(TextEditor::Constants::UN_COMMENT_SELECTION);
+ cmd = ActionManager::command(TextEditor::Constants::UN_COMMENT_SELECTION);
contextMenu->addAction(cmd);
errorMessage->clear();
- Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- Core::MimeDatabase *mimeDatabase = Core::ICore::mimeDatabase();
+ FileIconProvider *iconProvider = FileIconProvider::instance();
+ MimeDatabase *mimeDatabase = ICore::mimeDatabase();
iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/glsleditor/images/glslfile.png")),
mimeDatabase->findByType(QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE)));
iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/glsleditor/images/glslfile.png")),
@@ -159,8 +159,8 @@ bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *er
iconProvider->registerIconOverlayForMimeType(QIcon(QLatin1String(":/glsleditor/images/glslfile.png")),
mimeDatabase->findByType(QLatin1String(GLSLEditor::Constants::GLSL_MIMETYPE_FRAG_ES)));
- QObject *core = Core::ICore::instance();
- Core::BaseFileWizardParameters fragWizardParameters(Core::IWizard::FileWizard);
+ QObject *core = ICore::instance();
+ BaseFileWizardParameters fragWizardParameters(IWizard::FileWizard);
fragWizardParameters.setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
fragWizardParameters.setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
fragWizardParameters.setDescription
@@ -172,7 +172,7 @@ bool GLSLEditorPlugin::initialize(const QStringList & /*arguments*/, QString *er
fragWizardParameters.setId(QLatin1String("F.GLSL"));
addAutoReleasedObject(new GLSLFileWizard(fragWizardParameters, GLSLFileWizard::FragmentShaderES, core));
- Core::BaseFileWizardParameters vertWizardParameters(Core::IWizard::FileWizard);
+ BaseFileWizardParameters vertWizardParameters(IWizard::FileWizard);
vertWizardParameters.setCategory(QLatin1String(Constants::WIZARD_CATEGORY_GLSL));
vertWizardParameters.setDisplayCategory(QCoreApplication::translate("GLSLEditor", Constants::WIZARD_TR_CATEGORY_GLSL));
vertWizardParameters.setDescription
@@ -212,28 +212,14 @@ void GLSLEditorPlugin::extensionsInitialized()
ExtensionSystem::IPlugin::ShutdownFlag GLSLEditorPlugin::aboutToShutdown()
{
// delete GLSL::Icons::instance(); // delete object held by singleton
-
return IPlugin::aboutToShutdown();
}
void GLSLEditorPlugin::initializeEditor(GLSLEditor::GLSLTextEditorWidget *editor)
{
QTC_CHECK(m_instance);
-
m_actionHandler->setupActions(editor);
-
- TextEditor::TextEditorSettings::instance()->initializeEditor(editor);
-}
-
-Core::Command *GLSLEditorPlugin::addToolAction(QAction *a,
- Core::Context &context, const Core::Id &id,
- Core::ActionContainer *c1, const QString &keySequence)
-{
- Core::Command *command = Core::ActionManager::registerAction(a, id, context);
- if (!keySequence.isEmpty())
- command->setDefaultKeySequence(QKeySequence(keySequence));
- c1->addAction(command);
- return command;
+ TextEditorSettings::instance()->initializeEditor(editor);
}
GLSLEditorPlugin::InitFile *GLSLEditorPlugin::getInitFile(const QString &fileName, InitFile **initFile) const
@@ -247,10 +233,7 @@ GLSLEditorPlugin::InitFile *GLSLEditorPlugin::getInitFile(const QString &fileNam
QByteArray GLSLEditorPlugin::glslFile(const QString &fileName) const
{
- QString path = Core::ICore::resourcePath();
- path += QLatin1String("/glsl/");
- path += fileName;
- QFile file(path);
+ QFile file(ICore::resourcePath() + QLatin1String("/glsl/") + fileName);
if (file.open(QFile::ReadOnly))
return file.readAll();
return QByteArray();
@@ -291,4 +274,7 @@ const GLSLEditorPlugin::InitFile *GLSLEditorPlugin::shaderInit(int variant) cons
return getInitFile(QLatin1String("glsl_es_100_common.glsl"), &m_glsl_es_100_common);
}
-Q_EXPORT_PLUGIN(GLSLEditorPlugin)
+} // namespace Internal
+} // namespace GLSLEditor
+
+Q_EXPORT_PLUGIN(GLSLEditor::Internal::GLSLEditorPlugin)
diff --git a/src/plugins/glsleditor/glsleditorplugin.h b/src/plugins/glsleditor/glsleditorplugin.h
index 63330676c0..b119cfc9c2 100644
--- a/src/plugins/glsleditor/glsleditorplugin.h
+++ b/src/plugins/glsleditor/glsleditorplugin.h
@@ -33,14 +33,15 @@
#include <extensionsystem/iplugin.h>
#include <coreplugin/icontext.h>
#include <coreplugin/id.h>
-#include <QPointer>
#include <glsl/glsl.h>
+#include <QPointer>
+
QT_FORWARD_DECLARE_CLASS(QAction)
-QT_FORWARD_DECLARE_CLASS(QTimer)
namespace TextEditor {
class TextEditorActionHandler;
+class ITextEditor;
} // namespace TextEditor
namespace Core {
@@ -49,14 +50,6 @@ class ActionContainer;
class ActionManager;
}
-namespace TextEditor {
-class ITextEditor;
-}
-
-namespace GLSL {
-class ModelManagerInterface;
-}
-
namespace GLSLEditor {
class GLSLTextEditorWidget;
@@ -64,8 +57,6 @@ class GLSLTextEditorWidget;
namespace Internal {
class GLSLEditorFactory;
-class GLSLPreviewRunner;
-class GLSLQuickFixCollector;
class GLSLEditorPlugin : public ExtensionSystem::IPlugin
{
@@ -74,26 +65,27 @@ class GLSLEditorPlugin : public ExtensionSystem::IPlugin
public:
GLSLEditorPlugin();
- virtual ~GLSLEditorPlugin();
+ ~GLSLEditorPlugin();
// IPlugin
bool initialize(const QStringList &arguments, QString *errorMessage = 0);
void extensionsInitialized();
ShutdownFlag aboutToShutdown();
- static GLSLEditorPlugin *instance()
- { return m_instance; }
+ static GLSLEditorPlugin *instance() { return m_instance; }
void initializeEditor(GLSLEditor::GLSLTextEditorWidget *editor);
- struct InitFile {
- GLSL::Engine *engine;
- GLSL::TranslationUnitAST *ast;
-
+ struct InitFile
+ {
InitFile(GLSL::Engine *engine = 0, GLSL::TranslationUnitAST *ast = 0)
- : engine(engine), ast(ast) {}
+ : engine(engine), ast(ast)
+ {}
~InitFile();
+
+ GLSL::Engine *engine;
+ GLSL::TranslationUnitAST *ast;
};
const InitFile *fragmentShaderInit(int variant) const;
@@ -105,10 +97,6 @@ private:
InitFile *getInitFile(const QString &fileName, InitFile **initFile) const;
void parseGlslFile(const QString &fileName, InitFile *initFile) const;
- // FIXME: Unused?
- Core::Command *addToolAction(QAction *a, Core::Context &context, const Core::Id &name,
- Core::ActionContainer *c1, const QString &keySequence);
-
static GLSLEditorPlugin *m_instance;
GLSLEditorFactory *m_editor;
diff --git a/src/plugins/glsleditor/glslhighlighter.cpp b/src/plugins/glsleditor/glslhighlighter.cpp
index 93364a25f2..61b1e341d6 100644
--- a/src/plugins/glsleditor/glslhighlighter.cpp
+++ b/src/plugins/glsleditor/glslhighlighter.cpp
@@ -270,48 +270,48 @@ bool Highlighter::isPPKeyword(const QStringRef &text) const
switch (text.length())
{
case 2:
- if (text.at(0) == 'i' && text.at(1) == 'f')
+ if (text.at(0) == QLatin1Char('i') && text.at(1) == QLatin1Char('f'))
return true;
break;
case 4:
- if (text.at(0) == 'e' && text == QLatin1String("elif"))
+ if (text.at(0) == QLatin1Char('e') && text == QLatin1String("elif"))
return true;
- else if (text.at(0) == 'e' && text == QLatin1String("else"))
+ else if (text.at(0) == QLatin1Char('e') && text == QLatin1String("else"))
return true;
break;
case 5:
- if (text.at(0) == 'i' && text == QLatin1String("ifdef"))
+ if (text.at(0) == QLatin1Char('i') && text == QLatin1String("ifdef"))
return true;
- else if (text.at(0) == 'u' && text == QLatin1String("undef"))
+ else if (text.at(0) == QLatin1Char('u') && text == QLatin1String("undef"))
return true;
- else if (text.at(0) == 'e' && text == QLatin1String("endif"))
+ else if (text.at(0) == QLatin1Char('e') && text == QLatin1String("endif"))
return true;
- else if (text.at(0) == 'e' && text == QLatin1String("error"))
+ else if (text.at(0) == QLatin1Char('e') && text == QLatin1String("error"))
return true;
break;
case 6:
- if (text.at(0) == 'i' && text == QLatin1String("ifndef"))
+ if (text.at(0) == QLatin1Char('i') && text == QLatin1String("ifndef"))
return true;
- if (text.at(0) == 'i' && text == QLatin1String("import"))
+ if (text.at(0) == QLatin1Char('i') && text == QLatin1String("import"))
return true;
- else if (text.at(0) == 'd' && text == QLatin1String("define"))
+ else if (text.at(0) == QLatin1Char('d') && text == QLatin1String("define"))
return true;
- else if (text.at(0) == 'p' && text == QLatin1String("pragma"))
+ else if (text.at(0) == QLatin1Char('p') && text == QLatin1String("pragma"))
return true;
break;
case 7:
- if (text.at(0) == 'i' && text == QLatin1String("include"))
+ if (text.at(0) == QLatin1Char('i') && text == QLatin1String("include"))
return true;
- else if (text.at(0) == 'w' && text == QLatin1String("warning"))
+ else if (text.at(0) == QLatin1Char('w') && text == QLatin1String("warning"))
return true;
break;
case 12:
- if (text.at(0) == 'i' && text == QLatin1String("include_next"))
+ if (text.at(0) == QLatin1Char('i') && text == QLatin1String("include_next"))
return true;
break;
diff --git a/src/plugins/glsleditor/glslhoverhandler.cpp b/src/plugins/glsleditor/glslhoverhandler.cpp
index 58d2793bae..2dd021d24a 100644
--- a/src/plugins/glsleditor/glslhoverhandler.cpp
+++ b/src/plugins/glsleditor/glslhoverhandler.cpp
@@ -61,9 +61,8 @@ bool GLSLHoverHandler::acceptEditor(IEditor *editor)
void GLSLHoverHandler::identifyMatch(TextEditor::ITextEditor *editor, int pos)
{
if (GLSLTextEditorWidget *glslEditor = qobject_cast<GLSLTextEditorWidget *>(editor->widget())) {
- if (! glslEditor->extraSelectionTooltip(pos).isEmpty()) {
+ if (! glslEditor->extraSelectionTooltip(pos).isEmpty())
setToolTip(glslEditor->extraSelectionTooltip(pos));
- }
}
}
diff --git a/src/plugins/helloworld/helloworld.qbs b/src/plugins/helloworld/helloworld.qbs
index d71e157d85..e5546e282a 100644
--- a/src/plugins/helloworld/helloworld.qbs
+++ b/src/plugins/helloworld/helloworld.qbs
@@ -6,20 +6,13 @@ QtcPlugin {
name: "HelloWorld"
Depends { name: "Core" }
- Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "xml", "network", "script"] }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
+ "helloworldplugin.cpp",
"helloworldplugin.h",
+ "helloworldwindow.cpp",
"helloworldwindow.h",
- "helloworldplugin.cpp",
- "helloworldwindow.cpp"
]
}
diff --git a/src/plugins/help/centralwidget.cpp b/src/plugins/help/centralwidget.cpp
index 6177650a30..43dea44778 100644
--- a/src/plugins/help/centralwidget.cpp
+++ b/src/plugins/help/centralwidget.cpp
@@ -288,7 +288,7 @@ void CentralWidget::focusInEvent(QFocusEvent * /* event */)
void CentralWidget::highlightSearchTerms()
{
if (HelpViewer *viewer = currentHelpViewer()) {
- QHelpSearchEngine *searchEngine =
+ QHelpSearchEngine *searchEngine =
LocalHelpManager::helpEngine().searchEngine();
QList<QHelpSearchQuery> queryList = searchEngine->query();
diff --git a/src/plugins/help/docsettingspage.cpp b/src/plugins/help/docsettingspage.cpp
index f1fe9fab79..061c54d91e 100644
--- a/src/plugins/help/docsettingspage.cpp
+++ b/src/plugins/help/docsettingspage.cpp
@@ -42,9 +42,9 @@ using namespace Help::Internal;
DocSettingsPage::DocSettingsPage()
{
- setId(QLatin1String("B.Documentation"));
+ setId("B.Documentation");
setDisplayName(tr("Documentation"));
- setCategory(QLatin1String(Help::Constants::HELP_CATEGORY));
+ setCategory(Help::Constants::HELP_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Help", Help::Constants::HELP_TR_CATEGORY));
setCategoryIcon(QLatin1String(Help::Constants::HELP_CATEGORY_ICON));
}
diff --git a/src/plugins/help/externalhelpwindow.cpp b/src/plugins/help/externalhelpwindow.cpp
index 2c8fc6eae0..d4fad1c23e 100644
--- a/src/plugins/help/externalhelpwindow.cpp
+++ b/src/plugins/help/externalhelpwindow.cpp
@@ -35,6 +35,7 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
+#include <utils/hostosinfo.h>
#include <QAction>
#include <QHBoxLayout>
@@ -48,7 +49,7 @@ ExternalHelpWindow::ExternalHelpWindow(QWidget *parent)
: QMainWindow(parent)
{
QSettings *settings = Core::ICore::settings();
- settings->beginGroup(Help::Constants::ID_MODE_HELP);
+ settings->beginGroup(QLatin1String(Help::Constants::ID_MODE_HELP));
const QVariant geometry = settings->value(QLatin1String("geometry"));
if (geometry.isValid())
@@ -138,21 +139,21 @@ ExternalHelpWindow::ExternalHelpWindow(QWidget *parent)
SLOT(gotoNextPage()));
addAction(ctrlShiftTab);
- action = new QAction(QIcon(Core::Constants::ICON_TOGGLE_SIDEBAR),
+ action = new QAction(QIcon(QLatin1String(Core::Constants::ICON_TOGGLE_SIDEBAR)),
tr("Show Sidebar"), this);
connect(action, SIGNAL(triggered()), this, SIGNAL(showHideSidebar()));
-#ifdef Q_OS_MAC
- reset->setShortcut(QKeySequence(Qt::ALT + Qt::Key_0));
- action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
- ctrlTab->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Tab));
- ctrlShiftTab->setShortcut(QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Tab));
-#else
- reset->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
- action->setShortcut(QKeySequence(Qt::ALT + Qt::Key_0));
- ctrlTab->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Tab));
- ctrlShiftTab->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Tab));
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ reset->setShortcut(QKeySequence(Qt::ALT + Qt::Key_0));
+ action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
+ ctrlTab->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Tab));
+ ctrlShiftTab->setShortcut(QKeySequence(Qt::ALT + Qt::SHIFT + Qt::Key_Tab));
+ } else {
+ reset->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
+ action->setShortcut(QKeySequence(Qt::ALT + Qt::Key_0));
+ ctrlTab->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Tab));
+ ctrlShiftTab->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Tab));
+ }
QToolButton *button = new QToolButton;
button->setDefaultAction(action);
@@ -178,7 +179,7 @@ ExternalHelpWindow::~ExternalHelpWindow()
void ExternalHelpWindow::closeEvent(QCloseEvent *event)
{
QSettings *settings = Core::ICore::settings();
- settings->beginGroup(Help::Constants::ID_MODE_HELP);
+ settings->beginGroup(QLatin1String(Help::Constants::ID_MODE_HELP));
settings->setValue(QLatin1String("geometry"), saveGeometry());
settings->endGroup();
diff --git a/src/plugins/help/filtersettingspage.cpp b/src/plugins/help/filtersettingspage.cpp
index 216e97f865..023d7a99cd 100644
--- a/src/plugins/help/filtersettingspage.cpp
+++ b/src/plugins/help/filtersettingspage.cpp
@@ -43,9 +43,9 @@ using namespace Help::Internal;
FilterSettingsPage::FilterSettingsPage()
{
- setId(QLatin1String("D.Filters"));
+ setId("D.Filters");
setDisplayName(tr("Filters"));
- setCategory(QLatin1String(Help::Constants::HELP_CATEGORY));
+ setCategory(Help::Constants::HELP_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Help", Help::Constants::HELP_TR_CATEGORY));
setCategoryIcon(QLatin1String(Help::Constants::HELP_CATEGORY_ICON));
}
diff --git a/src/plugins/help/generalsettingspage.cpp b/src/plugins/help/generalsettingspage.cpp
index 42d0f93bbe..7d951747b0 100644
--- a/src/plugins/help/generalsettingspage.cpp
+++ b/src/plugins/help/generalsettingspage.cpp
@@ -63,9 +63,9 @@ GeneralSettingsPage::GeneralSettingsPage()
QWebSettings* webSettings = QWebSettings::globalSettings();
m_font.setPointSize(webSettings->fontSize(QWebSettings::DefaultFontSize));
#endif
- setId(QLatin1String("A.General settings"));
+ setId("A.General settings");
setDisplayName(tr("General"));
- setCategory(QLatin1String(Help::Constants::HELP_CATEGORY));
+ setCategory(Help::Constants::HELP_CATEGORY);
setDisplayCategory(QCoreApplication::translate("Help", Help::Constants::HELP_TR_CATEGORY));
setCategoryIcon(QLatin1String(Help::Constants::HELP_CATEGORY_ICON));
}
@@ -79,7 +79,7 @@ QWidget *GeneralSettingsPage::createPage(QWidget *parent)
m_ui->styleComboBox->setEditable(false);
Core::HelpManager *manager = Core::HelpManager::instance();
- m_font = qVariantValue<QFont>(manager->customValue(QLatin1String("font"),
+ m_font = qvariant_cast<QFont>(manager->customValue(QLatin1String("font"),
m_font));
updateFontSize();
@@ -185,7 +185,7 @@ void GeneralSettingsPage::apply()
manager->setCustomValue(QLatin1String("ContextHelpOption"), helpOption);
QSettings *settings = Core::ICore::settings();
- settings->beginGroup(Help::Constants::ID_MODE_HELP);
+ settings->beginGroup(QLatin1String(Help::Constants::ID_MODE_HELP));
settings->setValue(QLatin1String("ContextHelpOption"), helpOption);
settings->endGroup();
@@ -246,7 +246,7 @@ void GeneralSettingsPage::exportBookmarks()
m_ui->errorLabel->setVisible(false);
QString fileName = QFileDialog::getSaveFileName(0, tr("Save File"),
- "untitled.xbel", tr("Files (*.xbel)"));
+ QLatin1String("untitled.xbel"), tr("Files (*.xbel)"));
QLatin1String suffix(".xbel");
if (!fileName.endsWith(suffix))
@@ -337,9 +337,8 @@ int GeneralSettingsPage::closestPointSizeIndex(int desiredPointSize) const
if (closestAbsError == 0)
break;
} else { // past optimum
- if (absError > closestAbsError) {
+ if (absError > closestAbsError)
break;
- }
}
}
return closestIndex;
diff --git a/src/plugins/help/help.pro b/src/plugins/help/help.pro
index 26aa05b25b..7e2dd639dc 100644
--- a/src/plugins/help/help.pro
+++ b/src/plugins/help/help.pro
@@ -16,7 +16,9 @@ INCLUDEPATH += $$PWD
include(../../qtcreatorplugin.pri)
include(help_dependencies.pri)
-DEFINES += QT_CLUCENE_SUPPORT HELP_LIBRARY
+DEFINES += \
+ QT_CLUCENE_SUPPORT \
+ HELP_LIBRARY
HEADERS += \
centralwidget.h \
@@ -62,7 +64,7 @@ SOURCES += \
searchwidget.cpp \
xbelsupport.cpp \
externalhelpwindow.cpp
-
+
FORMS += docsettingspage.ui \
filtersettingspage.ui \
generalsettingspage.ui \
diff --git a/src/plugins/help/help.qbs b/src/plugins/help/help.qbs
index 97eaefe9ec..75152239c4 100644
--- a/src/plugins/help/help.qbs
+++ b/src/plugins/help/help.qbs
@@ -18,85 +18,75 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "Find" }
Depends { name: "Locator" }
+ Depends { name: "app_version_header" }
Depends { name: "cpp" }
Properties {
condition: qtcore.versionMajor >= 5
cpp.defines: base.concat(["QT_NO_WEBKIT"])
}
- cpp.defines: base.concat([
- "QT_CLUCENE_SUPPORT",
- "HELP_LIBRARY"
- ])
- cpp.includePaths: [
- "../../shared/help",
- ".",
- "..",
- "../..",
- "../../libs",
- buildDirectory
- ]
+ cpp.defines: base.concat("QT_CLUCENE_SUPPORT")
+ cpp.includePaths: base.concat("../../shared/help")
files: [
+ "centralwidget.cpp",
"centralwidget.h",
+ "docsettingspage.cpp",
"docsettingspage.h",
+ "docsettingspage.ui",
+ "externalhelpwindow.cpp",
+ "externalhelpwindow.h",
+ "filtersettingspage.cpp",
"filtersettingspage.h",
+ "filtersettingspage.ui",
+ "generalsettingspage.cpp",
"generalsettingspage.h",
+ "generalsettingspage.ui",
+ "help.qrc",
"help_global.h",
"helpconstants.h",
+ "helpfindsupport.cpp",
"helpfindsupport.h",
+ "helpindexfilter.cpp",
"helpindexfilter.h",
- "localhelpmanager.h",
+ "helpmode.cpp",
"helpmode.h",
+ "helpplugin.cpp",
"helpplugin.h",
+ "helpviewer.cpp",
"helpviewer.h",
"helpviewer_p.h",
- "openpagesmanager.h",
- "openpagesmodel.h",
- "openpagesswitcher.h",
- "openpageswidget.h",
- "remotehelpfilter.h",
- "searchwidget.h",
- "xbelsupport.h",
- "externalhelpwindow.h",
- "centralwidget.cpp",
- "docsettingspage.cpp",
- "filtersettingspage.cpp",
- "generalsettingspage.cpp",
- "helpfindsupport.cpp",
- "helpindexfilter.cpp",
- "localhelpmanager.cpp",
- "helpmode.cpp",
- "helpplugin.cpp",
- "helpviewer.cpp",
"helpviewer_qtb.cpp",
"helpviewer_qwv.cpp",
+ "localhelpmanager.cpp",
+ "localhelpmanager.h",
"openpagesmanager.cpp",
+ "openpagesmanager.h",
"openpagesmodel.cpp",
+ "openpagesmodel.h",
"openpagesswitcher.cpp",
+ "openpagesswitcher.h",
"openpageswidget.cpp",
+ "openpageswidget.h",
"remotehelpfilter.cpp",
+ "remotehelpfilter.h",
+ "remotehelpfilter.ui",
"searchwidget.cpp",
+ "searchwidget.h",
"xbelsupport.cpp",
- "externalhelpwindow.cpp",
- "docsettingspage.ui",
- "filtersettingspage.ui",
- "generalsettingspage.ui",
- "remotehelpfilter.ui",
- "help.qrc",
- "../../shared/help/bookmarkmanager.h",
- "../../shared/help/contentwindow.h",
- "../../shared/help/filternamedialog.h",
- "../../shared/help/indexwindow.h",
- "../../shared/help/topicchooser.h",
+ "xbelsupport.h",
+ "../../shared/help/bookmarkdialog.ui",
"../../shared/help/bookmarkmanager.cpp",
+ "../../shared/help/bookmarkmanager.h",
"../../shared/help/contentwindow.cpp",
+ "../../shared/help/contentwindow.h",
"../../shared/help/filternamedialog.cpp",
+ "../../shared/help/filternamedialog.h",
+ "../../shared/help/filternamedialog.ui",
"../../shared/help/indexwindow.cpp",
+ "../../shared/help/indexwindow.h",
"../../shared/help/topicchooser.cpp",
- "../../shared/help/bookmarkdialog.ui",
- "../../shared/help/filternamedialog.ui",
- "../../shared/help/topicchooser.ui"
+ "../../shared/help/topicchooser.h",
+ "../../shared/help/topicchooser.ui",
]
}
-
diff --git a/src/plugins/help/helpindexfilter.cpp b/src/plugins/help/helpindexfilter.cpp
index d6242eaacd..1016ed38eb 100644
--- a/src/plugins/help/helpindexfilter.cpp
+++ b/src/plugins/help/helpindexfilter.cpp
@@ -46,8 +46,11 @@ Q_DECLARE_METATYPE(ILocatorFilter*)
HelpIndexFilter::HelpIndexFilter()
{
+ setId("HelpIndexFilter");
+ setDisplayName(tr("Help Index"));
setIncludedByDefault(false);
setShortcutString(QString(QLatin1Char('?')));
+
m_icon = QIcon(QLatin1String(":/help/images/bookmark.png"));
}
@@ -55,21 +58,6 @@ HelpIndexFilter::~HelpIndexFilter()
{
}
-QString HelpIndexFilter::displayName() const
-{
- return tr("Help Index");
-}
-
-QString HelpIndexFilter::id() const
-{
- return QLatin1String("HelpIndexFilter");
-}
-
-ILocatorFilter::Priority HelpIndexFilter::priority() const
-{
- return Medium;
-}
-
QList<FilterEntry> HelpIndexFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry)
{
QStringList keywords;
diff --git a/src/plugins/help/helpindexfilter.h b/src/plugins/help/helpindexfilter.h
index f10b03b134..5658246e14 100644
--- a/src/plugins/help/helpindexfilter.h
+++ b/src/plugins/help/helpindexfilter.h
@@ -46,9 +46,6 @@ public:
~HelpIndexFilter();
// ILocatorFilter
- QString displayName() const;
- QString id() const;
- Priority priority() const;
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/help/helpplugin.cpp b/src/plugins/help/helpplugin.cpp
index bad80291d8..9dae8e2d71 100644
--- a/src/plugins/help/helpplugin.cpp
+++ b/src/plugins/help/helpplugin.cpp
@@ -66,6 +66,7 @@
#include <extensionsystem/pluginmanager.h>
#include <find/findplugin.h>
#include <texteditor/texteditorconstants.h>
+#include <utils/hostosinfo.h>
#include <utils/styledbar.h>
#include <QDir>
@@ -252,12 +253,12 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
cmd->setDefaultKeySequence(QKeySequence(Qt::Key_F1));
connect(action, SIGNAL(triggered()), this, SLOT(activateContext()));
-#ifndef Q_OS_MAC
- action = new QAction(this);
- action->setSeparator(true);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Separator"), globalcontext);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
-#endif
+ if (!Utils::HostOsInfo::isMacHost()) {
+ action = new QAction(this);
+ action->setSeparator(true);
+ cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Separator"), globalcontext);
+ Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ }
action = new QAction(tr("Technical Support"), this);
cmd = Core::ActionManager::registerAction(action, Core::Id("Help.TechSupport"), globalcontext);
@@ -269,12 +270,12 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
connect(action, SIGNAL(triggered()), this, SLOT(slotReportBug()));
-#ifndef Q_OS_MAC
- action = new QAction(this);
- action->setSeparator(true);
- cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Separator2"), globalcontext);
- Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
-#endif
+ if (!Utils::HostOsInfo::isMacHost()) {
+ action = new QAction(this);
+ action->setSeparator(true);
+ cmd = Core::ActionManager::registerAction(action, Core::Id("Help.Separator2"), globalcontext);
+ Core::ActionManager::actionContainer(Core::Constants::M_HELP)->addAction(cmd, Core::Constants::G_HELP_HELP);
+ }
action = new QAction(this);
Core::ActionManager::registerAction(action, Core::Constants::PRINT, modecontext);
@@ -363,7 +364,7 @@ bool HelpPlugin::initialize(const QStringList &arguments, QString *error)
connect(remoteHelpFilter, SIGNAL(linkActivated(QUrl)), this,
SLOT(switchToHelpMode(QUrl)));
- QDesktopServices::setUrlHandler("qthelp", this, "handleHelpRequest");
+ QDesktopServices::setUrlHandler(QLatin1String("qthelp"), this, "handleHelpRequest");
connect(Core::ModeManager::instance(), SIGNAL(currentModeChanged(Core::IMode*,
Core::IMode*)), this, SLOT(modeChanged(Core::IMode*,Core::IMode*)));
@@ -461,7 +462,7 @@ void HelpPlugin::setupUi()
ContentWindow *contentWindow = new ContentWindow();
contentWindow->setWindowTitle(tr(SB_CONTENTS));
- m_contentItem = new Core::SideBarItem(contentWindow, SB_CONTENTS);
+ m_contentItem = new Core::SideBarItem(contentWindow, QLatin1String(SB_CONTENTS));
connect(contentWindow, SIGNAL(linkActivated(QUrl)), m_centralWidget,
SLOT(setSource(QUrl)));
@@ -772,7 +773,7 @@ void HelpPlugin::fontChanged()
createRightPaneContextViewer();
const QHelpEngine &engine = LocalHelpManager::helpEngine();
- QFont font = qVariantValue<QFont>(engine.customValue(QLatin1String("font"),
+ QFont font = qvariant_cast<QFont>(engine.customValue(QLatin1String("font"),
m_helpViewerForSideBar->viewerFont()));
m_helpViewerForSideBar->setFont(font);
@@ -929,7 +930,7 @@ void HelpPlugin::activateContext()
"available.</center></body></html>").arg(m_idFromContext));
} else {
int version = 0;
- QRegExp exp("(\\d+)");
+ QRegExp exp(QLatin1String("(\\d+)"));
QUrl source = *links.begin();
const QLatin1String qtRefDoc = QLatin1String("com.trolltech.qt");
@@ -1167,15 +1168,14 @@ void HelpPlugin::handleHelpRequest(const QUrl &url)
QString address = url.toString();
if (!Core::HelpManager::instance()->findFile(url).isValid()) {
- if (address.startsWith(HelpViewer::NsNokia)
- || address.startsWith(HelpViewer::NsTrolltech)) {
+ if (address.startsWith(QLatin1String("qthelp://com.nokia."))
+ || address.startsWith(QLatin1String("qthelp://com.trolltech."))) {
// local help not installed, resort to external web help
QString urlPrefix = QLatin1String("http://doc.qt.digia.com/");
- if (url.authority() == QLatin1String("com.nokia.qtcreator")) {
+ if (url.authority() == QLatin1String("com.nokia.qtcreator"))
urlPrefix.append(QString::fromLatin1("qtcreator"));
- } else {
+ else
urlPrefix.append(QLatin1String("latest"));
- }
address = urlPrefix + address.mid(address.lastIndexOf(QLatin1Char('/')));
}
}
@@ -1243,12 +1243,12 @@ void HelpPlugin::slotOpenActionUrl(QAction *action)
void HelpPlugin::slotOpenSupportPage()
{
- switchToHelpMode(QUrl("qthelp://com.nokia.qtcreator/doc/technical-support.html"));
+ switchToHelpMode(QUrl(QLatin1String("qthelp://com.nokia.qtcreator/doc/technical-support.html")));
}
void HelpPlugin::slotReportBug()
{
- QDesktopServices::openUrl(QUrl("https://bugreports.qt-project.org"));
+ QDesktopServices::openUrl(QUrl(QLatin1String("https://bugreports.qt-project.org")));
}
void HelpPlugin::openFindToolBar()
@@ -1278,7 +1278,7 @@ void HelpPlugin::doSetupIfNeeded()
int HelpPlugin::contextHelpOption() const
{
QSettings *settings = Core::ICore::settings();
- const QString key = Help::Constants::ID_MODE_HELP + QLatin1String("/ContextHelpOption");
+ const QString key = QLatin1String(Help::Constants::ID_MODE_HELP) + QLatin1String("/ContextHelpOption");
if (settings->contains(key))
return settings->value(key, Help::Constants::SideBySideIfPossible).toInt();
diff --git a/src/plugins/help/helpviewer.cpp b/src/plugins/help/helpviewer.cpp
index 1471010e50..825f7b141f 100644
--- a/src/plugins/help/helpviewer.cpp
+++ b/src/plugins/help/helpviewer.cpp
@@ -48,18 +48,6 @@
using namespace Help::Internal;
-const QString HelpViewer::NsNokia = QLatin1String("qthelp://com.nokia.");
-const QString HelpViewer::NsTrolltech = QLatin1String("qthelp://com.trolltech.");
-
-const QString HelpViewer::AboutBlankPage =
- QCoreApplication::translate("HelpViewer", "<title>about:blank</title>");
-
-const QString HelpViewer::PageNotFoundMessage =
- QCoreApplication::translate("HelpViewer", "<html><head><meta http-equiv=\""
- "content-type\" content=\"text/html; charset=UTF-8\"><title>Error 404...</title>"
- "</head><body><div align=\"center\"><br><br><h1>The page could not be found</h1>"
- "<br><h3>'%1'</h3></div></body>");
-
struct ExtensionMap {
const char *extension;
const char *mimeType;
diff --git a/src/plugins/help/helpviewer.h b/src/plugins/help/helpviewer.h
index d99a7f6fe7..6882aa92f8 100644
--- a/src/plugins/help/helpviewer.h
+++ b/src/plugins/help/helpviewer.h
@@ -85,11 +85,6 @@ public:
bool findText(const QString &text, Find::FindFlags flags,
bool incremental, bool fromSearch, bool *wrapped = 0);
- static const QString NsNokia;
- static const QString NsTrolltech;
- static const QString AboutBlankPage;
- static const QString PageNotFoundMessage;
-
static bool isLocalUrl(const QUrl &url);
static bool canOpenPage(const QString &url);
static QString mimeFromUrl(const QUrl &url);
diff --git a/src/plugins/help/helpviewer_p.h b/src/plugins/help/helpviewer_p.h
index ff272b58ab..0115326442 100644
--- a/src/plugins/help/helpviewer_p.h
+++ b/src/plugins/help/helpviewer_p.h
@@ -49,7 +49,7 @@ public:
: zoomCount(zoom)
, forceFont(false)
, lastAnchor(QString())
-
+
{}
bool hasAnchorAt(QTextBrowser *browser, const QPoint& pos)
@@ -69,7 +69,7 @@ public:
void openLink(bool newPage)
{
- if(lastAnchor.isEmpty())
+ if (lastAnchor.isEmpty())
return;
if (newPage)
OpenPagesManager::instance().createPage(lastAnchor);
diff --git a/src/plugins/help/helpviewer_qtb.cpp b/src/plugins/help/helpviewer_qtb.cpp
index 0064882a74..45b0735ec5 100644
--- a/src/plugins/help/helpviewer_qtb.cpp
+++ b/src/plugins/help/helpviewer_qtb.cpp
@@ -35,6 +35,8 @@
#include "helpviewer_p.h"
#include "localhelpmanager.h"
+#include <utils/hostosinfo.h>
+
#include <QApplication>
#include <QClipboard>
#include <QContextMenuEvent>
@@ -79,7 +81,7 @@ HelpViewer::~HelpViewer()
QFont HelpViewer::viewerFont() const
{
const QHelpEngineCore &engine = LocalHelpManager::helpEngine();
- return qVariantValue<QFont>(engine.customValue(QLatin1String("font"),
+ return qvariant_cast<QFont>(engine.customValue(QLatin1String("font"),
qApp->font()));
}
@@ -166,8 +168,14 @@ void HelpViewer::setSource(const QUrl &url)
}
QTextBrowser::setSource(url);
- setHtml(string == Help::Constants::AboutBlank ? AboutBlankPage
- : PageNotFoundMessage.arg(url.toString()));
+ setHtml(string == Help::Constants::AboutBlank
+ ? HelpViewer::tr("<title>about:blank</title>")
+ : HelpViewer::tr("<html><head><meta http-equiv=\""
+ "content-type\" content=\"text/html; charset=UTF-8\"><title>Error 404...</title>"
+ "</head><body><div align=\"center\"><br><br><h1>The page could not be found</h1>"
+ "<br><h3>'%1'</h3></div></body>")
+ .arg(url.toString()));
+
emit loadFinished(true);
}
@@ -285,19 +293,15 @@ void HelpViewer::wheelEvent(QWheelEvent *e)
void HelpViewer::mousePressEvent(QMouseEvent *e)
{
-#ifdef Q_OS_LINUX
- if (handleForwardBackwardMouseButtons(e))
+ if (Utils::HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(e))
return;
-#endif
QTextBrowser::mousePressEvent(e);
}
void HelpViewer::mouseReleaseEvent(QMouseEvent *e)
{
-#ifndef Q_OS_LINUX
- if (handleForwardBackwardMouseButtons(e))
+ if (!Utils::HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(e))
return;
-#endif
bool controlPressed = e->modifiers() & Qt::ControlModifier;
if ((controlPressed && d->hasAnchorAt(this, e->pos())) ||
diff --git a/src/plugins/help/helpviewer_qwv.cpp b/src/plugins/help/helpviewer_qwv.cpp
index b35407c36a..586e3908c4 100644
--- a/src/plugins/help/helpviewer_qwv.cpp
+++ b/src/plugins/help/helpviewer_qwv.cpp
@@ -36,6 +36,8 @@
#include "localhelpmanager.h"
#include "openpagesmanager.h"
+#include <utils/hostosinfo.h>
+
#include <QDebug>
#include <QFileInfo>
#include <QString>
@@ -54,6 +56,8 @@
#include <utils/networkaccessmanager.h>
+#include <cstring>
+
using namespace Find;
using namespace Help;
using namespace Help::Internal;
@@ -145,7 +149,7 @@ qint64 HelpNetworkReply::readData(char *buffer, qint64 maxlen)
{
qint64 len = qMin(qint64(data.length()), maxlen);
if (len) {
- qMemCopy(buffer, data.constData(), len);
+ std::memcpy(buffer, data.constData(), len);
data.remove(0, len);
}
return len;
@@ -329,7 +333,7 @@ HelpViewer::HelpViewer(qreal zoom, QWidget *parent)
connect(page(), SIGNAL(printRequested(QWebFrame*)), this, SIGNAL(printRequested()));
setViewerFont(viewerFont());
- setTextSizeMultiplier(zoom == 0.0 ? 1.0 : zoom);
+ setZoomFactor(zoom == 0.0 ? 1.0 : zoom);
}
HelpViewer::~HelpViewer()
@@ -342,7 +346,7 @@ QFont HelpViewer::viewerFont() const
QFont font(QApplication::font().family(),
webSettings->fontSize(QWebSettings::DefaultFontSize));
const QHelpEngineCore &engine = LocalHelpManager::helpEngine();
- return qVariantValue<QFont>(engine.customValue(QLatin1String("font"),
+ return qvariant_cast<QFont>(engine.customValue(QLatin1String("font"),
font));
}
@@ -355,22 +359,22 @@ void HelpViewer::setViewerFont(const QFont &font)
void HelpViewer::scaleUp()
{
- setTextSizeMultiplier(textSizeMultiplier() + 0.1);
+ setZoomFactor(zoomFactor() + 0.1);
}
void HelpViewer::scaleDown()
{
- setTextSizeMultiplier(qMax(qreal(0.0), textSizeMultiplier() - qreal(0.1)));
+ setZoomFactor(qMax(qreal(0.0), zoomFactor() - qreal(0.1)));
}
void HelpViewer::resetScale()
{
- setTextSizeMultiplier(1.0);
+ setZoomFactor(1.0);
}
qreal HelpViewer::scale() const
{
- return textSizeMultiplier();
+ return zoomFactor();
}
QString HelpViewer::title() const
@@ -480,10 +484,8 @@ void HelpViewer::wheelEvent(QWheelEvent *event)
void HelpViewer::mousePressEvent(QMouseEvent *event)
{
-#ifdef Q_OS_LINUX
- if (handleForwardBackwardMouseButtons(event))
+ if (Utils::HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(event))
return;
-#endif
if (HelpPage *currentPage = static_cast<HelpPage*> (page())) {
currentPage->m_pressedButtons = event->buttons();
@@ -495,10 +497,8 @@ void HelpViewer::mousePressEvent(QMouseEvent *event)
void HelpViewer::mouseReleaseEvent(QMouseEvent *event)
{
-#ifndef Q_OS_LINUX
- if (handleForwardBackwardMouseButtons(event))
+ if (!Utils::HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(event))
return;
-#endif
QWebView::mouseReleaseEvent(event);
}
diff --git a/src/plugins/help/localhelpmanager.cpp b/src/plugins/help/localhelpmanager.cpp
index 0beb4fa6d1..0182ee3bee 100644
--- a/src/plugins/help/localhelpmanager.cpp
+++ b/src/plugins/help/localhelpmanager.cpp
@@ -87,7 +87,7 @@ QHelpEngine &LocalHelpManager::helpEngine()
if (!m_guiEngine) {
QMutexLocker _(&m_guiMutex);
if (!m_guiEngine) {
- m_guiEngine = new QHelpEngine("");
+ m_guiEngine = new QHelpEngine(QString());
m_guiEngine->setAutoSaveFilter(false);
}
}
diff --git a/src/plugins/help/openpagesmanager.cpp b/src/plugins/help/openpagesmanager.cpp
index 4bd309105b..f4cd9206bf 100644
--- a/src/plugins/help/openpagesmanager.cpp
+++ b/src/plugins/help/openpagesmanager.cpp
@@ -259,11 +259,10 @@ void OpenPagesManager::closePagesExcept(const QModelIndex &index)
int i = 0;
HelpViewer *viewer = m_model->pageAt(index.row());
while (m_model->rowCount() > 1) {
- if (m_model->pageAt(i) != viewer) {
+ if (m_model->pageAt(i) != viewer)
removePage(i);
- } else {
+ else
i++;
- }
}
}
}
diff --git a/src/plugins/help/openpagesswitcher.cpp b/src/plugins/help/openpagesswitcher.cpp
index 3d47c0d255..b07e58bd9f 100644
--- a/src/plugins/help/openpagesswitcher.cpp
+++ b/src/plugins/help/openpagesswitcher.cpp
@@ -33,6 +33,8 @@
#include "openpagesmodel.h"
#include "openpageswidget.h"
+#include <utils/hostosinfo.h>
+
#include <QEvent>
#include <QKeyEvent>
@@ -53,9 +55,8 @@ OpenPagesSwitcher::OpenPagesSwitcher(OpenPagesModel *model)
// We disable the frame on this list view and use a QFrame around it instead.
// This improves the look with QGTKStyle.
-#ifndef Q_OS_MAC
- setFrameStyle(m_openPagesWidget->frameStyle());
-#endif
+ if (!Utils::HostOsInfo::isMacHost())
+ setFrameStyle(m_openPagesWidget->frameStyle());
m_openPagesWidget->setFrameStyle(QFrame::NoFrame);
m_openPagesWidget->allowContextMenu(false);
@@ -124,11 +125,8 @@ bool OpenPagesSwitcher::eventFilter(QObject *object, QEvent *event)
emit setCurrentPage(m_openPagesWidget->currentIndex());
return true;
}
-#ifdef Q_OS_MAC
- const Qt::KeyboardModifier modifier = Qt::AltModifier;
-#else
- const Qt::KeyboardModifier modifier = Qt::ControlModifier;
-#endif
+ const Qt::KeyboardModifiers modifier = Utils::HostOsInfo::isMacHost()
+ ? Qt::AltModifier : Qt::ControlModifier;
if (key == Qt::Key_Backtab
&& (ke->modifiers() == (modifier | Qt::ShiftModifier)))
gotoNextPage();
diff --git a/src/plugins/help/remotehelpfilter.cpp b/src/plugins/help/remotehelpfilter.cpp
index 6e8fc28adb..5a1459cf7e 100644
--- a/src/plugins/help/remotehelpfilter.cpp
+++ b/src/plugins/help/remotehelpfilter.cpp
@@ -49,6 +49,8 @@ RemoteFilterOptions::RemoteFilterOptions(RemoteHelpFilter *filter, QWidget *pare
connect(m_ui.add, SIGNAL(clicked()), this, SLOT(addNewItem()));
connect(m_ui.remove, SIGNAL(clicked()), this, SLOT(removeItem()));
+ connect(m_ui.listWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)), SLOT(updateRemoveButton()));
+ updateRemoveButton();
}
void RemoteFilterOptions::addNewItem()
@@ -57,6 +59,7 @@ void RemoteFilterOptions::addNewItem()
m_ui.listWidget->addItem(item);
item->setSelected(true);
item->setFlags(item->flags() | Qt::ItemIsEditable);
+ m_ui.listWidget->setCurrentItem(item);
m_ui.listWidget->editItem(item);
}
@@ -68,12 +71,20 @@ void RemoteFilterOptions::removeItem()
}
}
+void RemoteFilterOptions::updateRemoveButton()
+{
+ m_ui.remove->setEnabled(m_ui.listWidget->currentItem());
+}
+
// -- RemoteHelpFilter
RemoteHelpFilter::RemoteHelpFilter()
{
+ setId("RemoteHelpFilter");
+ setDisplayName(tr("Web Search"));
setIncludedByDefault(false);
setShortcutString(QLatin1String("r"));
+
m_remoteUrls.append(QLatin1String("http://www.bing.com/search?q=%1"));
m_remoteUrls.append(QLatin1String("http://www.google.com/search?q=%1"));
m_remoteUrls.append(QLatin1String("http://search.yahoo.com/search?p=%1"));
@@ -85,21 +96,6 @@ RemoteHelpFilter::~RemoteHelpFilter()
{
}
-QString RemoteHelpFilter::displayName() const
-{
- return tr("Web Search");
-}
-
-QString RemoteHelpFilter::id() const
-{
- return QLatin1String("RemoteHelpFilter");
-}
-
-Locator::ILocatorFilter::Priority RemoteHelpFilter::priority() const
-{
- return Medium;
-}
-
QList<Locator::FilterEntry> RemoteHelpFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &pattern)
{
QList<Locator::FilterEntry> entries;
@@ -116,9 +112,8 @@ QList<Locator::FilterEntry> RemoteHelpFilter::matchesFor(QFutureInterface<Locato
void RemoteHelpFilter::accept(Locator::FilterEntry selection) const
{
const QString &url = selection.displayName;
- if (!url.isEmpty()) {
+ if (!url.isEmpty())
emit linkActivated(url);
- }
}
void RemoteHelpFilter::refresh(QFutureInterface<void> &future)
diff --git a/src/plugins/help/remotehelpfilter.h b/src/plugins/help/remotehelpfilter.h
index 4f70d6781a..4bcb0c8ed6 100644
--- a/src/plugins/help/remotehelpfilter.h
+++ b/src/plugins/help/remotehelpfilter.h
@@ -47,9 +47,6 @@ public:
~RemoteHelpFilter();
// ILocatorFilter
- QString displayName() const;
- QString id() const;
- Priority priority() const;
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
@@ -78,6 +75,7 @@ public:
private slots:
void addNewItem();
void removeItem();
+ void updateRemoveButton();
private:
RemoteHelpFilter *m_filter;
diff --git a/src/plugins/help/searchwidget.cpp b/src/plugins/help/searchwidget.cpp
index 98fa67c0d5..25f5b8ade8 100644
--- a/src/plugins/help/searchwidget.cpp
+++ b/src/plugins/help/searchwidget.cpp
@@ -67,7 +67,7 @@ SearchWidget::~SearchWidget()
void SearchWidget::zoomIn()
{
- QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget);
+ QTextBrowser* browser = resultWidget->findChild<QTextBrowser*>();
if (browser && zoomCount != 10) {
zoomCount++;
browser->zoomIn();
@@ -76,7 +76,7 @@ void SearchWidget::zoomIn()
void SearchWidget::zoomOut()
{
- QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget);
+ QTextBrowser* browser = resultWidget->findChild<QTextBrowser*>();
if (browser && zoomCount != -5) {
zoomCount--;
browser->zoomOut();
@@ -88,7 +88,7 @@ void SearchWidget::resetZoom()
if (zoomCount == 0)
return;
- QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget);
+ QTextBrowser* browser = resultWidget->findChild<QTextBrowser*>();
if (browser) {
browser->zoomOut(zoomCount);
zoomCount = 0;
@@ -135,7 +135,7 @@ void SearchWidget::showEvent(QShowEvent *event)
connect(searchEngine, SIGNAL(searchingFinished(int)), this,
SLOT(searchingFinished(int)));
- QTextBrowser* browser = qFindChild<QTextBrowser*>(resultWidget);
+ QTextBrowser* browser = resultWidget->findChild<QTextBrowser*>();
browser->viewport()->installEventFilter(this);
connect(searchEngine, SIGNAL(indexingStarted()), this,
@@ -214,7 +214,7 @@ void SearchWidget::indexingFinished()
bool SearchWidget::eventFilter(QObject *o, QEvent *e)
{
- QTextBrowser *browser = qFindChild<QTextBrowser *>(resultWidget);
+ QTextBrowser *browser = resultWidget->findChild<QTextBrowser *>();
if (browser && o == browser->viewport()
&& e->type() == QEvent::MouseButtonRelease){
QMouseEvent *me = static_cast<QMouseEvent *>(e);
@@ -232,7 +232,7 @@ bool SearchWidget::eventFilter(QObject *o, QEvent *e)
void SearchWidget::contextMenuEvent(QContextMenuEvent *contextMenuEvent)
{
- QTextBrowser *browser = qFindChild<QTextBrowser *>(resultWidget);
+ QTextBrowser *browser = resultWidget->findChild<QTextBrowser *>();
if (!browser)
return;
@@ -259,11 +259,10 @@ void SearchWidget::contextMenuEvent(QContextMenuEvent *contextMenuEvent)
}
QAction *usedAction = menu.exec(mapToGlobal(contextMenuEvent->pos()));
- if (usedAction == openLink) {
+ if (usedAction == openLink)
browser->selectAll();
- } else if (usedAction == openLinkInNewTab) {
+ else if (usedAction == openLinkInNewTab)
OpenPagesManager::instance().createPageFromSearch(link);
- } else if (usedAction == copyAnchorAction) {
+ else if (usedAction == copyAnchorAction)
QApplication::clipboard()->setText(link.toString());
- }
}
diff --git a/src/plugins/imageviewer/imageviewer.cpp b/src/plugins/imageviewer/imageviewer.cpp
index 80a64247da..6ff625f3a6 100644
--- a/src/plugins/imageviewer/imageviewer.cpp
+++ b/src/plugins/imageviewer/imageviewer.cpp
@@ -73,15 +73,15 @@ ImageViewer::ImageViewer(QWidget *parent)
d->ui_toolbar.setupUi(d->toolbar);
// icons update - try to use system theme
- updateButtonIconByTheme(d->ui_toolbar.toolButtonZoomIn, "zoom-in");
- updateButtonIconByTheme(d->ui_toolbar.toolButtonZoomOut, "zoom-out");
- updateButtonIconByTheme(d->ui_toolbar.toolButtonOriginalSize, "zoom-original");
- updateButtonIconByTheme(d->ui_toolbar.toolButtonFitToScreen, "zoom-fit-best");
+ updateButtonIconByTheme(d->ui_toolbar.toolButtonZoomIn, QLatin1String("zoom-in"));
+ updateButtonIconByTheme(d->ui_toolbar.toolButtonZoomOut, QLatin1String("zoom-out"));
+ updateButtonIconByTheme(d->ui_toolbar.toolButtonOriginalSize, QLatin1String("zoom-original"));
+ updateButtonIconByTheme(d->ui_toolbar.toolButtonFitToScreen, QLatin1String("zoom-fit-best"));
// a display - something is on the background
- updateButtonIconByTheme(d->ui_toolbar.toolButtonBackground, "video-display");
+ updateButtonIconByTheme(d->ui_toolbar.toolButtonBackground, QLatin1String("video-display"));
// "emblem to specify the directory where the user stores photographs"
// (photograph has outline - piece of paper)
- updateButtonIconByTheme(d->ui_toolbar.toolButtonOutline, "emblem-photos");
+ updateButtonIconByTheme(d->ui_toolbar.toolButtonOutline, QLatin1String("emblem-photos"));
d->ui_toolbar.toolButtonZoomIn->setCommandId(Constants::ACTION_ZOOM_IN);
d->ui_toolbar.toolButtonZoomOut->setCommandId(Constants::ACTION_ZOOM_OUT);
diff --git a/src/plugins/imageviewer/imageviewer.qbs b/src/plugins/imageviewer/imageviewer.qbs
index d2257621cc..79e5528baa 100644
--- a/src/plugins/imageviewer/imageviewer.qbs
+++ b/src/plugins/imageviewer/imageviewer.qbs
@@ -8,31 +8,22 @@ QtcPlugin {
Depends { name: "Qt"; submodules: ["widgets", "svg"] }
Depends { name: "Core" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "imageviewerplugin.h",
- "imageviewerfactory.h",
- "imageviewerfile.h",
- "imageviewer.h",
+ "ImageViewer.mimetypes.xml",
+ "imageview.cpp",
"imageview.h",
- "imageviewerconstants.h",
+ "imageviewer.cpp",
+ "imageviewer.h",
+ "imageviewer.qrc",
+ "imagevieweractionhandler.cpp",
"imagevieweractionhandler.h",
- "imageviewerplugin.cpp",
+ "imageviewerconstants.h",
"imageviewerfactory.cpp",
+ "imageviewerfactory.h",
"imageviewerfile.cpp",
- "imageviewer.cpp",
- "imageview.cpp",
- "imagevieweractionhandler.cpp",
+ "imageviewerfile.h",
+ "imageviewerplugin.cpp",
+ "imageviewerplugin.h",
"imageviewertoolbar.ui",
- "imageviewer.qrc",
- "ImageViewer.mimetypes.xml"
]
}
-
diff --git a/src/plugins/imageviewer/imagevieweractionhandler.cpp b/src/plugins/imageviewer/imagevieweractionhandler.cpp
index ef309b97ec..f5fc2a2674 100644
--- a/src/plugins/imageviewer/imagevieweractionhandler.cpp
+++ b/src/plugins/imageviewer/imagevieweractionhandler.cpp
@@ -69,7 +69,7 @@ void ImageViewerActionHandler::actionTriggered(int supportedAction)
return;
SupportedActions action = static_cast<SupportedActions>(supportedAction);
- switch(action) {
+ switch (action) {
case ZoomIn:
viewer->zoomIn();
break;
diff --git a/src/plugins/imageviewer/imagevieweractionhandler.h b/src/plugins/imageviewer/imagevieweractionhandler.h
index 89ea4dc4fa..fc872f3e91 100644
--- a/src/plugins/imageviewer/imagevieweractionhandler.h
+++ b/src/plugins/imageviewer/imagevieweractionhandler.h
@@ -60,9 +60,7 @@ protected:
\param actionId Action's internal id
\param id Command id
\param title Action's title
- \param context Current context
- \param key Key sequence for the command
- \return Created and registered action, 0 if something goes wrong
+ \param key Key sequence for the commands
*/
void registerNewAction(int actionId, const Core::Id &id, const QString &title,
const QKeySequence &key);
diff --git a/src/plugins/imageviewer/imageviewerfactory.cpp b/src/plugins/imageviewer/imageviewerfactory.cpp
index 1b98ed62ed..55d501c5c4 100644
--- a/src/plugins/imageviewer/imageviewerfactory.cpp
+++ b/src/plugins/imageviewer/imageviewerfactory.cpp
@@ -95,7 +95,7 @@ QStringList ImageViewerFactory::mimeTypes() const
Core::Id ImageViewerFactory::id() const
{
- return Constants::IMAGEVIEWER_ID;
+ return Core::Id(Constants::IMAGEVIEWER_ID);
}
QString ImageViewerFactory::displayName() const
diff --git a/src/plugins/locator/basefilefilter.cpp b/src/plugins/locator/basefilefilter.cpp
index 7d46a5c237..14166a5bdf 100644
--- a/src/plugins/locator/basefilefilter.cpp
+++ b/src/plugins/locator/basefilefilter.cpp
@@ -30,12 +30,14 @@
#include "basefilefilter.h"
#include <coreplugin/editormanager/editormanager.h>
+#include <utils/fileutils.h>
#include <QDir>
#include <QStringMatcher>
using namespace Core;
using namespace Locator;
+using namespace Utils;
BaseFileFilter::BaseFileFilter()
: m_forceNewSearchList(false)
@@ -80,8 +82,8 @@ QList<FilterEntry> BaseFileFilter::matchesFor(QFutureInterface<Locator::FilterEn
|| (!hasWildcard && matcher.indexIn(name) != -1)) {
QFileInfo fi(path);
FilterEntry entry(this, fi.fileName(), QString(path + lineNoSuffix));
- entry.extraInfo = QDir::toNativeSeparators(fi.path());
- entry.resolveFileIcon = true;
+ entry.extraInfo = FileUtils::shortNativePath(FileName(fi));
+ entry.fileName = path;
if (name.startsWith(needle))
matches.append(entry);
else
diff --git a/src/plugins/locator/commandlocator.cpp b/src/plugins/locator/commandlocator.cpp
index 092b013a46..a7537eb454 100644
--- a/src/plugins/locator/commandlocator.cpp
+++ b/src/plugins/locator/commandlocator.cpp
@@ -38,24 +38,20 @@
namespace Locator {
-struct CommandLocatorPrivate {
- CommandLocatorPrivate(const QString &prefix,
- const QString &displayName) :
- m_prefix(prefix), m_displayName(displayName) {}
-
- const QString m_prefix;
- const QString m_displayName;
-
+struct CommandLocatorPrivate
+{
QList<Core::Command *> commands;
};
-CommandLocator::CommandLocator(const QString &prefix,
+CommandLocator::CommandLocator(Core::Id id,
const QString &displayName,
const QString &shortCutString,
QObject *parent) :
Locator::ILocatorFilter(parent),
- d(new CommandLocatorPrivate(prefix, displayName))
+ d(new CommandLocatorPrivate)
{
+ setId(id);
+ setDisplayName(displayName);
setShortcutString(shortCutString);
}
@@ -69,21 +65,6 @@ void CommandLocator::appendCommand(Core::Command *cmd)
d->commands.push_back(cmd);
}
-QString CommandLocator::displayName() const
-{
- return d->m_displayName;
-}
-
-QString CommandLocator::id() const
-{
- return d->m_prefix;
-}
-
-ILocatorFilter::Priority CommandLocator::priority() const
-{
- return Medium;
-}
-
QList<Locator::FilterEntry> CommandLocator::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry)
{
QList<FilterEntry> filters;
@@ -99,9 +80,8 @@ QList<Locator::FilterEntry> CommandLocator::matchesFor(QFutureInterface<Locator:
if (action->isEnabled()) {
QString text = action->text();
text.remove(ampersand);
- if (text.contains(entry, Qt::CaseInsensitive)) {
+ if (text.contains(entry, Qt::CaseInsensitive))
filters.append(FilterEntry(this, text, QVariant(i)));
- }
}
}
}
diff --git a/src/plugins/locator/commandlocator.h b/src/plugins/locator/commandlocator.h
index 72b54d555d..b33000d006 100644
--- a/src/plugins/locator/commandlocator.h
+++ b/src/plugins/locator/commandlocator.h
@@ -32,15 +32,8 @@
#include "locator_global.h"
#include "ilocatorfilter.h"
-#include <QList>
-QT_BEGIN_NAMESPACE
-class QAction;
-QT_END_NAMESPACE
-
-namespace Core {
- class Command;
-}
+namespace Core { class Command; }
namespace Locator {
/* Command locators: Provides completion for a set of
@@ -53,31 +46,20 @@ class LOCATOR_EXPORT CommandLocator : public Locator::ILocatorFilter
Q_OBJECT
public:
- explicit CommandLocator(const QString &prefix,
- const QString &displayName,
- const QString &shortCutString,
- QObject *parent = 0);
- virtual ~CommandLocator();
+ CommandLocator(Core::Id id, const QString &displayName,
+ const QString &shortCutString, QObject *parent = 0);
+ ~CommandLocator();
void appendCommand(Core::Command *cmd);
- virtual QString displayName() const;
- virtual QString id() const;
- virtual Priority priority() const;
- virtual QList<FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
- virtual void accept(FilterEntry selection) const;
- virtual void refresh(QFutureInterface<void> &future);
+ QList<FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
+ void accept(FilterEntry selection) const;
+ void refresh(QFutureInterface<void> &future);
private:
CommandLocatorPrivate *d;
};
-inline CommandLocator &operator<<(CommandLocator &locator, Core::Command *cmd)
-{
- locator.appendCommand(cmd);
- return locator;
-}
-
} // namespace Locator
#endif // COMMANDLOCATOR_H
diff --git a/src/plugins/locator/directoryfilter.cpp b/src/plugins/locator/directoryfilter.cpp
index fa551225ef..b5c6b12a43 100644
--- a/src/plugins/locator/directoryfilter.cpp
+++ b/src/plugins/locator/directoryfilter.cpp
@@ -43,11 +43,16 @@ using namespace Locator::Internal;
DirectoryFilter::DirectoryFilter()
: m_name(tr("Generic Directory Filter")),
- m_filters(QStringList() << QLatin1String("*.h") << QLatin1String("*.cpp")
- << QLatin1String("*.ui") << QLatin1String("*.qrc")),
m_dialog(0)
{
+ setId(Core::Id::fromString(m_name));
setIncludedByDefault(true);
+ setDisplayName(m_name);
+
+ m_filters.append(QLatin1String("*.h"));
+ m_filters.append(QLatin1String("*.cpp"));
+ m_filters.append(QLatin1String("*.ui"));
+ m_filters.append(QLatin1String("*.qrc"));
}
QByteArray DirectoryFilter::saveState() const
@@ -138,9 +143,8 @@ bool DirectoryFilter::openConfigDialog(QWidget *parent, bool &needsRefresh)
void DirectoryFilter::addDirectory()
{
QString dir = QFileDialog::getExistingDirectory(m_dialog, tr("Select Directory"));
- if (!dir.isEmpty()) {
+ if (!dir.isEmpty())
m_ui.directoryList->addItem(dir);
- }
}
void DirectoryFilter::editDirectory()
@@ -150,9 +154,8 @@ void DirectoryFilter::editDirectory()
QListWidgetItem *currentItem = m_ui.directoryList->selectedItems().at(0);
QString dir = QFileDialog::getExistingDirectory(m_dialog, tr("Select Directory"),
currentItem->text());
- if (!dir.isEmpty()) {
+ if (!dir.isEmpty())
currentItem->setText(dir);
- }
}
void DirectoryFilter::removeDirectory()
diff --git a/src/plugins/locator/directoryfilter.h b/src/plugins/locator/directoryfilter.h
index be5ee6ffa6..2f8c067943 100644
--- a/src/plugins/locator/directoryfilter.h
+++ b/src/plugins/locator/directoryfilter.h
@@ -48,9 +48,6 @@ class DirectoryFilter : public BaseFileFilter
public:
DirectoryFilter();
- QString displayName() const { return m_name; }
- QString id() const { return m_name; }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::Medium; }
QByteArray saveState() const;
bool restoreState(const QByteArray &state);
bool openConfigDialog(QWidget *parent, bool &needsRefresh);
diff --git a/src/plugins/locator/executefilter.cpp b/src/plugins/locator/executefilter.cpp
index fbcf8313e7..c6545515d3 100644
--- a/src/plugins/locator/executefilter.cpp
+++ b/src/plugins/locator/executefilter.cpp
@@ -41,6 +41,8 @@ using namespace Locator::Internal;
ExecuteFilter::ExecuteFilter()
{
+ setId("Execute custom commands");
+ setDisplayName(tr("Execute Custom Commands"));
setShortcutString(QString(QLatin1Char('!')));
setIncludedByDefault(false);
diff --git a/src/plugins/locator/executefilter.h b/src/plugins/locator/executefilter.h
index fc8f984344..338b7d2f26 100644
--- a/src/plugins/locator/executefilter.h
+++ b/src/plugins/locator/executefilter.h
@@ -53,9 +53,6 @@ class ExecuteFilter : public Locator::ILocatorFilter
public:
ExecuteFilter();
- QString displayName() const { return tr("Execute Custom Commands"); }
- QString id() const { return QLatin1String("Execute custom commands"); }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::Medium; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future,
const QString &entry);
void accept(Locator::FilterEntry selection) const;
diff --git a/src/plugins/locator/filesystemfilter.cpp b/src/plugins/locator/filesystemfilter.cpp
index a02e606b9e..212d494b3d 100644
--- a/src/plugins/locator/filesystemfilter.cpp
+++ b/src/plugins/locator/filesystemfilter.cpp
@@ -41,6 +41,8 @@ using namespace Locator::Internal;
FileSystemFilter::FileSystemFilter(EditorManager *editorManager, LocatorWidget *locatorWidget)
: m_editorManager(editorManager), m_locatorWidget(locatorWidget), m_includeHidden(true)
{
+ setId("Files in file system");
+ setDisplayName(tr("Files in File System"));
setShortcutString(QString(QLatin1Char('f')));
setIncludedByDefault(false);
}
@@ -64,7 +66,7 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
}
}
QDir dirInfo(directory);
- QDir::Filters dirFilter = QDir::Dirs|QDir::Drives;
+ QDir::Filters dirFilter = QDir::Dirs|QDir::Drives|QDir::NoDot;
QDir::Filters fileFilter = QDir::Files;
if (m_includeHidden) {
dirFilter |= QDir::Hidden;
@@ -77,10 +79,10 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
foreach (const QString &dir, dirs) {
if (future.isCanceled())
break;
- if (dir != QLatin1String(".") && (name.isEmpty() || dir.startsWith(name, Qt::CaseInsensitive))) {
+ if (name.isEmpty() || dir.startsWith(name, Qt::CaseInsensitive)) {
const QString fullPath = dirInfo.filePath(dir);
- FilterEntry filterEntry(this, dir, fullPath);
- filterEntry.resolveFileIcon = true;
+ FilterEntry filterEntry(this, dir, QVariant());
+ filterEntry.fileName = fullPath;
value.append(filterEntry);
}
}
@@ -94,7 +96,7 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
if (name.isEmpty() || file.startsWith(name, Qt::CaseInsensitive)) {
const QString fullPath = dirInfo.filePath(file);
FilterEntry filterEntry(this, file, QString(fullPath + lineNoSuffix));
- filterEntry.resolveFileIcon = true;
+ filterEntry.fileName = fullPath;
value.append(filterEntry);
}
}
@@ -103,8 +105,8 @@ QList<FilterEntry> FileSystemFilter::matchesFor(QFutureInterface<Locator::Filter
void FileSystemFilter::accept(FilterEntry selection) const
{
- QString file = selection.internalData.toString();
- QFileInfo info(file);
+ QString fileName = selection.fileName;
+ QFileInfo info(fileName);
if (info.isDir()) {
QString value = shortcutString();
value += QLatin1Char(' ');
@@ -112,7 +114,7 @@ void FileSystemFilter::accept(FilterEntry selection) const
m_locatorWidget->show(value, value.length());
return;
}
- EditorManager::openEditor(file, Id(),
+ EditorManager::openEditor(selection.internalData.toString(), Id(),
EditorManager::ModeSwitch | EditorManager::CanContainLineNumber);
}
diff --git a/src/plugins/locator/filesystemfilter.h b/src/plugins/locator/filesystemfilter.h
index 0e7f63d9f5..6a4f9db7b3 100644
--- a/src/plugins/locator/filesystemfilter.h
+++ b/src/plugins/locator/filesystemfilter.h
@@ -38,9 +38,7 @@
#include <QByteArray>
#include <QFutureInterface>
-namespace Core {
- class EditorManager;
-}
+namespace Core { class EditorManager; }
namespace Locator {
namespace Internal {
@@ -53,9 +51,6 @@ class FileSystemFilter : public Locator::ILocatorFilter
public:
FileSystemFilter(Core::EditorManager *editorManager, LocatorWidget *locatorWidget);
- QString displayName() const { return tr("Files in File System"); }
- QString id() const { return QLatin1String("Files in file system"); }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::Medium; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
QByteArray saveState() const;
diff --git a/src/plugins/locator/ilocatorfilter.cpp b/src/plugins/locator/ilocatorfilter.cpp
index 7f7e42bbc8..16521dc5f1 100644
--- a/src/plugins/locator/ilocatorfilter.cpp
+++ b/src/plugins/locator/ilocatorfilter.cpp
@@ -40,9 +40,11 @@ using namespace Locator;
ILocatorFilter::ILocatorFilter(QObject *parent):
QObject(parent),
+ m_priority(Medium),
m_includedByDefault(false),
m_hidden(false),
- m_enabled(true)
+ m_enabled(true),
+ m_isConfigurable(true)
{
}
@@ -114,9 +116,25 @@ bool ILocatorFilter::openConfigDialog(QWidget *parent, bool &needsRefresh)
return false;
}
+QString ILocatorFilter::trimWildcards(const QString &str)
+{
+ if (str.isEmpty())
+ return str;
+ int first = 0, last = str.size()-1;
+ const QChar asterisk = QLatin1Char('*');
+ const QChar question = QLatin1Char('?');
+ while (first < str.size() && (str.at(first) == asterisk || str.at(first) == question))
+ ++first;
+ while (last >= 0 && (str.at(last) == asterisk || str.at(last) == question))
+ --last;
+ if (first > last)
+ return QString();
+ return str.mid(first, last-first+1);
+}
+
bool ILocatorFilter::isConfigurable() const
{
- return true;
+ return m_isConfigurable;
}
bool ILocatorFilter::isIncludedByDefault() const
@@ -144,7 +162,42 @@ bool ILocatorFilter::isEnabled() const
return m_enabled;
}
+Core::Id ILocatorFilter::id() const
+{
+ return m_id;
+}
+
+QString ILocatorFilter::displayName() const
+{
+ return m_displayName;
+}
+
+ILocatorFilter::Priority ILocatorFilter::priority() const
+{
+ return m_priority;
+}
+
void ILocatorFilter::setEnabled(bool enabled)
{
m_enabled = enabled;
}
+
+void ILocatorFilter::setId(Core::Id id)
+{
+ m_id = id;
+}
+
+void ILocatorFilter::setPriority(Priority priority)
+{
+ m_priority = priority;
+}
+
+void ILocatorFilter::setDisplayName(const QString &displayString)
+{
+ m_displayName = displayString;
+}
+
+void ILocatorFilter::setConfigurable(bool configurable)
+{
+ m_isConfigurable = configurable;
+}
diff --git a/src/plugins/locator/ilocatorfilter.h b/src/plugins/locator/ilocatorfilter.h
index 5a6d19e519..331b17e847 100644
--- a/src/plugins/locator/ilocatorfilter.h
+++ b/src/plugins/locator/ilocatorfilter.h
@@ -32,6 +32,8 @@
#include "locator_global.h"
+#include <coreplugin/id.h>
+
#include <QVariant>
#include <QFutureInterface>
#include <QIcon>
@@ -44,7 +46,7 @@ struct FilterEntry
{
FilterEntry()
: filter(0)
- , resolveFileIcon(false)
+ , fileIconResolved(false)
{}
FilterEntry(ILocatorFilter *fromFilter, const QString &name, const QVariant &data,
@@ -53,7 +55,7 @@ struct FilterEntry
, displayName(name)
, internalData(data)
, displayIcon(icon)
- , resolveFileIcon(false)
+ , fileIconResolved(false)
{}
bool operator==(const FilterEntry &other) const {
@@ -72,8 +74,10 @@ struct FilterEntry
QVariant internalData;
/* icon to display along with the entry */
QIcon displayIcon;
- /* internal data is interpreted as file name and icon is retrieved from the file system if true */
- bool resolveFileIcon;
+ /* file name, if the entry is related to a file, is used e.g. for resolving a file icon */
+ QString fileName;
+ /* internal */
+ bool fileIconResolved;
};
class LOCATOR_EXPORT ILocatorFilter : public QObject
@@ -86,14 +90,14 @@ public:
ILocatorFilter(QObject *parent = 0);
virtual ~ILocatorFilter() {}
- /* Visible name. */
- virtual QString displayName() const = 0;
+ /* Internal Id. */
+ Core::Id id() const;
- /* Internal name. */
- virtual QString id() const = 0;
+ /* Visible name. */
+ QString displayName() const;
/* Selection list order in case of multiple active filters (high goes on top). */
- virtual Priority priority() const = 0;
+ Priority priority() const;
/* String to type to use this filter exclusively. */
QString shortcutString() const;
@@ -122,7 +126,7 @@ public:
/* If there is a configure dialog available for this filter. The default
* implementation returns true. */
- virtual bool isConfigurable() const;
+ bool isConfigurable() const;
/* Is this filter used also when the shortcutString is not used? */
bool isIncludedByDefault() const;
@@ -133,20 +137,7 @@ public:
/* Returns whether the filter should be enabled and used in menus. */
bool isEnabled() const;
- static QString trimWildcards(const QString &str) {
- if (str.isEmpty())
- return str;
- int first = 0, last = str.size()-1;
- const QChar asterisk = QLatin1Char('*');
- const QChar question = QLatin1Char('?');
- while (first < str.size() && (str.at(first) == asterisk || str.at(first) == question))
- ++first;
- while (last >= 0 && (str.at(last) == asterisk || str.at(last) == question))
- --last;
- if (first > last)
- return QString();
- return str.mid(first, last-first+1);
- }
+ static QString trimWildcards(const QString &str);
public slots:
/* Enable or disable the filter. */
@@ -156,12 +147,20 @@ protected:
void setShortcutString(const QString &shortcut);
void setIncludedByDefault(bool includedByDefault);
void setHidden(bool hidden);
+ void setId(Core::Id id);
+ void setPriority(Priority priority);
+ void setDisplayName(const QString &displayString);
+ void setConfigurable(bool configurable);
private:
+ Core::Id m_id;
QString m_shortcut;
+ Priority m_priority;
+ QString m_displayName;
bool m_includedByDefault;
bool m_hidden;
bool m_enabled;
+ bool m_isConfigurable;
};
} // namespace Locator
diff --git a/src/plugins/locator/locator.qbs b/src/plugins/locator/locator.qbs
index 651fece80a..af809cfd84 100644
--- a/src/plugins/locator/locator.qbs
+++ b/src/plugins/locator/locator.qbs
@@ -9,32 +9,29 @@ QtcPlugin {
Depends { name: "Core" }
Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
- "..",
+ cpp.includePaths: base.concat([
"generichighlighter",
"tooltip",
"snippets",
- "codeassist",
- "../../libs",
- buildDirectory
- ]
+ "codeassist"
+ ])
files: [
- "directoryfilter.ui",
- "filesystemfilter.ui",
- "locator.qrc",
- "settingspage.ui",
"basefilefilter.cpp",
"basefilefilter.h",
"commandlocator.cpp",
"commandlocator.h",
"directoryfilter.cpp",
"directoryfilter.h",
+ "directoryfilter.ui",
+ "executefilter.cpp",
"executefilter.h",
"filesystemfilter.cpp",
"filesystemfilter.h",
+ "filesystemfilter.ui",
"ilocatorfilter.cpp",
+ "ilocatorfilter.h",
+ "locator.qrc",
"locator_global.h",
"locatorconstants.h",
"locatorfiltersfilter.cpp",
@@ -43,16 +40,14 @@ QtcPlugin {
"locatormanager.h",
"locatorplugin.cpp",
"locatorplugin.h",
+ "locatorwidget.cpp",
+ "locatorwidget.h",
"opendocumentsfilter.cpp",
"opendocumentsfilter.h",
"settingspage.cpp",
"settingspage.h",
- "executefilter.cpp",
- "ilocatorfilter.h",
- "locatorwidget.cpp",
- "locatorwidget.h",
+ "settingspage.ui",
"images/locator.png",
- "images/reload.png"
+ "images/reload.png",
]
}
-
diff --git a/src/plugins/locator/locatorfiltersfilter.cpp b/src/plugins/locator/locatorfiltersfilter.cpp
index ef44fd10f6..18300038aa 100644
--- a/src/plugins/locator/locatorfiltersfilter.cpp
+++ b/src/plugins/locator/locatorfiltersfilter.cpp
@@ -44,23 +44,12 @@ LocatorFiltersFilter::LocatorFiltersFilter(LocatorPlugin *plugin,
m_locatorWidget(locatorWidget),
m_icon(QIcon(QLatin1String(Core::Constants::ICON_NEXT)))
{
+ setId("FiltersFilter");
+ setDisplayName(tr("Available filters"));
setIncludedByDefault(true);
setHidden(true);
-}
-
-QString LocatorFiltersFilter::displayName() const
-{
- return tr("Available filters");
-}
-
-QString LocatorFiltersFilter::id() const
-{
- return QLatin1String("FiltersFilter");
-}
-
-ILocatorFilter::Priority LocatorFiltersFilter::priority() const
-{
- return High;
+ setPriority(High);
+ setConfigurable(false);
}
QList<FilterEntry> LocatorFiltersFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry)
@@ -104,8 +93,3 @@ void LocatorFiltersFilter::refresh(QFutureInterface<void> &future)
Q_UNUSED(future)
// Nothing to refresh
}
-
-bool LocatorFiltersFilter::isConfigurable() const
-{
- return false;
-}
diff --git a/src/plugins/locator/locatorfiltersfilter.h b/src/plugins/locator/locatorfiltersfilter.h
index e1739eec2c..fe81e63d9c 100644
--- a/src/plugins/locator/locatorfiltersfilter.h
+++ b/src/plugins/locator/locatorfiltersfilter.h
@@ -53,13 +53,9 @@ public:
LocatorWidget *locatorWidget);
// ILocatorFilter
- QString displayName() const;
- QString id() const;
- Priority priority() const;
QList<FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
- bool isConfigurable() const;
private:
LocatorPlugin *m_plugin;
diff --git a/src/plugins/locator/locatorplugin.cpp b/src/plugins/locator/locatorplugin.cpp
index 589cdd46ae..a849e565f4 100644
--- a/src/plugins/locator/locatorplugin.cpp
+++ b/src/plugins/locator/locatorplugin.cpp
@@ -74,9 +74,7 @@ namespace {
return true;
if (first->priority() > second->priority())
return false;
- if (first->id().compare(second->id(), Qt::CaseInsensitive) < 0)
- return true;
- return false;
+ return first->id().alphabeticallyBefore(second->id());
}
}
@@ -200,7 +198,7 @@ void LocatorPlugin::saveSettings()
s->setValue(QLatin1String("RefreshInterval"), refreshInterval());
foreach (ILocatorFilter *filter, m_filters) {
if (!m_customFilters.contains(filter))
- s->setValue(filter->id(), filter->saveState());
+ s->setValue(filter->id().toString(), filter->saveState());
}
s->beginGroup(QLatin1String("CustomFilters"));
int i = 0;
diff --git a/src/plugins/locator/locatorplugin.h b/src/plugins/locator/locatorplugin.h
index 66df5ee8b1..5488561e29 100644
--- a/src/plugins/locator/locatorplugin.h
+++ b/src/plugins/locator/locatorplugin.h
@@ -108,8 +108,8 @@ void LocatorPlugin::loadSettingsHelper(S *settings)
m_refreshTimer.setInterval(settings->value(QLatin1String("RefreshInterval"), 60).toInt() * 60000);
foreach (ILocatorFilter *filter, m_filters) {
- if (settings->contains(filter->id())) {
- const QByteArray state = settings->value(filter->id()).toByteArray();
+ if (settings->contains(filter->id().toString())) {
+ const QByteArray state = settings->value(filter->id().toString()).toByteArray();
if (!state.isEmpty())
filter->restoreState(state);
}
diff --git a/src/plugins/locator/locatorwidget.cpp b/src/plugins/locator/locatorwidget.cpp
index c40a6bbf88..cee7a8588e 100644
--- a/src/plugins/locator/locatorwidget.cpp
+++ b/src/plugins/locator/locatorwidget.cpp
@@ -44,6 +44,7 @@
#include <coreplugin/coreconstants.h>
#include <coreplugin/fileiconprovider.h>
#include <utils/filterlineedit.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/runextensions.h>
@@ -72,6 +73,8 @@
Q_DECLARE_METATYPE(Locator::ILocatorFilter*)
Q_DECLARE_METATYPE(Locator::FilterEntry)
+using namespace Core;
+
namespace Locator {
namespace Internal {
@@ -173,11 +176,10 @@ QVariant LocatorModel::data(const QModelIndex &index, int role) const
return QVariant();
if (role == Qt::DisplayRole) {
- if (index.column() == 0) {
+ if (index.column() == 0)
return mEntries.at(index.row()).displayName;
- } else if (index.column() == 1) {
+ else if (index.column() == 1)
return mEntries.at(index.row()).extraInfo;
- }
} else if (role == Qt::ToolTipRole) {
if (mEntries.at(index.row()).extraInfo.isEmpty())
return QVariant(mEntries.at(index.row()).displayName);
@@ -186,11 +188,9 @@ QVariant LocatorModel::data(const QModelIndex &index, int role) const
+ QLatin1String("\n\n") + mEntries.at(index.row()).extraInfo);
} else if (role == Qt::DecorationRole && index.column() == 0) {
FilterEntry &entry = mEntries[index.row()];
- if (entry.resolveFileIcon && entry.displayIcon.isNull()) {
- entry.resolveFileIcon = false;
- QString path = entry.internalData.toString();
- Core::EditorManager::splitLineNumber(&path);
- entry.displayIcon = Core::FileIconProvider::instance()->icon(QFileInfo(path));
+ if (!entry.fileIconResolved && !entry.fileName.isEmpty() && entry.displayIcon.isNull()) {
+ entry.fileIconResolved = true;
+ entry.displayIcon = Core::FileIconProvider::instance()->icon(QFileInfo(entry.fileName));
}
return entry.displayIcon;
} else if (role == Qt::ForegroundRole && index.column() == 1) {
@@ -204,8 +204,9 @@ QVariant LocatorModel::data(const QModelIndex &index, int role) const
void LocatorModel::setEntries(const QList<FilterEntry> &entries)
{
+ beginResetModel();
mEntries = entries;
- reset();
+ endResetModel();
}
// =========== CompletionList ===========
@@ -221,12 +222,12 @@ CompletionList::CompletionList(QWidget *parent)
// This is too slow when done on all results
//header()->setResizeMode(QHeaderView::ResizeToContents);
setWindowFlags(Qt::ToolTip);
-#ifdef Q_OS_MAC
- if (horizontalScrollBar())
- horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
- if (verticalScrollBar())
- verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ if (horizontalScrollBar())
+ horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
+ if (verticalScrollBar())
+ verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
+ }
}
void CompletionList::updatePreferredSize()
@@ -248,7 +249,8 @@ LocatorWidget::LocatorWidget(LocatorPlugin *qop) :
m_configureAction(new QAction(tr("Configure..."), this)),
m_fileLineEdit(new Utils::FilterLineEdit),
m_updateRequested(false),
- m_acceptRequested(false)
+ m_acceptRequested(false),
+ m_possibleToolTipRequest(false)
{
// Explicitly hide the completion list popup.
m_completionList->hide();
@@ -316,36 +318,36 @@ void LocatorWidget::updateFilterList()
m_filterMenu->clear();
// update actions and menu
- QMap<QString, QAction *> actionCopy = m_filterActionMap;
+ QMap<Id, QAction *> actionCopy = m_filterActionMap;
m_filterActionMap.clear();
// register new actions, update existent
foreach (ILocatorFilter *filter, m_locatorPlugin->filters()) {
if (filter->shortcutString().isEmpty() || filter->isHidden())
continue;
- Core::Id locatorId = Core::Id(QLatin1String("Locator.") + filter->id());
+ Id filterId = filter->id();
+ Id locatorId = filterId.withPrefix("Locator.");
QAction *action = 0;
- Core::Command *cmd = 0;
- if (!actionCopy.contains(filter->id())) {
+ Command *cmd = 0;
+ if (!actionCopy.contains(filterId)) {
// register new action
action = new QAction(filter->displayName(), this);
- cmd = Core::ActionManager::registerAction(action, locatorId,
- Core::Context(Core::Constants::C_GLOBAL));
- cmd->setAttribute(Core::Command::CA_UpdateText);
+ cmd = ActionManager::registerAction(action, locatorId,
+ Context(Core::Constants::C_GLOBAL));
+ cmd->setAttribute(Command::CA_UpdateText);
connect(action, SIGNAL(triggered()), this, SLOT(filterSelected()));
action->setData(qVariantFromValue(filter));
} else {
- action = actionCopy.take(filter->id());
- action->setText(filter->displayName());
- cmd = Core::ActionManager::command(locatorId);
+ action = actionCopy.take(filterId);
+ action->setText(filterId.toString());
+ cmd = ActionManager::command(locatorId);
}
- m_filterActionMap.insert(filter->id(), action);
+ m_filterActionMap.insert(filterId, action);
m_filterMenu->addAction(cmd->action());
}
// unregister actions that are deleted now
- foreach (const QString &id, actionCopy.keys()) {
- Core::ActionManager::unregisterAction(actionCopy.value(id), Core::Id(QLatin1String("Locator.") + id));
- }
+ foreach (const Id id, actionCopy.keys())
+ ActionManager::unregisterAction(actionCopy.value(id), id.withPrefix("Locator."));
qDeleteAll(actionCopy);
m_filterMenu->addSeparator();
@@ -408,11 +410,14 @@ bool LocatorWidget::eventFilter(QObject *obj, QEvent *event)
}
}
} else if (obj == m_fileLineEdit && event->type() == QEvent::FocusOut) {
-#if defined(Q_OS_WIN)
- QFocusEvent *fev = static_cast<QFocusEvent*>(event);
- if (fev->reason() != Qt::ActiveWindowFocusReason ||
- (fev->reason() == Qt::ActiveWindowFocusReason && !m_completionList->isActiveWindow()))
-#endif
+ bool hideList = true;
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ QFocusEvent *fev = static_cast<QFocusEvent*>(event);
+ if (fev->reason() == Qt::ActiveWindowFocusReason &&
+ !(fev->reason() == Qt::ActiveWindowFocusReason && !m_completionList->isActiveWindow()))
+ hideList = false;
+ }
+ if (hideList)
m_completionList->hide();
} else if (obj == m_fileLineEdit && event->type() == QEvent::FocusIn) {
showPopupNow();
@@ -535,9 +540,8 @@ void LocatorWidget::updateEntries()
const QList<FilterEntry> entries = m_entriesWatcher->future().results();
m_locatorModel->setEntries(entries);
- if (m_locatorModel->rowCount() > 0) {
+ if (m_locatorModel->rowCount() > 0)
m_completionList->setCurrentIndex(m_locatorModel->index(0, 0));
- }
#if 0
m_completionList->updatePreferredSize();
#endif
@@ -619,6 +623,5 @@ void LocatorWidget::showEvent(QShowEvent *event)
void LocatorWidget::showConfigureDialog()
{
- Core::ICore::showOptionsDialog(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE),
- QLatin1String(Constants::FILTER_OPTIONS_PAGE));
+ ICore::showOptionsDialog(Core::Constants::SETTINGS_CATEGORY_CORE, Constants::FILTER_OPTIONS_PAGE);
}
diff --git a/src/plugins/locator/locatorwidget.h b/src/plugins/locator/locatorwidget.h
index 25f1cbbd32..547d17c5c6 100644
--- a/src/plugins/locator/locatorwidget.h
+++ b/src/plugins/locator/locatorwidget.h
@@ -95,7 +95,7 @@ private:
Utils::FilterLineEdit *m_fileLineEdit;
QTimer *m_showPopupTimer;
QFutureWatcher<FilterEntry> *m_entriesWatcher;
- QMap<QString, QAction *> m_filterActionMap;
+ QMap<Core::Id, QAction *> m_filterActionMap;
bool m_updateRequested;
bool m_acceptRequested;
bool m_possibleToolTipRequest;
diff --git a/src/plugins/locator/opendocumentsfilter.cpp b/src/plugins/locator/opendocumentsfilter.cpp
index e4197dd2eb..0409515515 100644
--- a/src/plugins/locator/opendocumentsfilter.cpp
+++ b/src/plugins/locator/opendocumentsfilter.cpp
@@ -31,6 +31,7 @@
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
+#include <utils/fileutils.h>
#include <QFileInfo>
#include <QDir>
@@ -38,16 +39,20 @@
using namespace Core;
using namespace Locator;
using namespace Locator::Internal;
+using namespace Utils;
OpenDocumentsFilter::OpenDocumentsFilter(EditorManager *editorManager) :
m_editorManager(editorManager)
{
+ setId("Open documents");
+ setDisplayName(tr("Open Documents"));
+ setShortcutString(QString(QLatin1Char('o')));
+ setIncludedByDefault(true);
+
connect(m_editorManager, SIGNAL(editorOpened(Core::IEditor*)),
this, SLOT(refreshInternally()));
connect(m_editorManager, SIGNAL(editorsClosed(QList<Core::IEditor*>)),
this, SLOT(refreshInternally()));
- setShortcutString(QString(QLatin1Char('o')));
- setIncludedByDefault(true);
}
QList<FilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry_)
@@ -71,8 +76,8 @@ QList<FilterEntry> OpenDocumentsFilter::matchesFor(QFutureInterface<Locator::Fil
if (!fileName.isEmpty()) {
QFileInfo fi(fileName);
FilterEntry fiEntry(this, fi.fileName(), QString(fileName + lineNoSuffix));
- fiEntry.extraInfo = QDir::toNativeSeparators(fi.path());
- fiEntry.resolveFileIcon = true;
+ fiEntry.extraInfo = FileUtils::shortNativePath(FileName(fi));
+ fiEntry.fileName = fileName;
value.append(fiEntry);
}
}
diff --git a/src/plugins/locator/opendocumentsfilter.h b/src/plugins/locator/opendocumentsfilter.h
index 02e455d2d0..a60abbd735 100644
--- a/src/plugins/locator/opendocumentsfilter.h
+++ b/src/plugins/locator/opendocumentsfilter.h
@@ -52,9 +52,6 @@ class OpenDocumentsFilter : public Locator::ILocatorFilter
public:
explicit OpenDocumentsFilter(Core::EditorManager *editorManager);
- QString displayName() const { return tr("Open Documents"); }
- QString id() const { return QLatin1String("Open documents"); }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::Medium; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/locator/settingspage.cpp b/src/plugins/locator/settingspage.cpp
index 2b8a6f7582..7d282de261 100644
--- a/src/plugins/locator/settingspage.cpp
+++ b/src/plugins/locator/settingspage.cpp
@@ -50,7 +50,7 @@ SettingsPage::SettingsPage(LocatorPlugin *plugin)
{
setId(Constants::FILTER_OPTIONS_PAGE);
setDisplayName(QCoreApplication::translate("Locator", Locator::Constants::FILTER_OPTIONS_PAGE));
- setCategory(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE));
+ setCategory(Core::Constants::SETTINGS_CATEGORY_CORE);
setDisplayCategory(QCoreApplication::translate("Core", Core::Constants::SETTINGS_TR_CATEGORY_CORE));
setCategoryIcon(QLatin1String(Core::Constants::SETTINGS_CATEGORY_CORE_ICON));
}
diff --git a/src/plugins/locator/settingspage.ui b/src/plugins/locator/settingspage.ui
index 6ae70a06f2..e600ca1ced 100644
--- a/src/plugins/locator/settingspage.ui
+++ b/src/plugins/locator/settingspage.ui
@@ -69,6 +69,9 @@
<layout class="QHBoxLayout">
<item>
<widget class="QLabel" name="refreshIntervalLabel">
+ <property name="toolTip">
+ <string>Locator filters that do not update their cached data immediately, such as the custom directory filters, update it after this time interval.</string>
+ </property>
<property name="text">
<string>Refresh interval:</string>
</property>
diff --git a/src/plugins/macros/actionmacrohandler.cpp b/src/plugins/macros/actionmacrohandler.cpp
index f9127b8da6..da2bb4e1bd 100644
--- a/src/plugins/macros/actionmacrohandler.cpp
+++ b/src/plugins/macros/actionmacrohandler.cpp
@@ -31,26 +31,27 @@
#include "macroevent.h"
#include "macro.h"
-#include <texteditor/texteditorconstants.h>
-
-#include <coreplugin/icore.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/command.h>
#include <coreplugin/coreconstants.h>
-#include <coreplugin/id.h>
#include <coreplugin/icontext.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/id.h>
-#include <QObject>
+#include <texteditor/texteditorconstants.h>
+
+#include <QAction>
#include <QEvent>
+#include <QObject>
+#include <QShortcut>
#include <QSignalMapper>
-#include <QtAlgorithms>
#include <QStringList>
+#include <QtAlgorithms>
-#include <QAction>
-#include <QShortcut>
+using namespace Core;
-using namespace Macros;
-using namespace Macros::Internal;
+namespace Macros {
+namespace Internal {
static const char EVENTNAME[] = "Action";
static quint8 ACTIONNAME = 0;
@@ -61,27 +62,25 @@ ActionMacroHandler::ActionMacroHandler():
connect(m_mapper, SIGNAL(mapped(QString)),
this, SLOT(addActionEvent(QString)));
- connect(Core::ActionManager::instance(), SIGNAL(commandAdded(QString)),
+ connect(ActionManager::instance(), SIGNAL(commandAdded(QString)),
this, SLOT(addCommand(QString)));
// Register all existing scriptable actions
- QList<Core::Command *> commands = Core::ActionManager::commands();
- foreach (Core::Command *command, commands) {
- if (command->isScriptable()) {
- QString id = command->id().toString();
- registerCommand(id);
- }
+ QList<Command *> commands = ActionManager::commands();
+ foreach (Command *command, commands) {
+ if (command->isScriptable())
+ registerCommand(command->id());
}
}
bool ActionMacroHandler::canExecuteEvent(const MacroEvent &macroEvent)
{
- return (macroEvent.id() == EVENTNAME);
+ return macroEvent.id() == EVENTNAME;
}
bool ActionMacroHandler::executeEvent(const MacroEvent &macroEvent)
{
- QAction *action = Core::ActionManager::command(Core::Id(macroEvent.value(ACTIONNAME).toString()))->action();
+ QAction *action = ActionManager::command(Id::fromSetting(macroEvent.value(ACTIONNAME)))->action();
if (!action)
return false;
@@ -89,40 +88,45 @@ bool ActionMacroHandler::executeEvent(const MacroEvent &macroEvent)
return true;
}
-void ActionMacroHandler::addActionEvent(const QString &id)
+void ActionMacroHandler::addActionEvent(const QString &name)
{
if (!isRecording())
return;
- const Core::Command *cmd = Core::ActionManager::command(Core::Id(id));
- if (cmd->isScriptable(cmd->context())) {
+ const Id id = Id::fromString(name);
+ const Command *command = ActionManager::command(id);
+ if (command->isScriptable(command->context())) {
MacroEvent e;
e.setId(EVENTNAME);
- e.setValue(ACTIONNAME, id);
+ e.setValue(ACTIONNAME, id.toSetting());
addMacroEvent(e);
}
}
-void ActionMacroHandler::registerCommand(const QString &id)
+void ActionMacroHandler::registerCommand(Id id)
{
if (!m_commandIds.contains(id)) {
m_commandIds.insert(id);
- QAction* action = Core::ActionManager::command(Core::Id(id))->action();
- if (action) {
+ const Command *command = ActionManager::command(id);
+ if (QAction *action = command->action()) {
connect(action, SIGNAL(triggered()), m_mapper, SLOT(map()));
- m_mapper->setMapping(action, id);
+ m_mapper->setMapping(action, id.toString());
return;
}
- QShortcut* shortcut = Core::ActionManager::command(Core::Id(id))->shortcut();
- if (shortcut) {
+ if (QShortcut *shortcut = command->shortcut()) {
connect(shortcut, SIGNAL(activated()), m_mapper, SLOT(map()));
- m_mapper->setMapping(shortcut, id);
+ m_mapper->setMapping(shortcut, id.toString());
}
}
}
-void ActionMacroHandler::addCommand(const QString &id)
+void ActionMacroHandler::addCommand(const QString &name)
{
- if (Core::ActionManager::command(Core::Id(id))->isScriptable())
+ const Id id = Id::fromString(name);
+ const Command *command = ActionManager::command(id);
+ if (command->isScriptable())
registerCommand(id);
}
+
+} // namespace Internal
+} // namespace Macros
diff --git a/src/plugins/macros/actionmacrohandler.h b/src/plugins/macros/actionmacrohandler.h
index 5177515e2a..d89863ee20 100644
--- a/src/plugins/macros/actionmacrohandler.h
+++ b/src/plugins/macros/actionmacrohandler.h
@@ -32,10 +32,12 @@
#include "imacrohandler.h"
+#include <coreplugin/id.h>
+#include <coreplugin/actionmanager/actionmanager.h>
+
#include <QSet>
QT_BEGIN_NAMESPACE
-class QAction;
class QSignalMapper;
QT_END_NAMESPACE
@@ -53,14 +55,15 @@ public:
bool executeEvent(const MacroEvent &macroEvent);
private:
- void registerCommand(const QString &id);
+ void registerCommand(Core::Id id);
+ Core::Command *command(const QString &id);
private slots:
void addCommand(const QString &id);
void addActionEvent(const QString &id);
private:
- QSet<QString> m_commandIds;
+ QSet<Core::Id> m_commandIds;
QSignalMapper *m_mapper;
};
diff --git a/src/plugins/macros/macro.cpp b/src/plugins/macros/macro.cpp
index 4da976aaff..91a8008afc 100644
--- a/src/plugins/macros/macro.cpp
+++ b/src/plugins/macros/macro.cpp
@@ -61,7 +61,7 @@ public:
};
Macro::MacroPrivate::MacroPrivate() :
- version(Core::Constants::IDE_VERSION_LONG)
+ version(QLatin1String(Core::Constants::IDE_VERSION_LONG))
{
}
diff --git a/src/plugins/macros/macroevent.cpp b/src/plugins/macros/macroevent.cpp
index e244f88553..59f9a7ac53 100644
--- a/src/plugins/macros/macroevent.cpp
+++ b/src/plugins/macros/macroevent.cpp
@@ -53,7 +53,7 @@ using namespace Macros;
class MacroEvent::MacroEventPrivate
{
public:
- QByteArray id;
+ Core::Id id;
QMap<quint8, QVariant> values;
};
@@ -88,9 +88,7 @@ MacroEvent& MacroEvent::operator=(const MacroEvent &other)
QVariant MacroEvent::value(quint8 id) const
{
- if (d->values.contains(id))
- return d->values.value(id);
- return QVariant();
+ return d->values.value(id);
}
void MacroEvent::setValue(quint8 id, const QVariant &value)
@@ -100,7 +98,9 @@ void MacroEvent::setValue(quint8 id, const QVariant &value)
void MacroEvent::load(QDataStream &stream)
{
- stream >> d->id;
+ QByteArray ba;
+ stream >> ba;
+ d->id = Core::Id(ba);
int count;
stream >> count;
quint8 id;
@@ -114,7 +114,7 @@ void MacroEvent::load(QDataStream &stream)
void MacroEvent::save(QDataStream &stream) const
{
- stream << d->id;
+ stream << d->id.name();
stream << d->values.count();
QMapIterator<quint8, QVariant> i(d->values);
while (i.hasNext()) {
@@ -123,17 +123,12 @@ void MacroEvent::save(QDataStream &stream) const
}
}
-const QByteArray & MacroEvent::id() const
+Core::Id MacroEvent::id() const
{
return d->id;
}
-void MacroEvent::setId(const char *id)
+void MacroEvent::setId(Core::Id id)
{
d->id = id;
}
-
-QMap<quint8, QVariant> MacroEvent::values() const
-{
- return d->values;
-}
diff --git a/src/plugins/macros/macroevent.h b/src/plugins/macros/macroevent.h
index efc0138fd1..9345f89dbe 100644
--- a/src/plugins/macros/macroevent.h
+++ b/src/plugins/macros/macroevent.h
@@ -32,6 +32,8 @@
#include "macros_global.h"
+#include <coreplugin/id.h>
+
#include <QMap>
QT_BEGIN_NAMESPACE
@@ -50,14 +52,12 @@ public:
virtual ~MacroEvent();
MacroEvent& operator=(const MacroEvent &other);
- const QByteArray &id() const;
- void setId(const char *id);
+ Core::Id id() const;
+ void setId(Core::Id id);
QVariant value(quint8 id) const;
void setValue(quint8 id, const QVariant &value);
- QMap<quint8, QVariant> values() const;
-
void load(QDataStream &stream);
void save(QDataStream &stream) const;
diff --git a/src/plugins/macros/macrolocatorfilter.cpp b/src/plugins/macros/macrolocatorfilter.cpp
index 8b67065b4f..2d4d72386f 100644
--- a/src/plugins/macros/macrolocatorfilter.cpp
+++ b/src/plugins/macros/macrolocatorfilter.cpp
@@ -43,6 +43,8 @@ using namespace Macros::Internal;
MacroLocatorFilter::MacroLocatorFilter():
m_icon(QPixmap(QLatin1String(":/macros/images/macro.png")))
{
+ setId("Macros");
+ setDisplayName(tr("Macros"));
setShortcutString(QLatin1String("rm"));
}
diff --git a/src/plugins/macros/macrolocatorfilter.h b/src/plugins/macros/macrolocatorfilter.h
index 1a183ed903..e3efd66a39 100644
--- a/src/plugins/macros/macrolocatorfilter.h
+++ b/src/plugins/macros/macrolocatorfilter.h
@@ -48,10 +48,6 @@ public:
MacroLocatorFilter();
~MacroLocatorFilter();
- QString displayName() const { return tr("Macros"); }
- QString id() const { return QLatin1String("Macros"); }
- Priority priority() const { return Medium; }
-
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/macros/macromanager.cpp b/src/plugins/macros/macromanager.cpp
index 0656973875..63a623038b 100644
--- a/src/plugins/macros/macromanager.cpp
+++ b/src/plugins/macros/macromanager.cpp
@@ -142,11 +142,11 @@ void MacroManager::MacroManagerPrivate::initialize()
macros.clear();
QDir dir(q->macrosDirectory());
QStringList filter;
- filter << QString("*.")+Constants::M_EXTENSION;
+ filter << QLatin1String("*.") + QLatin1String(Constants::M_EXTENSION);
QStringList files = dir.entryList(filter, QDir::Files);
foreach (const QString &name, files) {
- QString fileName = dir.absolutePath() + '/' + name;
+ QString fileName = dir.absolutePath() + QLatin1Char('/') + name;
Macro *macro = new Macro;
if (macro->loadHeader(fileName))
addMacro(macro);
@@ -155,14 +155,18 @@ void MacroManager::MacroManagerPrivate::initialize()
}
}
+static Core::Id makeId(const QString &name)
+{
+ return Core::Id::fromString(QLatin1String(Constants::PREFIX_MACRO) + name);
+}
+
void MacroManager::MacroManagerPrivate::addMacro(Macro *macro)
{
// Add sortcut
Core::Context context(TextEditor::Constants::C_TEXTEDITOR);
QShortcut *shortcut = new QShortcut(Core::ICore::mainWindow());
shortcut->setWhatsThis(macro->description());
- const Core::Id macroId(QLatin1String(Constants::PREFIX_MACRO) + macro->displayName());
- Core::ActionManager::registerShortcut(shortcut, macroId, context);
+ Core::ActionManager::registerShortcut(shortcut, makeId(macro->displayName()), context);
connect(shortcut, SIGNAL(activated()), mapper, SLOT(map()));
mapper->setMapping(shortcut, macro->displayName());
@@ -175,7 +179,7 @@ void MacroManager::MacroManagerPrivate::removeMacro(const QString &name)
if (!macros.contains(name))
return;
// Remove shortcut
- Core::ActionManager::unregisterShortcut(Core::Id(Constants::PREFIX_MACRO+name));
+ Core::ActionManager::unregisterShortcut(makeId(name));
// Remove macro from the map
Macro *macro = macros.take(name);
@@ -190,7 +194,7 @@ void MacroManager::MacroManagerPrivate::changeMacroDescription(Macro *macro, con
macro->save(macro->fileName(), Core::ICore::mainWindow());
// Change shortcut what's this
- Core::Command *command = Core::ActionManager::command(Core::Id(Constants::PREFIX_MACRO+macro->displayName()));
+ Core::Command *command = Core::ActionManager::command(makeId(macro->displayName()));
if (command && command->shortcut())
command->shortcut()->setWhatsThis(description);
}
@@ -233,8 +237,8 @@ void MacroManager::MacroManagerPrivate::showSaveDialog()
return;
// Save in the resource path
- QString fileName = q->macrosDirectory() + '/' + dialog.name()
- + '.' + Constants::M_EXTENSION;
+ QString fileName = q->macrosDirectory() + QLatin1Char('/') + dialog.name()
+ + QLatin1Char('.') + QLatin1String(Constants::M_EXTENSION);
currentMacro->setDescription(dialog.description());
currentMacro->save(fileName, mainWindow);
addMacro(currentMacro);
diff --git a/src/plugins/macros/macrooptionspage.cpp b/src/plugins/macros/macrooptionspage.cpp
index bdeba640ec..97220d054c 100644
--- a/src/plugins/macros/macrooptionspage.cpp
+++ b/src/plugins/macros/macrooptionspage.cpp
@@ -46,9 +46,9 @@ using namespace Macros::Internal;
MacroOptionsPage::MacroOptionsPage(QObject *parent)
: Core::IOptionsPage(parent)
{
- setId(QLatin1String(Constants::M_OPTIONS_PAGE));
+ setId(Constants::M_OPTIONS_PAGE);
setDisplayName(QCoreApplication::translate("Macros", Constants::M_OPTIONS_TR_PAGE));
- setCategory(QLatin1String(TextEditor::Constants::TEXT_EDITOR_SETTINGS_CATEGORY));
+ setCategory(TextEditor::Constants::TEXT_EDITOR_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("TextEditor",
TextEditor::Constants::TEXT_EDITOR_SETTINGS_TR_CATEGORY));
}
diff --git a/src/plugins/macros/macrooptionswidget.cpp b/src/plugins/macros/macrooptionswidget.cpp
index 8a8c4c68c0..7c8106e6f5 100644
--- a/src/plugins/macros/macrooptionswidget.cpp
+++ b/src/plugins/macros/macrooptionswidget.cpp
@@ -111,7 +111,8 @@ void MacroOptionsWidget::createTable()
macroItem->setData(0, WRITE_ROLE, it.value()->isWritable());
Core::Command *command =
- Core::ActionManager::command(Core::Id(Constants::PREFIX_MACRO+it.value()->displayName()));
+ Core::ActionManager::command(Core::Id::fromString(QLatin1String(Constants::PREFIX_MACRO)
+ + it.value()->displayName()));
if (command && command->shortcut())
macroItem->setText(2, command->shortcut()->key().toString());
}
diff --git a/src/plugins/macros/macros.qbs b/src/plugins/macros/macros.qbs
index 1712dc5661..c30877a7cc 100644
--- a/src/plugins/macros/macros.qbs
+++ b/src/plugins/macros/macros.qbs
@@ -10,19 +10,9 @@ QtcPlugin {
Depends { name: "Locator" }
Depends { name: "Find" }
Depends { name: "TextEditor" }
-
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- "../..",
- buildDirectory
- ]
+ Depends { name: "app_version_header" }
files: [
- "macrooptionswidget.ui",
- "macros.qrc",
- "savedialog.ui",
"actionmacrohandler.cpp",
"actionmacrohandler.h",
"findmacrohandler.cpp",
@@ -41,6 +31,8 @@ QtcPlugin {
"macrooptionspage.h",
"macrooptionswidget.cpp",
"macrooptionswidget.h",
+ "macrooptionswidget.ui",
+ "macros.qrc",
"macros_global.h",
"macrosconstants.h",
"macrosplugin.cpp",
@@ -49,8 +41,8 @@ QtcPlugin {
"macrotextfind.h",
"savedialog.cpp",
"savedialog.h",
+ "savedialog.ui",
"texteditormacrohandler.cpp",
- "texteditormacrohandler.h"
+ "texteditormacrohandler.h",
]
}
-
diff --git a/src/plugins/macros/savedialog.cpp b/src/plugins/macros/savedialog.cpp
index 45dce81e2e..2f79efa09e 100644
--- a/src/plugins/macros/savedialog.cpp
+++ b/src/plugins/macros/savedialog.cpp
@@ -41,7 +41,7 @@ SaveDialog::SaveDialog(QWidget *parent) :
ui(new Ui::SaveDialog)
{
ui->setupUi(this);
- ui->name->setValidator(new QRegExpValidator(QRegExp("\\w*"), this));
+ ui->name->setValidator(new QRegExpValidator(QRegExp(QLatin1String("\\w*")), this));
}
SaveDialog::~SaveDialog()
diff --git a/src/plugins/madde/Madde.pluginspec.in b/src/plugins/madde/Madde.pluginspec.in
index cb3a2c8fb2..f0803a8b95 100644
--- a/src/plugins/madde/Madde.pluginspec.in
+++ b/src/plugins/madde/Madde.pluginspec.in
@@ -1,4 +1,4 @@
-<plugin name=\"Madde\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\">
+<plugin name=\"Madde\" version=\"$$QTCREATOR_VERSION\" compatVersion=\"$$QTCREATOR_VERSION\" disabledByDefault=\"true\">
<vendor>Digia Plc</vendor>
<copyright>(C) 2013 Digia Plc</copyright>
<license>
@@ -15,5 +15,6 @@ Alternatively, this plugin may be used under the terms of the GNU Lesser General
<url>http://www.qt-project.org</url>
<dependencyList>
<dependency name=\"RemoteLinux\" version=\"$$QTCREATOR_VERSION\"/>
+ <dependency name=\"Qt4ProjectManager\" version=\"$$QTCREATOR_VERSION\"/>
</dependencyList>
</plugin>
diff --git a/src/plugins/madde/debianmanager.cpp b/src/plugins/madde/debianmanager.cpp
index ead22dda6b..e629f9ae53 100644
--- a/src/plugins/madde/debianmanager.cpp
+++ b/src/plugins/madde/debianmanager.cpp
@@ -58,11 +58,11 @@
namespace {
-const QByteArray IconFieldName("XB-Maemo-Icon-26");
-const QByteArray NameFieldName("Package");
-const QByteArray ShortDescriptionFieldName("Description");
+const char IconFieldName[] = "XB-Maemo-Icon-26";
+const char NameFieldName[] = "Package";
+const char ShortDescriptionFieldName[] = "Description";
-const QLatin1String PackagingDirName("qtc_packaging");
+const char PackagingDirName[] = "qtc_packaging";
// The QDateTime API can only deliver these in localized form...
QString shortMonthName(const QDateTime &dt)
@@ -307,7 +307,7 @@ DebianManager::DebianManager(QObject *parent) :
{
m_instance = this;
- m_watcher->setObjectName("Madde::DebianManager");
+ m_watcher->setObjectName(QLatin1String("Madde::DebianManager"));
connect(m_watcher, SIGNAL(directoryChanged(QString)),
this, SLOT(directoryWasChanged(QString)));
}
@@ -441,7 +441,7 @@ bool DebianManager::setProjectVersion(const Utils::FileName &debianDir, const QS
QString DebianManager::packageName(const Utils::FileName &debianDir)
{
- return QString::fromUtf8(controlFileFieldValue(controlFilePath(debianDir), NameFieldName, false));
+ return QString::fromUtf8(controlFileFieldValue(controlFilePath(debianDir), QLatin1String(NameFieldName), false));
}
bool DebianManager::setPackageName(const Utils::FileName &debianDir, const QString &newName)
@@ -484,7 +484,8 @@ bool DebianManager::setPackageName(const Utils::FileName &debianDir, const QStri
QString DebianManager::shortDescription(const Utils::FileName &debianDir)
{
- return QString::fromUtf8(controlFileFieldValue(controlFilePath(debianDir), ShortDescriptionFieldName, false));
+ return QString::fromUtf8(controlFileFieldValue(controlFilePath(debianDir),
+ QLatin1String(ShortDescriptionFieldName), false));
}
bool DebianManager::setShortDescription(const Utils::FileName &debianDir, const QString &description)
@@ -495,7 +496,7 @@ bool DebianManager::setShortDescription(const Utils::FileName &debianDir, const
QString DebianManager::packageManagerName(const Utils::FileName &debianDir, Core::Id deviceType)
{
return QString::fromUtf8(controlFileFieldValue(controlFilePath(debianDir),
- packageManagerNameFieldName(deviceType), false));
+ QLatin1String(packageManagerNameFieldName(deviceType)), false));
}
bool DebianManager::setPackageManagerName(const Utils::FileName &debianDir, Core::Id deviceType, const QString &name)
@@ -507,7 +508,7 @@ bool DebianManager::setPackageManagerName(const Utils::FileName &debianDir, Core
QIcon DebianManager::packageManagerIcon(const Utils::FileName &debianDir, QString *error)
{
const QByteArray &base64Icon
- = controlFileFieldValue(controlFilePath(debianDir), IconFieldName, true);
+ = controlFileFieldValue(controlFilePath(debianDir), QLatin1String(IconFieldName), true);
if (base64Icon.isEmpty())
return QIcon();
QPixmap pixmap;
@@ -537,7 +538,7 @@ bool DebianManager::setPackageManagerIcon(const Utils::FileName &debianDir, Core
QBuffer buffer(&iconAsBase64);
buffer.open(QIODevice::WriteOnly);
if (!pixmap.scaled(MaddeDevice::packageManagerIconSize(deviceType))
- .save(&buffer, iconPath.toFileInfo().suffix().toAscii())) {
+ .save(&buffer, iconPath.toFileInfo().suffix().toLatin1())) {
if (error)
*error = tr("Could not export image file '%1'.").arg(iconPath.toUserOutput());
return false;
@@ -545,7 +546,7 @@ bool DebianManager::setPackageManagerIcon(const Utils::FileName &debianDir, Core
buffer.close();
iconAsBase64 = iconAsBase64.toBase64();
QByteArray contents = reader.data();
- const QByteArray iconFieldNameWithColon = IconFieldName + ':';
+ const QByteArray iconFieldNameWithColon = QByteArray(IconFieldName) + ':';
const int iconFieldPos = contents.startsWith(iconFieldNameWithColon)
? 0 : contents.indexOf('\n' + iconFieldNameWithColon);
if (iconFieldPos == -1) {
@@ -635,7 +636,7 @@ DebianManager::ActionStatus DebianManager::createTemplate(Qt4ProjectManager::Qt4
if (!QFile::rename(location.appendPath(QLatin1String("debian")).toString(), debianDir.toString())) {
raiseError(tr("Unable to move new debian directory to '%1'.").arg(debianDir.toUserOutput()));
- Utils::FileUtils::removeRecursively(location.toString(), &error);
+ Utils::FileUtils::removeRecursively(location, &error);
return ActionFailed;
}
@@ -672,7 +673,7 @@ QStringList DebianManager::debianFiles(const Utils::FileName &debianDir)
Utils::FileName DebianManager::debianDirectory(ProjectExplorer::Target *target)
{
Utils::FileName path = Utils::FileName::fromString(target->project()->projectDirectory());
- path.appendPath(PackagingDirName);
+ path.appendPath(QLatin1String(PackagingDirName));
Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target->kit());
if (deviceType == HarmattanOsType)
path.appendPath(QLatin1String("debian_harmattan"));
@@ -709,19 +710,19 @@ void DebianManager::changelogWasChanged()
Utils::FileName DebianManager::changelogFilePath(const Utils::FileName &debianDir)
{
Utils::FileName result = debianDir;
- return result.appendPath("changelog");
+ return result.appendPath(QLatin1String("changelog"));
}
Utils::FileName DebianManager::controlFilePath(const Utils::FileName &debianDir)
{
Utils::FileName result = debianDir;
- return result.appendPath("control");
+ return result.appendPath(QLatin1String("control"));
}
Utils::FileName DebianManager::rulesFilePath(const Utils::FileName &debianDir)
{
Utils::FileName result = debianDir;
- return result.appendPath("rules");
+ return result.appendPath(QLatin1String("rules"));
}
} // namespace Internal
diff --git a/src/plugins/madde/madde.pro b/src/plugins/madde/madde.pro
index 73bf1efad4..ba7f2bc223 100644
--- a/src/plugins/madde/madde.pro
+++ b/src/plugins/madde/madde.pro
@@ -36,7 +36,6 @@ HEADERS += \
maemoqemusettings.h \
qt4maemodeployconfiguration.h \
maemodeviceconfigwizard.h \
- maemodeployconfigurationwidget.h \
maemoinstalltosysrootstep.h \
maemodeploymentmounter.h \
maemopackageinstaller.h \
@@ -80,7 +79,6 @@ SOURCES += \
maemoqemusettings.cpp \
qt4maemodeployconfiguration.cpp \
maemodeviceconfigwizard.cpp \
- maemodeployconfigurationwidget.cpp \
maemoinstalltosysrootstep.cpp \
maemodeploymentmounter.cpp \
maemopackageinstaller.cpp \
@@ -107,9 +105,7 @@ FORMS += \
maemodeviceconfigwizardpreviouskeysetupcheckpage.ui \
maemodeviceconfigwizardreusekeyscheckpage.ui \
maemodeviceconfigwizardkeycreationpage.ui \
- maemodeviceconfigwizardkeydeploymentpage.ui \
- maemodeployconfigurationwidget.ui
+ maemodeviceconfigwizardkeydeploymentpage.ui
RESOURCES += qt-maemo.qrc
-DEFINES += QT_NO_CAST_TO_ASCII
DEFINES += MADDE_LIBRARY
diff --git a/src/plugins/madde/madde.qbs b/src/plugins/madde/madde.qbs
index 260ca82050..a6641b6a6e 100644
--- a/src/plugins/madde/madde.qbs
+++ b/src/plugins/madde/madde.qbs
@@ -12,32 +12,27 @@ QtcPlugin {
Depends { name: "RemoteLinux" }
Depends { name: "Qt.gui" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
- cpp.defines: base.concat(['QT_NO_CAST_TO_ASCII'])
-
files: [
+ "debianmanager.cpp",
+ "debianmanager.h",
"madde_exports.h",
+ "maddedevice.cpp",
+ "maddedevice.h",
"maddedeviceconfigurationfactory.cpp",
"maddedeviceconfigurationfactory.h",
"maddedevicetester.cpp",
"maddedevicetester.h",
"maddeplugin.cpp",
"maddeplugin.h",
- "maddeuploadandinstallpackagesteps.cpp",
- "maddeuploadandinstallpackagesteps.h",
"maddeqemustartstep.cpp",
"maddeqemustartstep.h",
+ "maddeuploadandinstallpackagesteps.cpp",
+ "maddeuploadandinstallpackagesteps.h",
+ "maemoapplicationrunnerhelperactions.cpp",
+ "maemoapplicationrunnerhelperactions.h",
"maemoconstants.h",
"maemodeploybymountsteps.cpp",
"maemodeploybymountsteps.h",
- "maemodeployconfigurationwidget.cpp",
- "maemodeployconfigurationwidget.h",
- "maemodeployconfigurationwidget.ui",
"maemodeploymentmounter.cpp",
"maemodeploymentmounter.h",
"maemodeploystepfactory.cpp",
@@ -115,11 +110,5 @@ QtcPlugin {
"qt-maemo.qrc",
"qt4maemodeployconfiguration.cpp",
"qt4maemodeployconfiguration.h",
- "maddedevice.cpp",
- "maddedevice.h",
- "debianmanager.h",
- "debianmanager.cpp",
- "maemoapplicationrunnerhelperactions.h",
- "maemoapplicationrunnerhelperactions.cpp"
]
}
diff --git a/src/plugins/madde/madde_dependencies.pri b/src/plugins/madde/madde_dependencies.pri
index 94d99fc73d..630796bcbf 100644
--- a/src/plugins/madde/madde_dependencies.pri
+++ b/src/plugins/madde/madde_dependencies.pri
@@ -1 +1,2 @@
+include(../../plugins/qt4projectmanager/qt4projectmanager.pri)
include(../../plugins/remotelinux/remotelinux.pri)
diff --git a/src/plugins/madde/maddedevicetester.cpp b/src/plugins/madde/maddedevicetester.cpp
index 666070bdaf..8a68d98565 100644
--- a/src/plugins/madde/maddedevicetester.cpp
+++ b/src/plugins/madde/maddedevicetester.cpp
@@ -214,7 +214,7 @@ void MaddeDeviceTester::handleQmlToolingTestFinished(int exitStatus)
m_result = TestFailure;
} else if (m_processRunner->processExitCode() != 0) {
emit errorMessage(tr("Missing directory '%1'. You will not be able to do "
- "QML debugging on this device.\n").arg(QmlToolingDirectory));
+ "QML debugging on this device.\n").arg(QLatin1String(QmlToolingDirectory)));
m_result = TestFailure;
} else {
emit progressMessage(tr("QML tooling support present.\n"));
diff --git a/src/plugins/madde/maemoconstants.h b/src/plugins/madde/maemoconstants.h
index b190720d23..54208ec323 100644
--- a/src/plugins/madde/maemoconstants.h
+++ b/src/plugins/madde/maemoconstants.h
@@ -40,12 +40,6 @@ const char HarmattanOsType[] = "HarmattanOsType";
#define PREFIX "Qt4ProjectManager.MaemoRunConfiguration"
-#ifdef Q_OS_WIN32
-#define EXEC_SUFFIX ".exe"
-#else
-#define EXEC_SUFFIX ""
-#endif
-
static const char MAEMO_RC_ID_PREFIX[] = PREFIX ":";
static const QLatin1String LastDeployedHostsKey(PREFIX ".LastDeployedHosts");
diff --git a/src/plugins/madde/maemodeploybymountsteps.cpp b/src/plugins/madde/maemodeploybymountsteps.cpp
index d30d173a8c..9da25792e0 100644
--- a/src/plugins/madde/maemodeploybymountsteps.cpp
+++ b/src/plugins/madde/maemodeploybymountsteps.cpp
@@ -37,13 +37,13 @@
#include "maemoremotecopyfacility.h"
#include "qt4maemodeployconfiguration.h"
+#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <remotelinux/abstractremotelinuxdeployservice.h>
-#include <remotelinux/deployablefile.h>
-#include <remotelinux/deploymentinfo.h>
#include <remotelinux/linuxdevice.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <ssh/sshconnection.h>
@@ -129,7 +129,7 @@ private:
void cancelInstallation();
void handleInstallationSuccess();
- Q_SLOT void handleFileCopied(const RemoteLinux::DeployableFile&deployable);
+ Q_SLOT void handleFileCopied(const ProjectExplorer::DeployableFile &deployable);
MaemoRemoteCopyFacility * const m_copyFacility;
mutable QList<DeployableFile> m_filesToCopy;
@@ -168,8 +168,8 @@ void AbstractMaemoDeployByMountService::doDeploy()
{
QTC_ASSERT(m_state == Inactive, return);
- if (!buildConfiguration()) {
- emit errorMessage(tr("Missing build configuration."));
+ if (!target()) {
+ emit errorMessage(tr("Missing target."));
setFinished();
return;
}
@@ -255,7 +255,7 @@ QString AbstractMaemoDeployByMountService::deployMountPoint() const
{
return MaemoGlobal::homeDirOnDevice(deviceConfiguration()->sshParameters().userName)
+ QLatin1String("/deployMountPoint_")
- + buildConfiguration()->target()->project()->displayName();
+ + target()->project()->displayName();
}
@@ -304,8 +304,8 @@ MaemoMountAndCopyFilesService::MaemoMountAndCopyFilesService(QObject *parent)
connect(m_copyFacility, SIGNAL(stdoutData(QString)), SIGNAL(stdOutData(QString)));
connect(m_copyFacility, SIGNAL(stderrData(QString)), SIGNAL(stdErrData(QString)));
connect(m_copyFacility, SIGNAL(progress(QString)), SIGNAL(progressMessage(QString)));
- connect(m_copyFacility, SIGNAL(fileCopied(RemoteLinux::DeployableFile)),
- SLOT(handleFileCopied(RemoteLinux::DeployableFile)));
+ connect(m_copyFacility, SIGNAL(fileCopied(ProjectExplorer::DeployableFile)),
+ SLOT(handleFileCopied(ProjectExplorer::DeployableFile)));
connect(m_copyFacility, SIGNAL(finished(QString)), SLOT(handleInstallationFinished(QString)));
}
@@ -314,7 +314,7 @@ bool MaemoMountAndCopyFilesService::isDeploymentNecessary() const
m_filesToCopy.clear();
for (int i = 0; i < m_deployableFiles.count(); ++i) {
const DeployableFile &d = m_deployableFiles.at(i);
- if (hasChangedSinceLastDeployment(d) || QFileInfo(d.localFilePath).isDir())
+ if (hasChangedSinceLastDeployment(d) || d.localFilePath().toFileInfo().isDir())
m_filesToCopy << d;
}
return !m_filesToCopy.isEmpty();
@@ -323,29 +323,31 @@ bool MaemoMountAndCopyFilesService::isDeploymentNecessary() const
QList<MaemoMountSpecification> MaemoMountAndCopyFilesService::mountSpecifications() const
{
QList<MaemoMountSpecification> mountSpecs;
-#ifdef Q_OS_WIN
- bool drivesToMount[26];
- qFill(drivesToMount, drivesToMount + sizeof drivesToMount / sizeof drivesToMount[0], false);
- for (int i = 0; i < m_filesToCopy.count(); ++i) {
- const QString localDir = QFileInfo(m_filesToCopy.at(i).localFilePath).canonicalPath();
- const char driveLetter = localDir.at(0).toLower().toLatin1();
- if (driveLetter < 'a' || driveLetter > 'z') {
- qWarning("Weird: drive letter is '%c'.", driveLetter);
- continue;
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ bool drivesToMount[26];
+ qFill(drivesToMount, drivesToMount + sizeof drivesToMount / sizeof drivesToMount[0], false);
+ for (int i = 0; i < m_filesToCopy.count(); ++i) {
+ const QString localDir
+ = m_filesToCopy.at(i).localFilePath().toFileInfo().canonicalPath();
+ const char driveLetter = localDir.at(0).toLower().toLatin1();
+ if (driveLetter < 'a' || driveLetter > 'z') {
+ qWarning("Weird: drive letter is '%c'.", driveLetter);
+ continue;
+ }
+
+ const int index = driveLetter - 'a';
+ if (drivesToMount[index])
+ continue;
+
+ const QString mountPoint = deployMountPoint() + QLatin1Char('/')
+ + QLatin1Char(driveLetter);
+ const MaemoMountSpecification mountSpec(localDir.left(3), mountPoint);
+ mountSpecs << mountSpec;
+ drivesToMount[index] = true;
}
-
- const int index = driveLetter - 'a';
- if (drivesToMount[index])
- continue;
-
- const QString mountPoint = deployMountPoint() + QLatin1Char('/') + QLatin1Char(driveLetter);
- const MaemoMountSpecification mountSpec(localDir.left(3), mountPoint);
- mountSpecs << mountSpec;
- drivesToMount[index] = true;
+ } else {
+ mountSpecs << MaemoMountSpecification(QLatin1String("/"), deployMountPoint());
}
-#else
- mountSpecs << MaemoMountSpecification(QLatin1String("/"), deployMountPoint());
-#endif
return mountSpecs;
}
@@ -444,12 +446,7 @@ AbstractRemoteLinuxDeployService *MaemoCopyFilesViaMountStep::deployService() co
bool MaemoCopyFilesViaMountStep::initInternal(QString *error)
{
- QList<DeployableFile> deployableFiles;
- const DeploymentInfo * const deploymentInfo = deployConfiguration()->deploymentInfo();
- const int deployableCount = deploymentInfo->deployableCount();
- for (int i = 0; i < deployableCount; ++i)
- deployableFiles << deploymentInfo->deployableAt(i);
- m_deployService->setDeployableFiles(deployableFiles);
+ m_deployService->setDeployableFiles(target()->deploymentData().allFiles());
return deployService()->isDeploymentPossible(error);
}
diff --git a/src/plugins/madde/maemodeployconfigurationwidget.cpp b/src/plugins/madde/maemodeployconfigurationwidget.cpp
deleted file mode 100644
index f38380c5aa..0000000000
--- a/src/plugins/madde/maemodeployconfigurationwidget.cpp
+++ /dev/null
@@ -1,218 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-#include "maemodeployconfigurationwidget.h"
-#include "ui_maemodeployconfigurationwidget.h"
-
-#include "maemoglobal.h"
-#include "maemoconstants.h"
-#include "qt4maemodeployconfiguration.h"
-
-#include <projectexplorer/kitinformation.h>
-#include <projectexplorer/target.h>
-#include <qt4projectmanager/qt4nodes.h>
-#include <remotelinux/deployablefile.h>
-#include <remotelinux/deployablefilesperprofile.h>
-#include <remotelinux/deploymentinfo.h>
-#include <remotelinux/deploymentsettingsassistant.h>
-#include <remotelinux/remotelinuxdeployconfigurationwidget.h>
-#include <utils/fileutils.h>
-#include <utils/qtcassert.h>
-
-#include <QFileInfo>
-#include <QFileDialog>
-#include <QMessageBox>
-#include <QPixmap>
-#include <QVBoxLayout>
-
-using namespace ProjectExplorer;
-using namespace Qt4ProjectManager;
-using namespace RemoteLinux;
-
-namespace Madde {
-namespace Internal {
-
-MaemoDeployConfigurationWidget::MaemoDeployConfigurationWidget(QWidget *parent)
- : DeployConfigurationWidget(parent),
- ui(new Ui::MaemoDeployConfigurationWidget),
- m_remoteLinuxWidget(new RemoteLinuxDeployConfigurationWidget)
-{
- QVBoxLayout *mainLayout = new QVBoxLayout(this);
- mainLayout->setSpacing(0);
- mainLayout->addWidget(m_remoteLinuxWidget);
- QWidget * const subWidget = new QWidget;
- ui->setupUi(subWidget);
- mainLayout->addWidget(subWidget);
- mainLayout->addStretch(1);
-
- connect(m_remoteLinuxWidget,
- SIGNAL(currentModelChanged(const RemoteLinux::DeployableFilesPerProFile*)),
- SLOT(handleCurrentModelChanged(const RemoteLinux::DeployableFilesPerProFile*)));
- handleCurrentModelChanged(m_remoteLinuxWidget->currentModel());
-}
-
-MaemoDeployConfigurationWidget::~MaemoDeployConfigurationWidget()
-{
- delete ui;
-}
-
-void MaemoDeployConfigurationWidget::init(DeployConfiguration *dc)
-{
- m_remoteLinuxWidget->init(dc);
- connect(ui->addDesktopFileButton, SIGNAL(clicked()), SLOT(addDesktopFile()));
- connect(ui->addIconButton, SIGNAL(clicked()), SLOT(addIcon()));
- connect(deployConfiguration()->deploymentInfo(), SIGNAL(modelAboutToBeReset()),
- SLOT(handleDeploymentInfoToBeReset()));
-}
-
-Qt4MaemoDeployConfiguration *MaemoDeployConfigurationWidget::deployConfiguration() const
-{
- return qobject_cast<Qt4MaemoDeployConfiguration *>(m_remoteLinuxWidget->deployConfiguration());
-}
-
-void MaemoDeployConfigurationWidget::handleDeploymentInfoToBeReset()
-{
- ui->addDesktopFileButton->setEnabled(false);
- ui->addIconButton->setEnabled(false);
-}
-
-void MaemoDeployConfigurationWidget::handleCurrentModelChanged(const DeployableFilesPerProFile *proFileInfo)
-{
- ui->addDesktopFileButton->setEnabled(canAddDesktopFile(proFileInfo));
- ui->addIconButton->setEnabled(canAddIcon(proFileInfo));
-}
-
-void MaemoDeployConfigurationWidget::addDesktopFile()
-{
- DeployableFilesPerProFile * const proFileInfo = m_remoteLinuxWidget->currentModel();
- QTC_ASSERT(canAddDesktopFile(proFileInfo), return);
-
- const QString desktopFilePath = QFileInfo(proFileInfo->proFilePath()).path()
- + QLatin1Char('/') + proFileInfo->projectName() + QLatin1String(".desktop");
- if (!QFile::exists(desktopFilePath)) {
- const QString desktopTemplate = QLatin1String("[Desktop Entry]\nEncoding=UTF-8\n"
- "Version=1.0\nType=Application\nTerminal=false\nName=%1\nExec=%2\n"
- "Icon=%1\nX-Window-Icon=\nX-HildonDesk-ShowInToolbar=true\n"
- "X-Osso-Type=application/x-executable\n");
- Utils::FileSaver saver(desktopFilePath);
- saver.write(desktopTemplate.arg(proFileInfo->projectName(),
- proFileInfo->remoteExecutableFilePath()).toUtf8());
- if (!saver.finalize(this))
- return;
- }
-
- DeployableFile d;
- d.remoteDir = QLatin1String("/usr/share/applications");
- Core::Id deviceType
- = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(deployConfiguration()->target()->kit());
- if (deviceType == Maemo5OsType)
- d.remoteDir += QLatin1String("/hildon");
- d.localFilePath = desktopFilePath;
- if (!deployConfiguration()->deploymentSettingsAssistant()
- ->addDeployableToProFile(deployConfiguration()->qmakeScope(), proFileInfo,
- QLatin1String("desktopfile"), d)) {
- QMessageBox::critical(this, tr("Project File Update Failed"),
- tr("Could not update the project file."));
- } else {
- ui->addDesktopFileButton->setEnabled(false);
- }
-}
-
-void MaemoDeployConfigurationWidget::addIcon()
-{
- DeployableFilesPerProFile * const proFileInfo = m_remoteLinuxWidget->currentModel();
- const int iconDim
- = MaemoGlobal::applicationIconSize(deployConfiguration()->target());
- const QString origFilePath = QFileDialog::getOpenFileName(this,
- tr("Choose Icon (will be scaled to %1x%1 pixels, if necessary)").arg(iconDim),
- proFileInfo->projectDir(), QLatin1String("(*.png)"));
- if (origFilePath.isEmpty())
- return;
- QPixmap pixmap(origFilePath);
- if (pixmap.isNull()) {
- QMessageBox::critical(this, tr("Invalid Icon"),
- tr("Unable to read image"));
- return;
- }
- const QSize iconSize(iconDim, iconDim);
- if (pixmap.size() != iconSize)
- pixmap = pixmap.scaled(iconSize);
- const QString newFileName = proFileInfo->projectName() + QLatin1Char('.')
- + QFileInfo(origFilePath).suffix();
- const QString newFilePath = proFileInfo->projectDir() + QLatin1Char('/') + newFileName;
- if (!pixmap.save(newFilePath)) {
- QMessageBox::critical(this, tr("Failed to Save Icon"),
- tr("Could not save icon to '%1'.").arg(newFilePath));
- return;
- }
-
- if (!deployConfiguration()->deploymentSettingsAssistant()
- ->addDeployableToProFile(deployConfiguration()->qmakeScope(), proFileInfo,
- QLatin1String("icon"), DeployableFile(newFilePath, remoteIconDir()))) {
- QMessageBox::critical(this, tr("Project File Update Failed"),
- tr("Could not update the project file."));
- } else {
- ui->addIconButton->setEnabled(false);
- }
-}
-
-bool MaemoDeployConfigurationWidget::canAddDesktopFile(const DeployableFilesPerProFile *proFileInfo) const
-{
- return proFileInfo && proFileInfo->isApplicationProject()
- && deployConfiguration()->localDesktopFilePath(proFileInfo).isEmpty();
-}
-
-bool MaemoDeployConfigurationWidget::canAddIcon(const DeployableFilesPerProFile *proFileInfo) const
-{
- return proFileInfo && proFileInfo->isApplicationProject()
- && remoteIconFilePath(proFileInfo).isEmpty();
-}
-
-QString MaemoDeployConfigurationWidget::remoteIconFilePath(const DeployableFilesPerProFile *proFileInfo) const
-{
- QTC_ASSERT(proFileInfo->projectType() == ApplicationTemplate, return QString());
-
- const QStringList imageTypes = QStringList() << QLatin1String("jpg") << QLatin1String("png")
- << QLatin1String("svg");
- for (int i = 0; i < proFileInfo->rowCount(); ++i) {
- const DeployableFile &d = proFileInfo->deployableAt(i);
- const QString extension = QFileInfo(d.localFilePath).suffix();
- if (d.remoteDir.startsWith(remoteIconDir()) && imageTypes.contains(extension))
- return d.remoteDir + QLatin1Char('/') + QFileInfo(d.localFilePath).fileName();
- }
- return QString();
-}
-
-QString MaemoDeployConfigurationWidget::remoteIconDir() const
-{
- return QString::fromLatin1("/usr/share/icons/hicolor/%1x%1/apps")
- .arg(MaemoGlobal::applicationIconSize(deployConfiguration()->target()));
-}
-
-} // namespace Internal
-} // namespace Madde
diff --git a/src/plugins/madde/maemodeployconfigurationwidget.ui b/src/plugins/madde/maemodeployconfigurationwidget.ui
deleted file mode 100644
index 04f5b74fd9..0000000000
--- a/src/plugins/madde/maemodeployconfigurationwidget.ui
+++ /dev/null
@@ -1,48 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>Madde::Internal::MaemoDeployConfigurationWidget</class>
- <widget class="QWidget" name="Madde::Internal::MaemoDeployConfigurationWidget">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>276</width>
- <height>45</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Form</string>
- </property>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QPushButton" name="addDesktopFileButton">
- <property name="text">
- <string>Add Desktop File</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="addIconButton">
- <property name="text">
- <string>Add Launcher Icon...</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections/>
-</ui>
diff --git a/src/plugins/madde/maemodeploystepfactory.cpp b/src/plugins/madde/maemodeploystepfactory.cpp
index 11721b85b2..27ef1559e6 100644
--- a/src/plugins/madde/maemodeploystepfactory.cpp
+++ b/src/plugins/madde/maemodeploystepfactory.cpp
@@ -72,14 +72,14 @@ QList<Core::Id> MaemoDeployStepFactory::availableCreationIds(BuildStepList *pare
if (version)
platform = version->platformName();
- if (platform == QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM) {
+ if (platform == QLatin1String(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM)) {
ids << MaemoMakeInstallToSysrootStep::Id
<< MaemoInstallDebianPackageToSysrootStep::Id
<< MaemoUploadAndInstallPackageStep::stepId()
<< MaemoInstallPackageViaMountStep::stepId()
<< MaemoCopyFilesViaMountStep::stepId()
<< MaddeQemuStartStep::stepId();
- } else if (platform == QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM) {
+ } else if (platform == QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM)) {
ids << MaemoMakeInstallToSysrootStep::Id
<< MaemoInstallDebianPackageToSysrootStep::Id
<< MaemoUploadAndInstallPackageStep::stepId()
diff --git a/src/plugins/madde/maemoglobal.cpp b/src/plugins/madde/maemoglobal.cpp
index e730b57227..ea748457a1 100644
--- a/src/plugins/madde/maemoglobal.cpp
+++ b/src/plugins/madde/maemoglobal.cpp
@@ -39,6 +39,7 @@
#include <qtsupport/qtkitinformation.h>
#include <remotelinux/remotelinux_constants.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QFileInfo>
@@ -50,12 +51,11 @@ using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Constants;
using namespace RemoteLinux;
+using namespace Utils;
namespace Madde {
namespace Internal {
-namespace {
-static const QLatin1String binQmake("/bin/qmake" EXEC_SUFFIX);
-} // namespace
+static const QString binQmake = QLatin1String("/bin/qmake" QTC_HOST_EXE_SUFFIX);
bool MaemoGlobal::hasMaemoDevice(const Kit *k)
{
@@ -95,7 +95,7 @@ bool MaemoGlobal::isValidMaemoQtVersion(const QString &qmakePath, Core::Id devic
return false;
madAdminProc.setReadChannel(QProcess::StandardOutput);
- const QByteArray tgtName = targetName(qmakePath).toAscii();
+ const QByteArray tgtName = targetName(qmakePath).toLatin1();
while (madAdminProc.canReadLine()) {
const QByteArray &line = madAdminProc.readLine();
if (line.contains(tgtName)
@@ -140,16 +140,16 @@ QString MaemoGlobal::remoteSourceProfilesCommand()
QByteArray remoteCall(":");
foreach (const QByteArray &profile, profiles)
remoteCall += "; test -f " + profile + " && source " + profile;
- return QString::fromAscii(remoteCall);
+ return QString::fromLatin1(remoteCall);
}
-Utils::PortList MaemoGlobal::freePorts(const Kit *k)
+PortList MaemoGlobal::freePorts(const Kit *k)
{
IDevice::ConstPtr device = DeviceKitInformation::device(k);
QtSupport::BaseQtVersion *qtVersion = QtSupport::QtKitInformation::qtVersion(k);
if (!device || !qtVersion)
- return Utils::PortList();
+ return PortList();
if (device->machineType() == IDevice::Emulator) {
MaemoQemuRuntime rt;
const int id = qtVersion->uniqueId();
@@ -166,19 +166,14 @@ QString MaemoGlobal::maddeRoot(const QString &qmakePath)
return dir.absolutePath();
}
-Utils::FileName MaemoGlobal::maddeRoot(const Kit *k)
+FileName MaemoGlobal::maddeRoot(const Kit *k)
{
return SysRootKitInformation::sysRoot(k).parentDir().parentDir();
}
QString MaemoGlobal::targetRoot(const QString &qmakePath)
{
-#ifdef Q_OS_WIN
- Qt::CaseSensitivity cs = Qt::CaseInsensitive;
-#else
- Qt::CaseSensitivity cs = Qt::CaseSensitive;
-#endif
- return QDir::cleanPath(qmakePath).remove(binQmake, cs);
+ return QDir::cleanPath(qmakePath).remove(binQmake, HostOsInfo::fileNameCaseSensitivity());
}
QString MaemoGlobal::targetName(const QString &qmakePath)
@@ -226,32 +221,26 @@ QString MaemoGlobal::architecture(const QString &qmakePath)
return arch;
}
-void MaemoGlobal::addMaddeEnvironment(Utils::Environment &env, const QString &qmakePath)
+void MaemoGlobal::addMaddeEnvironment(Environment &env, const QString &qmakePath)
{
- Utils::Environment maddeEnv;
-#ifdef Q_OS_WIN
- const QString root = maddeRoot(qmakePath);
- env.prependOrSetPath(root + QLatin1String("/bin"));
- env.prependOrSet(QLatin1String("HOME"),
- QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
-#else
- Q_UNUSED(qmakePath);
-#endif
- for (Utils::Environment::const_iterator it = maddeEnv.constBegin(); it != maddeEnv.constEnd(); ++it)
+ Environment maddeEnv;
+ if (HostOsInfo::isWindowsHost()) {
+ const QString root = maddeRoot(qmakePath);
+ env.prependOrSetPath(root + QLatin1String("/bin"));
+ env.prependOrSet(QLatin1String("HOME"),
+ QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
+ }
+ for (Environment::const_iterator it = maddeEnv.constBegin(); it != maddeEnv.constEnd(); ++it)
env.prependOrSet(it.key(), it.value());
}
void MaemoGlobal::transformMaddeCall(QString &command, QStringList &args, const QString &qmakePath)
{
-#ifdef Q_OS_WIN
- const QString root = maddeRoot(qmakePath);
- args.prepend(command);
- command = root + QLatin1String("/bin/sh.exe");
-#else
- Q_UNUSED(command);
- Q_UNUSED(args);
- Q_UNUSED(qmakePath);
-#endif
+ if (HostOsInfo::isWindowsHost()) {
+ const QString root = maddeRoot(qmakePath);
+ args.prepend(command);
+ command = root + QLatin1String("/bin/sh.exe");
+ }
}
bool MaemoGlobal::callMad(QProcess &proc, const QStringList &args,
@@ -276,7 +265,7 @@ bool MaemoGlobal::callMaddeShellScript(QProcess &proc,
return false;
QString actualCommand = command;
QStringList actualArgs = targetArgs(qmakePath, useTarget) + args;
- Utils::Environment env(proc.systemEnvironment());
+ Environment env(proc.systemEnvironment());
addMaddeEnvironment(env, qmakePath);
proc.setEnvironment(env.toStringList());
transformMaddeCall(actualCommand, actualArgs, qmakePath);
@@ -287,9 +276,8 @@ bool MaemoGlobal::callMaddeShellScript(QProcess &proc,
QStringList MaemoGlobal::targetArgs(const QString &qmakePath, bool useTarget)
{
QStringList args;
- if (useTarget) {
+ if (useTarget)
args << QLatin1String("-t") << targetName(qmakePath);
- }
return args;
}
diff --git a/src/plugins/madde/maemoinstalltosysrootstep.cpp b/src/plugins/madde/maemoinstalltosysrootstep.cpp
index 6e553093af..c074c6b384 100644
--- a/src/plugins/madde/maemoinstalltosysrootstep.cpp
+++ b/src/plugins/madde/maemoinstalltosysrootstep.cpp
@@ -34,19 +34,19 @@
#include "maemopackagecreationstep.h"
#include "maemoqtversion.h"
-#include <utils/fileutils.h>
+#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/target.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
-#include <remotelinux/deploymentinfo.h>
#include <remotelinux/remotelinuxdeployconfiguration.h>
+#include <utils/fileutils.h>
#include <QDir>
#include <QFileInfo>
#include <QLatin1Char>
+#include <QPointer>
#include <QProcess>
-#include <QWeakPointer>
using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
@@ -110,7 +110,7 @@ class MaemoCopyFilesToSysrootWidget : public BuildStepConfigWidget
{
Q_OBJECT
public:
- MaemoCopyFilesToSysrootWidget(const BuildStep *buildStep)
+ MaemoCopyFilesToSysrootWidget(BuildStep *buildStep)
: m_buildStep(buildStep)
{
if (m_buildStep) {
@@ -125,7 +125,7 @@ public:
}
virtual bool showWidget() const { return false; }
private:
- const QWeakPointer<const BuildStep> m_buildStep;
+ const QPointer<BuildStep> m_buildStep;
};
@@ -264,8 +264,7 @@ MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl,
bool MaemoCopyToSysrootStep::init()
{
- const Qt4BuildConfiguration * const bc
- = qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
+ const BuildConfiguration * const bc = target()->activeBuildConfiguration();
if (!bc) {
addOutput(tr("Cannot copy to sysroot without build configuration."),
ErrorMessageOutput);
@@ -281,11 +280,7 @@ bool MaemoCopyToSysrootStep::init()
}
m_systemRoot = ProjectExplorer::SysRootKitInformation::sysRoot(target()->kit()).toString();
- const DeploymentInfo * const deploymentInfo
- = static_cast<RemoteLinuxDeployConfiguration *>(deployConfiguration())->deploymentInfo();
- m_files.clear();
- for (int i = 0; i < deploymentInfo->deployableCount(); ++i)
- m_files << deploymentInfo->deployableAt(i);
+ m_files = target()->deploymentData().allFiles();
return true;
}
@@ -297,14 +292,14 @@ void MaemoCopyToSysrootStep::run(QFutureInterface<bool> &fi)
const QChar sep = QLatin1Char('/');
foreach (const DeployableFile &deployable, m_files) {
- const QFileInfo localFileInfo(deployable.localFilePath);
+ const QFileInfo localFileInfo = deployable.localFilePath().toFileInfo();
const QString targetFilePath = m_systemRoot + sep
- + deployable.remoteDir + sep + localFileInfo.fileName();
- sysrootDir.mkpath(deployable.remoteDir.mid(1));
+ + deployable.remoteDirectory() + sep + localFileInfo.fileName();
+ sysrootDir.mkpath(deployable.remoteDirectory().mid(1));
QString errorMsg;
- Utils::FileUtils::removeRecursively(targetFilePath, &errorMsg);
- if (!Utils::FileUtils::copyRecursively(deployable.localFilePath,
- targetFilePath, &errorMsg)) {
+ Utils::FileUtils::removeRecursively(Utils::FileName::fromString(targetFilePath), &errorMsg);
+ if (!Utils::FileUtils::copyRecursively(deployable.localFilePath(),
+ Utils::FileName::fromString(targetFilePath), &errorMsg)) {
emit addOutput(tr("Sysroot installation failed: %1\n"
" Continuing anyway.").arg(errorMsg), ErrorMessageOutput);
}
diff --git a/src/plugins/madde/maemoinstalltosysrootstep.h b/src/plugins/madde/maemoinstalltosysrootstep.h
index 5aca0e96a9..1ab18e1dea 100644
--- a/src/plugins/madde/maemoinstalltosysrootstep.h
+++ b/src/plugins/madde/maemoinstalltosysrootstep.h
@@ -32,7 +32,7 @@
#include <projectexplorer/abstractprocessstep.h>
#include <projectexplorer/buildstep.h>
-#include <remotelinux/deployablefile.h>
+#include <projectexplorer/deployablefile.h>
#include <QStringList>
@@ -104,7 +104,7 @@ public:
static QString displayName();
private:
QString m_systemRoot;
- QList<RemoteLinux::DeployableFile> m_files;
+ QList<ProjectExplorer::DeployableFile> m_files;
};
class MaemoMakeInstallToSysrootStep : public ProjectExplorer::AbstractProcessStep
diff --git a/src/plugins/madde/maemopackagecreationstep.cpp b/src/plugins/madde/maemopackagecreationstep.cpp
index a2c702d9e6..207e42c1cb 100644
--- a/src/plugins/madde/maemopackagecreationstep.cpp
+++ b/src/plugins/madde/maemopackagecreationstep.cpp
@@ -42,6 +42,7 @@
#include <qtsupport/qtkitinformation.h>
#include <utils/environment.h>
#include <utils/fileutils.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDateTime>
@@ -57,6 +58,7 @@ using ProjectExplorer::BuildStepList;
using ProjectExplorer::BuildStepConfigWidget;
using ProjectExplorer::Task;
using namespace Qt4ProjectManager;
+using namespace Utils;
namespace Madde {
namespace Internal {
@@ -225,7 +227,7 @@ bool AbstractMaemoPackageCreationStep::callPackagingCommand(QProcess *proc,
void AbstractMaemoPackageCreationStep::preparePackagingProcess(QProcess *proc,
const Qt4BuildConfiguration *bc, const QString &workingDir)
{
- Utils::Environment env = bc->environment();
+ Environment env = bc->environment();
if (bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild) {
env.appendOrSet(QLatin1String("DEB_BUILD_OPTIONS"),
QLatin1String("nostrip"), QLatin1String(" "));
@@ -329,12 +331,12 @@ bool MaemoDebianPackageCreationStep::createPackage(QProcess *buildProc,
bool MaemoDebianPackageCreationStep::isMetaDataNewerThan(const QDateTime &packageDate) const
{
- const Utils::FileName debianPath = DebianManager::debianDirectory(target());
+ const FileName debianPath = DebianManager::debianDirectory(target());
if (packageDate <= debianPath.toFileInfo().lastModified())
return true;
const QStringList debianFiles = DebianManager::debianFiles(debianPath);
foreach (const QString &debianFile, debianFiles) {
- Utils::FileName absFilePath = debianPath;
+ FileName absFilePath = debianPath;
absFilePath.appendPath(debianFile);
if (packageDate <= absFilePath.toFileInfo().lastModified())
return true;
@@ -351,7 +353,7 @@ void MaemoDebianPackageCreationStep::checkProjectName()
"Debian packages.\nThey must only use lower-case letters, "
"numbers, '-', '+' and '.'.\n""We will try to work around that, "
"but you may experience problems."),
- Utils::FileName(), -1, Core::Id(TASK_CATEGORY_BUILDSYSTEM)));
+ FileName(), -1, Core::Id(TASK_CATEGORY_BUILDSYSTEM)));
}
}
@@ -370,13 +372,13 @@ bool MaemoDebianPackageCreationStep::copyDebianFiles(bool inSourceBuild)
return false;
}
QString error;
- if (!Utils::FileUtils::removeRecursively(debianDirPath, &error)) {
+ if (!FileUtils::removeRecursively(FileName::fromString(debianDirPath), &error)) {
raiseError(tr("Packaging failed: Could not remove directory '%1': %2")
.arg(debianDirPath, error));
return false;
}
QDir buildDir(cachedPackageDirectory());
- if (!buildDir.mkdir("debian")) {
+ if (!buildDir.mkdir(QLatin1String("debian"))) {
raiseError(tr("Could not create Debian directory '%1'.").arg(debianDirPath));
return false;
}
@@ -396,7 +398,7 @@ bool MaemoDebianPackageCreationStep::copyDebianFiles(bool inSourceBuild)
}
if (newFileName == DebianManager::packageName(DebianManager::debianDirectory(target())) + QLatin1String(".aegis")) {
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(srcFile)) {
raiseError(tr("Could not read manifest file '%1': %2.")
.arg(QDir::toNativeSeparators(srcFile), reader.errorString()));
@@ -436,9 +438,8 @@ bool MaemoDebianPackageCreationStep::copyDebianFiles(bool inSourceBuild)
QString MaemoDebianPackageCreationStep::packagingCommand(const QString &maddeRoot, const QString &commandName)
{
QString perl;
-#ifdef Q_OS_WIN
- perl = maddeRoot + QLatin1String("/bin/perl.exe ");
-#endif
+ if (HostOsInfo::isWindowsHost())
+ perl = maddeRoot + QLatin1String("/bin/perl.exe ");
return perl + maddeRoot + QLatin1String("/madbin/") + commandName;
}
@@ -457,7 +458,7 @@ void MaemoDebianPackageCreationStep::ensureShlibdeps(QByteArray &rulesContent)
bool MaemoDebianPackageCreationStep::adaptRulesFile(
const QString &templatePath, const QString &rulesFilePath)
{
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(templatePath)) {
raiseError(reader.errorString());
return false;
@@ -467,7 +468,7 @@ bool MaemoDebianPackageCreationStep::adaptRulesFile(
if (!m_debugBuild)
ensureShlibdeps(content);
- Utils::FileSaver saver(rulesFilePath);
+ FileSaver saver(rulesFilePath);
saver.write(content);
if (!saver.finalize()) {
raiseError(saver.errorString());
diff --git a/src/plugins/madde/maemopackagecreationwidget.cpp b/src/plugins/madde/maemopackagecreationwidget.cpp
index 2ad228c182..0511985bb0 100644
--- a/src/plugins/madde/maemopackagecreationwidget.cpp
+++ b/src/plugins/madde/maemopackagecreationwidget.cpp
@@ -188,7 +188,7 @@ void MaemoPackageCreationWidget::setPackageManagerIcon()
QString imageFilter = tr("Images") + QLatin1String("( ");
const QList<QByteArray> &imageTypes = QImageReader::supportedImageFormats();
foreach (const QByteArray &imageType, imageTypes)
- imageFilter += "*." + QString::fromAscii(imageType) + QLatin1Char(' ');
+ imageFilter += QLatin1String("*.") + QLatin1String(imageType) + QLatin1Char(' ');
imageFilter += QLatin1Char(')');
const QSize iconSize = MaddeDevice::packageManagerIconSize(deviceType);
const QString iconFileName = QFileDialog::getOpenFileName(this,
diff --git a/src/plugins/madde/maemopublishedprojectmodel.cpp b/src/plugins/madde/maemopublishedprojectmodel.cpp
index 24656a7fb8..27c5a738c3 100644
--- a/src/plugins/madde/maemopublishedprojectmodel.cpp
+++ b/src/plugins/madde/maemopublishedprojectmodel.cpp
@@ -116,11 +116,10 @@ bool MaemoPublishedProjectModel::setData(const QModelIndex &index,
if (index.column() != IncludeColumn)
return QFileSystemModel::setData(index, value, role);
if (role == Qt::CheckStateRole) {
- if (value == Qt::Checked) {
+ if (value == Qt::Checked)
m_filesToExclude.remove(filePath(index));
- } else {
+ else
m_filesToExclude.insert(filePath(index));
- }
if (isDir(index))
emit layoutChanged();
return true;
diff --git a/src/plugins/madde/maemopublisherfremantlefree.cpp b/src/plugins/madde/maemopublisherfremantlefree.cpp
index 494c847764..2656fa953c 100644
--- a/src/plugins/madde/maemopublisherfremantlefree.cpp
+++ b/src/plugins/madde/maemopublisherfremantlefree.cpp
@@ -42,8 +42,6 @@
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
-#include <remotelinux/deployablefilesperprofile.h>
-#include <remotelinux/deploymentinfo.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <ssh/sshremoteprocessrunner.h>
@@ -59,6 +57,7 @@ using namespace Core;
using namespace Qt4ProjectManager;
using namespace RemoteLinux;
using namespace QSsh;
+using namespace Utils;
namespace Madde {
namespace Internal {
@@ -128,7 +127,7 @@ void MaemoPublisherFremantleFree::createPackage()
if (QFileInfo(tmpDirContainer()).exists()) {
emit progressReport(tr("Removing left-over temporary directory..."));
QString error;
- if (!Utils::FileUtils::removeRecursively(tmpDirContainer(), &error)) {
+ if (!FileUtils::removeRecursively(FileName::fromString(tmpDirContainer()), &error)) {
finishWithFailure(tr("Error removing temporary directory: %1").arg(error),
tr("Publishing failed: Could not create source package."));
return;
@@ -152,13 +151,6 @@ void MaemoPublisherFremantleFree::createPackage()
return;
}
- QString error;
- if (!updateDesktopFiles(&error)) {
- finishWithFailure(error,
- tr("Publishing failed: Could not create package."));
- return;
- }
-
emit progressReport(tr("Cleaning up temporary directory..."));
AbstractMaemoPackageCreationStep::preparePackagingProcess(m_process,
m_buildConfig, m_tmpProjectDir);
@@ -209,7 +201,7 @@ bool MaemoPublisherFremantleFree::copyRecursively(const QString &srcFilePath,
}
} else {
if (tgtFilePath == m_tmpProjectDir + QLatin1String("/debian/rules")) {
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(srcFilePath)) {
emit progressReport(reader.errorString(), ErrorOutput);
return false;
@@ -219,7 +211,7 @@ bool MaemoPublisherFremantleFree::copyRecursively(const QString &srcFilePath,
rulesContents.replace("# Add here commands to configure the package.",
"qmake " + QFileInfo(m_project->document()->fileName()).fileName().toLocal8Bit());
MaemoDebianPackageCreationStep::ensureShlibdeps(rulesContents);
- Utils::FileSaver saver(tgtFilePath);
+ FileSaver saver(tgtFilePath);
saver.write(rulesContents);
if (!saver.finalize()) {
emit progressReport(saver.errorString(), ErrorOutput);
@@ -251,7 +243,7 @@ bool MaemoPublisherFremantleFree::fixNewlines()
const QStringList &fileNames = debianDir.entryList(QDir::Files);
foreach (const QString &fileName, fileNames) {
QString filePath = debianDir.filePath(fileName);
- Utils::FileReader reader;
+ FileReader reader;
if (!reader.fetch(filePath))
return false;
QByteArray contents = reader.data();
@@ -259,7 +251,7 @@ bool MaemoPublisherFremantleFree::fixNewlines()
if (!contents.contains(crlf))
continue;
contents.replace(crlf, "\n");
- Utils::FileSaver saver(filePath);
+ FileSaver saver(filePath);
saver.write(contents);
if (!saver.finalize())
return false;
@@ -373,7 +365,7 @@ void MaemoPublisherFremantleFree::runDpkgBuildPackage()
}
foreach (const QString &filePath, d.filesToExclude()) {
QString error;
- if (!Utils::FileUtils::removeRecursively(filePath, &error)) {
+ if (!FileUtils::removeRecursively(FileName::fromString(filePath), &error)) {
finishWithFailure(error,
tr("Publishing failed: Could not create package."));
}
@@ -541,65 +533,6 @@ void MaemoPublisherFremantleFree::finishWithFailure(const QString &progressMsg,
setState(Inactive);
}
-bool MaemoPublisherFremantleFree::updateDesktopFiles(QString *error) const
-{
- bool success = true;
- const Qt4MaemoDeployConfiguration *const deployConfig
- = qobject_cast<Qt4MaemoDeployConfiguration *>(m_buildConfig->target()->activeDeployConfiguration());
- QTC_ASSERT(deployConfig, return false);
- const DeploymentInfo *const deploymentInfo = deployConfig->deploymentInfo();
- for (int i = 0; i < deploymentInfo->modelCount(); ++i) {
- const DeployableFilesPerProFile * const model = deploymentInfo->modelAt(i);
- QString desktopFilePath = deployConfig->localDesktopFilePath(model);
- if (desktopFilePath.isEmpty())
- continue;
- desktopFilePath.replace(model->projectDir(), m_tmpProjectDir);
- const QString executableFilePath = model->remoteExecutableFilePath();
- if (executableFilePath.isEmpty()) {
- qDebug("%s: Skipping subproject %s with missing deployment information.",
- Q_FUNC_INFO, qPrintable(model->proFilePath()));
- continue;
- }
- Utils::FileReader reader;
- if (!reader.fetch(desktopFilePath, error)) {
- success = false;
- continue;
- }
- QByteArray desktopFileContents = reader.data();
- bool fileNeedsUpdate = addOrReplaceDesktopFileValue(desktopFileContents,
- "Exec", executableFilePath.toUtf8());
- if (fileNeedsUpdate) {
- Utils::FileSaver saver(desktopFilePath);
- saver.write(desktopFileContents);
- if (!saver.finalize(error))
- success = false;
- }
- }
- return success;
-}
-
-bool MaemoPublisherFremantleFree::addOrReplaceDesktopFileValue(QByteArray &fileContent,
- const QByteArray &key, const QByteArray &newValue) const
-{
- const int keyPos = fileContent.indexOf(key + '=');
- if (keyPos == -1) {
- if (!fileContent.endsWith('\n'))
- fileContent += '\n';
- fileContent += key + '=' + newValue + '\n';
- return true;
- }
- int nextNewlinePos = fileContent.indexOf('\n', keyPos);
- if (nextNewlinePos == -1)
- nextNewlinePos = fileContent.count();
- const int replacePos = keyPos + key.count() + 1;
- const int replaceCount = nextNewlinePos - replacePos;
- const QByteArray &oldValue = fileContent.mid(replacePos, replaceCount);
- if (oldValue == newValue)
- return false;
- fileContent.replace(replacePos, replaceCount, newValue);
- return true;
-}
-
QStringList MaemoPublisherFremantleFree::findProblems() const
{
QStringList problems;
diff --git a/src/plugins/madde/maemopublisherfremantlefree.h b/src/plugins/madde/maemopublisherfremantlefree.h
index 98c4fb2f1f..f14f077bd1 100644
--- a/src/plugins/madde/maemopublisherfremantlefree.h
+++ b/src/plugins/madde/maemopublisherfremantlefree.h
@@ -104,9 +104,6 @@ private:
void prepareToSendFile();
void sendFile();
void finishWithFailure(const QString &progressMsg, const QString &resultMsg);
- bool updateDesktopFiles(QString *error = 0) const;
- bool addOrReplaceDesktopFileValue(QByteArray &fileContent,
- const QByteArray &key, const QByteArray &newValue) const;
QStringList findProblems() const;
const ProjectExplorer::Project * const m_project;
diff --git a/src/plugins/madde/maemoqemumanager.cpp b/src/plugins/madde/maemoqemumanager.cpp
index 516c45e372..12c875981f 100644
--- a/src/plugins/madde/maemoqemumanager.cpp
+++ b/src/plugins/madde/maemoqemumanager.cpp
@@ -83,8 +83,8 @@ MaemoQemuManager::MaemoQemuManager(QObject *parent)
, m_runtimeRootWatcher(0)
, m_runtimeFolderWatcher(0)
{
- m_qemuStarterIcon.addFile(":/qt-maemo/images/qemu-run.png", iconSize);
- m_qemuStarterIcon.addFile(":/qt-maemo/images/qemu-stop.png", iconSize,
+ m_qemuStarterIcon.addFile(QLatin1String(":/qt-maemo/images/qemu-run.png"), iconSize);
+ m_qemuStarterIcon.addFile(QLatin1String(":/qt-maemo/images/qemu-stop.png"), iconSize,
QIcon::Normal, QIcon::On);
m_qemuAction = new QAction(tr("MeeGo Emulator"), this);
diff --git a/src/plugins/madde/maemoqemuruntimeparser.cpp b/src/plugins/madde/maemoqemuruntimeparser.cpp
index d0ee1fb61f..e013711fe5 100644
--- a/src/plugins/madde/maemoqemuruntimeparser.cpp
+++ b/src/plugins/madde/maemoqemuruntimeparser.cpp
@@ -32,6 +32,7 @@
#include "maemoqemusettings.h"
#include <qtsupport/baseqtversion.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDir>
@@ -94,7 +95,7 @@ MaemoQemuRuntime MaemoQemuRuntimeParser::parseRuntime(const QtSupport::BaseQtVer
return runtime;
if (!madProc.waitForStarted() || !madProc.waitForFinished())
return runtime;
- const QByteArray &madInfoOutput = madProc.readAllStandardOutput();
+ QString madInfoOutput = QString::fromLocal8Bit(madProc.readAllStandardOutput());
const QString &targetName = MaemoGlobal::targetName(qtVersion->qmakeCommand().toString());
runtime = MaemoQemuRuntimeParserV2(madInfoOutput, targetName, maddeRootPath)
.parseRuntime();
@@ -127,7 +128,7 @@ MaemoQemuRuntime MaemoQemuRuntimeParserV1::parseRuntime()
&& m_madInfoReader.name() == QLatin1String("target")) {
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (attrs.value(QLatin1String("target_id")) == m_targetName)
- targetRuntime = attrs.value("runtime_id").toString();
+ targetRuntime = attrs.value(QLatin1String("runtime_id")).toString();
} else if (m_madInfoReader.name() == QLatin1String("runtime")) {
const QXmlStreamAttributes attrs = m_madInfoReader.attributes();
while (!m_madInfoReader.atEnd()) {
@@ -198,17 +199,17 @@ void MaemoQemuRuntimeParserV1::fillRuntimeInformation(MaemoQemuRuntime *runtime)
// This is complex because of extreme MADDE weirdness.
const QString root = m_maddeRoot + QLatin1Char('/');
const bool pathIsRelative = QFileInfo(runtime->m_bin).isRelative();
- runtime->m_bin =
- #ifdef Q_OS_WIN
- root + (pathIsRelative
- ? QLatin1String("madlib/") + runtime->m_bin // Fremantle.
- : runtime->m_bin) // Harmattan.
- + QLatin1String(".exe");
- #else
- pathIsRelative
- ? root + QLatin1String("madlib/") + runtime->m_bin // Fremantle.
- : runtime->m_bin; // Harmattan.
- #endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ runtime->m_bin =
+ root + (pathIsRelative
+ ? QLatin1String("madlib/") + runtime->m_bin // Fremantle.
+ : runtime->m_bin) // Harmattan.
+ + QLatin1String(".exe");
+ } else {
+ runtime->m_bin = pathIsRelative
+ ? root + QLatin1String("madlib/") + runtime->m_bin // Fremantle.
+ : runtime->m_bin; // Harmattan.
+ }
}
}
}
@@ -335,17 +336,17 @@ void MaemoQemuRuntimeParserV2::handleEnvironmentTag(MaemoQemuRuntime &runtime)
while (m_madInfoReader.readNextStartElement())
handleVariableTag(runtime);
-#ifdef Q_OS_WIN
- const QString root = QDir::toNativeSeparators(m_maddeRoot)
- + QLatin1Char('/');
- const QLatin1Char colon(';');
- const QLatin1String key("PATH");
- QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
- runtime.m_normalVars << MaemoQemuRuntime::Variable(key,
- root + QLatin1String("bin") + colon + env.value(key));
- runtime.m_normalVars << MaemoQemuRuntime::Variable(key,
- root + QLatin1String("madlib") + colon + env.value(key));
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ const QString root = QDir::toNativeSeparators(m_maddeRoot)
+ + QLatin1Char('/');
+ const QLatin1Char colon(';');
+ const QLatin1String key("PATH");
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ runtime.m_normalVars << MaemoQemuRuntime::Variable(key,
+ root + QLatin1String("bin") + colon + env.value(key));
+ runtime.m_normalVars << MaemoQemuRuntime::Variable(key,
+ root + QLatin1String("madlib") + colon + env.value(key));
+ }
}
void MaemoQemuRuntimeParserV2::handleVariableTag(MaemoQemuRuntime &runtime)
@@ -378,11 +379,10 @@ void MaemoQemuRuntimeParserV2::handleVariableTag(MaemoQemuRuntime &runtime)
if (varName.isEmpty())
return;
- if (isGlBackend) {
+ if (isGlBackend)
runtime.m_openGlBackendVarName = varName;
- } else {
+ else
runtime.m_normalVars << MaemoQemuRuntime::Variable(varName, varValue);
- }
}
QList<MaemoQemuRuntimeParserV2::Port> MaemoQemuRuntimeParserV2::handleTcpPortListTag()
diff --git a/src/plugins/madde/maemoqtversion.cpp b/src/plugins/madde/maemoqtversion.cpp
index e71791d009..ed2b15d8e8 100644
--- a/src/plugins/madde/maemoqtversion.cpp
+++ b/src/plugins/madde/maemoqtversion.cpp
@@ -34,6 +34,7 @@
#include <projectexplorer/kitinformation.h>
#include <qt4projectmanager/qt4projectmanagerconstants.h>
#include <qtsupport/qtsupportconstants.h>
+#include <utils/hostosinfo.h>
#include <QCoreApplication>
#include <QFile>
@@ -59,7 +60,7 @@ MaemoQtVersion::MaemoQtVersion(const Utils::FileName &path, bool isAutodetected,
m_isvalidVersion(false),
m_initialized(false)
{
-
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
}
MaemoQtVersion::~MaemoQtVersion()
@@ -76,7 +77,7 @@ void MaemoQtVersion::fromMap(const QVariantMap &map)
QString MaemoQtVersion::type() const
{
- return QtSupport::Constants::MAEMOQT;
+ return QLatin1String(QtSupport::Constants::MAEMOQT);
}
bool MaemoQtVersion::isValid() const
@@ -124,10 +125,7 @@ QString MaemoQtVersion::description() const
bool MaemoQtVersion::supportsShadowBuilds() const
{
-#ifdef Q_OS_WIN
- return false;
-#endif
- return true;
+ return !Utils::HostOsInfo::isWindowsHost();
}
Core::Id MaemoQtVersion::deviceType() const
@@ -170,15 +168,15 @@ void MaemoQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Envi
// Needed to make pkg-config stuff work.
Utils::FileName sysRoot = ProjectExplorer::SysRootKitInformation::sysRoot(k);
env.prependOrSet(QLatin1String("SYSROOT_DIR"), sysRoot.toUserOutput());
- env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madbin")
+ env.prependOrSetPath(QDir::toNativeSeparators(QString::fromLatin1("%1/madbin")
.arg(maddeRoot)));
- env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madlib")
+ env.prependOrSetPath(QDir::toNativeSeparators(QString::fromLatin1("%1/madlib")
.arg(maddeRoot)));
env.prependOrSet(QLatin1String("PERL5LIB"),
- QDir::toNativeSeparators(QString("%1/madlib/perl5").arg(maddeRoot)));
+ QDir::toNativeSeparators(QString::fromLatin1("%1/madlib/perl5").arg(maddeRoot)));
- env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin").arg(maddeRoot)));
- env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin")
+ env.prependOrSetPath(QDir::toNativeSeparators(QString::fromLatin1("%1/bin").arg(maddeRoot)));
+ env.prependOrSetPath(QDir::toNativeSeparators(QString::fromLatin1("%1/bin")
.arg(MaemoGlobal::targetRoot(qmakeCommand().toString()))));
// Actually this is tool chain related, but since we no longer have a tool chain...
diff --git a/src/plugins/madde/maemoremotecopyfacility.cpp b/src/plugins/madde/maemoremotecopyfacility.cpp
index 57da2eb7e9..9a2386f6e9 100644
--- a/src/plugins/madde/maemoremotecopyfacility.cpp
+++ b/src/plugins/madde/maemoremotecopyfacility.cpp
@@ -32,12 +32,12 @@
#include <ssh/sshconnection.h>
#include <ssh/sshremoteprocessrunner.h>
+#include <utils/hostosinfo.h>
#include <QDir>
using namespace ProjectExplorer;
using namespace QSsh;
-using namespace RemoteLinux;
namespace Madde {
namespace Internal {
@@ -124,19 +124,19 @@ void MaemoRemoteCopyFacility::copyNextFile()
const DeployableFile &d = m_deployables.first();
QString sourceFilePath = m_mountPoint;
-#ifdef Q_OS_WIN
- const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath);
- sourceFilePath += QLatin1Char('/') + localFilePath.at(0).toLower()
- + localFilePath.mid(2);
-#else
- sourceFilePath += d.localFilePath;
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ const QString localFilePath = QDir::fromNativeSeparators(d.localFilePath().toString());
+ sourceFilePath += QLatin1Char('/') + localFilePath.at(0).toLower()
+ + localFilePath.mid(2);
+ } else {
+ sourceFilePath += d.localFilePath().toString();
+ }
QString command = QString::fromLatin1("%1 mkdir -p %3 && %1 cp -a %2 %3")
.arg(MaemoGlobal::remoteSudo(m_devConf->type(), m_devConf->sshParameters().userName),
- sourceFilePath, d.remoteDir);
+ sourceFilePath, d.remoteDirectory());
emit progress(tr("Copying file '%1' to directory '%2' on the device...")
- .arg(d.localFilePath, d.remoteDir));
+ .arg(d.localFilePath().toString(), d.remoteDirectory()));
m_copyRunner->run(command.toUtf8(), m_devConf->sshParameters());
}
diff --git a/src/plugins/madde/maemoremotecopyfacility.h b/src/plugins/madde/maemoremotecopyfacility.h
index 0d97624c50..ae88139348 100644
--- a/src/plugins/madde/maemoremotecopyfacility.h
+++ b/src/plugins/madde/maemoremotecopyfacility.h
@@ -30,7 +30,7 @@
#ifndef MAEMOREMOTECOPYFACILITY_H
#define MAEMOREMOTECOPYFACILITY_H
-#include <remotelinux/deployablefile.h>
+#include <projectexplorer/deployablefile.h>
#include <projectexplorer/devicesupport/idevice.h>
#include <QList>
@@ -53,14 +53,14 @@ public:
void copyFiles(QSsh::SshConnection *connection,
const ProjectExplorer::IDevice::ConstPtr &device,
- const QList<RemoteLinux::DeployableFile> &deployables, const QString &mountPoint);
+ const QList<ProjectExplorer::DeployableFile> &deployables, const QString &mountPoint);
void cancel();
signals:
void stdoutData(const QString &output);
void stderrData(const QString &output);
void progress(const QString &message);
- void fileCopied(const RemoteLinux::DeployableFile &deployable);
+ void fileCopied(const ProjectExplorer::DeployableFile &deployable);
void finished(const QString &errorMsg = QString());
private slots:
@@ -76,7 +76,7 @@ private:
QSsh::SshRemoteProcessRunner *m_copyRunner;
QSsh::SshRemoteProcessRunner *m_killProcess;
ProjectExplorer::IDevice::ConstPtr m_devConf;
- QList<RemoteLinux::DeployableFile> m_deployables;
+ QList<ProjectExplorer::DeployableFile> m_deployables;
QString m_mountPoint;
bool m_isCopying; // TODO: Redundant due to being in sync with m_copyRunner?
};
diff --git a/src/plugins/madde/maemorunconfiguration.h b/src/plugins/madde/maemorunconfiguration.h
index 9034e3bace..d7083322d9 100644
--- a/src/plugins/madde/maemorunconfiguration.h
+++ b/src/plugins/madde/maemorunconfiguration.h
@@ -40,7 +40,8 @@ class MaemoRunConfiguration : public RemoteLinux::RemoteLinuxRunConfiguration
Q_OBJECT
public:
- MaemoRunConfiguration(ProjectExplorer::Target *parent, Core::Id id, const QString &proFilePath);
+ MaemoRunConfiguration(ProjectExplorer::Target *parent, Core::Id id,
+ const QString &projectFilePath);
MaemoRunConfiguration(ProjectExplorer::Target *parent, MaemoRunConfiguration *source);
QVariantMap toMap() const;
diff --git a/src/plugins/madde/maemorunfactories.cpp b/src/plugins/madde/maemorunfactories.cpp
index 39cf0bc09f..0ab91955f1 100644
--- a/src/plugins/madde/maemorunfactories.cpp
+++ b/src/plugins/madde/maemorunfactories.cpp
@@ -110,7 +110,8 @@ bool MaemoRunConfigurationFactory::canClone(Target *parent,
return false;
const RemoteLinuxRunConfiguration * const rlrc
= qobject_cast<RemoteLinuxRunConfiguration *>(source);
- QString idStr = QString::fromLatin1(source->id().name()) + QLatin1Char('.') + rlrc->proFilePath();
+ QString idStr = QString::fromLatin1(source->id().name()) + QLatin1Char('.')
+ + rlrc->projectFilePath();
return rlrc && canCreate(parent, Core::Id(idStr));
}
@@ -178,7 +179,7 @@ QList<RunConfiguration *> MaemoRunConfigurationFactory::runConfigurationsForNode
QList<ProjectExplorer::RunConfiguration *> result;
foreach (ProjectExplorer::RunConfiguration *rc, t->runConfigurations())
if (MaemoRunConfiguration *mrc = qobject_cast<MaemoRunConfiguration *>(rc))
- if (mrc->proFilePath() == n->path())
+ if (mrc->projectFilePath() == n->path())
result << rc;
return result;
}
diff --git a/src/plugins/madde/maemosettingspages.cpp b/src/plugins/madde/maemosettingspages.cpp
index aa96c5a503..185b3791b7 100644
--- a/src/plugins/madde/maemosettingspages.cpp
+++ b/src/plugins/madde/maemosettingspages.cpp
@@ -136,14 +136,14 @@ void MaemoQemuSettingsPage::showQemuCrashDialog()
dlg.exec();
}
-QString MaemoQemuSettingsPage::pageId()
+Core::Id MaemoQemuSettingsPage::pageId()
{
- return QLatin1String("ZZ.Qemu Settings");
+ return "ZZ.Qemu Settings";
}
-QString MaemoQemuSettingsPage::pageCategory()
+Core::Id MaemoQemuSettingsPage::pageCategory()
{
- return QLatin1String(ProjectExplorer::Constants::DEVICE_SETTINGS_CATEGORY);
+ return ProjectExplorer::Constants::DEVICE_SETTINGS_CATEGORY;
}
} // namespace Internal
diff --git a/src/plugins/madde/maemosettingspages.h b/src/plugins/madde/maemosettingspages.h
index 34a78a4ab4..da273400de 100644
--- a/src/plugins/madde/maemosettingspages.h
+++ b/src/plugins/madde/maemosettingspages.h
@@ -31,6 +31,7 @@
#define MAEMOSETTINGSPAGES_H
#include <coreplugin/dialogs/ioptionspage.h>
+#include <coreplugin/id.h>
namespace Madde{
namespace Internal {
@@ -49,8 +50,8 @@ public:
void finish();
static void showQemuCrashDialog();
- static QString pageId();
- static QString pageCategory();
+ static Core::Id pageId();
+ static Core::Id pageCategory();
private:
QString m_keywords;
diff --git a/src/plugins/madde/qt4maemodeployconfiguration.cpp b/src/plugins/madde/qt4maemodeployconfiguration.cpp
index c3c78424c0..adec54f79b 100644
--- a/src/plugins/madde/qt4maemodeployconfiguration.cpp
+++ b/src/plugins/madde/qt4maemodeployconfiguration.cpp
@@ -33,23 +33,21 @@
#include "maddeuploadandinstallpackagesteps.h"
#include "maemoconstants.h"
#include "maemodeploybymountsteps.h"
-#include "maemodeployconfigurationwidget.h"
#include "maemoglobal.h"
#include "maemoinstalltosysrootstep.h"
#include "maemopackagecreationstep.h"
#include <coreplugin/icore.h>
#include <projectexplorer/buildsteplist.h>
+#include <projectexplorer/deployablefile.h>
#include <projectexplorer/target.h>
#include <projectexplorer/projectexplorer.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4project.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
-#include <remotelinux/deployablefile.h>
-#include <remotelinux/deployablefilesperprofile.h>
-#include <remotelinux/deploymentinfo.h>
#include <remotelinux/remotelinuxcheckforfreediskspacestep.h>
+#include <remotelinux/remotelinuxdeployconfigurationwidget.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
@@ -62,38 +60,27 @@ using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace RemoteLinux;
-const char OldDeployConfigId[] = "2.2MaemoDeployConfig";
-const char DEPLOYMENT_ASSISTANT_SETTING[] = "RemoteLinux.DeploymentAssistant";
-
namespace Madde {
namespace Internal {
Qt4MaemoDeployConfiguration::Qt4MaemoDeployConfiguration(ProjectExplorer::Target *target,
const Core::Id id, const QString &displayName)
: RemoteLinuxDeployConfiguration(target, id, displayName)
-{ init(); }
+{
+ init();
+}
Qt4MaemoDeployConfiguration::Qt4MaemoDeployConfiguration(ProjectExplorer::Target *target,
Qt4MaemoDeployConfiguration *source)
: RemoteLinuxDeployConfiguration(target, source)
-{ init(); }
-
-QString Qt4MaemoDeployConfiguration::localDesktopFilePath(const DeployableFilesPerProFile *proFileInfo) const
{
- QTC_ASSERT(proFileInfo->projectType() == ApplicationTemplate, return QString());
-
- for (int i = 0; i < proFileInfo->rowCount(); ++i) {
- const DeployableFile &d = proFileInfo->deployableAt(i);
- if (QFileInfo(d.localFilePath).fileName().endsWith(QLatin1String(".desktop")))
- return d.localFilePath;
- }
- return QString();
+ init();
+ cloneSteps(source);
}
-
-DeployConfigurationWidget *Qt4MaemoDeployConfiguration::configurationWidget() const
+NamedWidget *Qt4MaemoDeployConfiguration::createConfigWidget()
{
- return new MaemoDeployConfigurationWidget;
+ return new RemoteLinuxDeployConfigurationWidget(this);
}
Qt4MaemoDeployConfiguration::~Qt4MaemoDeployConfiguration() {}
@@ -113,33 +100,6 @@ Core::Id Qt4MaemoDeployConfiguration::harmattanId()
return Core::Id("DeployToHarmattan");
}
-DeploymentSettingsAssistant *Qt4MaemoDeployConfiguration::deploymentSettingsAssistant()
-{
- return static_cast<DeploymentSettingsAssistant *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING)).value<QObject *>());
-}
-
-QString Qt4MaemoDeployConfiguration::qmakeScope() const
-{
- Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target()->kit());
-
- if (deviceType == Maemo5OsType)
- return QLatin1String("maemo5");
- if (deviceType == HarmattanOsType)
- return QLatin1String("contains(MEEGO_EDITION,harmattan)");
- return QString("unix");
-}
-
-QString Qt4MaemoDeployConfiguration::installPrefix() const
-{
- Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target()->kit());
-
- if (deviceType == Maemo5OsType)
- return QLatin1String("/opt");
- if (deviceType == HarmattanOsType)
- return QLatin1String("/opt");
- return QLatin1String("/usr/local");
-}
-
void Qt4MaemoDeployConfiguration::debianDirChanged(const Utils::FileName &dir)
{
if (dir == DebianManager::debianDirectory(target()))
@@ -246,15 +206,6 @@ void Qt4MaemoDeployConfiguration::addFilesToProject(const QStringList &files)
void Qt4MaemoDeployConfiguration::init()
{
- // Make sure we have deploymentInfo, but create it only once:
- DeploymentSettingsAssistant *assistant
- = qobject_cast<DeploymentSettingsAssistant *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING)).value<QObject *>());
- if (!assistant) {
- assistant = new DeploymentSettingsAssistant(deploymentInfo(), static_cast<Qt4ProjectManager::Qt4Project *>(target()->project()));
- QVariant data = QVariant::fromValue(static_cast<QObject *>(assistant));
- target()->project()->setNamedSettings(QLatin1String(DEPLOYMENT_ASSISTANT_SETTING), data);
- }
-
connect(target()->project(), SIGNAL(fileListChanged()), this, SLOT(setupPackaging()));
}
@@ -327,25 +278,16 @@ DeployConfiguration *Qt4MaemoDeployConfigurationFactory::create(Target *parent,
bool Qt4MaemoDeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
Core::Id id = idFromMap(map);
- return canHandle(parent)
- && (availableCreationIds(parent).contains(id) || id == OldDeployConfigId)
+ return canHandle(parent) && availableCreationIds(parent).contains(id)
&& MaemoGlobal::supportsMaemoDevice(parent->kit());
}
DeployConfiguration *Qt4MaemoDeployConfigurationFactory::restore(Target *parent, const QVariantMap &map)
{
- if (!canRestore(parent, map))
- return 0;
- Core::Id id = idFromMap(map);
- Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(parent->kit());
- if (id == OldDeployConfigId) {
- if (deviceType == Maemo5OsType)
- id = Qt4MaemoDeployConfiguration::fremantleWithPackagingId();
- else if (deviceType == HarmattanOsType)
- id = Qt4MaemoDeployConfiguration::harmattanId();
- }
+ QTC_ASSERT(canRestore(parent, map), return 0);
+
Qt4MaemoDeployConfiguration * const dc
- = qobject_cast<Qt4MaemoDeployConfiguration *>(create(parent, id));
+ = qobject_cast<Qt4MaemoDeployConfiguration *>(create(parent, idFromMap(map)));
if (!dc->fromMap(map)) {
delete dc;
return 0;
diff --git a/src/plugins/madde/qt4maemodeployconfiguration.h b/src/plugins/madde/qt4maemodeployconfiguration.h
index 301ad0787a..b4a7f70dbd 100644
--- a/src/plugins/madde/qt4maemodeployconfiguration.h
+++ b/src/plugins/madde/qt4maemodeployconfiguration.h
@@ -30,15 +30,9 @@
#ifndef QT4PROJECTMANAGER_QT4DEPLOYCONFIGURATION_H
#define QT4PROJECTMANAGER_QT4DEPLOYCONFIGURATION_H
-#include <remotelinux/deploymentsettingsassistant.h>
#include <remotelinux/remotelinuxdeployconfiguration.h>
#include <utils/fileutils.h>
-namespace RemoteLinux {
-class DeployableFilesPerProFile;
-class DeploymentSettingsAssistant;
-} // namespace RemoteLinux
-
namespace Madde {
namespace Internal {
@@ -68,18 +62,14 @@ class Qt4MaemoDeployConfiguration : public RemoteLinux::RemoteLinuxDeployConfigu
public:
~Qt4MaemoDeployConfiguration();
- ProjectExplorer::DeployConfigurationWidget *configurationWidget() const;
-
- QString localDesktopFilePath(const RemoteLinux::DeployableFilesPerProFile *proFileInfo) const;
+ ProjectExplorer::NamedWidget *createConfigWidget();
static Core::Id fremantleWithPackagingId();
static Core::Id fremantleWithoutPackagingId();
static Core::Id harmattanId();
- RemoteLinux::DeploymentSettingsAssistant *deploymentSettingsAssistant();
-
- QString qmakeScope() const;
- QString installPrefix() const;
+signals:
+ void packagingChanged();
private slots:
void debianDirChanged(const Utils::FileName &dir);
diff --git a/src/plugins/mercurial/annotationhighlighter.h b/src/plugins/mercurial/annotationhighlighter.h
index 81f25b231f..310596554d 100644
--- a/src/plugins/mercurial/annotationhighlighter.h
+++ b/src/plugins/mercurial/annotationhighlighter.h
@@ -43,7 +43,7 @@ public:
QTextDocument *document = 0);
private:
- virtual QString changeNumber(const QString &block) const;
+ QString changeNumber(const QString &block) const;
mutable QRegExp changeset;
};
diff --git a/src/plugins/mercurial/commiteditor.cpp b/src/plugins/mercurial/commiteditor.cpp
index cb2b9d804d..189afd4c43 100644
--- a/src/plugins/mercurial/commiteditor.cpp
+++ b/src/plugins/mercurial/commiteditor.cpp
@@ -69,7 +69,7 @@ void CommitEditor::setFields(const QFileInfo &repositoryRoot, const QString &bra
if (item.flags == QLatin1String("Untracked"))
shouldTrack.append(item.file);
else
- fileModel->addFile(item.file, item.flags, false);
+ fileModel->addFile(item.file, item.flags, VcsBase::Unchecked);
}
VcsBaseSubmitEditor::filterUntrackedFilesOfProject(repositoryRoot.absoluteFilePath(),
@@ -78,7 +78,7 @@ void CommitEditor::setFields(const QFileInfo &repositoryRoot, const QString &bra
foreach (const QString &track, shouldTrack) {
foreach (const VcsBaseClient::StatusItem &item, repoStatus) {
if (item.file == track)
- fileModel->addFile(item.file, item.flags, false);
+ fileModel->addFile(item.file, item.flags, VcsBase::Unchecked);
}
}
diff --git a/src/plugins/mercurial/constants.h b/src/plugins/mercurial/constants.h
index c90d97856f..060cdc39c1 100644
--- a/src/plugins/mercurial/constants.h
+++ b/src/plugins/mercurial/constants.h
@@ -42,7 +42,8 @@ const char CHANGESETID12[] = " ([a-f0-9]{12,12}) "; //match 12 hex chars and cap
const char CHANGESETID40[] = " ([a-f0-9]{40,40}) ";
const char CHANGEIDEXACT12[] = "[a-f0-9]{12,12}"; //match 12 hex chars a
const char CHANGEIDEXACT40[] = "[a-f0-9]{40,40}";
-const char DIFFIDENTIFIER[] = "^[-+]{3,3} [ab]{1,1}.*"; // match e.g. +++ b/filename
+// match diff header. e.g. +++ b/filename
+const char DIFFIDENTIFIER[] = "^(?:diff --git a/|[+-]{3} (?:/dev/null|[ab]/(.+$)))";
// Base editor parameters
const char COMMANDLOG_ID[] = "Mercurial Command Log Editor";
diff --git a/src/plugins/mercurial/mercurial.pro b/src/plugins/mercurial/mercurial.pro
index c63171089e..20a1f94ceb 100644
--- a/src/plugins/mercurial/mercurial.pro
+++ b/src/plugins/mercurial/mercurial.pro
@@ -2,7 +2,6 @@ TARGET = Mercurial
TEMPLATE = lib
include(../../qtcreatorplugin.pri)
include(mercurial_dependencies.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
SOURCES += mercurialplugin.cpp \
optionspage.cpp \
mercurialcontrol.cpp \
diff --git a/src/plugins/mercurial/mercurial.qbs b/src/plugins/mercurial/mercurial.qbs
index 3875ddd979..fcf9752e5f 100644
--- a/src/plugins/mercurial/mercurial.qbs
+++ b/src/plugins/mercurial/mercurial.qbs
@@ -12,46 +12,38 @@ QtcPlugin {
Depends { name: "VcsBase" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "mercurialplugin.cpp",
- "optionspage.cpp",
- "mercurialcontrol.cpp",
- "mercurialclient.cpp",
"annotationhighlighter.cpp",
- "mercurialeditor.cpp",
- "revertdialog.cpp",
- "srcdestdialog.cpp",
- "mercurialcommitwidget.cpp",
- "commiteditor.cpp",
- "clonewizardpage.cpp",
+ "annotationhighlighter.h",
"clonewizard.cpp",
- "mercurialsettings.cpp",
- "mercurialplugin.h",
+ "clonewizard.h",
+ "clonewizardpage.cpp",
+ "clonewizardpage.h",
+ "commiteditor.cpp",
+ "commiteditor.h",
"constants.h",
- "optionspage.h",
- "mercurialcontrol.h",
+ "mercurial.qrc",
+ "mercurialclient.cpp",
"mercurialclient.h",
- "annotationhighlighter.h",
- "mercurialeditor.h",
- "revertdialog.h",
- "srcdestdialog.h",
+ "mercurialcommitpanel.ui",
+ "mercurialcommitwidget.cpp",
"mercurialcommitwidget.h",
- "commiteditor.h",
- "clonewizardpage.h",
- "clonewizard.h",
+ "mercurialcontrol.cpp",
+ "mercurialcontrol.h",
+ "mercurialeditor.cpp",
+ "mercurialeditor.h",
+ "mercurialplugin.cpp",
+ "mercurialplugin.h",
+ "mercurialsettings.cpp",
"mercurialsettings.h",
+ "optionspage.cpp",
+ "optionspage.h",
"optionspage.ui",
+ "revertdialog.cpp",
+ "revertdialog.h",
"revertdialog.ui",
+ "srcdestdialog.cpp",
+ "srcdestdialog.h",
"srcdestdialog.ui",
- "mercurialcommitpanel.ui",
- "mercurial.qrc"
]
}
-
diff --git a/src/plugins/mercurial/mercurialclient.cpp b/src/plugins/mercurial/mercurialclient.cpp
index cb1d164c5b..ecb552c433 100644
--- a/src/plugins/mercurial/mercurialclient.cpp
+++ b/src/plugins/mercurial/mercurialclient.cpp
@@ -94,18 +94,16 @@ bool MercurialClient::synchronousClone(const QString &workingDir,
if (workingDirectory.exists()) {
// Let's make first init
QStringList arguments(QLatin1String("init"));
- if (!vcsFullySynchronousExec(workingDirectory.path(), arguments, &output)) {
+ if (!vcsFullySynchronousExec(workingDirectory.path(), arguments, &output))
return false;
- }
// Then pull remote repository
arguments.clear();
arguments << QLatin1String("pull") << dstLocation;
const Utils::SynchronousProcessResponse resp1 =
vcsSynchronousExec(workingDirectory.path(), arguments, flags);
- if (resp1.result != Utils::SynchronousProcessResponse::Finished) {
+ if (resp1.result != Utils::SynchronousProcessResponse::Finished)
return false;
- }
// By now, there is no hgrc file -> create it
Utils::FileSaver saver(workingDirectory.path() + QLatin1String("/.hg/hgrc"));
diff --git a/src/plugins/mercurial/mercurialclient.h b/src/plugins/mercurial/mercurialclient.h
index 80a3b4e5eb..89b106f88c 100644
--- a/src/plugins/mercurial/mercurialclient.h
+++ b/src/plugins/mercurial/mercurialclient.h
@@ -45,10 +45,10 @@ public:
MercurialSettings *settings() const;
- virtual bool synchronousClone(const QString &workingDir,
- const QString &srcLocation,
- const QString &dstLocation,
- const QStringList &extraOptions = QStringList());
+ bool synchronousClone(const QString &workingDir,
+ const QString &srcLocation,
+ const QString &dstLocation,
+ const QStringList &extraOptions = QStringList());
bool manifestSync(const QString &repository, const QString &filename);
QString branchQuerySync(const QString &repositoryRoot);
QStringList parentRevisionsSync(const QString &workingDirectory,
diff --git a/src/plugins/mercurial/mercurialcommitwidget.cpp b/src/plugins/mercurial/mercurialcommitwidget.cpp
index dcf17e57c9..4f2d17f508 100644
--- a/src/plugins/mercurial/mercurialcommitwidget.cpp
+++ b/src/plugins/mercurial/mercurialcommitwidget.cpp
@@ -61,7 +61,7 @@ class MercurialSubmitHighlighter : QSyntaxHighlighter
{
public:
explicit MercurialSubmitHighlighter(QTextEdit *parent);
- virtual void highlightBlock(const QString &text);
+ void highlightBlock(const QString &text);
private:
enum State { Header, Comment, Other };
@@ -114,7 +114,7 @@ void MercurialSubmitHighlighter::highlightBlock(const QString &text)
MercurialCommitWidget::MercurialCommitWidget(QWidget *parent) :
- Utils::SubmitEditorWidget(parent),
+ VcsBase::SubmitEditorWidget(parent),
mercurialCommitPanel(new QWidget)
{
mercurialCommitPanelUi.setupUi(mercurialCommitPanel);
diff --git a/src/plugins/mercurial/mercurialcommitwidget.h b/src/plugins/mercurial/mercurialcommitwidget.h
index f3ed74e872..e7d1b960ff 100644
--- a/src/plugins/mercurial/mercurialcommitwidget.h
+++ b/src/plugins/mercurial/mercurialcommitwidget.h
@@ -32,7 +32,7 @@
#include "ui_mercurialcommitpanel.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
namespace Mercurial {
namespace Internal {
@@ -41,7 +41,7 @@ namespace Internal {
Some extra fields have been added to the standard SubmitEditorWidget,
to help to conform to the commit style that is used by both git and Mercurial*/
-class MercurialCommitWidget : public Utils::SubmitEditorWidget
+class MercurialCommitWidget : public VcsBase::SubmitEditorWidget
{
public:
diff --git a/src/plugins/mercurial/mercurialcontrol.cpp b/src/plugins/mercurial/mercurialcontrol.cpp
index 24d2a35474..558021f93a 100644
--- a/src/plugins/mercurial/mercurialcontrol.cpp
+++ b/src/plugins/mercurial/mercurialcontrol.cpp
@@ -52,7 +52,7 @@ QString MercurialControl::displayName() const
Core::Id MercurialControl::id() const
{
- return VcsBase::Constants::VCS_ID_MERCURIAL;
+ return Core::Id(VcsBase::Constants::VCS_ID_MERCURIAL);
}
bool MercurialControl::managesDirectory(const QString &directory, QString *topLevel) const
diff --git a/src/plugins/mercurial/mercurialcontrol.h b/src/plugins/mercurial/mercurialcontrol.h
index 96b52a1f10..3fac104c04 100644
--- a/src/plugins/mercurial/mercurialcontrol.h
+++ b/src/plugins/mercurial/mercurialcontrol.h
@@ -67,7 +67,7 @@ public:
bool vcsRestoreSnapshot(const QString &topLevel, const QString &name);
bool vcsRemoveSnapshot(const QString &topLevel, const QString &name);
bool sccManaged(const QString &filename);
- virtual bool vcsAnnotate(const QString &file, int line);
+ bool vcsAnnotate(const QString &file, int line);
public slots:
// To be connected to the HgTask's success signal to emit the repository/
diff --git a/src/plugins/mercurial/mercurialeditor.cpp b/src/plugins/mercurial/mercurialeditor.cpp
index 31463bb5f9..59865be2ee 100644
--- a/src/plugins/mercurial/mercurialeditor.cpp
+++ b/src/plugins/mercurial/mercurialeditor.cpp
@@ -51,9 +51,10 @@ MercurialEditor::MercurialEditor(const VcsBase::VcsBaseEditorParameters *type, Q
exactIdentifier12(QLatin1String(Constants::CHANGEIDEXACT12)),
exactIdentifier40(QLatin1String(Constants::CHANGEIDEXACT40)),
changesetIdentifier12(QLatin1String(Constants::CHANGESETID12)),
- changesetIdentifier40(QLatin1String(Constants::CHANGESETID40)),
- diffIdentifier(QLatin1String(Constants::DIFFIDENTIFIER))
+ changesetIdentifier40(QLatin1String(Constants::CHANGESETID40))
{
+ setDiffFilePattern(QRegExp(QLatin1String(Constants::DIFFIDENTIFIER)));
+ setLogEntryPattern(QRegExp(QLatin1String("^changeset:\\s+(\\S+)$")));
setAnnotateRevisionTextFormat(tr("Annotate %1"));
setAnnotatePreviousRevisionTextFormat(tr("Annotate parent revision %1"));
}
@@ -88,33 +89,12 @@ QString MercurialEditor::changeUnderCursor(const QTextCursor &cursorIn) const
return QString();
}
-VcsBase::DiffHighlighter *MercurialEditor::createDiffHighlighter() const
-{
- return new VcsBase::DiffHighlighter(diffIdentifier);
-}
-
VcsBase::BaseAnnotationHighlighter *MercurialEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new MercurialAnnotationHighlighter(changes, bg);
}
-QString MercurialEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
-{
- // git-compatible format: check for "+++ b/src/plugins/git/giteditor.cpp" (blame and diff)
- // Go back chunks.
- const QString newFileIndicator = QLatin1String("+++ b/");
- for (QTextBlock block = inBlock; block.isValid(); block = block.previous()) {
- QString diffFileName = block.text();
- if (diffFileName.startsWith(newFileIndicator)) {
- diffFileName.remove(0, newFileIndicator.size());
- return findDiffFile(diffFileName);
- }
-
- }
- return QString();
-}
-
QString MercurialEditor::decorateVersion(const QString &revision) const
{
const QFileInfo fi(source());
diff --git a/src/plugins/mercurial/mercurialeditor.h b/src/plugins/mercurial/mercurialeditor.h
index ee1ec0da44..a2ca6dce8b 100644
--- a/src/plugins/mercurial/mercurialeditor.h
+++ b/src/plugins/mercurial/mercurialeditor.h
@@ -44,19 +44,16 @@ public:
explicit MercurialEditor(const VcsBase::VcsBaseEditorParameters *type, QWidget *parent);
private:
- virtual QSet<QString> annotationChanges() const;
- virtual QString changeUnderCursor(const QTextCursor &cursor) const;
- virtual VcsBase::DiffHighlighter *createDiffHighlighter() const;
- virtual VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- virtual QString fileNameFromDiffSpecification(const QTextBlock &diffFileSpec) const;
- virtual QString decorateVersion(const QString &revision) const;
- virtual QStringList annotationPreviousVersions(const QString &revision) const;
+ QSet<QString> annotationChanges() const;
+ QString changeUnderCursor(const QTextCursor &cursor) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ QString decorateVersion(const QString &revision) const;
+ QStringList annotationPreviousVersions(const QString &revision) const;
mutable QRegExp exactIdentifier12;
mutable QRegExp exactIdentifier40;
mutable QRegExp changesetIdentifier12;
const QRegExp changesetIdentifier40;
- const QRegExp diffIdentifier;
};
} // namespace Internal
diff --git a/src/plugins/mercurial/mercurialplugin.cpp b/src/plugins/mercurial/mercurialplugin.cpp
index 90fc93e476..f89b755a4f 100644
--- a/src/plugins/mercurial/mercurialplugin.cpp
+++ b/src/plugins/mercurial/mercurialplugin.cpp
@@ -108,7 +108,8 @@ static const VcsBaseSubmitEditorParameters submitEditorParameters = {
Constants::COMMITMIMETYPE,
Constants::COMMIT_ID,
Constants::COMMIT_DISPLAY_NAME,
- Constants::COMMIT_ID
+ Constants::COMMIT_ID,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
MercurialPlugin *MercurialPlugin::m_instance = 0;
@@ -161,7 +162,7 @@ bool MercurialPlugin::initialize(const QStringList & /* arguments */, QString *
addAutoReleasedObject(new CloneWizard);
const QString prefix = QLatin1String("hg");
- m_commandLocator = new Locator::CommandLocator(QLatin1String("Mercurial"), prefix, prefix);
+ m_commandLocator = new Locator::CommandLocator("Mercurial", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
createMenu();
@@ -684,4 +685,62 @@ void MercurialPlugin::updateActions(VcsBasePlugin::ActionState as)
repoAction->setEnabled(repoEnabled);
}
+#ifdef WITH_TESTS
+#include <QTest>
+
+void MercurialPlugin::testDiffFileResolving_data()
+{
+ QTest::addColumn<QByteArray>("header");
+ QTest::addColumn<QByteArray>("fileName");
+
+ QTest::newRow("New") << QByteArray(
+ "diff --git a/src/plugins/mercurial/mercurialeditor.cpp b/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "new file mode 100644\n"
+ "--- /dev/null\n"
+ "+++ b/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "@@ -0,0 +1,112 @@\n\n")
+ << QByteArray("src/plugins/mercurial/mercurialeditor.cpp");
+ QTest::newRow("Deleted") << QByteArray(
+ "diff --git a/src/plugins/mercurial/mercurialeditor.cpp b/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "deleted file mode 100644\n"
+ "--- a/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "+++ /dev/null\n"
+ "@@ -1,112 +0,0 @@\n\n")
+ << QByteArray("src/plugins/mercurial/mercurialeditor.cpp");
+ QTest::newRow("Normal") << QByteArray(
+ "diff --git a/src/plugins/mercurial/mercurialeditor.cpp b/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "--- a/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "+++ b/src/plugins/mercurial/mercurialeditor.cpp\n"
+ "@@ -49,6 +49,8 @@\n\n")
+ << QByteArray("src/plugins/mercurial/mercurialeditor.cpp");
+}
+
+void MercurialPlugin::testDiffFileResolving()
+{
+ MercurialEditor editor(editorParameters + 3, 0);
+ editor.testDiffFileResolving();
+}
+
+void MercurialPlugin::testLogResolving()
+{
+ QByteArray data(
+ "changeset: 18473:692cbda1eb50\n"
+ "branch: stable\n"
+ "bookmark: @\n"
+ "tag: tip\n"
+ "user: FUJIWARA Katsunori <foozy@lares.dti.ne.jp>\n"
+ "date: Wed Jan 23 22:52:55 2013 +0900\n"
+ "summary: revset: evaluate sub expressions correctly (issue3775)\n"
+ "\n"
+ "changeset: 18472:37100f30590f\n"
+ "branch: stable\n"
+ "user: Pierre-Yves David <pierre-yves.david@ens-lyon.org>\n"
+ "date: Sat Jan 19 04:08:16 2013 +0100\n"
+ "summary: test-rebase: add another test for rebase with multiple roots\n"
+ );
+ MercurialEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data, "18473:692cbda1eb50", "18472:37100f30590f");
+}
+#endif
+
Q_EXPORT_PLUGIN(MercurialPlugin)
diff --git a/src/plugins/mercurial/mercurialplugin.h b/src/plugins/mercurial/mercurialplugin.h
index 81b1d9c20d..a6c1265969 100644
--- a/src/plugins/mercurial/mercurialplugin.h
+++ b/src/plugins/mercurial/mercurialplugin.h
@@ -68,7 +68,7 @@ class MercurialPlugin : public VcsBase::VcsBasePlugin
public:
MercurialPlugin();
- virtual ~MercurialPlugin();
+ ~MercurialPlugin();
bool initialize(const QStringList &arguments, QString *errorMessage);
static MercurialPlugin *instance() { return m_instance; }
@@ -103,6 +103,11 @@ private slots:
void showCommitWidget(const QList<VcsBase::VcsBaseClient::StatusItem> &status);
void commitFromEditor();
void diffFromEditorSelected(const QStringList &files);
+#ifdef WITH_TESTS
+ void testDiffFileResolving_data();
+ void testDiffFileResolving();
+ void testLogResolving();
+#endif
//TODO implement
/* //repository management action slots
@@ -119,8 +124,8 @@ private slots:
void serve();*/
protected:
- virtual void updateActions(VcsBase::VcsBasePlugin::ActionState);
- virtual bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
+ void updateActions(VcsBase::VcsBasePlugin::ActionState);
+ bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
private:
void createMenu();
diff --git a/src/plugins/mercurial/optionspage.cpp b/src/plugins/mercurial/optionspage.cpp
index dc65415299..8f6087ab94 100644
--- a/src/plugins/mercurial/optionspage.cpp
+++ b/src/plugins/mercurial/optionspage.cpp
@@ -91,7 +91,7 @@ QString OptionsPageWidget::searchKeywords() const
OptionsPage::OptionsPage()
{
- setId(QLatin1String(VcsBase::Constants::VCS_ID_MERCURIAL));
+ setId(VcsBase::Constants::VCS_ID_MERCURIAL);
setDisplayName(tr("Mercurial"));
}
diff --git a/src/plugins/mercurial/optionspage.h b/src/plugins/mercurial/optionspage.h
index fe74d47ad0..ff55161a7c 100644
--- a/src/plugins/mercurial/optionspage.h
+++ b/src/plugins/mercurial/optionspage.h
@@ -64,8 +64,6 @@ class OptionsPage : public VcsBase::VcsBaseOptionsPage
public:
OptionsPage();
- QString id() const;
- QString displayName() const;
QWidget *createPage(QWidget *parent);
void apply();
diff --git a/src/plugins/perforce/annotationhighlighter.h b/src/plugins/perforce/annotationhighlighter.h
index 29eabc654b..4c47fd48b3 100644
--- a/src/plugins/perforce/annotationhighlighter.h
+++ b/src/plugins/perforce/annotationhighlighter.h
@@ -45,7 +45,7 @@ public:
QTextDocument *document = 0);
private:
- virtual QString changeNumber(const QString &block) const;
+ QString changeNumber(const QString &block) const;
const QChar m_colon;
};
diff --git a/src/plugins/perforce/perforce.pro b/src/plugins/perforce/perforce.pro
index 403f07257d..7754b7fae5 100644
--- a/src/plugins/perforce/perforce.pro
+++ b/src/plugins/perforce/perforce.pro
@@ -4,8 +4,6 @@ TARGET = Perforce
include(../../qtcreatorplugin.pri)
include(perforce_dependencies.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
-
HEADERS += \
perforceplugin.h \
perforcechecker.h \
diff --git a/src/plugins/perforce/perforce.qbs b/src/plugins/perforce/perforce.qbs
index 9c4c3d881b..ee31c90959 100644
--- a/src/plugins/perforce/perforce.qbs
+++ b/src/plugins/perforce/perforce.qbs
@@ -12,42 +12,34 @@ QtcPlugin {
Depends { name: "VcsBase" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "perforceplugin.h",
- "perforcechecker.h",
- "settingspage.h",
- "perforceeditor.h",
+ "annotationhighlighter.cpp",
+ "annotationhighlighter.h",
+ "changenumberdialog.cpp",
"changenumberdialog.h",
- "perforcesubmiteditor.h",
+ "changenumberdialog.ui",
+ "pendingchangesdialog.cpp",
"pendingchangesdialog.h",
- "perforceconstants.h",
- "perforceversioncontrol.h",
- "perforcesettings.h",
- "annotationhighlighter.h",
- "perforcesubmiteditorwidget.h",
- "perforceplugin.cpp",
+ "pendingchangesdialog.ui",
+ "perforce.qrc",
"perforcechecker.cpp",
- "settingspage.cpp",
+ "perforcechecker.h",
+ "perforceconstants.h",
"perforceeditor.cpp",
- "changenumberdialog.cpp",
- "perforcesubmiteditor.cpp",
- "pendingchangesdialog.cpp",
- "perforceversioncontrol.cpp",
+ "perforceeditor.h",
+ "perforceplugin.cpp",
+ "perforceplugin.h",
"perforcesettings.cpp",
- "annotationhighlighter.cpp",
+ "perforcesettings.h",
+ "perforcesubmiteditor.cpp",
+ "perforcesubmiteditor.h",
"perforcesubmiteditorwidget.cpp",
+ "perforcesubmiteditorwidget.h",
+ "perforceversioncontrol.cpp",
+ "perforceversioncontrol.h",
+ "settingspage.cpp",
+ "settingspage.h",
"settingspage.ui",
- "changenumberdialog.ui",
- "pendingchangesdialog.ui",
"submitpanel.ui",
- "perforce.qrc"
]
}
-
diff --git a/src/plugins/perforce/perforcechecker.h b/src/plugins/perforce/perforcechecker.h
index ee43010e3e..e466250c27 100644
--- a/src/plugins/perforce/perforcechecker.h
+++ b/src/plugins/perforce/perforcechecker.h
@@ -45,7 +45,7 @@ class PerforceChecker : public QObject
Q_OBJECT
public:
explicit PerforceChecker(QObject *parent = 0);
- virtual ~PerforceChecker();
+ ~PerforceChecker();
public slots:
void start(const QString &binary,
diff --git a/src/plugins/perforce/perforceeditor.cpp b/src/plugins/perforce/perforceeditor.cpp
index a6d68fafd9..7a31f5af42 100644
--- a/src/plugins/perforce/perforceeditor.cpp
+++ b/src/plugins/perforce/perforceeditor.cpp
@@ -63,6 +63,11 @@ PerforceEditor::PerforceEditor(const VcsBase::VcsBaseEditorParameters *type,
m_plugin(PerforcePlugin::perforcePluginInstance())
{
QTC_CHECK(m_changeNumberPattern.isValid());
+ // Diff format:
+ // 1) "==== //depot/.../mainwindow.cpp#2 - /depot/.../mainwindow.cpp ====" (created by p4 diff)
+ // 2) "==== //depot/.../mainwindow.cpp#15 (text) ====" (created by p4 describe)
+ setDiffFilePattern(QRegExp(QLatin1String("^==== (.+)#\\d")));
+ setLogEntryPattern(QRegExp(QLatin1String("^... #\\d change (\\d+) ")));
setAnnotateRevisionTextFormat(tr("Annotate change list \"%1\""));
if (Perforce::Constants::debug)
qDebug() << "PerforceEditor::PerforceEditor" << type->type << type->id;
@@ -103,58 +108,19 @@ QString PerforceEditor::changeUnderCursor(const QTextCursor &c) const
return m_changeNumberPattern.exactMatch(change) ? change : QString();
}
-VcsBase::DiffHighlighter *PerforceEditor::createDiffHighlighter() const
-{
- const QRegExp filePattern(QLatin1String("^====.*"));
- return new VcsBase::DiffHighlighter(filePattern);
-}
-
VcsBase::BaseAnnotationHighlighter *PerforceEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new PerforceAnnotationHighlighter(changes, bg);
}
-QString PerforceEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
+QString PerforceEditor::findDiffFile(const QString &f) const
{
QString errorMessage;
- const QString diffIndicator = QLatin1String("==== ");
- const QString diffEndIndicator = QLatin1String(" ====");
- // Go back chunks. Note that for 'describe', an extra, empty line
- // occurs.
- for (QTextBlock block = inBlock; block.isValid(); block = block.previous()) {
- QString diffFileName = block.text();
- if (diffFileName.startsWith(diffIndicator) && diffFileName.endsWith(diffEndIndicator)) {
- // Split:
- // 1) "==== //depot/.../mainwindow.cpp#2 - /depot/.../mainwindow.cpp ===="
- // (as created by p4 diff) or
- // 2) "==== //depot/.../mainwindow.cpp#15 (text) ===="
- // (as created by p4 describe).
- diffFileName.remove(0, diffIndicator.size());
- diffFileName.truncate(diffFileName.size() - diffEndIndicator.size());
- const int separatorPos = diffFileName.indexOf(QLatin1String(" - "));
- if (separatorPos == -1) {
- // ==== depot path (text) ==== (p4 describe)
- const int blankPos = diffFileName.indexOf(QLatin1Char(' '));
- if (blankPos == -1)
- return QString();
- diffFileName.truncate(blankPos);
- } else {
- // ==== depot path - local path ==== (p4 diff)
- diffFileName.truncate(separatorPos);
- }
- // Split off revision "#4"
- const int revisionPos = diffFileName.lastIndexOf(QLatin1Char('#'));
- if (revisionPos != -1 && revisionPos < diffFileName.length() - 1)
- diffFileName.truncate(revisionPos);
- // Ask plugin to map back
- const QString fileName = m_plugin->fileNameFromPerforceName(diffFileName.trimmed(), false, &errorMessage);
- if (fileName.isEmpty())
- qWarning("%s", qPrintable(errorMessage));
- return fileName;
- }
- }
- return QString();
+ const QString fileName = m_plugin->fileNameFromPerforceName(f.trimmed(), false, &errorMessage);
+ if (fileName.isEmpty())
+ qWarning("%s", qPrintable(errorMessage));
+ return fileName;
}
QStringList PerforceEditor::annotationPreviousVersions(const QString &v) const
diff --git a/src/plugins/perforce/perforceeditor.h b/src/plugins/perforce/perforceeditor.h
index 7827315d2b..915d6ee4cd 100644
--- a/src/plugins/perforce/perforceeditor.h
+++ b/src/plugins/perforce/perforceeditor.h
@@ -48,12 +48,11 @@ public:
QWidget *parent);
private:
- virtual QSet<QString> annotationChanges() const;
- virtual QString changeUnderCursor(const QTextCursor &) const;
- virtual VcsBase::DiffHighlighter *createDiffHighlighter() const;
- virtual VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- virtual QString fileNameFromDiffSpecification(const QTextBlock &diffFileName) const;
- virtual QStringList annotationPreviousVersions(const QString &v) const;
+ QSet<QString> annotationChanges() const;
+ QString changeUnderCursor(const QTextCursor &) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ QString findDiffFile(const QString &f) const;
+ QStringList annotationPreviousVersions(const QString &v) const;
mutable QRegExp m_changeNumberPattern;
PerforcePlugin *m_plugin;
diff --git a/src/plugins/perforce/perforceplugin.cpp b/src/plugins/perforce/perforceplugin.cpp
index 3ad29dd1c8..9790ef20b8 100644
--- a/src/plugins/perforce/perforceplugin.cpp
+++ b/src/plugins/perforce/perforceplugin.cpp
@@ -108,7 +108,7 @@ static inline const VcsBase::VcsBaseEditorParameters *findType(int ie)
static inline QString debugCodec(const QTextCodec *c)
{
- return c ? QString::fromAscii(c->name()) : QString::fromAscii("Null codec");
+ return c ? QString::fromLatin1(c->name()) : QString::fromLatin1("Null codec");
}
// Ensure adding "..." to relative paths which is p4's convention
@@ -211,7 +211,8 @@ static const VcsBase::VcsBaseSubmitEditorParameters submitParameters = {
Perforce::Constants::SUBMIT_MIMETYPE,
Perforce::Constants::PERFORCE_SUBMIT_EDITOR_ID,
Perforce::Constants::PERFORCE_SUBMIT_EDITOR_DISPLAY_NAME,
- Perforce::Constants::PERFORCESUBMITEDITOR_CONTEXT
+ Perforce::Constants::PERFORCESUBMITEDITOR_CONTEXT,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *errorMessage)
@@ -238,7 +239,7 @@ bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *er
addAutoReleasedObject(new PerforceEditorFactory(editorParameters + i, this, describeSlot));
const QString prefix = QLatin1String("p4");
- m_commandLocator = new Locator::CommandLocator(QLatin1String("Perforce"), prefix, prefix);
+ m_commandLocator = new Locator::CommandLocator("Perforce", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
Core::ActionContainer *mtools =
@@ -561,7 +562,7 @@ void PerforcePlugin::updateCheckout(const QString &workingDir, const QStringList
perforceVersionControl()->emitRepositoryChanged(workingDir);
} else {
const QChar slash = QLatin1Char('/');
- foreach(const QString &dir, dirs)
+ foreach (const QString &dir, dirs)
perforceVersionControl()->emitRepositoryChanged(workingDir + slash + dir);
}
}
@@ -584,11 +585,10 @@ void PerforcePlugin::printOpenedFileList()
const int delimiterPos = line.indexOf(delimiter);
if (delimiterPos > 0)
mapped = fileNameFromPerforceName(line.left(delimiterPos), true, &errorMessage);
- if (mapped.isEmpty()) {
+ if (mapped.isEmpty())
outWin->appendSilently(line);
- } else {
+ else
outWin->appendSilently(mapped + QLatin1Char(' ') + line.mid(delimiterPos));
- }
}
outWin->popup(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus);
}
@@ -623,7 +623,7 @@ void PerforcePlugin::startSubmitProject()
Utils::TempFileSaver saver;
saver.setAutoRemove(false);
- saver.write(result.stdOut.toAscii());
+ saver.write(result.stdOut.toLatin1());
if (!saver.finalize()) {
VcsBase::VcsBaseOutputWindow::instance()->appendError(saver.errorString());
cleanCommitMessageFile();
@@ -722,11 +722,10 @@ void PerforcePlugin::annotate(const QString &workingDir,
const QString source = VcsBase::VcsBaseEditorWidget::getSource(workingDir, files);
QStringList args;
args << QLatin1String("annotate") << QLatin1String("-cqi");
- if (changeList.isEmpty()) {
+ if (changeList.isEmpty())
args << fileName;
- } else {
+ else
args << (fileName + QLatin1Char('@') + changeList);
- }
const PerforceResponse result = runP4Cmd(workingDir, args,
CommandToWindow|StdErrToWindow|ErrorToWindow,
QStringList(), QByteArray(), codec);
@@ -797,7 +796,7 @@ void PerforcePlugin::updateActions(VcsBase::VcsBasePlugin::ActionState as)
{
if (!enableMenuAction(as, m_menuAction)) {
m_commandLocator->setEnabled(false);
- return;
+ return;
}
const bool hasTopLevel = currentState().hasTopLevel();
m_commandLocator->setEnabled(hasTopLevel);
@@ -833,11 +832,10 @@ bool PerforcePlugin::managesDirectory(const QString &directory, QString *topLeve
{
const bool rc = managesDirectoryFstat(directory);
if (topLevel) {
- if (rc) {
+ if (rc)
*topLevel = m_settings.topLevelSymLinkTarget();
- } else {
+ else
topLevel->clear();
- }
}
return rc;
}
@@ -864,7 +862,7 @@ bool PerforcePlugin::managesDirectoryFstat(const QString &directory)
RunFullySynchronous);
managed = result.stdOut.contains(QLatin1String("depotFile"))
|| result.stdErr.contains(QLatin1String("... - no such file(s)"));
- } while(false);
+ } while (false);
m_managedDirectoryCache.insert(directory, managed);
return managed;
@@ -1172,7 +1170,7 @@ Core::IEditor *PerforcePlugin::showOutputInEditor(const QString &title, const QS
{
const VcsBase::VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
- const Core::Id id(params->id);
+ const Core::Id id = Core::Id(QByteArray(params->id));
if (Perforce::Constants::debug)
qDebug() << "PerforcePlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
@@ -1260,11 +1258,10 @@ void PerforcePlugin::p4Diff(const PerforceDiffParameters &p)
if (!p.diffArguments.isEmpty()) // -duw..
args << (QLatin1String("-d") + p.diffArguments.join(QString()));
QStringList extraArgs;
- if (p.files.size() > 1) {
+ if (p.files.size() > 1)
extraArgs = p.files;
- } else {
+ else
args.append(p.files);
- }
const unsigned flags = CommandToWindow|StdErrToWindow|ErrorToWindow|OverrideDiffEnvironment;
const PerforceResponse result = runP4Cmd(p.workingDir, args, flags,
extraArgs, QByteArray(), codec);
@@ -1529,6 +1526,23 @@ void PerforcePlugin::getTopLevel()
checker->start(m_settings.p4BinaryPath(), m_settings.commonP4Arguments(QString()), 30000);
}
+#ifdef WITH_TESTS
+void PerforcePlugin::testLogResolving()
+{
+ // Source: http://mail.opensolaris.org/pipermail/opengrok-discuss/2008-October/001668.html
+ QByteArray data(
+ "... #4 change 12345 edit on 2013/01/28 by User at UserWorkspaceName(text)\n"
+ "\n"
+ " Comment\n"
+ "... #3 change 12344 edit on 2013/01/27 by User at UserWorkspaceName(text)\n"
+ "\n"
+ " Comment\n"
+ );
+ PerforceEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data, "12345", "12344");
+}
+#endif
+
}
}
diff --git a/src/plugins/perforce/perforceplugin.h b/src/plugins/perforce/perforceplugin.h
index 5c16ed397a..bfde3f71a2 100644
--- a/src/plugins/perforce/perforceplugin.h
+++ b/src/plugins/perforce/perforceplugin.h
@@ -137,9 +137,12 @@ private slots:
void slotTopLevelFound(const QString &);
void slotTopLevelFailed(const QString &);
+#ifdef WITH_TESTS
+ void testLogResolving();
+#endif
protected:
- virtual void updateActions(VcsBase::VcsBasePlugin::ActionState);
- virtual bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
+ void updateActions(VcsBase::VcsBasePlugin::ActionState);
+ bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
private:
diff --git a/src/plugins/perforce/perforcesettings.cpp b/src/plugins/perforce/perforcesettings.cpp
index 1b9b7b048e..8579fa2f80 100644
--- a/src/plugins/perforce/perforcesettings.cpp
+++ b/src/plugins/perforce/perforcesettings.cpp
@@ -33,6 +33,7 @@
#include <utils/qtcassert.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QDebug>
#include <QSettings>
@@ -56,12 +57,7 @@ enum { defaultTimeOutS = 30, defaultLogCount = 1000 };
static QString defaultCommand()
{
- QString rc;
- rc = QLatin1String("p4");
-#if defined(Q_OS_WIN32)
- rc.append(QLatin1String(".exe"));
-#endif
- return rc;
+ return QLatin1String("p4" QTC_HOST_EXE_SUFFIX);
}
namespace Perforce {
diff --git a/src/plugins/perforce/perforcesubmiteditor.cpp b/src/plugins/perforce/perforcesubmiteditor.cpp
index c6715a13b3..c72bac449c 100644
--- a/src/plugins/perforce/perforcesubmiteditor.cpp
+++ b/src/plugins/perforce/perforcesubmiteditor.cpp
@@ -114,7 +114,7 @@ bool PerforceSubmitEditor::parseText(QString text)
void PerforceSubmitEditor::restrictToProjectFiles(const QStringList &knownProjectFiles)
{
- m_fileModel->filter(knownProjectFiles, fileNameColumn());
+ m_fileModel->filterFiles(knownProjectFiles);
}
void PerforceSubmitEditor::updateFields()
diff --git a/src/plugins/perforce/perforcesubmiteditorwidget.cpp b/src/plugins/perforce/perforcesubmiteditorwidget.cpp
index 0c49bf9eb0..be1ef9c2bb 100644
--- a/src/plugins/perforce/perforcesubmiteditorwidget.cpp
+++ b/src/plugins/perforce/perforcesubmiteditorwidget.cpp
@@ -33,7 +33,7 @@ namespace Perforce {
namespace Internal {
PerforceSubmitEditorWidget::PerforceSubmitEditorWidget(QWidget *parent) :
- Utils::SubmitEditorWidget(parent),
+ VcsBase::SubmitEditorWidget(parent),
m_submitPanel(new QGroupBox)
{
m_submitPanelUi.setupUi(m_submitPanel);
diff --git a/src/plugins/perforce/perforcesubmiteditorwidget.h b/src/plugins/perforce/perforcesubmiteditorwidget.h
index baada4288e..f0acd1c897 100644
--- a/src/plugins/perforce/perforcesubmiteditorwidget.h
+++ b/src/plugins/perforce/perforcesubmiteditorwidget.h
@@ -31,14 +31,14 @@
#define PERFORCESUBMITEDITORWIDGET_H
#include "ui_submitpanel.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
namespace Perforce {
namespace Internal {
/* Submit editor widget with additional information pane
* at the top. */
-class PerforceSubmitEditorWidget : public Utils::SubmitEditorWidget
+class PerforceSubmitEditorWidget : public VcsBase::SubmitEditorWidget
{
public:
diff --git a/src/plugins/perforce/perforceversioncontrol.cpp b/src/plugins/perforce/perforceversioncontrol.cpp
index a24dac0dcb..6d11996036 100644
--- a/src/plugins/perforce/perforceversioncontrol.cpp
+++ b/src/plugins/perforce/perforceversioncontrol.cpp
@@ -52,7 +52,7 @@ QString PerforceVersionControl::displayName() const
Core::Id PerforceVersionControl::id() const
{
- return VcsBase::Constants::VCS_ID_PERFORCE;
+ return Core::Id(VcsBase::Constants::VCS_ID_PERFORCE);
}
bool PerforceVersionControl::isConfigured() const
diff --git a/src/plugins/perforce/settingspage.cpp b/src/plugins/perforce/settingspage.cpp
index 0007ccabbd..b065e9a83b 100644
--- a/src/plugins/perforce/settingspage.cpp
+++ b/src/plugins/perforce/settingspage.cpp
@@ -138,7 +138,7 @@ QString SettingsPageWidget::searchKeywords() const
SettingsPage::SettingsPage()
{
- setId(QLatin1String(VcsBase::Constants::VCS_ID_PERFORCE));
+ setId(VcsBase::Constants::VCS_ID_PERFORCE);
setDisplayName(tr("Perforce"));
}
diff --git a/src/plugins/plugins.pro b/src/plugins/plugins.pro
index 7e6268b708..e82b02806f 100644
--- a/src/plugins/plugins.pro
+++ b/src/plugins/plugins.pro
@@ -163,7 +163,7 @@ plugin_remotelinux.subdir = remotelinux
plugin_remotelinux.depends += plugin_coreplugin
plugin_remotelinux.depends += plugin_debugger
plugin_remotelinux.depends += plugin_projectexplorer
-plugin_remotelinux.depends += plugin_qt4projectmanager
+plugin_remotelinux.depends += plugin_qtsupport
plugin_android.subdir = android
plugin_android.depends = plugin_coreplugin
@@ -173,6 +173,7 @@ plugin_android.depends += plugin_qt4projectmanager
plugin_madde.subdir = madde
plugin_madde.depends += plugin_remotelinux
+plugin_madde.depends += plugin_qt4projectmanager
plugin_locator.subdir = locator
plugin_locator.depends = plugin_coreplugin
@@ -329,6 +330,7 @@ plugin_qnx.subdir = qnx
plugin_qnx.depends = plugin_remotelinux
plugin_qnx.depends += plugin_qt4projectmanager
plugin_qnx.depends += plugin_coreplugin
+plugin_qnx.depends += plugin_texteditor
plugin_clearcase.subdir = clearcase
plugin_clearcase.depends = plugin_vcsbase
diff --git a/src/plugins/projectexplorer/abi.cpp b/src/plugins/projectexplorer/abi.cpp
index ab30cef70b..5181cfc097 100644
--- a/src/plugins/projectexplorer/abi.cpp
+++ b/src/plugins/projectexplorer/abi.cpp
@@ -699,7 +699,7 @@ QList<Abi> Abi::abisOfBinary(const Utils::FileName &path)
quint64 fileNameOffset = 0;
if (fileName.startsWith(QLatin1String("#1/")))
fileNameOffset = fileName.mid(3).toInt();
- const QString fileLength = QString::fromAscii(data.mid(48, 10));
+ const QString fileLength = QString::fromLatin1(data.mid(48, 10));
int toSkip = 60 + fileNameOffset;
offset += fileLength.toInt() + 60 /* header */;
diff --git a/src/plugins/projectexplorer/abiwidget.cpp b/src/plugins/projectexplorer/abiwidget.cpp
index a5316e4c85..4d5c588bc9 100644
--- a/src/plugins/projectexplorer/abiwidget.cpp
+++ b/src/plugins/projectexplorer/abiwidget.cpp
@@ -157,6 +157,7 @@ void AbiWidget::setAbis(const QList<Abi> &abiList, const Abi &current)
d->m_abi->setCurrentIndex(i + 1);
}
+ d->m_abi->setVisible(!abiList.isEmpty());
if (d->m_abi->currentIndex() == 0) {
if (!current.isValid() && !abiList.isEmpty())
d->m_abi->setCurrentIndex(1); // default to the first Abi if none is selected.
diff --git a/src/plugins/projectexplorer/abstractmsvctoolchain.cpp b/src/plugins/projectexplorer/abstractmsvctoolchain.cpp
index 9bf320cee7..64e53c3dc6 100644
--- a/src/plugins/projectexplorer/abstractmsvctoolchain.cpp
+++ b/src/plugins/projectexplorer/abstractmsvctoolchain.cpp
@@ -105,8 +105,9 @@ ToolChain::CompilerFlags AbstractMsvcToolChain::compilerFlags(const QStringList
}
}
-QList<HeaderPath> AbstractMsvcToolChain::systemHeaderPaths(const Utils::FileName &sysRoot) const
+QList<HeaderPath> AbstractMsvcToolChain::systemHeaderPaths(const QStringList &cxxflags, const Utils::FileName &sysRoot) const
{
+ Q_UNUSED(cxxflags);
Q_UNUSED(sysRoot);
if (m_headerPaths.isEmpty()) {
Utils::Environment env(m_lastEnvironment);
@@ -154,7 +155,7 @@ Utils::FileName AbstractMsvcToolChain::compilerCommand() const
{
Utils::Environment env = Utils::Environment::systemEnvironment();
addToEnvironment(env);
- return Utils::FileName::fromString(env.searchInPath("cl.exe"));
+ return Utils::FileName::fromString(env.searchInPath(QLatin1String("cl.exe")));
}
IOutputParser *AbstractMsvcToolChain::outputParser() const
@@ -212,9 +213,8 @@ bool AbstractMsvcToolChain::generateEnvironmentSettings(Utils::Environment &env,
call += ' ';
call += batchArgs.toLocal8Bit();
}
- call += "\r\n";
+ saver.write(call + "\r\n");
- saver.write(call);
const QByteArray redirect = "set > " + Utils::QtcProcess::quoteArg(
QDir::toNativeSeparators(tempOutFile)).toLocal8Bit() + "\r\n";
saver.write(redirect);
@@ -250,6 +250,10 @@ bool AbstractMsvcToolChain::generateEnvironmentSettings(Utils::Environment &env,
Utils::SynchronousProcess::stopProcess(run);
return false;
}
+ // The SDK/MSVC scripts do not return exit codes != 0. Check on stdout.
+ const QByteArray stdOut = run.readAllStandardOutput();
+ if (!stdOut.isEmpty() && (stdOut.contains("Unknown") || stdOut.contains("Error")))
+ qWarning("%s: '%s' reports:\n%s", Q_FUNC_INFO, call.constData(), stdOut.constData());
//
// Now parse the file to get the environment settings
diff --git a/src/plugins/projectexplorer/abstractmsvctoolchain.h b/src/plugins/projectexplorer/abstractmsvctoolchain.h
index 7c4aa54aaf..ca1336d785 100644
--- a/src/plugins/projectexplorer/abstractmsvctoolchain.h
+++ b/src/plugins/projectexplorer/abstractmsvctoolchain.h
@@ -50,7 +50,7 @@ public:
QByteArray predefinedMacros(const QStringList &cxxflags) const;
CompilerFlags compilerFlags(const QStringList &cxxflags) const;
- QList<HeaderPath> systemHeaderPaths(const Utils::FileName &sysRoot) const;
+ QList<HeaderPath> systemHeaderPaths(const QStringList &cxxflags, const Utils::FileName &sysRoot) const;
void addToEnvironment(Utils::Environment &env) const;
QString makeCommand(const Utils::Environment &environment) const;
diff --git a/src/plugins/projectexplorer/abstractprocessstep.cpp b/src/plugins/projectexplorer/abstractprocessstep.cpp
index 59ee4f5b3d..ad6ee8c24c 100644
--- a/src/plugins/projectexplorer/abstractprocessstep.cpp
+++ b/src/plugins/projectexplorer/abstractprocessstep.cpp
@@ -389,7 +389,7 @@ void AbstractProcessStep::taskAdded(const ProjectExplorer::Task &task)
filePath.remove(0, 3);
int count = 0;
QString possibleFilePath;
- foreach(const QFileInfo &fi, possibleFiles) {
+ foreach (const QFileInfo &fi, possibleFiles) {
if (fi.filePath().endsWith(filePath)) {
possibleFilePath = fi.filePath();
++count;
diff --git a/src/plugins/projectexplorer/abstractprocessstep.h b/src/plugins/projectexplorer/abstractprocessstep.h
index b7cfab9834..998fda3ab9 100644
--- a/src/plugins/projectexplorer/abstractprocessstep.h
+++ b/src/plugins/projectexplorer/abstractprocessstep.h
@@ -58,9 +58,6 @@ public:
virtual bool init();
virtual void run(QFutureInterface<bool> &);
- virtual BuildStepConfigWidget *createConfigWidget() = 0;
- virtual bool immutable() const = 0;
-
ProcessParameters *processParameters() { return &m_param; }
bool ignoreReturnValue();
diff --git a/src/plugins/projectexplorer/allprojectsfilter.cpp b/src/plugins/projectexplorer/allprojectsfilter.cpp
index abb832271b..b65fb5bdc5 100644
--- a/src/plugins/projectexplorer/allprojectsfilter.cpp
+++ b/src/plugins/projectexplorer/allprojectsfilter.cpp
@@ -42,10 +42,14 @@ using namespace ProjectExplorer::Internal;
AllProjectsFilter::AllProjectsFilter(ProjectExplorerPlugin *pe)
: m_projectExplorer(pe), m_filesUpToDate(false)
{
- connect(m_projectExplorer, SIGNAL(fileListChanged()),
- this, SLOT(markFilesAsOutOfDate()));
+ setId("Files in any project");
+ setDisplayName(tr("Files in Any Project"));
setShortcutString(QString(QLatin1Char('a')));
+ setPriority(Low);
setIncludedByDefault(true);
+
+ connect(m_projectExplorer, SIGNAL(fileListChanged()),
+ this, SLOT(markFilesAsOutOfDate()));
}
void AllProjectsFilter::markFilesAsOutOfDate()
diff --git a/src/plugins/projectexplorer/allprojectsfilter.h b/src/plugins/projectexplorer/allprojectsfilter.h
index 81f061ab95..68756d7bb0 100644
--- a/src/plugins/projectexplorer/allprojectsfilter.h
+++ b/src/plugins/projectexplorer/allprojectsfilter.h
@@ -47,9 +47,6 @@ class AllProjectsFilter : public Locator::BaseFileFilter
public:
explicit AllProjectsFilter(ProjectExplorerPlugin *pe);
- QString displayName() const { return tr("Files in Any Project"); }
- QString id() const { return QLatin1String("Files in any project"); }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::Low; }
void refresh(QFutureInterface<void> &future);
protected:
diff --git a/src/plugins/projectexplorer/applicationlauncher.cpp b/src/plugins/projectexplorer/applicationlauncher.cpp
index 439d87e92a..fbcfc7ec70 100644
--- a/src/plugins/projectexplorer/applicationlauncher.cpp
+++ b/src/plugins/projectexplorer/applicationlauncher.cpp
@@ -28,13 +28,13 @@
****************************************************************************/
#include "applicationlauncher.h"
-#include "consoleprocess.h"
#ifdef Q_OS_WIN
#include "windebuginterface.h"
#endif
#include <coreplugin/icore.h>
+#include <utils/consoleprocess.h>
#include <utils/qtcprocess.h>
#ifdef Q_OS_WIN
#include <utils/winutils.h>
diff --git a/src/plugins/projectexplorer/appoutputpane.cpp b/src/plugins/projectexplorer/appoutputpane.cpp
index 074575ab5b..979857fa6b 100644
--- a/src/plugins/projectexplorer/appoutputpane.cpp
+++ b/src/plugins/projectexplorer/appoutputpane.cpp
@@ -121,6 +121,8 @@ AppOutputPane::AppOutputPane() :
m_stopButton(new QToolButton),
m_attachButton(new QToolButton)
{
+ setObjectName(QLatin1String("AppOutputPane")); // Used in valgrind engine
+
// Rerun
m_reRunButton->setIcon(QIcon(QLatin1String(ProjectExplorer::Constants::ICON_RUN_SMALL)));
m_reRunButton->setToolTip(tr("Re-run this run-configuration"));
@@ -324,7 +326,8 @@ void AppOutputPane::createNewOutputWindow(RunControl *rc)
}
// Create new
static uint counter = 0;
- Core::Context context(Constants::C_APP_OUTPUT, counter++);
+ Core::Id contextId = Core::Id(Constants::C_APP_OUTPUT).withSuffix(counter++);
+ Core::Context context(contextId);
Core::OutputWindow *ow = new Core::OutputWindow(context, m_tabWidget);
ow->setWindowTitle(tr("Application Output Window"));
ow->setWindowIcon(QIcon(QLatin1String(Constants::ICON_WINDOW)));
diff --git a/src/plugins/projectexplorer/baseprojectwizarddialog.cpp b/src/plugins/projectexplorer/baseprojectwizarddialog.cpp
index 69c63eb850..619f98986a 100644
--- a/src/plugins/projectexplorer/baseprojectwizarddialog.cpp
+++ b/src/plugins/projectexplorer/baseprojectwizarddialog.cpp
@@ -158,9 +158,8 @@ void BaseProjectWizardDialog::slotAccepted()
void BaseProjectWizardDialog::nextClicked()
{
- if (currentId() == d->introPageId) {
+ if (currentId() == d->introPageId)
emit projectParametersChanged(d->introPage->projectName(), d->introPage->path());
- }
}
Utils::ProjectIntroPage *BaseProjectWizardDialog::introPage() const
diff --git a/src/plugins/projectexplorer/buildconfiguration.cpp b/src/plugins/projectexplorer/buildconfiguration.cpp
index 7a592d8eab..05bd88e4eb 100644
--- a/src/plugins/projectexplorer/buildconfiguration.cpp
+++ b/src/plugins/projectexplorer/buildconfiguration.cpp
@@ -39,6 +39,7 @@
#include "kit.h"
#include <coreplugin/variablemanager.h>
+#include <projectexplorer/buildenvironmentwidget.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
@@ -92,8 +93,8 @@ BuildConfiguration::BuildConfiguration(Target *target, const Core::Id id) :
bsl->setDefaultDisplayName(tr("Clean"));
m_stepLists.append(bsl);
- connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
- this, SLOT(handleKitUpdate(ProjectExplorer::Kit*)));
+ connect(target, SIGNAL(kitChanged()),
+ this, SLOT(handleKitUpdate()));
}
BuildConfiguration::BuildConfiguration(Target *target, BuildConfiguration *source) :
@@ -107,8 +108,8 @@ BuildConfiguration::BuildConfiguration(Target *target, BuildConfiguration *sourc
// otherwise BuildStepFactories might reject to set up a BuildStep for us
// since we are not yet the derived class!
- connect(KitManager::instance(), SIGNAL(kitUpdated(ProjectExplorer::Kit*)),
- this, SLOT(handleKitUpdate(ProjectExplorer::Kit*)));
+ connect(target, SIGNAL(kitChanged()),
+ this, SLOT(handleKitUpdate()));
}
BuildConfiguration::~BuildConfiguration()
@@ -116,6 +117,11 @@ BuildConfiguration::~BuildConfiguration()
delete m_macroExpander;
}
+QList<NamedWidget *> BuildConfiguration::createSubConfigWidgets()
+{
+ return QList<NamedWidget *>() << new ProjectExplorer::BuildEnvironmentWidget(this);
+}
+
Utils::AbstractMacroExpander *BuildConfiguration::macroExpander()
{
if (!m_macroExpander)
@@ -157,6 +163,8 @@ bool BuildConfiguration::fromMap(const QVariantMap &map)
m_clearSystemEnvironment = map.value(QLatin1String(CLEAR_SYSTEM_ENVIRONMENT_KEY)).toBool();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(map.value(QLatin1String(USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
+ m_lastEnvironment = environment();
+
qDeleteAll(m_stepLists);
m_stepLists.clear();
@@ -187,11 +195,18 @@ bool BuildConfiguration::fromMap(const QVariantMap &map)
return ProjectConfiguration::fromMap(map);
}
-void BuildConfiguration::handleKitUpdate(ProjectExplorer::Kit *k)
+void BuildConfiguration::emitEnvironmentChanged()
{
- if (k != target()->kit())
- return;
- emit environmentChanged();
+ Utils::Environment env = environment();
+ if (env == m_lastEnvironment)
+ return;
+ m_lastEnvironment = env;
+ emit environmentChanged();
+}
+
+void BuildConfiguration::handleKitUpdate()
+{
+ emitEnvironmentChanged();
}
Target *BuildConfiguration::target() const
@@ -228,7 +243,7 @@ void BuildConfiguration::setUseSystemEnvironment(bool b)
if (useSystemEnvironment() == b)
return;
m_clearSystemEnvironment = !b;
- emit environmentChanged();
+ emitEnvironmentChanged();
}
bool BuildConfiguration::useSystemEnvironment() const
@@ -246,7 +261,7 @@ void BuildConfiguration::setUserEnvironmentChanges(const QList<Utils::Environmen
if (m_userEnvironmentChanges == diff)
return;
m_userEnvironmentChanges = diff;
- emit environmentChanged();
+ emitEnvironmentChanged();
}
void BuildConfiguration::cloneSteps(BuildConfiguration *source)
@@ -283,6 +298,7 @@ IBuildConfigurationFactory::IBuildConfigurationFactory(QObject *parent) :
IBuildConfigurationFactory::~IBuildConfigurationFactory()
{ }
+// restore
IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, const QVariantMap &map)
{
QList<IBuildConfigurationFactory *> factories
@@ -294,6 +310,7 @@ IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, con
return 0;
}
+// create
IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
{
QList<IBuildConfigurationFactory *> factories
@@ -305,4 +322,15 @@ IBuildConfigurationFactory * IBuildConfigurationFactory::find(Target *parent)
return 0;
}
+// clone
+IBuildConfigurationFactory *IBuildConfigurationFactory::find(Target *parent, BuildConfiguration *bc)
+{
+ QList<IBuildConfigurationFactory *> factories
+ = ExtensionSystem::PluginManager::instance()->getObjects<IBuildConfigurationFactory>();
+ foreach (IBuildConfigurationFactory *factory, factories) {
+ if (factory->canClone(parent, bc))
+ return factory;
+ }
+ return 0;
+}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/buildconfiguration.h b/src/plugins/projectexplorer/buildconfiguration.h
index 0dca42a73b..f234307922 100644
--- a/src/plugins/projectexplorer/buildconfiguration.h
+++ b/src/plugins/projectexplorer/buildconfiguration.h
@@ -44,7 +44,7 @@ class AbstractMacroExpander;
namespace ProjectExplorer {
class BuildConfiguration;
-class BuildConfigWidget;
+class NamedWidget;
class BuildStepList;
class Kit;
class Target;
@@ -60,10 +60,11 @@ public:
virtual QString buildDirectory() const = 0;
- virtual BuildConfigWidget *createConfigWidget() = 0;
+ virtual ProjectExplorer::NamedWidget *createConfigWidget() = 0;
+ virtual QList<NamedWidget *> createSubConfigWidgets();
// Maybe the BuildConfiguration is not the best place for the environment
- virtual Utils::Environment baseEnvironment() const;
+ Utils::Environment baseEnvironment() const;
QString baseEnvironmentText() const;
Utils::Environment environment() const;
void setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff);
@@ -76,13 +77,6 @@ public:
virtual QVariantMap toMap() const;
- // Creates a suitable outputparser for custom build steps
- // (based on the tool chain)
- // this is not great API
- // it's mainly so that custom build systems are better integrated
- // with the generic project manager
- virtual IOutputParser *createOutputParser() const = 0;
-
Target *target() const;
virtual bool isEnabled() const;
@@ -111,13 +105,16 @@ protected:
virtual bool fromMap(const QVariantMap &map);
private slots:
- void handleKitUpdate(ProjectExplorer::Kit *k);
+ void handleKitUpdate();
private:
+ void emitEnvironmentChanged();
+
bool m_clearSystemEnvironment;
QList<Utils::EnvironmentItem> m_userEnvironmentChanges;
QList<BuildStepList *> m_stepLists;
Utils::AbstractMacroExpander *m_macroExpander;
+ Utils::Environment m_lastEnvironment;
};
class PROJECTEXPLORER_EXPORT IBuildConfigurationFactory :
@@ -144,6 +141,7 @@ public:
static IBuildConfigurationFactory *find(Target *parent, const QVariantMap &map);
static IBuildConfigurationFactory *find(Target *parent);
+ static IBuildConfigurationFactory *find(Target *parent, BuildConfiguration *bc);
signals:
void availableCreationIdsChanged();
diff --git a/src/plugins/projectexplorer/buildconfigurationmodel.cpp b/src/plugins/projectexplorer/buildconfigurationmodel.cpp
index 01ffa7c183..4d44118d24 100644
--- a/src/plugins/projectexplorer/buildconfigurationmodel.cpp
+++ b/src/plugins/projectexplorer/buildconfigurationmodel.cpp
@@ -127,9 +127,8 @@ QVariant BuildConfigurationModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
const int row = index.row();
- if (row < m_buildConfigurations.size()) {
+ if (row < m_buildConfigurations.size())
return m_buildConfigurations.at(row)->displayName();
- }
}
return QVariant();
@@ -163,9 +162,8 @@ void BuildConfigurationModel::addedBuildConfiguration(ProjectExplorer::BuildConf
BuildConfigurationComparer compare;
int i = 0;
for (; i < m_buildConfigurations.size(); ++i) {
- if (compare(bc, m_buildConfigurations.at(i))) {
+ if (compare(bc, m_buildConfigurations.at(i)))
break;
- }
}
beginInsertRows(QModelIndex(), i, i);
diff --git a/src/plugins/projectexplorer/buildenvironmentwidget.cpp b/src/plugins/projectexplorer/buildenvironmentwidget.cpp
index e1144d6ca5..a37312dc57 100644
--- a/src/plugins/projectexplorer/buildenvironmentwidget.cpp
+++ b/src/plugins/projectexplorer/buildenvironmentwidget.cpp
@@ -40,7 +40,7 @@
using namespace ProjectExplorer;
-BuildEnvironmentWidget::BuildEnvironmentWidget()
+BuildEnvironmentWidget::BuildEnvironmentWidget(BuildConfiguration *bc)
: m_buildConfiguration(0)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
@@ -55,21 +55,6 @@ BuildEnvironmentWidget::BuildEnvironmentWidget()
this, SLOT(environmentModelUserChangesChanged()));
connect(m_clearSystemEnvironmentCheckBox, SIGNAL(toggled(bool)),
this, SLOT(clearSystemEnvironmentCheckBoxClicked(bool)));
-}
-
-QString BuildEnvironmentWidget::displayName() const
-{
- return tr("Build Environment");
-}
-
-void BuildEnvironmentWidget::init(BuildConfiguration *bc)
-{
- Q_ASSERT(bc);
-
- if (m_buildConfiguration) {
- disconnect(m_buildConfiguration->target(), SIGNAL(environmentChanged()),
- this, SLOT(environmentChanged()));
- }
m_buildConfiguration = bc;
@@ -80,6 +65,8 @@ void BuildEnvironmentWidget::init(BuildConfiguration *bc)
m_buildEnvironmentWidget->setBaseEnvironment(m_buildConfiguration->baseEnvironment());
m_buildEnvironmentWidget->setBaseEnvironmentText(m_buildConfiguration->baseEnvironmentText());
m_buildEnvironmentWidget->setUserChanges(m_buildConfiguration->userEnvironmentChanges());
+
+ setDisplayName(tr("Build Environment"));
}
void BuildEnvironmentWidget::environmentModelUserChangesChanged()
diff --git a/src/plugins/projectexplorer/buildenvironmentwidget.h b/src/plugins/projectexplorer/buildenvironmentwidget.h
index a5ec6373f7..07e3976f83 100644
--- a/src/plugins/projectexplorer/buildenvironmentwidget.h
+++ b/src/plugins/projectexplorer/buildenvironmentwidget.h
@@ -31,6 +31,7 @@
#define BUILDENVIRONMENTWIDGET_H
#include <projectexplorer/buildstep.h>
+#include <projectexplorer/namedwidget.h>
QT_BEGIN_NAMESPACE
class QCheckBox;
@@ -41,15 +42,12 @@ namespace ProjectExplorer {
class EnvironmentWidget;
class BuildConfiguration;
-class PROJECTEXPLORER_EXPORT BuildEnvironmentWidget : public BuildConfigWidget
+class PROJECTEXPLORER_EXPORT BuildEnvironmentWidget : public NamedWidget
{
Q_OBJECT
public:
- BuildEnvironmentWidget();
-
- QString displayName() const;
- void init(BuildConfiguration *bc);
+ BuildEnvironmentWidget(BuildConfiguration *bc);
private slots:
void environmentModelUserChangesChanged();
diff --git a/src/plugins/projectexplorer/buildmanager.cpp b/src/plugins/projectexplorer/buildmanager.cpp
index 5da4000a65..b8f60b3166 100644
--- a/src/plugins/projectexplorer/buildmanager.cpp
+++ b/src/plugins/projectexplorer/buildmanager.cpp
@@ -48,12 +48,14 @@
#include <utils/qtcassert.h>
#include <QDir>
+#include <QPointer>
#include <QTime>
#include <QTimer>
#include <QMetaType>
#include <QList>
#include <QHash>
#include <QFutureWatcher>
+#include <QElapsedTimer>
#include <utils/QtConcurrentTools>
@@ -75,7 +77,6 @@ struct BuildManagerPrivate {
QList<BuildStep *> m_buildQueue;
QList<bool> m_enabledState;
QStringList m_stepNames;
- ProjectExplorerPlugin *m_projectExplorerPlugin;
bool m_running;
QFutureWatcher<bool> m_watcher;
QFutureInterface<bool> m_futureInterfaceForAysnc;
@@ -97,7 +98,9 @@ struct BuildManagerPrivate {
int m_maxProgress;
QFutureInterface<void> *m_progressFutureInterface;
QFutureWatcher<void> m_progressWatcher;
- QWeakPointer<Core::FutureProgress> m_futureProgress;
+ QPointer<Core::FutureProgress> m_futureProgress;
+
+ QElapsedTimer m_elapsed;
};
BuildManagerPrivate::BuildManagerPrivate() :
@@ -115,8 +118,6 @@ BuildManagerPrivate::BuildManagerPrivate() :
BuildManager::BuildManager(ProjectExplorerPlugin *parent, QAction *cancelBuildAction)
: QObject(parent), d(new BuildManagerPrivate)
{
- d->m_projectExplorerPlugin = parent;
-
connect(&d->m_watcher, SIGNAL(finished()),
this, SLOT(nextBuildQueue()));
@@ -237,16 +238,27 @@ void BuildManager::updateTaskCount()
{
Core::ProgressManager *progressManager = Core::ICore::progressManager();
const int errors = getErrorTaskCount();
- if (errors > 0) {
+ if (errors > 0)
progressManager->setApplicationLabel(QString::number(errors));
- } else {
+ else
progressManager->setApplicationLabel(QString());
- }
emit tasksChanged();
}
void BuildManager::finish()
{
+ const int seconds = d->m_elapsed.elapsed() / 1000;
+ const int minutes = seconds / 60;
+ const int hours = minutes / 60;
+ QString maybeHours;
+ if (hours) {
+ maybeHours.setNum(hours);
+ maybeHours.append(QLatin1Char(':'));
+ }
+ addToOutputWindow(tr("Elapsed time: %1%2:%3.") .arg(maybeHours)
+ .arg(minutes % 60, 2, 10, QLatin1Char('0'))
+ .arg(seconds % 60, 2, 10, QLatin1Char('0')), BuildStep::MessageOutput);
+
QApplication::alert(Core::ICore::mainWindow(), 3000);
}
@@ -274,7 +286,7 @@ void BuildManager::clearBuildQueue()
d->m_progressWatcher.setFuture(QFuture<void>());
delete d->m_progressFutureInterface;
d->m_progressFutureInterface = 0;
- d->m_futureProgress.clear();
+ d->m_futureProgress = 0;
d->m_maxProgress = 0;
emit buildQueueFinished(false);
@@ -311,6 +323,7 @@ void BuildManager::startBuildQueue(const QStringList &preambleMessage)
return;
}
if (!d->m_running) {
+ d->m_elapsed.start();
// Progress Reporting
Core::ProgressManager *progressManager = Core::ICore::progressManager();
d->m_progressFutureInterface = new QFutureInterface<void>;
@@ -321,10 +334,10 @@ void BuildManager::startBuildQueue(const QStringList &preambleMessage)
d->m_taskHub->clearTasks(Core::Id(Constants::TASK_CATEGORY_COMPILE));
d->m_taskHub->clearTasks(Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM));
progressManager->setApplicationLabel(QString());
- d->m_futureProgress = QWeakPointer<Core::FutureProgress>(progressManager->addTask(d->m_progressFutureInterface->future(),
+ d->m_futureProgress = progressManager->addTask(d->m_progressFutureInterface->future(),
QString(),
QLatin1String(Constants::TASK_BUILD),
- Core::ProgressManager::KeepOnFinish | Core::ProgressManager::ShowInApplicationIcon));
+ Core::ProgressManager::KeepOnFinish | Core::ProgressManager::ShowInApplicationIcon);
connect(d->m_futureProgress.data(), SIGNAL(clicked()), this, SLOT(showBuildResults()));
d->m_futureProgress.data()->setWidget(new Internal::BuildProgress(d->m_taskWindow));
d->m_progress = 0;
@@ -532,7 +545,7 @@ bool BuildManager::buildList(BuildStepList *bsl, const QString &stepListName)
bool BuildManager::buildLists(QList<BuildStepList *> bsls, const QStringList &stepListNames, const QStringList &preambelMessage)
{
QList<BuildStep *> steps;
- foreach(BuildStepList *list, bsls)
+ foreach (BuildStepList *list, bsls)
steps.append(list->steps());
QStringList names;
diff --git a/src/plugins/projectexplorer/buildsettingspropertiespage.cpp b/src/plugins/projectexplorer/buildsettingspropertiespage.cpp
index 2466798e4a..bb07f50b49 100644
--- a/src/plugins/projectexplorer/buildsettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/buildsettingspropertiespage.cpp
@@ -175,7 +175,7 @@ BuildSettingsWidget::BuildSettingsWidget(Target *target) :
connect(m_target, SIGNAL(kitChanged()), this, SLOT(updateAddButtonMenu()));
}
-void BuildSettingsWidget::addSubWidget(BuildConfigWidget *widget)
+void BuildSettingsWidget::addSubWidget(NamedWidget *widget)
{
widget->setContentsMargins(0, 10, 0, 0);
@@ -205,7 +205,7 @@ void BuildSettingsWidget::clear()
m_labels.clear();
}
-QList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const
+QList<NamedWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
@@ -235,19 +235,20 @@ void BuildSettingsWidget::updateBuildSettings()
// update buttons
m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);
+ if (!m_buildConfiguration)
+ return;
+
// Add pages
- BuildConfigWidget *generalConfigWidget = m_buildConfiguration->createConfigWidget();
- addSubWidget(generalConfigWidget);
+ NamedWidget *generalConfigWidget = m_buildConfiguration->createConfigWidget();
+ if (generalConfigWidget)
+ addSubWidget(generalConfigWidget);
- addSubWidget(new BuildStepsPage(m_target, Core::Id(Constants::BUILDSTEPS_BUILD)));
- addSubWidget(new BuildStepsPage(m_target, Core::Id(Constants::BUILDSTEPS_CLEAN)));
+ addSubWidget(new BuildStepsPage(m_buildConfiguration, Core::Id(Constants::BUILDSTEPS_BUILD)));
+ addSubWidget(new BuildStepsPage(m_buildConfiguration, Core::Id(Constants::BUILDSTEPS_CLEAN)));
- QList<BuildConfigWidget *> subConfigWidgets = m_target->project()->subConfigWidgets();
- foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
+ QList<NamedWidget *> subConfigWidgets = m_buildConfiguration->createSubConfigWidgets();
+ foreach (NamedWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget);
-
- foreach (BuildConfigWidget *widget, subWidgets())
- widget->init(m_buildConfiguration);
}
void BuildSettingsWidget::currentIndexChanged(int index)
@@ -267,11 +268,7 @@ void BuildSettingsWidget::updateActiveConfiguration()
BuildConfigurationModel *model = static_cast<BuildConfigurationModel *>(m_buildConfigurationComboBox->model());
m_buildConfigurationComboBox->setCurrentIndex(model->indexFor(m_buildConfiguration).row());
- foreach (QWidget *widget, subWidgets()) {
- if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
- buildStepWidget->init(m_buildConfiguration);
- }
- }
+ updateBuildSettings();
}
void BuildSettingsWidget::createConfiguration()
@@ -291,7 +288,6 @@ void BuildSettingsWidget::createConfiguration()
QTC_CHECK(bc->id() == id);
m_target->setActiveBuildConfiguration(bc);
- updateBuildSettings();
}
void BuildSettingsWidget::cloneConfiguration()
@@ -357,8 +353,6 @@ void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfigura
bc->setDisplayName(name);
m_target->addBuildConfiguration(bc);
- updateBuildSettings();
-
m_target->setActiveBuildConfiguration(bc);
}
@@ -392,6 +386,4 @@ void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfigur
}
m_target->removeBuildConfiguration(deleteConfiguration);
-
- updateBuildSettings();
}
diff --git a/src/plugins/projectexplorer/buildsettingspropertiespage.h b/src/plugins/projectexplorer/buildsettingspropertiespage.h
index 6ad5f059c0..32f214e771 100644
--- a/src/plugins/projectexplorer/buildsettingspropertiespage.h
+++ b/src/plugins/projectexplorer/buildsettingspropertiespage.h
@@ -45,8 +45,8 @@ QT_END_NAMESPACE
namespace ProjectExplorer {
class BuildConfiguration;
-class BuildConfigWidget;
class IBuildStepFactory;
+class NamedWidget;
namespace Internal {
@@ -73,8 +73,8 @@ public:
~BuildSettingsWidget();
void clear();
- void addSubWidget(BuildConfigWidget *widget);
- QList<BuildConfigWidget *> subWidgets() const;
+ void addSubWidget(ProjectExplorer::NamedWidget *widget);
+ QList<ProjectExplorer::NamedWidget *> subWidgets() const;
private slots:
void updateBuildSettings();
@@ -103,7 +103,7 @@ private:
QComboBox *m_buildConfigurationComboBox;
QMenu *m_addButtonMenu;
- QList<BuildConfigWidget *> m_subWidgets;
+ QList<NamedWidget *> m_subWidgets;
QList<QLabel *> m_labels;
};
diff --git a/src/plugins/projectexplorer/buildstep.h b/src/plugins/projectexplorer/buildstep.h
index 1dc7725a0e..5a81920c45 100644
--- a/src/plugins/projectexplorer/buildstep.h
+++ b/src/plugins/projectexplorer/buildstep.h
@@ -118,24 +118,6 @@ public:
virtual BuildStep *clone(BuildStepList *parent, BuildStep *product) = 0;
};
-class PROJECTEXPLORER_EXPORT BuildConfigWidget
- : public QWidget
-{
- Q_OBJECT
-public:
- BuildConfigWidget()
- :QWidget(0)
- {}
-
- virtual QString displayName() const = 0;
-
- // This is called to set up the config widget before showing it
- virtual void init(BuildConfiguration *bc) = 0;
-
-signals:
- void displayNameChanged(const QString &);
-};
-
class PROJECTEXPLORER_EXPORT BuildStepConfigWidget
: public QWidget
{
diff --git a/src/plugins/projectexplorer/buildsteplist.cpp b/src/plugins/projectexplorer/buildsteplist.cpp
index 5b4764c918..4993c6eaa4 100644
--- a/src/plugins/projectexplorer/buildsteplist.cpp
+++ b/src/plugins/projectexplorer/buildsteplist.cpp
@@ -45,7 +45,7 @@ namespace {
IBuildStepFactory *findCloneFactory(BuildStepList *parent, BuildStep *source)
{
QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::getObjects<IBuildStepFactory>();
- foreach(IBuildStepFactory *factory, factories)
+ foreach (IBuildStepFactory *factory, factories)
if (factory->canClone(parent, source))
return factory;
return 0;
@@ -54,7 +54,7 @@ IBuildStepFactory *findCloneFactory(BuildStepList *parent, BuildStep *source)
IBuildStepFactory *findRestoreFactory(BuildStepList *parent, const QVariantMap &map)
{
QList<IBuildStepFactory *> factories = ExtensionSystem::PluginManager::getObjects<IBuildStepFactory>();
- foreach(IBuildStepFactory *factory, factories)
+ foreach (IBuildStepFactory *factory, factories)
if (factory->canRestore(parent, map))
return factory;
return 0;
diff --git a/src/plugins/projectexplorer/buildstepspage.cpp b/src/plugins/projectexplorer/buildstepspage.cpp
index 7a5e4d32e2..aff53ec435 100644
--- a/src/plugins/projectexplorer/buildstepspage.cpp
+++ b/src/plugins/projectexplorer/buildstepspage.cpp
@@ -38,6 +38,7 @@
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <utils/detailswidget.h>
+#include <utils/hostosinfo.h>
#include <QSignalMapper>
@@ -53,9 +54,10 @@
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
+using namespace Utils;
ToolWidget::ToolWidget(QWidget *parent)
- : Utils::FadingPanel(parent), m_buildStepEnabled(true)
+ : Utils::FadingPanel(parent), m_buildStepEnabled(true), m_targetOpacity(1.0f)
{
QHBoxLayout *layout = new QHBoxLayout;
layout->setMargin(4);
@@ -67,11 +69,7 @@ ToolWidget::ToolWidget(QWidget *parent)
hbox->setContentsMargins(0, 0, 0, 0);
hbox->setSpacing(0);
m_firstWidget->setLayout(hbox);
-#ifdef Q_OS_MAC
- QSize buttonSize(20, 20);
-#else
- QSize buttonSize(20, 26);
-#endif
+ QSize buttonSize(20, HostOsInfo::isMacHost() ? 20 : 26);
m_disableButton = new QToolButton(m_firstWidget);
m_disableButton->setAutoRaise(true);
@@ -138,17 +136,15 @@ void ToolWidget::setBuildStepEnabled(bool b)
{
m_buildStepEnabled = b;
if (m_buildStepEnabled) {
-#ifdef Q_OS_MAC
- m_firstWidget->setOpacity(m_targetOpacity);
-#else
- m_firstWidget->fadeTo(m_targetOpacity);
-#endif
+ if (HostOsInfo::isMacHost())
+ m_firstWidget->setOpacity(m_targetOpacity);
+ else
+ m_firstWidget->fadeTo(m_targetOpacity);
} else {
-#ifdef Q_OS_MAC
- m_firstWidget->setOpacity(1.0);
-#else
- m_firstWidget->fadeTo(1.0);
-#endif
+ if (HostOsInfo::isMacHost())
+ m_firstWidget->setOpacity(1.0);
+ else
+ m_firstWidget->fadeTo(1.0);
}
m_disableButton->setChecked(!b);
}
@@ -461,9 +457,8 @@ void BuildStepListWidget::setupUi()
hboxLayout->addStretch(10);
-#ifdef Q_OS_MAC
- m_addButton->setAttribute(Qt::WA_MacSmallSize);
-#endif
+ if (HostOsInfo::isMacHost())
+ m_addButton->setAttribute(Qt::WA_MacSmallSize);
m_vbox->addLayout(hboxLayout);
@@ -483,7 +478,7 @@ void BuildStepListWidget::updateBuildStepButtonsState()
s->toolWidget->setUpEnabled((i > 0)
&& !(m_buildStepList->at(i)->immutable()
- && m_buildStepList->at(i - 1)));
+ && m_buildStepList->at(i - 1)->immutable()));
m_upMapper->setMapping(s->toolWidget, i);
s->toolWidget->setDownEnabled((i + 1 < m_buildStepList->count())
&& !(m_buildStepList->at(i)->immutable()
@@ -496,31 +491,23 @@ void BuildStepListWidget::updateBuildStepButtonsState()
}
}
-BuildStepsPage::BuildStepsPage(Target *target, Core::Id id) :
- BuildConfigWidget(),
+BuildStepsPage::BuildStepsPage(BuildConfiguration *bc, Core::Id id) :
+ NamedWidget(),
m_id(id),
m_widget(new BuildStepListWidget(this))
{
- Q_UNUSED(target);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setMargin(0);
layout->setSpacing(0);
layout->addWidget(m_widget);
-}
-BuildStepsPage::~BuildStepsPage()
-{ }
+ m_widget->init(bc->stepList(m_id));
-QString BuildStepsPage::displayName() const
-{
if (m_id == Constants::BUILDSTEPS_BUILD)
- return tr("Build Steps");
+ setDisplayName(tr("Build Steps"));
if (m_id == Constants::BUILDSTEPS_CLEAN)
- return tr("Clean Steps");
- return QString();
+ setDisplayName(tr("Clean Steps"));
}
-void BuildStepsPage::init(BuildConfiguration *bc)
-{
- m_widget->init(bc->stepList(m_id));
-}
+BuildStepsPage::~BuildStepsPage()
+{ }
diff --git a/src/plugins/projectexplorer/buildstepspage.h b/src/plugins/projectexplorer/buildstepspage.h
index 7246c5bcb2..ee8222d7ec 100644
--- a/src/plugins/projectexplorer/buildstepspage.h
+++ b/src/plugins/projectexplorer/buildstepspage.h
@@ -151,17 +151,14 @@ namespace Ui {
class BuildStepsPage;
}
-class BuildStepsPage : public BuildConfigWidget
+class BuildStepsPage : public NamedWidget
{
Q_OBJECT
public:
- BuildStepsPage(Target *target, Core::Id id);
+ BuildStepsPage(BuildConfiguration *bc, Core::Id id);
virtual ~BuildStepsPage();
- QString displayName() const;
- void init(BuildConfiguration *bc);
-
private:
Core::Id m_id;
BuildStepListWidget *m_widget;
diff --git a/src/plugins/projectexplorer/buildtargetinfo.h b/src/plugins/projectexplorer/buildtargetinfo.h
index 8f6dfbc0f7..526a1072b3 100644
--- a/src/plugins/projectexplorer/buildtargetinfo.h
+++ b/src/plugins/projectexplorer/buildtargetinfo.h
@@ -34,6 +34,7 @@
#include <utils/fileutils.h>
#include <QList>
+#include <QSet>
namespace ProjectExplorer {
@@ -58,6 +59,22 @@ public:
bool isValid() const { return !targetFilePath.isEmpty(); }
};
+inline bool operator==(const BuildTargetInfo &ti1, const BuildTargetInfo &ti2)
+{
+ return ti1.targetFilePath == ti2.targetFilePath;
+}
+
+inline bool operator!=(const BuildTargetInfo &ti1, const BuildTargetInfo &ti2)
+{
+ return !(ti1 == ti2);
+}
+
+inline uint qHash(const BuildTargetInfo &ti)
+{
+ return qHash(ti.targetFilePath);
+}
+
+
class PROJECTEXPLORER_EXPORT BuildTargetInfoList
{
public:
@@ -78,6 +95,16 @@ public:
QList<BuildTargetInfo> list;
};
+inline bool operator==(const BuildTargetInfoList &til1, const BuildTargetInfoList &til2)
+{
+ return til1.list.toSet() == til2.list.toSet();
+}
+
+inline bool operator!=(const BuildTargetInfoList &til1, const BuildTargetInfoList &til2)
+{
+ return !(til1 == til2);
+}
+
} // namespace ProjectExplorer
#endif // BUILDTARGETINFO_H
diff --git a/src/plugins/projectexplorer/clangparser.cpp b/src/plugins/projectexplorer/clangparser.cpp
index cb62285f49..6de86dc241 100644
--- a/src/plugins/projectexplorer/clangparser.cpp
+++ b/src/plugins/projectexplorer/clangparser.cpp
@@ -197,13 +197,13 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In file included from ..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qnamespace.h:45:"),
- Utils::FileName::fromUserInput("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qnamespace.h"), 45,
+ Utils::FileName::fromUserInput(QLatin1String("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qnamespace.h")), 45,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("unknown attribute 'dllimport' ignored [-Wunknown-attributes]\n"
"class Q_CORE_EXPORT QSysInfo {\n"
" ^"),
- Utils::FileName::fromUserInput("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qglobal.h"), 1425,
+ Utils::FileName::fromUserInput(QLatin1String("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qglobal.h")), 1425,
categoryCompile))
<< QString();
QTest::newRow("note")
@@ -217,7 +217,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
QLatin1String("instantiated from:\n"
"# define Q_CORE_EXPORT Q_DECL_IMPORT\n"
" ^"),
- Utils::FileName::fromUserInput("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qglobal.h"), 1289,
+ Utils::FileName::fromUserInput(QLatin1String("..\\..\\..\\QtSDK1.1\\Desktop\\Qt\\4.7.3\\mingw\\include/QtCore/qglobal.h")), 1289,
categoryCompile))
<< QString();
QTest::newRow("fatal error")
@@ -231,7 +231,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
QLatin1String("'bits/c++config.h' file not found\n"
"#include <bits/c++config.h>\n"
" ^"),
- Utils::FileName::fromUserInput("/usr/include/c++/4.6/utility"), 68,
+ Utils::FileName::fromUserInput(QLatin1String("/usr/include/c++/4.6/utility")), 68,
categoryCompile))
<< QString();
@@ -246,7 +246,7 @@ void ProjectExplorerPlugin::testClangOutputParser_data()
QLatin1String("?: has lower precedence than +; + will be evaluated first [-Wparentheses]\n"
" int x = option->rect.x() + horizontal ? 2 : 6;\n"
" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ^"),
- Utils::FileName::fromUserInput("/home/code/src/creator/src/plugins/coreplugin/manhattanstyle.cpp"), 567,
+ Utils::FileName::fromUserInput(QLatin1String("/home/code/src/creator/src/plugins/coreplugin/manhattanstyle.cpp")), 567,
categoryCompile))
<< QString();
}
diff --git a/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp b/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
index e16e8728b7..51cc900a77 100644
--- a/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/codestylesettingspropertiespage.cpp
@@ -76,13 +76,13 @@ CodeStyleSettingsWidget::CodeStyleSettingsWidget(Project *project) : QWidget(),
const EditorConfiguration *config = m_project->editorConfiguration();
- QMap<QString, ICodeStylePreferencesFactory *> factories
+ QMap<Core::Id, ICodeStylePreferencesFactory *> factories
= TextEditor::TextEditorSettings::instance()->codeStyleFactories();
- QMapIterator<QString, ICodeStylePreferencesFactory *> it(factories);
+ QMapIterator<Core::Id, ICodeStylePreferencesFactory *> it(factories);
while (it.hasNext()) {
it.next();
ICodeStylePreferencesFactory *factory = it.value();
- const QString languageId = factory->languageId();
+ Core::Id languageId = factory->languageId();
ICodeStylePreferences *codeStylePreferences = config->codeStyle(languageId);
CodeStyleEditor *preview = new CodeStyleEditor(factory, codeStylePreferences, m_ui.stackedWidget);
diff --git a/src/plugins/projectexplorer/compileoutputwindow.cpp b/src/plugins/projectexplorer/compileoutputwindow.cpp
index 4ff6009169..81ae4b9613 100644
--- a/src/plugins/projectexplorer/compileoutputwindow.cpp
+++ b/src/plugins/projectexplorer/compileoutputwindow.cpp
@@ -57,7 +57,7 @@ using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
namespace {
-const int MAX_LINECOUNT = 50000;
+const int MAX_LINECOUNT = 100000;
}
namespace ProjectExplorer {
@@ -119,6 +119,15 @@ CompileOutputWindow::CompileOutputWindow(BuildManager * /*bm*/, QAction *cancelB
m_outputWindow->setUndoRedoEnabled(false);
m_outputWindow->setMaxLineCount(MAX_LINECOUNT);
+ // Let selected text be colored as if the text edit was editable,
+ // otherwise the highlight for searching is too light
+ QPalette p = m_outputWindow->palette();
+ QColor activeHighlight = p.color(QPalette::Active, QPalette::Highlight);
+ p.setColor(QPalette::Highlight, activeHighlight);
+ QColor activeHighlightedText = p.color(QPalette::Active, QPalette::HighlightedText);
+ p.setColor(QPalette::HighlightedText, activeHighlightedText);
+ m_outputWindow->setPalette(p);
+
m_cancelBuildButton->setDefaultAction(cancelBuildAction);
Aggregation::Aggregate *agg = new Aggregation::Aggregate;
diff --git a/src/plugins/projectexplorer/copytaskhandler.cpp b/src/plugins/projectexplorer/copytaskhandler.cpp
index 2cce401ac5..ba8ae2948c 100644
--- a/src/plugins/projectexplorer/copytaskhandler.cpp
+++ b/src/plugins/projectexplorer/copytaskhandler.cpp
@@ -30,8 +30,10 @@
#include "copytaskhandler.h"
#include "task.h"
+#include "taskwindow.h"
#include <coreplugin/coreconstants.h>
+#include <coreplugin/actionmanager/actionmanager.h>
#include <QDir>
#include <QAction>
@@ -61,9 +63,13 @@ void CopyTaskHandler::handle(const ProjectExplorer::Task &task)
+ type + task.description);
}
+Core::Id CopyTaskHandler::actionManagerId() const
+{
+ return Core::Id(Core::Constants::COPY);
+}
+
QAction *CopyTaskHandler::createAction(QObject *parent) const
{
- QAction *copyAction = new QAction(tr("&Copy", "Name of the action triggering the copytaskhandler"), parent);
- copyAction->setToolTip(tr("Copy task to clipboard"));
+ QAction *copyAction = new QAction(parent);
return copyAction;
}
diff --git a/src/plugins/projectexplorer/copytaskhandler.h b/src/plugins/projectexplorer/copytaskhandler.h
index aaac5376ed..0931ff520f 100644
--- a/src/plugins/projectexplorer/copytaskhandler.h
+++ b/src/plugins/projectexplorer/copytaskhandler.h
@@ -44,6 +44,7 @@ public:
bool canHandle(const Task &) const { return true; }
void handle(const Task &task);
+ Core::Id actionManagerId() const;
QAction *createAction(QObject *parent) const;
};
diff --git a/src/plugins/projectexplorer/currentprojectfilter.cpp b/src/plugins/projectexplorer/currentprojectfilter.cpp
index f20a583b43..b86559ec94 100644
--- a/src/plugins/projectexplorer/currentprojectfilter.cpp
+++ b/src/plugins/projectexplorer/currentprojectfilter.cpp
@@ -41,12 +41,14 @@ using namespace ProjectExplorer::Internal;
CurrentProjectFilter::CurrentProjectFilter(ProjectExplorerPlugin *pe)
: BaseFileFilter(), m_projectExplorer(pe), m_project(0), m_filesUpToDate(false)
{
- m_projectExplorer = pe;
+ setId("Files in current project");
+ setDisplayName(tr("Files in Current Project"));
+ setPriority(Low);
+ setShortcutString(QString(QLatin1Char('p')));
+ setIncludedByDefault(false);
connect(m_projectExplorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)),
this, SLOT(currentProjectChanged(ProjectExplorer::Project*)));
- setShortcutString(QString(QLatin1Char('p')));
- setIncludedByDefault(false);
}
void CurrentProjectFilter::markFilesAsOutOfDate()
diff --git a/src/plugins/projectexplorer/currentprojectfilter.h b/src/plugins/projectexplorer/currentprojectfilter.h
index beb8231e49..3738750fdd 100644
--- a/src/plugins/projectexplorer/currentprojectfilter.h
+++ b/src/plugins/projectexplorer/currentprojectfilter.h
@@ -47,9 +47,6 @@ class CurrentProjectFilter : public Locator::BaseFileFilter
public:
CurrentProjectFilter(ProjectExplorerPlugin *pe);
- QString displayName() const { return tr("Files in Current Project"); }
- QString id() const { return QLatin1String("Files in current project"); }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::Low; }
void refresh(QFutureInterface<void> &future);
protected:
@@ -60,7 +57,6 @@ private slots:
void markFilesAsOutOfDate();
private:
-
ProjectExplorerPlugin *m_projectExplorer;
Project *m_project;
bool m_filesUpToDate;
diff --git a/src/plugins/projectexplorer/customtoolchain.cpp b/src/plugins/projectexplorer/customtoolchain.cpp
new file mode 100644
index 0000000000..9275ef86a6
--- /dev/null
+++ b/src/plugins/projectexplorer/customtoolchain.cpp
@@ -0,0 +1,506 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "abiwidget.h"
+#include "customtoolchain.h"
+#include "gccparser.h"
+#include "projectexplorerconstants.h"
+#include "toolchainmanager.h"
+
+#include <utils/detailswidget.h>
+#include <utils/environment.h>
+#include <utils/pathchooser.h>
+
+#include <QFormLayout>
+#include <QPlainTextEdit>
+#include <QLineEdit>
+
+using namespace Utils;
+
+namespace ProjectExplorer {
+
+// --------------------------------------------------------------------------
+// Helpers:
+// --------------------------------------------------------------------------
+
+static const char compilerCommandKeyC[] = "ProjectExplorer.CustomToolChain.CompilerPath";
+static const char makeCommandKeyC[] = "ProjectExplorer.CustomToolChain.MakePath";
+static const char targetAbiKeyC[] = "ProjectExplorer.CustomToolChain.TargetAbi";
+static const char supportedAbisKeyC[] = "ProjectExplorer.CustomToolChain.SupportedAbis";
+static const char predefinedMacrosKeyC[] = "ProjectExplorer.CustomToolChain.PredefinedMacros";
+static const char headerPathsKeyC[] = "ProjectExplorer.CustomToolChain.HeaderPaths";
+static const char cxx11FlagsKeyC[] = "ProjectExplorer.CustomToolChain.Cxx11Flags";
+static const char mkspecsKeyC[] = "ProjectExplorer.CustomToolChain.Mkspecs";
+
+// --------------------------------------------------------------------------
+// CustomToolChain
+// --------------------------------------------------------------------------
+
+CustomToolChain::CustomToolChain(bool autodetect) :
+ ToolChain(QLatin1String(Constants::CUSTOM_TOOLCHAIN_ID), autodetect)
+{ }
+
+CustomToolChain::CustomToolChain(const QString &id, bool autodetect) :
+ ToolChain(id, autodetect)
+{ }
+
+CustomToolChain::CustomToolChain(const CustomToolChain &tc) :
+ ToolChain(tc),
+ m_compilerCommand(tc.m_compilerCommand),
+ m_makeCommand(tc.m_makeCommand),
+ m_targetAbi(tc.m_targetAbi),
+ m_predefinedMacros(tc.m_predefinedMacros),
+ m_systemHeaderPaths(tc.m_systemHeaderPaths)
+{ }
+
+QString CustomToolChain::type() const
+{
+ return QLatin1String("custom");
+}
+
+QString CustomToolChain::typeDisplayName() const
+{
+ return Internal::CustomToolChainFactory::tr("Custom");
+}
+
+Abi CustomToolChain::targetAbi() const
+{
+ return m_targetAbi;
+}
+
+void CustomToolChain::setTargetAbi(const Abi &abi)
+{
+ if (abi == m_targetAbi)
+ return;
+
+ m_targetAbi = abi;
+ toolChainUpdated();
+}
+
+bool CustomToolChain::isValid() const
+{
+ return true;
+}
+
+QByteArray CustomToolChain::predefinedMacros(const QStringList &cxxflags) const
+{
+ QByteArray result;
+ QStringList macros = m_predefinedMacros;
+ foreach (const QString &cxxFlag, cxxflags) {
+ if (cxxFlag.startsWith(QLatin1String("-D"))) {
+ macros << cxxFlag.mid(2).trimmed();
+ } else if (cxxFlag.startsWith(QLatin1String("-U"))) {
+ const QString &removedName = cxxFlag.mid(2).trimmed();
+ for (int i = macros.size() - 1; i >= 0; --i) {
+ const QString &m = macros.at(i);
+ if (m.left(m.indexOf(QLatin1Char('='))) == removedName)
+ macros.removeAt(i);
+ }
+ }
+ }
+ foreach (const QString &str, macros) {
+ QByteArray ba = str.toUtf8();
+ int equals = ba.indexOf('=');
+ if (equals == -1) {
+ result += "#define " + ba.trimmed() + '\n';
+ } else {
+ result += "#define " + ba.left(equals).trimmed() + ' '
+ + ba.mid(equals + 1).trimmed() + '\n';
+ }
+ }
+ return result;
+}
+
+ToolChain::CompilerFlags CustomToolChain::compilerFlags(const QStringList &cxxflags) const
+{
+ foreach (const QString &cxx11Flag, m_cxx11Flags)
+ if (cxxflags.contains(cxx11Flag))
+ return STD_CXX11;
+ return NO_FLAGS;
+}
+
+const QStringList &CustomToolChain::rawPredefinedMacros() const
+{
+ return m_predefinedMacros;
+}
+
+void CustomToolChain::setPredefinedMacros(const QStringList &list)
+{
+ m_predefinedMacros = list;
+}
+
+QList<HeaderPath> CustomToolChain::systemHeaderPaths(const QStringList &cxxFlags, const Utils::FileName &) const
+{
+ QList<HeaderPath> flagHeaderPaths;
+ foreach (const QString &cxxFlag, cxxFlags) {
+ if (cxxFlag.startsWith(QLatin1String("-I")))
+ flagHeaderPaths << HeaderPath(cxxFlag.mid(2).trimmed(), HeaderPath::GlobalHeaderPath);
+ }
+
+ return m_systemHeaderPaths + flagHeaderPaths;
+}
+
+void CustomToolChain::addToEnvironment(Environment &env) const
+{
+ if (!m_compilerCommand.isEmpty()) {
+ FileName path = m_compilerCommand.parentDir();
+ env.prependOrSetPath(path.toString());
+ FileName makePath = m_makeCommand.parentDir();
+ if (makePath != path)
+ env.prependOrSetPath(makePath.toString());
+ }
+}
+
+QList<FileName> CustomToolChain::suggestedMkspecList() const
+{
+ return m_mkspecs;
+}
+
+// TODO: Customize
+IOutputParser *CustomToolChain::outputParser() const
+{
+ return new GccParser;
+}
+
+QStringList CustomToolChain::headerPathsList() const
+{
+ QStringList list;
+ foreach (const HeaderPath &headerPath, m_systemHeaderPaths)
+ list << headerPath.path();
+ return list;
+}
+
+void CustomToolChain::setHeaderPaths(const QStringList &list)
+{
+ m_systemHeaderPaths.clear();
+ foreach (const QString &headerPath, list)
+ m_systemHeaderPaths << HeaderPath(headerPath.trimmed(), HeaderPath::GlobalHeaderPath);
+}
+
+void CustomToolChain::setCompilerCommand(const FileName &path)
+{
+ if (path == m_compilerCommand)
+ return;
+ m_compilerCommand = path;
+ toolChainUpdated();
+}
+
+FileName CustomToolChain::compilerCommand() const
+{
+ return m_compilerCommand;
+}
+
+void CustomToolChain::setMakeCommand(const FileName &path)
+{
+ if (path == m_makeCommand)
+ return;
+ m_makeCommand = path;
+ toolChainUpdated();
+}
+
+QString CustomToolChain::makeCommand(const Utils::Environment &) const
+{
+ return m_makeCommand.toString();
+}
+
+void CustomToolChain::setCxx11Flags(const QStringList &flags)
+{
+ if (flags == m_cxx11Flags)
+ return;
+ m_cxx11Flags = flags;
+ toolChainUpdated();
+}
+
+const QStringList &CustomToolChain::cxx11Flags() const
+{
+ return m_cxx11Flags;
+}
+
+void CustomToolChain::setMkspecs(const QString &specs)
+{
+ m_mkspecs.clear();
+ foreach (const QString &spec, specs.split(QLatin1Char(',')))
+ m_mkspecs << FileName::fromString(spec);
+}
+
+QString CustomToolChain::mkspecs() const
+{
+ QString list;
+ foreach (const FileName &spec, m_mkspecs)
+ list.append(spec.toString() + QLatin1Char(','));
+ list.chop(1);
+ return list;
+}
+
+ToolChain *CustomToolChain::clone() const
+{
+ return new CustomToolChain(*this);
+}
+
+QVariantMap CustomToolChain::toMap() const
+{
+ QVariantMap data = ToolChain::toMap();
+ data.insert(QLatin1String(compilerCommandKeyC), m_compilerCommand.toString());
+ data.insert(QLatin1String(makeCommandKeyC), m_makeCommand.toString());
+ data.insert(QLatin1String(targetAbiKeyC), m_targetAbi.toString());
+ data.insert(QLatin1String(predefinedMacrosKeyC), m_predefinedMacros);
+ data.insert(QLatin1String(headerPathsKeyC), headerPathsList());
+ data.insert(QLatin1String(cxx11FlagsKeyC), m_cxx11Flags);
+ data.insert(QLatin1String(mkspecsKeyC), mkspecs());
+
+ return data;
+}
+
+bool CustomToolChain::fromMap(const QVariantMap &data)
+{
+ if (!ToolChain::fromMap(data))
+ return false;
+
+ m_compilerCommand = FileName::fromString(data.value(QLatin1String(compilerCommandKeyC)).toString());
+ m_makeCommand = FileName::fromString(data.value(QLatin1String(makeCommandKeyC)).toString());
+ m_targetAbi = Abi(data.value(QLatin1String(targetAbiKeyC)).toString());
+ m_predefinedMacros = data.value(QLatin1String(predefinedMacrosKeyC)).toStringList();
+ setHeaderPaths(data.value(QLatin1String(headerPathsKeyC)).toStringList());
+ m_cxx11Flags = data.value(QLatin1String(cxx11FlagsKeyC)).toStringList();
+ setMkspecs(data.value(QLatin1String(mkspecsKeyC)).toString());
+
+ return true;
+}
+
+bool CustomToolChain::operator ==(const ToolChain &other) const
+{
+ if (!ToolChain::operator ==(other))
+ return false;
+
+ const CustomToolChain *customTc = static_cast<const CustomToolChain *>(&other);
+ return m_compilerCommand == customTc->m_compilerCommand
+ && m_makeCommand == customTc->m_makeCommand
+ && m_targetAbi == customTc->m_targetAbi
+ && m_predefinedMacros == customTc->m_predefinedMacros
+ && m_systemHeaderPaths == customTc->m_systemHeaderPaths;
+}
+
+ToolChainConfigWidget *CustomToolChain::configurationWidget()
+{
+ return new Internal::CustomToolChainConfigWidget(this);
+}
+
+namespace Internal {
+
+// --------------------------------------------------------------------------
+// CustomToolChainFactory
+// --------------------------------------------------------------------------
+
+QString CustomToolChainFactory::displayName() const
+{
+ return tr("Custom");
+}
+
+QString CustomToolChainFactory::id() const
+{
+ return QLatin1String(Constants::CUSTOM_TOOLCHAIN_ID);
+}
+
+bool CustomToolChainFactory::canCreate()
+{
+ return true;
+}
+
+ToolChain *CustomToolChainFactory::create()
+{
+ return createToolChain(false);
+}
+
+// Used by the ToolChainManager to restore user-generated tool chains
+bool CustomToolChainFactory::canRestore(const QVariantMap &data)
+{
+ const QString id = idFromMap(data);
+ return id.startsWith(QLatin1String(Constants::CUSTOM_TOOLCHAIN_ID) + QLatin1Char(':'));
+}
+
+ToolChain *CustomToolChainFactory::restore(const QVariantMap &data)
+{
+ CustomToolChain *tc = new CustomToolChain(false);
+ if (tc->fromMap(data))
+ return tc;
+
+ delete tc;
+ return 0;
+}
+
+CustomToolChain *CustomToolChainFactory::createToolChain(bool autoDetect)
+{
+ return new CustomToolChain(autoDetect);
+}
+
+// --------------------------------------------------------------------------
+// Helper for ConfigWidget
+// --------------------------------------------------------------------------
+
+class TextEditDetailsWidget : public DetailsWidget
+{
+ Q_DECLARE_TR_FUNCTIONS(ProjectExplorer::Internal::TextEditDetailsWidget)
+public:
+ TextEditDetailsWidget(QPlainTextEdit *textEdit)
+ {
+ setWidget(textEdit);
+ }
+
+ inline QPlainTextEdit *textEditWidget() const
+ {
+ return static_cast<QPlainTextEdit *>(widget());
+ }
+
+ inline QStringList entries() const
+ {
+ return textEditWidget()->toPlainText().split(QLatin1Char('\n'), QString::SkipEmptyParts);
+ }
+
+ // not accurate, counts empty lines (except last)
+ int entryCount() const
+ {
+ int count = textEditWidget()->blockCount();
+ QString text = textEditWidget()->toPlainText();
+ if (text.isEmpty() || text.endsWith(QLatin1Char('\n')))
+ --count;
+ return count;
+ }
+
+ void updateSummaryText()
+ {
+ int count = entryCount();
+ setSummaryText(count ? tr("%n entry(ies)", "", count) : tr("Empty"));
+ }
+};
+
+// --------------------------------------------------------------------------
+// CustomToolChainConfigWidget
+// --------------------------------------------------------------------------
+
+CustomToolChainConfigWidget::CustomToolChainConfigWidget(CustomToolChain *tc) :
+ ToolChainConfigWidget(tc),
+ m_compilerCommand(new PathChooser),
+ m_makeCommand(new PathChooser),
+ m_abiWidget(new AbiWidget),
+ m_predefinedMacros(new QPlainTextEdit),
+ m_headerPaths(new QPlainTextEdit),
+ m_predefinedDetails(new TextEditDetailsWidget(m_predefinedMacros)),
+ m_headerDetails(new TextEditDetailsWidget(m_headerPaths)),
+ m_cxx11Flags(new QLineEdit),
+ m_mkspecs(new QLineEdit)
+{
+ Q_ASSERT(tc);
+
+ m_predefinedMacros->setTabChangesFocus(true);
+ m_predefinedMacros->setToolTip(tr("Each line defines a macro. Format is MACRO[=VALUE]"));
+ m_headerPaths->setTabChangesFocus(true);
+ m_headerPaths->setToolTip(tr("Each line adds a global header lookup path"));
+ m_cxx11Flags->setToolTip(tr("Comma-separated list of flags that turn on C++11 support"));
+ m_mkspecs->setToolTip(tr("Comma-separated list of mkspecs"));
+ m_compilerCommand->setExpectedKind(PathChooser::ExistingCommand);
+ m_makeCommand->setExpectedKind(PathChooser::ExistingCommand);
+ m_mainLayout->addRow(tr("&Compiler path:"), m_compilerCommand);
+ m_mainLayout->addRow(tr("&Make path:"), m_makeCommand);
+ m_mainLayout->addRow(tr("&ABI:"), m_abiWidget);
+ m_mainLayout->addRow(tr("&Predefined macros:"), m_predefinedDetails);
+ m_mainLayout->addRow(tr("&Header paths:"), m_headerDetails);
+ m_mainLayout->addRow(tr("C++11 &flags:"), m_cxx11Flags);
+ m_mainLayout->addRow(tr("&Qt mkspecs:"), m_mkspecs);
+ addErrorLabel();
+
+ setFromToolchain();
+ m_predefinedDetails->updateSummaryText();
+ m_headerDetails->updateSummaryText();
+
+ connect(m_abiWidget, SIGNAL(abiChanged()), this, SIGNAL(dirty()));
+ connect(m_predefinedMacros, SIGNAL(textChanged()), this, SLOT(updateSummaries()));
+ connect(m_headerPaths, SIGNAL(textChanged()), this, SLOT(updateSummaries()));
+}
+
+void CustomToolChainConfigWidget::updateSummaries()
+{
+ if (sender() == m_predefinedMacros)
+ m_predefinedDetails->updateSummaryText();
+ else
+ m_headerDetails->updateSummaryText();
+}
+
+void CustomToolChainConfigWidget::applyImpl()
+{
+ if (toolChain()->isAutoDetected())
+ return;
+
+ CustomToolChain *tc = static_cast<CustomToolChain *>(toolChain());
+ Q_ASSERT(tc);
+ QString displayName = tc->displayName();
+ tc->setCompilerCommand(m_compilerCommand->fileName());
+ tc->setMakeCommand(m_makeCommand->fileName());
+ tc->setTargetAbi(m_abiWidget->currentAbi());
+ tc->setPredefinedMacros(m_predefinedDetails->entries());
+ tc->setHeaderPaths(m_headerDetails->entries());
+ tc->setCxx11Flags(m_cxx11Flags->text().split(QLatin1Char(',')));
+ tc->setMkspecs(m_mkspecs->text());
+ tc->setDisplayName(displayName); // reset display name
+}
+
+void CustomToolChainConfigWidget::setFromToolchain()
+{
+ // subwidgets are not yet connected!
+ bool blocked = blockSignals(true);
+ CustomToolChain *tc = static_cast<CustomToolChain *>(toolChain());
+ m_compilerCommand->setFileName(tc->compilerCommand());
+ m_makeCommand->setFileName(FileName::fromString(tc->makeCommand(Utils::Environment())));
+ m_abiWidget->setAbis(QList<Abi>(), tc->targetAbi());
+ m_predefinedMacros->setPlainText(tc->rawPredefinedMacros().join(QLatin1String("\n")));
+ m_headerPaths->setPlainText(tc->headerPathsList().join(QLatin1String("\n")));
+ m_cxx11Flags->setText(tc->cxx11Flags().join(QLatin1String(",")));
+ m_mkspecs->setText(tc->mkspecs());
+ blockSignals(blocked);
+}
+
+bool CustomToolChainConfigWidget::isDirtyImpl() const
+{
+ CustomToolChain *tc = static_cast<CustomToolChain *>(toolChain());
+ Q_ASSERT(tc);
+ return m_compilerCommand->fileName() != tc->compilerCommand()
+ || m_makeCommand->path() != tc->makeCommand(Utils::Environment())
+ || m_abiWidget->currentAbi() != tc->targetAbi()
+ || m_predefinedDetails->entries() != tc->rawPredefinedMacros()
+ || m_headerDetails->entries() != tc->headerPathsList()
+ || m_cxx11Flags->text().split(QLatin1Char(',')) != tc->cxx11Flags()
+ || m_mkspecs->text() != tc->mkspecs();
+}
+
+void CustomToolChainConfigWidget::makeReadOnlyImpl()
+{
+ m_mainLayout->setEnabled(false);
+}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/customtoolchain.h b/src/plugins/projectexplorer/customtoolchain.h
new file mode 100644
index 0000000000..4d56b3cc1d
--- /dev/null
+++ b/src/plugins/projectexplorer/customtoolchain.h
@@ -0,0 +1,179 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CUSTOMTOOLCHAIN_H
+#define CUSTOMTOOLCHAIN_H
+
+#include "projectexplorer_export.h"
+
+#include "abi.h"
+#include "toolchain.h"
+#include "toolchainconfigwidget.h"
+
+QT_BEGIN_NAMESPACE
+class QPlainTextEdit;
+class QTextEdit;
+QT_END_NAMESPACE
+
+namespace Utils { class PathChooser; }
+
+namespace ProjectExplorer {
+
+class AbiWidget;
+
+namespace Internal { class CustomToolChainFactory; }
+// --------------------------------------------------------------------------
+// CustomToolChain
+// --------------------------------------------------------------------------
+
+class PROJECTEXPLORER_EXPORT CustomToolChain : public ToolChain
+{
+public:
+ QString type() const;
+ QString typeDisplayName() const;
+ Abi targetAbi() const;
+ void setTargetAbi(const Abi &);
+
+ bool isValid() const;
+
+ QByteArray predefinedMacros(const QStringList &cxxflags) const;
+ CompilerFlags compilerFlags(const QStringList &cxxflags) const;
+ const QStringList &rawPredefinedMacros() const;
+ void setPredefinedMacros(const QStringList &list);
+
+ QList<HeaderPath> systemHeaderPaths(const QStringList &cxxFlags, const Utils::FileName &) const;
+ void addToEnvironment(Utils::Environment &env) const;
+ QList<Utils::FileName> suggestedMkspecList() const;
+ IOutputParser *outputParser() const;
+ QStringList headerPathsList() const;
+ void setHeaderPaths(const QStringList &list);
+
+ QVariantMap toMap() const;
+ bool fromMap(const QVariantMap &data);
+
+ ToolChainConfigWidget *configurationWidget();
+
+ bool operator ==(const ToolChain &) const;
+
+ void setCompilerCommand(const Utils::FileName &);
+ Utils::FileName compilerCommand() const;
+ void setMakeCommand(const Utils::FileName &);
+ QString makeCommand(const Utils::Environment &environment) const;
+
+ void setCxx11Flags(const QStringList &);
+ const QStringList &cxx11Flags() const;
+
+ void setMkspecs(const QString &);
+ QString mkspecs() const;
+
+ ToolChain *clone() const;
+
+protected:
+ CustomToolChain(const QString &id, bool autodetect);
+ CustomToolChain(const CustomToolChain &);
+
+private:
+ CustomToolChain(bool autodetect);
+
+ Utils::FileName m_compilerCommand;
+ Utils::FileName m_makeCommand;
+
+ Abi m_targetAbi;
+ QStringList m_predefinedMacros;
+ QList<HeaderPath> m_systemHeaderPaths;
+ QStringList m_cxx11Flags;
+ QList<Utils::FileName> m_mkspecs;
+
+ friend class Internal::CustomToolChainFactory;
+ friend class ToolChainFactory;
+};
+
+namespace Internal {
+
+class CustomToolChainFactory : public ToolChainFactory
+{
+ Q_OBJECT
+
+public:
+ // Name used to display the name of the tool chain that will be created.
+ QString displayName() const;
+ QString id() const;
+
+ bool canCreate();
+ ToolChain *create();
+
+ // Used by the ToolChainManager to restore user-generated tool chains
+ bool canRestore(const QVariantMap &data);
+ ToolChain *restore(const QVariantMap &data);
+
+protected:
+ virtual CustomToolChain *createToolChain(bool autoDetect);
+ QList<ToolChain *> autoDetectToolchains(const QString &compiler,
+ const Abi &);
+};
+
+// --------------------------------------------------------------------------
+// CustomToolChainConfigWidget
+// --------------------------------------------------------------------------
+
+class TextEditDetailsWidget;
+
+class CustomToolChainConfigWidget : public ToolChainConfigWidget
+{
+ Q_OBJECT
+
+public:
+ CustomToolChainConfigWidget(CustomToolChain *);
+
+private slots:
+ void updateSummaries();
+
+protected:
+ void applyImpl();
+ void discardImpl() { setFromToolchain(); }
+ bool isDirtyImpl() const;
+ void makeReadOnlyImpl();
+
+ void setFromToolchain();
+
+ Utils::PathChooser *m_compilerCommand;
+ Utils::PathChooser *m_makeCommand;
+ AbiWidget *m_abiWidget;
+ QPlainTextEdit *m_predefinedMacros;
+ QPlainTextEdit *m_headerPaths;
+ TextEditDetailsWidget *m_predefinedDetails;
+ TextEditDetailsWidget *m_headerDetails;
+ QLineEdit *m_cxx11Flags;
+ QLineEdit *m_mkspecs;
+};
+
+} // namespace Internal
+} // namespace ProjectExplorer
+
+#endif // CUSTOMTOOLCHAIN_H
diff --git a/src/plugins/projectexplorer/customwizard/customwizard.cpp b/src/plugins/projectexplorer/customwizard/customwizard.cpp
index 94675455f9..5bb18802e6 100644
--- a/src/plugins/projectexplorer/customwizard/customwizard.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizard.cpp
@@ -144,7 +144,7 @@ void CustomWizard::initWizardDialog(Utils::Wizard *wizard, const QString &defaul
addWizardPage(wizard, customPage, parameters()->firstPageId);
if (!parameters()->fieldPageTitle.isEmpty())
customPage->setTitle(parameters()->fieldPageTitle);
- foreach(QWizardPage *ep, extensionPages)
+ foreach (QWizardPage *ep, extensionPages)
BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(ep));
Core::BaseFileWizard::setupWizard(wizard);
if (CustomWizardPrivate::verbose)
@@ -314,7 +314,7 @@ Core::GeneratedFiles CustomWizard::generateWizardFiles(QString *errorMessage) co
return rc;
}
// Add the template files specified by the <file> elements.
- foreach(const Internal::CustomWizardFile &file, d->m_parameters->files)
+ foreach (const Internal::CustomWizardFile &file, d->m_parameters->files)
if (!createFile(file, d->m_parameters->directory, ctx->targetPath, context()->replacements, &rc, errorMessage))
return Core::GeneratedFiles();
return rc;
@@ -449,7 +449,7 @@ QList<CustomWizard*> CustomWizard::createWizards()
const QString configFile = QLatin1String(configFileC);
// Check and parse config file in each directory.
- foreach(const QFileInfo &dirFi, dirs) {
+ foreach (const QFileInfo &dirFi, dirs) {
const QDir dir(dirFi.absoluteFilePath());
if (CustomWizardPrivate::verbose)
verboseLog += QString::fromLatin1("CustomWizard: Scanning %1\n").arg(dirFi.absoluteFilePath());
@@ -465,11 +465,10 @@ QList<CustomWizard*> CustomWizard::createWizards()
<< baseFileParameters.category() << " / " <<baseFileParameters.displayCategory() << '\n'
<< " (" << baseFileParameters.description() << ")\n"
<< parameters->toString();
- if (CustomWizard *w = createWizard(parameters, baseFileParameters)) {
+ if (CustomWizard *w = createWizard(parameters, baseFileParameters))
rc.push_back(w);
- } else {
+ else
qWarning("Custom wizard factory function failed for %s", qPrintable(baseFileParameters.id()));
- }
break;
case Internal::CustomWizardParameters::ParseDisabled:
if (CustomWizardPrivate::verbose)
@@ -548,7 +547,7 @@ void CustomProjectWizard::initProjectWizardDialog(BaseProjectWizardDialog *w,
if (!pa->fieldPageTitle.isEmpty())
cp->setTitle(pa->fieldPageTitle);
}
- foreach(QWizardPage *ep, extensionPages)
+ foreach (QWizardPage *ep, extensionPages)
BaseFileWizard::applyExtensionPageShortTitle(w, w->addPage(ep));
w->setPath(defaultPath);
w->setProjectName(BaseProjectWizardDialog::uniqueProjectName(defaultPath));
@@ -584,11 +583,10 @@ Core::GeneratedFiles CustomProjectWizard::generateFiles(const QWizard *w, QStrin
bool CustomProjectWizard::postGenerateOpen(const Core::GeneratedFiles &l, QString *errorMessage)
{
// Post-Generate: Open the project and the editors as desired
- foreach(const Core::GeneratedFile &file, l) {
+ foreach (const Core::GeneratedFile &file, l) {
if (file.attributes() & Core::GeneratedFile::OpenProjectAttribute) {
- if (!ProjectExplorer::ProjectExplorerPlugin::instance()->openProject(file.path(), errorMessage)) {
+ if (!ProjectExplorer::ProjectExplorerPlugin::instance()->openProject(file.path(), errorMessage))
return false;
- }
}
}
return BaseFileWizard::postGenerateOpenEditors(l, errorMessage);
diff --git a/src/plugins/projectexplorer/customwizard/customwizardpage.cpp b/src/plugins/projectexplorer/customwizard/customwizardpage.cpp
index 5651ab774c..5e4f221785 100644
--- a/src/plugins/projectexplorer/customwizard/customwizardpage.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizardpage.cpp
@@ -181,7 +181,7 @@ CustomWizardFieldPage::CustomWizardFieldPage(const QSharedPointer<CustomWizardCo
m_formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
if (debug)
qDebug() << Q_FUNC_INFO << parameters->fields.size();
- foreach(const CustomWizardField &f, parameters->fields)
+ foreach (const CustomWizardField &f, parameters->fields)
addField(f);
vLayout->addLayout(m_formLayout);
m_errorLabel->setVisible(false);
@@ -239,11 +239,10 @@ void CustomWizardFieldPage::addField(const CustomWizardField &field)\
} else {
fieldWidget = registerLineEdit(fieldName, field);
}
- if (spansRow) {
+ if (spansRow)
m_formLayout->addRow(fieldWidget);
- } else {
+ else
addRow(field.description, fieldWidget);
- }
}
// Return the list of values and display texts for combo
@@ -345,11 +344,10 @@ QWidget *CustomWizardFieldPage::registerLineEdit(const QString &fieldName,
const QString validationRegExp = field.controlAttributes.value(QLatin1String("validator"));
if (!validationRegExp.isEmpty()) {
QRegExp re(validationRegExp);
- if (re.isValid()) {
+ if (re.isValid())
lineEdit->setValidator(new QRegExpValidator(re, lineEdit));
- } else {
+ else
qWarning("Invalid custom wizard field validator regular expression %s.", qPrintable(validationRegExp));
- }
}
registerField(fieldName, lineEdit, "text", SIGNAL(textEdited(QString)));
@@ -362,7 +360,7 @@ void CustomWizardFieldPage::initializePage()
{
QWizardPage::initializePage();
clearError();
- foreach(const LineEditData &led, m_lineEdits) {
+ foreach (const LineEditData &led, m_lineEdits) {
if (!led.userChange.isNull()) {
led.lineEdit->setText(led.userChange);
} else if (!led.defaultText.isEmpty()) {
@@ -371,7 +369,7 @@ void CustomWizardFieldPage::initializePage()
led.lineEdit->setText(defaultText);
}
}
- foreach(const TextEditData &ted, m_textEdits) {
+ foreach (const TextEditData &ted, m_textEdits) {
if (!ted.userChange.isNull()) {
ted.textEdit->setText(ted.userChange);
} else if (!ted.defaultText.isEmpty()) {
@@ -428,7 +426,7 @@ bool CustomWizardFieldPage::validatePage()
{
clearError();
// Check line edits with validators
- foreach(const LineEditData &led, m_lineEdits) {
+ foreach (const LineEditData &led, m_lineEdits) {
if (const QValidator *val = led.lineEdit->validator()) {
int pos = 0;
QString text = led.lineEdit->text();
@@ -456,7 +454,7 @@ QMap<QString, QString> CustomWizardFieldPage::replacementMap(const QWizard *w,
const FieldList &f)
{
QMap<QString, QString> fieldReplacementMap = ctx->baseReplacements;
- foreach(const Internal::CustomWizardField &field, f) {
+ foreach (const Internal::CustomWizardField &field, f) {
const QString value = w->field(field.name).toString();
fieldReplacementMap.insert(field.name, value);
}
diff --git a/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp b/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp
index d5764832f2..37e8a25c07 100644
--- a/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp
@@ -52,6 +52,8 @@
enum { debug = 0 };
+using namespace Core;
+
static const char customWizardElementC[] = "wizard";
static const char iconElementC[] = "icon";
static const char descriptionElementC[] = "description";
@@ -175,7 +177,7 @@ bool CustomWizardValidationRule::validateRules(const QList<CustomWizardValidatio
if (rules.isEmpty())
return true;
QScriptEngine engine;
- foreach(const CustomWizardValidationRule &rule, rules)
+ foreach (const CustomWizardValidationRule &rule, rules)
if (!rule.validate(engine, replacementMap)) {
*errorMessage = rule.message;
CustomWizardContext::replaceFields(replacementMap, errorMessage);
@@ -271,8 +273,8 @@ static inline bool assignLanguageElementText(QXmlStreamReader &reader,
// as an exercise to the reader.
static inline bool assignLanguageElementText(QXmlStreamReader &reader,
const QString &desiredLanguage,
- Core::BaseFileWizardParameters *bp,
- void (Core::BaseFileWizardParameters::*setter)(const QString &))
+ BaseFileWizardParameters *bp,
+ void (BaseFileWizardParameters::*setter)(const QString &))
{
const QStringRef elementLanguage = reader.attributes().value(QLatin1String(langAttributeC));
if (elementLanguage.isEmpty()) {
@@ -295,7 +297,7 @@ static bool parseCustomProjectElement(QXmlStreamReader &reader,
const QString &configFileFullPath,
const QString &language,
CustomWizardParameters *p,
- Core::BaseFileWizardParameters *bp)
+ BaseFileWizardParameters *bp)
{
const QStringRef elementName = reader.name();
if (elementName == QLatin1String(iconElementC)) {
@@ -311,17 +313,17 @@ static bool parseCustomProjectElement(QXmlStreamReader &reader,
}
if (elementName == QLatin1String(descriptionElementC)) {
assignLanguageElementText(reader, language, bp,
- &Core::BaseFileWizardParameters::setDescription);
+ &BaseFileWizardParameters::setDescription);
return true;
}
if (elementName == QLatin1String(displayNameElementC)) {
assignLanguageElementText(reader, language, bp,
- &Core::BaseFileWizardParameters::setDisplayName);
+ &BaseFileWizardParameters::setDisplayName);
return true;
}
if (elementName == QLatin1String(displayCategoryElementC)) {
assignLanguageElementText(reader, language, bp,
- &Core::BaseFileWizardParameters::setDisplayCategory);
+ &BaseFileWizardParameters::setDisplayCategory);
return true;
}
if (elementName == QLatin1String(fieldPageTitleElementC)) {
@@ -334,7 +336,7 @@ static bool parseCustomProjectElement(QXmlStreamReader &reader,
static inline QMap<QString, QString> attributesToStringMap(const QXmlStreamAttributes &attributes)
{
QMap<QString, QString> rc;
- foreach(const QXmlStreamAttribute &attribute, attributes)
+ foreach (const QXmlStreamAttribute &attribute, attributes)
rc.insert(attribute.name().toString(), attribute.value().toString());
return rc;
}
@@ -473,38 +475,38 @@ static ParseState nextClosingState(ParseState in, const QStringRef &name)
}
// Parse kind attribute
-static inline Core::IWizard::WizardKind kindAttribute(const QXmlStreamReader &r)
+static inline IWizard::WizardKind kindAttribute(const QXmlStreamReader &r)
{
const QStringRef value = r.attributes().value(QLatin1String(kindAttributeC));
if (!value.isEmpty()) {
if (value == QLatin1String("file"))
- return Core::IWizard::FileWizard;
+ return IWizard::FileWizard;
if (value == QLatin1String("class"))
- return Core::IWizard::ClassWizard;
+ return IWizard::ClassWizard;
}
- return Core::IWizard::ProjectWizard;
+ return IWizard::ProjectWizard;
}
-static inline Core::FeatureSet requiredFeatures(const QXmlStreamReader &reader)
+static inline FeatureSet requiredFeatures(const QXmlStreamReader &reader)
{
- Core::FeatureSet r;
+ FeatureSet r;
QString value = reader.attributes().value(QLatin1String(featuresRequiredC)).toString();
QStringList stringList = value.split(QLatin1Char(','), QString::SkipEmptyParts);
- Core::FeatureSet features;
+ FeatureSet features;
foreach (const QString &string, stringList) {
- Core::Feature feature(string);
+ Feature feature(Id::fromString(string));
features |= feature;
}
return features;
}
-static inline Core::IWizard::WizardFlags wizardFlags(const QXmlStreamReader &reader)
+static inline IWizard::WizardFlags wizardFlags(const QXmlStreamReader &reader)
{
- Core::IWizard::WizardFlags flags;
+ IWizard::WizardFlags flags;
QString value = reader.attributes().value(QLatin1String(platformIndependentC)).toString();
if (!value.isEmpty() && value == QLatin1String("true"))
- flags |= Core::IWizard::PlatformIndependent;
+ flags |= IWizard::PlatformIndependent;
return flags;
}
@@ -549,7 +551,7 @@ static inline QString attributeValue(const QXmlStreamReader &r, const char *name
// Return locale language attribute "de_UTF8" -> "de", empty string for "C"
static inline QString languageSetting()
{
- QString name = Core::ICore::userInterfaceLanguage();
+ QString name = ICore::userInterfaceLanguage();
const int underScorePos = name.indexOf(QLatin1Char('_'));
if (underScorePos != -1)
name.truncate(underScorePos);
@@ -577,7 +579,7 @@ GeneratorScriptArgument::GeneratorScriptArgument(const QString &v) :
CustomWizardParameters::ParseResult
CustomWizardParameters::parse(QIODevice &device,
const QString &configFileFullPath,
- Core::BaseFileWizardParameters *bp,
+ BaseFileWizardParameters *bp,
QString *errorMessage)
{
int comboEntryCount = 0;
@@ -586,7 +588,7 @@ CustomWizardParameters::ParseResult
ParseState state = ParseBeginning;
clear();
bp->clear();
- bp->setKind(Core::IWizard::ProjectWizard);
+ bp->setKind(IWizard::ProjectWizard);
const QString language = languageSetting();
CustomWizardField field;
do {
@@ -657,11 +659,10 @@ CustomWizardParameters::ParseResult
file.binary = booleanAttributeValue(reader, fileBinaryAttributeC, false);
if (file.target.isEmpty())
file.target = file.source;
- if (file.source.isEmpty()) {
+ if (file.source.isEmpty())
qWarning("Skipping empty file name in custom project.");
- } else {
+ else
files.push_back(file);
- }
}
break;
case ParseWithinScript:
@@ -730,7 +731,7 @@ CustomWizardParameters::ParseResult
CustomWizardParameters::ParseResult
CustomWizardParameters::parse(const QString &configFileFullPath,
- Core::BaseFileWizardParameters *bp,
+ BaseFileWizardParameters *bp,
QString *errorMessage)
{
QFile configFile(configFileFullPath);
@@ -748,12 +749,12 @@ QString CustomWizardParameters::toString() const
str << "Directory: " << directory << " Klass: '" << klass << "'\n";
if (!filesGeneratorScriptArguments.isEmpty()) {
str << "Script:";
- foreach(const QString &a, filesGeneratorScript)
+ foreach (const QString &a, filesGeneratorScript)
str << " '" << a << '\'';
if (!filesGeneratorScriptWorkingDirectory.isEmpty())
str << "\nrun in '" << filesGeneratorScriptWorkingDirectory << '\'';
str << "\nArguments: ";
- foreach(const GeneratorScriptArgument &a, filesGeneratorScriptArguments) {
+ foreach (const GeneratorScriptArgument &a, filesGeneratorScriptArguments) {
str << " '" << a.value << '\'';
if (a.flags & GeneratorScriptArgument::OmitEmpty)
str << " [omit empty]";
@@ -763,7 +764,7 @@ QString CustomWizardParameters::toString() const
}
str << '\n';
}
- foreach(const CustomWizardFile &f, files) {
+ foreach (const CustomWizardFile &f, files) {
str << " File source: " << f.source << " Target: " << f.target;
if (f.openEditor)
str << " [editor]";
@@ -773,7 +774,7 @@ QString CustomWizardParameters::toString() const
str << " [binary]";
str << '\n';
}
- foreach(const CustomWizardField &f, fields) {
+ foreach (const CustomWizardField &f, fields) {
str << " Field name: " << f.name;
if (f.mandatory)
str << '*';
@@ -787,7 +788,7 @@ QString CustomWizardParameters::toString() const
}
str << '\n';
}
- foreach(const CustomWizardValidationRule &r, rules)
+ foreach (const CustomWizardValidationRule &r, rules)
str << " Rule: '" << r.condition << "'->'" << r.message << '\n';
return rc;
}
@@ -995,7 +996,7 @@ void CustomWizardContext::reset()
{
// Basic replacement fields: Suffixes.
baseReplacements.clear();
- const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
+ const MimeDatabase *mdb = ICore::mimeDatabase();
baseReplacements.insert(QLatin1String("CppSourceSuffix"),
mdb->preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)));
baseReplacements.insert(QLatin1String("CppHeaderSuffix"),
diff --git a/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp b/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp
index 53e95331b6..db638aecaa 100644
--- a/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp
+++ b/src/plugins/projectexplorer/customwizard/customwizardscriptgenerator.cpp
@@ -31,6 +31,7 @@
#include "customwizard.h"
#include "customwizardparameters.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QProcess>
@@ -65,15 +66,16 @@ QStringList fixGeneratorScript(const QString &configFile, QString binary)
}
} // not absolute
QStringList rc(binary);
-#ifdef Q_OS_WIN // Windows: Cannot run scripts by QProcess, do 'cmd /c'
- const QString extension = binaryInfo.suffix();
- if (!extension.isEmpty() && extension.compare(QLatin1String("exe"), Qt::CaseInsensitive) != 0) {
- rc.push_front(QLatin1String("/C"));
- rc.push_front(QString::fromLocal8Bit(qgetenv("COMSPEC")));
- if (rc.front().isEmpty())
- rc.front() = QLatin1String("cmd.exe");
+ if (Utils::HostOsInfo::isWindowsHost()) { // Windows: Cannot run scripts by QProcess, do 'cmd /c'
+ const QString extension = binaryInfo.suffix();
+ if (!extension.isEmpty() && extension.compare(QLatin1String("exe"),
+ Qt::CaseInsensitive) != 0) {
+ rc.push_front(QLatin1String("/C"));
+ rc.push_front(QString::fromLocal8Bit(qgetenv("COMSPEC")));
+ if (rc.front().isEmpty())
+ rc.front() = QLatin1String("cmd.exe");
+ }
}
-#endif
return rc;
}
@@ -200,7 +202,7 @@ Core::GeneratedFiles
if (CustomWizard::verbose()) {
QDebug nospace = qDebug().nospace();
nospace << script << " generated:\n";
- foreach(const Core::GeneratedFile &f, files)
+ foreach (const Core::GeneratedFile &f, files)
nospace << ' ' << f.path() << f.attributes() << '\n';
}
return files;
diff --git a/src/plugins/projectexplorer/dependenciespanel.cpp b/src/plugins/projectexplorer/dependenciespanel.cpp
index 2285b6c965..f8585de795 100644
--- a/src/plugins/projectexplorer/dependenciespanel.cpp
+++ b/src/plugins/projectexplorer/dependenciespanel.cpp
@@ -81,9 +81,10 @@ DependenciesModel::~DependenciesModel()
void DependenciesModel::resetModel()
{
+ beginResetModel();
m_projects = m_session->projects();
m_projects.removeAll(m_project);
- reset();
+ endResetModel();
}
int DependenciesModel::rowCount(const QModelIndex &index) const
@@ -213,9 +214,8 @@ void DependenciesView::updateSizeHint()
int heightOffset = size().height() - viewport()->height();
int heightPerRow = sizeHintForRow(0);
- if (heightPerRow == -1) {
+ if (heightPerRow == -1)
heightPerRow = 30;
- }
int rows = qMin(qMax(model()->rowCount(), 2), 10);
int height = rows * heightPerRow + heightOffset;
if (m_sizeHint.height() != height) {
diff --git a/src/plugins/projectexplorer/deployconfiguration.cpp b/src/plugins/projectexplorer/deployconfiguration.cpp
index 1cbcb8e7a7..e88bfb2b9e 100644
--- a/src/plugins/projectexplorer/deployconfiguration.cpp
+++ b/src/plugins/projectexplorer/deployconfiguration.cpp
@@ -64,7 +64,8 @@ DeployConfiguration::DeployConfiguration(Target *target, const Core::Id id) :
}
DeployConfiguration::DeployConfiguration(Target *target, DeployConfiguration *source) :
- ProjectConfiguration(target, source)
+ ProjectConfiguration(target, source),
+ m_stepList(0)
{
Q_ASSERT(target);
// Do not clone stepLists here, do that in the derived constructor instead
@@ -90,7 +91,7 @@ QVariantMap DeployConfiguration::toMap() const
return map;
}
-DeployConfigurationWidget *DeployConfiguration::configurationWidget() const
+NamedWidget *DeployConfiguration::createConfigWidget()
{
return 0;
}
@@ -150,6 +151,21 @@ void DeployConfiguration::cloneSteps(DeployConfiguration *source)
}
///
+// DefaultDeployConfiguration
+///
+DefaultDeployConfiguration::DefaultDeployConfiguration(Target *target, const Core::Id id)
+ : DeployConfiguration(target, id)
+{
+
+}
+
+DefaultDeployConfiguration::DefaultDeployConfiguration(Target *target, DeployConfiguration *source)
+ : DeployConfiguration(target, source)
+{
+ cloneSteps(source);
+}
+
+///
// DeployConfigurationFactory
///
@@ -186,7 +202,7 @@ DeployConfiguration *DeployConfigurationFactory::create(Target *parent, const Co
{
if (!canCreate(parent, id))
return 0;
- return new DeployConfiguration(parent, id);
+ return new DefaultDeployConfiguration(parent, id);
}
bool DeployConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
@@ -198,7 +214,7 @@ DeployConfiguration *DeployConfigurationFactory::restore(Target *parent, const Q
{
if (!canRestore(parent, map))
return 0;
- DeployConfiguration *dc = new DeployConfiguration(parent, idFromMap(map));
+ DefaultDeployConfiguration *dc = new DefaultDeployConfiguration(parent, idFromMap(map));
if (!dc->fromMap(map)) {
delete dc;
return 0;
@@ -215,7 +231,7 @@ DeployConfiguration *DeployConfigurationFactory::clone(Target *parent, DeployCon
{
if (!canClone(parent, product))
return 0;
- return new DeployConfiguration(parent, product);
+ return new DefaultDeployConfiguration(parent, product);
}
DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, const QVariantMap &map)
@@ -240,16 +256,20 @@ DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent)
return 0;
}
+DeployConfigurationFactory *DeployConfigurationFactory::find(Target *parent, DeployConfiguration *dc)
+{
+ QList<DeployConfigurationFactory *> factories
+ = ExtensionSystem::PluginManager::instance()->getObjects<DeployConfigurationFactory>();
+ foreach (DeployConfigurationFactory *factory, factories) {
+ if (factory->canClone(parent, dc))
+ return factory;
+ }
+ return 0;
+}
+
bool DeployConfigurationFactory::canHandle(Target *parent) const
{
if (!parent->project()->supportsKit(parent->kit()))
return false;
return DeviceTypeKitInformation::deviceTypeId(parent->kit()) == Constants::DESKTOP_DEVICE_TYPE;
}
-
-///
-// DeployConfigurationWidget
-///
-
-DeployConfigurationWidget::DeployConfigurationWidget(QWidget *parent) : NamedWidget(parent)
-{ }
diff --git a/src/plugins/projectexplorer/deployconfiguration.h b/src/plugins/projectexplorer/deployconfiguration.h
index ecc00f0047..f71d67c173 100644
--- a/src/plugins/projectexplorer/deployconfiguration.h
+++ b/src/plugins/projectexplorer/deployconfiguration.h
@@ -44,7 +44,7 @@ namespace ProjectExplorer {
class BuildStepList;
class Target;
class DeployConfigurationFactory;
-class DeployConfigurationWidget;
+class NamedWidget;
class PROJECTEXPLORER_EXPORT DeployConfiguration : public ProjectConfiguration
{
@@ -58,7 +58,7 @@ public:
virtual QVariantMap toMap() const;
- virtual DeployConfigurationWidget *configurationWidget() const;
+ virtual NamedWidget *createConfigWidget();
virtual bool isEnabled() const;
virtual QString disabledReason() const;
@@ -77,11 +77,18 @@ protected:
bool fromMap(const QVariantMap &map);
private:
- friend class DeployConfigurationFactory;
-
BuildStepList *m_stepList;
};
+class PROJECTEXPLORER_EXPORT DefaultDeployConfiguration : public DeployConfiguration
+{
+ Q_OBJECT
+ friend class DeployConfigurationFactory; // for the ctors
+protected:
+ DefaultDeployConfiguration(Target *target, const Core::Id id);
+ DefaultDeployConfiguration(Target *target, DeployConfiguration *source);
+};
+
class PROJECTEXPLORER_EXPORT DeployConfigurationFactory :
public QObject
{
@@ -106,6 +113,7 @@ public:
static DeployConfigurationFactory *find(Target *parent, const QVariantMap &map);
static DeployConfigurationFactory *find(Target *parent);
+ static DeployConfigurationFactory *find(Target *parent, DeployConfiguration *dc);
signals:
void availableCreationIdsChanged();
@@ -116,17 +124,6 @@ protected:
private:
};
-class PROJECTEXPLORER_EXPORT DeployConfigurationWidget : public NamedWidget
-{
- Q_OBJECT
-
-public:
- explicit DeployConfigurationWidget(QWidget *parent = 0);
-
- // This is called to set up the config widget before showing it
- virtual void init(DeployConfiguration *dc) = 0;
-};
-
} // namespace ProjectExplorer
Q_DECLARE_METATYPE(ProjectExplorer::DeployConfiguration *)
diff --git a/src/plugins/projectexplorer/deployconfigurationmodel.cpp b/src/plugins/projectexplorer/deployconfigurationmodel.cpp
index ab226ad776..3e948d3790 100644
--- a/src/plugins/projectexplorer/deployconfigurationmodel.cpp
+++ b/src/plugins/projectexplorer/deployconfigurationmodel.cpp
@@ -126,9 +126,8 @@ QVariant DeployConfigurationModel::data(const QModelIndex &index, int role) cons
{
if (role == Qt::DisplayRole) {
const int row = index.row();
- if (row < m_deployConfigurations.size()) {
+ if (row < m_deployConfigurations.size())
return m_deployConfigurations.at(row)->displayName();
- }
}
return QVariant();
@@ -162,9 +161,8 @@ void DeployConfigurationModel::addedDeployConfiguration(ProjectExplorer::DeployC
DeployConfigurationComparer compare;
int i = 0;
for (; i < m_deployConfigurations.size(); ++i) {
- if (compare(dc, m_deployConfigurations.at(i))) {
+ if (compare(dc, m_deployConfigurations.at(i)))
break;
- }
}
beginInsertRows(QModelIndex(), i, i);
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
index 993535d9d5..24c879a814 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicemanager.cpp
@@ -230,7 +230,6 @@ Utils::FileName DeviceManager::settingsFilePath(const QString &extension)
void DeviceManager::addDevice(const IDevice::Ptr &_device)
{
const IDevice::Ptr device = _device->clone();
- QTC_ASSERT(this != instance() || device->isAutoDetected(), return);
QString name = device->displayName();
const int pos = d->indexForId(device->id());
@@ -383,15 +382,13 @@ IDevice::ConstPtr DeviceManager::findInactiveAutoDetectedDevice(Core::Id type, C
IDevice::ConstPtr DeviceManager::defaultDevice(Core::Id deviceType) const
{
- const Core::Id id = d->defaultDevices.value(deviceType, IDevice::invalidId());
- if (id == IDevice::invalidId())
- return IDevice::ConstPtr();
- return find(id);
+ const Core::Id id = d->defaultDevices.value(deviceType);
+ return id.isValid() ? find(id) : IDevice::ConstPtr();
}
Core::Id DeviceManager::deviceId(const IDevice::ConstPtr &device) const
{
- return device ? device->id() : IDevice::invalidId();
+ return device ? device->id() : Core::Id();
}
void DeviceManager::ensureOneDefaultDevicePerType()
diff --git a/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp b/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp
index 72df33961b..97e35c8bf7 100644
--- a/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicemanagermodel.cpp
@@ -93,9 +93,7 @@ IDevice::ConstPtr DeviceManagerModel::device(int pos) const
Core::Id DeviceManagerModel::deviceId(int pos) const
{
IDevice::ConstPtr dev = device(pos);
- if (dev.isNull())
- return IDevice::invalidId();
- return dev->id();
+ return dev ? dev->id() : Core::Id();
}
int DeviceManagerModel::indexOf(IDevice::ConstPtr dev) const
diff --git a/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp b/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp
index a7727bb6b9..c1d7a61f81 100644
--- a/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp
+++ b/src/plugins/projectexplorer/devicesupport/devicesettingspage.cpp
@@ -42,9 +42,9 @@ namespace Internal {
DeviceSettingsPage::DeviceSettingsPage(QObject *parent)
: Core::IOptionsPage(parent)
{
- setId(QLatin1String(Constants::DEVICE_SETTINGS_PAGE_ID));
+ setId(Constants::DEVICE_SETTINGS_PAGE_ID);
setDisplayName(tr("Devices"));
- setCategory(QLatin1String(Constants::DEVICE_SETTINGS_CATEGORY));
+ setCategory(Constants::DEVICE_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer", "Devices"));
setCategoryIcon(QLatin1String(":/projectexplorer/images/MaemoDevice.png"));
}
diff --git a/src/plugins/projectexplorer/devicesupport/idevice.cpp b/src/plugins/projectexplorer/devicesupport/idevice.cpp
index 90a03c8a84..b2306b86ee 100644
--- a/src/plugins/projectexplorer/devicesupport/idevice.cpp
+++ b/src/plugins/projectexplorer/devicesupport/idevice.cpp
@@ -141,7 +141,7 @@
static Core::Id newId()
{
- return Core::Id(QUuid::createUuid().toString());
+ return Core::Id::fromString(QUuid::createUuid().toString());
}
namespace ProjectExplorer {
@@ -278,43 +278,35 @@ void IDevice::setDeviceState(const IDevice::DeviceState state)
d->deviceState = state;
}
-Core::Id IDevice::invalidId()
-{
- return Core::Id();
-}
-
Core::Id IDevice::typeFromMap(const QVariantMap &map)
{
- const QString idStr = map.value(QLatin1String(TypeKey)).toString();
- if (idStr.isEmpty())
- return Core::Id();
- return Core::Id(idStr);
+ return Core::Id::fromSetting(map.value(QLatin1String(TypeKey)));
}
Core::Id IDevice::idFromMap(const QVariantMap &map)
{
- return Core::Id(map.value(QLatin1String(IdKey)).toString());
+ return Core::Id::fromSetting(map.value(QLatin1String(IdKey)));
}
void IDevice::fromMap(const QVariantMap &map)
{
d->type = typeFromMap(map);
d->displayName = map.value(QLatin1String(DisplayNameKey)).toString();
- d->id = Core::Id(map.value(QLatin1String(IdKey), newId().name()).toByteArray().constData());
+ d->id = Core::Id(map.value(QLatin1String(IdKey), newId().name()).toByteArray());
d->origin = static_cast<Origin>(map.value(QLatin1String(OriginKey), ManuallyAdded).toInt());
- d->sshParameters.host = map.value(HostKey).toString();
- d->sshParameters.port = map.value(SshPortKey, 22).toInt();
- d->sshParameters.userName = map.value(UserNameKey).toString();
+ d->sshParameters.host = map.value(QLatin1String(HostKey)).toString();
+ d->sshParameters.port = map.value(QLatin1String(SshPortKey), 22).toInt();
+ d->sshParameters.userName = map.value(QLatin1String(UserNameKey)).toString();
d->sshParameters.authenticationType
- = static_cast<AuthType>(map.value(AuthKey, DefaultAuthType).toInt());
- d->sshParameters.password = map.value(PasswordKey).toString();
- d->sshParameters.privateKeyFile = map.value(KeyFileKey, defaultPrivateKeyFilePath()).toString();
- d->sshParameters.timeout = map.value(TimeoutKey, DefaultTimeout).toInt();
+ = static_cast<AuthType>(map.value(QLatin1String(AuthKey), DefaultAuthType).toInt());
+ d->sshParameters.password = map.value(QLatin1String(PasswordKey)).toString();
+ d->sshParameters.privateKeyFile = map.value(QLatin1String(KeyFileKey), defaultPrivateKeyFilePath()).toString();
+ d->sshParameters.timeout = map.value(QLatin1String(TimeoutKey), DefaultTimeout).toInt();
- d->freePorts = Utils::PortList::fromString(map.value(PortsSpecKey,
+ d->freePorts = Utils::PortList::fromString(map.value(QLatin1String(PortsSpecKey),
QLatin1String("10000-10100")).toString());
- d->machineType = static_cast<MachineType>(map.value(MachineTypeKey, DefaultMachineType).toInt());
+ d->machineType = static_cast<MachineType>(map.value(QLatin1String(MachineTypeKey), DefaultMachineType).toInt());
}
QVariantMap IDevice::toMap() const
@@ -325,16 +317,16 @@ QVariantMap IDevice::toMap() const
map.insert(QLatin1String(IdKey), d->id.name());
map.insert(QLatin1String(OriginKey), d->origin);
- map.insert(MachineTypeKey, d->machineType);
- map.insert(HostKey, d->sshParameters.host);
- map.insert(SshPortKey, d->sshParameters.port);
- map.insert(UserNameKey, d->sshParameters.userName);
- map.insert(AuthKey, d->sshParameters.authenticationType);
- map.insert(PasswordKey, d->sshParameters.password);
- map.insert(KeyFileKey, d->sshParameters.privateKeyFile);
- map.insert(TimeoutKey, d->sshParameters.timeout);
+ map.insert(QLatin1String(MachineTypeKey), d->machineType);
+ map.insert(QLatin1String(HostKey), d->sshParameters.host);
+ map.insert(QLatin1String(SshPortKey), d->sshParameters.port);
+ map.insert(QLatin1String(UserNameKey), d->sshParameters.userName);
+ map.insert(QLatin1String(AuthKey), d->sshParameters.authenticationType);
+ map.insert(QLatin1String(PasswordKey), d->sshParameters.password);
+ map.insert(QLatin1String(KeyFileKey), d->sshParameters.privateKeyFile);
+ map.insert(QLatin1String(TimeoutKey), d->sshParameters.timeout);
- map.insert(PortsSpecKey, d->freePorts.toString());
+ map.insert(QLatin1String(PortsSpecKey), d->freePorts.toString());
return map;
}
diff --git a/src/plugins/projectexplorer/devicesupport/idevice.h b/src/plugins/projectexplorer/devicesupport/idevice.h
index 9a6ce16cfe..cc66de599c 100644
--- a/src/plugins/projectexplorer/devicesupport/idevice.h
+++ b/src/plugins/projectexplorer/devicesupport/idevice.h
@@ -125,8 +125,6 @@ public:
virtual QVariantMap toMap() const;
virtual Ptr clone() const = 0;
- static Core::Id invalidId();
-
static Core::Id typeFromMap(const QVariantMap &map);
static Core::Id idFromMap(const QVariantMap &map);
diff --git a/src/plugins/projectexplorer/doubletabwidget.cpp b/src/plugins/projectexplorer/doubletabwidget.cpp
index 5fade0c6f7..d6fa832563 100644
--- a/src/plugins/projectexplorer/doubletabwidget.cpp
+++ b/src/plugins/projectexplorer/doubletabwidget.cpp
@@ -201,11 +201,10 @@ void DoubleTabWidget::removeTab(int index)
--m_currentIndex;
if (m_currentIndex < 0 && m_tabs.size() > 0)
m_currentIndex = 0;
- if (m_currentIndex < 0) {
+ if (m_currentIndex < 0)
emit currentIndexChanged(-1, -1);
- } else {
+ else
emit currentIndexChanged(m_currentIndex, m_tabs.at(m_currentIndex).currentSubTab);
- }
}
update();
}
@@ -233,18 +232,16 @@ QPair<DoubleTabWidget::HitArea, int> DoubleTabWidget::convertPosToTab(QPoint pos
for (i = 0; i <= m_lastVisibleIndex; ++i) {
int otherX = x + 2 * MARGIN + fm.width(m_tabs.at(
m_currentTabIndices.at(i)).displayName());
- if (eventX > x && eventX < otherX) {
+ if (eventX > x && eventX < otherX)
break;
- }
x = otherX;
}
if (i <= m_lastVisibleIndex) {
return qMakePair(HITTAB, i);
} else if (m_lastVisibleIndex < m_tabs.size() - 1) {
// handle overflow menu
- if (eventX > x && eventX < x + OVERFLOW_DROPDOWN_WIDTH) {
+ if (eventX > x && eventX < x + OVERFLOW_DROPDOWN_WIDTH)
return qMakePair(HITOVERFLOW, -1);
- }
}
} else if (pos.y() < Utils::StyleHelper::navigationWidgetHeight() + OTHER_HEIGHT) {
int diff = (OTHER_HEIGHT - SELECTION_IMAGE_HEIGHT) / 2;
@@ -264,14 +261,12 @@ QPair<DoubleTabWidget::HitArea, int> DoubleTabWidget::convertPosToTab(QPoint pos
int i;
for (i = 0; i < subTabs.size(); ++i) {
int otherX = x + 2 * SELECTION_IMAGE_WIDTH + fm.width(subTabs.at(i));
- if (eventX > x && eventX < otherX) {
+ if (eventX > x && eventX < otherX)
break;
- }
x = otherX + 2 * MARGIN;
}
- if (i < subTabs.size()) {
+ if (i < subTabs.size())
return qMakePair(HITSUBTAB, i);
- }
}
return qMakePair(HITNOTHING, -1);
}
diff --git a/src/plugins/projectexplorer/editorconfiguration.cpp b/src/plugins/projectexplorer/editorconfiguration.cpp
index 4fd896e95d..a583f15f32 100644
--- a/src/plugins/projectexplorer/editorconfiguration.cpp
+++ b/src/plugins/projectexplorer/editorconfiguration.cpp
@@ -82,23 +82,23 @@ struct EditorConfigurationPrivate
ExtraEncodingSettings m_extraEncodingSettings;
QTextCodec *m_textCodec;
- QMap<QString, ICodeStylePreferences *> m_languageCodeStylePreferences;
+ QMap<Core::Id, ICodeStylePreferences *> m_languageCodeStylePreferences;
};
EditorConfiguration::EditorConfiguration() : d(new EditorConfigurationPrivate)
{
TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
- const QMap<QString, ICodeStylePreferences *> languageCodeStylePreferences = textEditorSettings->codeStyles();
- QMapIterator<QString, ICodeStylePreferences *> itCodeStyle(languageCodeStylePreferences);
+ const QMap<Core::Id, ICodeStylePreferences *> languageCodeStylePreferences = textEditorSettings->codeStyles();
+ QMapIterator<Core::Id, ICodeStylePreferences *> itCodeStyle(languageCodeStylePreferences);
while (itCodeStyle.hasNext()) {
itCodeStyle.next();
- const QString languageId = itCodeStyle.key();
+ Core::Id languageId = itCodeStyle.key();
ICodeStylePreferences *originalPreferences = itCodeStyle.value();
ICodeStylePreferencesFactory *factory = textEditorSettings->codeStyleFactory(languageId);
ICodeStylePreferences *preferences = factory->createCodeStyle();
preferences->setDelegatingPool(textEditorSettings->codeStylePool(languageId));
- preferences->setId(languageId + QLatin1String("Project"));
+ preferences->setId(languageId.toString() + QLatin1String("Project"));
preferences->setDisplayName(tr("Project %1", "Settings, %1 is a language (C++ or QML)").arg(factory->displayName()));
preferences->setCurrentDelegate(originalPreferences);
d->m_languageCodeStylePreferences.insert(languageId, preferences);
@@ -165,12 +165,12 @@ ICodeStylePreferences *EditorConfiguration::codeStyle() const
return d->m_defaultCodeStyle;
}
-ICodeStylePreferences *EditorConfiguration::codeStyle(const QString &languageId) const
+ICodeStylePreferences *EditorConfiguration::codeStyle(Core::Id languageId) const
{
return d->m_languageCodeStylePreferences.value(languageId, codeStyle());
}
-QMap<QString, ICodeStylePreferences *> EditorConfiguration::codeStyles() const
+QMap<Core::Id, ICodeStylePreferences *> EditorConfiguration::codeStyles() const
{
return d->m_languageCodeStylePreferences;
}
@@ -182,12 +182,12 @@ QVariantMap EditorConfiguration::toMap() const
map.insert(kCodec, d->m_textCodec->name());
map.insert(kCodeStyleCount, d->m_languageCodeStylePreferences.count());
- QMapIterator<QString, ICodeStylePreferences *> itCodeStyle(d->m_languageCodeStylePreferences);
+ QMapIterator<Core::Id, ICodeStylePreferences *> itCodeStyle(d->m_languageCodeStylePreferences);
int i = 0;
while (itCodeStyle.hasNext()) {
itCodeStyle.next();
QVariantMap settingsIdMap;
- settingsIdMap.insert(QLatin1String("language"), itCodeStyle.key());
+ settingsIdMap.insert(QLatin1String("language"), itCodeStyle.key().name());
QVariantMap value;
itCodeStyle.value()->toMap(QString(), &value);
settingsIdMap.insert(QLatin1String("value"), value);
@@ -220,12 +220,11 @@ void EditorConfiguration::fromMap(const QVariantMap &map)
qWarning() << "No data for code style settings list" << i << "found!";
continue;
}
- QString languageId = settingsIdMap.value(QLatin1String("language")).toString();
+ Core::Id languageId(settingsIdMap.value(QLatin1String("language")).toByteArray());
QVariantMap value = settingsIdMap.value(QLatin1String("value")).toMap();
ICodeStylePreferences *preferences = d->m_languageCodeStylePreferences.value(languageId);
- if (preferences) {
+ if (preferences)
preferences->fromMap(QString(), value);
- }
}
d->m_defaultCodeStyle->fromMap(kPrefix, map);
diff --git a/src/plugins/projectexplorer/editorconfiguration.h b/src/plugins/projectexplorer/editorconfiguration.h
index f601e993ec..a55587b611 100644
--- a/src/plugins/projectexplorer/editorconfiguration.h
+++ b/src/plugins/projectexplorer/editorconfiguration.h
@@ -32,6 +32,8 @@
#include "projectexplorer_export.h"
+#include <coreplugin/id.h>
+
#include <QObject>
#include <QVariantMap>
@@ -71,8 +73,8 @@ public:
const TextEditor::ExtraEncodingSettings &extraEncodingSettings() const;
TextEditor::ICodeStylePreferences *codeStyle() const;
- TextEditor::ICodeStylePreferences *codeStyle(const QString &languageId) const;
- QMap<QString, TextEditor::ICodeStylePreferences *> codeStyles() const;
+ TextEditor::ICodeStylePreferences *codeStyle(Core::Id languageId) const;
+ QMap<Core::Id, TextEditor::ICodeStylePreferences *> codeStyles() const;
void configureEditor(TextEditor::ITextEditor *textEditor) const;
diff --git a/src/plugins/projectexplorer/environmentitemswidget.cpp b/src/plugins/projectexplorer/environmentitemswidget.cpp
index 4d196d89c7..3e3f30a03f 100644
--- a/src/plugins/projectexplorer/environmentitemswidget.cpp
+++ b/src/plugins/projectexplorer/environmentitemswidget.cpp
@@ -30,6 +30,7 @@
#include "environmentitemswidget.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <texteditor/snippets/snippeteditor.h>
#include <texteditor/texteditorsettings.h>
@@ -53,9 +54,8 @@ QList<Utils::EnvironmentItem> EnvironmentItemsWidgetPrivate::cleanUp(
QSet<QString> uniqueSet;
for (int i = items.count() - 1; i >= 0; i--) {
Utils::EnvironmentItem item = items.at(i);
-#if defined(Q_OS_WIN)
- item.name = item.name.toUpper();
-#endif
+ if (Utils::HostOsInfo::isWindowsHost())
+ item.name = item.name.toUpper();
const QString &itemName = item.name;
QString emptyName = itemName;
emptyName.remove(QLatin1Char(' '));
diff --git a/src/plugins/projectexplorer/foldernavigationwidget.cpp b/src/plugins/projectexplorer/foldernavigationwidget.cpp
index e0922cc939..dcdaa8b68b 100644
--- a/src/plugins/projectexplorer/foldernavigationwidget.cpp
+++ b/src/plugins/projectexplorer/foldernavigationwidget.cpp
@@ -47,6 +47,7 @@
#include <utils/environment.h>
#include <utils/pathchooser.h>
#include <utils/qtcassert.h>
+#include <utils/elidinglabel.h>
#include <QDebug>
#include <QSize>
@@ -125,7 +126,7 @@ QVariant FolderNavigationModel::data(const QModelIndex &index, int role) const
}
/*!
- /class FolderNavigationWidget
+ \class FolderNavigationWidget
Shows a file system folder
*/
@@ -133,9 +134,11 @@ FolderNavigationWidget::FolderNavigationWidget(QWidget *parent)
: QWidget(parent),
m_listView(new QListView(this)),
m_fileSystemModel(new FolderNavigationModel(this)),
+ m_filterHiddenFilesAction(new QAction(tr("Show Hidden Files"), this)),
m_filterModel(new DotRemovalFilter(this)),
- m_title(new QLabel(this)),
- m_autoSync(false)
+ m_title(new Utils::ElidingLabel(this)),
+ m_autoSync(false),
+ m_toggleSync(new QToolButton(this))
{
m_fileSystemModel->setResolveSymlinks(false);
m_fileSystemModel->setIconProvider(Core::FileIconProvider::instance());
@@ -147,6 +150,8 @@ FolderNavigationWidget::FolderNavigationWidget(QWidget *parent)
#endif
m_fileSystemModel->setFilter(filters);
m_filterModel->setSourceModel(m_fileSystemModel);
+ m_filterHiddenFilesAction->setCheckable(true);
+ setHiddenFilesFilter(false);
m_listView->setIconSize(QSize(16,16));
m_listView->setModel(m_filterModel);
m_listView->setFrameStyle(QFrame::NoFrame);
@@ -161,11 +166,16 @@ FolderNavigationWidget::FolderNavigationWidget(QWidget *parent)
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
+ m_toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
+ m_toggleSync->setCheckable(true);
+ m_toggleSync->setToolTip(tr("Synchronize with Editor"));
+ setAutoSynchronization(true);
+
// connections
connect(m_listView, SIGNAL(activated(QModelIndex)),
this, SLOT(slotOpenItem(QModelIndex)));
-
- setAutoSynchronization(true);
+ connect(m_filterHiddenFilesAction, SIGNAL(toggled(bool)), this, SLOT(setHiddenFilesFilter(bool)));
+ connect(m_toggleSync, SIGNAL(clicked(bool)), this, SLOT(toggleAutoSynchronization()));
}
void FolderNavigationWidget::toggleAutoSynchronization()
@@ -180,6 +190,7 @@ bool FolderNavigationWidget::autoSynchronization() const
void FolderNavigationWidget::setAutoSynchronization(bool sync)
{
+ m_toggleSync->setChecked(sync);
if (sync == m_autoSync)
return;
@@ -380,6 +391,22 @@ void FolderNavigationWidget::findOnFileSystem(const QString &pathIn)
Find::FindPlugin::instance()->openFindDialog(fif);
}
+void FolderNavigationWidget::setHiddenFilesFilter(bool filter)
+{
+ QDir::Filters filters = m_fileSystemModel->filter();
+ if (filter)
+ filters |= QDir::Hidden;
+ else
+ filters &= ~(QDir::Hidden);
+ m_fileSystemModel->setFilter(filters);
+ m_filterHiddenFilesAction->setChecked(filter);
+}
+
+bool FolderNavigationWidget::hiddenFilesFilter() const
+{
+ return m_filterHiddenFilesAction->isChecked();
+}
+
// --------------------FolderNavigationWidgetFactory
FolderNavigationWidgetFactory::FolderNavigationWidgetFactory()
{
@@ -401,7 +428,7 @@ int FolderNavigationWidgetFactory::priority() const
Core::Id FolderNavigationWidgetFactory::id() const
{
- return "File System";
+ return Core::Id("File System");
}
QKeySequence FolderNavigationWidgetFactory::activationSequence() const
@@ -412,18 +439,39 @@ QKeySequence FolderNavigationWidgetFactory::activationSequence() const
Core::NavigationView FolderNavigationWidgetFactory::createWidget()
{
Core::NavigationView n;
- FolderNavigationWidget *ptw = new FolderNavigationWidget;
- n.widget = ptw;
- QToolButton *toggleSync = new QToolButton;
- toggleSync->setIcon(QIcon(QLatin1String(Core::Constants::ICON_LINK)));
- toggleSync->setCheckable(true);
- toggleSync->setChecked(ptw->autoSynchronization());
- toggleSync->setToolTip(tr("Synchronize with Editor"));
- connect(toggleSync, SIGNAL(clicked(bool)), ptw, SLOT(toggleAutoSynchronization()));
- n.dockToolBarWidgets << toggleSync;
+ FolderNavigationWidget *fnw = new FolderNavigationWidget;
+ n.widget = fnw;
+ QToolButton *filter = new QToolButton;
+ filter->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
+ filter->setToolTip(tr("Filter Files"));
+ filter->setPopupMode(QToolButton::InstantPopup);
+ filter->setProperty("noArrow", true);
+ QMenu *filterMenu = new QMenu(filter);
+ filterMenu->addAction(fnw->m_filterHiddenFilesAction);
+ filter->setMenu(filterMenu);
+ n.dockToolBarWidgets << filter << fnw->m_toggleSync;
return n;
}
+void FolderNavigationWidgetFactory::saveSettings(int position, QWidget *widget)
+{
+ FolderNavigationWidget *fnw = qobject_cast<FolderNavigationWidget *>(widget);
+ QTC_ASSERT(fnw, return);
+ QSettings *settings = Core::ICore::settings();
+ const QString baseKey = QLatin1String("FolderNavigationWidget.") + QString::number(position);
+ settings->setValue(baseKey + QLatin1String(".HiddenFilesFilter"), fnw->hiddenFilesFilter());
+ settings->setValue(baseKey + QLatin1String(".SyncWithEditor"), fnw->autoSynchronization());
+}
+
+void FolderNavigationWidgetFactory::restoreSettings(int position, QWidget *widget)
+{
+ FolderNavigationWidget *fnw = qobject_cast<FolderNavigationWidget *>(widget);
+ QTC_ASSERT(fnw, return);
+ QSettings *settings = Core::ICore::settings();
+ const QString baseKey = QLatin1String("FolderNavigationWidget.") + QString::number(position);
+ fnw->setHiddenFilesFilter(settings->value(baseKey + QLatin1String(".HiddenFilesFilter"), false).toBool());
+ fnw->setAutoSynchronization(settings->value(baseKey + QLatin1String(".SyncWithEditor"), true).toBool());
+}
} // namespace Internal
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/foldernavigationwidget.h b/src/plugins/projectexplorer/foldernavigationwidget.h
index 42e6a68566..fbc109a9df 100644
--- a/src/plugins/projectexplorer/foldernavigationwidget.h
+++ b/src/plugins/projectexplorer/foldernavigationwidget.h
@@ -63,6 +63,8 @@ public:
static void findOnFileSystem(const QString &pathIn);
static QString msgFindOnFileSystem();
+ bool hiddenFilesFilter() const;
+
public slots:
void setAutoSynchronization(bool sync);
void toggleAutoSynchronization();
@@ -70,6 +72,7 @@ public slots:
private slots:
void setCurrentFile(const QString &filePath);
void slotOpenItem(const QModelIndex &viewIndex);
+ void setHiddenFilesFilter(bool filter);
protected:
virtual void contextMenuEvent(QContextMenuEvent *ev);
@@ -83,9 +86,13 @@ private:
QListView *m_listView;
QFileSystemModel *m_fileSystemModel;
+ QAction *m_filterHiddenFilesAction;
QSortFilterProxyModel *m_filterModel;
QLabel *m_title;
bool m_autoSync;
+ QToolButton *m_toggleSync;
+ // FolderNavigationWidgetFactory needs private members to build a menu
+ friend class FolderNavigationWidgetFactory;
};
class FolderNavigationWidgetFactory : public Core::INavigationWidgetFactory
@@ -100,6 +107,8 @@ public:
Core::Id id() const;
QKeySequence activationSequence() const;
Core::NavigationView createWidget();
+ void saveSettings(int position, QWidget *widget);
+ void restoreSettings(int position, QWidget *widget);
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/gccparser.cpp b/src/plugins/projectexplorer/gccparser.cpp
index 503426f1fb..ca88c95410 100644
--- a/src/plugins/projectexplorer/gccparser.cpp
+++ b/src/plugins/projectexplorer/gccparser.cpp
@@ -171,17 +171,17 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< QString() << QString()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
- QLatin1String("In function `int main(int, char**)':"),
- Utils::FileName::fromUserInput("/temp/test/untitled8/main.cpp"), -1,
- categoryCompile)
+ QLatin1String("In function `int main(int, char**)':"),
+ Utils::FileName::fromUserInput(QLatin1String("/temp/test/untitled8/main.cpp")), -1,
+ categoryCompile)
<< Task(Task::Error,
- QLatin1String("`sfasdf' undeclared (first use this function)"),
- Utils::FileName::fromUserInput("/temp/test/untitled8/main.cpp"), 9,
- categoryCompile)
+ QLatin1String("`sfasdf' undeclared (first use this function)"),
+ Utils::FileName::fromUserInput(QLatin1String("/temp/test/untitled8/main.cpp")), 9,
+ categoryCompile)
<< Task(Task::Error,
- QLatin1String("(Each undeclared identifier is reported only once for each function it appears in.)"),
- Utils::FileName::fromUserInput("/temp/test/untitled8/main.cpp"), 9,
- categoryCompile)
+ QLatin1String("(Each undeclared identifier is reported only once for each function it appears in.)"),
+ Utils::FileName::fromUserInput(QLatin1String("/temp/test/untitled8/main.cpp")), 9,
+ categoryCompile)
)
<< QString();
QTest::newRow("GCCE warning")
@@ -191,7 +191,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("inline function `QDebug qDebug()' used but never defined"),
- Utils::FileName::fromUserInput("/src/corelib/global/qglobal.h"), 1635,
+ Utils::FileName::fromUserInput(QLatin1String("/src/corelib/global/qglobal.h")), 1635,
categoryCompile))
<< QString();
QTest::newRow("warning")
@@ -200,36 +200,39 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< QString() << QString()
<< (QList<ProjectExplorer::Task>() << Task(Task::Warning,
QLatin1String("Some warning"),
- Utils::FileName::fromUserInput("main.cpp"), 7,
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 7,
categoryCompile))
<< QString();
QTest::newRow("GCCE #error")
<< QString::fromLatin1("C:\\temp\\test\\untitled8\\main.cpp:7: #error Symbian error")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>() << Task(Task::Error,
- QLatin1String("#error Symbian error"),
- Utils::FileName::fromUserInput("C:\\temp\\test\\untitled8\\main.cpp"), 7,
- categoryCompile))
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("#error Symbian error"),
+ Utils::FileName::fromUserInput(QLatin1String("C:\\temp\\test\\untitled8\\main.cpp")), 7,
+ categoryCompile))
<< QString();
// Symbian reports #warning(s) twice (using different syntax).
QTest::newRow("GCCE #warning1")
<< QString::fromLatin1("C:\\temp\\test\\untitled8\\main.cpp:8: warning: #warning Symbian warning")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>() << Task(Task::Warning,
- QLatin1String("#warning Symbian warning"),
- Utils::FileName::fromUserInput("C:\\temp\\test\\untitled8\\main.cpp"), 8,
- categoryCompile))
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Warning,
+ QLatin1String("#warning Symbian warning"),
+ Utils::FileName::fromUserInput(QLatin1String("C:\\temp\\test\\untitled8\\main.cpp")), 8,
+ categoryCompile))
<< QString();
QTest::newRow("GCCE #warning2")
<< QString::fromLatin1("/temp/test/untitled8/main.cpp:8:2: warning: #warning Symbian warning")
<< OutputParserTester::STDERR
<< QString() << QString()
- << (QList<ProjectExplorer::Task>() << Task(Task::Warning,
- QLatin1String("#warning Symbian warning"),
- Utils::FileName::fromUserInput("/temp/test/untitled8/main.cpp"), 8,
- categoryCompile))
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Warning,
+ QLatin1String("#warning Symbian warning"),
+ Utils::FileName::fromUserInput(QLatin1String("/temp/test/untitled8/main.cpp")), 8,
+ categoryCompile))
<< QString();
QTest::newRow("Undefined reference (debug)")
<< QString::fromLatin1("main.o: In function `main':\n"
@@ -240,11 +243,11 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In function `main':"),
- Utils::FileName::fromUserInput("main.o"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("main.o")), -1,
categoryCompile)
<< Task(Task::Error,
QLatin1String("undefined reference to `MainWindow::doSomething()'"),
- Utils::FileName::fromUserInput("C:\\temp\\test\\untitled8/main.cpp"), 8,
+ Utils::FileName::fromUserInput(QLatin1String("C:\\temp\\test\\untitled8/main.cpp")), 8,
categoryCompile)
<< Task(Task::Error,
QLatin1String("collect2: ld returned 1 exit status"),
@@ -261,11 +264,11 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In function `main':"),
- Utils::FileName::fromUserInput("main.o"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("main.o")), -1,
categoryCompile)
<< Task(Task::Error,
QLatin1String("undefined reference to `MainWindow::doSomething()'"),
- Utils::FileName::fromUserInput("C:\\temp\\test\\untitled8/main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("C:\\temp\\test\\untitled8/main.cpp")), -1,
categoryCompile)
<< Task(Task::Error,
QLatin1String("collect2: ld returned 1 exit status"),
@@ -280,7 +283,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("file not recognized: File format not recognized"),
- Utils::FileName::fromUserInput("c:\\Qt\\4.6\\lib/QtGuid4.dll"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("c:\\Qt\\4.6\\lib/QtGuid4.dll")), -1,
categoryCompile))
<< QString();
QTest::newRow("Invalid rpath")
@@ -303,17 +306,17 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In member function 'void Debugger::Internal::GdbEngine::handleBreakInsert2(const Debugger::Internal::GdbResponse&)':"),
- Utils::FileName::fromUserInput("../../../../master/src/plugins/debugger/gdb/gdbengine.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../../../../master/src/plugins/debugger/gdb/gdbengine.cpp")), -1,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("unused variable 'index'"),
- Utils::FileName::fromUserInput("../../../../master/src/plugins/debugger/gdb/gdbengine.cpp"), 2114,
+ Utils::FileName::fromUserInput(QLatin1String("../../../../master/src/plugins/debugger/gdb/gdbengine.cpp")), 2114,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("unused variable 'handler'"),
- Utils::FileName::fromUserInput("../../../../master/src/plugins/debugger/gdb/gdbengine.cpp"), 2115,
+ Utils::FileName::fromUserInput(QLatin1String("../../../../master/src/plugins/debugger/gdb/gdbengine.cpp")), 2115,
categoryCompile))
- << QString();
+ << QString();
QTest::newRow("gnumakeparser.cpp errors")
<< QString::fromLatin1("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp: In member function 'void ProjectExplorer::ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()':\n"
"/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp:264: error: expected primary-expression before ':' token\n"
@@ -323,15 +326,15 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In member function 'void ProjectExplorer::ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()':"),
- Utils::FileName::fromUserInput("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp")), -1,
categoryCompile)
<< Task(Task::Error,
QLatin1String("expected primary-expression before ':' token"),
- Utils::FileName::fromUserInput("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp"), 264,
+ Utils::FileName::fromUserInput(QLatin1String("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp")), 264,
categoryCompile)
<< Task(Task::Error,
QLatin1String("expected ';' before ':' token"),
- Utils::FileName::fromUserInput("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp"), 264,
+ Utils::FileName::fromUserInput(QLatin1String("/home/code/src/creator/src/plugins/projectexplorer/gnumakeparser.cpp")), 264,
categoryCompile))
<< QString();
QTest::newRow("distcc error(QTCREATORBUG-904)")
@@ -375,7 +378,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("initialized from here"),
- Utils::FileName::fromUserInput("/home/dev/creator/share/qtcreator/dumper/dumper.cpp"), 1079,
+ Utils::FileName::fromUserInput(QLatin1String("/home/dev/creator/share/qtcreator/dumper/dumper.cpp")), 1079,
categoryCompile))
<< QString();
QTest::newRow("static member function")
@@ -386,11 +389,11 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In static member function 'static std::_Rb_tree_node_base* std::_Rb_global<_Dummy>::_Rebalance_for_erase(std::_Rb_tree_node_base*, std::_Rb_tree_node_base*&, std::_Rb_tree_node_base*&, std::_Rb_tree_node_base*&)':"),
- Utils::FileName::fromUserInput("/Qt/4.6.2-Symbian/s60sdk/epoc32/include/stdapis/stlport/stl/_tree.c"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("/Qt/4.6.2-Symbian/s60sdk/epoc32/include/stdapis/stlport/stl/_tree.c")), -1,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("suggest explicit braces to avoid ambiguous 'else'"),
- Utils::FileName::fromUserInput("/Qt/4.6.2-Symbian/s60sdk/epoc32/include/stdapis/stlport/stl/_tree.c"), 194,
+ Utils::FileName::fromUserInput(QLatin1String("/Qt/4.6.2-Symbian/s60sdk/epoc32/include/stdapis/stlport/stl/_tree.c")), 194,
categoryCompile))
<< QString();
QTest::newRow("rm false positive")
@@ -424,15 +427,15 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In function void foo(i) [with i = double]:"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), -1,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("instantiated from here"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), 22,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), 22,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("unused variable c"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), 8,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), 8,
categoryCompile))
<< QString();
QTest::newRow("instanciated from here")
@@ -442,7 +445,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("instantiated from here"),
- Utils::FileName::fromUserInput("main.cpp"), 10,
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 10,
categoryCompile))
<< QString();
QTest::newRow("In constructor")
@@ -452,7 +455,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In constructor 'Find::BaseTextFind::BaseTextFind(QTextEdit*)':"),
- Utils::FileName::fromUserInput("/dev/creator/src/plugins/find/basetextfind.h"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("/dev/creator/src/plugins/find/basetextfind.h")), -1,
categoryCompile))
<< QString();
@@ -467,23 +470,23 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("At global scope:"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), -1,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("In instantiation of void bar(i) [with i = double]:"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), -1,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("instantiated from void foo(i) [with i = double]"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), 8,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), 8,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("instantiated from here"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), 22,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), 22,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("unused parameter v"),
- Utils::FileName::fromUserInput("../../scriptbug/main.cpp"), 5,
+ Utils::FileName::fromUserInput(QLatin1String("../../scriptbug/main.cpp")), 5,
categoryCompile))
<< QString();
@@ -494,7 +497,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("test.moc: No such file or directory"),
- Utils::FileName::fromUserInput("/home/code/test.cpp"), 54,
+ Utils::FileName::fromUserInput(QLatin1String("/home/code/test.cpp")), 54,
categoryCompile))
<< QString();
@@ -508,15 +511,15 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In function `QPlotAxis':"),
- Utils::FileName::fromUserInput("debug/qplotaxis.o"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("debug/qplotaxis.o")), -1,
categoryCompile)
<< Task(Task::Error,
QLatin1String("undefined reference to `vtable for QPlotAxis'"),
- Utils::FileName::fromUserInput("M:\\Development\\x64\\QtPlot/qplotaxis.cpp"), 26,
+ Utils::FileName::fromUserInput(QLatin1String("M:\\Development\\x64\\QtPlot/qplotaxis.cpp")), 26,
categoryCompile)
<< Task(Task::Error,
QLatin1String("undefined reference to `vtable for QPlotAxis'"),
- Utils::FileName::fromUserInput("M:\\Development\\x64\\QtPlot/qplotaxis.cpp"), 26,
+ Utils::FileName::fromUserInput(QLatin1String("M:\\Development\\x64\\QtPlot/qplotaxis.cpp")), 26,
categoryCompile)
<< Task(Task::Error,
QLatin1String("collect2: ld returned 1 exit status"),
@@ -535,23 +538,23 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In member function typename _Vector_base<_Tp, _Alloc>::_Tp_alloc_type::const_reference Vector<_Tp, _Alloc>::at(int) [with _Tp = Point, _Alloc = Allocator<Point>]:"),
- Utils::FileName::fromUserInput("../stl/main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../stl/main.cpp")), -1,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("instantiated from here"),
- Utils::FileName::fromUserInput("../stl/main.cpp"), 38,
+ Utils::FileName::fromUserInput(QLatin1String("../stl/main.cpp")), 38,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("returning reference to temporary"),
- Utils::FileName::fromUserInput("../stl/main.cpp"), 31,
+ Utils::FileName::fromUserInput(QLatin1String("../stl/main.cpp")), 31,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("At global scope:"),
- Utils::FileName::fromUserInput("../stl/main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../stl/main.cpp")), -1,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("unused parameter index"),
- Utils::FileName::fromUserInput("../stl/main.cpp"), 31,
+ Utils::FileName::fromUserInput(QLatin1String("../stl/main.cpp")), 31,
categoryCompile))
<< QString();
@@ -565,19 +568,19 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In file included from C:/Symbian_SDK/epoc32/include/e32cmn.h:6792,"),
- Utils::FileName::fromUserInput("C:/Symbian_SDK/epoc32/include/e32cmn.h"), 6792,
+ Utils::FileName::fromUserInput(QLatin1String("C:/Symbian_SDK/epoc32/include/e32cmn.h")), 6792,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("from C:/Symbian_SDK/epoc32/include/e32std.h:25,"),
- Utils::FileName::fromUserInput("C:/Symbian_SDK/epoc32/include/e32std.h"), 25,
+ Utils::FileName::fromUserInput(QLatin1String("C:/Symbian_SDK/epoc32/include/e32std.h")), 25,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("In member function 'SSecureId::operator const TSecureId&() const':"),
- Utils::FileName::fromUserInput("C:/Symbian_SDK/epoc32/include/e32cmn.inl"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("C:/Symbian_SDK/epoc32/include/e32cmn.inl")), -1,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("returning reference to temporary"),
- Utils::FileName::fromUserInput("C:/Symbian_SDK/epoc32/include/e32cmn.inl"), 7094,
+ Utils::FileName::fromUserInput(QLatin1String("C:/Symbian_SDK/epoc32/include/e32cmn.inl")), 7094,
categoryCompile))
<< QString();
@@ -588,7 +591,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("At top level:"),
- Utils::FileName::fromUserInput("../../../src/XmlUg/targetdelete.c"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../../../src/XmlUg/targetdelete.c")), -1,
categoryCompile))
<< QString();
@@ -601,15 +604,15 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In file included from /Symbian/SDK/EPOC32/INCLUDE/GCCE/GCCE.h:15,"),
- Utils::FileName::fromUserInput("/Symbian/SDK/EPOC32/INCLUDE/GCCE/GCCE.h"), 15,
+ Utils::FileName::fromUserInput(QLatin1String("/Symbian/SDK/EPOC32/INCLUDE/GCCE/GCCE.h")), 15,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("from <command line>:26:"),
- Utils::FileName::fromUserInput("<command line>"), 26,
+ Utils::FileName::fromUserInput(QLatin1String("<command line>")), 26,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("no newline at end of file"),
- Utils::FileName::fromUserInput("/Symbian/SDK/epoc32/include/variant/Symbian_OS.hrh"), 1134,
+ Utils::FileName::fromUserInput(QLatin1String("/Symbian/SDK/epoc32/include/variant/Symbian_OS.hrh")), 1134,
categoryCompile))
<< QString();
@@ -620,7 +623,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("undefined reference to `MainWindow::doSomething()'"),
- Utils::FileName::fromUserInput("main.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), -1,
categoryCompile))
<< QString();
@@ -632,11 +635,11 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In member function 'ProFileEvaluator::Private::VisitReturn ProFileEvaluator::Private::evaluateConditionalFunction(const ProString&, const ProStringList&)':"),
- Utils::FileName::fromUserInput("../../../src/shared/proparser/profileevaluator.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("../../../src/shared/proparser/profileevaluator.cpp")), -1,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("case value '0' not in enumerated type 'ProFileEvaluator::Private::TestFunc'"),
- Utils::FileName::fromUserInput("../../../src/shared/proparser/profileevaluator.cpp"), 2817,
+ Utils::FileName::fromUserInput(QLatin1String("../../../src/shared/proparser/profileevaluator.cpp")), 2817,
categoryCompile))
<< QString();
@@ -648,11 +651,11 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In file included from <command-line>:0:0:"),
- Utils::FileName::fromUserInput("<command-line>"), 0,
+ Utils::FileName::fromUserInput(QLatin1String("<command-line>")), 0,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("\"STUPID_DEFINE\" redefined"),
- Utils::FileName::fromUserInput("./mw.h"), 4,
+ Utils::FileName::fromUserInput(QLatin1String("./mw.h")), 4,
categoryCompile))
<< QString();
QTest::newRow("instanciation with line:column info")
@@ -664,15 +667,15 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Unknown,
QLatin1String("In function 'void UnitTest::CheckEqual(UnitTest::TestResults&, const Expected&, const Actual&, const UnitTest::TestDetails&) [with Expected = unsigned int, Actual = int]':"),
- Utils::FileName::fromUserInput("file.h"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("file.h")), -1,
categoryCompile)
<< Task(Task::Unknown,
QLatin1String("instantiated from here"),
- Utils::FileName::fromUserInput("file.cpp"), 87,
+ Utils::FileName::fromUserInput(QLatin1String("file.cpp")), 87,
categoryCompile)
<< Task(Task::Warning,
QLatin1String("comparison between signed and unsigned integer expressions [-Wsign-compare]"),
- Utils::FileName::fromUserInput("file.h"), 21,
+ Utils::FileName::fromUserInput(QLatin1String("file.h")), 21,
categoryCompile))
<< QString();
QTest::newRow("linker error") // QTCREATORBUG-3107
@@ -682,7 +685,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("undefined reference to `CNS5kINSPacket::SOH_BYTE'"),
- Utils::FileName::fromUserInput("cns5k_ins_parser_tests.cpp"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("cns5k_ins_parser_tests.cpp")), -1,
categoryCompile))
<< QString();
@@ -693,7 +696,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("The name 'pushButton' (QPushButton) is already in use, defaulting to 'pushButton1'."),
- Utils::FileName::fromUserInput("mainwindow.ui"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("mainwindow.ui")), -1,
Constants::TASK_CATEGORY_COMPILE))
<< QString();
@@ -704,7 +707,7 @@ void ProjectExplorerPlugin::testGccOutputParsers_data()
<< ( QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("warning: feupdateenv is not implemented and will always fail"),
- Utils::FileName::fromUserInput("libimf.so"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("libimf.so")), -1,
Constants::TASK_CATEGORY_COMPILE))
<< QString();
}
diff --git a/src/plugins/projectexplorer/gcctoolchain.cpp b/src/plugins/projectexplorer/gcctoolchain.cpp
index a68dc2f584..b70d210bca 100644
--- a/src/plugins/projectexplorer/gcctoolchain.cpp
+++ b/src/plugins/projectexplorer/gcctoolchain.cpp
@@ -37,6 +37,7 @@
#include <utils/detailswidget.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <utils/synchronousprocess.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>
@@ -121,7 +122,8 @@ static QByteArray gccPredefinedMacros(const FileName &gcc, const QStringList &ar
|| a == QLatin1String("-O2") || a == QLatin1String("-O3")
|| a == QLatin1String("-ffinite-math-only") || a == QLatin1String("-fshort-double")
|| a == QLatin1String("-fshort-wchar") || a == QLatin1String("-fsignaling-nans")
- || a.startsWith(QLatin1String("-std=")) || a.startsWith(QLatin1String("-specs="))
+ || a.startsWith(QLatin1String("-std=")) || a.startsWith(QLatin1String("-stdlib="))
+ || a.startsWith(QLatin1String("-specs="))
|| a == QLatin1String("-ansi")
|| a.startsWith(QLatin1String("-D")) || a.startsWith(QLatin1String("-U"))
|| a == QLatin1String("-undef"))
@@ -131,28 +133,35 @@ static QByteArray gccPredefinedMacros(const FileName &gcc, const QStringList &ar
arguments << QLatin1String("-");
QByteArray predefinedMacros = runGcc(gcc, arguments, env);
-#ifdef Q_OS_MAC
- // Turn off flag indicating Apple's blocks support
- const QByteArray blocksDefine("#define __BLOCKS__ 1");
- const QByteArray blocksUndefine("#undef __BLOCKS__");
- const int idx = predefinedMacros.indexOf(blocksDefine);
- if (idx != -1) {
- predefinedMacros.replace(idx, blocksDefine.length(), blocksUndefine);
+ if (Utils::HostOsInfo::isMacHost()) {
+ // Turn off flag indicating Apple's blocks support
+ const QByteArray blocksDefine("#define __BLOCKS__ 1");
+ const QByteArray blocksUndefine("#undef __BLOCKS__");
+ const int idx = predefinedMacros.indexOf(blocksDefine);
+ if (idx != -1)
+ predefinedMacros.replace(idx, blocksDefine.length(), blocksUndefine);
+
+ // Define __strong and __weak (used for Apple's GC extension of C) to be empty
+ predefinedMacros.append("#define __strong\n");
+ predefinedMacros.append("#define __weak\n");
}
-
- // Define __strong and __weak (used for Apple's GC extension of C) to be empty
- predefinedMacros.append("#define __strong\n");
- predefinedMacros.append("#define __weak\n");
-#endif // Q_OS_MAC
return predefinedMacros;
}
-QList<HeaderPath> GccToolChain::gccHeaderPaths(const FileName &gcc, const QStringList &env, const FileName &sysrootPath)
+const int GccToolChain::PREDEFINED_MACROS_CACHE_SIZE = 16;
+
+QList<HeaderPath> GccToolChain::gccHeaderPaths(const FileName &gcc, const QStringList &args,
+ const QStringList &env, const FileName &sysrootPath)
{
QList<HeaderPath> systemHeaderPaths;
QStringList arguments;
if (!sysrootPath.isEmpty())
arguments.append(QString::fromLatin1("--sysroot=%1").arg(sysrootPath.toString()));
+ foreach (const QString &a, args) {
+ if (a.startsWith(QLatin1String("-stdlib=")))
+ arguments << a;
+ }
+
arguments << QLatin1String("-xc++")
<< QLatin1String("-E")
<< QLatin1String("-v")
@@ -315,7 +324,7 @@ GccToolChain::GccToolChain(const QString &id, bool autodetect) :
GccToolChain::GccToolChain(const GccToolChain &tc) :
ToolChain(tc),
- m_predefinedMacros(tc.predefinedMacros(QStringList())),
+ m_predefinedMacros(tc.m_predefinedMacros),
m_compilerCommand(tc.compilerCommand()),
m_targetAbi(tc.m_targetAbi),
m_supportedAbis(tc.m_supportedAbis),
@@ -327,9 +336,11 @@ QString GccToolChain::defaultDisplayName() const
{
if (!m_targetAbi.isValid())
return typeDisplayName();
- return QString::fromLatin1("%1 (%2 %3)").arg(typeDisplayName(),
- Abi::toString(m_targetAbi.architecture()),
- Abi::toString(m_targetAbi.wordWidth()));
+ return QCoreApplication::translate("ProjectExplorer::GccToolChain",
+ "%1 (%2 %3 in %4)").arg(typeDisplayName(),
+ Abi::toString(m_targetAbi.architecture()),
+ Abi::toString(m_targetAbi.wordWidth()),
+ compilerCommand().parentDir().toUserOutput());
}
QString GccToolChain::type() const
@@ -373,32 +384,60 @@ bool GccToolChain::isValid() const
return !m_compilerCommand.isNull();
}
+/**
+ * @brief Asks compiler for set of predefined macros
+ * @param cxxflags - compiler flags collected from project settings
+ * @return defines list, one per line, e.g. "#define __GXX_WEAK__ 1"
+ *
+ * @note changing compiler flags sometimes changes macros set, e.g. -fopenmp
+ * adds _OPENMP macro, for full list of macro search by word "when" on this page:
+ * http://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html
+ */
QByteArray GccToolChain::predefinedMacros(const QStringList &cxxflags) const
{
- if (m_predefinedMacros.isEmpty()) {
- // Using a clean environment breaks ccache/distcc/etc.
- Environment env = Environment::systemEnvironment();
- addToEnvironment(env);
- m_predefinedMacros = gccPredefinedMacros(m_compilerCommand, cxxflags, env.toStringList());
- }
- return m_predefinedMacros;
+ typedef QPair<QStringList, QByteArray> CacheItem;
+
+ for (GccCache::iterator it = m_predefinedMacros.begin(); it != m_predefinedMacros.end(); ++it)
+ if (it->first == cxxflags) {
+ // Increase cached item priority
+ CacheItem pair = *it;
+ m_predefinedMacros.erase(it);
+ m_predefinedMacros.push_back(pair);
+
+ return pair.second;
+ }
+
+ CacheItem runResults;
+ runResults.first = cxxflags;
+
+ // Using a clean environment breaks ccache/distcc/etc.
+ Environment env = Environment::systemEnvironment();
+ addToEnvironment(env);
+ runResults.second = gccPredefinedMacros(m_compilerCommand, cxxflags, env.toStringList());
+
+ m_predefinedMacros.push_back(runResults);
+ if (m_predefinedMacros.size() > PREDEFINED_MACROS_CACHE_SIZE)
+ m_predefinedMacros.pop_front();
+
+ return runResults.second;
}
ToolChain::CompilerFlags GccToolChain::compilerFlags(const QStringList &cxxflags) const
{
- if (cxxflags.contains("-std=c++0x") || cxxflags.contains("-std=gnu++0x") ||
- cxxflags.contains("-std=c++11") || cxxflags.contains("-std=gnu++11"))
+ if (cxxflags.contains(QLatin1String("-std=c++0x")) || cxxflags.contains(QLatin1String("-std=gnu++0x")) ||
+ cxxflags.contains(QLatin1String("-std=c++11")) || cxxflags.contains(QLatin1String("-std=gnu++11")) ||
+ cxxflags.contains(QLatin1String("-std=c++1y")) || cxxflags.contains(QLatin1String("-std=gnu++1y")))
return STD_CXX11;
return NO_FLAGS;
}
-QList<HeaderPath> GccToolChain::systemHeaderPaths(const Utils::FileName &sysRoot) const
+QList<HeaderPath> GccToolChain::systemHeaderPaths(const QStringList &cxxflags, const Utils::FileName &sysRoot) const
{
if (m_headerPaths.isEmpty()) {
// Using a clean environment breaks ccache/distcc/etc.
Environment env = Environment::systemEnvironment();
addToEnvironment(env);
- m_headerPaths = gccHeaderPaths(m_compilerCommand, env.toStringList(), sysRoot);
+ m_headerPaths = gccHeaderPaths(m_compilerCommand, cxxflags, env.toStringList(), sysRoot);
}
return m_headerPaths;
}
@@ -589,11 +628,11 @@ ToolChain *Internal::GccToolChainFactory::create()
QList<ToolChain *> Internal::GccToolChainFactory::autoDetect()
{
QList<ToolChain *> tcs;
-#ifdef Q_OS_MAC
- // Old mac compilers needed to support macx-gccXY mkspecs:
- tcs.append(autoDetectToolchains(QLatin1String("g++-4.0"), Abi::hostAbi()));
- tcs.append(autoDetectToolchains(QLatin1String("g++-4.2"), Abi::hostAbi()));
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ // Old mac compilers needed to support macx-gccXY mkspecs:
+ tcs.append(autoDetectToolchains(QLatin1String("g++-4.0"), Abi::hostAbi()));
+ tcs.append(autoDetectToolchains(QLatin1String("g++-4.2"), Abi::hostAbi()));
+ }
tcs.append(autoDetectToolchains(QLatin1String("g++"), Abi::hostAbi()));
return tcs;
@@ -613,7 +652,7 @@ ToolChain *Internal::GccToolChainFactory::restore(const QVariantMap &data)
// Updating from 2.5:
QVariantMap updated = data;
QString id = idFromMap(updated);
- if (id.startsWith(LEGACY_MAEMO_ID)) {
+ if (id.startsWith(QLatin1String(LEGACY_MAEMO_ID))) {
id = QString::fromLatin1(Constants::GCC_TOOLCHAIN_ID).append(id.mid(id.indexOf(QLatin1Char(':'))));
idToMap(updated, id);
autoDetectionToMap(updated, false);
@@ -767,12 +806,12 @@ QString ClangToolChain::typeDisplayName() const
QString ClangToolChain::makeCommand(const Utils::Environment &environment) const
{
QStringList makes;
-#if defined(Q_OS_WIN)
- makes << QLatin1String("mingw32-make.exe");
- makes << QLatin1String("make.exe");
-#else
- makes << QLatin1String("make");
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ makes << QLatin1String("mingw32-make.exe");
+ makes << QLatin1String("make.exe");
+ } else {
+ makes << QLatin1String("make");
+ }
QString tmp;
foreach (const QString &make, makes) {
@@ -877,31 +916,30 @@ QString MingwToolChain::typeDisplayName() const
QList<FileName> MingwToolChain::suggestedMkspecList() const
{
-#if defined(Q_OS_WIN)
- return QList<FileName>() << FileName::fromString(QLatin1String("win32-g++"));
-#elif defined(Q_OS_LINUX)
- if (version().startsWith("4.6."))
- return QList<FileName>()
- << FileName::fromString(QLatin1String("win32-g++-4.6-cross"))
- << FileName::fromString(QLatin1String("unsupported/win32-g++-4.6-cross"));
- else
- return QList<FileName>()
- << FileName::fromString(QLatin1String("win32-g++-cross"))
- << FileName::fromString(QLatin1String("unsupported/win32-g++-cross"));
-#else
+ if (Utils::HostOsInfo::isWindowsHost())
+ return QList<FileName>() << FileName::fromString(QLatin1String("win32-g++"));
+ if (Utils::HostOsInfo::isLinuxHost()) {
+ if (version().startsWith(QLatin1String("4.6.")))
+ return QList<FileName>()
+ << FileName::fromString(QLatin1String("win32-g++-4.6-cross"))
+ << FileName::fromString(QLatin1String("unsupported/win32-g++-4.6-cross"));
+ else
+ return QList<FileName>()
+ << FileName::fromString(QLatin1String("win32-g++-cross"))
+ << FileName::fromString(QLatin1String("unsupported/win32-g++-cross"));
+ }
return QList<FileName>();
-#endif
}
QString MingwToolChain::makeCommand(const Utils::Environment &environment) const
{
QStringList makes;
-#ifdef Q_OS_WIN
+ if (Utils::HostOsInfo::isWindowsHost()) {
makes << QLatin1String("mingw32-make.exe");
makes << QLatin1String("make.exe");
-#else
+ } else {
makes << QLatin1String("make");
-#endif
+ }
QString tmp;
foreach (const QString &make, makes) {
diff --git a/src/plugins/projectexplorer/gcctoolchain.h b/src/plugins/projectexplorer/gcctoolchain.h
index d5508d7bda..888ac8151e 100644
--- a/src/plugins/projectexplorer/gcctoolchain.h
+++ b/src/plugins/projectexplorer/gcctoolchain.h
@@ -51,6 +51,7 @@ class LinuxIccToolChainFactory;
class PROJECTEXPLORER_EXPORT GccToolChain : public ToolChain
{
public:
+ GccToolChain(const QString &id, bool autodetect);
QString type() const;
QString typeDisplayName() const;
Abi targetAbi() const;
@@ -63,7 +64,7 @@ public:
QByteArray predefinedMacros(const QStringList &cxxflags) const;
CompilerFlags compilerFlags(const QStringList &cxxflags) const;
- QList<HeaderPath> systemHeaderPaths(const Utils::FileName &sysRoot) const;
+ QList<HeaderPath> systemHeaderPaths(const QStringList &cxxflags, const Utils::FileName &sysRoot) const;
void addToEnvironment(Utils::Environment &env) const;
QString makeCommand(const Utils::Environment &environment) const;
QList<Utils::FileName> suggestedMkspecList() const;
@@ -82,7 +83,8 @@ public:
ToolChain *clone() const;
protected:
- GccToolChain(const QString &id, bool autodetect);
+ typedef QList<QPair<QStringList, QByteArray> > GccCache;
+
GccToolChain(const GccToolChain &);
virtual QString defaultDisplayName() const;
@@ -90,9 +92,10 @@ protected:
virtual QList<Abi> detectSupportedAbis() const;
virtual QString detectVersion() const;
- static QList<HeaderPath> gccHeaderPaths(const Utils::FileName &gcc, const QStringList &env, const Utils::FileName &sysrootPath);
+ static QList<HeaderPath> gccHeaderPaths(const Utils::FileName &gcc, const QStringList &args, const QStringList &env, const Utils::FileName &sysrootPath);
- mutable QByteArray m_predefinedMacros;
+ static const int PREDEFINED_MACROS_CACHE_SIZE;
+ mutable GccCache m_predefinedMacros;
private:
GccToolChain(bool autodetect);
diff --git a/src/plugins/projectexplorer/gcctoolchainfactories.h b/src/plugins/projectexplorer/gcctoolchainfactories.h
index b42bdb5461..c2d607bb3f 100644
--- a/src/plugins/projectexplorer/gcctoolchainfactories.h
+++ b/src/plugins/projectexplorer/gcctoolchainfactories.h
@@ -98,7 +98,6 @@ private:
Utils::PathChooser *m_compilerCommand;
AbiWidget *m_abiWidget;
- Utils::FileName m_autoDebuggerCommand;
QList<Abi> m_abiList;
bool m_isReadOnly;
diff --git a/src/plugins/projectexplorer/gnumakeparser.cpp b/src/plugins/projectexplorer/gnumakeparser.cpp
index ce09821ff7..1b73b795c4 100644
--- a/src/plugins/projectexplorer/gnumakeparser.cpp
+++ b/src/plugins/projectexplorer/gnumakeparser.cpp
@@ -284,7 +284,7 @@ void ProjectExplorerPlugin::testGnuMakeParserParsing_data()
<< (QList<Task>()
<< Task(Task::Error,
QString::fromLatin1("missing separator (did you mean TAB instead of 8 spaces?). Stop."),
- Utils::FileName::fromUserInput("Makefile"), 360,
+ Utils::FileName::fromUserInput(QLatin1String("Makefile")), 360,
Core::Id(Constants::TASK_CATEGORY_BUILDSYSTEM)))
<< QString()
<< QStringList();
@@ -368,7 +368,7 @@ void ProjectExplorerPlugin::testGnuMakeParserParsing()
QStringList searchDirs = childParser->searchDirectories();
// add extra directories:
- foreach(const QString &dir, extraSearchDirs)
+ foreach (const QString &dir, extraSearchDirs)
childParser->addDirectory(dir);
testbench.testParsing(input, inputChannel,
@@ -417,12 +417,12 @@ void ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()
<< QStringList()
<< Task(Task::Error,
QLatin1String("unknown filename, no mangling"),
- Utils::FileName::fromUserInput("some/path/unknown.cpp"),
+ Utils::FileName::fromUserInput(QLatin1String("some/path/unknown.cpp")),
-1,
Core::Id(Constants::TASK_CATEGORY_COMPILE))
<< Task(Task::Error,
QLatin1String("unknown filename, no mangling"),
- Utils::FileName::fromUserInput("some/path/unknown.cpp"),
+ Utils::FileName::fromUserInput(QLatin1String("some/path/unknown.cpp")),
-1,
Core::Id(Constants::TASK_CATEGORY_COMPILE));
QTest::newRow("find file")
@@ -430,12 +430,12 @@ void ProjectExplorerPlugin::testGnuMakeParserTaskMangling_data()
<< (QStringList(QLatin1String("test")))
<< Task(Task::Error,
QLatin1String("mangling"),
- Utils::FileName::fromUserInput("file.cpp"),
+ Utils::FileName::fromUserInput(QLatin1String("file.cpp")),
10,
Core::Id(Constants::TASK_CATEGORY_COMPILE))
<< Task(Task::Error,
QLatin1String("mangling"),
- Utils::FileName::fromUserInput("$TMPDIR/test/file.cpp"),
+ Utils::FileName::fromUserInput(QLatin1String("$TMPDIR/test/file.cpp")),
10,
Core::Id(Constants::TASK_CATEGORY_COMPILE));
}
diff --git a/src/plugins/projectexplorer/headerpath.h b/src/plugins/projectexplorer/headerpath.h
index bf8a1b8f79..2f8aaae042 100644
--- a/src/plugins/projectexplorer/headerpath.h
+++ b/src/plugins/projectexplorer/headerpath.h
@@ -56,6 +56,12 @@ public:
QString path() const { return m_path; }
Kind kind() const { return m_kind; }
+ bool operator==(const HeaderPath &other) const
+ {
+ return m_kind == other.m_kind
+ && m_path == other.m_path;
+ }
+
private:
QString m_path;
Kind m_kind;
diff --git a/src/plugins/projectexplorer/images/targetchangebutton.png b/src/plugins/projectexplorer/images/targetchangebutton.png
new file mode 100644
index 0000000000..1311d38ef8
--- /dev/null
+++ b/src/plugins/projectexplorer/images/targetchangebutton.png
Binary files differ
diff --git a/src/plugins/projectexplorer/images/targetchangebutton2.png b/src/plugins/projectexplorer/images/targetchangebutton2.png
new file mode 100644
index 0000000000..d5d5cfefd9
--- /dev/null
+++ b/src/plugins/projectexplorer/images/targetchangebutton2.png
Binary files differ
diff --git a/src/plugins/projectexplorer/images/targetremovebutton.png b/src/plugins/projectexplorer/images/targetremovebutton.png
deleted file mode 100644
index 15e8502ccf..0000000000
--- a/src/plugins/projectexplorer/images/targetremovebutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/projectexplorer/images/targetremovebuttondark.png b/src/plugins/projectexplorer/images/targetremovebuttondark.png
deleted file mode 100644
index c1ec33f910..0000000000
--- a/src/plugins/projectexplorer/images/targetremovebuttondark.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/projectexplorer/itaskhandler.h b/src/plugins/projectexplorer/itaskhandler.h
index 33771863bd..e1480fbf52 100644
--- a/src/plugins/projectexplorer/itaskhandler.h
+++ b/src/plugins/projectexplorer/itaskhandler.h
@@ -32,6 +32,8 @@
#include "projectexplorer_export.h"
+#include <coreplugin/id.h>
+
#include <QObject>
#include <QString>
@@ -52,6 +54,7 @@ public:
virtual bool isDefaultHandler() const { return false; }
virtual bool canHandle(const Task &) const = 0;
virtual void handle(const Task &) = 0;
+ virtual Core::Id actionManagerId() const { return Core::Id(); }
virtual QAction *createAction(QObject *parent) const = 0;
};
diff --git a/src/plugins/projectexplorer/kit.cpp b/src/plugins/projectexplorer/kit.cpp
index 31cd2d3b02..9929e8427e 100644
--- a/src/plugins/projectexplorer/kit.cpp
+++ b/src/plugins/projectexplorer/kit.cpp
@@ -34,6 +34,7 @@
#include "kitmanager.h"
#include "project.h"
#include "toolchainmanager.h"
+#include "ioutputparser.h"
#include <utils/qtcassert.h>
@@ -43,6 +44,8 @@
#include <QTextStream>
#include <QUuid>
+using namespace Core;
+
namespace {
const char ID_KEY[] = "PE.Profile.Id";
@@ -62,10 +65,10 @@ namespace ProjectExplorer {
static QString cleanName(const QString &name)
{
QString result = name;
- result.replace(QRegExp("\\W"), QLatin1String("_"));
- result.replace(QRegExp("_+"), "_"); // compact _
- result.remove(QRegExp("^_*")); // remove leading _
- result.remove(QRegExp("_+$")); // remove trailing _
+ result.replace(QRegExp(QLatin1String("\\W")), QLatin1String("_"));
+ result.replace(QRegExp(QLatin1String("_+")), QLatin1String("_")); // compact _
+ result.remove(QRegExp(QLatin1String("^_*"))); // remove leading _
+ result.remove(QRegExp(QLatin1String("_+$"))); // remove trailing _
if (result.isEmpty())
result = QLatin1String("unknown");
return result;
@@ -80,7 +83,7 @@ namespace Internal {
class KitPrivate
{
public:
- KitPrivate(Core::Id id) :
+ KitPrivate(Id id) :
m_id(id),
m_autodetected(false),
m_isValid(true),
@@ -88,11 +91,11 @@ public:
m_mustNotify(false)
{
if (!id.isValid())
- m_id = Core::Id(QUuid::createUuid().toString().toLatin1().constData());
+ m_id = Id::fromString(QUuid::createUuid().toString());
}
QString m_displayName;
- Core::Id m_id;
+ Id m_id;
bool m_autodetected;
bool m_isValid;
QIcon m_icon;
@@ -293,7 +296,7 @@ bool Kit::isAutoDetected() const
return d->m_autodetected;
}
-Core::Id Kit::id() const
+Id Kit::id() const
{
return d->m_id;
}
@@ -322,17 +325,17 @@ void Kit::setIconPath(const QString &path)
kitUpdated();
}
-QVariant Kit::value(const Core::Id &key, const QVariant &unset) const
+QVariant Kit::value(Id key, const QVariant &unset) const
{
return d->m_data.value(key, unset);
}
-bool Kit::hasValue(const Core::Id &key) const
+bool Kit::hasValue(Id key) const
{
return d->m_data.contains(key);
}
-void Kit::setValue(const Core::Id &key, const QVariant &value)
+void Kit::setValue(Id key, const QVariant &value)
{
if (d->m_data.value(key) == value)
return;
@@ -340,7 +343,7 @@ void Kit::setValue(const Core::Id &key, const QVariant &value)
kitUpdated();
}
-void Kit::removeKey(const Core::Id &key)
+void Kit::removeKey(Id key)
{
if (!d->m_data.contains(key))
return;
@@ -369,7 +372,7 @@ QVariantMap Kit::toMap() const
data.insert(QLatin1String(ICON_KEY), d->m_iconPath);
QVariantMap extra;
- foreach (const Core::Id &key, d->m_data.keys())
+ foreach (const Id key, d->m_data.keys())
extra.insert(QString::fromLatin1(key.name().constData()), d->m_data.value(key));
data.insert(QLatin1String(DATA_KEY), extra);
@@ -383,6 +386,23 @@ void Kit::addToEnvironment(Utils::Environment &env) const
ki->addToEnvironment(this, env);
}
+IOutputParser *Kit::createOutputParser() const
+{
+ IOutputParser *last = 0;
+ IOutputParser *first = 0;
+ QList<KitInformation *> infoList = KitManager::instance()->kitInformation();
+ foreach (KitInformation *ki, infoList) {
+ IOutputParser *next = ki->createOutputParser(this);
+ if (!first)
+ first = next;
+ if (last && next)
+ last->appendOutputParser(next);
+ if (next)
+ last = next;
+ }
+ return first;
+}
+
QString Kit::toHtml()
{
QString rc;
@@ -398,10 +418,10 @@ QString Kit::toHtml()
str << "<b>";
switch (t.type) {
case Task::Error:
- str << QCoreApplication::translate("ProjectExplorer::Kit", "Error:");
+ str << QCoreApplication::translate("ProjectExplorer::Kit", "Error:") << " ";
break;
case Task::Warning:
- str << QCoreApplication::translate("ProjectExplorer::Kit", "Warning:");
+ str << QCoreApplication::translate("ProjectExplorer::Kit", "Warning:") << " ";
break;
case Task::Unknown:
default:
@@ -425,17 +445,17 @@ QString Kit::toHtml()
bool Kit::fromMap(const QVariantMap &data)
{
KitGuard g(this);
- const QString id = data.value(QLatin1String(ID_KEY)).toString();
- if (id.isEmpty())
+ Id id = Id::fromSetting(data.value(QLatin1String(ID_KEY)));
+ if (!id.isValid())
return false;
- d->m_id = Core::Id(id);
+ d->m_id = id;
d->m_autodetected = data.value(QLatin1String(AUTODETECTED_KEY)).toBool();
setDisplayName(data.value(QLatin1String(DISPLAYNAME_KEY)).toString());
setIconPath(data.value(QLatin1String(ICON_KEY)).toString());
QVariantMap extra = data.value(QLatin1String(DATA_KEY)).toMap();
foreach (const QString &key, extra.keys())
- setValue(Core::Id(key), extra.value(key));
+ setValue(Id(key), extra.value(key));
return true;
}
diff --git a/src/plugins/projectexplorer/kit.h b/src/plugins/projectexplorer/kit.h
index 8d74e98765..031a0521a2 100644
--- a/src/plugins/projectexplorer/kit.h
+++ b/src/plugins/projectexplorer/kit.h
@@ -40,6 +40,7 @@
namespace Utils { class Environment; }
namespace ProjectExplorer {
+class IOutputParser;
namespace Internal {
class KitManagerPrivate;
@@ -81,15 +82,16 @@ public:
QString iconPath() const;
void setIconPath(const QString &path);
- QVariant value(const Core::Id &key, const QVariant &unset = QVariant()) const;
- bool hasValue(const Core::Id &key) const;
- void setValue(const Core::Id &key, const QVariant &value);
- void removeKey(const Core::Id &key);
+ QVariant value(Core::Id key, const QVariant &unset = QVariant()) const;
+ bool hasValue(Core::Id key) const;
+ void setValue(Core::Id key, const QVariant &value);
+ void removeKey(Core::Id key);
bool isDataEqual(const Kit *other) const;
bool isEqual(const Kit *other) const;
void addToEnvironment(Utils::Environment &env) const;
+ IOutputParser *createOutputParser() const;
QString toHtml();
Kit *clone(bool keepName = false) const;
diff --git a/src/plugins/projectexplorer/kitconfigwidget.h b/src/plugins/projectexplorer/kitconfigwidget.h
index 7465651cf2..5e973b104a 100644
--- a/src/plugins/projectexplorer/kitconfigwidget.h
+++ b/src/plugins/projectexplorer/kitconfigwidget.h
@@ -34,30 +34,35 @@
#include <QWidget>
-QT_FORWARD_DECLARE_CLASS(QGridLayout)
-
namespace ProjectExplorer {
+class Kit;
+
// --------------------------------------------------------------------------
// KitConfigWidget
// --------------------------------------------------------------------------
-class PROJECTEXPLORER_EXPORT KitConfigWidget : public QWidget
+class PROJECTEXPLORER_EXPORT KitConfigWidget : public QObject
{
Q_OBJECT
public:
- KitConfigWidget(QWidget *parent = 0) : QWidget(parent)
- { }
+ KitConfigWidget(Kit *kit) : m_kit(kit) { }
virtual QString displayName() const = 0;
+ virtual QString toolTip() const { return QString(); }
virtual void makeReadOnly() = 0;
virtual void refresh() = 0;
+ virtual bool visibleInKit() { return true; }
+ virtual QWidget *mainWidget() const = 0;
virtual QWidget *buttonWidget() const { return 0; }
signals:
void dirty();
+
+protected:
+ ProjectExplorer::Kit *m_kit;
};
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/kitinformation.cpp b/src/plugins/projectexplorer/kitinformation.cpp
index ba51142824..3f7028c3d7 100644
--- a/src/plugins/projectexplorer/kitinformation.cpp
+++ b/src/plugins/projectexplorer/kitinformation.cpp
@@ -222,6 +222,14 @@ void ToolChainKitInformation::addToEnvironment(const Kit *k, Utils::Environment
tc->addToEnvironment(env);
}
+IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const
+{
+ ToolChain *tc = toolChain(k);
+ if (tc)
+ return tc->outputParser();
+ return 0;
+}
+
ToolChain *ToolChainKitInformation::toolChain(const Kit *k)
{
if (!k)
@@ -305,14 +313,15 @@ KitInformation::ItemList DeviceTypeKitInformation::toUserOutput(Kit *k) const
const Core::Id DeviceTypeKitInformation::deviceTypeId(const Kit *k)
{
+ // FIXME: This should be fromSetting/toSetting instead.
if (!k)
return Core::Id();
- return Core::Id(k->value(Core::Id(DEVICETYPE_INFORMATION)).toByteArray().constData());
+ return Core::Id::fromName(k->value(DEVICETYPE_INFORMATION).toByteArray());
}
void DeviceTypeKitInformation::setDeviceTypeId(Kit *k, Core::Id type)
{
- k->setValue(Core::Id(DEVICETYPE_INFORMATION), type.name());
+ k->setValue(DEVICETYPE_INFORMATION, type.name());
}
// --------------------------------------------------------------------------
@@ -369,8 +378,7 @@ void DeviceKitInformation::fix(Kit *k)
if (!dev.isNull() && dev->type() == DeviceTypeKitInformation::deviceTypeId(k))
return;
- const QString id = defaultValue(k).toString();
- setDeviceId(k, id.isEmpty() ? Core::Id() : Core::Id(id));
+ setDeviceId(k, Core::Id::fromSetting(defaultValue(k)));
}
KitConfigWidget *DeviceKitInformation::createConfigWidget(Kit *k) const
@@ -398,21 +406,17 @@ IDevice::ConstPtr DeviceKitInformation::device(const Kit *k)
Core::Id DeviceKitInformation::deviceId(const Kit *k)
{
- if (k) {
- QString idname = k->value(Core::Id(DEVICE_INFORMATION)).toString();
- return idname.isEmpty() ? IDevice::invalidId() : Core::Id(idname);
- }
- return IDevice::invalidId();
+ return k ? Core::Id::fromSetting(k->value(DEVICE_INFORMATION)) : Core::Id();
}
void DeviceKitInformation::setDevice(Kit *k, IDevice::ConstPtr dev)
{
- setDeviceId(k, dev ? dev->id() : IDevice::invalidId());
+ setDeviceId(k, dev ? dev->id() : Core::Id());
}
void DeviceKitInformation::setDeviceId(Kit *k, const Core::Id id)
{
- k->setValue(Core::Id(DEVICE_INFORMATION), id.toString());
+ k->setValue(DEVICE_INFORMATION, id.toSetting());
}
void DeviceKitInformation::deviceUpdated(const Core::Id &id)
diff --git a/src/plugins/projectexplorer/kitinformation.h b/src/plugins/projectexplorer/kitinformation.h
index aaa6c9d8b5..c206b0d4dd 100644
--- a/src/plugins/projectexplorer/kitinformation.h
+++ b/src/plugins/projectexplorer/kitinformation.h
@@ -113,6 +113,7 @@ public:
ItemList toUserOutput(Kit *k) const;
void addToEnvironment(const Kit *k, Utils::Environment &env) const;
+ IOutputParser *createOutputParser(const Kit *k) const;
static ToolChain *toolChain(const Kit *k);
static void setToolChain(Kit *k, ToolChain *tc);
diff --git a/src/plugins/projectexplorer/kitinformationconfigwidget.cpp b/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
index 79e2c8f9eb..9945c31b18 100644
--- a/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
+++ b/src/plugins/projectexplorer/kitinformationconfigwidget.cpp
@@ -43,10 +43,11 @@
#include <utils/pathchooser.h>
#include <QComboBox>
-#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
+using namespace Core;
+
namespace ProjectExplorer {
namespace Internal {
@@ -54,22 +55,13 @@ namespace Internal {
// SysRootInformationConfigWidget:
// --------------------------------------------------------------------------
-SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k, QWidget *parent) :
- KitConfigWidget(parent),
- m_kit(k),
+SysRootInformationConfigWidget::SysRootInformationConfigWidget(Kit *k) :
+ KitConfigWidget(k),
m_ignoreChange(false)
{
- setToolTip(tr("The root directory of the system image to use.<br>"
- "Leave empty when building for the desktop."));
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
m_chooser = new Utils::PathChooser;
- m_chooser->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(m_chooser);
m_chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);
-
m_chooser->setFileName(SysRootKitInformation::sysRoot(k));
-
connect(m_chooser, SIGNAL(changed(QString)), this, SLOT(pathWasChanged()));
}
@@ -78,6 +70,12 @@ QString SysRootInformationConfigWidget::displayName() const
return tr("Sysroot:");
}
+QString SysRootInformationConfigWidget::toolTip() const
+{
+ return tr("The root directory of the system image to use.<br>"
+ "Leave empty when building for the desktop.");
+}
+
void SysRootInformationConfigWidget::refresh()
{
if (!m_ignoreChange)
@@ -89,6 +87,11 @@ void SysRootInformationConfigWidget::makeReadOnly()
m_chooser->setEnabled(false);
}
+QWidget *SysRootInformationConfigWidget::mainWidget() const
+{
+ return m_chooser->lineEdit();
+}
+
QWidget *SysRootInformationConfigWidget::buttonWidget() const
{
return m_chooser->buttonAtIndex(0);
@@ -105,22 +108,13 @@ void SysRootInformationConfigWidget::pathWasChanged()
// ToolChainInformationConfigWidget:
// --------------------------------------------------------------------------
-ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, QWidget *parent) :
- KitConfigWidget(parent),
- m_isReadOnly(false), m_kit(k),
- m_comboBox(new QComboBox), m_manageButton(new QPushButton(this))
+ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k) :
+ KitConfigWidget(k), m_isReadOnly(false)
{
- setToolTip(tr("The compiler to use for building.<br>"
- "Make sure the compiler will produce binaries compatible with the target device, "
- "Qt version and other libraries used."));
ToolChainManager *tcm = ToolChainManager::instance();
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
- m_comboBox->setContentsMargins(0, 0, 0, 0);
+ m_comboBox = new QComboBox;
m_comboBox->setEnabled(false);
- m_comboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
- layout->addWidget(m_comboBox);
foreach (ToolChain *tc, tcm->toolChains())
toolChainAdded(tc);
@@ -130,8 +124,8 @@ ToolChainInformationConfigWidget::ToolChainInformationConfigWidget(Kit *k, QWidg
refresh();
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentToolChainChanged(int)));
+ m_manageButton = new QPushButton(tr("Manage..."));
m_manageButton->setContentsMargins(0, 0, 0, 0);
- m_manageButton->setText(tr("Manage..."));
connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageToolChains()));
connect(tcm, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)),
@@ -147,6 +141,13 @@ QString ToolChainInformationConfigWidget::displayName() const
return tr("Compiler:");
}
+QString ToolChainInformationConfigWidget::toolTip() const
+{
+ return tr("The compiler to use for building.<br>"
+ "Make sure the compiler will produce binaries compatible with the target device, "
+ "Qt version and other libraries used.");
+}
+
void ToolChainInformationConfigWidget::refresh()
{
m_comboBox->setCurrentIndex(indexOf(ToolChainKitInformation::toolChain(m_kit)));
@@ -157,6 +158,11 @@ void ToolChainInformationConfigWidget::makeReadOnly()
m_comboBox->setEnabled(false);
}
+QWidget *ToolChainInformationConfigWidget::mainWidget() const
+{
+ return m_comboBox;
+}
+
QWidget *ToolChainInformationConfigWidget::buttonWidget() const
{
return m_manageButton;
@@ -186,8 +192,8 @@ void ToolChainInformationConfigWidget::toolChainUpdated(ProjectExplorer::ToolCha
void ToolChainInformationConfigWidget::manageToolChains()
{
- Core::ICore::showOptionsDialog(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::TOOLCHAIN_SETTINGS_PAGE_ID));
+ Core::ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ Constants::TOOLCHAIN_SETTINGS_PAGE_ID);
}
void ToolChainInformationConfigWidget::currentToolChainChanged(int idx)
@@ -226,35 +232,35 @@ int ToolChainInformationConfigWidget::indexOf(const ToolChain *tc)
// DeviceTypeInformationConfigWidget:
// --------------------------------------------------------------------------
-DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy, QWidget *parent) :
- KitConfigWidget(parent),
- m_isReadOnly(false), m_kit(workingCopy),
- m_comboBox(new QComboBox)
+DeviceTypeInformationConfigWidget::DeviceTypeInformationConfigWidget(Kit *workingCopy) :
+ KitConfigWidget(workingCopy), m_isReadOnly(false), m_comboBox(new QComboBox)
{
- setToolTip(tr("The type of device to run applications on."));
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
- m_comboBox->setContentsMargins(0, 0, 0, 0);
- m_comboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
- layout->addWidget(m_comboBox);
-
QList<IDeviceFactory *> factories
= ExtensionSystem::PluginManager::instance()->getObjects<IDeviceFactory>();
foreach (IDeviceFactory *factory, factories) {
- foreach (Core::Id id, factory->availableCreationIds()) {
+ foreach (Core::Id id, factory->availableCreationIds())
m_comboBox->addItem(factory->displayNameForId(id), id.uniqueIdentifier());
- }
}
refresh();
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentTypeChanged(int)));
}
+QWidget *DeviceTypeInformationConfigWidget::mainWidget() const
+{
+ return m_comboBox;
+}
+
QString DeviceTypeInformationConfigWidget::displayName() const
{
return tr("Device type:");
}
+QString DeviceTypeInformationConfigWidget::toolTip() const
+{
+ return tr("The type of device to run applications on.");
+}
+
void DeviceTypeInformationConfigWidget::refresh()
{
Core::Id devType = DeviceTypeKitInformation::deviceTypeId(m_kit);
@@ -283,39 +289,38 @@ void DeviceTypeInformationConfigWidget::currentTypeChanged(int idx)
// DeviceInformationConfigWidget:
// --------------------------------------------------------------------------
-DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy, QWidget *parent) :
- KitConfigWidget(parent),
- m_isReadOnly(false), m_kit(workingCopy),
- m_comboBox(new QComboBox), m_manageButton(new QPushButton(this)),
+DeviceInformationConfigWidget::DeviceInformationConfigWidget(Kit *workingCopy) :
+ KitConfigWidget(workingCopy),
+ m_isReadOnly(false),
+ m_comboBox(new QComboBox),
m_model(new DeviceManagerModel(DeviceManager::instance()))
{
- connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));
- connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));
-
- setToolTip(tr("The device to run the applications on."));
-
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
- m_comboBox->setContentsMargins(0, 0, 0, 0);
- m_comboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
- layout->addWidget(m_comboBox);
-
m_comboBox->setModel(m_model);
- m_manageButton->setContentsMargins(0, 0, 0, 0);
- m_manageButton->setText(tr("Manage..."));
+ m_manageButton = new QPushButton(tr("Manage"));
refresh();
+ connect(m_model, SIGNAL(modelAboutToBeReset()), SLOT(modelAboutToReset()));
+ connect(m_model, SIGNAL(modelReset()), SLOT(modelReset()));
connect(m_comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(currentDeviceChanged()));
-
connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageDevices()));
}
+QWidget *DeviceInformationConfigWidget::mainWidget() const
+{
+ return m_comboBox;
+}
+
QString DeviceInformationConfigWidget::displayName() const
{
return tr("Device:");
}
+QString DeviceInformationConfigWidget::toolTip() const
+{
+ return tr("The device to run the applications on.");
+}
+
void DeviceInformationConfigWidget::refresh()
{
m_model->setTypeFilter(DeviceTypeKitInformation::deviceTypeId(m_kit));
@@ -334,8 +339,8 @@ QWidget *DeviceInformationConfigWidget::buttonWidget() const
void DeviceInformationConfigWidget::manageDevices()
{
- Core::ICore::showOptionsDialog(QLatin1String(ProjectExplorer::Constants::DEVICE_SETTINGS_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::DEVICE_SETTINGS_PAGE_ID));
+ ICore::showOptionsDialog(Constants::DEVICE_SETTINGS_CATEGORY,
+ Constants::DEVICE_SETTINGS_PAGE_ID);
}
void DeviceInformationConfigWidget::modelAboutToReset()
diff --git a/src/plugins/projectexplorer/kitinformationconfigwidget.h b/src/plugins/projectexplorer/kitinformationconfigwidget.h
index 95592f9917..0b8ea8696a 100644
--- a/src/plugins/projectexplorer/kitinformationconfigwidget.h
+++ b/src/plugins/projectexplorer/kitinformationconfigwidget.h
@@ -44,7 +44,6 @@ namespace Utils { class PathChooser; }
namespace ProjectExplorer {
class DeviceManagerModel;
-class Kit;
class ToolChain;
namespace Internal {
@@ -58,18 +57,19 @@ class SysRootInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit SysRootInformationConfigWidget(Kit *k, QWidget *parent = 0);
+ explicit SysRootInformationConfigWidget(Kit *k);
QString displayName() const;
void refresh();
void makeReadOnly();
QWidget *buttonWidget() const;
+ QWidget *mainWidget() const;
+ QString toolTip() const;
private slots:
void pathWasChanged();
private:
- Kit *m_kit;
Utils::PathChooser *m_chooser;
bool m_ignoreChange;
};
@@ -83,12 +83,14 @@ class ToolChainInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit ToolChainInformationConfigWidget(Kit *k, QWidget *parent = 0);
+ explicit ToolChainInformationConfigWidget(Kit *k);
QString displayName() const;
void refresh();
void makeReadOnly();
+ QWidget *mainWidget() const;
QWidget *buttonWidget() const;
+ QString toolTip() const;
private slots:
void toolChainAdded(ProjectExplorer::ToolChain *tc);
@@ -102,7 +104,6 @@ private:
int indexOf(const ToolChain *tc);
bool m_isReadOnly;
- Kit *m_kit;
QComboBox *m_comboBox;
QPushButton *m_manageButton;
};
@@ -116,9 +117,11 @@ class DeviceTypeInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit DeviceTypeInformationConfigWidget(Kit *workingCopy, QWidget *parent = 0);
+ explicit DeviceTypeInformationConfigWidget(Kit *workingCopy);
+ QWidget *mainWidget() const;
QString displayName() const;
+ QString toolTip() const;
void refresh();
void makeReadOnly();
@@ -127,7 +130,6 @@ private slots:
private:
bool m_isReadOnly;
- Kit *m_kit;
QComboBox *m_comboBox;
};
@@ -140,12 +142,14 @@ class DeviceInformationConfigWidget : public KitConfigWidget
Q_OBJECT
public:
- explicit DeviceInformationConfigWidget(Kit *workingCopy, QWidget *parent = 0);
+ explicit DeviceInformationConfigWidget(Kit *workingCopy);
+ QWidget *mainWidget() const;
+ QWidget *buttonWidget() const;
QString displayName() const;
+ QString toolTip() const;
void refresh();
void makeReadOnly();
- QWidget *buttonWidget() const;
private slots:
void manageDevices();
@@ -155,7 +159,6 @@ private slots:
private:
bool m_isReadOnly;
- Kit *m_kit;
QComboBox *m_comboBox;
QPushButton *m_manageButton;
DeviceManagerModel *m_model;
diff --git a/src/plugins/projectexplorer/kitmanager.cpp b/src/plugins/projectexplorer/kitmanager.cpp
index 2b6cf7ffe9..7df67df142 100644
--- a/src/plugins/projectexplorer/kitmanager.cpp
+++ b/src/plugins/projectexplorer/kitmanager.cpp
@@ -215,6 +215,7 @@ void KitManager::restoreKits()
d->m_writer = new Utils::PersistentSettingsWriter(settingsFileName(), QLatin1String("QtCreatorProfiles"));
d->m_initialized = true;
+ emit kitsChanged();
}
KitManager::~KitManager()
@@ -378,6 +379,8 @@ Internal::KitManagerConfigWidget *KitManager::createConfigWidget(Kit *k) const
foreach (KitInformation *ki, d->m_informationList)
result->addConfigWidget(ki->createConfigWidget(result->workingCopy()));
+ result->updateVisibility();
+
return result;
}
@@ -473,6 +476,12 @@ void KitInformation::addToEnvironment(const Kit *k, Utils::Environment &env) con
Q_UNUSED(env);
}
+IOutputParser *KitInformation::createOutputParser(const Kit *k) const
+{
+ Q_UNUSED(k);
+ return 0;
+}
+
QString KitInformation::displayNamePostfix(const Kit *k) const
{
Q_UNUSED(k);
diff --git a/src/plugins/projectexplorer/kitmanager.h b/src/plugins/projectexplorer/kitmanager.h
index a8b4686597..f9c080e448 100644
--- a/src/plugins/projectexplorer/kitmanager.h
+++ b/src/plugins/projectexplorer/kitmanager.h
@@ -43,6 +43,7 @@
namespace Utils { class Environment; }
namespace ProjectExplorer {
+class IOutputParser;
class Kit;
class KitConfigWidget;
@@ -71,7 +72,6 @@ public:
virtual unsigned int priority() const = 0; // the higher the closer to the top.
- virtual bool visibleIn(Kit *) { return true; }
virtual QVariant defaultValue(Kit *) const = 0;
// called to find issues with the kit
@@ -86,6 +86,7 @@ public:
virtual KitConfigWidget *createConfigWidget(Kit *) const = 0;
virtual void addToEnvironment(const Kit *k, Utils::Environment &env) const;
+ virtual IOutputParser *createOutputParser(const Kit *k) const;
virtual QString displayNamePostfix(const Kit *k) const;
diff --git a/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp b/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp
index 6fd41c4438..f17b35fbb1 100644
--- a/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp
+++ b/src/plugins/projectexplorer/kitmanagerconfigwidget.cpp
@@ -35,11 +35,11 @@
#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
-#include <QHBoxLayout>
#include <QFileDialog>
#include <QGridLayout>
#include <QLabel>
#include <QLineEdit>
+#include <QPainter>
#include <QToolButton>
#include <QScrollArea>
#include <QSizePolicy>
@@ -48,11 +48,9 @@
static const char WORKING_COPY_KIT_ID[] = "modified kit";
namespace ProjectExplorer {
-
namespace Internal {
-KitManagerConfigWidget::KitManagerConfigWidget(Kit *k, QWidget *parent) :
- QWidget(parent),
+KitManagerConfigWidget::KitManagerConfigWidget(Kit *k) :
m_layout(new QGridLayout),
m_iconButton(new QToolButton),
m_nameEdit(new QLineEdit),
@@ -60,30 +58,30 @@ KitManagerConfigWidget::KitManagerConfigWidget(Kit *k, QWidget *parent) :
m_modifiedKit(new Kit(Core::Id(WORKING_COPY_KIT_ID))),
m_fixingKit(false)
{
- QVBoxLayout *top = new QVBoxLayout(this);
- top->setMargin(0);
+ m_layout->addWidget(m_nameEdit, 0, WidgetColumn);
+ m_layout->addWidget(m_iconButton, 0, ButtonColumn);
+ setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
+
+ QWidget *inner = new QWidget;
+ inner->setLayout(m_layout);
QScrollArea *scroll = new QScrollArea;
+ scroll->setWidget(inner);
scroll->setFrameShape(QFrame::NoFrame);
scroll->setWidgetResizable(true);
scroll->setFocusPolicy(Qt::NoFocus);
- top->addWidget(scroll);
-
- Utils::DetailsWidget *details = new Utils::DetailsWidget;
- details->setState(Utils::DetailsWidget::NoSummary);
- scroll->setWidget(details);
- QWidget *widget = new QWidget;
+ QGridLayout *mainLayout = new QGridLayout(this);
+ mainLayout->setMargin(1);
+ mainLayout->addWidget(scroll, 0, 0);
- m_layout->setMargin(0);
- m_layout->setSpacing(6);
- m_layout->setContentsMargins(6, 0, 6, 0);
- m_layout->setRowStretch(1, 1);
- widget->setLayout(m_layout);
-
- details->setWidget(widget);
+ static const Qt::Alignment alignment
+ = static_cast<Qt::Alignment>(style()->styleHint(QStyle::SH_FormLayoutLabelAlignment));
+ QString toolTip = tr("Kit name and icon.");
+ QLabel *label = createLabel(tr("Name:"), toolTip);
+ m_layout->addWidget(label, 0, LabelColumn, alignment);
+ m_iconButton->setToolTip(toolTip);
- addToLayout(tr("Name:"), tr("Kit name and icon."), m_nameEdit, m_iconButton);
discard();
connect(m_iconButton, SIGNAL(clicked()), this, SLOT(setIcon()));
@@ -104,7 +102,7 @@ KitManagerConfigWidget::~KitManagerConfigWidget()
delete m_modifiedKit;
// Make sure our workingCopy did not get registered somehow:
foreach (const Kit *k, KitManager::instance()->kits())
- Q_ASSERT(k->id() != Core::Id(WORKING_COPY_KIT_ID));
+ QTC_CHECK(k->id() != Core::Id(WORKING_COPY_KIT_ID));
}
QString KitManagerConfigWidget::displayName() const
@@ -169,8 +167,33 @@ void KitManagerConfigWidget::addConfigWidget(ProjectExplorer::KitConfigWidget *w
QTC_ASSERT(widget, return);
QTC_ASSERT(!m_widgets.contains(widget), return);
- addToLayout(widget->displayName(), widget->toolTip(), widget, widget->buttonWidget());
+ QString name = widget->displayName();
+ QString toolTip = widget->toolTip();
+
+ int row = m_layout->rowCount();
+ m_layout->addWidget(widget->mainWidget(), row, WidgetColumn);
+ if (QWidget *button = widget->buttonWidget())
+ m_layout->addWidget(button, row, ButtonColumn);
+
+ static const Qt::Alignment alignment
+ = static_cast<Qt::Alignment>(style()->styleHint(QStyle::SH_FormLayoutLabelAlignment));
+ QLabel *label = createLabel(name, toolTip);
+ m_layout->addWidget(label, row, LabelColumn, alignment);
m_widgets.append(widget);
+ m_labels.append(label);
+}
+
+void KitManagerConfigWidget::updateVisibility()
+{
+ int count = m_widgets.count();
+ for (int i = 0; i < count; ++i) {
+ KitConfigWidget *widget = m_widgets.at(i);
+ bool visible = widget->visibleInKit();
+ widget->mainWidget()->setVisible(visible);
+ if (widget->buttonWidget())
+ widget->buttonWidget()->setVisible(visible);
+ m_labels.at(i)->setVisible(visible);
+ }
}
void KitManagerConfigWidget::makeReadOnly()
@@ -246,6 +269,7 @@ void KitManagerConfigWidget::workingCopyWasUpdated(Kit *k)
w->refresh();
m_nameEdit->setText(k->displayName());
m_iconButton->setIcon(k->icon());
+ updateVisibility();
emit dirty();
}
@@ -253,33 +277,22 @@ void KitManagerConfigWidget::kitWasUpdated(Kit *k)
{
if (m_kit == k)
discard();
+ updateVisibility();
}
-void KitManagerConfigWidget::addToLayout(const QString &name, const QString &toolTip,
- QWidget *widget, QWidget *button)
+QLabel *KitManagerConfigWidget::createLabel(const QString &name, const QString &toolTip)
{
- int row = m_layout->rowCount();
- addLabel(name, toolTip, row);
- m_layout->addWidget(widget, row, WidgetColumn);
- addButtonWidget(button, toolTip, row);
-}
-
-void KitManagerConfigWidget::addLabel(const QString &name, const QString &toolTip, int row)
-{
- static const Qt::Alignment alignment
- = static_cast<Qt::Alignment>(style()->styleHint(QStyle::SH_FormLayoutLabelAlignment));
QLabel *label = new QLabel(name);
label->setToolTip(toolTip);
- m_layout->addWidget(label, row, LabelColumn, alignment);
+ return label;
}
-void KitManagerConfigWidget::addButtonWidget(QWidget *button, const QString &toolTip, int row)
+void KitManagerConfigWidget::paintEvent(QPaintEvent *)
{
- if (!button)
- return;
- if (button->toolTip().isEmpty())
- button->setToolTip(toolTip);
- m_layout->addWidget(button, row, ButtonColumn);
+ QPainter p(this);
+ if (m_background.size() != size())
+ m_background = Utils::DetailsWidget::createBackground(size(), 0, this);
+ p.drawPixmap(rect(), m_background);
}
} // namespace Internal
diff --git a/src/plugins/projectexplorer/kitmanagerconfigwidget.h b/src/plugins/projectexplorer/kitmanagerconfigwidget.h
index dbf3f0c8d7..9267034e02 100644
--- a/src/plugins/projectexplorer/kitmanagerconfigwidget.h
+++ b/src/plugins/projectexplorer/kitmanagerconfigwidget.h
@@ -32,9 +32,11 @@
#include "kitconfigwidget.h"
+#include <QWidget>
+
QT_BEGIN_NAMESPACE
-class QHBoxLayout;
class QGridLayout;
+class QLabel;
class QLineEdit;
class QToolButton;
QT_END_NAMESPACE
@@ -49,7 +51,7 @@ class KitManagerConfigWidget : public QWidget
Q_OBJECT
public:
- explicit KitManagerConfigWidget(Kit *k, QWidget *parent = 0);
+ explicit KitManagerConfigWidget(Kit *k);
~KitManagerConfigWidget();
QString displayName() const;
@@ -67,8 +69,7 @@ public:
void setIsDefaultKit(bool d);
bool isDefaultKit() const;
void removeKit();
-
-public slots:
+ void updateVisibility();
signals:
void dirty();
@@ -86,20 +87,19 @@ private:
ButtonColumn
};
- void addToLayout(const QString &name, const QString &toolTip, QWidget *widget, QWidget *button = 0);
-
-
- void addLabel(const QString &name, const QString &toolTip, int row);
- void addButtonWidget(QWidget *button, const QString &toolTip, int row);
+ QLabel *createLabel(const QString &name, const QString &toolTip);
+ void paintEvent(QPaintEvent *ev);
QGridLayout *m_layout;
QToolButton *m_iconButton;
QLineEdit *m_nameEdit;
QList<KitConfigWidget *> m_widgets;
+ QList<QLabel *> m_labels;
Kit *m_kit;
Kit *m_modifiedKit;
bool m_isDefaultKit;
bool m_fixingKit;
+ QPixmap m_background;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/kitmodel.cpp b/src/plugins/projectexplorer/kitmodel.cpp
index 7c4d4e9f98..3c6732f91f 100644
--- a/src/plugins/projectexplorer/kitmodel.cpp
+++ b/src/plugins/projectexplorer/kitmodel.cpp
@@ -153,7 +153,7 @@ int KitModel::columnCount(const QModelIndex &parent) const
QVariant KitModel::data(const QModelIndex &index, int role) const
{
- static QIcon warningIcon(":/projectexplorer/images/compile_warning.png");
+ static QIcon warningIcon(QLatin1String(":/projectexplorer/images/compile_warning.png"));
if (!index.isValid() || index.column() != 0)
return QVariant();
@@ -366,8 +366,7 @@ KitNode *KitModel::findWorkingCopy(Kit *k) const
KitNode *KitModel::createNode(KitNode *parent, Kit *k)
{
KitNode *node = new KitNode(parent, k);
- node->widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
- m_parentLayout->addWidget(node->widget, 10);
+ m_parentLayout->addWidget(node->widget);
connect(node->widget, SIGNAL(dirty()), this, SLOT(setDirty()));
return node;
}
diff --git a/src/plugins/projectexplorer/kitoptionspage.cpp b/src/plugins/projectexplorer/kitoptionspage.cpp
index bf48f16963..f28f399192 100644
--- a/src/plugins/projectexplorer/kitoptionspage.cpp
+++ b/src/plugins/projectexplorer/kitoptionspage.cpp
@@ -57,7 +57,7 @@ KitOptionsPage::KitOptionsPage() :
{
setId(Constants::KITS_SETTINGS_PAGE_ID);
setDisplayName(tr("Kits"));
- setCategory(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY));
+ setCategory(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
@@ -85,7 +85,7 @@ QWidget *KitOptionsPage::createPage(QWidget *parent)
buttonLayout->addWidget(m_cloneButton);
buttonLayout->addWidget(m_delButton);
buttonLayout->addWidget(m_makeDefaultButton);
- buttonLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
+ buttonLayout->addStretch();
QHBoxLayout *horizontalLayout = new QHBoxLayout();
horizontalLayout->addWidget(m_kitsView);
@@ -96,6 +96,8 @@ QWidget *KitOptionsPage::createPage(QWidget *parent)
m_model = new Internal::KitModel(verticalLayout);
connect(m_model, SIGNAL(kitStateChanged()), this, SLOT(updateState()));
+ verticalLayout->setStretch(0, 1);
+ verticalLayout->setStretch(1, 0);
m_kitsView->setModel(m_model);
m_kitsView->header()->setResizeMode(0, QHeaderView::Stretch);
diff --git a/src/plugins/projectexplorer/kitoptionspage.h b/src/plugins/projectexplorer/kitoptionspage.h
index afb7abccc8..8022f82b8a 100644
--- a/src/plugins/projectexplorer/kitoptionspage.h
+++ b/src/plugins/projectexplorer/kitoptionspage.h
@@ -47,9 +47,6 @@ namespace ProjectExplorer {
namespace Internal { class KitModel; }
class Kit;
-class KitConfigWidget;
-class KitFactory;
-class KitManager;
// --------------------------------------------------------------------------
// KitOptionsPage:
diff --git a/src/plugins/projectexplorer/linuxiccparser.cpp b/src/plugins/projectexplorer/linuxiccparser.cpp
index 5306cbb9d1..4dad65fe47 100644
--- a/src/plugins/projectexplorer/linuxiccparser.cpp
+++ b/src/plugins/projectexplorer/linuxiccparser.cpp
@@ -144,7 +144,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("identifier \"f\" is undefined\nf(0);"),
- Utils::FileName::fromUserInput("main.cpp"), 13,
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 13,
Core::Id(Constants::TASK_CATEGORY_COMPILE)))
<< QString();
@@ -158,7 +158,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("function \"AClass::privatefunc\" (declared at line 4 of \"main.h\") is inaccessible\nb.privatefunc();"),
- Utils::FileName::fromUserInput("main.cpp"), 53,
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 53,
Core::Id(Constants::TASK_CATEGORY_COMPILE)))
<< QString();
@@ -172,7 +172,7 @@ void ProjectExplorerPlugin::testLinuxIccOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("use of \"=\" where \"==\" may have been intended\nwhile (a = true)"),
- Utils::FileName::fromUserInput("main.cpp"), 41,
+ Utils::FileName::fromUserInput(QLatin1String("main.cpp")), 41,
Core::Id(Constants::TASK_CATEGORY_COMPILE)))
<< QString();
}
diff --git a/src/plugins/projectexplorer/applicationrunconfiguration.cpp b/src/plugins/projectexplorer/localapplicationrunconfiguration.cpp
index cc060a33b0..0fa55d91cf 100644
--- a/src/plugins/projectexplorer/applicationrunconfiguration.cpp
+++ b/src/plugins/projectexplorer/localapplicationrunconfiguration.cpp
@@ -27,7 +27,8 @@
**
****************************************************************************/
-#include "applicationrunconfiguration.h"
+#include "localapplicationrunconfiguration.h"
+
#include "buildconfiguration.h"
#include <coreplugin/variablemanager.h>
@@ -52,26 +53,11 @@ LocalApplicationRunConfiguration::~LocalApplicationRunConfiguration()
{
}
-namespace Internal {
-
-class VarManMacroExpander : public Utils::AbstractQtcMacroExpander {
-public:
- virtual bool resolveMacro(const QString &name, QString *ret)
- {
- *ret = Core::VariableManager::instance()->value(name.toUtf8());
- return !ret->isEmpty();
- }
-};
-
-} // namespace Internal
-
Utils::AbstractMacroExpander *LocalApplicationRunConfiguration::macroExpander() const
{
if (BuildConfiguration *bc = activeBuildConfiguration())
return bc->macroExpander();
-
- static Internal::VarManMacroExpander mx;
- return &mx;
+ return Core::VariableManager::instance()->macroExpander();
}
} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/applicationrunconfiguration.h b/src/plugins/projectexplorer/localapplicationrunconfiguration.h
index 943bd20c91..0942e7e6ec 100644
--- a/src/plugins/projectexplorer/applicationrunconfiguration.h
+++ b/src/plugins/projectexplorer/localapplicationrunconfiguration.h
@@ -27,8 +27,8 @@
**
****************************************************************************/
-#ifndef APPLICATIONRUNCONFIGURATION_H
-#define APPLICATIONRUNCONFIGURATION_H
+#ifndef LOCALAPPLICATIONRUNCONFIGURATION_H
+#define LOCALAPPLICATIONRUNCONFIGURATION_H
#include "runconfiguration.h"
#include "applicationlauncher.h"
@@ -67,4 +67,4 @@ protected:
} // namespace ProjectExplorer
-#endif // APPLICATIONRUNCONFIGURATION_H
+#endif // LOCALAPPLICATIONRUNCONFIGURATION_H
diff --git a/src/plugins/projectexplorer/localapplicationruncontrol.cpp b/src/plugins/projectexplorer/localapplicationruncontrol.cpp
index 363595b8a7..e1038f5bbd 100644
--- a/src/plugins/projectexplorer/localapplicationruncontrol.cpp
+++ b/src/plugins/projectexplorer/localapplicationruncontrol.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "localapplicationruncontrol.h"
-#include "applicationrunconfiguration.h"
+#include "localapplicationrunconfiguration.h"
#include "projectexplorerconstants.h"
#include <utils/outputformat.h>
@@ -106,10 +106,10 @@ void LocalApplicationRunControl::start()
emit finished();
} else {
m_running = true;
- m_applicationLauncher.start(m_runMode, m_executable, m_commandLineArguments);
- setApplicationProcessHandle(ProcessHandle(m_applicationLauncher.applicationPID()));
QString msg = tr("Starting %1...\n").arg(QDir::toNativeSeparators(m_executable));
appendMessage(msg, Utils::NormalMessageFormat);
+ m_applicationLauncher.start(m_runMode, m_executable, m_commandLineArguments);
+ setApplicationProcessHandle(ProcessHandle(m_applicationLauncher.applicationPID()));
}
}
diff --git a/src/plugins/projectexplorer/miniprojecttargetselector.cpp b/src/plugins/projectexplorer/miniprojecttargetselector.cpp
index 20496804a0..301526a750 100644
--- a/src/plugins/projectexplorer/miniprojecttargetselector.cpp
+++ b/src/plugins/projectexplorer/miniprojecttargetselector.cpp
@@ -270,12 +270,11 @@ void ProjectListWidget::addProject(Project *project)
item->setText(displayName);
insertItem(pos, item);
- if (project == ProjectExplorerPlugin::instance()->startupProject()) {
+ if (project == ProjectExplorerPlugin::instance()->startupProject())
setCurrentItem(item);
- }
QFontMetrics fn(font());
- int width = fn.width(project->displayName()) + padding();
+ int width = fn.width(displayName) + padding();
if (width > optimalWidth())
setOptimalWidth(width);
@@ -309,10 +308,8 @@ void ProjectListWidget::removeProject(Project *project)
// recheck optimal width
int width = 0;
- for (int i = 0; i < count(); ++i) {
- Project *p = item(i)->data(Qt::UserRole).value<Project *>();
- width = qMax(fn.width(p->displayName()) + padding(), width);
- }
+ for (int i = 0; i < count(); ++i)
+ width = qMax(fn.width(item(i)->text()) + padding(), width);
setOptimalWidth(width);
m_ignoreIndexChange = false;
@@ -355,10 +352,8 @@ void ProjectListWidget::projectDisplayNameChanged(Project *project)
// recheck optimal width
QFontMetrics fn(font());
int width = 0;
- for (int i = 0; i < count(); ++i) {
- Project *p = item(i)->data(Qt::UserRole).value<Project *>();
- width = qMax(fn.width(p->displayName()) + padding(), width);
- }
+ for (int i = 0; i < count(); ++i)
+ width = qMax(fn.width(item(i)->text()) + padding(), width);
setOptimalWidth(width);
m_ignoreIndexChange = false;
@@ -521,9 +516,8 @@ QListWidgetItem *GenericListWidget::itemForProjectConfiguration(ProjectConfigura
{
for (int i = 0; i < count(); ++i) {
QListWidgetItem *lwi = item(i);
- if (lwi->data(Qt::UserRole).value<ProjectConfiguration *>() == pc) {
+ if (lwi->data(Qt::UserRole).value<ProjectConfiguration *>() == pc)
return lwi;
- }
}
return 0;
}
@@ -1377,6 +1371,7 @@ void MiniProjectTargetSelector::mousePressEvent(QMouseEvent *e)
void MiniProjectTargetSelector::updateActionAndSummary()
{
QString projectName;
+ QString fileName; // contains the path if projectName is not unique
QString targetName;
QString targetToolTipText;
QString buildConfig;
@@ -1387,6 +1382,12 @@ void MiniProjectTargetSelector::updateActionAndSummary()
Project *project = ProjectExplorerPlugin::instance()->startupProject();
if (project) {
projectName = project->displayName();
+ foreach (Project *p, ProjectExplorerPlugin::instance()->session()->projects()) {
+ if (p != project && p->displayName() == projectName) {
+ fileName = project->document()->fileName();
+ break;
+ }
+ }
if (Target *target = project->activeTarget()) {
targetName = project->activeTarget()->displayName();
@@ -1405,14 +1406,15 @@ void MiniProjectTargetSelector::updateActionAndSummary()
}
}
m_projectAction->setProperty("heading", projectName);
- if (project && project->needsConfiguration()) {
+ if (project && project->needsConfiguration())
m_projectAction->setProperty("subtitle", tr("Unconfigured"));
- } else {
+ else
m_projectAction->setProperty("subtitle", buildConfig);
- }
m_projectAction->setIcon(targetIcon);
QStringList lines;
lines << tr("<b>Project:</b> %1").arg(projectName);
+ if (!fileName.isEmpty())
+ lines << tr("<b>Path:</b> %1").arg(fileName);
if (!targetName.isEmpty())
lines << tr("<b>Kit:</b> %1").arg(targetName);
if (!buildConfig.isEmpty())
@@ -1455,13 +1457,13 @@ void MiniProjectTargetSelector::updateSummary()
.arg(startupProject->displayName());
} else {
if (!m_listWidgets[TARGET]->isVisibleTo(this))
- summary.append("<br/>");
+ summary.append(QLatin1String("<br/>"));
if (!m_listWidgets[BUILD]->isVisibleTo(this))
- summary.append("<br/>");
+ summary.append(QLatin1String("<br/>"));
if (!m_listWidgets[DEPLOY]->isVisibleTo(this))
- summary.append("<br/>");
+ summary.append(QLatin1String("<br/>"));
if (!m_listWidgets[RUN]->isVisibleTo(this))
- summary.append("<br/>");
+ summary.append(QLatin1String("<br/>"));
}
}
m_summaryLabel->setText(summary);
diff --git a/src/plugins/projectexplorer/msvcparser.cpp b/src/plugins/projectexplorer/msvcparser.cpp
index 3e59188a96..7c572cec0b 100644
--- a/src/plugins/projectexplorer/msvcparser.cpp
+++ b/src/plugins/projectexplorer/msvcparser.cpp
@@ -105,7 +105,7 @@ void MsvcParser::stdOutput(const QString &line)
if (processCompileLine(line))
return;
- if (line.startsWith("Error:")) {
+ if (line.startsWith(QLatin1String("Error:"))) {
m_lastTask = Task(Task::Error,
line.mid(6).trimmed(), /* description */
Utils::FileName(), /* fileName */
@@ -113,7 +113,7 @@ void MsvcParser::stdOutput(const QString &line)
Core::Id(Constants::TASK_CATEGORY_COMPILE));
return;
}
- if (line.startsWith("Warning:")) {
+ if (line.startsWith(QLatin1String("Warning:"))) {
m_lastTask = Task(Task::Warning,
line.mid(8).trimmed(), /* description */
Utils::FileName(), /* fileName */
@@ -203,19 +203,21 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
QTest::newRow("labeled error")
<< QString::fromLatin1("qmlstandalone\\main.cpp(54) : error C4716: 'findUnresolvedModule' : must return a value") << OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>() << Task(Task::Error,
- QLatin1String("C4716: 'findUnresolvedModule' : must return a value"),
- Utils::FileName::fromUserInput("qmlstandalone\\main.cpp"), 54,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Error,
+ QLatin1String("C4716: 'findUnresolvedModule' : must return a value"),
+ Utils::FileName::fromUserInput(QLatin1String("qmlstandalone\\main.cpp")), 54,
+ Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
QTest::newRow("labeled warning")
<< QString::fromLatin1("x:\\src\\plugins\\projectexplorer\\msvcparser.cpp(69) : warning C4100: 'something' : unreferenced formal parameter") << OutputParserTester::STDOUT
<< QString() << QString()
- << (QList<ProjectExplorer::Task>() << Task(Task::Warning,
- QLatin1String("C4100: 'something' : unreferenced formal parameter"),
- Utils::FileName::fromUserInput("x:\\src\\plugins\\projectexplorer\\msvcparser.cpp"), 69,
- Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ << (QList<ProjectExplorer::Task>()
+ << Task(Task::Warning,
+ QLatin1String("C4100: 'something' : unreferenced formal parameter"),
+ Utils::FileName::fromUserInput(QLatin1String("x:\\src\\plugins\\projectexplorer\\msvcparser.cpp")), 69,
+ Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
QTest::newRow("additional information")
@@ -226,11 +228,11 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("C4099: 'TextEditor::CompletionItem' : type name first seen using 'struct' now seen using 'class'"),
- Utils::FileName::fromUserInput("x:\\src\\plugins\\texteditor\\icompletioncollector.h"), 50,
+ Utils::FileName::fromUserInput(QLatin1String("x:\\src\\plugins\\texteditor\\icompletioncollector.h")), 50,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< Task(Task::Unknown,
QLatin1String("see declaration of 'TextEditor::CompletionItem'"),
- Utils::FileName::fromUserInput("x:\\src\\plugins\\texteditor\\completionsupport.h"), 39,
+ Utils::FileName::fromUserInput(QLatin1String("x:\\src\\plugins\\texteditor\\completionsupport.h")), 39,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
@@ -273,7 +275,7 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
" _Traits=std::_Tmap_traits<int,double,std::less<int>,std::allocator<std::pair<const int,double>>,false>\n"
"]\n"
"No constructor could take the source type, or constructor overload resolution was ambiguous"),
- Utils::FileName::fromUserInput("..\\untitled\\main.cpp"), 19,
+ Utils::FileName::fromUserInput(QLatin1String("..\\untitled\\main.cpp")), 19,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
QTest::newRow("Linker error 1")
@@ -283,7 +285,7 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("LNK2019: unresolved external symbol \"public: void __thiscall Data::doit(void)\" (?doit@Data@@QAEXXZ) referenced in function _main"),
- Utils::FileName::fromUserInput("main.obj"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("main.obj")), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
QTest::newRow("Linker error 2")
@@ -293,7 +295,7 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("LNK1120: 1 unresolved externals"),
- Utils::FileName::fromUserInput("debug\\Experimentation.exe"), -1,
+ Utils::FileName::fromUserInput(QLatin1String("debug\\Experimentation.exe")), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
QTest::newRow("Linker error 3")
@@ -321,11 +323,11 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("C4996: 'std::_Copy_impl': Function call with parameters that may be unsafe - this call relies on the caller to check that the passed values are correct. To disable this warning, use -D_SCL_SECURE_NO_WARNINGS. See documentation on how to use Visual C++ 'Checked Iterators'"),
- Utils::FileName::fromUserInput("c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\xutility"), 2227,
+ Utils::FileName::fromUserInput(QLatin1String("c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\xutility")), 2227,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< Task(Task::Unknown,
QLatin1String("see declaration of 'std::_Copy_impl'"),
- Utils::FileName::fromUserInput("c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\xutility"), 2212,
+ Utils::FileName::fromUserInput(QLatin1String("c:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\INCLUDE\\xutility")), 2212,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE))
<< Task(Task::Unknown,
QLatin1String("see reference to function template instantiation '_OutIt std::copy<const unsigned char*,unsigned short*>(_InIt,_InIt,_OutIt)' being compiled\n"
@@ -334,7 +336,7 @@ void ProjectExplorerPlugin::testMsvcOutputParsers_data()
" _OutIt=unsigned short *,\n"
" _InIt=const unsigned char *\n"
"]"),
- Utils::FileName::fromUserInput("symbolgroupvalue.cpp"), 2314,
+ Utils::FileName::fromUserInput(QLatin1String("symbolgroupvalue.cpp")), 2314,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
<< QString();
}
diff --git a/src/plugins/projectexplorer/msvctoolchain.cpp b/src/plugins/projectexplorer/msvctoolchain.cpp
index 38dab0d570..7e828c3ee0 100644
--- a/src/plugins/projectexplorer/msvctoolchain.cpp
+++ b/src/plugins/projectexplorer/msvctoolchain.cpp
@@ -40,6 +40,7 @@
#include <utils/synchronousprocess.h>
#include <utils/winutils.h>
#include <utils/qtcassert.h>
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QFileInfo>
@@ -70,12 +71,10 @@ static QString platformName(MsvcToolChain::Platform t)
return QLatin1String(" (x86)");
case MsvcToolChain::amd64:
return QLatin1String(" (amd64)");
- case MsvcToolChain::x86_amd64:
- return QLatin1String(" (x86_amd64)");
case MsvcToolChain::ia64:
return QLatin1String(" (ia64)");
- case MsvcToolChain::x86_ia64:
- return QLatin1String(" (x86_ia64)");
+ case MsvcToolChain::arm:
+ return QLatin1String(" (arm)");
}
return QString();
}
@@ -92,11 +91,13 @@ static Abi findAbiOfMsvc(MsvcToolChain::Type type, MsvcToolChain::Platform platf
wordWidth = 32;
break;
case ProjectExplorer::Internal::MsvcToolChain::ia64:
- case ProjectExplorer::Internal::MsvcToolChain::x86_ia64:
arch = Abi::ItaniumArchitecture;
break;
case ProjectExplorer::Internal::MsvcToolChain::amd64:
- case ProjectExplorer::Internal::MsvcToolChain::x86_amd64:
+ break;
+ case ProjectExplorer::Internal::MsvcToolChain::arm:
+ arch = Abi::ArmArchitecture;
+ wordWidth = 32;
break;
};
@@ -241,9 +242,8 @@ QByteArray MsvcToolChain::msvcPredefinedMacros(const QStringList cxxflags,
QList<QByteArray> split = line.split('=');
const QByteArray key = split.at(0).mid(1);
QByteArray value = split.at(1);
- if (!value.isEmpty()) {
+ if (!value.isEmpty())
value.chop(1); //remove '\n'
- }
predefinedMacros += "#define ";
predefinedMacros += key;
predefinedMacros += ' ';
@@ -484,15 +484,9 @@ QList<ToolChain *> MsvcToolChainFactory::autoDetect()
tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::amd64),
findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::amd64, version),
fi.absoluteFilePath(), QLatin1String("/x64"), true));
- tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::x86_amd64),
- findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::x86_amd64, version),
- fi.absoluteFilePath(), QLatin1String("/x64"), true));
tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::ia64),
findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::ia64, version),
fi.absoluteFilePath(), QLatin1String("/ia64"), true));
- tmp.append(new MsvcToolChain(generateDisplayName(name, MsvcToolChain::WindowsSDK, MsvcToolChain::x86_ia64),
- findAbiOfMsvc(MsvcToolChain::WindowsSDK, MsvcToolChain::x86_ia64, version),
- fi.absoluteFilePath(), QLatin1String("/ia64"), true));
// Make sure the default is front.
if (folder == defaultSdkPath)
results = tmp + results;
@@ -519,56 +513,59 @@ QList<ToolChain *> MsvcToolChainFactory::autoDetect()
const QString path = vsRegistry.value(vsName).toString();
const int version = vsName.left(dotPos).toInt();
- // Check existence of various install scripts
- const QString vcvars32bat = path + QLatin1String("bin\\vcvars32.bat");
- if (QFileInfo(vcvars32bat).isFile())
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86, vsName),
- vcvars32bat, QString(), true));
- if (version >= 10) {
- // Just one common file
- const QString vcvarsAllbat = path + QLatin1String("vcvarsall.bat");
- if (QFileInfo(vcvarsAllbat).isFile()) {
+ const QString vcvarsAllbat = path + QLatin1String("vcvarsall.bat");
+ if (QFileInfo(vcvarsAllbat).isFile()) {
+ Utils::HostOsInfo::HostArchitecture arch = Utils::HostOsInfo::hostArchitecture();
+ if (QFileInfo(path + QLatin1String("bin/vcvars32.bat")).isFile())
results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86),
findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86, vsName),
vcvarsAllbat, QLatin1String("x86"), true));
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
- vcvarsAllbat, QLatin1String("amd64"), true));
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86_amd64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86_amd64, vsName),
- vcvarsAllbat, QLatin1String("x86_amd64"), true));
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
- vcvarsAllbat, QLatin1String("ia64"), true));
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86_ia64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86_ia64, vsName),
- vcvarsAllbat, QString("x86_ia64"), true));
- } else {
- qWarning("Unable to find MSVC setup script %s in version %d", qPrintable(vcvarsAllbat), version);
+
+ if (arch == Utils::HostOsInfo::HostArchitectureX86) {
+ if (QFileInfo(path + QLatin1String("bin/x86_amd64/vcvarsx86_amd64.bat")).isFile())
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
+ vcvarsAllbat, QLatin1String("x86_amd64"), true));
+ } else if (arch == Utils::HostOsInfo::HostArchitectureAMD64) {
+ if (QFileInfo(path + QLatin1String("bin/amd64/vcvars64.bat")).isFile()) {
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
+ vcvarsAllbat, QLatin1String("amd64"), true));
+ } else if (QFileInfo(path + QLatin1String("bin/x86_amd64/vcvarsx86_amd64.bat")).isFile()) {
+ // Fall back to 32 bit to 4 bit
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
+ vcvarsAllbat, QLatin1String("x86_amd64"), true));
+ }
+ }
+
+ if (arch == Utils::HostOsInfo::HostArchitectureX86
+ || arch == Utils::HostOsInfo::HostArchitectureAMD64) {
+ if (QFileInfo(path + QLatin1String("bin/x86_arm/vcvarsx86_arm.bat")).isFile())
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::arm),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::arm, vsName),
+ vcvarsAllbat, QLatin1String("x86_arm"), true));
+ } else if (arch == Utils::HostOsInfo::HostArchitectureArm) {
+ if (QFileInfo(path + QLatin1String("bin/arm/vcvarsarm.bat")).isFile())
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::arm),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::arm, vsName),
+ vcvarsAllbat, QLatin1String("arm"), true));
+ }
+
+ if (arch == Utils::HostOsInfo::HostArchitectureItanium) {
+ if (QFileInfo(path + QLatin1String("bin/ia64/vcvars64.bat")).isFile())
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
+ vcvarsAllbat, QLatin1String("ia64"), true));
+ } else if (arch == Utils::HostOsInfo::HostArchitectureX86
+ || arch == Utils::HostOsInfo::HostArchitectureAMD64) {
+ if (QFileInfo(path + QLatin1String("bin/x86_ia64/vcvarsx86_ia64.bat")).isFile())
+ results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::ia64),
+ findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::ia64, vsName),
+ vcvarsAllbat, QLatin1String("x86_ia64"), true));
}
} else {
- // Amd 64 is the preferred 64bit platform
- const QString vcvarsAmd64bat = path + QLatin1String("bin\\amd64\\vcvarsamd64.bat");
- if (QFileInfo(vcvarsAmd64bat).isFile())
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
- vcvarsAmd64bat, QString(), true));
- const QString vcvarsX86_amd64bat = path + QLatin1String("bin\\vcvarsx86_amd64.bat");
- if (QFileInfo(vcvarsX86_amd64bat).isFile())
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86_amd64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86_amd64, vsName),
- vcvarsX86_amd64bat, QString(), true));
- const QString vcvars64bat = path + QLatin1String("bin\\vcvars64.bat");
- if (QFileInfo(vcvars64bat).isFile())
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::amd64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::amd64, vsName),
- vcvars64bat, QString(), true));
- const QString vcvarsX86_ia64bat = path + QLatin1String("bin\\vcvarsx86_ia64.bat");
- if (QFileInfo(vcvarsX86_ia64bat).isFile())
- results.append(new MsvcToolChain(generateDisplayName(vsName, MsvcToolChain::VS, MsvcToolChain::x86_ia64),
- findAbiOfMsvc(MsvcToolChain::VS, MsvcToolChain::x86_ia64, vsName),
- vcvarsX86_ia64bat, QString(), true));
+ qWarning("Unable to find MSVC setup script %s in version %d", qPrintable(vcvarsAllbat), version);
}
}
diff --git a/src/plugins/projectexplorer/msvctoolchain.h b/src/plugins/projectexplorer/msvctoolchain.h
index e01dcc3a4b..1a12e0b2a3 100644
--- a/src/plugins/projectexplorer/msvctoolchain.h
+++ b/src/plugins/projectexplorer/msvctoolchain.h
@@ -49,11 +49,10 @@ class MsvcToolChain : public AbstractMsvcToolChain
{
public:
enum Type { WindowsSDK, VS };
- enum Platform { x86, // x86 -> x86
- amd64, // amd64 -> amd64
- ia64, // ia64 -> ia64
- x86_amd64, // x86 -> amd64
- x86_ia64, // x86 -> ia64
+ enum Platform { x86,
+ amd64,
+ ia64,
+ arm
};
MsvcToolChain(const QString &name, const Abi &abi,
diff --git a/src/plugins/projectexplorer/nodesvisitor.cpp b/src/plugins/projectexplorer/nodesvisitor.cpp
index 2b94c6f4f3..3f9a3894ab 100644
--- a/src/plugins/projectexplorer/nodesvisitor.cpp
+++ b/src/plugins/projectexplorer/nodesvisitor.cpp
@@ -92,13 +92,11 @@ void FindNodesForFileVisitor::visitProjectNode(ProjectNode *node)
void FindNodesForFileVisitor::visitFolderNode(FolderNode *node)
{
- if (node->path() == m_path) {
+ if (node->path() == m_path)
m_nodes << node;
- }
foreach (FileNode *fileNode, node->fileNodes()) {
- if (fileNode->path() == m_path) {
+ if (fileNode->path() == m_path)
m_nodes << fileNode;
- }
}
}
diff --git a/src/plugins/projectexplorer/outputparser_test.cpp b/src/plugins/projectexplorer/outputparser_test.cpp
index a838145c94..f9b2e29872 100644
--- a/src/plugins/projectexplorer/outputparser_test.cpp
+++ b/src/plugins/projectexplorer/outputparser_test.cpp
@@ -84,7 +84,7 @@ void OutputParserTester::testParsing(const QString &lines,
QCOMPARE(m_receivedStdOutChildLine, childStdOutLines);
QCOMPARE(m_receivedTasks.size(), tasks.size());
if (m_receivedTasks.size() == tasks.size()) {
- for(int i = 0; i < tasks.size(); ++i) {
+ for (int i = 0; i < tasks.size(); ++i) {
QCOMPARE(m_receivedTasks.at(i).category, tasks.at(i).category);
QCOMPARE(m_receivedTasks.at(i).description, tasks.at(i).description);
QCOMPARE(m_receivedTasks.at(i).file, tasks.at(i).file);
diff --git a/src/plugins/projectexplorer/pluginfilefactory.cpp b/src/plugins/projectexplorer/pluginfilefactory.cpp
index aea9d1b7aa..f27e4893ad 100644
--- a/src/plugins/projectexplorer/pluginfilefactory.cpp
+++ b/src/plugins/projectexplorer/pluginfilefactory.cpp
@@ -65,7 +65,7 @@ QStringList ProjectFileFactory::mimeTypes() const
Core::Id ProjectFileFactory::id() const
{
- return Constants::FILE_FACTORY_ID;
+ return Core::Id(Constants::FILE_FACTORY_ID);
}
QString ProjectFileFactory::displayName() const
diff --git a/src/plugins/projectexplorer/pluginfilefactory.h b/src/plugins/projectexplorer/pluginfilefactory.h
index 28a885072d..68cb962b4c 100644
--- a/src/plugins/projectexplorer/pluginfilefactory.h
+++ b/src/plugins/projectexplorer/pluginfilefactory.h
@@ -49,7 +49,6 @@ class ProjectFileFactory : public Core::IDocumentFactory
public:
virtual QStringList mimeTypes() const;
- bool canOpen(const QString &fileName);
Core::Id id() const;
QString displayName() const;
diff --git a/src/plugins/projectexplorer/processparameters.cpp b/src/plugins/projectexplorer/processparameters.cpp
index da6c8c09fb..da86fff931 100644
--- a/src/plugins/projectexplorer/processparameters.cpp
+++ b/src/plugins/projectexplorer/processparameters.cpp
@@ -198,3 +198,10 @@ QString ProcessParameters::summaryInWorkdir(const QString &displayName) const
prettyArguments(),
QDir::toNativeSeparators(effectiveWorkingDirectory()));
}
+
+void ProcessParameters::resolveAll()
+{
+ effectiveCommand();
+ effectiveArguments();
+ effectiveWorkingDirectory();
+}
diff --git a/src/plugins/projectexplorer/processparameters.h b/src/plugins/projectexplorer/processparameters.h
index 771b161fd8..0084ce98f6 100644
--- a/src/plugins/projectexplorer/processparameters.h
+++ b/src/plugins/projectexplorer/processparameters.h
@@ -76,6 +76,7 @@ public:
QString summary(const QString &displayName) const;
QString summaryInWorkdir(const QString &displayName) const;
+ void resolveAll();
private:
QString m_workingDirectory;
QString m_command;
diff --git a/src/plugins/projectexplorer/processstep.cpp b/src/plugins/projectexplorer/processstep.cpp
index 7676082d2a..553dc053d2 100644
--- a/src/plugins/projectexplorer/processstep.cpp
+++ b/src/plugins/projectexplorer/processstep.cpp
@@ -33,6 +33,7 @@
#include "buildconfiguration.h"
#include "projectexplorerconstants.h"
#include "target.h"
+#include "kit.h"
#include <coreplugin/idocument.h>
#include <coreplugin/variablemanager.h>
@@ -58,12 +59,6 @@ ProcessStep::ProcessStep(BuildStepList *bsl) :
ctor();
}
-ProcessStep::ProcessStep(BuildStepList *bsl, const Core::Id id) :
- AbstractProcessStep(bsl, id)
-{
- ctor();
-}
-
ProcessStep::ProcessStep(BuildStepList *bsl, ProcessStep *bs) :
AbstractProcessStep(bsl, bs),
m_command(bs->m_command),
@@ -96,7 +91,11 @@ bool ProcessStep::init()
pp->setWorkingDirectory(workingDirectory());
pp->setCommand(m_command);
pp->setArguments(m_arguments);
- setOutputParser(bc->createOutputParser());
+ pp->resolveAll();
+
+ IOutputParser *parser = target()->kit()->createOutputParser();
+ if (parser)
+ setOutputParser(parser);
return AbstractProcessStep::init();
}
diff --git a/src/plugins/projectexplorer/processstep.h b/src/plugins/projectexplorer/processstep.h
index 6816654947..c5f28fe6a0 100644
--- a/src/plugins/projectexplorer/processstep.h
+++ b/src/plugins/projectexplorer/processstep.h
@@ -32,7 +32,8 @@
#include "ui_processstep.h"
#include "abstractprocessstep.h"
-#include "environment.h"
+
+#include <utils/environment.h>
namespace ProjectExplorer {
@@ -84,7 +85,6 @@ public:
protected:
ProcessStep(BuildStepList *bsl, ProcessStep *bs);
- ProcessStep(BuildStepList *bsl, const Core::Id id);
bool fromMap(const QVariantMap &map);
diff --git a/src/plugins/projectexplorer/project.cpp b/src/plugins/projectexplorer/project.cpp
index 21df7b8244..faefbc44a7 100644
--- a/src/plugins/projectexplorer/project.cpp
+++ b/src/plugins/projectexplorer/project.cpp
@@ -32,7 +32,6 @@
#include "buildconfiguration.h"
#include "deployconfiguration.h"
#include "editorconfiguration.h"
-#include "environment.h"
#include "projectexplorer.h"
#include "projectexplorerconstants.h"
#include "projectnodes.h"
@@ -48,6 +47,7 @@
#include <projectexplorer/kitmanager.h>
#include <limits>
#include <utils/qtcassert.h>
+#include <utils/environment.h>
/*!
\class ProjectExplorer::Project
@@ -180,13 +180,12 @@ bool Project::removeTarget(Target *target)
return false;
if (target == activeTarget()) {
- if (d->m_targets.size() == 1) {
+ if (d->m_targets.size() == 1)
setActiveTarget(0);
- } else if (d->m_targets.first() == target) {
+ else if (d->m_targets.first() == target)
setActiveTarget(d->m_targets.at(1));
- } else {
+ else
setActiveTarget(d->m_targets.at(0));
- }
}
emit aboutToRemoveTarget(target);
@@ -306,10 +305,6 @@ bool Project::restoreSettings()
return ok;
}
-QList<BuildConfigWidget*> Project::subConfigWidgets()
-{
- return QList<BuildConfigWidget*>();
-}
/*!
\brief Serialize all data into a QVariantMap.
@@ -425,7 +420,7 @@ QVariant Project::namedSettings(const QString &name) const
return d->m_pluginSettings.value(name);
}
-void Project::setNamedSettings(const QString &name, QVariant &value)
+void Project::setNamedSettings(const QString &name, const QVariant &value)
{
if (value.isNull())
d->m_pluginSettings.remove(name);
diff --git a/src/plugins/projectexplorer/project.h b/src/plugins/projectexplorer/project.h
index 8605ae39e9..a1cb6419f5 100644
--- a/src/plugins/projectexplorer/project.h
+++ b/src/plugins/projectexplorer/project.h
@@ -45,11 +45,11 @@ class Context;
namespace ProjectExplorer {
-class BuildConfigWidget;
class IProjectManager;
class EditorConfiguration;
class ProjectNode;
class Kit;
+class NamedWidget;
class Target;
class ProjectPrivate;
@@ -63,7 +63,8 @@ public:
// Roles to be implemented by all models that are exported via model()
enum ModelRoles {
// Absolute file path
- FilePathRole = QFileSystemModel::FilePathRole
+ FilePathRole = QFileSystemModel::FilePathRole,
+ EnabledRole
};
Project();
@@ -97,8 +98,6 @@ public:
void saveSettings();
bool restoreSettings();
- virtual QList<BuildConfigWidget*> subConfigWidgets();
-
virtual ProjectNode *rootProjectNode() const = 0;
enum FilesMode { AllFiles, ExcludeGeneratedFiles };
@@ -118,7 +117,7 @@ public:
virtual Core::Context projectLanguage() const;
QVariant namedSettings(const QString &name) const;
- void setNamedSettings(const QString &name, QVariant &value);
+ void setNamedSettings(const QString &name, const QVariant &value);
virtual bool needsConfiguration() const;
virtual void configureAsExampleProject(const QStringList &platforms);
diff --git a/src/plugins/projectexplorer/projectconfiguration.cpp b/src/plugins/projectexplorer/projectconfiguration.cpp
index 32dea59dcb..fd61dff1fc 100644
--- a/src/plugins/projectexplorer/projectconfiguration.cpp
+++ b/src/plugins/projectexplorer/projectconfiguration.cpp
@@ -68,11 +68,10 @@ void ProjectConfiguration::setDisplayName(const QString &name)
{
if (displayName() == name)
return;
- if (name == m_defaultDisplayName) {
+ if (name == m_defaultDisplayName)
m_displayName.clear();
- } else {
+ else
m_displayName = name;
- }
emit displayNameChanged();
}
@@ -102,7 +101,7 @@ QVariantMap ProjectConfiguration::toMap() const
bool ProjectConfiguration::fromMap(const QVariantMap &map)
{
- m_id = Core::Id(map.value(QLatin1String(CONFIGURATION_ID_KEY), QByteArray()).toByteArray().constData());
+ m_id = Core::Id(map.value(QLatin1String(CONFIGURATION_ID_KEY), QByteArray()).toByteArray());
m_displayName = map.value(QLatin1String(DISPLAY_NAME_KEY), QString()).toString();
m_defaultDisplayName = map.value(QLatin1String(DEFAULT_DISPLAY_NAME_KEY),
m_defaultDisplayName.isEmpty() ?
diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp
index a9bd4d11cd..da3cd5e9a9 100644
--- a/src/plugins/projectexplorer/projectexplorer.cpp
+++ b/src/plugins/projectexplorer/projectexplorer.cpp
@@ -35,6 +35,7 @@
#include "gcctoolchainfactories.h"
#include "project.h"
#include "projectexplorersettings.h"
+#include "removetaskhandler.h"
#include "kitmanager.h"
#include "kitoptionspage.h"
#include "target.h"
@@ -78,6 +79,7 @@
#include "buildconfiguration.h"
#include "miniprojecttargetselector.h"
#include "taskhub.h"
+#include "customtoolchain.h"
#include "devicesupport/desktopdevice.h"
#include "devicesupport/desktopdevicefactory.h"
#include "devicesupport/devicemanager.h"
@@ -154,10 +156,6 @@ namespace {
bool debug = false;
}
-static const char kCurrentProjectPath[] = "CurrentProject:Path";
-static const char kCurrentProjectFilePath[] = "CurrentProject:FilePath";
-static const char kCurrentProjectBuildPath[] = "CurrentProject:BuildPath";
-
namespace ProjectExplorer {
struct ProjectExplorerPluginPrivate {
@@ -336,6 +334,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
#endif
addAutoReleasedObject(new Internal::GccToolChainFactory);
addAutoReleasedObject(new Internal::ClangToolChainFactory);
+ addAutoReleasedObject(new Internal::CustomToolChainFactory);
addAutoReleasedObject(new Internal::DesktopDeviceFactory);
@@ -393,6 +392,7 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
addAutoReleasedObject(new CopyTaskHandler);
addAutoReleasedObject(new ShowInEditorTaskHandler);
addAutoReleasedObject(new VcsAnnotateTaskHandler);
+ addAutoReleasedObject(new RemoveTaskHandler);
addAutoReleasedObject(new CoreListener);
d->m_outputPane = new AppOutputPane;
@@ -737,16 +737,19 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
// build action (context menu)
d->m_buildActionContextMenu = new QAction(tr("Build"), this);
cmd = Core::ActionManager::registerAction(d->m_buildActionContextMenu, Constants::BUILDCM, projecTreeContext);
+ cmd->setAttribute(Core::Command::CA_UpdateText);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_BUILD);
// rebuild action (context menu)
d->m_rebuildActionContextMenu = new QAction(tr("Rebuild"), this);
cmd = Core::ActionManager::registerAction(d->m_rebuildActionContextMenu, Constants::REBUILDCM, projecTreeContext);
+ cmd->setAttribute(Core::Command::CA_UpdateText);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_REBUILD);
// clean action (context menu)
d->m_cleanActionContextMenu = new QAction(tr("Clean"), this);
cmd = Core::ActionManager::registerAction(d->m_cleanActionContextMenu, Constants::CLEANCM, projecTreeContext);
+ cmd->setAttribute(Core::Command::CA_UpdateText);
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_REBUILD);
// build without dependencies action
@@ -988,12 +991,20 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
updateWelcomePage();
Core::VariableManager *vm = Core::VariableManager::instance();
- vm->registerVariable(kCurrentProjectFilePath,
+ vm->registerVariable(Constants::VAR_CURRENTPROJECT_FILEPATH,
tr("Full path of the current project's main file, including file name."));
- vm->registerVariable(kCurrentProjectPath,
+ vm->registerVariable(Constants::VAR_CURRENTPROJECT_PATH,
tr("Full path of the current project's main file, excluding file name."));
- vm->registerVariable(kCurrentProjectBuildPath,
+ vm->registerVariable(Constants::VAR_CURRENTPROJECT_BUILDPATH,
tr("Full build path of the current project's active build configuration."));
+ vm->registerVariable(Constants::VAR_CURRENTPROJECT_NAME, tr("The current project's name."));
+ vm->registerVariable(Constants::VAR_CURRENTKIT_NAME, tr("The currently active kit's name."));
+ vm->registerVariable(Constants::VAR_CURRENTKIT_FILESYSTEMNAME,
+ tr("The currently active kit's name in a filesystem friendly version."));
+ vm->registerVariable(Constants::VAR_CURRENTKIT_ID, tr("The currently active kit's id."));
+ vm->registerVariable(Constants::VAR_CURRENTBUILD_NAME, tr("The currently active build configuration's name."));
+ vm->registerVariable(Constants::VAR_CURRENTBUILD_TYPE, tr("The currently active build configuration's type."));
+
connect(vm, SIGNAL(variableUpdateRequested(QByteArray)),
this, SLOT(updateVariable(QByteArray)));
@@ -1067,7 +1078,12 @@ void ProjectExplorerPlugin::unloadProject()
return;
addToRecentProjects(document->fileName(), d->m_currentProject->displayName());
- d->m_session->removeProject(d->m_currentProject);
+ unloadProject(d->m_currentProject);
+}
+
+void ProjectExplorerPlugin::unloadProject(Project *project)
+{
+ d->m_session->removeProject(project);
updateActions();
}
@@ -1081,6 +1097,8 @@ void ProjectExplorerPlugin::closeAllProjects()
d->m_session->closeAllProjects();
updateActions();
+
+ Core::ModeManager::activateMode(Core::Id(Core::Constants::MODE_WELCOME));
}
void ProjectExplorerPlugin::extensionsInitialized()
@@ -1112,34 +1130,73 @@ void ProjectExplorerPlugin::loadCustomWizards()
static bool firstTime = true;
if (firstTime) {
firstTime = false;
- foreach(Core::IWizard *cpw, ProjectExplorer::CustomWizard::createWizards())
+ foreach (Core::IWizard *cpw, ProjectExplorer::CustomWizard::createWizards())
addAutoReleasedObject(cpw);
}
}
void ProjectExplorerPlugin::updateVariable(const QByteArray &variable)
{
- if (variable == kCurrentProjectFilePath) {
+ if (variable == Constants::VAR_CURRENTPROJECT_FILEPATH) {
if (currentProject() && currentProject()->document()) {
Core::VariableManager::instance()->insert(variable,
currentProject()->document()->fileName());
} else {
Core::VariableManager::instance()->remove(variable);
}
- } else if (variable == kCurrentProjectPath) {
+ } else if (variable == Constants::VAR_CURRENTPROJECT_PATH) {
if (currentProject() && currentProject()->document()) {
Core::VariableManager::instance()->insert(variable,
QFileInfo(currentProject()->document()->fileName()).path());
} else {
Core::VariableManager::instance()->remove(variable);
}
- } else if (variable == kCurrentProjectBuildPath) {
+ } else if (variable == Constants::VAR_CURRENTPROJECT_BUILDPATH) {
if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->activeBuildConfiguration()) {
Core::VariableManager::instance()->insert(variable,
currentProject()->activeTarget()->activeBuildConfiguration()->buildDirectory());
} else {
Core::VariableManager::instance()->remove(variable);
}
+ } else if (variable == Constants::VAR_CURRENTPROJECT_NAME) {
+ if (currentProject())
+ Core::VariableManager::instance()->insert(variable, currentProject()->displayName());
+ else
+ Core::VariableManager::instance()->remove(variable);
+ } else if (variable == Constants::VAR_CURRENTKIT_NAME) {
+ if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->kit())
+ Core::VariableManager::instance()->insert(variable, currentProject()->activeTarget()->kit()->displayName());
+ else
+ Core::VariableManager::instance()->remove(variable);
+ } else if (variable == Constants::VAR_CURRENTKIT_FILESYSTEMNAME) {
+ if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->kit())
+ Core::VariableManager::instance()->insert(variable, currentProject()->activeTarget()->kit()->fileSystemFriendlyName());
+ else
+ Core::VariableManager::instance()->remove(variable);
+ } else if (variable == Constants::VAR_CURRENTKIT_ID) {
+ if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->kit())
+ Core::VariableManager::instance()->insert(variable, currentProject()->activeTarget()->kit()->id().toString());
+ else
+ Core::VariableManager::instance()->remove(variable);
+ } else if (variable == Constants::VAR_CURRENTBUILD_NAME) {
+ if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->activeBuildConfiguration())
+ Core::VariableManager::instance()->insert(variable, currentProject()->activeTarget()->activeBuildConfiguration()->displayName());
+ else
+ Core::VariableManager::instance()->remove(variable);
+ } else if (variable == Constants::VAR_CURRENTBUILD_TYPE) {
+ if (currentProject() && currentProject()->activeTarget() && currentProject()->activeTarget()->activeBuildConfiguration()) {
+ BuildConfiguration::BuildType type = currentProject()->activeTarget()->activeBuildConfiguration()->buildType();
+ QString typeString;
+ if (type == BuildConfiguration::Debug)
+ typeString = tr("debug");
+ else if (type == BuildConfiguration::Release)
+ typeString = tr("release");
+ else
+ typeString = tr("unknown");
+ Core::VariableManager::instance()->insert(variable, typeString);
+ } else {
+ Core::VariableManager::instance()->remove(variable);
+ }
}
}
@@ -1447,6 +1504,21 @@ void ProjectExplorerPlugin::determineSessionToRestoreAtStartup()
Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
}
+// Return a list of glob patterns for project files ("*.pro", etc), use first, main pattern only.
+static inline QStringList projectFileGlobs()
+{
+ QStringList result;
+ const Core::MimeDatabase *mimeDatabase = Core::ICore::instance()->mimeDatabase();
+ foreach (const IProjectManager *ipm, ExtensionSystem::PluginManager::getObjects<IProjectManager>()) {
+ if (const Core::MimeType mimeType = mimeDatabase->findByType(ipm->mimeType())) {
+ const QList<Core::MimeGlobPattern> patterns = mimeType.globPatterns();
+ if (!patterns.isEmpty())
+ result.push_back(patterns.front().regExp().pattern());
+ }
+ }
+ return result;
+}
+
/*!
\fn void ProjectExplorerPlugin::restoreSession()
@@ -1462,8 +1534,55 @@ void ProjectExplorerPlugin::restoreSession()
// We have command line arguments, try to find a session in them
QStringList arguments = ExtensionSystem::PluginManager::arguments();
- arguments.removeOne(d->m_sessionToRestoreAtStartup);
-
+ if (!d->m_sessionToRestoreAtStartup.isEmpty() && !arguments.isEmpty())
+ arguments.removeOne(d->m_sessionToRestoreAtStartup);
+
+ // Massage the argument list.
+ // Be smart about directories: If there is a session of that name, load it.
+ // Other than that, look for project files in it. The idea is to achieve
+ // 'Do what I mean' functionality when starting Creator in a directory with
+ // the single command line argument '.' and avoid editor warnings about not
+ // being able to open directories.
+ // In addition, convert "filename" "+45" or "filename" ":23" into
+ // "filename+45" and "filename:23".
+ if (!arguments.isEmpty()) {
+ const QStringList sessions = d->m_session->sessions();
+ QStringList projectGlobs = projectFileGlobs();
+ for (int a = 0; a < arguments.size(); ) {
+ const QString &arg = arguments.at(a);
+ const QFileInfo fi(arg);
+ if (fi.isDir()) {
+ const QDir dir(fi.absoluteFilePath());
+ // Does the directory name match a session?
+ if (d->m_sessionToRestoreAtStartup.isEmpty()
+ && sessions.contains(dir.dirName())) {
+ d->m_sessionToRestoreAtStartup = dir.dirName();
+ arguments.removeAt(a);
+ continue;
+ } else {
+ // Are there project files in that directory?
+ const QFileInfoList proFiles
+ = dir.entryInfoList(projectGlobs, QDir::Files);
+ if (!proFiles.isEmpty()) {
+ arguments[a] = proFiles.front().absoluteFilePath();
+ ++a;
+ continue;
+ }
+ }
+ // Cannot handle: Avoid mime type warning for directory.
+ qWarning("Skipping directory '%s' passed on to command line.",
+ qPrintable(QDir::toNativeSeparators(arg)));
+ arguments.removeAt(a);
+ continue;
+ } // Done directories.
+ // Converts "filename" "+45" or "filename" ":23" into "filename+45" and "filename:23"
+ if (a && (arg.startsWith(QLatin1Char('+')) || arg.startsWith(QLatin1Char(':')))) {
+ arguments[a - 1].append(arguments.takeAt(a));
+ continue;
+ }
+ ++a;
+ } // for arguments
+ } // !arguments.isEmpty()
// Restore latest session or what was passed on the command line
if (!d->m_sessionToRestoreAtStartup.isEmpty())
d->m_session->loadSession(d->m_sessionToRestoreAtStartup);
@@ -1475,19 +1594,7 @@ void ProjectExplorerPlugin::restoreSession()
connect(d->m_welcomePage, SIGNAL(requestSession(QString)), this, SLOT(loadSession(QString)));
connect(d->m_welcomePage, SIGNAL(requestProject(QString)), this, SLOT(openProjectWelcomePage(QString)));
- QStringList combinedList;
- // Converts "filename" "+45" or "filename" ":23"
- // into "filename+45" and "filename:23"
- foreach (const QString &str, arguments) {
- if (!combinedList.isEmpty() && (str.startsWith(QLatin1Char('+'))
- || str.startsWith(QLatin1Char(':')))) {
- combinedList.last().append(str);
- } else {
- combinedList << str;
- }
- }
-
- Core::ICore::openFiles(combinedList, Core::ICore::OpenFilesFlags(Core::ICore::CanContainLineNumbers | Core::ICore::SwitchMode));
+ Core::ICore::openFiles(arguments, Core::ICore::OpenFilesFlags(Core::ICore::CanContainLineNumbers | Core::ICore::SwitchMode));
updateActions();
}
@@ -1537,9 +1644,8 @@ void ProjectExplorerPlugin::showContextMenu(QWidget *view, const QPoint &globalP
updateContextMenuActions();
d->m_projectTreeCollapseAllAction->disconnect(SIGNAL(triggered()));
connect(d->m_projectTreeCollapseAllAction, SIGNAL(triggered()), view, SLOT(collapseAll()));
- if (contextMenu && contextMenu->actions().count() > 0) {
+ if (contextMenu && contextMenu->actions().count() > 0)
contextMenu->popup(globalPos);
- }
}
BuildManager *ProjectExplorerPlugin::buildManager() const
@@ -1721,6 +1827,17 @@ void ProjectExplorerPlugin::updateActions()
// Context menu actions
d->m_setStartupProjectAction->setParameter(projectNameContextMenu);
+ bool hasDependencies = session()->projectOrder(d->m_currentProject).size() > 1;
+ if (hasDependencies) {
+ d->m_buildActionContextMenu->setText(tr("Build Without Dependencies"));
+ d->m_rebuildActionContextMenu->setText(tr("Rebuild Without Dependencies"));
+ d->m_cleanActionContextMenu->setText(tr("Clean Without Dependencies"));
+ } else {
+ d->m_buildActionContextMenu->setText(tr("Build"));
+ d->m_rebuildActionContextMenu->setText(tr("Rebuild"));
+ d->m_cleanActionContextMenu->setText(tr("Clean"));
+ }
+
d->m_buildActionContextMenu->setEnabled(buildActionContextState.first);
d->m_rebuildActionContextMenu->setEnabled(buildActionContextState.first);
d->m_cleanActionContextMenu->setEnabled(buildActionContextState.first);
@@ -1835,7 +1952,7 @@ int ProjectExplorerPlugin::queue(QList<Project *> projects, QList<Core::Id> step
foreach (const Project *p, projects)
projectNames << p->displayName();
foreach (const Core::Id id, stepIds)
- stepNames << id.name();
+ stepNames << id.toString();
qDebug() << "Building" << stepNames << "for projects" << projectNames;
}
@@ -2007,7 +2124,7 @@ void ProjectExplorerPlugin::runProjectContextMenu()
bool ProjectExplorerPlugin::hasBuildSettings(Project *pro)
{
const QList<Project *> & projects = d->m_session->projectOrder(pro);
- foreach(Project *project, projects)
+ foreach (Project *project, projects)
if (project
&& project->activeTarget()
&& project->activeTarget()->activeBuildConfiguration())
@@ -2033,7 +2150,7 @@ QPair<bool, QString> ProjectExplorerPlugin::buildSettingsEnabled(Project *pro)
result.second = tr("Project has no build settings.");
} else {
const QList<Project *> & projects = d->m_session->projectOrder(pro);
- foreach(Project *project, projects) {
+ foreach (Project *project, projects) {
if (project
&& project->activeTarget()
&& project->activeTarget()->activeBuildConfiguration()
@@ -2063,7 +2180,7 @@ QPair<bool, QString> ProjectExplorerPlugin::buildSettingsEnabledForSession()
result.second = tr("Project has no build settings");
} else {
const QList<Project *> & projects = d->m_session->projectOrder(0);
- foreach(Project *project, projects) {
+ foreach (Project *project, projects) {
if (project
&& project->activeTarget()
&& project->activeTarget()->activeBuildConfiguration()
@@ -2100,7 +2217,7 @@ bool ProjectExplorerPlugin::coreAboutToClose()
bool ProjectExplorerPlugin::hasDeploySettings(Project *pro)
{
const QList<Project *> & projects = d->m_session->projectOrder(pro);
- foreach(Project *project, projects)
+ foreach (Project *project, projects)
if (project->activeTarget()
&& project->activeTarget()->activeDeployConfiguration()
&& !project->activeTarget()->activeDeployConfiguration()->stepList()->isEmpty())
@@ -2401,7 +2518,7 @@ void ProjectExplorerPlugin::addToRecentProjects(const QString &fileName, const Q
QString prettyFileName(QDir::toNativeSeparators(fileName));
QList<QPair<QString, QString> >::iterator it;
- for(it = d->m_recentProjects.begin(); it != d->m_recentProjects.end();)
+ for (it = d->m_recentProjects.begin(); it != d->m_recentProjects.end();)
if ((*it).first == prettyFileName)
it = d->m_recentProjects.erase(it);
else
@@ -2575,11 +2692,10 @@ QString pathOrDirectoryFor(Node *node, bool dir)
}
} else {
QFileInfo fi(path);
- if (dir) {
+ if (dir)
location = fi.isDir() ? fi.absoluteFilePath() : fi.absolutePath();
- } else {
+ else
location = fi.absoluteFilePath();
- }
}
return location;
}
@@ -2810,6 +2926,8 @@ void ProjectExplorerPlugin::renameFile(Node *node, const QString &to)
.arg(orgFilePath)
.arg(newFilePath)
.arg(projectNode->displayName()));
+ } else {
+ setCurrent(d->m_session->projectForFile(newFilePath), newFilePath, 0);
}
}
}
@@ -2864,9 +2982,9 @@ QStringList ProjectExplorerPlugin::projectFilePatterns()
{
QStringList patterns;
const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
- foreach(const IProjectManager *pm, allProjectManagers())
+ foreach (const IProjectManager *pm, allProjectManagers())
if (const Core::MimeType mt = mdb->findByType(pm->mimeType()))
- foreach(const Core::MimeGlobPattern &gp, mt.globPatterns())
+ foreach (const Core::MimeGlobPattern &gp, mt.globPatterns())
patterns += gp.regExp().pattern();
return patterns;
}
diff --git a/src/plugins/projectexplorer/projectexplorer.h b/src/plugins/projectexplorer/projectexplorer.h
index f476cccb9b..c42f453940 100644
--- a/src/plugins/projectexplorer/projectexplorer.h
+++ b/src/plugins/projectexplorer/projectexplorer.h
@@ -81,6 +81,7 @@ public:
Project *openProject(const QString &fileName, QString *error);
QList<Project *> openProjects(const QStringList &fileNames, QString *error);
Q_SLOT void openProjectWelcomePage(const QString &fileName);
+ void unloadProject(Project *project);
SessionManager *session() const;
diff --git a/src/plugins/projectexplorer/projectexplorer.pro b/src/plugins/projectexplorer/projectexplorer.pro
index a4bd7003df..ed9c7cd0aa 100644
--- a/src/plugins/projectexplorer/projectexplorer.pro
+++ b/src/plugins/projectexplorer/projectexplorer.pro
@@ -13,8 +13,10 @@ HEADERS += projectexplorer.h \
abiwidget.h \
clangparser.h \
gcctoolchain.h \
+ localapplicationrunconfiguration.h \
projectexplorer_export.h \
projectwindow.h \
+ removetaskhandler.h \
kit.h \
kitchooser.h \
kitconfigwidget.h \
@@ -65,7 +67,6 @@ HEADERS += projectexplorer.h \
editorsettingspropertiespage.h \
runconfiguration.h \
applicationlauncher.h \
- applicationrunconfiguration.h \
runsettingspropertiespage.h \
projecttreewidget.h \
foldernavigationwidget.h \
@@ -126,14 +127,18 @@ HEADERS += projectexplorer.h \
devicesupport/localprocesslist.h \
devicesupport/sshdeviceprocesslist.h \
deploymentdata.h \
- buildtargetinfo.h
+ buildtargetinfo.h \
+ customtoolchain.h \
+ projectmacroexpander.h
SOURCES += projectexplorer.cpp \
abi.cpp \
abiwidget.cpp \
clangparser.cpp \
gcctoolchain.cpp \
+ localapplicationrunconfiguration.cpp \
projectwindow.cpp \
+ removetaskhandler.cpp \
kit.cpp \
kitchooser.cpp \
kitinformation.cpp \
@@ -178,7 +183,6 @@ SOURCES += projectexplorer.cpp \
editorsettingspropertiespage.cpp \
runconfiguration.cpp \
applicationlauncher.cpp \
- applicationrunconfiguration.cpp \
runsettingspropertiespage.cpp \
projecttreewidget.cpp \
foldernavigationwidget.cpp \
@@ -232,7 +236,9 @@ SOURCES += projectexplorer.cpp \
devicesupport/deviceapplicationrunner.cpp \
devicesupport/localprocesslist.cpp \
devicesupport/sshdeviceprocesslist.cpp \
- deployablefile.cpp
+ deployablefile.cpp \
+ customtoolchain.cpp \
+ projectmacroexpander.cpp
FORMS += processstep.ui \
editorsettingspropertiespage.ui \
diff --git a/src/plugins/projectexplorer/projectexplorer.qbs b/src/plugins/projectexplorer/projectexplorer.qbs
index 6c8b79753f..8b0b5333c1 100644
--- a/src/plugins/projectexplorer/projectexplorer.qbs
+++ b/src/plugins/projectexplorer/projectexplorer.qbs
@@ -1,5 +1,7 @@
import qbs.base 1.0
+
import "../QtcPlugin.qbs" as QtcPlugin
+import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "ProjectExplorer"
@@ -12,79 +14,96 @@ QtcPlugin {
Depends { name: "QtcSsh" }
Depends { name: "cpp" }
- cpp.defines: base.concat(["QTC_CPU=X86Architecture"])
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- "../../libs/utils",
+ cpp.defines: base.concat("QTC_CPU=X86Architecture")
+ cpp.includePaths: base.concat([
"customwizard",
- "publishing",
- buildDirectory
- ]
+ "publishing"
+ ])
files: [
- "doubletabwidget.ui",
- "processstep.ui",
- "projectexplorer.qrc",
- "sessiondialog.ui",
- "targetsettingswidget.ui",
- "projectwizardpage.ui",
+ "abi.cpp",
"abi.h",
"abiwidget.cpp",
"abiwidget.h",
"abstractprocessstep.cpp",
"abstractprocessstep.h",
"allprojectsfilter.cpp",
+ "allprojectsfilter.h",
"allprojectsfind.cpp",
"allprojectsfind.h",
"applicationlauncher.cpp",
"applicationlauncher.h",
- "applicationrunconfiguration.h",
+ "appoutputpane.cpp",
"appoutputpane.h",
"baseprojectwizarddialog.cpp",
"baseprojectwizarddialog.h",
+ "buildconfiguration.cpp",
"buildconfiguration.h",
"buildconfigurationmodel.cpp",
"buildconfigurationmodel.h",
"buildenvironmentwidget.cpp",
"buildenvironmentwidget.h",
+ "buildmanager.cpp",
"buildmanager.h",
+ "buildprogress.cpp",
"buildprogress.h",
+ "buildsettingspropertiespage.cpp",
"buildsettingspropertiespage.h",
"buildstep.cpp",
+ "buildstep.h",
"buildsteplist.cpp",
"buildsteplist.h",
+ "buildstepspage.cpp",
"buildstepspage.h",
+ "buildtargetinfo.h",
"cesdkhandler.cpp",
"cesdkhandler.h",
+ "clangparser.cpp",
"clangparser.h",
+ "codestylesettingspropertiespage.cpp",
"codestylesettingspropertiespage.h",
"codestylesettingspropertiespage.ui",
"compileoutputwindow.cpp",
"compileoutputwindow.h",
+ "copytaskhandler.cpp",
"copytaskhandler.h",
"corelistenercheckingforrunningbuild.cpp",
"corelistenercheckingforrunningbuild.h",
"currentprojectfilter.cpp",
+ "currentprojectfilter.h",
"currentprojectfind.cpp",
"currentprojectfind.h",
+ "customtoolchain.cpp",
+ "customtoolchain.h",
+ "dependenciespanel.cpp",
"dependenciespanel.h",
+ "deployablefile.cpp",
+ "deployablefile.h",
"deployconfiguration.cpp",
"deployconfiguration.h",
"deployconfigurationmodel.cpp",
"deployconfigurationmodel.h",
+ "deploymentdata.h",
+ "doubletabwidget.cpp",
"doubletabwidget.h",
+ "doubletabwidget.ui",
"editorconfiguration.cpp",
"editorconfiguration.h",
+ "editorsettingspropertiespage.cpp",
"editorsettingspropertiespage.h",
"editorsettingspropertiespage.ui",
"environmentitemswidget.cpp",
+ "environmentitemswidget.h",
+ "environmentwidget.cpp",
"environmentwidget.h",
"foldernavigationwidget.cpp",
"foldernavigationwidget.h",
+ "gccparser.cpp",
"gccparser.h",
+ "gcctoolchain.cpp",
+ "gcctoolchain.h",
"gcctoolchainfactories.h",
+ "gnumakeparser.cpp",
"gnumakeparser.h",
"headerpath.h",
"ioutputparser.cpp",
@@ -92,21 +111,6 @@ QtcPlugin {
"iprojectmanager.h",
"iprojectproperties.h",
"itaskhandler.h",
- "ldparser.h",
- "linuxiccparser.h",
- "metatypedeclarations.h",
- "miniprojecttargetselector.h",
- "namedwidget.cpp",
- "namedwidget.h",
- "nodesvisitor.cpp",
- "nodesvisitor.h",
- "outputparser_test.h",
- "pluginfilefactory.cpp",
- "pluginfilefactory.h",
- "processparameters.cpp",
- "processparameters.h",
- "processstep.cpp",
- "processstep.h",
"kit.cpp",
"kit.h",
"kitchooser.cpp",
@@ -124,29 +128,74 @@ QtcPlugin {
"kitmodel.h",
"kitoptionspage.cpp",
"kitoptionspage.h",
+ "ldparser.cpp",
+ "ldparser.h",
+ "linuxiccparser.cpp",
+ "linuxiccparser.h",
+ "localapplicationrunconfiguration.cpp",
+ "localapplicationrunconfiguration.h",
+ "localapplicationruncontrol.cpp",
+ "localapplicationruncontrol.h",
+ "metatypedeclarations.h",
+ "miniprojecttargetselector.cpp",
+ "miniprojecttargetselector.h",
+ "namedwidget.cpp",
+ "namedwidget.h",
+ "nodesvisitor.cpp",
+ "nodesvisitor.h",
+ "outputparser_test.cpp",
+ "outputparser_test.h",
+ "pluginfilefactory.cpp",
+ "pluginfilefactory.h",
+ "processparameters.cpp",
+ "processparameters.h",
+ "processstep.cpp",
+ "processstep.h",
+ "processstep.ui",
"project.cpp",
"project.h",
"projectconfiguration.cpp",
"projectconfiguration.h",
+ "projectexplorer.cpp",
+ "projectexplorer.h",
+ "projectexplorer.qrc",
"projectexplorer_export.h",
+ "projectexplorerconstants.h",
+ "projectexplorersettings.h",
+ "projectexplorersettingspage.cpp",
"projectexplorersettingspage.h",
+ "projectexplorersettingspage.ui",
"projectfilewizardextension.cpp",
"projectfilewizardextension.h",
+ "projectmacroexpander.cpp",
+ "projectmacroexpander.h",
"projectmodels.cpp",
"projectmodels.h",
"projectnodes.cpp",
"projectnodes.h",
+ "projecttreewidget.cpp",
"projecttreewidget.h",
+ "projectwelcomepage.cpp",
"projectwelcomepage.h",
"projectwindow.cpp",
"projectwindow.h",
+ "projectwizardpage.cpp",
"projectwizardpage.h",
+ "projectwizardpage.ui",
+ "removetaskhandler.cpp",
+ "removetaskhandler.h",
+ "runconfiguration.cpp",
+ "runconfiguration.h",
"runconfigurationmodel.cpp",
"runconfigurationmodel.h",
"runsettingspropertiespage.cpp",
"runsettingspropertiespage.h",
+ "session.cpp",
"session.h",
+ "sessiondialog.cpp",
"sessiondialog.h",
+ "sessiondialog.ui",
+ "settingsaccessor.cpp",
"settingsaccessor.h",
"showineditortaskhandler.cpp",
"showineditortaskhandler.h",
@@ -160,87 +209,74 @@ QtcPlugin {
"targetsettingspanel.h",
"targetsettingswidget.cpp",
"targetsettingswidget.h",
+ "targetsettingswidget.ui",
"task.cpp",
"task.h",
"taskhub.cpp",
"taskhub.h",
+ "taskmodel.cpp",
"taskmodel.h",
+ "taskwindow.cpp",
"taskwindow.h",
"toolchain.cpp",
"toolchain.h",
"toolchainconfigwidget.cpp",
"toolchainconfigwidget.h",
- "toolchainmanager.h",
- "toolchainoptionspage.h",
- "vcsannotatetaskhandler.h",
- "environmentitemswidget.h",
- "abi.cpp",
- "allprojectsfilter.h",
- "applicationrunconfiguration.cpp",
- "appoutputpane.cpp",
- "buildconfiguration.cpp",
- "buildmanager.cpp",
- "buildprogress.cpp",
- "buildsettingspropertiespage.cpp",
- "buildstep.h",
- "buildstepspage.cpp",
- "clangparser.cpp",
- "codestylesettingspropertiespage.cpp",
- "copytaskhandler.cpp",
- "currentprojectfilter.h",
- "dependenciespanel.cpp",
- "doubletabwidget.cpp",
- "editorsettingspropertiespage.cpp",
- "environmentwidget.cpp",
- "gccparser.cpp",
- "gcctoolchain.cpp",
- "gcctoolchain.h",
- "gnumakeparser.cpp",
- "ldparser.cpp",
- "linuxiccparser.cpp",
- "localapplicationruncontrol.cpp",
- "localapplicationruncontrol.h",
- "miniprojecttargetselector.cpp",
- "outputparser_test.cpp",
- "projectexplorer.cpp",
- "projectexplorer.h",
- "projectexplorerconstants.h",
- "projectexplorersettings.h",
- "projectexplorersettingspage.cpp",
- "projectexplorersettingspage.ui",
- "projecttreewidget.cpp",
- "projectwelcomepage.cpp",
- "projectwizardpage.cpp",
- "runconfiguration.cpp",
- "runconfiguration.h",
- "session.cpp",
- "sessiondialog.cpp",
- "settingsaccessor.cpp",
- "taskmodel.cpp",
- "taskwindow.cpp",
"toolchainmanager.cpp",
+ "toolchainmanager.h",
"toolchainoptionspage.cpp",
+ "toolchainoptionspage.h",
"vcsannotatetaskhandler.cpp",
+ "vcsannotatetaskhandler.h",
+ "customwizard/customwizard.cpp",
"customwizard/customwizard.h",
"customwizard/customwizardpage.cpp",
"customwizard/customwizardpage.h",
+ "customwizard/customwizardparameters.cpp",
"customwizard/customwizardparameters.h",
"customwizard/customwizardpreprocessor.cpp",
"customwizard/customwizardpreprocessor.h",
"customwizard/customwizardscriptgenerator.cpp",
"customwizard/customwizardscriptgenerator.h",
- "customwizard/customwizard.cpp",
- "customwizard/customwizardparameters.cpp",
- "deployablefile.h",
- "deployablefile.cpp",
- "deploymentdata.h",
- "buildtargetinfo.h",
+ "devicesupport/desktopdevice.cpp",
+ "devicesupport/desktopdevice.h",
+ "devicesupport/desktopdevicefactory.cpp",
+ "devicesupport/desktopdevicefactory.h",
+ "devicesupport/deviceapplicationrunner.cpp",
+ "devicesupport/deviceapplicationrunner.h",
+ "devicesupport/devicefactoryselectiondialog.cpp",
+ "devicesupport/devicefactoryselectiondialog.h",
+ "devicesupport/devicefactoryselectiondialog.ui",
+ "devicesupport/devicemanager.cpp",
+ "devicesupport/devicemanager.h",
+ "devicesupport/devicemanagermodel.cpp",
+ "devicesupport/devicemanagermodel.h",
+ "devicesupport/deviceprocessesdialog.cpp",
+ "devicesupport/deviceprocessesdialog.h",
+ "devicesupport/deviceprocesslist.cpp",
+ "devicesupport/deviceprocesslist.h",
+ "devicesupport/devicesettingspage.cpp",
+ "devicesupport/devicesettingspage.h",
+ "devicesupport/devicesettingswidget.cpp",
+ "devicesupport/devicesettingswidget.h",
+ "devicesupport/devicesettingswidget.ui",
+ "devicesupport/deviceusedportsgatherer.cpp",
+ "devicesupport/deviceusedportsgatherer.h",
+ "devicesupport/idevice.cpp",
+ "devicesupport/idevice.h",
+ "devicesupport/idevicefactory.cpp",
+ "devicesupport/idevicefactory.h",
+ "devicesupport/idevicewidget.h",
+ "devicesupport/localprocesslist.cpp",
+ "devicesupport/localprocesslist.h",
+ "devicesupport/sshdeviceprocesslist.cpp",
+ "devicesupport/sshdeviceprocesslist.h",
"images/BuildSettings.png",
"images/CodeStyleSettings.png",
+ "images/Desktop.png",
"images/DeviceConnected.png",
"images/DeviceDisconnected.png",
"images/DeviceReadyToUse.png",
- "images/Desktop.png",
"images/EditorSettings.png",
"images/MaemoDevice.png",
"images/ProjectDependencies.png",
@@ -269,75 +305,45 @@ QtcPlugin {
"images/session.png",
"images/stop.png",
"images/stop_small.png",
- "images/targetleftbutton.png",
- "images/targetrightbutton.png",
"images/targetbuildselected.png",
+ "images/targetleftbutton.png",
"images/targetpanel_bottom.png",
"images/targetpanel_gradient.png",
"images/targetremovebutton.png",
"images/targetremovebuttondark.png",
+ "images/targetrightbutton.png",
"images/targetrunselected.png",
"images/targetseparatorbackground.png",
"images/targetunselected.png",
"images/window.png",
- "publishing/publishingwizardselectiondialog.ui",
"publishing/ipublishingwizardfactory.h",
"publishing/publishingwizardselectiondialog.cpp",
"publishing/publishingwizardselectiondialog.h",
- "devicesupport/idevice.h",
- "devicesupport/idevice.cpp",
- "devicesupport/desktopdevice.cpp",
- "devicesupport/desktopdevice.h",
- "devicesupport/desktopdevicefactory.cpp",
- "devicesupport/desktopdevicefactory.h",
- "devicesupport/devicemanager.h",
- "devicesupport/devicemanager.cpp",
- "devicesupport/devicemanagermodel.h",
- "devicesupport/devicemanagermodel.cpp",
- "devicesupport/devicesettingspage.h",
- "devicesupport/devicesettingspage.cpp",
- "devicesupport/devicefactoryselectiondialog.cpp",
- "devicesupport/devicefactoryselectiondialog.h",
- "devicesupport/devicefactoryselectiondialog.ui",
- "devicesupport/deviceprocesslist.cpp",
- "devicesupport/deviceprocesslist.h",
- "devicesupport/sshdeviceprocesslist.cpp",
- "devicesupport/sshdeviceprocesslist.h",
- "devicesupport/deviceprocessesdialog.cpp",
- "devicesupport/deviceprocessesdialog.h",
- "devicesupport/devicesettingswidget.cpp",
- "devicesupport/devicesettingswidget.h",
- "devicesupport/devicesettingswidget.ui",
- "devicesupport/deviceusedportsgatherer.cpp",
- "devicesupport/deviceusedportsgatherer.h",
- "devicesupport/idevicewidget.h",
- "devicesupport/idevicefactory.cpp",
- "devicesupport/idevicefactory.h",
- "devicesupport/deviceapplicationrunner.cpp",
- "devicesupport/deviceapplicationrunner.h",
- "devicesupport/localprocesslist.h",
- "devicesupport/localprocesslist.cpp"
+ "publishing/publishingwizardselectiondialog.ui",
]
Group {
- condition: qbs.targetOS == "windows"
+ condition: qbs.targetOS == "windows" || Defaults.testsEnabled(qbs)
files: [
- "wincetoolchain.cpp",
- "wincetoolchain.h",
- "windebuginterface.cpp",
- "windebuginterface.h",
+ "abstractmsvctoolchain.cpp",
+ "abstractmsvctoolchain.h",
"msvcparser.cpp",
"msvcparser.h",
"msvctoolchain.cpp",
"msvctoolchain.h",
- "abstractmsvctoolchain.cpp",
- "abstractmsvctoolchain.h"
+ "wincetoolchain.cpp",
+ "wincetoolchain.h",
+ "windebuginterface.cpp",
+ "windebuginterface.h",
]
}
+ Group {
+ condition: Defaults.testsEnabled(qbs)
+ files: ["outputparser_test.h", "outputparser_test.cpp"]
+ }
+
ProductModule {
- Depends { name: "cpp" }
- Depends { name: "Qt"; submodules: ["network"] }
- cpp.includePaths: [".."]
+ Depends { name: "Qt.network" }
}
}
diff --git a/src/plugins/projectexplorer/projectexplorer.qrc b/src/plugins/projectexplorer/projectexplorer.qrc
index b36371d106..85ea369bbe 100644
--- a/src/plugins/projectexplorer/projectexplorer.qrc
+++ b/src/plugins/projectexplorer/projectexplorer.qrc
@@ -40,7 +40,7 @@
<file>images/unconfigured.png</file>
<file>images/targetleftbutton.png</file>
<file>images/targetrightbutton.png</file>
- <file>images/targetremovebutton.png</file>
- <file>images/targetremovebuttondark.png</file>
+ <file>images/targetchangebutton.png</file>
+ <file>images/targetchangebutton2.png</file>
</qresource>
</RCC>
diff --git a/src/plugins/projectexplorer/projectexplorerconstants.h b/src/plugins/projectexplorer/projectexplorerconstants.h
index 84009b2527..76bea57d35 100644
--- a/src/plugins/projectexplorer/projectexplorerconstants.h
+++ b/src/plugins/projectexplorer/projectexplorerconstants.h
@@ -170,7 +170,7 @@ const char C_HEADER_MIMETYPE[] = "text/x-chdr";
const char CPP_SOURCE_MIMETYPE[] = "text/x-c++src";
const char CPP_HEADER_MIMETYPE[] = "text/x-c++hdr";
const char FORM_MIMETYPE[] = "application/x-designer";
-const char QML_MIMETYPE[] = "application/x-qml";
+const char QML_MIMETYPE[] = "application/x-qml"; // separate def also in qmljstoolsconstants.h
const char RESOURCE_MIMETYPE[] = "application/vnd.nokia.xml.qt.resource";
// Settings page
@@ -182,7 +182,7 @@ const char TOOLCHAIN_SETTINGS_PAGE_ID[] = "M.ProjectExplorer.ToolChainOptions";
const char KITS_SETTINGS_PAGE_ID[] = "D.ProjectExplorer.KitsOptions";
// Device settings page
-const char DEVICE_SETTINGS_CATEGORY[] = "X.Devices";
+const char DEVICE_SETTINGS_CATEGORY[] = "XW.Devices";
const char DEVICE_SETTINGS_PAGE_ID[] = "AA.Device Settings";
// Task categories
@@ -224,6 +224,7 @@ const char LINUXICC_TOOLCHAIN_ID[] = "ProjectExplorer.ToolChain.LinuxIcc";
const char MINGW_TOOLCHAIN_ID[] = "ProjectExplorer.ToolChain.Mingw";
const char MSVC_TOOLCHAIN_ID[] = "ProjectExplorer.ToolChain.Msvc";
const char WINCE_TOOLCHAIN_ID[] = "ProjectExplorer.ToolChain.WinCE";
+const char CUSTOM_TOOLCHAIN_ID[] = "ProjectExplorer.ToolChain.Custom";
// Run Configuration defaults:
const int QML_DEFAULT_DEBUG_SERVER_PORT = 3768;
@@ -235,6 +236,17 @@ const char DEFAULT_WORKING_DIR[] = "%{buildDir}";
const char DESKTOP_DEVICE_ID[] = "Desktop Device";
const char DESKTOP_DEVICE_TYPE[] = "Desktop";
+// Variable Names:
+const char VAR_CURRENTPROJECT_PATH[] = "CurrentProject:Path";
+const char VAR_CURRENTPROJECT_FILEPATH[] = "CurrentProject:FilePath";
+const char VAR_CURRENTPROJECT_BUILDPATH[] = "CurrentProject:BuildPath";
+const char VAR_CURRENTPROJECT_NAME[] = "CurrentProject:Name";
+const char VAR_CURRENTKIT_NAME[] = "CurrentKit:Name";
+const char VAR_CURRENTKIT_FILESYSTEMNAME[] = "CurrentKit:FileSystemName";
+const char VAR_CURRENTKIT_ID[] = "CurrentKit:Id";
+const char VAR_CURRENTBUILD_NAME[] = "CurrentBuild:Name";
+const char VAR_CURRENTBUILD_TYPE[] = "CurrentBuild:Type";
+
} // namespace Constants
// Run modes
diff --git a/src/plugins/projectexplorer/projectexplorersettingspage.cpp b/src/plugins/projectexplorer/projectexplorersettingspage.cpp
index afb21e9d68..1673bfaf64 100644
--- a/src/plugins/projectexplorer/projectexplorersettingspage.cpp
+++ b/src/plugins/projectexplorer/projectexplorersettingspage.cpp
@@ -32,8 +32,10 @@
#include "projectexplorerconstants.h"
#include "projectexplorer.h"
-#include <coreplugin/icore.h>
+#include <coreplugin/coreconstants.h>
#include <coreplugin/documentmanager.h>
+#include <coreplugin/icore.h>
+#include <utils/hostosinfo.h>
#include <QLabel>
#include <QCoreApplication>
@@ -47,13 +49,15 @@ ProjectExplorerSettingsWidget::ProjectExplorerSettingsWidget(QWidget *parent) :
QWidget(parent)
{
m_ui.setupUi(this);
-#ifndef Q_OS_WIN
- setJomVisible(false);
-#endif
+ setJomVisible(Utils::HostOsInfo::isWindowsHost());
m_ui.directoryButtonGroup->setId(m_ui.currentDirectoryRadioButton, UseCurrentDirectory);
m_ui.directoryButtonGroup->setId(m_ui.directoryRadioButton, UseProjectDirectory);
+ m_ui.buildDirectoryEdit->setProperty(Core::Constants::VARIABLE_SUPPORT_PROPERTY, true);
+
connect(m_ui.directoryButtonGroup, SIGNAL(buttonClicked(int)),
this, SLOT(slotDirectoryButtonGroupChanged()));
+ connect(m_ui.resetButton, SIGNAL(clicked()), this, SLOT(resetDefaultBuildDirectory()));
+ connect(m_ui.buildDirectoryEdit, SIGNAL(textChanged(QString)), this, SLOT(updateResetButton()));
}
void ProjectExplorerSettingsWidget::setJomVisible(bool v)
@@ -119,9 +123,30 @@ void ProjectExplorerSettingsWidget::setUseProjectsDirectory(bool b)
}
}
+QString ProjectExplorerSettingsWidget::buildDirectory() const
+{
+ return m_ui.buildDirectoryEdit->text();
+}
+
+void ProjectExplorerSettingsWidget::setBuildDirectory(const QString &bd)
+{
+ m_ui.buildDirectoryEdit->setText(bd);
+}
+
void ProjectExplorerSettingsWidget::slotDirectoryButtonGroupChanged()
{
- m_ui.projectsDirectoryPathChooser->setEnabled(useProjectsDirectory());
+ bool enable = useProjectsDirectory();
+ m_ui.projectsDirectoryPathChooser->setEnabled(enable);
+}
+
+void ProjectExplorerSettingsWidget::resetDefaultBuildDirectory()
+{
+ setBuildDirectory(QLatin1String(Core::Constants::DEFAULT_BUILD_DIRECTORY));
+}
+
+void ProjectExplorerSettingsWidget::updateResetButton()
+{
+ m_ui.resetButton->setEnabled(buildDirectory() != QLatin1String(Core::Constants::DEFAULT_BUILD_DIRECTORY));
}
QString ProjectExplorerSettingsWidget::searchKeywords() const
@@ -150,9 +175,9 @@ QString ProjectExplorerSettingsWidget::searchKeywords() const
// ------------------ ProjectExplorerSettingsPage
ProjectExplorerSettingsPage::ProjectExplorerSettingsPage()
{
- setId(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_ID));
+ setId(Constants::PROJECTEXPLORER_SETTINGS_ID);
setDisplayName(tr("General"));
- setCategory(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY));
+ setCategory(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
@@ -168,6 +193,7 @@ QWidget *ProjectExplorerSettingsPage::createPage(QWidget *parent)
m_widget->setSettings(ProjectExplorerPlugin::instance()->projectExplorerSettings());
m_widget->setProjectsDirectory(Core::DocumentManager::projectsDirectory());
m_widget->setUseProjectsDirectory(Core::DocumentManager::useProjectsDirectory());
+ m_widget->setBuildDirectory(Core::DocumentManager::buildDirectory());
if (m_searchKeywords.isEmpty())
m_searchKeywords = m_widget->searchKeywords();
return m_widget;
@@ -179,6 +205,7 @@ void ProjectExplorerSettingsPage::apply()
ProjectExplorerPlugin::instance()->setProjectExplorerSettings(m_widget->settings());
Core::DocumentManager::setProjectsDirectory(m_widget->projectsDirectory());
Core::DocumentManager::setUseProjectsDirectory(m_widget->useProjectsDirectory());
+ Core::DocumentManager::setBuildDirectory(m_widget->buildDirectory());
}
}
diff --git a/src/plugins/projectexplorer/projectexplorersettingspage.h b/src/plugins/projectexplorer/projectexplorersettingspage.h
index e4f0764578..f84d9981bb 100644
--- a/src/plugins/projectexplorer/projectexplorersettingspage.h
+++ b/src/plugins/projectexplorer/projectexplorersettingspage.h
@@ -55,10 +55,15 @@ public:
bool useProjectsDirectory();
void setUseProjectsDirectory(bool v);
+ QString buildDirectory() const;
+ void setBuildDirectory(const QString &bd);
+
QString searchKeywords() const;
private slots:
void slotDirectoryButtonGroupChanged();
+ void resetDefaultBuildDirectory();
+ void updateResetButton();
private:
void setJomVisible(bool);
diff --git a/src/plugins/projectexplorer/projectexplorersettingspage.ui b/src/plugins/projectexplorer/projectexplorersettingspage.ui
index 6f13f17fd7..7963fd4bc7 100644
--- a/src/plugins/projectexplorer/projectexplorersettingspage.ui
+++ b/src/plugins/projectexplorer/projectexplorersettingspage.ui
@@ -20,6 +20,9 @@
<property name="fieldGrowthPolicy">
<enum>QFormLayout::ExpandingFieldsGrow</enum>
</property>
+ <property name="labelAlignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
+ </property>
<item row="0" column="0" colspan="2">
<widget class="QRadioButton" name="currentDirectoryRadioButton">
<property name="text">
@@ -44,7 +47,7 @@
</widget>
</item>
<item row="1" column="1">
- <widget class="Utils::PathChooser" name="projectsDirectoryPathChooser" native="true"/>
+ <widget class="Utils::PathChooser" name="projectsDirectoryPathChooser"/>
</item>
</layout>
</widget>
@@ -107,7 +110,7 @@
</property>
</widget>
</item>
- <item row="3" column="1" rowspan="2">
+ <item row="3" column="1">
<widget class="QWidget" name="widget" native="true">
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="margin">
@@ -146,7 +149,21 @@
</layout>
</widget>
</item>
- <item row="7" column="0">
+ <item row="4" column="0">
+ <widget class="QCheckBox" name="showRunOutputCheckBox">
+ <property name="text">
+ <string>Open application output pane when running</string>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="0">
+ <widget class="QCheckBox" name="showDebugOutputCheckBox">
+ <property name="text">
+ <string>Open application output pane when debugging</string>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="0">
<widget class="QCheckBox" name="promptToStopRunControlCheckBox">
<property name="toolTip">
<string>Ask before terminating the running application in response to clicking the stop button in Application Output.</string>
@@ -156,7 +173,7 @@
</property>
</widget>
</item>
- <item row="8" column="0" colspan="2">
+ <item row="7" column="0" colspan="2">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
@@ -189,19 +206,29 @@
</item>
</layout>
</item>
- <item row="5" column="0">
- <widget class="QCheckBox" name="showRunOutputCheckBox">
- <property name="text">
- <string>Open application output pane when running</string>
- </property>
- </widget>
- </item>
- <item row="6" column="0">
- <widget class="QCheckBox" name="showDebugOutputCheckBox">
- <property name="text">
- <string>Open application output pane when debugging</string>
+ <item row="8" column="0" colspan="2">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <property name="topMargin">
+ <number>12</number>
</property>
- </widget>
+ <item>
+ <widget class="QLabel" name="buildDirLabel">
+ <property name="text">
+ <string>Default Build Directory:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLineEdit" name="buildDirectoryEdit"/>
+ </item>
+ <item>
+ <widget class="QPushButton" name="resetButton">
+ <property name="text">
+ <string>Reset</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
</item>
</layout>
<zorder>saveAllFilesCheckBox</zorder>
@@ -235,8 +262,9 @@
<customwidgets>
<customwidget>
<class>Utils::PathChooser</class>
- <extends>QWidget</extends>
- <header location="global">utils/pathchooser.h</header>
+ <extends>QLineEdit</extends>
+ <header>utils/pathchooser.h</header>
+ <container>1</container>
</customwidget>
</customwidgets>
<resources/>
diff --git a/src/plugins/projectexplorer/projectfilewizardextension.cpp b/src/plugins/projectexplorer/projectfilewizardextension.cpp
index f388c8f22f..28b9de349a 100644
--- a/src/plugins/projectexplorer/projectfilewizardextension.cpp
+++ b/src/plugins/projectexplorer/projectfilewizardextension.cpp
@@ -313,11 +313,10 @@ void ProjectFileWizardExtension::firstExtensionPageShown(
m_context->page->setNoneLabel(tr("<None>"));
}
- if (bestProjectIndex == -1) {
+ if (bestProjectIndex == -1)
m_context->page->setCurrentProjectIndex(0);
- } else {
+ else
m_context->page->setCurrentProjectIndex(bestProjectIndex + 1);
- }
// Store all version controls for later use:
if (m_context->versionControls.isEmpty()) {
@@ -377,11 +376,10 @@ void ProjectFileWizardExtension::initializeVersionControlChoices()
QList<QWizardPage *> ProjectFileWizardExtension::extensionPages(const Core::IWizard *wizard)
{
- if (!m_context) {
+ if (!m_context)
m_context = new ProjectWizardContext;
- } else {
+ else
m_context->clear();
- }
// Init context with page and projects
m_context->page = new ProjectWizardPage;
m_context->wizard = wizard;
@@ -410,7 +408,7 @@ static inline void getProjectChoicesAndToolTips(QStringList *projectChoicesParam
ProjectNode::ProjectAction projectAction =
context->wizard->kind() == Core::IWizard::ProjectWizard
? ProjectNode::AddSubProject : ProjectNode::AddNewFile;
- foreach(ProjectNode *n, AllProjectNodesVisitor::allProjects(projectAction)) {
+ foreach (ProjectNode *n, AllProjectNodesVisitor::allProjects(projectAction)) {
if (projectAction == ProjectNode::AddNewFile
|| (projectAction == ProjectNode::AddSubProject
&& (generatedProjectFilePath.isEmpty() ? true : n->canAddSubProject(generatedProjectFilePath))))
@@ -524,9 +522,9 @@ bool ProjectFileWizardExtension::processVersionControl(const QList<Core::Generat
return true;
}
-static TextEditor::ICodeStylePreferences *codeStylePreferences(ProjectExplorer::Project *project, const QString &languageId)
+static TextEditor::ICodeStylePreferences *codeStylePreferences(ProjectExplorer::Project *project, Core::Id languageId)
{
- if (languageId.isEmpty())
+ if (!languageId.isValid())
return 0;
if (project)
@@ -542,9 +540,9 @@ void ProjectFileWizardExtension::applyCodeStyle(Core::GeneratedFile *file) const
const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
Core::MimeType mt = mdb->findByFile(QFileInfo(file->path()));
- const QString languageId = TextEditor::TextEditorSettings::instance()->languageId(mt.type());
+ Core::Id languageId = TextEditor::TextEditorSettings::instance()->languageId(mt.type());
- if (languageId.isEmpty())
+ if (!languageId.isValid())
return; // don't modify files like *.ui *.pro
ProjectNode *project = 0;
diff --git a/src/plugins/projectexplorer/projectmacroexpander.cpp b/src/plugins/projectexplorer/projectmacroexpander.cpp
new file mode 100644
index 0000000000..22a03bbf56
--- /dev/null
+++ b/src/plugins/projectexplorer/projectmacroexpander.cpp
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "projectmacroexpander.h"
+#include "kit.h"
+#include "projectexplorerconstants.h"
+
+#include <coreplugin/variablemanager.h>
+
+using namespace ProjectExplorer;
+
+ProjectExpander::ProjectExpander(const QString &projectFilePath, const QString &projectName,
+ const Kit *k, const QString &bcName)
+ : m_projectFile(projectFilePath), m_projectName(projectName), m_kit(k), m_bcName(bcName)
+{ }
+
+bool ProjectExpander::resolveMacro(const QString &name, QString *ret)
+{
+ QString result;
+ bool found = false;
+ if (name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTPROJECT_NAME)) {
+ result = m_projectName;
+ found = true;
+ } else if (name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTPROJECT_PATH)) {
+ result = m_projectFile.absolutePath();
+ found = true;
+ } else if (name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTPROJECT_FILEPATH)) {
+ result = m_projectFile.absoluteFilePath();
+ found = true;
+ } else if (m_kit && name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTKIT_NAME)) {
+ result = m_kit->displayName();
+ found = true;
+ } else if (m_kit && name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTKIT_FILESYSTEMNAME)) {
+ result = m_kit->fileSystemFriendlyName();
+ found = true;
+ } else if (m_kit && name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTKIT_ID)) {
+ result = m_kit->id().toString();
+ found = true;
+ } else if (name == QLatin1String(ProjectExplorer::Constants::VAR_CURRENTBUILD_NAME)) {
+ result = m_bcName;
+ found = true;
+ } else {
+ result = Core::VariableManager::instance()->value(name.toUtf8(), &found);
+ }
+ if (ret)
+ *ret = result;
+ return found;
+}
diff --git a/tests/auto/icheckbuild/ichecklib.h b/src/plugins/projectexplorer/projectmacroexpander.h
index 4133c03d22..eb5d51f3e3 100644
--- a/tests/auto/icheckbuild/ichecklib.h
+++ b/src/plugins/projectexplorer/projectmacroexpander.h
@@ -27,23 +27,28 @@
**
****************************************************************************/
-#ifndef ICHECKLIB_H
-#define ICHECKLIB_H
+#ifndef PROJECTMACROEXPANDER_H
+#define PROJECTMACROEXPANDER_H
-#include <QStringList>
-#include "ichecklib_global.h"
+#include "projectexplorer_export.h"
+#include <utils/stringutils.h>
+#include <QFileInfo>
-namespace CPlusPlus{
- class ParseManager;
-}
-class ICHECKLIBSHARED_EXPORT ICheckLib {
+namespace ProjectExplorer {
+class Kit;
+
+class PROJECTEXPLORER_EXPORT ProjectExpander : public Utils::AbstractQtcMacroExpander
+{
public:
- ICheckLib();
- void ParseHeader(const QStringList& includePath, const QStringList& filelist);
- bool check(const ICheckLib& ichecklib /*ICheckLib from interface header*/, QString outputfile);
- QStringList getErrorMsg();
+ ProjectExpander(const QString &projectFilePath, const QString &projectName, const Kit *k, const QString &bcName);
+ bool resolveMacro(const QString &name, QString *ret);
+
private:
- CPlusPlus::ParseManager* pParseManager;
+ QFileInfo m_projectFile;
+ QString m_projectName;
+ const Kit *m_kit;
+ QString m_bcName;
};
+} // namespace
-#endif // ICHECKLIB_H
+#endif // PROJECTMACROEXPANDER_H
diff --git a/src/plugins/projectexplorer/projectmodels.cpp b/src/plugins/projectexplorer/projectmodels.cpp
index 7c206ddf80..b9c7ffaea5 100644
--- a/src/plugins/projectexplorer/projectmodels.cpp
+++ b/src/plugins/projectexplorer/projectmodels.cpp
@@ -75,9 +75,8 @@ bool sortNodes(Node *n1, Node *n2)
return true; // project file is before everything else
}
} else {
- if (file2 && file2->fileType() == ProjectFileType) {
+ if (file2 && file2->fileType() == ProjectFileType)
return false;
- }
}
// projects
@@ -151,11 +150,10 @@ bool sortNodes(Node *n1, Node *n2)
return result < 0; // sort by filename
} else {
result = caseFriendlyCompare(filePath1, filePath2);
- if (result != 0) {
+ if (result != 0)
return result < 0; // sort by filepath
- } else {
+ else
return n1 < n2; // sort by pointer value
- }
}
}
return false;
@@ -199,6 +197,9 @@ FlatModel::FlatModel(SessionNode *rootNode, QObject *parent)
this, SLOT(filesAboutToBeRemoved(FolderNode*,QList<FileNode*>)));
connect(watcher, SIGNAL(filesRemoved()),
this, SLOT(filesRemoved()));
+
+ connect(watcher, SIGNAL(nodeUpdated(ProjectExplorer::Node*)),
+ this, SLOT(nodeUpdated(ProjectExplorer::Node*)));
}
QModelIndex FlatModel::index(int row, int column, const QModelIndex &parent) const
@@ -258,7 +259,20 @@ QVariant FlatModel::data(const QModelIndex &index, int role) const
if (Node *node = nodeForIndex(index)) {
FolderNode *folderNode = qobject_cast<FolderNode*>(node);
switch (role) {
- case Qt::DisplayRole:
+ case Qt::DisplayRole: {
+ QString name = node->displayName();
+
+ if (node->parentFolderNode()
+ && node->parentFolderNode()->nodeType() == SessionNodeType) {
+ const QString vcsTopic = node->vcsTopic();
+
+ if (!vcsTopic.isEmpty())
+ name += QLatin1String(" (") + vcsTopic + QLatin1Char(')');
+ }
+
+ result = name;
+ break;
+ }
case Qt::EditRole: {
result = node->displayName();
break;
@@ -285,6 +299,10 @@ QVariant FlatModel::data(const QModelIndex &index, int role) const
result = node->path();
break;
}
+ case ProjectExplorer::Project::EnabledRole: {
+ result = node->isEnabled();
+ break;
+ }
}
}
@@ -300,6 +318,8 @@ Qt::ItemFlags FlatModel::flags(const QModelIndex &index) const
// We control the only view, and that one does the checks
Qt::ItemFlags f = Qt::ItemIsSelectable|Qt::ItemIsEnabled;
if (Node *node = nodeForIndex(index)) {
+ if (node == m_rootNode)
+ return 0; // no flags for session node...
if (!qobject_cast<ProjectNode *>(node)) {
// either folder or file node
if (node->projectNode()->supportedActions(node).contains(ProjectNode::Rename))
@@ -451,8 +471,9 @@ void FlatModel::setStartupProject(ProjectNode *projectNode)
void FlatModel::reset()
{
+ beginResetModel();
m_childNodes.clear();
- QAbstractItemModel::reset();
+ endResetModel();
}
QModelIndex FlatModel::indexForNode(const Node *node_)
@@ -822,7 +843,7 @@ void FlatModel::filesAboutToBeRemoved(FolderNode *folder, const QList<FileNode*>
FolderNode *folderNode = visibleFolderNode(folder);
QSet<Node *> blackList;
- foreach(Node *node, staleFiles)
+ foreach (Node *node, staleFiles)
blackList.insert(node);
// Now get the new List for that folder
@@ -835,6 +856,12 @@ void FlatModel::filesRemoved()
// Do nothing
}
+void FlatModel::nodeUpdated(Node *node)
+{
+ QModelIndex idx = indexForNode(node);
+ emit dataChanged(idx, idx);
+}
+
namespace ProjectExplorer {
namespace Internal {
diff --git a/src/plugins/projectexplorer/projectmodels.h b/src/plugins/projectexplorer/projectmodels.h
index 45cfebf4f9..c57d5890f2 100644
--- a/src/plugins/projectexplorer/projectmodels.h
+++ b/src/plugins/projectexplorer/projectmodels.h
@@ -93,6 +93,8 @@ private slots:
void filesAboutToBeRemoved(FolderNode *folder, const QList<FileNode*> &staleFiles);
void filesRemoved();
+ void nodeUpdated(ProjectExplorer::Node *node);
+
private:
void added(FolderNode* folderNode, const QList<Node*> &newNodeList);
void removed(FolderNode* parentNode, const QList<Node*> &newNodeList);
diff --git a/src/plugins/projectexplorer/projectnodes.cpp b/src/plugins/projectexplorer/projectnodes.cpp
index 05707563b5..7c04426e41 100644
--- a/src/plugins/projectexplorer/projectnodes.cpp
+++ b/src/plugins/projectexplorer/projectnodes.cpp
@@ -34,6 +34,9 @@
#include <coreplugin/mimedatabase.h>
#include <coreplugin/fileiconprovider.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/iversioncontrol.h>
+#include <coreplugin/vcsmanager.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
@@ -104,11 +107,21 @@ QString Node::displayName() const
return QFileInfo(path()).fileName();
}
+QString Node::vcsTopic() const
+{
+ return QString();
+}
+
QString Node::tooltip() const
{
return QDir::toNativeSeparators(path());
}
+bool Node::isEnabled() const
+{
+ return parentFolderNode()->isEnabled();
+}
+
void Node::setNodeType(NodeType type)
{
m_nodeType = type;
@@ -119,6 +132,12 @@ void Node::setProjectNode(ProjectNode *project)
m_projectNode = project;
}
+void Node::emitNodeUpdated()
+{
+ foreach (NodesWatcher *watcher, projectNode()->watchers())
+ emit watcher->nodeUpdated(this);
+}
+
void Node::setParentFolderNode(FolderNode *parentFolder)
{
m_folderNode = parentFolder;
@@ -269,6 +288,16 @@ ProjectNode::ProjectNode(const QString &projectFilePath)
setDisplayName(QFileInfo(projectFilePath).fileName());
}
+QString ProjectNode::vcsTopic() const {
+ const QString dir = QFileInfo(path()).absolutePath();
+
+ if (Core::IVersionControl *const vc =
+ Core::ICore::vcsManager()->findVersionControlForDirectory(dir))
+ return vc->vcsTopic(dir);
+
+ return QString();
+}
+
QList<ProjectNode*> ProjectNode::subProjectNodes() const
{
return m_subProjectNodes;
@@ -738,7 +767,7 @@ void SessionNode::watcherDestroyed(QObject *watcher)
by calling ProjectNode::unregisterWatcher and
SessionNode::unregisterWatcher().
- The NodesWatcher is similar to the Observer in the
+ The NodesWatcher is similar to the Observer in the
well-known Observer pattern (Booch et al).
\sa ProjectExplorer::Node
@@ -767,7 +796,8 @@ FileType typeForFileName(const Core::MimeDatabase *db, const QFileInfo &file)
return ResourceType;
if (typeName == QLatin1String(Constants::FORM_MIMETYPE))
return FormType;
- if (typeName == QLatin1String(Constants::QML_MIMETYPE))
+ if (mt.subClassesOf().contains(QLatin1String(Constants::QML_MIMETYPE))
+ || typeName == QLatin1String(Constants::QML_MIMETYPE))
return QMLType;
return UnknownFileType;
}
diff --git a/src/plugins/projectexplorer/projectnodes.h b/src/plugins/projectexplorer/projectnodes.h
index 8d632b2141..749dda0368 100644
--- a/src/plugins/projectexplorer/projectnodes.h
+++ b/src/plugins/projectexplorer/projectnodes.h
@@ -86,7 +86,9 @@ public:
FolderNode *parentFolderNode() const; // parent folder or project
QString path() const; // file system path
virtual QString displayName() const;
+ virtual QString vcsTopic() const;
virtual QString tooltip() const;
+ virtual bool isEnabled() const;
protected:
Node(NodeType nodeType, const QString &path);
@@ -95,6 +97,8 @@ protected:
void setProjectNode(ProjectNode *project);
void setParentFolderNode(FolderNode *parentFolder);
+ void emitNodeUpdated();
+
private:
NodeType m_nodeType;
ProjectNode *m_projectNode;
@@ -183,6 +187,8 @@ public:
HasSubProjectRunConfigurations
};
+ QString vcsTopic() const;
+
// all subFolders that are projects
QList<ProjectNode*> subProjectNodes() const;
@@ -225,6 +231,8 @@ public:
void accept(NodesVisitor *visitor);
+ bool isEnabled() const { return true; }
+
protected:
// this is just the in-memory representation, a subclass
// will add the persistent stuff
@@ -267,6 +275,8 @@ public:
void accept(NodesVisitor *visitor);
+ bool isEnabled() const { return true; }
+
protected:
void addProjectNodes(const QList<ProjectNode*> &projectNodes);
void removeProjectNodes(const QList<ProjectNode*> &projectNodes);
@@ -286,6 +296,11 @@ public:
explicit NodesWatcher(QObject *parent = 0);
signals:
+ // everything
+
+ // Emited whenever the model needs to send a update signal.
+ void nodeUpdated(ProjectExplorer::Node *node);
+
// projects
void aboutToChangeHasBuildTargets(ProjectExplorer::ProjectNode*);
void hasBuildTargetsChanged(ProjectExplorer::ProjectNode *node);
@@ -313,6 +328,7 @@ private:
// let project & session emit signals
friend class ProjectNode;
friend class SessionNode;
+ friend class Node;
};
diff --git a/src/plugins/projectexplorer/projecttreewidget.cpp b/src/plugins/projectexplorer/projecttreewidget.cpp
index 3109d596e2..ab8fe7ec20 100644
--- a/src/plugins/projectexplorer/projecttreewidget.cpp
+++ b/src/plugins/projectexplorer/projecttreewidget.cpp
@@ -49,6 +49,7 @@
#include <QSettings>
#include <QHeaderView>
+#include <QStyledItemDelegate>
#include <QTreeView>
#include <QVBoxLayout>
#include <QToolButton>
@@ -57,11 +58,28 @@
#include <QPalette>
#include <QMenu>
+using namespace Core;
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
namespace {
- bool debug = false;
+
+class ProjectTreeItemDelegate : public QStyledItemDelegate
+{
+public:
+ ProjectTreeItemDelegate(QObject *parent) : QStyledItemDelegate(parent)
+ { }
+
+ void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
+ {
+ QStyleOptionViewItem opt = option;
+ if (!index.data(ProjectExplorer::Project::EnabledRole).toBool())
+ opt.state &= ~QStyle::State_Enabled;
+ QStyledItemDelegate::paint(painter, opt, index);
+ }
+};
+
+bool debug = false;
}
class ProjectTreeView : public Utils::NavigationTreeView
@@ -71,20 +89,19 @@ public:
{
setEditTriggers(QAbstractItemView::EditKeyPressed);
setContextMenuPolicy(Qt::CustomContextMenu);
-// setExpandsOnDoubleClick(false);
- m_context = new Core::IContext(this);
- m_context->setContext(Core::Context(Constants::C_PROJECT_TREE));
+ m_context = new IContext(this);
+ m_context->setContext(Context(ProjectExplorer::Constants::C_PROJECT_TREE));
m_context->setWidget(this);
- Core::ICore::addContextObject(m_context);
+ ICore::addContextObject(m_context);
}
~ProjectTreeView()
{
- Core::ICore::removeContextObject(m_context);
+ ICore::removeContextObject(m_context);
delete m_context;
}
private:
- Core::IContext *m_context;
+ IContext *m_context;
};
/*!
@@ -115,6 +132,7 @@ ProjectTreeWidget::ProjectTreeWidget(QWidget *parent)
m_view = new ProjectTreeView;
m_view->setModel(m_model);
+ m_view->setItemDelegate(new ProjectTreeItemDelegate(this));
setFocusProxy(m_view);
initView();
@@ -208,7 +226,7 @@ void ProjectTreeWidget::recursiveSaveExpandData(const QModelIndex &index, QStrin
void ProjectTreeWidget::foldersAboutToBeRemoved(FolderNode *, const QList<FolderNode*> &list)
{
Node *n = m_explorer->currentNode();
- while(n) {
+ while (n) {
if (FolderNode *fn = qobject_cast<FolderNode *>(n)) {
if (list.contains(fn)) {
ProjectNode *pn = n->projectNode();
@@ -226,9 +244,8 @@ void ProjectTreeWidget::foldersAboutToBeRemoved(FolderNode *, const QList<Folder
void ProjectTreeWidget::filesAboutToBeRemoved(FolderNode *, const QList<FileNode*> &list)
{
if (FileNode *fileNode = qobject_cast<FileNode *>(m_explorer->currentNode())) {
- if (list.contains(fileNode)) {
+ if (list.contains(fileNode))
m_explorer->setCurrentNode(fileNode->projectNode());
- }
}
}
@@ -285,9 +302,8 @@ void ProjectTreeWidget::setCurrentItem(Node *node, Project *project)
qDebug() << "ProjectTreeWidget::setCurrentItem(" << (project ? project->displayName() : QLatin1String("0"))
<< ", " << (node ? node->path() : QLatin1String("0")) << ")";
- if (!project) {
+ if (!project)
return;
- }
const QModelIndex mainIndex = m_model->indexForNode(node);
@@ -359,7 +375,7 @@ void ProjectTreeWidget::openItem(const QModelIndex &mainIndex)
{
Node *node = m_model->nodeForIndex(mainIndex);
if (node->nodeType() == FileNodeType)
- Core::EditorManager::openEditor(node->path(), Core::Id(), Core::EditorManager::ModeSwitch);
+ EditorManager::openEditor(node->path(), Id(), EditorManager::ModeSwitch);
}
void ProjectTreeWidget::setProjectFilter(bool filter)
@@ -403,19 +419,19 @@ int ProjectTreeWidgetFactory::priority() const
return 100;
}
-Core::Id ProjectTreeWidgetFactory::id() const
+Id ProjectTreeWidgetFactory::id() const
{
- return Core::Id("Projects");
+ return Id("Projects");
}
QKeySequence ProjectTreeWidgetFactory::activationSequence() const
{
- return QKeySequence(Core::UseMacShortcuts ? tr("Meta+X") : tr("Alt+X"));
+ return QKeySequence(UseMacShortcuts ? tr("Meta+X") : tr("Alt+X"));
}
-Core::NavigationView ProjectTreeWidgetFactory::createWidget()
+NavigationView ProjectTreeWidgetFactory::createWidget()
{
- Core::NavigationView n;
+ NavigationView n;
ProjectTreeWidget *ptw = new ProjectTreeWidget;
n.widget = ptw;
@@ -437,7 +453,7 @@ void ProjectTreeWidgetFactory::saveSettings(int position, QWidget *widget)
{
ProjectTreeWidget *ptw = qobject_cast<ProjectTreeWidget *>(widget);
Q_ASSERT(ptw);
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
const QString baseKey = QLatin1String("ProjectTreeWidget.") + QString::number(position);
settings->setValue(baseKey + QLatin1String(".ProjectFilter"), ptw->projectFilter());
settings->setValue(baseKey + QLatin1String(".GeneratedFilter"), ptw->generatedFilesFilter());
@@ -448,7 +464,7 @@ void ProjectTreeWidgetFactory::restoreSettings(int position, QWidget *widget)
{
ProjectTreeWidget *ptw = qobject_cast<ProjectTreeWidget *>(widget);
Q_ASSERT(ptw);
- QSettings *settings = Core::ICore::settings();
+ QSettings *settings = ICore::settings();
const QString baseKey = QLatin1String("ProjectTreeWidget.") + QString::number(position);
ptw->setProjectFilter(settings->value(baseKey + QLatin1String(".ProjectFilter"), false).toBool());
ptw->setGeneratedFilesFilter(settings->value(baseKey + QLatin1String(".GeneratedFilter"), true).toBool());
diff --git a/src/plugins/projectexplorer/projectwelcomepage.cpp b/src/plugins/projectexplorer/projectwelcomepage.cpp
index 16e1232e95..1b4acb2fcd 100644
--- a/src/plugins/projectexplorer/projectwelcomepage.cpp
+++ b/src/plugins/projectexplorer/projectwelcomepage.cpp
@@ -114,7 +114,8 @@ bool SessionModel::isDefaultVirgin() const
void SessionModel::resetSessions()
{
- reset();
+ beginResetModel();
+ endResetModel();
}
void SessionModel::cloneSession(const QString &session)
@@ -127,19 +128,20 @@ void SessionModel::cloneSession(const QString &session)
QString newSession = newSessionInputDialog.value();
if (newSession.isEmpty() || m_manager->sessions().contains(newSession))
return;
+ beginResetModel();
m_manager->cloneSession(session, newSession);
- reset();
+ endResetModel();
- if (newSessionInputDialog.isSwitchToRequested()) {
+ if (newSessionInputDialog.isSwitchToRequested())
m_manager->loadSession(newSession);
- }
}
}
void SessionModel::deleteSession(const QString &session)
{
+ beginResetModel();
m_manager->deleteSession(session);
- reset();
+ endResetModel();
}
void SessionModel::renameSession(const QString &session)
@@ -152,12 +154,12 @@ void SessionModel::renameSession(const QString &session)
QString newSession = newSessionInputDialog.value();
if (newSession.isEmpty() || m_manager->sessions().contains(newSession))
return;
+ beginResetModel();
m_manager->renameSession(session, newSession);
- reset();
+ endResetModel();
- if (newSessionInputDialog.isSwitchToRequested()) {
+ if (newSessionInputDialog.isSwitchToRequested())
m_manager->loadSession(newSession);
- }
}
}
@@ -197,7 +199,8 @@ QVariant ProjectModel::data(const QModelIndex &index, int role) const
void ProjectModel::resetProjects()
{
- reset();
+ beginResetModel();
+ endResetModel();
}
///////////////////
diff --git a/src/plugins/projectexplorer/projectwizardpage.cpp b/src/plugins/projectexplorer/projectwizardpage.cpp
index 29aeb0fbcb..c6c4b3edac 100644
--- a/src/plugins/projectexplorer/projectwizardpage.cpp
+++ b/src/plugins/projectexplorer/projectwizardpage.cpp
@@ -193,6 +193,6 @@ void ProjectWizardPage::slotProjectChanged(int index)
void ProjectWizardPage::slotManageVcs()
{
- Core::ICore::showOptionsDialog(QLatin1String(VcsBase::Constants::VCS_SETTINGS_CATEGORY),
- QLatin1String(VcsBase::Constants::VCS_COMMON_SETTINGS_ID));
+ Core::ICore::showOptionsDialog(VcsBase::Constants::VCS_SETTINGS_CATEGORY,
+ VcsBase::Constants::VCS_COMMON_SETTINGS_ID);
}
diff --git a/src/plugins/projectexplorer/removetaskhandler.cpp b/src/plugins/projectexplorer/removetaskhandler.cpp
new file mode 100644
index 0000000000..fa75bf791d
--- /dev/null
+++ b/src/plugins/projectexplorer/removetaskhandler.cpp
@@ -0,0 +1,58 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: http://www.qt-project.org/
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+**
+**************************************************************************/
+
+#include "removetaskhandler.h"
+
+#include "projectexplorer.h"
+#include "task.h"
+#include "taskhub.h"
+
+#include <coreplugin/coreconstants.h>
+
+#include <QDir>
+#include <QAction>
+#include <QApplication>
+#include <QClipboard>
+
+using namespace ProjectExplorer::Internal;
+
+void RemoveTaskHandler::handle(const ProjectExplorer::Task &task)
+{
+ ProjectExplorerPlugin::instance()->taskHub()->removeTask(task);
+}
+
+QAction *RemoveTaskHandler::createAction(QObject *parent) const
+{
+ QAction *removeAction = new QAction(tr("Remove", "Name of the action triggering the removetaskhandler"), parent);
+ removeAction->setToolTip(tr("Remove task from the task list"));
+ removeAction->setShortcut(QKeySequence(QKeySequence::Delete));
+ removeAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
+ return removeAction;
+}
diff --git a/src/plugins/projectexplorer/removetaskhandler.h b/src/plugins/projectexplorer/removetaskhandler.h
new file mode 100644
index 0000000000..e13258e9bf
--- /dev/null
+++ b/src/plugins/projectexplorer/removetaskhandler.h
@@ -0,0 +1,54 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: http://www.qt-project.org/
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+**
+**************************************************************************/
+
+#ifndef PROJECTEXPLORER_REMOVETASKHANDLER_H
+#define PROJECTEXPLORER_REMOVETASKHANDLER_H
+
+#include "itaskhandler.h"
+
+namespace ProjectExplorer {
+namespace Internal {
+
+class RemoveTaskHandler : public ITaskHandler
+{
+ Q_OBJECT
+
+public:
+ RemoveTaskHandler() {}
+
+ bool canHandle(const Task &) const { return true; }
+ void handle(const Task &task);
+ QAction *createAction(QObject *parent) const;
+};
+
+} // namespace Internal
+} // namespace ProjectExplorer
+
+#endif // PROJECTEXPLORER_REMOVETASKHANDLER_H
diff --git a/src/plugins/projectexplorer/runconfiguration.cpp b/src/plugins/projectexplorer/runconfiguration.cpp
index d787883d59..aaf3d08e48 100644
--- a/src/plugins/projectexplorer/runconfiguration.cpp
+++ b/src/plugins/projectexplorer/runconfiguration.cpp
@@ -122,16 +122,17 @@ DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(RunConfiguration
m_suppressQmlDebuggingSpinbox(false)
{}
-DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(DebuggerRunConfigurationAspect *other) :
- m_runConfiguration(other->m_runConfiguration),
- m_useCppDebugger(other->m_useCppDebugger),
- m_useQmlDebugger(other->m_useQmlDebugger),
- m_qmlDebugServerPort(other->m_qmlDebugServerPort),
- m_useMultiProcess(other->m_useMultiProcess),
- m_suppressDisplay(other->m_suppressDisplay),
- m_suppressQmlDebuggingOptions(other->m_suppressQmlDebuggingOptions),
- m_suppressCppDebuggingOptions(other->m_suppressCppDebuggingOptions),
- m_suppressQmlDebuggingSpinbox(other->m_suppressQmlDebuggingSpinbox)
+DebuggerRunConfigurationAspect::DebuggerRunConfigurationAspect(RunConfiguration *runConfiguration,
+ DebuggerRunConfigurationAspect *other)
+ : m_runConfiguration(runConfiguration),
+ m_useCppDebugger(other->m_useCppDebugger),
+ m_useQmlDebugger(other->m_useQmlDebugger),
+ m_qmlDebugServerPort(other->m_qmlDebugServerPort),
+ m_useMultiProcess(other->m_useMultiProcess),
+ m_suppressDisplay(other->m_suppressDisplay),
+ m_suppressQmlDebuggingOptions(other->m_suppressQmlDebuggingOptions),
+ m_suppressCppDebuggingOptions(other->m_suppressCppDebuggingOptions),
+ m_suppressQmlDebuggingSpinbox(other->m_suppressQmlDebuggingSpinbox)
{}
RunConfiguration *DebuggerRunConfigurationAspect::runConfiguration()
@@ -289,10 +290,18 @@ RunConfiguration::RunConfiguration(Target *target, const Core::Id id) :
RunConfiguration::RunConfiguration(Target *target, RunConfiguration *source) :
ProjectConfiguration(target, source),
- m_debuggerAspect(new DebuggerRunConfigurationAspect(source->debuggerAspect()))
+ m_debuggerAspect(new DebuggerRunConfigurationAspect(this, source->debuggerAspect()))
{
Q_ASSERT(target);
- addExtraAspects();
+ QList<IRunControlFactory *> factories = ExtensionSystem::PluginManager::getObjects<IRunControlFactory>();
+ foreach (IRunConfigurationAspect *aspect, source->m_aspects) {
+ foreach (IRunControlFactory *factory, factories) {
+ if (IRunConfigurationAspect *clone = factory->cloneRunConfigurationAspect(aspect)) {
+ m_aspects.append(clone);
+ break;
+ }
+ }
+ }
}
RunConfiguration::~RunConfiguration()
@@ -460,6 +469,17 @@ IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, const Q
return 0;
}
+IRunConfigurationFactory *IRunConfigurationFactory::find(Target *parent, RunConfiguration *rc)
+{
+ QList<IRunConfigurationFactory *> factories
+ = ExtensionSystem::PluginManager::instance()->getObjects<IRunConfigurationFactory>();
+ foreach (IRunConfigurationFactory *factory, factories) {
+ if (factory->canClone(parent, rc))
+ return factory;
+ }
+ return 0;
+}
+
QList<IRunConfigurationFactory *> IRunConfigurationFactory::find(Target *parent)
{
QList<IRunConfigurationFactory *> factories
@@ -510,6 +530,12 @@ IRunConfigurationAspect *IRunControlFactory::createRunConfigurationAspect()
return 0;
}
+IRunConfigurationAspect *IRunControlFactory::cloneRunConfigurationAspect(IRunConfigurationAspect *source)
+{
+ Q_UNUSED(source);
+ return 0;
+}
+
RunConfigWidget *IRunControlFactory::createConfigurationWidget(RunConfiguration *)
{
return 0;
diff --git a/src/plugins/projectexplorer/runconfiguration.h b/src/plugins/projectexplorer/runconfiguration.h
index 20b1e06382..8a9e0ca5f2 100644
--- a/src/plugins/projectexplorer/runconfiguration.h
+++ b/src/plugins/projectexplorer/runconfiguration.h
@@ -37,7 +37,7 @@
#include <utils/outputformat.h>
#include <QMetaType>
-#include <QWeakPointer>
+#include <QPointer>
#include <QWidget>
QT_FORWARD_DECLARE_CLASS(QIcon)
@@ -90,7 +90,7 @@ class PROJECTEXPLORER_EXPORT DebuggerRunConfigurationAspect
public:
DebuggerRunConfigurationAspect(RunConfiguration *runConfiguration);
- DebuggerRunConfigurationAspect(DebuggerRunConfigurationAspect *other);
+ DebuggerRunConfigurationAspect(RunConfiguration *runConfiguration, DebuggerRunConfigurationAspect *other);
enum QmlDebuggerStatus {
DisableQmlDebugger = 0,
@@ -213,6 +213,7 @@ public:
virtual RunConfiguration *clone(Target *parent, RunConfiguration *product) = 0;
static IRunConfigurationFactory *find(Target *parent, const QVariantMap &map);
+ static IRunConfigurationFactory *find(Target *parent, RunConfiguration *rc);
static QList<IRunConfigurationFactory *> find(Target *parent);
signals:
@@ -234,6 +235,7 @@ public:
virtual QString displayName() const = 0;
virtual IRunConfigurationAspect *createRunConfigurationAspect();
+ virtual IRunConfigurationAspect *cloneRunConfigurationAspect(IRunConfigurationAspect *);
virtual RunConfigWidget *createConfigurationWidget(RunConfiguration *runConfiguration);
};
@@ -304,7 +306,7 @@ protected:
private:
QString m_displayName;
RunMode m_runMode;
- const QWeakPointer<RunConfiguration> m_runConfiguration;
+ const QPointer<RunConfiguration> m_runConfiguration;
Utils::OutputFormatter *m_outputFormatter;
// A handle to the actual application process.
diff --git a/src/plugins/projectexplorer/runconfigurationmodel.cpp b/src/plugins/projectexplorer/runconfigurationmodel.cpp
index 8314182339..5183206f08 100644
--- a/src/plugins/projectexplorer/runconfigurationmodel.cpp
+++ b/src/plugins/projectexplorer/runconfigurationmodel.cpp
@@ -126,9 +126,8 @@ QVariant RunConfigurationModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole) {
const int row = index.row();
- if (row < m_runConfigurations.size()) {
+ if (row < m_runConfigurations.size())
return m_runConfigurations.at(row)->displayName();
- }
}
return QVariant();
@@ -162,9 +161,8 @@ void RunConfigurationModel::addedRunConfiguration(ProjectExplorer::RunConfigurat
RunConfigurationComparer compare;
int i = 0;
for (; i < m_runConfigurations.size(); ++i) {
- if (compare(rc, m_runConfigurations.at(i))) {
+ if (compare(rc, m_runConfigurations.at(i)))
break;
- }
}
beginInsertRows(QModelIndex(), i, i);
diff --git a/src/plugins/projectexplorer/runsettingspropertiespage.cpp b/src/plugins/projectexplorer/runsettingspropertiespage.cpp
index 5fd61e3f86..ef0cb60aa2 100644
--- a/src/plugins/projectexplorer/runsettingspropertiespage.cpp
+++ b/src/plugins/projectexplorer/runsettingspropertiespage.cpp
@@ -496,11 +496,9 @@ void RunSettingsWidget::updateDeployConfiguration(DeployConfiguration *dc)
m_deployConfigurationCombo->setCurrentIndex(actDc.row());
m_ignoreChange = false;
- m_deployConfigurationWidget = dc->configurationWidget();
- if (m_deployConfigurationWidget) {
- m_deployConfigurationWidget->init(dc);
+ m_deployConfigurationWidget = dc->createConfigWidget();
+ if (m_deployConfigurationWidget)
m_deployLayout->addWidget(m_deployConfigurationWidget);
- }
m_deploySteps = new BuildStepListWidget;
m_deploySteps->init(dc->stepList());
diff --git a/src/plugins/projectexplorer/runsettingspropertiespage.h b/src/plugins/projectexplorer/runsettingspropertiespage.h
index e50c747900..55517f6e70 100644
--- a/src/plugins/projectexplorer/runsettingspropertiespage.h
+++ b/src/plugins/projectexplorer/runsettingspropertiespage.h
@@ -47,8 +47,8 @@ QT_END_NAMESPACE
namespace ProjectExplorer {
class DeployConfiguration;
-class DeployConfigurationWidget;
class DeployConfigurationModel;
+class NamedWidget;
class RunConfiguration;
class RunConfigurationModel;
class RunConfigWidget;
@@ -107,7 +107,7 @@ private:
DeployConfigurationModel *m_deployConfigurationModel;
QWidget *m_runConfigurationWidget;
QVBoxLayout *m_runLayout;
- DeployConfigurationWidget *m_deployConfigurationWidget;
+ NamedWidget *m_deployConfigurationWidget;
QVBoxLayout *m_deployLayout;
BuildStepListWidget *m_deploySteps;
QMenu *m_addRunMenu;
diff --git a/src/plugins/projectexplorer/session.cpp b/src/plugins/projectexplorer/session.cpp
index 1b00ffc952..75423af786 100644
--- a/src/plugins/projectexplorer/session.cpp
+++ b/src/plugins/projectexplorer/session.cpp
@@ -49,6 +49,7 @@
#include <utils/listutils.h>
#include <utils/qtcassert.h>
+#include <utils/stylehelper.h>
#include <QDebug>
#include <QDir>
@@ -220,11 +221,10 @@ void SessionManager::removeDependency(Project *project, Project *depProject)
QStringList proDeps = m_depMap.value(proName);
proDeps.removeAll(depName);
- if (proDeps.isEmpty()) {
+ if (proDeps.isEmpty())
m_depMap.remove(proName);
- } else {
+ else
m_depMap[proName] = proDeps;
- }
emit dependencyChanged(project, depProject);
}
@@ -316,6 +316,15 @@ bool SessionManager::save()
if (m_startupProject)
data.insert(QLatin1String("StartupProject"), m_startupProject->document()->fileName());
+ QColor c = Utils::StyleHelper::requestedBaseColor();
+ if (c.isValid()) {
+ QString tmp = QString::fromLatin1("#%1%2%3")
+ .arg(c.red(), 2, 16, QLatin1Char('0'))
+ .arg(c.green(), 2, 16, QLatin1Char('0'))
+ .arg(c.blue(), 2, 16, QLatin1Char('0'));
+ data.insert(QLatin1String("Color"), tmp);
+ }
+
QStringList projectFiles;
foreach (Project *pro, m_projects)
projectFiles << pro->document()->fileName();
@@ -438,11 +447,10 @@ QList<Project *> SessionManager::projectOrder(Project *project) const
QList<Project *> result;
QStringList pros;
- if (project) {
+ if (project)
pros = dependencies(project->document()->fileName());
- } else {
+ else
pros = dependenciesOrder();
- }
foreach (const QString &proFile, pros) {
foreach (Project *pro, projects()) {
@@ -861,6 +869,10 @@ bool SessionManager::loadSession(const QString &session)
restoreValues(reader);
emit aboutToLoadSession(session);
+ QColor c = QColor(reader.restoreValue(QLatin1String("Color")).toString());
+ if (c.isValid())
+ Utils::StyleHelper::setBaseColor(c);
+
QStringList fileList =
reader.restoreValue(QLatin1String("ProjectList")).toStringList();
int openEditorsCount = reader.restoreValue(QLatin1String("OpenEditors")).toInt();
@@ -901,8 +913,7 @@ bool SessionManager::loadSession(const QString &session)
QString SessionManager::lastSession() const
{
- QString fileName = ICore::settings()->value(QLatin1String("ProjectExplorer/StartupSession")).toString();
- return QFileInfo(fileName).completeBaseName();
+ return ICore::settings()->value(QLatin1String("ProjectExplorer/StartupSession")).toString();
}
SessionNode *SessionManager::sessionNode() const
diff --git a/src/plugins/projectexplorer/sessiondialog.cpp b/src/plugins/projectexplorer/sessiondialog.cpp
index 301a121073..8e751e89ce 100644
--- a/src/plugins/projectexplorer/sessiondialog.cpp
+++ b/src/plugins/projectexplorer/sessiondialog.cpp
@@ -170,7 +170,7 @@ void SessionDialog::addItems(bool setDefaultSession)
}
void SessionDialog::markItems()
{
- for(int i = 0; i < m_ui.sessionList->count(); ++i) {
+ for (int i = 0; i < m_ui.sessionList->count(); ++i) {
QListWidgetItem *item = m_ui.sessionList->item(i);
QFont f = item->font();
QString session = item->data(Qt::DisplayRole).toString();
@@ -219,9 +219,8 @@ void SessionDialog::createNew()
m_ui.sessionList->addItems(sessions);
m_ui.sessionList->setCurrentRow(sessions.indexOf(newSession));
markItems();
- if (newSessionInputDialog.isSwitchToRequested()) {
+ if (newSessionInputDialog.isSwitchToRequested())
switchToSession();
- }
}
}
diff --git a/src/plugins/projectexplorer/settingsaccessor.cpp b/src/plugins/projectexplorer/settingsaccessor.cpp
index ae6e03acd3..6caf11b97a 100644
--- a/src/plugins/projectexplorer/settingsaccessor.cpp
+++ b/src/plugins/projectexplorer/settingsaccessor.cpp
@@ -45,6 +45,7 @@
#include <coreplugin/icore.h>
#include <coreplugin/idocument.h>
#include <extensionsystem/pluginmanager.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <utils/persistentsettings.h>
@@ -1627,7 +1628,7 @@ QVariantMap Version4Handler::update(Project *, const QVariantMap &map)
const QVariantMap &originalBc = targetIt.value().toMap();
QVariantMap newBc;
QMapIterator<QString, QVariant> bcIt(originalBc);
- while(bcIt.hasNext()) {
+ while (bcIt.hasNext()) {
bcIt.next();
const QString &bcKey = bcIt.key();
if (!bcKey.startsWith(QLatin1String("ProjectExplorer.BuildConfiguration.BuildStep."))) {
@@ -1893,7 +1894,6 @@ static const char * const lameArgListKeys[] = {
0
};
-#ifdef Q_OS_UNIX
inline static bool isSpecialChar(ushort c)
{
// Chars that should be quoted (TM). This includes:
@@ -1912,27 +1912,26 @@ inline static bool hasSpecialChars(const QString &arg)
return true;
return false;
}
-#endif
// These were split according to sane (even if a bit arcane) rules
static QVariant version8ArgNodeHandler(const QVariant &var)
{
QString ret;
foreach (const QVariant &svar, var.toList()) {
-#ifdef Q_OS_UNIX
- // We don't just addArg, so we don't disarm existing env expansions.
- // This is a bit fuzzy logic ...
- QString s = svar.toString();
- s.replace(QLatin1Char('\\'), QLatin1String("\\\\"));
- s.replace(QLatin1Char('"'), QLatin1String("\\\""));
- s.replace(QLatin1Char('`'), QLatin1String("\\`"));
- if (s != svar.toString() || hasSpecialChars(s))
- s.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
- Utils::QtcProcess::addArgs(&ret, s);
-#else
- // Under windows, env expansions cannot be quoted anyway.
- Utils::QtcProcess::addArg(&ret, svar.toString());
-#endif
+ if (Utils::HostOsInfo::isAnyUnixHost()) {
+ // We don't just addArg, so we don't disarm existing env expansions.
+ // This is a bit fuzzy logic ...
+ QString s = svar.toString();
+ s.replace(QLatin1Char('\\'), QLatin1String("\\\\"));
+ s.replace(QLatin1Char('"'), QLatin1String("\\\""));
+ s.replace(QLatin1Char('`'), QLatin1String("\\`"));
+ if (s != svar.toString() || hasSpecialChars(s))
+ s.prepend(QLatin1Char('"')).append(QLatin1Char('"'));
+ Utils::QtcProcess::addArgs(&ret, s);
+ } else {
+ // Under windows, env expansions cannot be quoted anyway.
+ Utils::QtcProcess::addArg(&ret, svar.toString());
+ }
}
return QVariant(ret);
}
@@ -1987,13 +1986,13 @@ static const char * const envExpandedKeys[] = {
static QString version8NewVar(const QString &old)
{
QString ret = old;
-#ifdef Q_OS_UNIX
- ret.prepend(QLatin1String("${"));
- ret.append(QLatin1Char('}'));
-#else
- ret.prepend(QLatin1Char('%'));
- ret.append(QLatin1Char('%'));
-#endif
+ if (Utils::HostOsInfo::isAnyUnixHost()) {
+ ret.prepend(QLatin1String("${"));
+ ret.append(QLatin1Char('}'));
+ } else {
+ ret.prepend(QLatin1Char('%'));
+ ret.append(QLatin1Char('%'));
+ }
return ret;
}
@@ -2007,65 +2006,65 @@ static QVariant version8EnvNodeTransform(const QVariant &var)
QLatin1String("%{sourceDir}"));
result.replace(QRegExp(QLatin1String("%BUILDDIR%|\\$(BUILDDIR\\b|\\{BUILDDIR\\})")),
QLatin1String("%{buildDir}"));
-#ifdef Q_OS_UNIX
- for (int vStart = -1, i = 0; i < result.length(); ) {
- QChar c = result.at(i++);
- if (c == QLatin1Char('%')) {
- if (vStart > 0 && vStart < i - 1) {
- QString nv = version8NewVar(result.mid(vStart, i - 1 - vStart));
- result.replace(vStart - 1, i - vStart + 1, nv);
- i = vStart - 1 + nv.length();
- vStart = -1;
- } else {
- vStart = i;
+ if (Utils::HostOsInfo::isAnyUnixHost()) {
+ for (int vStart = -1, i = 0; i < result.length(); ) {
+ QChar c = result.at(i++);
+ if (c == QLatin1Char('%')) {
+ if (vStart > 0 && vStart < i - 1) {
+ QString nv = version8NewVar(result.mid(vStart, i - 1 - vStart));
+ result.replace(vStart - 1, i - vStart + 1, nv);
+ i = vStart - 1 + nv.length();
+ vStart = -1;
+ } else {
+ vStart = i;
+ }
+ } else if (vStart > 0) {
+ // Sanity check so we don't catch too much garbage
+ if (!c.isLetterOrNumber() && c != QLatin1Char('_'))
+ vStart = -1;
}
- } else if (vStart > 0) {
- // Sanity check so we don't catch too much garbage
- if (!c.isLetterOrNumber() && c != QLatin1Char('_'))
- vStart = -1;
}
- }
-#else
- enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
- int vStart = -1;
-
- for (int i = 0; i < result.length();) {
- QChar c = result.at(i++);
- if (state == BASE) {
- if (c == QLatin1Char('$'))
- state = OPTIONALVARIABLEBRACE;
- } else if (state == OPTIONALVARIABLEBRACE) {
- if (c == QLatin1Char('{')) {
- state = BRACEDVARIABLE;
- vStart = i;
- } else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
- state = VARIABLE;
- vStart = i - 1;
- } else {
- state = BASE;
- }
- } else if (state == BRACEDVARIABLE) {
- if (c == QLatin1Char('}')) {
- QString nv = version8NewVar(result.mid(vStart, i - 1 - vStart));
- result.replace(vStart - 2, i - vStart + 2, nv);
- i = vStart + nv.length();
- state = BASE;
- }
- } else if (state == VARIABLE) {
- if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
- QString nv = version8NewVar(result.mid(vStart, i - 1 - vStart));
- result.replace(vStart - 1, i - vStart, nv);
- i = vStart - 1 + nv.length(); // On the same char - could be next expansion.
- state = BASE;
+ } else {
+ enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
+ int vStart = -1;
+
+ for (int i = 0; i < result.length();) {
+ QChar c = result.at(i++);
+ if (state == BASE) {
+ if (c == QLatin1Char('$'))
+ state = OPTIONALVARIABLEBRACE;
+ } else if (state == OPTIONALVARIABLEBRACE) {
+ if (c == QLatin1Char('{')) {
+ state = BRACEDVARIABLE;
+ vStart = i;
+ } else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
+ state = VARIABLE;
+ vStart = i - 1;
+ } else {
+ state = BASE;
+ }
+ } else if (state == BRACEDVARIABLE) {
+ if (c == QLatin1Char('}')) {
+ QString nv = version8NewVar(result.mid(vStart, i - 1 - vStart));
+ result.replace(vStart - 2, i - vStart + 2, nv);
+ i = vStart + nv.length();
+ state = BASE;
+ }
+ } else if (state == VARIABLE) {
+ if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
+ QString nv = version8NewVar(result.mid(vStart, i - 1 - vStart));
+ result.replace(vStart - 1, i - vStart, nv);
+ i = vStart - 1 + nv.length(); // On the same char - could be next expansion.
+ state = BASE;
+ }
}
}
+ if (state == VARIABLE) {
+ QString nv = version8NewVar(result.mid(vStart));
+ result.truncate(vStart - 1);
+ result += nv;
+ }
}
- if (state == VARIABLE) {
- QString nv = version8NewVar(result.mid(vStart));
- result.truncate(vStart - 1);
- result += nv;
- }
-#endif
return QVariant(result);
}
@@ -2365,7 +2364,7 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
tcId.replace(QLatin1String("Qt4ProjectManager.ToolChain.Maemo:"),
QLatin1String("ProjectExplorer.ToolChain.Gcc:")); // convert Maemo to GCC
QString data = tcId.mid(tcId.indexOf(QLatin1Char(':')) + 1);
- QStringList split = data.split('.', QString::KeepEmptyParts);
+ QStringList split = data.split(QLatin1Char('.'), QString::KeepEmptyParts);
QString compilerPath;
QString debuggerPath;
Abi compilerAbi;
@@ -2424,7 +2423,7 @@ QVariantMap Version11Handler::update(Project *project, const QVariantMap &map)
int dcPos = deployIt.key();
const QVariantMap &dc = deployIt.value();
// Device
- QString devId = dc.value(QLatin1String("Qt4ProjectManager.MaemoRunConfiguration.DeviceId")).toString();
+ QByteArray devId = dc.value(QLatin1String("Qt4ProjectManager.MaemoRunConfiguration.DeviceId")).toByteArray();
if (devId.isEmpty())
devId = QByteArray("Desktop Device");
if (!devId.isEmpty() && !DeviceManager::instance()->find(Core::Id(devId))) // We do not know that device
@@ -2574,14 +2573,8 @@ void Version11Handler::addRunConfigurations(Kit *k,
static QString targetRoot(const QString &qmakePath)
{
-#ifdef Q_OS_WIN
- Qt::CaseSensitivity cs = Qt::CaseInsensitive;
- const QString binQmake = "/bin/qmake.exe";
-#else
- Qt::CaseSensitivity cs = Qt::CaseSensitive;
- const QString binQmake = "/bin/qmake";
-#endif
- return QDir::cleanPath(qmakePath).remove(binQmake, cs);
+ return QDir::cleanPath(qmakePath).remove(QLatin1String("/bin/qmake" QTC_HOST_EXE_SUFFIX),
+ Utils::HostOsInfo::fileNameCaseSensitivity());
}
static QString maddeRoot(const QString &qmakePath)
@@ -2622,9 +2615,8 @@ void Version11Handler::parseQtversionFile()
const QStringList &list = line.split(QLatin1Char(' '));
if (list.count() <= 1)
continue;
- if (list.at(0) == QLatin1String("sysroot")) {
+ if (list.at(0) == QLatin1String("sysroot"))
sysRoot = maddeRoot(qmake) + QLatin1String("/sysroots/") + list.at(1);
- }
}
}
}
diff --git a/src/plugins/projectexplorer/showineditortaskhandler.cpp b/src/plugins/projectexplorer/showineditortaskhandler.cpp
index 73ec7e4593..128c34f2d0 100644
--- a/src/plugins/projectexplorer/showineditortaskhandler.cpp
+++ b/src/plugins/projectexplorer/showineditortaskhandler.cpp
@@ -55,7 +55,9 @@ void ShowInEditorTaskHandler::handle(const ProjectExplorer::Task &task)
QAction *ShowInEditorTaskHandler::createAction(QObject *parent) const
{
- QAction *showAction = new QAction(tr("&Show in Editor"), parent);
+ QAction *showAction = new QAction(tr("Show in Editor"), parent);
showAction->setToolTip(tr("Show task location in an editor."));
+ showAction->setShortcut(QKeySequence(Qt::Key_Return));
+ showAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
return showAction;
}
diff --git a/src/plugins/projectexplorer/showoutputtaskhandler.cpp b/src/plugins/projectexplorer/showoutputtaskhandler.cpp
index 238bb72143..0e98e7e200 100644
--- a/src/plugins/projectexplorer/showoutputtaskhandler.cpp
+++ b/src/plugins/projectexplorer/showoutputtaskhandler.cpp
@@ -61,5 +61,7 @@ QAction *ShowOutputTaskHandler::createAction(QObject *parent) const
{
QAction *outputAction = new QAction(tr("Show &Output"), parent);
outputAction->setToolTip(tr("Show output generating this issue."));
+ outputAction->setShortcut(QKeySequence(tr("O")));
+ outputAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
return outputAction;
}
diff --git a/src/plugins/projectexplorer/target.cpp b/src/plugins/projectexplorer/target.cpp
index f3305d0b9f..922af6c690 100644
--- a/src/plugins/projectexplorer/target.cpp
+++ b/src/plugins/projectexplorer/target.cpp
@@ -368,7 +368,10 @@ void Target::setActiveDeployConfiguration(DeployConfiguration *dc)
void Target::setDeploymentData(const DeploymentData &deploymentData)
{
- d->m_deploymentData = deploymentData;
+ if (d->m_deploymentData != deploymentData) {
+ d->m_deploymentData = deploymentData;
+ emit deploymentDataChanged();
+ }
}
DeploymentData Target::deploymentData() const
@@ -378,7 +381,10 @@ DeploymentData Target::deploymentData() const
void Target::setApplicationTargets(const BuildTargetInfoList &appTargets)
{
- d->m_appTargets = appTargets;
+ if (d->m_appTargets != appTargets) {
+ d->m_appTargets = appTargets;
+ emit applicationTargetsChanged();
+ }
}
BuildTargetInfoList Target::applicationTargets() const
@@ -776,7 +782,7 @@ bool Target::fromMap(const QVariantMap &map)
if (!factory) {
Core::Id id = idFromMap(valueMap);
qWarning("No factory found to restore deployment configuration of id '%s'!",
- qPrintable(id.isValid() ? id.toString() : "UNKNOWN"));
+ id.isValid() ? qPrintable(id.toString()) : "UNKNOWN");
continue;
}
DeployConfiguration *dc = factory->restore(this, valueMap);
diff --git a/src/plugins/projectexplorer/target.h b/src/plugins/projectexplorer/target.h
index 74a946be46..3583ffd0c6 100644
--- a/src/plugins/projectexplorer/target.h
+++ b/src/plugins/projectexplorer/target.h
@@ -49,7 +49,7 @@ class DeployConfigurationFactory;
class IRunConfigurationFactory;
class Kit;
class Project;
-class BuildConfigWidget;
+class NamedWidget;
class TargetPrivate;
@@ -148,6 +148,9 @@ signals:
void deployConfigurationEnabledChanged();
void runConfigurationEnabledChanged();
+ void deploymentDataChanged();
+ void applicationTargetsChanged();
+
// Remove all the signals below, they are stupid
/// Emitted whenever the current build configuartion changed or the build directory of the current
/// build configuration was changed.
diff --git a/src/plugins/projectexplorer/targetselector.cpp b/src/plugins/projectexplorer/targetselector.cpp
index 2c28e45b8d..d09f83f562 100644
--- a/src/plugins/projectexplorer/targetselector.cpp
+++ b/src/plugins/projectexplorer/targetselector.cpp
@@ -36,10 +36,41 @@
#include <QMenu>
#include <QMouseEvent>
#include <QFontMetrics>
+#include <QPushButton>
static const int TARGET_HEIGHT = 43;
static const int NAVBUTTON_WIDTH = 27;
+namespace ProjectExplorer {
+namespace Internal {
+class QPixmapButton : public QPushButton
+{
+public:
+ QPixmapButton(QWidget *parent, const QPixmap &first, const QPixmap &second)
+ : QPushButton(parent), m_showFirst(true), m_first(first), m_second(second)
+ {
+ setFixedSize(m_first.size());
+ }
+
+ void paintEvent(QPaintEvent *)
+ {
+ QPainter p(this);
+ p.drawPixmap(0, 0, m_showFirst ? m_first : m_second);
+ }
+
+ void setFirst(bool f)
+ {
+ m_showFirst = f;
+ }
+
+private:
+ bool m_showFirst;
+ const QPixmap m_first;
+ const QPixmap m_second;
+};
+}
+}
+
using namespace ProjectExplorer::Internal;
TargetSelector::TargetSelector(QWidget *parent) :
@@ -49,11 +80,12 @@ TargetSelector::TargetSelector(QWidget *parent) :
m_buildselected(QLatin1String(":/projectexplorer/images/targetbuildselected.png")),
m_targetRightButton(QLatin1String(":/projectexplorer/images/targetrightbutton.png")),
m_targetLeftButton(QLatin1String(":/projectexplorer/images/targetleftbutton.png")),
- m_targetRemoveButton(QLatin1String(":/projectexplorer/images/targetremovebutton.png")),
- m_targetRemoveDarkButton(QLatin1String(":/projectexplorer/images/targetremovebuttondark.png")),
+ m_targetChangePixmap(QLatin1String(":/projectexplorer/images/targetchangebutton.png")),
+ m_targetChangePixmap2(QLatin1String(":/projectexplorer/images/targetchangebutton2.png")),
m_currentTargetIndex(-1),
m_currentHoveredTargetIndex(-1),
- m_startIndex(0)
+ m_startIndex(0),
+ m_menuShown(false)
{
QFont f = font();
f.setPixelSize(10);
@@ -61,6 +93,27 @@ TargetSelector::TargetSelector(QWidget *parent) :
setFont(f);
setMouseTracking(true);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
+
+ m_targetChangeButton = new QPixmapButton(this, m_targetChangePixmap2, m_targetChangePixmap);
+ m_targetChangeButton->hide();
+ connect(m_targetChangeButton, SIGNAL(pressed()), this, SLOT(changeButtonPressed()));
+}
+
+void TargetSelector::changeButtonPressed()
+{
+ emit menuShown(m_currentHoveredTargetIndex);
+}
+
+void TargetSelector::menuAboutToShow()
+{
+ m_menuShown = true;
+ updateButtons();
+}
+
+void TargetSelector::menuAboutToHide()
+{
+ m_menuShown = false;
+ updateButtons();
}
void TargetSelector::insertTarget(int index, const QString &name)
@@ -136,6 +189,25 @@ TargetSelector::Target TargetSelector::targetAt(int index) const
return m_targets.at(index);
}
+void TargetSelector::setTargetMenu(QMenu *menu)
+{
+ if (m_targetChangeButton->menu()) {
+ disconnect(m_targetChangeButton->menu(), SIGNAL(aboutToShow()),
+ this, SLOT(menuAboutToShow()));
+ disconnect(m_targetChangeButton->menu(), SIGNAL(aboutToHide()),
+ this, SLOT(menuAboutToHide()));
+ }
+
+ m_targetChangeButton->setMenu(menu);
+
+ if (menu) {
+ connect(m_targetChangeButton->menu(), SIGNAL(aboutToShow()),
+ this, SLOT(menuAboutToShow()));
+ connect(m_targetChangeButton->menu(), SIGNAL(aboutToHide()),
+ this, SLOT(menuAboutToHide()));
+ }
+}
+
int TargetSelector::targetWidth() const
{
static int width = -1;
@@ -157,7 +229,7 @@ int TargetSelector::maxVisibleTargets() const
return (width() - ((NAVBUTTON_WIDTH + 1) * 2 + 3))/(targetWidth() + 1);
}
-void TargetSelector::getControlAt(int x, int y, int *buttonIndex, int *targetIndex, int *targetSubIndex, bool *removeButton)
+void TargetSelector::getControlAt(int x, int y, int *buttonIndex, int *targetIndex, int *targetSubIndex)
{
if (buttonIndex)
*buttonIndex = -1;
@@ -165,8 +237,6 @@ void TargetSelector::getControlAt(int x, int y, int *buttonIndex, int *targetInd
*targetIndex = -1;
if (targetSubIndex)
*targetSubIndex = -1;
- if (removeButton)
- *removeButton = false;
// left button?
if (m_startIndex > 0 /* button visible */ && x >= 0 && x < NAVBUTTON_WIDTH + 2) {
@@ -189,13 +259,13 @@ void TargetSelector::getControlAt(int x, int y, int *buttonIndex, int *targetInd
int tx = NAVBUTTON_WIDTH + 3;
int index;
for (index = m_startIndex; index < m_targets.size(); ++index) {
- if (x <= tx) {
+ if (x <= tx)
break;
- }
tx += targetWidth() + 1;
}
--index;
tx -= targetWidth() + 1;
+
if (index >= 0 && index < m_targets.size()) {
if (targetIndex)
*targetIndex = index;
@@ -209,10 +279,6 @@ void TargetSelector::getControlAt(int x, int y, int *buttonIndex, int *targetInd
if (targetSubIndex)
*targetSubIndex = 0;
}
- } else if (y < m_targetRemoveButton.height() + 3
- && x >= tx + targetWidth() - m_targetRemoveButton.width() - 1) {
- if (removeButton)
- *removeButton = true;
}
}
}
@@ -222,8 +288,7 @@ void TargetSelector::mousePressEvent(QMouseEvent *event)
int buttonIndex;
int targetIndex;
int targetSubIndex;
- bool removeButton;
- getControlAt(event->x(), event->y(), &buttonIndex, &targetIndex, &targetSubIndex, &removeButton);
+ getControlAt(event->x(), event->y(), &buttonIndex, &targetIndex, &targetSubIndex);
if (buttonIndex == 0) {
event->accept();
--m_startIndex;
@@ -235,7 +300,7 @@ void TargetSelector::mousePressEvent(QMouseEvent *event)
} else if (targetIndex != -1) {
event->accept();
bool updateNeeded = false;
- if (targetIndex != m_currentTargetIndex && !removeButton) {
+ if (targetIndex != m_currentTargetIndex) {
m_currentTargetIndex = targetIndex;
updateNeeded = true;
}
@@ -244,8 +309,6 @@ void TargetSelector::mousePressEvent(QMouseEvent *event)
m_targets[m_currentTargetIndex].currentSubIndex = targetSubIndex;
updateNeeded = true;
}
- } else if (removeButton) {
- emit removeButtonClicked(targetIndex);
}
if (updateNeeded) {
update();
@@ -259,11 +322,12 @@ void TargetSelector::mousePressEvent(QMouseEvent *event)
void TargetSelector::mouseMoveEvent(QMouseEvent *event)
{
int targetIndex;
- getControlAt(event->x(), event->y(), 0, &targetIndex, 0, 0);
+ getControlAt(event->x(), event->y(), 0, &targetIndex, 0);
if (m_currentHoveredTargetIndex != targetIndex) {
m_currentHoveredTargetIndex = targetIndex;
if (targetIndex != -1)
event->accept();
+ updateButtons();
update();
}
}
@@ -272,18 +336,34 @@ void TargetSelector::leaveEvent(QEvent *event)
{
Q_UNUSED(event)
m_currentHoveredTargetIndex = -1;
+ updateButtons();
update();
}
+void TargetSelector::updateButtons()
+{
+ if (m_menuShown) {
+ // Do nothing while the menu is show
+ } else if (m_currentHoveredTargetIndex == -1) {
+ m_targetChangeButton->hide();
+ } else {
+ int tx = NAVBUTTON_WIDTH + 3 + (m_currentHoveredTargetIndex - m_startIndex) * (targetWidth() + 1);
+
+ QPoint buttonTopLeft(tx + targetWidth() - m_targetChangePixmap.width() - 1, 3);
+ m_targetChangeButton->move(buttonTopLeft);
+ m_targetChangeButton->setVisible(true);
+ m_targetChangeButton->setFirst(m_currentHoveredTargetIndex == m_currentTargetIndex);
+ }
+}
+
bool TargetSelector::event(QEvent *e)
{
if (e->type() == QEvent::ToolTip) {
const QHelpEvent *helpEvent = static_cast<const QHelpEvent *>(e);
int targetIndex;
int subTargetIndex;
- bool removeButton;
- getControlAt(helpEvent->x(), helpEvent->y(), 0, &targetIndex, &subTargetIndex, &removeButton);
- if (targetIndex >= 0 && subTargetIndex < 0 && !removeButton) {
+ getControlAt(helpEvent->x(), helpEvent->y(), 0, &targetIndex, &subTargetIndex);
+ if (targetIndex >= 0 && subTargetIndex < 0) {
emit toolTipRequested(helpEvent->globalPos(), targetIndex);
e->accept();
return true;
@@ -324,11 +404,10 @@ void TargetSelector::paintEvent(QPaintEvent *event)
bool buildSelected = target.currentSubIndex == 0;
if (index == m_currentTargetIndex) {
p.setPen(QColor(255, 255, 255));
- if (buildSelected) {
+ if (buildSelected)
image = m_buildselected;
- } else {
+ else
image = m_runselected;
- }
} else {
p.setPen(Qt::black);
}
@@ -340,12 +419,6 @@ void TargetSelector::paintEvent(QPaintEvent *event)
p.drawText(x + (targetWidth()- fm.width(nameText))/2 + 1, 7 + fm.ascent(),
nameText);
- // remove button
- if (m_currentHoveredTargetIndex == index) {
- p.drawPixmap(x + targetWidth() - m_targetRemoveButton.width() - 2, 3,
- index == m_currentTargetIndex ? m_targetRemoveDarkButton : m_targetRemoveButton);
- }
-
// Build
int margin = 2; // position centered within the rounded buttons
QFontMetrics fm = fontMetrics();
diff --git a/src/plugins/projectexplorer/targetselector.h b/src/plugins/projectexplorer/targetselector.h
index a57a8793bf..f882cbf7f4 100644
--- a/src/plugins/projectexplorer/targetselector.h
+++ b/src/plugins/projectexplorer/targetselector.h
@@ -35,10 +35,12 @@
QT_BEGIN_NAMESPACE
class QMenu;
+class QPushButton;
QT_END_NAMESPACE
namespace ProjectExplorer {
namespace Internal {
+class QPixmapButton;
class TargetSelector : public QWidget
{
@@ -62,6 +64,8 @@ public:
int currentIndex() const { return m_currentTargetIndex; }
int currentSubIndex() const { return m_targets.at(m_currentTargetIndex).currentSubIndex; }
+ void setTargetMenu(QMenu *menu);
+
public:
void insertTarget(int index, const QString &name);
void renameTarget(int index, const QString &name);
@@ -70,11 +74,11 @@ public:
void setCurrentSubIndex(int subindex);
signals:
- void removeButtonClicked(int targetIndex);
// This signal is emitted whenever the target pointed to by the indices
// has changed.
void currentChanged(int targetIndex, int subIndex);
void toolTipRequested(const QPoint &globalPosition, int targetIndex);
+ void menuShown(int targetIndex);
protected:
void paintEvent(QPaintEvent *event);
@@ -83,8 +87,13 @@ protected:
void leaveEvent(QEvent *event);
bool event(QEvent *e);
+private slots:
+ void changeButtonPressed();
+ void updateButtons();
+ void menuAboutToShow();
+ void menuAboutToHide();
private:
- void getControlAt(int x, int y, int *buttonIndex, int *targetIndex, int *targetSubIndex, bool *removeButton);
+ void getControlAt(int x, int y, int *buttonIndex, int *targetIndex, int *targetSubIndex);
int maxVisibleTargets() const;
const QImage m_unselected;
@@ -92,14 +101,17 @@ private:
const QImage m_buildselected;
const QPixmap m_targetRightButton;
const QPixmap m_targetLeftButton;
- const QPixmap m_targetRemoveButton;
- const QPixmap m_targetRemoveDarkButton;
+ const QPixmap m_targetChangePixmap;
+ const QPixmap m_targetChangePixmap2;
+
+ QPixmapButton *m_targetChangeButton;
QList<Target> m_targets;
int m_currentTargetIndex;
int m_currentHoveredTargetIndex;
int m_startIndex;
+ bool m_menuShown;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/targetsettingspanel.cpp b/src/plugins/projectexplorer/targetsettingspanel.cpp
index 62c231954e..10ac598155 100644
--- a/src/plugins/projectexplorer/targetsettingspanel.cpp
+++ b/src/plugins/projectexplorer/targetsettingspanel.cpp
@@ -44,6 +44,9 @@
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/deployconfiguration.h>
+#include <projectexplorer/runconfiguration.h>
#include <utils/qtcassert.h>
#include <QCoreApplication>
@@ -56,9 +59,11 @@
#include <QVBoxLayout>
#include <QToolTip>
-using namespace ProjectExplorer;
-using namespace ProjectExplorer::Internal;
+using namespace Core;
+
+namespace ProjectExplorer {
+namespace Internal {
///
// TargetSettingsWidget
@@ -69,6 +74,8 @@ TargetSettingsPanelWidget::TargetSettingsPanelWidget(Project *project) :
m_project(project),
m_selector(0),
m_centralWidget(0),
+ m_changeMenu(0),
+ m_duplicateMenu(0),
m_lastAction(0)
{
Q_ASSERT(m_project);
@@ -77,6 +84,7 @@ TargetSettingsPanelWidget::TargetSettingsPanelWidget(Project *project) :
m_panelWidgets[1] = 0;
m_addMenu = new QMenu(this);
+ m_targetMenu = new QMenu(this);
setFocusPolicy(Qt::NoFocus);
@@ -91,7 +99,7 @@ TargetSettingsPanelWidget::TargetSettingsPanelWidget(Project *project) :
this, SLOT(activeTargetChanged(ProjectExplorer::Target*)));
connect(KitManager::instance(), SIGNAL(kitsChanged()),
- this, SLOT(updateTargetAddAndRemoveButtons()));
+ this, SLOT(updateTargetButtons()));
}
TargetSettingsPanelWidget::~TargetSettingsPanelWidget()
@@ -101,21 +109,35 @@ TargetSettingsPanelWidget::~TargetSettingsPanelWidget()
bool TargetSettingsPanelWidget::event(QEvent *event)
{
if (event->type() == QEvent::StatusTip) {
+ QAction *act = 0;
+ QMenu *menu = 0;
+ if (m_addMenu->activeAction()) {
+ menu = m_addMenu;
+ act = m_addMenu->activeAction();
+ } else if (m_changeMenu && m_changeMenu->activeAction()) {
+ menu = m_changeMenu;
+ act = m_changeMenu->activeAction();
+ } else if (m_duplicateMenu && m_duplicateMenu->activeAction()) {
+ menu = m_duplicateMenu;
+ act = m_duplicateMenu->activeAction();
+ } else {
+ return QWidget::event(event);
+ }
+
QStatusTipEvent *ev = static_cast<QStatusTipEvent *>(event);
ev->accept();
- QAction *act = m_addMenu->activeAction();
if (act != m_lastAction)
QToolTip::showText(QPoint(), QString());
m_lastAction = act;
if (act) {
- QRect actionRect = m_addMenu->actionGeometry(act);
- actionRect.translate(m_addMenu->pos());
+ QRect actionRect = menu->actionGeometry(act);
+ actionRect.translate(menu->pos());
QPoint p = QCursor::pos();
if (!actionRect.contains(p))
p = actionRect.center();
p.setY(actionRect.center().y());
- QToolTip::showText(p, ev->tip(), m_addMenu, m_addMenu->actionGeometry(act));
+ QToolTip::showText(p, ev->tip(), menu, menu->actionGeometry(act));
} else {
QToolTip::showText(QPoint(), QString());
}
@@ -168,18 +190,20 @@ void TargetSettingsPanelWidget::setupUi()
connect(m_selector, SIGNAL(currentChanged(int,int)),
this, SLOT(currentTargetChanged(int,int)));
- connect(m_selector, SIGNAL(removeButtonClicked(int)),
- this, SLOT(removeTarget(int)));
connect(m_selector, SIGNAL(manageButtonClicked()),
this, SLOT(openTargetPreferences()));
connect(m_selector, SIGNAL(toolTipRequested(QPoint,int)),
this, SLOT(showTargetToolTip(QPoint,int)));
+ connect(m_selector, SIGNAL(menuShown(int)),
+ this, SLOT(menuShown(int)));
- m_selector->setAddButtonMenu(m_addMenu);
connect(m_addMenu, SIGNAL(triggered(QAction*)),
- this, SLOT(addTarget(QAction*)));
+ this, SLOT(addActionTriggered(QAction*)));
- updateTargetAddAndRemoveButtons();
+ m_selector->setAddButtonMenu(m_addMenu);
+ m_selector->setTargetMenu(m_targetMenu);
+
+ updateTargetButtons();
}
void TargetSettingsPanelWidget::currentTargetChanged(int targetIndex, int subIndex)
@@ -242,7 +266,36 @@ void TargetSettingsPanelWidget::currentTargetChanged(int targetIndex, int subInd
m_project->setActiveTarget(target);
}
-void TargetSettingsPanelWidget::addTarget(QAction *action)
+void TargetSettingsPanelWidget::menuShown(int targetIndex)
+{
+ m_menuTargetIndex = targetIndex;
+}
+
+void TargetSettingsPanelWidget::changeActionTriggered(QAction *action)
+{
+ Kit *k = KitManager::instance()->find(action->data().value<Core::Id>());
+ Target *sourceTarget = m_targets.at(m_menuTargetIndex);
+ Target *newTarget = cloneTarget(sourceTarget, k);
+
+ if (newTarget) {
+ m_project->addTarget(newTarget);
+ m_project->setActiveTarget(newTarget);
+ m_project->removeTarget(sourceTarget);
+ }
+}
+
+void TargetSettingsPanelWidget::duplicateActionTriggered(QAction *action)
+{
+ Kit *k = KitManager::instance()->find(action->data().value<Core::Id>());
+ Target *newTarget = cloneTarget(m_targets.at(m_menuTargetIndex), k);
+
+ if (newTarget) {
+ m_project->addTarget(newTarget);
+ m_project->setActiveTarget(newTarget);
+ }
+}
+
+void TargetSettingsPanelWidget::addActionTriggered(QAction *action)
{
Kit *k = KitManager::instance()->find(action->data().value<Core::Id>());
QTC_ASSERT(!m_project->target(k), return);
@@ -253,10 +306,146 @@ void TargetSettingsPanelWidget::addTarget(QAction *action)
m_project->addTarget(target);
}
-void TargetSettingsPanelWidget::removeTarget(int targetIndex)
+Target *TargetSettingsPanelWidget::cloneTarget(Target *sourceTarget, Kit *k)
+{
+ Target *newTarget = new Target(m_project, k);
+
+ QStringList buildconfigurationError;
+ QStringList deployconfigurationError;
+ QStringList runconfigurationError;
+
+ foreach (BuildConfiguration *sourceBc, sourceTarget->buildConfigurations()) {
+ IBuildConfigurationFactory *factory = IBuildConfigurationFactory::find(newTarget, sourceBc);
+ if (!factory) {
+ buildconfigurationError << sourceBc->displayName();
+ continue;
+ }
+ BuildConfiguration *newBc = factory->clone(newTarget, sourceBc);
+ if (!newBc) {
+ buildconfigurationError << sourceBc->displayName();
+ continue;
+ }
+ newBc->setDisplayName(sourceBc->displayName());
+ newTarget->addBuildConfiguration(newBc);
+ if (sourceTarget->activeBuildConfiguration() == sourceBc)
+ newTarget->setActiveBuildConfiguration(newBc);
+ }
+ if (!newTarget->activeBuildConfiguration()) {
+ QList<BuildConfiguration *> bcs = newTarget->buildConfigurations();
+ if (!bcs.isEmpty())
+ newTarget->setActiveBuildConfiguration(bcs.first());
+ }
+
+ foreach (DeployConfiguration *sourceDc, sourceTarget->deployConfigurations()) {
+ DeployConfigurationFactory *factory = DeployConfigurationFactory::find(newTarget, sourceDc);
+ if (!factory) {
+ deployconfigurationError << sourceDc->displayName();
+ continue;
+ }
+ DeployConfiguration *newDc = factory->clone(newTarget, sourceDc);
+ if (!newDc) {
+ deployconfigurationError << sourceDc->displayName();
+ continue;
+ }
+ newDc->setDisplayName(sourceDc->displayName());
+ newTarget->addDeployConfiguration(newDc);
+ if (sourceTarget->activeDeployConfiguration() == sourceDc)
+ newTarget->setActiveDeployConfiguration(newDc);
+ }
+ if (!newTarget->activeBuildConfiguration()) {
+ QList<DeployConfiguration *> dcs = newTarget->deployConfigurations();
+ if (!dcs.isEmpty())
+ newTarget->setActiveDeployConfiguration(dcs.first());
+ }
+
+ foreach (RunConfiguration *sourceRc, sourceTarget->runConfigurations()) {
+ IRunConfigurationFactory *factory = IRunConfigurationFactory::find(newTarget, sourceRc);
+ if (!factory) {
+ runconfigurationError << sourceRc->displayName();
+ continue;
+ }
+ RunConfiguration *newRc = factory->clone(newTarget, sourceRc);
+ if (!newRc) {
+ runconfigurationError << sourceRc->displayName();
+ continue;
+ }
+ newRc->setDisplayName(sourceRc->displayName());
+ newTarget->addRunConfiguration(newRc);
+ if (sourceTarget->activeRunConfiguration() == sourceRc)
+ newTarget->setActiveRunConfiguration(newRc);
+ }
+ if (!newTarget->activeRunConfiguration()) {
+ QList<RunConfiguration *> rcs = newTarget->runConfigurations();
+ if (!rcs.isEmpty())
+ newTarget->setActiveRunConfiguration(rcs.first());
+ }
+
+ bool fatalError = false;
+ if (buildconfigurationError.count() == sourceTarget->buildConfigurations().count())
+ fatalError = true;
+
+ if (deployconfigurationError.count() == sourceTarget->deployConfigurations().count())
+ fatalError = true;
+
+ if (runconfigurationError.count() == sourceTarget->runConfigurations().count())
+ fatalError = true;
+
+ if (fatalError) {
+ // That could be a more granular error message
+ QMessageBox::critical(Core::ICore::mainWindow(),
+ tr("Incompatible Kit"),
+ tr("The Kit %1 is incompatible with Kit %2.")
+ .arg(sourceTarget->kit()->displayName())
+ .arg(k->displayName()));
+
+ delete newTarget;
+ newTarget = 0;
+ } else if (!buildconfigurationError.isEmpty()
+ || !deployconfigurationError.isEmpty()
+ || ! runconfigurationError.isEmpty()) {
+
+ QString error;
+ if (!buildconfigurationError.isEmpty())
+ error += tr("Build configurations:\n")
+ + buildconfigurationError.join(QLatin1String("\n"));
+
+ if (!deployconfigurationError.isEmpty()) {
+ if (!error.isEmpty())
+ error.append(QLatin1Char('\n'));
+ error += tr("Deploy configurations:\n")
+ + deployconfigurationError.join(QLatin1String("\n"));
+ }
+
+ if (!runconfigurationError.isEmpty()) {
+ if (!error.isEmpty())
+ error.append(QLatin1Char('\n'));
+ error += tr("Run configurations ")
+ + runconfigurationError.join(QLatin1String("\n"));
+ }
+
+ QMessageBox msgBox(Core::ICore::mainWindow());
+ msgBox.setIcon(QMessageBox::Warning);
+ msgBox.setWindowTitle(tr("Partial Incompatible Kit"));
+ msgBox.setText(tr("Some configurations could not be copied."));
+ msgBox.setDetailedText(error);
+ msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
+ if (msgBox.exec() != QDialog::Accepted) {
+ delete newTarget;
+ newTarget = 0;
+ }
+ }
+
+ return newTarget;
+}
+
+void TargetSettingsPanelWidget::removeTarget()
{
- Target *t = m_targets.at(targetIndex);
+ Target *t = m_targets.at(m_menuTargetIndex);
+ removeTarget(t);
+}
+void TargetSettingsPanelWidget::removeTarget(Target *t)
+{
ProjectExplorer::BuildManager *bm = ProjectExplorerPlugin::instance()->buildManager();
if (bm->isBuilding(t)) {
QMessageBox box;
@@ -307,7 +496,7 @@ void TargetSettingsPanelWidget::targetAdded(ProjectExplorer::Target *target)
}
connect(target, SIGNAL(displayNameChanged()), this, SLOT(renameTarget()));
- updateTargetAddAndRemoveButtons();
+ updateTargetButtons();
}
void TargetSettingsPanelWidget::removedTarget(ProjectExplorer::Target *target)
@@ -322,7 +511,7 @@ void TargetSettingsPanelWidget::removedTarget(ProjectExplorer::Target *target)
m_selector->removeTarget(index);
- updateTargetAddAndRemoveButtons();
+ updateTargetButtons();
}
void TargetSettingsPanelWidget::activeTargetChanged(ProjectExplorer::Target *target)
@@ -333,37 +522,61 @@ void TargetSettingsPanelWidget::activeTargetChanged(ProjectExplorer::Target *tar
m_selector->setCurrentIndex(index);
}
-void TargetSettingsPanelWidget::updateTargetAddAndRemoveButtons()
+namespace {
+bool diplayNameSorter(Kit *a, Kit *b)
+{
+ return a->displayName() < b->displayName();
+}
+}
+
+void TargetSettingsPanelWidget::createAction(Kit *k, QMenu *menu)
+{
+ QAction *action = new QAction(k->displayName(), menu);
+ action->setData(QVariant::fromValue(k->id()));
+ QString errorMessage;
+ if (!m_project->supportsKit(k, &errorMessage)) {
+ action->setEnabled(false);
+ action->setStatusTip(errorMessage);
+ }
+ menu->addAction(action);
+}
+
+void TargetSettingsPanelWidget::updateTargetButtons()
{
if (!m_selector)
return;
m_addMenu->clear();
+ m_targetMenu->clear();
- foreach (Kit *k, KitManager::instance()->kits()) {
- if (m_project->target(k))
- continue;
+ m_changeMenu = m_targetMenu->addMenu(tr("Change Kit"));
+ m_duplicateMenu = m_targetMenu->addMenu(tr("Copy to Kit"));
+ QAction *removeAction = m_targetMenu->addAction(tr("Remove Kit"));
- QAction *action = new QAction(k->displayName(), m_addMenu);
- action->setData(QVariant::fromValue(k->id()));
- QString errorMessage;
- if (!m_project->supportsKit(k, &errorMessage)) {
- action->setEnabled(false);
- action->setStatusTip(errorMessage);
- }
+ if (m_project->targets().size() < 2)
+ removeAction->setEnabled(false);
- bool inserted = false;
- foreach (QAction *existing, m_addMenu->actions()) {
- if (existing->text() > action->text()) {
- m_addMenu->insertAction(existing, action);
- inserted = true;
- break;
- }
- }
- if (!inserted)
- m_addMenu->addAction(action);
+ connect(m_changeMenu, SIGNAL(triggered(QAction*)),
+ this, SLOT(changeActionTriggered(QAction*)));
+ connect(m_duplicateMenu, SIGNAL(triggered(QAction*)),
+ this, SLOT(duplicateActionTriggered(QAction*)));
+ connect(removeAction, SIGNAL(triggered()), this, SLOT(removeTarget()));
+
+ QList<Kit *> kits = KitManager::instance()->kits();
+ qSort(kits.begin(), kits.end(), diplayNameSorter);
+ foreach (Kit *k, kits) {
+ if (m_project->target(k))
+ continue;
+ createAction(k, m_addMenu);
+ createAction(k, m_changeMenu);
+ createAction(k, m_duplicateMenu);
}
+ if (m_changeMenu->actions().isEmpty())
+ m_changeMenu->setEnabled(false);
+ if (m_duplicateMenu->actions().isEmpty())
+ m_duplicateMenu->setEnabled(false);
+
m_selector->setAddButtonEnabled(!m_addMenu->actions().isEmpty());
}
@@ -382,13 +595,12 @@ void TargetSettingsPanelWidget::openTargetPreferences()
{
int targetIndex = m_selector->currentIndex();
if (targetIndex >= 0 && targetIndex < m_targets.size()) {
- ProjectExplorer::KitOptionsPage *page =
- ExtensionSystem::PluginManager::instance()->getObject<ProjectExplorer::KitOptionsPage>();
+ KitOptionsPage *page = ExtensionSystem::PluginManager::getObject<ProjectExplorer::KitOptionsPage>();
if (page)
page->showKit(m_targets.at(targetIndex)->kit());
}
- Core::ICore::showOptionsDialog(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY),
- QLatin1String(Constants::KITS_SETTINGS_PAGE_ID));
+ ICore::showOptionsDialog(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ Constants::KITS_SETTINGS_PAGE_ID);
}
int TargetSettingsPanelWidget::currentSubIndex() const
@@ -400,3 +612,6 @@ void TargetSettingsPanelWidget::setCurrentSubIndex(int subIndex)
{
m_selector->setCurrentSubIndex(subIndex);
}
+
+} // namespace Internal
+} // namespace ProjectExplorer
diff --git a/src/plugins/projectexplorer/targetsettingspanel.h b/src/plugins/projectexplorer/targetsettingspanel.h
index 83a745e005..c6f847985c 100644
--- a/src/plugins/projectexplorer/targetsettingspanel.h
+++ b/src/plugins/projectexplorer/targetsettingspanel.h
@@ -42,6 +42,7 @@ namespace ProjectExplorer {
class Target;
class Project;
+class Kit;
namespace Internal {
@@ -64,17 +65,24 @@ protected:
bool event(QEvent *event);
private slots:
void currentTargetChanged(int targetIndex, int subIndex);
- void removeTarget(int targetIndex);
void showTargetToolTip(const QPoint &globalPos, int targetIndex);
- void addTarget(QAction *);
void targetAdded(ProjectExplorer::Target *target);
void removedTarget(ProjectExplorer::Target *target);
void activeTargetChanged(ProjectExplorer::Target *target);
- void updateTargetAddAndRemoveButtons();
+ void updateTargetButtons();
void renameTarget();
void openTargetPreferences();
+ void removeTarget();
+ void menuShown(int targetIndex);
+ void addActionTriggered(QAction *action);
+ void changeActionTriggered(QAction *action);
+ void duplicateActionTriggered(QAction *action);
private:
+ Target *cloneTarget(Target *sourceTarget, Kit *k);
+ void removeTarget(Target *t);
+ void createAction(Kit *k, QMenu *menu);
+
Target *m_currentTarget;
Project *m_project;
TargetSettingsWidget *m_selector;
@@ -82,8 +90,12 @@ private:
QWidget *m_noTargetLabel;
PanelsWidget *m_panelWidgets[2];
QList<Target *> m_targets;
+ QMenu *m_targetMenu;
+ QMenu *m_changeMenu;
+ QMenu *m_duplicateMenu;
QMenu *m_addMenu;
QAction *m_lastAction;
+ int m_menuTargetIndex;
};
} // namespace Internal
diff --git a/src/plugins/projectexplorer/targetsettingswidget.cpp b/src/plugins/projectexplorer/targetsettingswidget.cpp
index 0a7e278ff5..7e28a0126c 100644
--- a/src/plugins/projectexplorer/targetsettingswidget.cpp
+++ b/src/plugins/projectexplorer/targetsettingswidget.cpp
@@ -62,12 +62,12 @@ TargetSettingsWidget::TargetSettingsWidget(QWidget *parent) :
headerLayout->addWidget(m_targetSelector, 0, Qt::AlignBottom);
headerLayout->addStretch(10);
- connect(m_targetSelector, SIGNAL(removeButtonClicked(int)),
- this, SIGNAL(removeButtonClicked(int)));
connect(m_targetSelector, SIGNAL(currentChanged(int,int)),
this, SIGNAL(currentChanged(int,int)));
connect(m_targetSelector, SIGNAL(toolTipRequested(QPoint,int)),
this, SIGNAL(toolTipRequested(QPoint,int)));
+ connect(m_targetSelector, SIGNAL(menuShown(int)),
+ this, SIGNAL(menuShown(int)));
QPalette shadowPal = palette();
QLinearGradient grad(0, 0, 0, 2);
@@ -118,6 +118,11 @@ void TargetSettingsWidget::setAddButtonMenu(QMenu *menu)
m_addButton->setMenu(menu);
}
+void TargetSettingsWidget::setTargetMenu(QMenu *menu)
+{
+ m_targetSelector->setTargetMenu(menu);
+}
+
QString TargetSettingsWidget::targetNameAt(int index) const
{
return m_targetSelector->targetAt(index).name;
diff --git a/src/plugins/projectexplorer/targetsettingswidget.h b/src/plugins/projectexplorer/targetsettingswidget.h
index b03d5f8744..c48fa5ad49 100644
--- a/src/plugins/projectexplorer/targetsettingswidget.h
+++ b/src/plugins/projectexplorer/targetsettingswidget.h
@@ -38,6 +38,8 @@ class QPushButton;
QT_END_NAMESPACE
namespace ProjectExplorer {
+class Target;
+class Kit;
namespace Internal {
namespace Ui {
@@ -66,12 +68,14 @@ public:
void setCurrentSubIndex(int index);
void setAddButtonEnabled(bool enabled);
void setAddButtonMenu(QMenu *menu);
-
+ void setTargetMenu(QMenu *menu);
signals:
- void removeButtonClicked(int targetIndex);
void currentChanged(int targetIndex, int subIndex);
void manageButtonClicked();
+ void duplicateButtonClicked();
+ void changeKitButtonClicked();
void toolTipRequested(const QPoint &globalPosition, int targetIndex);
+ void menuShown(int targetIndex);
protected:
void changeEvent(QEvent *e);
diff --git a/src/plugins/projectexplorer/taskhub.cpp b/src/plugins/projectexplorer/taskhub.cpp
index 65e4c35896..f8fbcdfe4d 100644
--- a/src/plugins/projectexplorer/taskhub.cpp
+++ b/src/plugins/projectexplorer/taskhub.cpp
@@ -45,7 +45,7 @@ public:
setVisible(visible);
}
- bool clickable() const;
+ bool isClickable() const;
void clicked();
void updateFileName(const QString &fileName);
@@ -72,7 +72,7 @@ void TaskMark::removedFromEditor()
ProjectExplorerPlugin::instance()->taskHub()->updateTaskLineNumber(m_id, -1);
}
-bool TaskMark::clickable() const
+bool TaskMark::isClickable() const
{
return true;
}
diff --git a/src/plugins/projectexplorer/taskmodel.cpp b/src/plugins/projectexplorer/taskmodel.cpp
index f3de04b582..e132f44840 100644
--- a/src/plugins/projectexplorer/taskmodel.cpp
+++ b/src/plugins/projectexplorer/taskmodel.cpp
@@ -252,25 +252,24 @@ QVariant TaskModel::data(const QModelIndex &index, int role) const
if (!index.isValid() || index.row() >= m_tasks.count() || index.column() != 0)
return QVariant();
- if (role == TaskModel::File) {
+ if (role == TaskModel::File)
return m_tasks.at(index.row()).file.toString();
- } else if (role == TaskModel::Line) {
+ else if (role == TaskModel::Line)
return m_tasks.at(index.row()).line;
- } else if (role == TaskModel::MovedLine) {
+ else if (role == TaskModel::MovedLine)
return m_tasks.at(index.row()).movedLine;
- } else if (role == TaskModel::Description) {
+ else if (role == TaskModel::Description)
return m_tasks.at(index.row()).description;
- } else if (role == TaskModel::FileNotFound) {
+ else if (role == TaskModel::FileNotFound)
return m_fileNotFound.value(m_tasks.at(index.row()).file.toString());
- } else if (role == TaskModel::Type) {
+ else if (role == TaskModel::Type)
return (int)m_tasks.at(index.row()).type;
- } else if (role == TaskModel::Category) {
+ else if (role == TaskModel::Category)
return m_tasks.at(index.row()).category.uniqueIdentifier();
- } else if (role == TaskModel::Icon) {
+ else if (role == TaskModel::Icon)
return taskTypeIcon(m_tasks.at(index.row()).type);
- } else if (role == TaskModel::Task_t) {
+ else if (role == TaskModel::Task_t)
return QVariant::fromValue(task(index));
- }
return QVariant();
}
diff --git a/src/plugins/projectexplorer/taskwindow.cpp b/src/plugins/projectexplorer/taskwindow.cpp
index 5b5c8b39b3..aa8acaf5e9 100644
--- a/src/plugins/projectexplorer/taskwindow.cpp
+++ b/src/plugins/projectexplorer/taskwindow.cpp
@@ -68,7 +68,6 @@ public:
TaskView(QWidget *parent = 0);
~TaskView();
void resizeEvent(QResizeEvent *e);
- void keyPressEvent(QKeyEvent *e);
};
class TaskWindowContext : public Core::IContext
@@ -189,16 +188,6 @@ void TaskView::resizeEvent(QResizeEvent *e)
static_cast<TaskDelegate *>(itemDelegate())->emitSizeHintChanged(selectionModel()->currentIndex());
}
-void TaskView::keyPressEvent(QKeyEvent *e)
-{
- if (!e->modifiers() && e->key() == Qt::Key_Return) {
- emit activated(currentIndex());
- e->accept();
- return;
- }
- QListView::keyPressEvent(e);
-}
-
/////
// TaskWindow
/////
@@ -211,13 +200,13 @@ public:
Internal::TaskView *m_listview;
Internal::TaskWindowContext *m_taskWindowContext;
QMenu *m_contextMenu;
- QModelIndex m_contextMenuIndex;
ITaskHandler *m_defaultHandler;
QToolButton *m_filterWarningsButton;
QToolButton *m_categoriesButton;
QMenu *m_categoriesMenu;
TaskHub *m_taskHub;
int m_badgeCount;
+ QList<QAction *> m_actions;
};
static QToolButton *createFilterButton(QIcon icon, const QString &toolTip,
@@ -261,17 +250,14 @@ TaskWindow::TaskWindow(TaskHub *taskhub) : d(new TaskWindowPrivate)
connect(d->m_listview->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
tld, SLOT(currentChanged(QModelIndex,QModelIndex)));
+ connect(d->m_listview->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
+ this, SLOT(currentChanged(QModelIndex)));
connect(d->m_listview, SIGNAL(activated(QModelIndex)),
this, SLOT(triggerDefaultHandler(QModelIndex)));
d->m_contextMenu = new QMenu(d->m_listview);
- connect(d->m_contextMenu, SIGNAL(triggered(QAction*)),
- this, SLOT(contextMenuEntryTriggered(QAction*)));
- d->m_listview->setContextMenuPolicy(Qt::CustomContextMenu);
-
- connect(d->m_listview, SIGNAL(customContextMenuRequested(QPoint)),
- this, SLOT(showContextMenu(QPoint)));
+ d->m_listview->setContextMenuPolicy(Qt::ActionsContextMenu);
d->m_filterWarningsButton = createFilterButton(d->m_model->taskTypeIcon(Task::Warning),
tr("Show Warnings"),
@@ -315,7 +301,6 @@ TaskWindow::TaskWindow(TaskHub *taskhub) : d(new TaskWindowPrivate)
TaskWindow::~TaskWindow()
{
Core::ICore::removeContextObject(d->m_taskWindowContext);
- cleanContextMenu();
delete d->m_filterWarningsButton;
delete d->m_listview;
delete d->m_filter;
@@ -323,6 +308,43 @@ TaskWindow::~TaskWindow()
delete d;
}
+static ITaskHandler *handler(QAction *action)
+{
+ return qobject_cast<ITaskHandler *>(action->data().value<QObject *>());
+}
+
+void TaskWindow::delayedInitialization()
+{
+ static bool alreadyDone = false;
+ if (alreadyDone)
+ return;
+
+ alreadyDone = true;
+
+ QList<ITaskHandler *> handlers = ExtensionSystem::PluginManager::getObjects<ITaskHandler>();
+ foreach (ITaskHandler *h, handlers) {
+ if (h->isDefaultHandler() && !d->m_defaultHandler)
+ d->m_defaultHandler = h;
+
+ QAction *action = h->createAction(this);
+ QTC_ASSERT(action, continue);
+ action->setData(qVariantFromValue(qobject_cast<QObject*>(h)));
+ connect(action, SIGNAL(triggered()), this, SLOT(actionTriggered()));
+ d->m_actions << action;
+
+ Core::Id id = h->actionManagerId();
+ if (id.isValid()) {
+ Core::Command *cmd = Core::ActionManager::instance()
+ ->registerAction(action, id, d->m_taskWindowContext->context(), true);
+ action = cmd->action();
+ }
+ d->m_listview->addAction(action);
+ }
+
+ // Disable everything for now:
+ currentChanged(QModelIndex());
+}
+
QList<QWidget*> TaskWindow::toolBarWidgets() const
{
return QList<QWidget*>() << d->m_filterWarningsButton << d->m_categoriesButton;
@@ -362,11 +384,10 @@ void TaskWindow::setCategoryVisibility(const Core::Id &categoryId, bool visible)
QList<Core::Id> categories = d->m_filter->filteredCategories();
- if (visible) {
+ if (visible)
categories.removeOne(categoryId);
- } else {
+ else
categories.append(categoryId);
- }
d->m_filter->setFilteredCategories(categories);
@@ -382,8 +403,19 @@ void TaskWindow::setCategoryVisibility(const Core::Id &categoryId, bool visible)
setBadgeNumber(d->m_badgeCount);
}
-void TaskWindow::visibilityChanged(bool /* b */)
+void TaskWindow::currentChanged(const QModelIndex &index)
{
+ const Task task = index.isValid() ? d->m_filter->task(index) : Task();
+ foreach (QAction *action, d->m_actions) {
+ ITaskHandler *h = handler(action);
+ action->setEnabled((task.isNull() || !h) ? false : h->canHandle(task));
+ }
+}
+
+void TaskWindow::visibilityChanged(bool visible)
+{
+ if (visible)
+ delayedInitialization();
}
void TaskWindow::addCategory(const Core::Id &categoryId, const QString &displayName, bool visible)
@@ -470,20 +502,9 @@ void TaskWindow::openTask(unsigned int id)
void TaskWindow::triggerDefaultHandler(const QModelIndex &index)
{
- if (!index.isValid())
+ if (!index.isValid() || !d->m_defaultHandler)
return;
- // Find a default handler to use:
- if (!d->m_defaultHandler) {
- QList<ITaskHandler *> handlers = ExtensionSystem::PluginManager::getObjects<ITaskHandler>();
- foreach(ITaskHandler *handler, handlers) {
- if (handler->isDefaultHandler()) {
- d->m_defaultHandler = handler;
- break;
- }
- }
- }
- Q_ASSERT(d->m_defaultHandler);
Task task(d->m_filter->task(index));
if (task.isNull())
return;
@@ -496,49 +517,21 @@ void TaskWindow::triggerDefaultHandler(const QModelIndex &index)
}
}
-void TaskWindow::showContextMenu(const QPoint &position)
+void TaskWindow::actionTriggered()
{
- QModelIndex index = d->m_listview->indexAt(position);
- if (!index.isValid())
+ QAction *action = qobject_cast<QAction *>(sender());
+ if (!action || !action->isEnabled())
+ return;
+ ITaskHandler *h = handler(action);
+ if (!h)
return;
- d->m_contextMenuIndex = index;
- cleanContextMenu();
+ QModelIndex index = d->m_listview->selectionModel()->currentIndex();
Task task = d->m_filter->task(index);
if (task.isNull())
return;
- QList<ITaskHandler *> handlers = ExtensionSystem::PluginManager::getObjects<ITaskHandler>();
- foreach(ITaskHandler *handler, handlers) {
- if (handler == d->m_defaultHandler)
- continue;
- QAction * action = handler->createAction(d->m_contextMenu);
- action->setEnabled(handler->canHandle(task));
- action->setData(qVariantFromValue(qobject_cast<QObject*>(handler)));
- d->m_contextMenu->addAction(action);
- }
- d->m_contextMenu->popup(d->m_listview->mapToGlobal(position));
-}
-
-void TaskWindow::contextMenuEntryTriggered(QAction *action)
-{
- if (action->isEnabled()) {
- Task task = d->m_filter->task(d->m_contextMenuIndex);
- if (task.isNull())
- return;
-
- ITaskHandler *handler = qobject_cast<ITaskHandler*>(action->data().value<QObject*>());
- if (!handler)
- return;
- handler->handle(task);
- }
-}
-
-void TaskWindow::cleanContextMenu()
-{
- QList<QAction *> actions = d->m_contextMenu->actions();
- qDeleteAll(actions);
- d->m_contextMenu->clear();
+ h->handle(task);
}
void TaskWindow::setShowWarnings(bool show)
@@ -564,14 +557,14 @@ void TaskWindow::updateCategoriesMenu()
action->setCheckable(true);
action->setText(displayName);
action->setData(categoryId);
- action->setChecked(!filteredCategories.contains(Core::Id(categoryId.constData())));
+ action->setChecked(!filteredCategories.contains(Core::Id(categoryId)));
d->m_categoriesMenu->addAction(action);
}
}
void TaskWindow::filterCategoryTriggered(QAction *action)
{
- Core::Id categoryId(action->data().toByteArray().constData());
+ Core::Id categoryId(action->data().toByteArray());
QTC_CHECK(categoryId.uniqueIdentifier() != 0);
setCategoryVisibility(categoryId, action->isChecked());
@@ -618,9 +611,8 @@ void TaskWindow::setFocus()
{
if (d->m_filter->rowCount()) {
d->m_listview->setFocus();
- if (d->m_listview->currentIndex() == QModelIndex()) {
+ if (d->m_listview->currentIndex() == QModelIndex())
d->m_listview->setCurrentIndex(d->m_filter->index(0,0, QModelIndex()));
- }
}
}
@@ -848,7 +840,8 @@ void TaskDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
const QString directory = QDir::toNativeSeparators(index.data(TaskModel::File).toString());
int secondBaseLine = positions.top() + fm.ascent() + height + leading;
- if (index.data(TaskModel::FileNotFound).toBool()) {
+ if (index.data(TaskModel::FileNotFound).toBool()
+ && !directory.isEmpty()) {
QString fileNotFound = tr("File not found: %1").arg(directory);
painter->setPen(Qt::red);
painter->drawText(positions.textAreaLeft(), secondBaseLine, fileNotFound);
diff --git a/src/plugins/projectexplorer/taskwindow.h b/src/plugins/projectexplorer/taskwindow.h
index 3b35657f21..a9d8f45263 100644
--- a/src/plugins/projectexplorer/taskwindow.h
+++ b/src/plugins/projectexplorer/taskwindow.h
@@ -55,6 +55,8 @@ public:
TaskWindow(ProjectExplorer::TaskHub *taskHub);
virtual ~TaskWindow();
+ void delayedInitialization();
+
int taskCount(const Core::Id &category = Core::Id()) const;
int warningTaskCount(const Core::Id &category = Core::Id()) const;
int errorTaskCount(const Core::Id &category = Core::Id()) const;
@@ -92,16 +94,15 @@ private slots:
void openTask(unsigned int id);
void clearTasks(const Core::Id &categoryId);
void setCategoryVisibility(const Core::Id &categoryId, bool visible);
+ void currentChanged(const QModelIndex &index);
void triggerDefaultHandler(const QModelIndex &index);
- void showContextMenu(const QPoint &position);
- void contextMenuEntryTriggered(QAction *);
+ void actionTriggered();
void setShowWarnings(bool);
void updateCategoriesMenu();
void filterCategoryTriggered(QAction *action);
private:
- void cleanContextMenu();
int sizeHintForColumn(int column) const;
TaskWindowPrivate *d;
diff --git a/src/plugins/projectexplorer/toolchain.cpp b/src/plugins/projectexplorer/toolchain.cpp
index 71af0b6e68..6639934a73 100644
--- a/src/plugins/projectexplorer/toolchain.cpp
+++ b/src/plugins/projectexplorer/toolchain.cpp
@@ -60,7 +60,7 @@ public:
static QString createId(const QString &id)
{
- QString newId = id.left(id.indexOf(':'));
+ QString newId = id.left(id.indexOf(QLatin1Char(':')));
newId.append(QLatin1Char(':') + QUuid::createUuid().toString());
return newId;
}
@@ -133,11 +133,6 @@ bool ToolChain::canClone() const
return true;
}
-QString ToolChain::defaultMakeTarget() const
-{
- return QString();
-}
-
bool ToolChain::operator == (const ToolChain &tc) const
{
if (this == &tc)
diff --git a/src/plugins/projectexplorer/toolchain.h b/src/plugins/projectexplorer/toolchain.h
index d73d075f51..c247bea0a1 100644
--- a/src/plugins/projectexplorer/toolchain.h
+++ b/src/plugins/projectexplorer/toolchain.h
@@ -87,12 +87,12 @@ public:
STD_CXX11 = 1
};
virtual CompilerFlags compilerFlags(const QStringList &cxxflags) const = 0;
- virtual QList<HeaderPath> systemHeaderPaths(const Utils::FileName &sysRoot) const = 0;
+ virtual QList<HeaderPath> systemHeaderPaths(const QStringList &cxxflags,
+ const Utils::FileName &sysRoot) const = 0;
virtual void addToEnvironment(Utils::Environment &env) const = 0;
virtual QString makeCommand(const Utils::Environment &env) const = 0;
virtual Utils::FileName compilerCommand() const = 0;
- virtual QString defaultMakeTarget() const;
virtual IOutputParser *outputParser() const = 0;
virtual bool operator ==(const ToolChain &) const;
diff --git a/src/plugins/projectexplorer/toolchainmanager.cpp b/src/plugins/projectexplorer/toolchainmanager.cpp
index caf8bbf5fe..051530136e 100644
--- a/src/plugins/projectexplorer/toolchainmanager.cpp
+++ b/src/plugins/projectexplorer/toolchainmanager.cpp
@@ -188,11 +188,16 @@ void ToolChainManager::restoreToolChains()
registerToolChain(toStore);
}
- // Delete all loaded autodetected tool chains that were not rediscovered:
+ // Keep toolchains that were not rediscovered but are still executable and delete the rest
foreach (ToolChain *tc, tcsToCheck) {
- qWarning() << QString::fromLatin1("ToolChain \"%1\" (%2) dropped since it was not auto-detected again")
- .arg(tc->displayName()).arg(tc->id());
- delete tc;
+ QFileInfo fi = tc->compilerCommand().toFileInfo();
+ if (!fi.isExecutable()) {
+ qWarning() << QString::fromLatin1("ToolChain \"%1\" (%2) dropped since it is not executable")
+ .arg(tc->displayName()).arg(tc->id());
+ delete tc;
+ } else {
+ registerToolChain(tc);
+ }
}
// Store manual tool chains
diff --git a/src/plugins/projectexplorer/toolchainoptionspage.cpp b/src/plugins/projectexplorer/toolchainoptionspage.cpp
index c99470a170..5f12c1af7d 100644
--- a/src/plugins/projectexplorer/toolchainoptionspage.cpp
+++ b/src/plugins/projectexplorer/toolchainoptionspage.cpp
@@ -73,13 +73,16 @@ public:
~ToolChainNode()
{
- if (parent)
- parent->childNodes.removeOne(this);
-
- qDeleteAll(childNodes);
// Do not delete tool chain, we do not own it.
- Q_ASSERT(childNodes.isEmpty());
+ for (int i = childNodes.size(); --i >= 0; ) {
+ ToolChainNode *child = childNodes.at(i);
+ child->parent = 0;
+ delete child;
+ }
+
+ if (parent)
+ parent->childNodes.removeOne(this);
}
ToolChainNode *parent;
@@ -442,9 +445,9 @@ ToolChainOptionsPage::ToolChainOptionsPage() :
m_model(0), m_selectionModel(0), m_toolChainView(0), m_container(0),
m_addButton(0), m_cloneButton(0), m_delButton(0)
{
- setId(QLatin1String(Constants::TOOLCHAIN_SETTINGS_PAGE_ID));
+ setId(Constants::TOOLCHAIN_SETTINGS_PAGE_ID);
setDisplayName(tr("Compilers"));
- setCategory(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY));
+ setCategory(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
diff --git a/src/plugins/projectexplorer/toolchainoptionspage.h b/src/plugins/projectexplorer/toolchainoptionspage.h
index 1e609df7a6..19b365dca4 100644
--- a/src/plugins/projectexplorer/toolchainoptionspage.h
+++ b/src/plugins/projectexplorer/toolchainoptionspage.h
@@ -35,11 +35,9 @@
#include <QAbstractItemModel>
QT_BEGIN_NAMESPACE
-class QBoxLayout;
class QItemSelectionModel;
class QPushButton;
class QTreeView;
-class QTreeWidgetItem;
QT_END_NAMESPACE
namespace Utils { class DetailsWidget; }
@@ -49,7 +47,6 @@ namespace ProjectExplorer {
class ToolChain;
class ToolChainConfigWidget;
class ToolChainFactory;
-class ToolChainManager;
namespace Internal {
@@ -101,9 +98,9 @@ private:
QModelIndex index(ToolChainNode *, int column = 0) const;
ToolChainNode *createNode(ToolChainNode *parent, ToolChain *tc, bool changed);
- ToolChainNode * m_root;
- ToolChainNode * m_autoRoot;
- ToolChainNode * m_manualRoot;
+ ToolChainNode *m_root;
+ ToolChainNode *m_autoRoot;
+ ToolChainNode *m_manualRoot;
QList<ToolChainNode *> m_toAddList;
QList<ToolChainNode *> m_toRemoveList;
diff --git a/src/plugins/projectexplorer/wincetoolchain.cpp b/src/plugins/projectexplorer/wincetoolchain.cpp
index 098de259b8..923744edfa 100644
--- a/src/plugins/projectexplorer/wincetoolchain.cpp
+++ b/src/plugins/projectexplorer/wincetoolchain.cpp
@@ -189,7 +189,7 @@ static bool parseSDK(QXmlStreamReader& theReader,
if (theReader.isEndElement()) {
// Got to the end element so return...
- if (theReader.name() == "Platform")
+ if (theReader.name() == QLatin1String("Platform"))
return (sdkArch!=Abi::UnknownArchitecture && !sdkName.isEmpty());
} else if (theReader.isStartElement()) {
const QStringRef elemName = theReader.name();
diff --git a/src/plugins/qmldesigner/components/componentcore/abstractdesigneraction.h b/src/plugins/qmldesigner/components/componentcore/abstractdesigneraction.h
new file mode 100644
index 0000000000..f44f0a7a07
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/abstractdesigneraction.h
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef ABSTRACTDESIGNERACTION_H
+#define ABSTRACTDESIGNERACTION_H
+
+#include "componentcore_constants.h"
+#include "selectioncontext.h"
+
+QT_BEGIN_NAMESPACE
+class QAction;
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+class AbstractDesignerAction
+{
+public:
+ enum Type {
+ Menu,
+ Action
+ };
+
+ enum Priorities {
+ HighestPriority = ComponentCoreConstants::priorityFirst,
+ CustomActionsPriority = ComponentCoreConstants::priorityCustomActions,
+ RefactoringActionsPriority = ComponentCoreConstants::priorityRefactoring,
+ LowestPriority = ComponentCoreConstants::priorityLast
+ };
+
+ virtual ~AbstractDesignerAction() {}
+
+ virtual QAction *action() const = 0;
+ virtual QString category() const = 0;
+ virtual QString menuId() const = 0;
+ virtual int priority() const = 0;
+ virtual Type type() const = 0;
+ virtual void setCurrentContext(const SelectionContext &selectionState) = 0;
+
+protected:
+ virtual bool isVisible(const SelectionContext &selectionState) const = 0;
+ virtual bool isEnabled(const SelectionContext &selectionState) const = 0;
+};
+
+} //QmlDesigner
+
+#endif //ABSTRACTDESIGNERACTION_H
diff --git a/src/plugins/qmldesigner/components/componentcore/componentcore.pri b/src/plugins/qmldesigner/components/componentcore/componentcore.pri
new file mode 100644
index 0000000000..271a585736
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/componentcore.pri
@@ -0,0 +1,15 @@
+VPATH += $$PWD
+INCLUDEPATH += $$PWD
+SOURCES += modelnodecontextmenu.cpp
+SOURCES += modelnodecontextmenu_helper.cpp
+SOURCES += selectioncontext.cpp
+SOURCES += designeractionmanager.cpp
+SOURCES += modelnodeoperations.cpp
+
+HEADERS += modelnodecontextmenu.h
+HEADERS += modelnodecontextmenu_helper.h
+HEADERS += selectioncontext.h
+HEADERS += componentcore_constants.h
+HEADERS += designeractionmanager.h
+HEADERS += modelnodeoperations.h
+HEADERS += abstractdesigneraction.h
diff --git a/src/plugins/qmldesigner/components/componentcore/componentcore_constants.h b/src/plugins/qmldesigner/components/componentcore/componentcore_constants.h
new file mode 100644
index 0000000000..125494b1d0
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/componentcore_constants.h
@@ -0,0 +1,106 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef COMPONENTCORE_CONSTANTS_H
+#define COMPONENTCORE_CONSTANTS_H
+
+#include <QtGlobal>
+
+namespace QmlDesigner {
+
+namespace ComponentCoreConstants {
+
+const char rootCategory[] = "";
+
+const char selectionCategory[] = "Selection";
+const char stackCategory[] = "Stack (z)";
+const char editCategory[] = "Edit";
+const char anchorsCategory[] = "Anchors";
+const char layoutCategory[] = "Layout";
+
+const char selectionCategoryDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Selection");
+const char stackCategoryDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Stack (z)");
+const char editCategoryDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Edit");
+const char anchorsCategoryDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Anchors");
+const char layoutCategoryDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Layout");
+
+const char selectParentDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select parent: %1");
+const char selectDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select: %1");
+const char deSelectDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "DeSelect: ");
+
+const char cutSelectionDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Cut");
+const char copySelectionDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Copy");
+const char pasteSelectionDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Paste");
+const char deleteSelectionDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Delete selection");
+
+const char toFrontDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "To Front");
+const char toBackDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "To Back");
+
+const char raiseDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Raise");
+const char lowerDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Lower");
+
+const char undoDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Undo");
+const char redoDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Redo");
+
+const char visibilityDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Visibility");
+
+const char resetSizeDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Reset size");
+const char resetPositionDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Reset position");
+
+const char goIntoComponentDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Go into Component");
+
+const char setIdDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Set Id");
+
+const char resetZDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Reset z property");
+
+const char anchorsFillDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Fill");
+const char anchorsResetDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Reset");
+
+const char layoutColumnDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Layout in Column");
+const char layoutRowDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Layout in Row");
+const char layoutGridDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Layout in Grid");
+const char layoutFlowDisplayName[] = QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Layout in Flow");
+
+const int priorityFirst = 220;
+const int prioritySelectionCategory = 200;
+const int priorityStackCategory = 180;
+const int priorityEditCategory = 160;
+const int priorityAnchorsCategory = 140;
+const int priorityLayoutCategory = 120;
+const int priorityTopLevelSeperator = 100;
+const int priorityCustomActions = 80;
+const int priorityRefactoring = 60;
+const int priorityGoIntoComponent = 40;
+const int priorityLast = 60;
+
+} //ComponentCoreConstants
+
+} //QmlDesigner
+
+#endif //COMPONENTCORE_CONSTANTS_H
diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp
new file mode 100644
index 0000000000..cdce831037
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.cpp
@@ -0,0 +1,444 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "designeractionmanager.h"
+#include "modelnodecontextmenu_helper.h"
+#include "modelnodeoperations.h"
+#include "componentcore_constants.h"
+#include <nodeproperty.h>
+
+#include <QMenu>
+
+namespace QmlDesigner {
+
+static inline QString captionForModelNode(const ModelNode &modelNode)
+{
+ if (modelNode.id().isEmpty())
+ return modelNode.simplifiedTypeName();
+
+ return modelNode.id();
+}
+
+static inline bool contains(const QmlItemNode &node, const QPoint &position)
+{
+ return node.isValid() && node.instanceSceneTransform().mapRect(node.instanceBoundingRect()).contains(position);
+}
+
+namespace Internal {
+
+class DesignerActionManagerView : public QmlModelView
+{
+public:
+ DesignerActionManagerView() : QmlModelView(0), m_isInRewriterTransaction(false), m_setupContextDirty(false)
+ {}
+
+ void modelAttached(Model *model)
+ {
+ QmlModelView::modelAttached(model);
+ setupContext();
+ }
+
+ void modelAboutToBeDetached(Model *model)
+ {
+ QmlModelView::modelAboutToBeDetached(model);
+ setupContext();
+ }
+
+ virtual void nodeCreated(const ModelNode &)
+ {
+ setupContext();
+ }
+
+ virtual void nodeAboutToBeRemoved(const ModelNode &)
+ {}
+
+ virtual void nodeRemoved(const ModelNode &, const NodeAbstractProperty &, PropertyChangeFlags)
+ {
+ setupContext();
+ }
+
+ virtual void nodeAboutToBeReparented(const ModelNode &,
+ const NodeAbstractProperty &,
+ const NodeAbstractProperty &,
+ AbstractView::PropertyChangeFlags )
+ {
+ setupContext();
+ }
+
+ virtual void nodeReparented(const ModelNode &, const NodeAbstractProperty &,
+ const NodeAbstractProperty &,
+ AbstractView::PropertyChangeFlags)
+ {
+ setupContext();
+ }
+
+ virtual void nodeIdChanged(const ModelNode&, const QString&, const QString&)
+ {}
+
+ virtual void propertiesAboutToBeRemoved(const QList<AbstractProperty>&)
+ {}
+
+ virtual void propertiesRemoved(const QList<AbstractProperty>&)
+ {
+ setupContext();
+ }
+
+ virtual void variantPropertiesChanged(const QList<VariantProperty>&, PropertyChangeFlags)
+ {}
+
+ virtual void bindingPropertiesChanged(const QList<BindingProperty>&, PropertyChangeFlags)
+ {}
+
+ virtual void rootNodeTypeChanged(const QString &, int , int )
+ {
+ setupContext();
+ }
+
+ virtual void instancePropertyChange(const QList<QPair<ModelNode, QString> > &)
+ {}
+
+ virtual void instancesCompleted(const QVector<ModelNode> &)
+ {}
+
+ virtual void instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &)
+ {}
+
+ virtual void instancesRenderImageChanged(const QVector<ModelNode> &)
+ {}
+
+ virtual void instancesPreviewImageChanged(const QVector<ModelNode> &)
+ {}
+
+ virtual void instancesChildrenChanged(const QVector<ModelNode> &)
+ {}
+
+ virtual void instancesToken(const QString &, int , const QVector<ModelNode> &)
+ {}
+
+ virtual void nodeSourceChanged(const ModelNode &, const QString &)
+ {}
+
+ virtual void rewriterBeginTransaction()
+ {
+ m_isInRewriterTransaction = true;
+ }
+
+ virtual void rewriterEndTransaction()
+ {
+ m_isInRewriterTransaction = false;
+
+ if (m_setupContextDirty)
+ setupContext();
+ }
+
+ virtual void actualStateChanged(const ModelNode &)
+ {
+ setupContext();
+ }
+
+ virtual void selectedNodesChanged(const QList<ModelNode> &,
+ const QList<ModelNode> &)
+ {
+ setupContext();
+ }
+
+ virtual void nodeOrderChanged(const NodeListProperty &, const ModelNode &, int )
+ {
+ setupContext();
+ }
+
+ virtual void importsChanged(const QList<Import> &, const QList<Import> &)
+ {
+ setupContext();
+ }
+
+ virtual void scriptFunctionsChanged(const ModelNode &, const QStringList &)
+ {}
+
+ void setDesignerActionList(const QList<AbstractDesignerAction* > &designerActionList)
+ {
+ m_designerActionList = designerActionList;
+ }
+
+ QWidget *widget()
+ {
+ return 0;
+ }
+
+protected:
+ void setupContext()
+ {
+ if (m_isInRewriterTransaction) {
+ m_setupContextDirty = true;
+ return;
+ }
+ SelectionContext selectionContext(this);
+ foreach (AbstractDesignerAction* action, m_designerActionList) {
+ action->setCurrentContext(selectionContext);
+ }
+ m_setupContextDirty = false;
+ }
+
+ QList<AbstractDesignerAction* > m_designerActionList;
+ bool m_isInRewriterTransaction;
+ bool m_setupContextDirty;
+};
+
+} //Internal
+
+DesignerActionManager *DesignerActionManager::m_instance = 0;
+
+void DesignerActionManager::addDesignerAction(AbstractDesignerAction *newAction)
+{
+ instance()->addDesignerActionInternal(newAction);
+}
+
+QList<AbstractDesignerAction* > DesignerActionManager::designerActions()
+{
+ return instance()->factoriesInternal();
+}
+
+QmlModelView *DesignerActionManager::view()
+{
+ return instance()->m_view.data();
+}
+
+class VisiblityModelNodeAction : public ModelNodeAction
+{
+public:
+ VisiblityModelNodeAction(const QString &description, const QString &category, int priority,
+ ModelNodeOperations::SelectionAction action,
+ SelectionContextFunction enabled = &SelectionContextFunctors::always,
+ SelectionContextFunction visibility = &SelectionContextFunctors::always) :
+ ModelNodeAction(description, category, priority, action, enabled, visibility)
+ {}
+ virtual void updateContext()
+ {
+ m_action->setSelectionContext(m_selectionContext);
+ if (m_selectionContext.isValid()) {
+ m_action->setEnabled(isEnabled(m_selectionContext));
+ m_action->setVisible(isVisible(m_selectionContext));
+
+ m_action->setCheckable(true);
+ QmlItemNode itemNode = QmlItemNode(m_selectionContext.currentSingleSelectedNode());
+ if (itemNode.isValid())
+ m_action->setChecked(itemNode.instanceValue("visible").toBool());
+ else
+ m_action->setEnabled(false);
+ }
+ }
+};
+
+class SelectionModelNodeAction : public MenuDesignerAction
+{
+public:
+ SelectionModelNodeAction(const QString &displayName, const QString &menuId, int priority) :
+ MenuDesignerAction(displayName, menuId, priority,
+ &SelectionContextFunctors::always, &SelectionContextFunctors::selectionEnabled)
+
+ {}
+
+ virtual void updateContext()
+ {
+ m_menu->clear();
+ if (m_selectionContext.isValid()) {
+ m_action->setEnabled(isEnabled(m_selectionContext));
+ m_action->setVisible(isVisible(m_selectionContext));
+ } else {
+ return;
+ }
+ if (m_action->isEnabled()) {
+ ModelNode parentNode;
+ if (m_selectionContext.singleSelected() && !m_selectionContext.currentSingleSelectedNode().isRootNode()) {
+ ActionTemplate *selectionAction = new ActionTemplate(QString(), &ModelNodeOperations::select);
+ selectionAction->setParent(m_menu.data());
+
+ parentNode = m_selectionContext.currentSingleSelectedNode().parentProperty().parentModelNode();
+ m_selectionContext.setTargetNode(parentNode);
+ selectionAction->setText(QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select parent: %1")).arg(
+ captionForModelNode(parentNode)));
+ selectionAction->setSelectionContext(m_selectionContext);
+
+ m_menu->addAction(selectionAction);
+ }
+ foreach (const ModelNode &node, m_selectionContext.view()->allModelNodes()) {
+ if (node != m_selectionContext.currentSingleSelectedNode()
+ && node != parentNode
+ && contains(node, m_selectionContext.scenePos())
+ && !node.isRootNode()) {
+ m_selectionContext.setTargetNode(node);
+ QString what = QString(QT_TRANSLATE_NOOP("QmlDesignerContextMenu", "Select: %1")).arg(captionForModelNode(node));
+ ActionTemplate *selectionAction = new ActionTemplate(what, &ModelNodeOperations::select);
+ selectionAction->setSelectionContext(m_selectionContext);
+
+ m_menu->addAction(selectionAction);
+ }
+ }
+ }
+ }
+};
+
+char xProperty[] = "x";
+char yProperty[] = "y";
+char zProperty[] = "z";
+char widthProperty[] = "width";
+char heightProperty[] = "height";
+
+using namespace SelectionContextFunctors;
+
+bool multiSelection(const SelectionContext &context)
+{
+ return !singleSelection(context);
+}
+
+bool singleSelectionAndInBaseState(const SelectionContext &context)
+{
+ return singleSelection(context) && inBaseState(context);
+}
+
+bool multiSelectionAndInBaseState(const SelectionContext &context)
+{
+ return multiSelection(context) && inBaseState(context);
+}
+
+bool selectionHasProperty1or2(const SelectionContext &context, const char *x, const char *y)
+{
+ return selectionHasProperty(context, x) || selectionHasProperty(context, y);
+}
+
+bool selectionHasSameParentAndInBaseState(const SelectionContext &context)
+{
+ return selectionHasSameParent(context) && inBaseState(context);
+}
+
+bool selectionCanBeLayouted(const SelectionContext &context)
+{
+ return selectionHasSameParentAndInBaseState(context) && inBaseState(context);
+}
+
+bool selectionNotEmptyAndHasZProperty(const SelectionContext &context)
+{
+ return selectionNotEmpty(context) && selectionHasProperty(context, zProperty);
+}
+
+bool selectionNotEmptyAndHasWidthOrHeightProperty(const SelectionContext &context)
+{
+ return selectionNotEmpty(context)
+ && selectionHasProperty1or2(context, widthProperty, heightProperty);
+}
+
+bool selectionNotEmptyAndHasXorYProperty(const SelectionContext &context)
+{
+ return selectionNotEmpty(context)
+ && selectionHasProperty1or2(context, xProperty, yProperty);
+}
+
+void DesignerActionManager::createDefaultDesignerActions()
+{
+ using namespace SelectionContextFunctors;
+ using namespace ComponentCoreConstants;
+ using namespace ModelNodeOperations;
+
+ addDesignerAction(new SelectionModelNodeAction(selectionCategoryDisplayName, selectionCategory, prioritySelectionCategory));
+
+ addDesignerAction(new MenuDesignerAction(stackCategoryDisplayName, stackCategory, priorityStackCategory, &always));
+ addDesignerAction(new ModelNodeAction
+ (toFrontDisplayName, stackCategory, 200, &toFront, &singleSelection));
+ addDesignerAction(new ModelNodeAction
+ (toBackDisplayName, stackCategory, 180, &toBack, &singleSelection));
+ addDesignerAction(new ModelNodeAction
+ (raiseDisplayName, stackCategory, 160, &raise, &selectionNotEmpty));
+ addDesignerAction(new ModelNodeAction
+ (lowerDisplayName, stackCategory, 140, &lower, &selectionNotEmpty));
+ addDesignerAction(new SeperatorDesignerAction(stackCategory, 120));
+ addDesignerAction(new ModelNodeAction
+ (resetZDisplayName, stackCategory, 100, &resetZ, &selectionNotEmptyAndHasZProperty));
+
+ addDesignerAction(new MenuDesignerAction(editCategoryDisplayName, editCategory, priorityEditCategory, &selectionNotEmpty));
+ addDesignerAction(new ModelNodeAction
+ (resetPositionDisplayName, editCategory, 200, &resetPosition, &selectionNotEmptyAndHasXorYProperty));
+ addDesignerAction(new ModelNodeAction
+ (resetSizeDisplayName, editCategory, 180, &resetSize, &selectionNotEmptyAndHasWidthOrHeightProperty));
+ addDesignerAction(new VisiblityModelNodeAction
+ (visibilityDisplayName, editCategory, 160, &setVisible, &singleSelectedItem));
+
+ addDesignerAction(new MenuDesignerAction(anchorsCategoryDisplayName, anchorsCategory,
+ priorityAnchorsCategory, &singleSelectionAndInBaseState));
+ addDesignerAction(new ModelNodeAction
+ (anchorsFillDisplayName, anchorsCategory, 200, &anchorsFill, &singleSelectionItemIsNotAnchored));
+ addDesignerAction(new ModelNodeAction
+ (anchorsResetDisplayName, anchorsCategory, 180, &anchorsReset, &singleSelectionItemIsAnchored));
+
+ addDesignerAction(new MenuDesignerAction(layoutCategoryDisplayName, layoutCategory,
+ priorityLayoutCategory, &multiSelectionAndInBaseState));
+ addDesignerAction(new ModelNodeAction
+ (layoutRowDisplayName, layoutCategory, 200, &layoutRow, &selectionCanBeLayouted));
+ addDesignerAction(new ModelNodeAction
+ (layoutColumnDisplayName, layoutCategory, 180, &layoutColumn, &selectionCanBeLayouted));
+ addDesignerAction(new ModelNodeAction
+ (layoutGridDisplayName, layoutCategory, 160, &layoutGrid, &selectionCanBeLayouted));
+ addDesignerAction(new ModelNodeAction
+ (layoutFlowDisplayName, layoutCategory, 140, &layoutFlow, &selectionCanBeLayouted));
+
+ addDesignerAction(new SeperatorDesignerAction(rootCategory, priorityTopLevelSeperator));
+ addDesignerAction(new ModelNodeAction
+ (goIntoComponentDisplayName, rootCategory, priorityGoIntoComponent, &goIntoComponent, &selectionIsComponent));
+}
+
+DesignerActionManager *DesignerActionManager::instance()
+{
+ if (!m_instance) {
+ m_instance = new DesignerActionManager;
+ createDefaultDesignerActions();
+ }
+
+ return m_instance;
+}
+
+void DesignerActionManager::addDesignerActionInternal(AbstractDesignerAction *newAction)
+{
+ m_designerActions.append(QSharedPointer<AbstractDesignerAction>(newAction));
+ m_view->setDesignerActionList(designerActions());
+}
+
+QList<AbstractDesignerAction* > DesignerActionManager::factoriesInternal() const
+{
+ QList<AbstractDesignerAction* > list;
+ foreach (const QSharedPointer<AbstractDesignerAction> &pointer, m_designerActions) {
+ list.append(pointer.data());
+ }
+
+ return list;
+}
+
+DesignerActionManager::DesignerActionManager() : m_view(new Internal::DesignerActionManagerView)
+{
+}
+
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h
new file mode 100644
index 0000000000..87a4c91140
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/designeractionmanager.h
@@ -0,0 +1,66 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef DESIGNERACTIONMANAGER_H
+#define DESIGNERACTIONMANAGER_H
+
+#include "abstractdesigneraction.h"
+#include "qmlmodelview.h"
+
+#include <QScopedPointer>
+
+namespace QmlDesigner {
+
+namespace Internal {
+class DesignerActionManagerView;
+}
+
+class DesignerActionManager {
+public:
+ static void addDesignerAction(AbstractDesignerAction *newAction);
+ static QList<AbstractDesignerAction* > designerActions();
+
+ static void createDefaultDesignerActions();
+ static QmlModelView *view();
+
+protected:
+ static DesignerActionManager *instance();
+ void addDesignerActionInternal(AbstractDesignerAction *newAction);
+ QList<AbstractDesignerAction* > factoriesInternal() const;
+ DesignerActionManager();
+
+private:
+ static DesignerActionManager *m_instance;
+ QList<QSharedPointer<AbstractDesignerAction> > m_designerActions;
+ QScopedPointer<Internal::DesignerActionManagerView> m_view;
+};
+
+} //QmlDesigner
+
+#endif //DESIGNERACTIONMANAGER_H
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp
new file mode 100644
index 0000000000..51750ac6e6
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.cpp
@@ -0,0 +1,140 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "modelnodecontextmenu.h"
+#include "modelnodecontextmenu_helper.h"
+#include "designeractionmanager.h"
+
+#include <cmath>
+#include <QApplication>
+#include <QMessageBox>
+#include <coreplugin/editormanager/editormanager.h>
+#include <nodeabstractproperty.h>
+#include <nodelistproperty.h>
+#include <nodemetainfo.h>
+#include <modelnode.h>
+#include <qmlitemnode.h>
+#include <variantproperty.h>
+#include <bindingproperty.h>
+#include <nodeproperty.h>
+#include <rewritingexception.h>
+#include <rewritertransaction.h>
+#include <designmodewidget.h>
+#include <qmlanchors.h>
+
+#include <QSet>
+
+namespace QmlDesigner {
+
+ModelNodeContextMenu::ModelNodeContextMenu(QmlModelView *view) :
+ m_view(view),
+ m_selectionContext(view)
+{
+}
+
+static bool sortFunction(AbstractDesignerAction * abstractDesignerAction01, AbstractDesignerAction *abstractDesignerAction02)
+{
+ return abstractDesignerAction01->priority() > abstractDesignerAction02->priority();
+}
+
+static QSet<AbstractDesignerAction* > findMembers(QSet<AbstractDesignerAction* > designerActionSet,
+ const QString &category)
+{
+ QSet<AbstractDesignerAction* > ret;
+
+ foreach (AbstractDesignerAction* factory, designerActionSet) {
+ if (factory->category() == category)
+ ret.insert(factory);
+ }
+ return ret;
+}
+
+
+void populateMenu(QSet<AbstractDesignerAction* > &abstractDesignerActions,
+ const QString &category,
+ QMenu* menu,
+ const SelectionContext &selectionContext)
+{
+ QSet<AbstractDesignerAction* > matchingFactories = findMembers(abstractDesignerActions, category);
+
+ abstractDesignerActions.subtract(matchingFactories);
+
+ QList<AbstractDesignerAction* > matchingFactoriesList = matchingFactories.toList();
+ qSort(matchingFactoriesList.begin(), matchingFactoriesList.end(), &sortFunction);
+
+ foreach (AbstractDesignerAction* designerAction, matchingFactoriesList) {
+ if (designerAction->type() == AbstractDesignerAction::Menu) {
+ designerAction->setCurrentContext(selectionContext);
+ QMenu *newMenu = designerAction->action()->menu();
+ menu->addMenu(newMenu);
+
+ //recurse
+
+ populateMenu(abstractDesignerActions, designerAction->menuId(), newMenu, selectionContext);
+ } else if (designerAction->type() == AbstractDesignerAction::Action) {
+ QAction* action = designerAction->action();
+ designerAction->setCurrentContext(selectionContext);
+ menu->addAction(action);
+ }
+ }
+}
+
+void ModelNodeContextMenu::execute(const QPoint &position, bool selectionMenuBool)
+{
+ QMenu* mainMenu = new QMenu();
+
+ m_selectionContext.setShowSelectionTools(selectionMenuBool);
+ m_selectionContext.setScenePos(m_scenePos);
+
+
+ QSet<AbstractDesignerAction* > factories =
+ QSet<AbstractDesignerAction* >::fromList(DesignerActionManager::designerActions());
+
+ populateMenu(factories, QString(""), mainMenu, m_selectionContext);
+
+ mainMenu->exec(position);
+ mainMenu->deleteLater();
+}
+
+void ModelNodeContextMenu::setScenePos(const QPoint &position)
+{
+ m_scenePos = position;
+}
+
+void ModelNodeContextMenu::showContextMenu(QmlModelView *view,
+ const QPoint &globalPosition,
+ const QPoint &scenePosition,
+ bool showSelection)
+{
+ ModelNodeContextMenu contextMenu(view);
+ contextMenu.setScenePos(scenePosition);
+ contextMenu.execute(globalPosition, showSelection);
+}
+
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h
new file mode 100644
index 0000000000..869890735c
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu.h
@@ -0,0 +1,59 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef MODELNODECONTEXTMENU_H
+#define MODELNODECONTEXTMENU_H
+
+#include <QPoint>
+#include <QCoreApplication>
+
+#include <qmlmodelview.h>
+#include "selectioncontext.h"
+
+namespace QmlDesigner {
+
+class ModelNodeContextMenu
+{
+ Q_DECLARE_TR_FUNCTIONS(QmlDesigner::ModelNodeContextMenu)
+public:
+ ModelNodeContextMenu(QmlModelView *view);
+ void execute(const QPoint &pos, bool selectionMenu);
+ void setScenePos(const QPoint &pos);
+
+ static void showContextMenu(QmlModelView *view, const QPoint &globalPosition, const QPoint &scenePosition, bool showSelection);
+
+private:
+ QmlModelView *m_view;
+ QPoint m_scenePos;
+ SelectionContext m_selectionContext;
+};
+
+}; //QmlDesigner
+
+#endif // MODELNODECONTEXTMENU_H
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp
new file mode 100644
index 0000000000..4cddd48293
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.cpp
@@ -0,0 +1,274 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "modelnodecontextmenu_helper.h"
+
+#include <nodemetainfo.h>
+#include <modelnode.h>
+#include <qmlitemnode.h>
+#include <bindingproperty.h>
+#include <nodeproperty.h>
+#include <designmodewidget.h>
+#include <qmldesignerplugin.h>
+
+namespace QmlDesigner {
+
+static inline DesignDocument* currentDesignDocument()
+{
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
+}
+
+static inline bool checkIfNodeIsAView(const ModelNode &node)
+{
+ return node.metaInfo().isValid() &&
+ (node.metaInfo().isSubclassOf("QtQuick.ListView", -1, -1) ||
+ node.metaInfo().isSubclassOf("QtQuick.GridView", -1, -1) ||
+ node.metaInfo().isSubclassOf("QtQuick.PathView", -1, -1));
+}
+
+static inline void getProperties(const ModelNode node, QHash<QString, QVariant> &propertyHash)
+{
+ if (QmlObjectNode(node).isValid()) {
+ foreach (const QString &propertyName, node.propertyNames()) {
+ if (node.property(propertyName).isVariantProperty() ||
+ (node.property(propertyName).isBindingProperty() &&
+ !propertyName.contains(QLatin1String("anchors.")))) {
+ propertyHash.insert(propertyName, QmlObjectNode(node).instanceValue(propertyName));
+ }
+ }
+ }
+ QmlItemNode itemNode(node);
+ if (itemNode.isValid()) {
+ propertyHash.insert(QLatin1String("width"), itemNode.instanceValue(QLatin1String("width")));
+ propertyHash.insert(QLatin1String("height"), itemNode.instanceValue(QLatin1String("height")));
+ propertyHash.remove(QLatin1String("x"));
+ propertyHash.remove(QLatin1String("y"));
+ propertyHash.remove(QLatin1String("rotation"));
+ propertyHash.remove(QLatin1String("opacity"));
+ }
+}
+
+static inline void applyProperties(ModelNode &node, const QHash<QString, QVariant> &propertyHash)
+{
+ QHash<QString, QVariant> auxiliaryData = node.auxiliaryData();
+ foreach (const QString propertyName, auxiliaryData.keys()) {
+ node.setAuxiliaryData(propertyName, QVariant());
+ }
+
+ QHashIterator<QString, QVariant> propertyIterator(propertyHash);
+ while (propertyIterator.hasNext()) {
+ propertyIterator.next();
+ const QString propertyName = propertyIterator.key();
+ if (propertyName == QLatin1String("width") || propertyName == QLatin1String("height")) {
+ node.setAuxiliaryData(propertyIterator.key(), propertyIterator.value());
+ } else if (node.property(propertyIterator.key()).isDynamic() &&
+ node.property(propertyIterator.key()).dynamicTypeName() == QLatin1String("alias") &&
+ node.property(propertyIterator.key()).isBindingProperty()) {
+ AbstractProperty targetProperty = node.bindingProperty(propertyIterator.key()).resolveToProperty();
+ if (targetProperty.isValid())
+ targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + QLatin1String("@NodeInstance"), propertyIterator.value());
+ } else {
+ node.setAuxiliaryData(propertyIterator.key() + QLatin1String("@NodeInstance"), propertyIterator.value());
+ }
+ }
+}
+
+static inline bool modelNodeIsComponent(const ModelNode &node)
+{
+ if (!node.isValid() || !node.metaInfo().isValid())
+ return false;
+
+ if (node.metaInfo().isFileComponent())
+ return true;
+
+ if (node.nodeSourceType() == ModelNode::NodeWithComponentSource)
+ return true;
+ if (checkIfNodeIsAView(node) &&
+ node.hasNodeProperty("delegate")) {
+ if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
+ return true;
+ if (node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource)
+ return true;
+ }
+
+ return false;
+}
+
+static inline bool itemsHaveSameParent(const QList<ModelNode> &siblingList)
+{
+ if (siblingList.isEmpty())
+ return false;
+
+
+ QmlItemNode item(siblingList.first());
+ if (!item.isValid())
+ return false;
+
+ if (item.isRootModelNode())
+ return false;
+
+ QmlItemNode parent = item.instanceParent().toQmlItemNode();
+ if (!parent.isValid())
+ return false;
+
+ foreach (const ModelNode &node, siblingList) {
+ QmlItemNode currentItem(node);
+ if (!currentItem.isValid())
+ return false;
+ QmlItemNode currentParent = currentItem.instanceParent().toQmlItemNode();
+ if (!currentParent.isValid())
+ return false;
+ if (currentItem.instanceIsInPositioner())
+ return false;
+ if (currentParent != parent)
+ return false;
+ }
+ return true;
+}
+
+static inline bool isFileComponent(const ModelNode &node)
+{
+ if (!node.isValid() || !node.metaInfo().isValid())
+ return false;
+
+ if (node.metaInfo().isFileComponent())
+ return true;
+
+ if (checkIfNodeIsAView(node) &&
+ node.hasNodeProperty("delegate")) {
+ if (node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent())
+ return true;
+ }
+
+ return false;
+}
+
+static inline void openFileForComponent(const ModelNode &node)
+{
+ QmlDesignerPlugin::instance()->viewManager().nextFileIsCalledInternally();
+
+ //int width = 0;
+ //int height = 0;
+ QHash<QString, QVariant> propertyHash;
+ if (node.metaInfo().isFileComponent()) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ currentDesignDocument()->changeToExternalSubComponent(node.metaInfo().componentFileName());
+ } else if (checkIfNodeIsAView(node) &&
+ node.hasNodeProperty("delegate") &&
+ node.nodeProperty("delegate").modelNode().metaInfo().isFileComponent()) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ currentDesignDocument()->changeToExternalSubComponent(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName());
+ }
+ ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
+ applyProperties(rootModelNode, propertyHash);
+ //rootModelNode.setAuxiliaryData("width", width);
+ //rootModelNode.setAuxiliaryData("height", height);
+}
+
+static inline void openInlineComponent(const ModelNode &node)
+{
+
+ if (!node.isValid() || !node.metaInfo().isValid())
+ return;
+
+ if (!currentDesignDocument())
+ return;
+
+ QHash<QString, QVariant> propertyHash;
+
+ if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ currentDesignDocument()->changeToSubComponent(node);
+ } else if (checkIfNodeIsAView(node) &&
+ node.hasNodeProperty("delegate")) {
+ if (node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {
+ //getWidthHeight(node, width, height);
+ getProperties(node, propertyHash);
+ currentDesignDocument()->changeToSubComponent(node.nodeProperty("delegate").modelNode());
+ }
+ }
+
+ ModelNode rootModelNode = currentDesignDocument()->rewriterView()->rootModelNode();
+ applyProperties(rootModelNode, propertyHash);
+ //rootModelNode.setAuxiliaryData("width", width);
+ //rootModelNode.setAuxiliaryData("height", height);
+}
+
+namespace ComponentUtils {
+void goIntoComponent(const ModelNode &modelNode)
+{
+ if (modelNode.isValid() && modelNodeIsComponent(modelNode)) {
+ QmlDesignerPlugin::instance()->viewManager().setComponentNode(modelNode);
+ if (isFileComponent(modelNode))
+ openFileForComponent(modelNode);
+ else
+ openInlineComponent(modelNode);
+ }
+}
+
+} // namespace ComponentUtils
+
+namespace SelectionContextFunctors {
+
+bool singleSelectionItemIsAnchored(const SelectionContext &selectionState)
+{
+ QmlItemNode itemNode(selectionState.currentSingleSelectedNode());
+ if (selectionState.isInBaseState() && itemNode.isValid()) {
+ bool anchored = itemNode.instanceHasAnchors();
+ return anchored;
+ }
+ return false;
+}
+
+bool singleSelectionItemIsNotAnchored(const SelectionContext &selectionState)
+{
+ QmlItemNode itemNode(selectionState.currentSingleSelectedNode());
+ if (selectionState.isInBaseState() && itemNode.isValid()) {
+ bool anchored = itemNode.instanceHasAnchors();
+ return !anchored;
+ }
+ return false;
+}
+
+bool selectionHasSameParent(const SelectionContext &selectionState)
+{
+ return !selectionState.selectedModelNodes().isEmpty() && itemsHaveSameParent(selectionState.selectedModelNodes());
+}
+
+bool selectionIsComponent(const SelectionContext &selectionState)
+{
+ return modelNodeIsComponent(selectionState.currentSingleSelectedNode());
+}
+
+} //SelectionStateFunctors
+
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h
new file mode 100644
index 0000000000..d5312fdfb7
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodecontextmenu_helper.h
@@ -0,0 +1,280 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef MODELNODECONTEXTMENU_HELPER_H
+#define MODELNODECONTEXTMENU_HELPER_H
+
+#include "modelnodecontextmenu.h"
+#include "modelnodeoperations.h"
+#include "designeractionmanager.h"
+
+#include <QAction>
+#include <QMenu>
+
+namespace QmlDesigner {
+
+typedef bool (*SelectionContextFunction)(const SelectionContext &);
+
+namespace SelectionContextFunctors {
+
+inline bool always(const SelectionContext &)
+{
+ return true;
+}
+
+inline bool inBaseState(const SelectionContext &selectionState)
+{
+ return selectionState.isInBaseState();
+}
+
+inline bool singleSelection(const SelectionContext &selectionState)
+{
+ return selectionState.singleSelected();
+}
+
+inline bool selectionEnabled(const SelectionContext &selectionState)
+{
+ return selectionState.showSelectionTools();
+}
+
+inline bool selectionNotEmpty(const SelectionContext &selectionState)
+{
+ return !selectionState.selectedModelNodes().isEmpty();
+}
+
+inline bool singleSelectionNotRoot(const SelectionContext &selectionState)
+{
+ return selectionState.singleSelected()
+ && !selectionState.currentSingleSelectedNode().isRootNode();
+}
+
+inline bool selectionHasProperty(const SelectionContext &selectionState, const char *property)
+{
+ foreach (const ModelNode &modelNode, selectionState.selectedModelNodes())
+ if (modelNode.hasProperty(QLatin1String(property)))
+ return true;
+ return false;
+}
+
+inline bool singleSelectedItem(const SelectionContext &selectionState)
+{
+ QmlItemNode itemNode(selectionState.currentSingleSelectedNode());
+ return itemNode.isValid();
+}
+
+bool selectionHasSameParent(const SelectionContext &selectionState);
+bool selectionIsComponent(const SelectionContext &selectionState);
+bool selectionIsComponent(const SelectionContext &selectionState);
+bool singleSelectionItemIsAnchored(const SelectionContext &selectionState);
+bool singleSelectionItemIsNotAnchored(const SelectionContext &selectionState);
+
+} // namespace SelectionStateFunctors
+
+
+namespace ComponentUtils {
+ void goIntoComponent(const ModelNode &modelNode);
+}
+
+class DefaultAction : public QAction
+{
+ Q_OBJECT
+
+public:
+ DefaultAction(const QString &description) : QAction(description, 0)
+ {
+ connect(this, SIGNAL(triggered(bool)), this, SLOT(actionTriggered(bool)));
+ }
+
+public slots: //virtual method instead of slot
+ virtual void actionTriggered(bool)
+ { }
+
+ void setSelectionContext(const SelectionContext &selectionContext)
+ {
+ m_selectionContext = selectionContext;
+ }
+
+protected:
+ SelectionContext m_selectionContext;
+};
+
+class ActionTemplate : public DefaultAction
+{
+
+public:
+ ActionTemplate(const QString &description, ModelNodeOperations::SelectionAction action)
+ : DefaultAction(description), m_action(action)
+ { }
+
+public /*slots*/:
+ virtual void actionTriggered(bool b)
+ {
+ m_selectionContext.setToggled(b);
+ return m_action(m_selectionContext);
+ }
+ ModelNodeOperations::SelectionAction m_action;
+};
+
+
+class DefaultDesignerAction : public AbstractDesignerAction
+{
+public:
+ DefaultDesignerAction() : m_action(new DefaultAction(QString()))
+ {}
+
+ DefaultDesignerAction(DefaultAction *action) : m_action(action)
+ {}
+
+ QAction *action() const { return m_action; }
+
+ void setCurrentContext(const SelectionContext &selectionContext)
+ {
+ m_selectionContext = selectionContext;
+ updateContext();
+ }
+
+ virtual void updateContext()
+ {
+ m_action->setSelectionContext(m_selectionContext);
+ if (m_selectionContext.isValid()) {
+ m_action->setEnabled(isEnabled(m_selectionContext));
+ m_action->setVisible(isVisible(m_selectionContext));
+ }
+ }
+
+protected:
+ DefaultAction *m_action;
+ SelectionContext m_selectionContext;
+};
+
+class MenuDesignerAction : public AbstractDesignerAction
+{
+public:
+ MenuDesignerAction(const QString &displayName, const QString &menuId, int priority,
+ SelectionContextFunction enabled = &SelectionContextFunctors::always,
+ SelectionContextFunction visibility = &SelectionContextFunctors::always) :
+ m_displayName(displayName),
+ m_menuId(menuId),
+ m_priority(priority),
+ m_menu(new QMenu),
+ m_enabled(enabled),
+ m_visibility(visibility)
+ {
+ m_menu->setTitle(displayName);
+ m_action = m_menu->menuAction();
+ }
+
+ bool isVisible(const SelectionContext &m_selectionState) const { return m_visibility(m_selectionState); }
+ bool isEnabled(const SelectionContext &m_selectionState) const { return m_enabled(m_selectionState); }
+ QString category() const { return QString(); }
+ QString menuId() const { return m_menuId; }
+ int priority() const { return m_priority; }
+ AbstractDesignerAction::Type type() const { return AbstractDesignerAction::Menu; }
+ QAction *action() const { return m_action; }
+
+ virtual void setCurrentContext(const SelectionContext &selectionContext)
+ {
+ m_selectionContext = selectionContext;
+ updateContext();
+ }
+
+ virtual void updateContext()
+ {
+ if (m_selectionContext.isValid()) {
+ m_action->setEnabled(isEnabled(m_selectionContext));
+ m_action->setVisible(isVisible(m_selectionContext));
+ }
+ }
+
+protected:
+ const QString m_displayName;
+ const QString m_menuId;
+ const int m_priority;
+ SelectionContext m_selectionContext;
+ QScopedPointer<QMenu> m_menu;
+ QAction *m_action;
+ SelectionContextFunction m_enabled;
+ SelectionContextFunction m_visibility;
+};
+
+class SeperatorDesignerAction : public DefaultDesignerAction
+{
+public:
+ SeperatorDesignerAction(const QString &category, int priority) :
+ m_category(category),
+ m_priority(priority),
+ m_visibility(&SelectionContextFunctors::always)
+ { m_action->setSeparator(true); }
+
+ bool isVisible(const SelectionContext &m_selectionState) const { return m_visibility(m_selectionState); }
+ bool isEnabled(const SelectionContext &) const { return true; }
+ QString category() const { return m_category; }
+ QString menuId() const { return QString(); }
+ int priority() const { return m_priority; }
+ Type type() const { return Action; }
+ void setCurrentContext(const SelectionContext &) {}
+
+private:
+ const QString m_category;
+ const int m_priority;
+ SelectionContextFunction m_visibility;
+};
+
+class ModelNodeAction : public DefaultDesignerAction
+{
+public:
+ ModelNodeAction(const QString &description, const QString &category, int priority,
+ ModelNodeOperations::SelectionAction selectionAction,
+ SelectionContextFunction enabled = &SelectionContextFunctors::always,
+ SelectionContextFunction visibility = &SelectionContextFunctors::always) :
+ DefaultDesignerAction(new ActionTemplate(description, selectionAction)),
+ m_category(category),
+ m_priority(priority),
+ m_enabled(enabled),
+ m_visibility(visibility)
+ {}
+
+ bool isVisible(const SelectionContext &selectionState) const { return m_visibility(selectionState); }
+ bool isEnabled(const SelectionContext &selectionState) const { return m_enabled(selectionState); }
+ QString category() const { return m_category; }
+ QString menuId() const { return QString(); }
+ int priority() const { return m_priority; }
+ Type type() const { return Action; }
+
+private:
+ const QString m_category;
+ const int m_priority;
+ const SelectionContextFunction m_enabled;
+ const SelectionContextFunction m_visibility;
+};
+
+
+} //QmlDesigner
+
+#endif // MODELNODECONTEXTMENU_HELPER_H
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
new file mode 100644
index 0000000000..dcf1fb4884
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.cpp
@@ -0,0 +1,606 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "modelnodeoperations.h"
+#include "modelnodecontextmenu_helper.h"
+
+#include <cmath>
+#include <QApplication>
+#include <QMessageBox>
+#include <coreplugin/editormanager/editormanager.h>
+#include <nodeabstractproperty.h>
+#include <nodelistproperty.h>
+#include <nodemetainfo.h>
+#include <modelnode.h>
+#include <qmlitemnode.h>
+#include <variantproperty.h>
+#include <bindingproperty.h>
+#include <nodeproperty.h>
+#include <rewritingexception.h>
+#include <rewritertransaction.h>
+#include <designmodewidget.h>
+#include <qmlanchors.h>
+
+namespace QmlDesigner {
+
+const QString auxDataString = QLatin1String("anchors_");
+
+static inline bool isItem(const ModelNode &node)
+{
+ return node.isValid() && node.metaInfo().isValid() && node.metaInfo().isSubclassOf("QtQuick.Item", -1, -1);
+}
+
+static inline QList<QmlItemNode> siblingsForNode(const QmlItemNode &itemNode)
+{
+ QList<QmlItemNode> siblingList;
+
+ if (itemNode.isValid() && itemNode.modelNode().parentProperty().isValid()) {
+ QList<ModelNode> modelNodes = itemNode.modelNode().parentProperty().parentModelNode().allDirectSubModelNodes();
+ foreach (const ModelNode &node, modelNodes) {
+ QmlItemNode childItemNode = node;
+ if (childItemNode.isValid())
+ siblingList.append(childItemNode);
+ }
+ }
+
+ return siblingList;
+}
+
+static signed int getMaxZValue(const QList<QmlItemNode> &siblingList)
+{
+ signed int maximum = INT_MIN;
+ foreach (const QmlItemNode &node, siblingList) {
+ signed int z = node.instanceValue("z").toInt();
+ if (z > maximum)
+ maximum = z;
+ }
+ return maximum;
+}
+
+static signed int getMinZValue(const QList<QmlItemNode> &siblingList)
+{
+ signed int minimum = INT_MAX;
+ foreach (const QmlItemNode &node, siblingList) {
+ signed int z = node.instanceValue("z").toInt();
+ if (z < minimum)
+ minimum = z;
+ }
+ return minimum;
+}
+
+static inline void getWidthHeight(const ModelNode &node, int &width, int &height)
+{
+ QmlItemNode itemNode(node);
+ if (itemNode.isValid()) {
+ width = itemNode.instanceValue("width").toInt();
+ height = itemNode.instanceValue("height").toInt();
+ }
+}
+
+static inline bool modelNodesHaveProperty(const QList<ModelNode> &modelNodeList, const QString &propertyName)
+{
+ foreach (const ModelNode &modelNode, modelNodeList)
+ if (modelNode.hasProperty(propertyName))
+ return true;
+
+ return false;
+}
+
+
+namespace ModelNodeOperations {
+
+void goIntoComponent(const ModelNode &modelNode)
+{
+ ComponentUtils::goIntoComponent(modelNode);
+}
+
+void select(const SelectionContext &selectionState)
+{
+ if (selectionState.view())
+ selectionState.view()->setSelectedModelNodes(QList<ModelNode>() << selectionState.targetNode());
+}
+
+void deSelect(const SelectionContext &selectionState)
+{
+ if (selectionState.view()) {
+ QList<ModelNode> selectedNodes = selectionState.view()->selectedModelNodes();
+ foreach (const ModelNode &node, selectionState.selectedModelNodes()) {
+ if (selectedNodes.contains(node))
+ selectedNodes.removeAll(node);
+ }
+ selectionState.view()->setSelectedModelNodes(selectedNodes);
+ }
+}
+
+void cut(const SelectionContext &)
+{
+}
+
+
+void copy(const SelectionContext &)
+{
+}
+
+void deleteSelection(const SelectionContext &)
+{
+}
+
+void toFront(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ try {
+ QmlItemNode node = selectionState.selectedModelNodes().first();
+ if (node.isValid()) {
+ signed int maximumZ = getMaxZValue(siblingsForNode(node));
+ maximumZ++;
+ node.setVariantProperty("z", maximumZ);
+ }
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+
+void toBack(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+ try {
+ QmlItemNode node = selectionState.selectedModelNodes().first();
+ if (node.isValid()) {
+ signed int minimumZ = getMinZValue(siblingsForNode(node));
+ minimumZ--;
+ node.setVariantProperty("z", minimumZ);
+ }
+
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void raise(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ try {
+ RewriterTransaction transaction(selectionState.view());
+ foreach (ModelNode modelNode, selectionState.selectedModelNodes()) {
+ QmlItemNode node = modelNode;
+ if (node.isValid()) {
+ signed int z = node.instanceValue("z").toInt();
+ z++;
+ node.setVariantProperty("z", z);
+ }
+ }
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void lower(const SelectionContext &selectionState)
+{
+
+ if (!selectionState.view())
+ return;
+
+ try {
+ RewriterTransaction transaction(selectionState.view());
+ foreach (ModelNode modelNode, selectionState.selectedModelNodes()) {
+ QmlItemNode node = modelNode;
+ if (node.isValid()) {
+ signed int z = node.instanceValue("z").toInt();
+ z--;
+ node.setVariantProperty("z", z);
+ }
+ }
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void paste(const SelectionContext &)
+{
+}
+
+void undo(const SelectionContext &)
+{
+}
+
+void redo(const SelectionContext &)
+{
+}
+
+void setVisible(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ try {
+ selectionState.selectedModelNodes().first().variantProperty("visible") = selectionState.toggled();
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+
+void resetSize(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ try {
+ RewriterTransaction transaction(selectionState.view());
+ foreach (ModelNode node, selectionState.selectedModelNodes()) {
+ node.removeProperty("width");
+ node.removeProperty("height");
+ }
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void resetPosition(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ try {
+ RewriterTransaction transaction(selectionState.view());
+ foreach (ModelNode node, selectionState.selectedModelNodes()) {
+ node.removeProperty("x");
+ node.removeProperty("y");
+ }
+ } catch (RewritingException &e) { //better save then sorry
+ QMessageBox::warning(0, "Error", e.description());
+ }
+}
+
+void goIntoComponent(const SelectionContext &selectionState)
+{
+ goIntoComponent(selectionState.currentSingleSelectedNode());
+}
+
+void setId(const SelectionContext &)
+{
+}
+
+void resetZ(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ RewriterTransaction transaction(selectionState.view());
+ foreach (ModelNode node, selectionState.selectedModelNodes()) {
+ node.removeProperty("z");
+ }
+}
+
+static inline void backupPropertyAndRemove(ModelNode node, const QString &propertyName)
+{
+ if (node.hasVariantProperty(propertyName)) {
+ node.setAuxiliaryData(auxDataString + propertyName, node.variantProperty(propertyName).value());
+ node.removeProperty(propertyName);
+
+ }
+ if (node.hasBindingProperty(propertyName)) {
+ node.setAuxiliaryData(auxDataString + propertyName, QmlItemNode(node).instanceValue(propertyName));
+ node.removeProperty(propertyName);
+ }
+}
+
+
+static inline void restoreProperty(ModelNode node, const QString &propertyName)
+{
+ if (node.hasAuxiliaryData(auxDataString + propertyName))
+ node.variantProperty(propertyName) = node.auxiliaryData(auxDataString + propertyName);
+}
+
+void anchorsFill(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ RewriterTransaction transaction(selectionState.view());
+
+ ModelNode modelNode = selectionState.currentSingleSelectedNode();
+
+ QmlItemNode node = modelNode;
+ if (node.isValid()) {
+ node.anchors().fill();
+ backupPropertyAndRemove(modelNode, QLatin1String("x"));
+ backupPropertyAndRemove(modelNode, QLatin1String("y"));
+ backupPropertyAndRemove(modelNode, QLatin1String("width"));
+ backupPropertyAndRemove(modelNode, QLatin1String("height"));
+ }
+}
+
+void anchorsReset(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ RewriterTransaction transaction(selectionState.view());
+
+ ModelNode modelNode = selectionState.currentSingleSelectedNode();
+
+ QmlItemNode node = modelNode;
+ if (node.isValid()) {
+ node.anchors().removeAnchors();
+ node.anchors().removeMargins();
+ restoreProperty(node, "x");
+ restoreProperty(node, "y");
+ restoreProperty(node, "width");
+ restoreProperty(node, "height");
+ }
+}
+
+static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent)
+{
+
+ if (parent.isValid() && node.isValid()) {
+ NodeAbstractProperty parentProperty;
+
+ if (parent.hasDefaultProperty())
+ parentProperty = parent.nodeAbstractProperty(parent.defaultProperty());
+ else
+ parentProperty = parent.nodeAbstractProperty(QLatin1String("data"));
+
+ parentProperty.reparentHere(node);
+ }
+}
+
+
+bool compareByX(const ModelNode &node1, const ModelNode &node2)
+{
+ QmlItemNode itemNode1 = QmlItemNode(node1);
+ QmlItemNode itemNode2 = QmlItemNode(node2);
+ if (itemNode1.isValid() && itemNode2.isValid())
+ return itemNode1.instancePosition().x() < itemNode2.instancePosition().x();
+ return false;
+}
+
+bool compareByY(const ModelNode &node1, const ModelNode &node2)
+{
+ QmlItemNode itemNode1 = QmlItemNode(node1);
+ QmlItemNode itemNode2 = QmlItemNode(node2);
+ if (itemNode1.isValid() && itemNode2.isValid())
+ return itemNode1.instancePosition().y() < itemNode2.instancePosition().y();
+ return false;
+}
+
+bool compareByGrid(const ModelNode &node1, const ModelNode &node2)
+{
+ QmlItemNode itemNode1 = QmlItemNode(node1);
+ QmlItemNode itemNode2 = QmlItemNode(node2);
+ if (itemNode1.isValid() && itemNode2.isValid()) {
+ if ((itemNode1.instancePosition().y() + itemNode1.instanceSize().height()) < itemNode2.instancePosition().y())
+ return true;
+ if ((itemNode2.instancePosition().y() + itemNode2.instanceSize().height()) < itemNode1.instancePosition().y())
+ return false; //first sort y (rows)
+ return itemNode1.instancePosition().x() < itemNode2.instancePosition().x();
+ }
+ return false;
+}
+
+static inline QPoint getUpperLeftPosition(const QList<ModelNode> &modelNodeList)
+{
+ QPoint p(INT_MAX, INT_MAX);
+ foreach (ModelNode modelNode, modelNodeList) {
+ QmlItemNode itemNode = QmlItemNode(modelNode);
+ if (itemNode.isValid()) {
+ if (itemNode.instancePosition().x() < p.x())
+ p.setX(itemNode.instancePosition().x());
+ if (itemNode.instancePosition().y() < p.y())
+ p.setY(itemNode.instancePosition().y());
+ }
+ }
+ return p;
+}
+
+void layoutRow(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ NodeMetaInfo rowMetaInfo = selectionState.view()->model()->metaInfo(QLatin1String("QtQuick.Row"));
+
+ if (!rowMetaInfo.isValid())
+ return;
+
+ QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
+
+ ModelNode row;
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
+ if (!parent.isValid())
+ return;
+
+ qDebug() << parent.modelNode().majorQtQuickVersion();
+
+ row = selectionState.view()->createModelNode(QLatin1String("QtQuick.Row"), rowMetaInfo.majorVersion(), rowMetaInfo.minorVersion());
+
+ reparentTo(row, parent);
+ }
+
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QPoint pos = getUpperLeftPosition(modelNodeList);
+ row.variantProperty(QLatin1String("x")) = pos.x();
+ row.variantProperty(QLatin1String("y")) = pos.y();
+
+ QList<ModelNode> sortedList = modelNodeList;
+ qSort(sortedList.begin(), sortedList.end(), compareByX);
+
+ foreach (ModelNode modelNode, sortedList) {
+ reparentTo(modelNode, row);
+ modelNode.removeProperty(QLatin1String("x"));
+ modelNode.removeProperty(QLatin1String("y"));
+ }
+ }
+}
+
+void layoutColumn(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ NodeMetaInfo columnMetaInfo = selectionState.view()->model()->metaInfo(QLatin1String("QtQuick.Column"));
+
+ if (!columnMetaInfo.isValid())
+ return;
+
+ QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
+
+ ModelNode column;
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
+ if (!parent.isValid())
+ return;
+
+ column = selectionState.view()->createModelNode(QLatin1String("QtQuick.Column"), columnMetaInfo.majorVersion(), columnMetaInfo.minorVersion());
+
+ reparentTo(column, parent);
+ }
+
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QPoint pos = getUpperLeftPosition(modelNodeList);
+ column.variantProperty(QLatin1String("x")) = pos.x();
+ column.variantProperty(QLatin1String("y")) = pos.y();
+
+ QList<ModelNode> sortedList = modelNodeList;
+ qSort(sortedList.begin(), sortedList.end(), compareByY);
+
+ foreach (ModelNode modelNode, sortedList) {
+ reparentTo(modelNode, column);
+ modelNode.removeProperty(QLatin1String("x"));
+ modelNode.removeProperty(QLatin1String("y"));
+ }
+ }
+}
+
+void layoutGrid(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ NodeMetaInfo gridMetaInfo = selectionState.view()->model()->metaInfo(QLatin1String("QtQuick.Grid"));
+
+ if (!gridMetaInfo.isValid())
+ return;
+
+ QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
+
+ ModelNode grid;
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
+ if (!parent.isValid())
+ return;
+
+ grid = selectionState.view()->createModelNode(QLatin1String("QtQuick.Grid"), gridMetaInfo.majorVersion(), gridMetaInfo.minorVersion());
+ grid.variantProperty(QLatin1String("columns")) = int(sqrt(double(modelNodeList.count())));
+
+ reparentTo(grid, parent);
+ }
+
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QPoint pos = getUpperLeftPosition(modelNodeList);
+ grid.variantProperty(QLatin1String("x")) = pos.x();
+ grid.variantProperty(QLatin1String("y")) = pos.y();
+
+ QList<ModelNode> sortedList = modelNodeList;
+ qSort(sortedList.begin(), sortedList.end(), compareByGrid);
+
+ foreach (ModelNode modelNode, sortedList) {
+ reparentTo(modelNode, grid);
+ modelNode.removeProperty(QLatin1String("x"));
+ modelNode.removeProperty(QLatin1String("y"));
+ }
+ }
+}
+
+void layoutFlow(const SelectionContext &selectionState)
+{
+ if (!selectionState.view())
+ return;
+
+ NodeMetaInfo flowMetaInfo = selectionState.view()->model()->metaInfo(QLatin1String("QtQuick.Flow"));
+
+ if (!flowMetaInfo.isValid())
+ return;
+
+ QList<ModelNode> modelNodeList = selectionState.selectedModelNodes();
+
+ ModelNode flow;
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QmlItemNode parent = QmlItemNode(modelNodeList.first()).instanceParent().toQmlItemNode();
+ if (!parent.isValid())
+ return;
+
+ flow = selectionState.view()->createModelNode(QLatin1String("QtQuick.Flow"), flowMetaInfo.majorVersion(), flowMetaInfo.minorVersion());
+
+ reparentTo(flow, parent);
+ }
+
+ {
+ RewriterTransaction transaction(selectionState.view());
+
+ QPoint pos = getUpperLeftPosition(modelNodeList);
+ flow.variantProperty(QLatin1String("x")) = pos.x();
+ flow.variantProperty(QLatin1String("y")) = pos.y();
+
+ QList<ModelNode> sortedList = modelNodeList;
+ qSort(sortedList.begin(), sortedList.end(), compareByGrid);
+
+ foreach (ModelNode modelNode, sortedList) {
+ reparentTo(modelNode, flow);
+ modelNode.removeProperty(QLatin1String("x"));
+ modelNode.removeProperty(QLatin1String("y"));
+ }
+ }
+}
+
+} // namespace Mode
+
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.h b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.h
new file mode 100644
index 0000000000..2cc8173905
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/modelnodeoperations.h
@@ -0,0 +1,70 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef MODELNODEOPERATIONS_H
+#define MODELNODEOPERATIONS_H
+
+#include "selectioncontext.h"
+
+namespace QmlDesigner {
+namespace ModelNodeOperations {
+
+void goIntoComponent(const ModelNode &modelNode);
+
+typedef void (*SelectionAction)(const SelectionContext &);
+
+void select(const SelectionContext &selectionState);
+void deSelect(const SelectionContext &selectionState);
+void cut(const SelectionContext &selectionState);
+void copy(const SelectionContext &selectionState);
+void deleteSelection(const SelectionContext &selectionState);
+void toFront(const SelectionContext &selectionState);
+void toBack(const SelectionContext &selectionState);
+void raise(const SelectionContext &selectionState);
+void lower(const SelectionContext &selectionState);
+void paste(const SelectionContext &selectionState);
+void undo(const SelectionContext &selectionState);
+void redo(const SelectionContext &selectionState);
+void setVisible(const SelectionContext &selectionState);
+void resetSize(const SelectionContext &selectionState);
+void resetPosition(const SelectionContext &selectionState);
+void goIntoComponent(const SelectionContext &selectionState);
+void setId(const SelectionContext &selectionState);
+void resetZ(const SelectionContext &selectionState);
+void anchorsFill(const SelectionContext &selectionState);
+void anchorsReset(const SelectionContext &selectionState);
+void layoutRow(const SelectionContext &selectionState);
+void layoutColumn(const SelectionContext &selectionState);
+void layoutGrid(const SelectionContext &selectionState);
+void layoutFlow(const SelectionContext &selectionState);
+
+} // namespace ModelNodeOperationso
+} //QmlDesigner
+
+#endif //MODELNODEOPERATIONS_H
diff --git a/src/plugins/qmldesigner/meegoplugin/meegoplugin.cpp b/src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp
index cd17355476..7d9c8e9d27 100644
--- a/src/plugins/qmldesigner/meegoplugin/meegoplugin.cpp
+++ b/src/plugins/qmldesigner/components/componentcore/selectioncontext.cpp
@@ -27,30 +27,33 @@
**
****************************************************************************/
-#include "meegoplugin.h"
-#include <widgetplugin_helper.h>
-#include <QtPlugin>
+#include "selectioncontext.h"
namespace QmlDesigner {
-MeegoPlugin::MeegoPlugin()
+SelectionContext::SelectionContext() :
+ m_view(0),
+ m_isInBaseState(false),
+ m_toggled(false)
{
-}
-QString MeegoPlugin::pluginName() const
-{
- return ("MeegoPlugin");
}
-QString MeegoPlugin::metaInfo() const
+SelectionContext::SelectionContext(QmlModelView *view) :
+ m_view(view),
+ m_isInBaseState(view->currentState().isBaseState()),
+ m_toggled(false)
{
- return QString(":/meegoplugin/meego.metainfo");
+ if (m_view && m_view->model())
+ m_selectedModelNodes = view->selectedModelNodes();
+
+ if (m_selectedModelNodes.count()== 1) {
+ m_singleSelected = true;
+ m_currentSingleSelectedNode = m_selectedModelNodes.first();
+ } else {
+ m_singleSelected = false;
+ }
}
-}
-
-#if QT_VERSION < 0x050000
-Q_EXPORT_PLUGIN(QmlDesigner::MeegoPlugin)
-#endif
-
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/components/componentcore/selectioncontext.h b/src/plugins/qmldesigner/components/componentcore/selectioncontext.h
new file mode 100644
index 0000000000..f49417d792
--- /dev/null
+++ b/src/plugins/qmldesigner/components/componentcore/selectioncontext.h
@@ -0,0 +1,99 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <qmlmodelview.h>
+
+#ifndef SELECTIONCONTEXT_H
+#define SELECTIONCONTEXT_H
+
+namespace QmlDesigner {
+
+class SelectionContext {
+
+public:
+ SelectionContext();
+ SelectionContext(QmlModelView *view);
+
+ void setTargetNode(const ModelNode &modelNode)
+ { m_targetNode = modelNode; }
+
+ bool singleSelected() const
+ { return m_singleSelected; }
+
+ bool isInBaseState() const
+ { return m_isInBaseState; }
+
+ ModelNode targetNode() const
+ { return m_targetNode; }
+
+ ModelNode currentSingleSelectedNode() const
+ { return m_currentSingleSelectedNode; }
+
+ QList<ModelNode> selectedModelNodes() const
+ { return m_selectedModelNodes; }
+
+ QmlModelView *view() const
+ { return m_view; }
+
+ void setShowSelectionTools(bool show)
+ { m_showSelectionTools = show; }
+
+ bool showSelectionTools() const
+ { return m_showSelectionTools; }
+
+ QPoint scenePos() const
+ { return m_scenePos; }
+
+ void setScenePos(const QPoint &pos)
+ { m_scenePos = pos; }
+
+ void setToggled(bool b)
+ { m_toggled = b; }
+
+ bool toggled() const
+ { return m_toggled; }
+
+ bool isValid() const
+ { return view() && view()->model() && view()->nodeInstanceView(); }
+
+private:
+ QmlModelView *m_view;
+ bool m_singleSelected;
+ ModelNode m_currentSingleSelectedNode;
+ ModelNode m_targetNode;
+ bool m_isInBaseState;
+ QList<ModelNode> m_selectedModelNodes;
+ bool m_showSelectionTools;
+ QPoint m_scenePos;
+ bool m_toggled;
+};
+
+} //QmlDesigner
+
+#endif //SELECTIONCONTEXT_H
diff --git a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp
index a2fbb5af42..e182b5db9c 100644
--- a/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/abstractformeditortool.cpp
@@ -31,6 +31,8 @@
#include "formeditorview.h"
#include "formeditorview.h"
+#include <modelnodecontextmenu.h>
+
#include <coreplugin/editormanager/editormanager.h>
#include <QDebug>
@@ -191,9 +193,8 @@ static inline bool checkIfNodeIsAView(const ModelNode &node)
void AbstractFormEditorTool::mousePressEvent(const QList<QGraphicsItem*> & /*itemList*/, QGraphicsSceneMouseEvent *event)
{
- if (event->button() == Qt::RightButton) {
+ if (event->button() == Qt::RightButton)
event->accept();
- }
}
void AbstractFormEditorTool::mouseReleaseEvent(const QList<QGraphicsItem*> & /*itemList*/, QGraphicsSceneMouseEvent *event)
@@ -210,7 +211,7 @@ void AbstractFormEditorTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &
void AbstractFormEditorTool::showContextMenu(QGraphicsSceneMouseEvent *event)
{
- view()->showContextMenu(event->screenPos(), event->scenePos().toPoint(), true);
+ ModelNodeContextMenu::showContextMenu(view(), event->screenPos(), event->scenePos().toPoint(), true);
}
void AbstractFormEditorTool::clear()
diff --git a/src/plugins/qmldesigner/components/formeditor/dragtool.cpp b/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
index 9c867e0e80..1ef585f4df 100644
--- a/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/dragtool.cpp
@@ -161,7 +161,7 @@ void DragTool::createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, QmlIt
Q_ASSERT(m_dragNode.modelNode().isValid());
QList<QmlItemNode> nodeList;
- nodeList.append(m_dragNode);
+ nodeList.append(m_dragNode);
m_selectionIndicator.setItems(scene()->itemsForQmlItemNodes(nodeList));
}
@@ -204,6 +204,23 @@ FormEditorItem* DragTool::calculateContainer(const QPointF &point, FormEditorIte
return 0;
}
+ QList<Import> DragTool::missingImportList(const ItemLibraryEntry &itemLibraryEntry)
+{
+ QList<Import> importToBeAddedList;
+
+ if (!itemLibraryEntry.requiredImport().isEmpty()) {
+ const QString newImportUrl = itemLibraryEntry.requiredImport();
+ const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
+ Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
+
+ if (itemLibraryEntry.majorVersion() == -1 && itemLibraryEntry.minorVersion() == -1)
+ newImport = Import::createFileImport(newImportUrl, QString());
+ else
+ newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
+ }
+ return importToBeAddedList;
+}
+
void DragTool::formEditorItemsChanged(const QList<FormEditorItem*> & itemList)
{
@@ -296,17 +313,9 @@ void DragTool::dragEnterEvent(QGraphicsSceneDragDropEvent * event)
view()->widget()->setFocus();
m_Aborted = false;
Q_ASSERT(!event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo").isEmpty());
- ItemLibraryEntry itemLibraryEntry = itemLibraryEntryFromData(event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo"));
- if (!itemLibraryEntry.requiredImport().isEmpty()) {
- const QString newImportUrl = itemLibraryEntry.requiredImport();
- const QString newImportVersion = QString("%1.%2").arg(QString::number(itemLibraryEntry.majorVersion()), QString::number(itemLibraryEntry.minorVersion()));
- Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
- if (!view()->model()->hasImport(newImport, true, true)) {
- importToBeAddedList.append(newImport);
- }
-
- }
+ importToBeAddedList = missingImportList(
+ itemLibraryEntryFromData(event->mimeData()->data("application/vnd.bauhaus.itemlibraryinfo")));
}
view()->model()->changeImports(importToBeAddedList, QList<Import>());
diff --git a/src/plugins/qmldesigner/components/formeditor/dragtool.h b/src/plugins/qmldesigner/components/formeditor/dragtool.h
index 01322fbbc4..16a1a6bf3d 100644
--- a/src/plugins/qmldesigner/components/formeditor/dragtool.h
+++ b/src/plugins/qmldesigner/components/formeditor/dragtool.h
@@ -114,6 +114,7 @@ private:
void createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, QmlItemNode parentNode, QPointF scenePos);
void createQmlItemNodeFromImage(const QString &imageName, QmlItemNode parentNode, QPointF scenePos);
FormEditorItem* calculateContainer(const QPointF &point, FormEditorItem * currentItem = 0);
+ QList<Import> missingImportList(const ItemLibraryEntry &itemLibraryEntry);
void begin(QPointF scenePos);
void end(QPointF scenePos);
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditor.pri b/src/plugins/qmldesigner/components/formeditor/formeditor.pri
index f353e868ee..f2ca8013c9 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditor.pri
+++ b/src/plugins/qmldesigner/components/formeditor/formeditor.pri
@@ -32,7 +32,8 @@ SOURCES += formeditoritem.cpp \
zoomaction.cpp \
formeditorgraphicsview.cpp \
numberseriesaction.cpp \
- lineeditaction.cpp
+ lineeditaction.cpp \
+ formeditorcrumblebar.cpp
HEADERS += formeditorscene.h \
formeditorwidget.h \
formeditoritem.h \
@@ -63,5 +64,6 @@ HEADERS += formeditorscene.h \
zoomaction.h \
formeditorgraphicsview.h \
numberseriesaction.h \
- lineeditaction.h
+ lineeditaction.h \
+ formeditorcrumblebar.h
RESOURCES += formeditor.qrc
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp
new file mode 100644
index 0000000000..8e009b6aae
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.cpp
@@ -0,0 +1,123 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "formeditorcrumblebar.h"
+
+#include "qmldesignerplugin.h"
+
+#include <QVariant>
+#include <QtDebug>
+
+namespace QmlDesigner {
+
+FormEditorCrumbleBar::FormEditorCrumbleBar(QObject *parent) :
+ QObject(parent),
+ m_isInternalCalled(false),
+ m_crumblePath(new Utils::CrumblePath)
+{
+ connect(m_crumblePath,
+ SIGNAL(elementClicked(QVariant)),
+ this,
+ SLOT(onCrumblePathElementClicked(QVariant)));
+}
+
+void FormEditorCrumbleBar::pushFile(const QString &fileName)
+{
+ if (m_isInternalCalled == false)
+ crumblePath()->clear();
+
+ CrumbleBarInfo crumbleBarInfo;
+ crumbleBarInfo.fileName = fileName;
+
+ crumblePath()->pushElement(fileName.split("/").last(), QVariant::fromValue(crumbleBarInfo));
+
+ m_isInternalCalled = false;
+}
+
+static DesignDocument *currentDesignDocument()
+{
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
+}
+
+void FormEditorCrumbleBar::pushInFileComponent(const QString &componentId)
+{
+ CrumbleBarInfo crumbleBarInfo;
+ crumbleBarInfo.componentId = componentId;
+ crumbleBarInfo.fileName = currentDesignDocument()->textEditor()->document()->fileName();
+
+ CrumbleBarInfo lastElementCrumbleBarInfo = crumblePath()->dataForLastIndex().value<CrumbleBarInfo>();
+
+ if (!lastElementCrumbleBarInfo.componentId.isEmpty())
+ crumblePath()->popElement();
+
+ crumblePath()->pushElement(componentId, QVariant::fromValue(crumbleBarInfo));
+}
+
+void FormEditorCrumbleBar::nextFileIsCalledInternally()
+{
+ m_isInternalCalled = true;
+}
+
+Utils::CrumblePath *FormEditorCrumbleBar::crumblePath()
+{
+ return m_crumblePath;
+}
+
+void FormEditorCrumbleBar::onCrumblePathElementClicked(const QVariant &data)
+{
+ CrumbleBarInfo crumbleBarInfo = data.value<CrumbleBarInfo>();
+
+ if (crumbleBarInfo == crumblePath()->dataForLastIndex().value<CrumbleBarInfo>())
+ return;
+
+ while (crumbleBarInfo != crumblePath()->dataForLastIndex().value<CrumbleBarInfo>())
+ crumblePath()->popElement();
+
+ if (!crumbleBarInfo.componentId.isEmpty())
+ crumblePath()->popElement();
+
+ crumblePath()->popElement();
+
+ m_isInternalCalled = true;
+ Core::EditorManager::openEditor(crumbleBarInfo.fileName);
+ if (!crumbleBarInfo.componentId.isEmpty())
+ currentDesignDocument()->changeToSubComponent(currentDesignDocument()->rewriterView()->modelNodeForId(crumbleBarInfo.componentId));
+}
+
+bool operator ==(const CrumbleBarInfo &first, const CrumbleBarInfo &second)
+{
+ return first.fileName == second.fileName && first.componentId == second.componentId;
+}
+
+bool operator !=(const CrumbleBarInfo &first, const CrumbleBarInfo &second)
+{
+ return first.fileName != second.fileName || first.componentId != second.componentId;
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h b/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h
new file mode 100644
index 0000000000..18069a0ca2
--- /dev/null
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorcrumblebar.h
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLDESIGNER_FORMEDITORCRUMBLEBAR_H
+#define QMLDESIGNER_FORMEDITORCRUMBLEBAR_H
+
+#include <QObject>
+#include <utils/crumblepath.h>
+
+namespace QmlDesigner {
+
+
+
+class FormEditorCrumbleBar : public QObject
+{
+ Q_OBJECT
+public:
+ explicit FormEditorCrumbleBar(QObject *parent = 0);
+
+ void pushFile(const QString &fileName);
+ void pushInFileComponent(const QString &componentId);
+
+ void nextFileIsCalledInternally();
+
+ Utils::CrumblePath *crumblePath();
+
+private slots:
+ void onCrumblePathElementClicked(const QVariant &data);
+
+private:
+ bool m_isInternalCalled;
+ Utils::CrumblePath *m_crumblePath;
+};
+
+class CrumbleBarInfo {
+public:
+ QString fileName;
+ QString componentId;
+};
+
+bool operator ==(const CrumbleBarInfo &first, const CrumbleBarInfo &second);
+bool operator !=(const CrumbleBarInfo &first, const CrumbleBarInfo &second);
+} // namespace QmlDesigner
+
+Q_DECLARE_METATYPE(QmlDesigner::CrumbleBarInfo)
+
+#endif // QMLDESIGNER_FORMEDITORCRUMBLEBAR_H
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorgraphicsview.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorgraphicsview.cpp
index 18c367fcfd..c34b1d9eaa 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorgraphicsview.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorgraphicsview.cpp
@@ -70,11 +70,10 @@ FormEditorGraphicsView::FormEditorGraphicsView(QWidget *parent) :
void FormEditorGraphicsView::wheelEvent(QWheelEvent *event)
{
- if (event->modifiers().testFlag(Qt::ControlModifier)) {
+ if (event->modifiers().testFlag(Qt::ControlModifier))
event->ignore();
- } else {
+ else
QGraphicsView::wheelEvent(event);
- }
}
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp b/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp
index f063b87e5b..aa1c0a533a 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditoritem.cpp
@@ -317,12 +317,15 @@ void FormEditorItem::paintPlaceHolderForInvisbleItem(QPainter *painter) const
void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
+ if (!painter->isActive())
+ return;
+
if (!qmlItemNode().isValid())
return;
painter->save();
- if (qmlItemNode().instanceIsRenderPixmapNull()) {
+ if (qmlItemNode().instanceIsRenderPixmapNull() || !isContentVisible()) {
if (scene()->showBoundingRects() && boundingRect().width() > 15 && boundingRect().height() > 15)
paintPlaceHolderForInvisbleItem(painter);
} else {
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorscene.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorscene.cpp
index 064a83c732..4d0c919fe0 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorscene.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorscene.cpp
@@ -65,7 +65,6 @@ FormEditorScene::FormEditorScene(FormEditorWidget *view, FormEditorView *editorV
setupScene();
view->setScene(this);
setItemIndexMethod(QGraphicsScene::NoIndex);
- setSceneRect(-canvasWidth()/2., -canvasHeight()/2., canvasWidth(), canvasHeight());
}
FormEditorScene::~FormEditorScene()
@@ -86,7 +85,7 @@ void FormEditorScene::setupScene()
void FormEditorScene::resetScene()
{
- foreach(QGraphicsItem *item, m_manipulatorLayerItem->childItems())
+ foreach (QGraphicsItem *item, m_manipulatorLayerItem->childItems())
removeItem(item);
setSceneRect(-canvasWidth()/2., -canvasHeight()/2., canvasWidth(), canvasHeight());
@@ -100,13 +99,13 @@ FormEditorItem* FormEditorScene::itemForQmlItemNode(const QmlItemNode &qmlItemNo
double FormEditorScene::canvasWidth() const
{
- DesignerSettings settings = Internal::BauhausPlugin::pluginInstance()->settings();
+ DesignerSettings settings = QmlDesignerPlugin::instance()->settings();
return settings.canvasWidth;
}
double FormEditorScene::canvasHeight() const
{
- DesignerSettings settings = Internal::BauhausPlugin::pluginInstance()->settings();
+ DesignerSettings settings = QmlDesignerPlugin::instance()->settings();
return settings.canvasHeight;
}
@@ -217,6 +216,7 @@ FormEditorItem *FormEditorScene::addFormEditorItem(const QmlItemNode &qmlItemNod
m_qmlItemNodeItemHash.insert(qmlItemNode, formEditorItem);
if (qmlItemNode.isRootNode()) {
+ setSceneRect(-canvasWidth()/2., -canvasHeight()/2., canvasWidth(), canvasHeight());
formLayerItem()->update();
manipulatorLayerItem()->update();
}
@@ -264,9 +264,8 @@ QList<QGraphicsItem *> FormEditorScene::removeLayerItems(const QList<QGraphicsIt
void FormEditorScene::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
- if (editorView() && editorView()->model()) {
+ if (editorView() && editorView()->model())
currentTool()->mousePressEvent(removeLayerItems(items(event->scenePos())), event);
- }
}
static QTime staticTimer()
@@ -311,16 +310,14 @@ void FormEditorScene::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
void FormEditorScene::keyPressEvent(QKeyEvent *keyEvent)
{
- if (editorView() && editorView()->model()) {
+ if (editorView() && editorView()->model())
currentTool()->keyPressEvent(keyEvent);
- }
}
void FormEditorScene::keyReleaseEvent(QKeyEvent *keyEvent)
{
- if (editorView() && editorView()->model()) {
+ if (editorView() && editorView()->model())
currentTool()->keyReleaseEvent(keyEvent);
- }
}
FormEditorView *FormEditorScene::editorView() const
@@ -340,7 +337,7 @@ LayerItem* FormEditorScene::formLayerItem() const
bool FormEditorScene::event(QEvent * event)
{
- switch(event->type())
+ switch (event->type())
{
case QEvent::GraphicsSceneHoverEnter :
hoverEnterEvent(static_cast<QGraphicsSceneHoverEvent *>(event));
@@ -401,9 +398,8 @@ void FormEditorScene::clearFormEditorItems()
QList<QGraphicsItem*> itemList(items());
foreach (QGraphicsItem *item, itemList) {
- if (qgraphicsitem_cast<FormEditorItem* >(item)) {
+ if (qgraphicsitem_cast<FormEditorItem* >(item))
item->setParentItem(0);
- }
}
foreach (QGraphicsItem *item, itemList) {
@@ -414,7 +410,7 @@ void FormEditorScene::clearFormEditorItems()
void FormEditorScene::highlightBoundingRect(FormEditorItem *highlighItem)
{
- foreach(FormEditorItem *item, allFormEditorItems()) {
+ foreach (FormEditorItem *item, allFormEditorItems()) {
if (item == highlighItem)
item->setHighlightBoundingRect(true);
else
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp
index 5a9eeb034e..23c6db6965 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorview.cpp
@@ -68,9 +68,9 @@ FormEditorView::FormEditorView(QObject *parent)
m_currentTool(m_selectionTool),
m_transactionCounter(0)
{
- connect(widget()->zoomAction(), SIGNAL(zoomLevelChanged(double)), SLOT(updateGraphicsIndicators()));
- connect(widget()->showBoundingRectAction(), SIGNAL(toggled(bool)), scene(), SLOT(setShowBoundingRects(bool)));
- connect(widget()->selectOnlyContentItemsAction(), SIGNAL(toggled(bool)), this, SLOT(setSelectOnlyContentItemsAction(bool)));
+ connect(formEditorWidget()->zoomAction(), SIGNAL(zoomLevelChanged(double)), SLOT(updateGraphicsIndicators()));
+ connect(formEditorWidget()->showBoundingRectAction(), SIGNAL(toggled(bool)), scene(), SLOT(setShowBoundingRects(bool)));
+ connect(formEditorWidget()->selectOnlyContentItemsAction(), SIGNAL(toggled(bool)), this, SLOT(setSelectOnlyContentItemsAction(bool)));
}
@@ -215,12 +215,12 @@ void FormEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
void FormEditorView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& propertyList)
{
- foreach(const AbstractProperty &property, propertyList) {
+ foreach (const AbstractProperty &property, propertyList) {
if (property.isNodeAbstractProperty()) {
NodeAbstractProperty nodeAbstractProperty = property.toNodeAbstractProperty();
QList<FormEditorItem*> removedItemList;
- foreach(const ModelNode &modelNode, nodeAbstractProperty.allSubNodes()) {
+ foreach (const ModelNode &modelNode, nodeAbstractProperty.allSubNodes()) {
QmlItemNode qmlItemNode(modelNode);
if (qmlItemNode.isValid() && m_scene->hasItemForQmlItemNode(qmlItemNode)) {
@@ -267,9 +267,13 @@ void FormEditorView::bindingPropertiesChanged(const QList<BindingProperty>& prop
QmlModelView::bindingPropertiesChanged(propertyList, propertyChange);
}
-FormEditorWidget *FormEditorView::widget() const
+QWidget *FormEditorView::widget()
+{
+ return m_formEditorWidget.data();
+}
+
+FormEditorWidget *FormEditorView::formEditorWidget()
{
- Q_ASSERT(!m_formEditorWidget.isNull());
return m_formEditorWidget.data();
}
@@ -405,7 +409,7 @@ void FormEditorView::changeToTransformTools()
void FormEditorView::nodeSlidedToIndex(const NodeListProperty &listProperty, int /*newIndex*/, int /*oldIndex*/)
{
QList<ModelNode> newOrderModelNodeList = listProperty.toModelNodeList();
- foreach(const ModelNode &node, newOrderModelNodeList) {
+ foreach (const ModelNode &node, newOrderModelNodeList) {
FormEditorItem *item = m_scene->itemForQmlItemNode(QmlItemNode(node));
if (item) {
FormEditorItem *oldParentItem = item->parentItem();
@@ -453,8 +457,8 @@ void FormEditorView::instanceInformationsChange(const QMultiHash<ModelNode, Info
if (qmlItemNode.isValid() && scene()->hasItemForQmlItemNode(qmlItemNode)) {
scene()->synchronizeTransformation(qmlItemNode);
if (qmlItemNode.isRootModelNode() && informationChangeHash.values(node).contains(Size)) {
- widget()->setRootItemRect(qmlItemNode.instanceBoundingRect());
- widget()->centerScene();
+ formEditorWidget()->setRootItemRect(qmlItemNode.instanceBoundingRect());
+ formEditorWidget()->centerScene();
}
itemNodeList.append(scene()->itemForQmlItemNode(qmlItemNode));
@@ -468,9 +472,8 @@ void FormEditorView::instancesRenderImageChanged(const QVector<ModelNode> &nodeL
{
foreach (const ModelNode &node, nodeList) {
QmlItemNode qmlItemNode(node);
- if (qmlItemNode.isValid() && scene()->hasItemForQmlItemNode(qmlItemNode)) {
+ if (qmlItemNode.isValid() && scene()->hasItemForQmlItemNode(qmlItemNode))
scene()->itemForQmlItemNode(qmlItemNode)->update();
- }
}
}
@@ -589,14 +592,6 @@ void FormEditorView::actualStateChanged(const ModelNode &node)
QmlModelState newQmlModelState(node);
}
-Utils::CrumblePath *FormEditorView::crumblePath() const
-{
- if (widget() && widget()->toolBox()) {
- return widget()->toolBox()->crumblePath();
- }
- return 0;
-}
-
void FormEditorView::reset()
{
QTimer::singleShot(200, this, SLOT(delayedReset()));
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorview.h b/src/plugins/qmldesigner/components/formeditor/formeditorview.h
index 4ac49b8c27..b40040efdc 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorview.h
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorview.h
@@ -61,7 +61,7 @@ class FormEditorView : public QmlModelView
Q_OBJECT
public:
- FormEditorView(QObject *parent);
+ FormEditorView(QObject *parent = 0);
~FormEditorView();
// AbstractView
@@ -85,7 +85,8 @@ public:
void propertiesRemoved(const QList<AbstractProperty> &propertyList);
// FormEditorView
- FormEditorWidget *widget() const;
+ QWidget *widget();
+ FormEditorWidget *formEditorWidget();
AbstractFormEditorTool *currentTool() const;
FormEditorScene *scene() const;
@@ -117,8 +118,6 @@ public:
void actualStateChanged(const ModelNode &node);
- Utils::CrumblePath *crumblePath() const;
-
protected:
void reset();
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp
index 76adb2bc7d..37ea74cb53 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.cpp
@@ -65,7 +65,7 @@ FormEditorWidget::FormEditorWidget(FormEditorView *view)
m_toolActionGroup = new QActionGroup(this);
- m_transformToolAction = m_toolActionGroup->addAction("Transform Tool (Press Key Q)");
+ m_transformToolAction = m_toolActionGroup->addAction(tr("Transform Tool (Press Key Q)"));
m_transformToolAction->setShortcut(Qt::Key_Q);
m_transformToolAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
m_transformToolAction->setCheckable(true);
@@ -83,7 +83,7 @@ FormEditorWidget::FormEditorWidget(FormEditorView *view)
m_snappingAction->setChecked(true);
m_snappingAction->setIcon(QPixmap(":/icon/layout/snapping.png"));
- m_snappingAndAnchoringAction = layoutActionGroup->addAction("Toogle Snapping And Anchoring (Press Key R)");
+ m_snappingAndAnchoringAction = layoutActionGroup->addAction(tr("Toogle Snapping And Anchoring (Press Key R)"));
m_snappingAndAnchoringAction->setShortcut(Qt::Key_R);
m_snappingAndAnchoringAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
m_snappingAndAnchoringAction->setCheckable(true);
@@ -130,7 +130,7 @@ FormEditorWidget::FormEditorWidget(FormEditorView *view)
addAction(m_rootHeightAction.data());
upperActions.append(m_rootHeightAction.data());
- m_snappingAndAnchoringAction = layoutActionGroup->addAction("Toogle Snapping And Anchoring (Press Key R)");
+ m_snappingAndAnchoringAction = layoutActionGroup->addAction(tr("Toogle Snapping And Anchoring (Press Key R)"));
m_toolBox = new ToolBox(this);
fillLayout->addWidget(m_toolBox.data());
@@ -171,22 +171,20 @@ void FormEditorWidget::changeRootItemWidth(const QString &widthText)
{
bool canConvert;
int width = widthText.toInt(&canConvert);
- if (canConvert) {
+ if (canConvert)
m_formEditorView->rootModelNode().setAuxiliaryData("width", width);
- } else {
+ else
m_formEditorView->rootModelNode().setAuxiliaryData("width", QVariant());
- }
}
void FormEditorWidget::changeRootItemHeight(const QString &heighText)
{
bool canConvert;
int height = heighText.toInt(&canConvert);
- if (canConvert) {
+ if (canConvert)
m_formEditorView->rootModelNode().setAuxiliaryData("height", height);
- } else {
+ else
m_formEditorView->rootModelNode().setAuxiliaryData("height", QVariant());
- }
}
void FormEditorWidget::resetNodeInstanceView()
@@ -198,11 +196,10 @@ void FormEditorWidget::resetNodeInstanceView()
void FormEditorWidget::wheelEvent(QWheelEvent *event)
{
if (event->modifiers().testFlag(Qt::ControlModifier)) {
- if (event->delta() > 0) {
+ if (event->delta() > 0)
zoomAction()->zoomOut();
- } else {
+ else
zoomAction()->zoomIn();
- }
event->accept();
} else {
@@ -214,16 +211,14 @@ void FormEditorWidget::wheelEvent(QWheelEvent *event)
void FormEditorWidget::updateActions()
{
if (m_formEditorView->model() && m_formEditorView->rootModelNode().isValid()) {
- if (m_formEditorView->rootModelNode().hasAuxiliaryData("width") && m_formEditorView->rootModelNode().auxiliaryData("width").isValid()) {
+ if (m_formEditorView->rootModelNode().hasAuxiliaryData("width") && m_formEditorView->rootModelNode().auxiliaryData("width").isValid())
m_rootWidthAction->setLineEditText(m_formEditorView->rootModelNode().auxiliaryData("width").toString());
- } else {
+ else
m_rootWidthAction->clearLineEditText();
- }
- if (m_formEditorView->rootModelNode().hasAuxiliaryData("height") && m_formEditorView->rootModelNode().auxiliaryData("height").isValid()) {
+ if (m_formEditorView->rootModelNode().hasAuxiliaryData("height") && m_formEditorView->rootModelNode().auxiliaryData("height").isValid())
m_rootHeightAction->setLineEditText(m_formEditorView->rootModelNode().auxiliaryData("height").toString());
- } else {
+ else
m_rootHeightAction->clearLineEditText();
- }
} else {
m_rootWidthAction->clearLineEditText();
m_rootHeightAction->clearLineEditText();
@@ -246,6 +241,11 @@ void FormEditorWidget::setFocus()
m_graphicsView->setFocus(Qt::OtherFocusReason);
}
+FormEditorCrumbleBar *FormEditorWidget::formEditorCrumbleBar() const
+{
+ return toolBox()->formEditorCrumbleBar();
+}
+
ZoomAction *FormEditorWidget::zoomAction() const
{
return m_zoomAction.data();
@@ -300,13 +300,13 @@ ToolBox *FormEditorWidget::toolBox() const
double FormEditorWidget::spacing() const
{
- DesignerSettings settings = Internal::BauhausPlugin::pluginInstance()->settings();
+ DesignerSettings settings = QmlDesignerPlugin::instance()->settings();
return settings.itemSpacing;
}
double FormEditorWidget::margins() const
{
- DesignerSettings settings = Internal::BauhausPlugin::pluginInstance()->settings();
+ DesignerSettings settings = QmlDesignerPlugin::instance()->settings();
return settings.snapMargin;
}
diff --git a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h
index 60b8ee3168..745c8f5acc 100644
--- a/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h
+++ b/src/plugins/qmldesigner/components/formeditor/formeditorwidget.h
@@ -32,6 +32,8 @@
#include <QWidget>
+#include "formeditorcrumblebar.h"
+
QT_BEGIN_NAMESPACE
class QActionGroup;
QT_END_NAMESPACE
@@ -78,6 +80,8 @@ public:
void setFocus();
+ FormEditorCrumbleBar *formEditorCrumbleBar() const;
+
protected:
void wheelEvent(QWheelEvent *event);
QActionGroup *toolActionGroup() const;
diff --git a/src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
index 9bc2c52e19..0836b2054f 100644
--- a/src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/movemanipulator.cpp
@@ -194,7 +194,7 @@ QPointF MoveManipulator::findSnappingOffset(const QHash<FormEditorItem*, QRectF>
QMap<double, double> horizontalOffsetMap;
QHashIterator<FormEditorItem*, QRectF> hashIterator(boundingRectHash);
- while(hashIterator.hasNext()) {
+ while (hashIterator.hasNext()) {
hashIterator.next();
FormEditorItem *formEditorItem = hashIterator.key();
QRectF boundingRect = hashIterator.value();
@@ -241,7 +241,7 @@ QHash<FormEditorItem*, QRectF> MoveManipulator::tanslatedBoundingRects(const QHa
QHash<FormEditorItem*, QRectF> translatedBoundingRectHash;
QHashIterator<FormEditorItem*, QRectF> hashIterator(boundingRectHash);
- while(hashIterator.hasNext()) {
+ while (hashIterator.hasNext()) {
QPointF alignedOffset(offsetVector);
hashIterator.next();
FormEditorItem *formEditorItem = hashIterator.key();
@@ -300,29 +300,23 @@ void MoveManipulator::update(const QPointF& updatePoint, Snapping useSnapping, S
if (stateToBeManipulated == UseActualState) {
QmlAnchors anchors(item->qmlItemNode().anchors());
- if (anchors.instanceHasAnchor(AnchorLine::Top)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Top))
anchors.setMargin(AnchorLine::Top, m_beginTopMarginHash.value(item) + offsetVector.y());
- }
- if (anchors.instanceHasAnchor(AnchorLine::Left)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Left))
anchors.setMargin(AnchorLine::Left, m_beginLeftMarginHash.value(item) + offsetVector.x());
- }
- if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Bottom))
anchors.setMargin(AnchorLine::Bottom, m_beginBottomMarginHash.value(item) - offsetVector.y());
- }
- if (anchors.instanceHasAnchor(AnchorLine::Right)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Right))
anchors.setMargin(AnchorLine::Right, m_beginRightMarginHash.value(item) - offsetVector.x());
- }
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
anchors.setMargin(AnchorLine::HorizontalCenter, m_beginHorizontalCenterHash.value(item) + offsetVector.x());
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
anchors.setMargin(AnchorLine::VerticalCenter, m_beginVerticalCenterHash.value(item) + offsetVector.y());
- }
setPosition(item->qmlItemNode(), positionInContainerSpace);
} else {
@@ -362,10 +356,10 @@ void MoveManipulator::reparentTo(FormEditorItem *newParent)
if (!itemsCanReparented())
return;
- if (!newParent->qmlItemNode().modelNode().metaInfo().isSubclassOf("<cpp>.QDeclarativeBasePositioner", -1, -1)
+ if (!newParent->qmlItemNode().modelNode().metaInfo().isPositioner()
&& newParent->qmlItemNode().modelNode().hasParentProperty()) {
ModelNode grandParent = newParent->qmlItemNode().modelNode().parentProperty().parentModelNode();
- if (grandParent.metaInfo().isSubclassOf("<cpp>.QDeclarativeBasePositioner", -1, -1))
+ if (grandParent.metaInfo().isPositioner())
newParent = m_view.data()->scene()->itemForQmlItemNode(QmlItemNode(grandParent));
}
@@ -376,11 +370,10 @@ void MoveManipulator::reparentTo(FormEditorItem *newParent)
QmlItemNode parent(newParent->qmlItemNode());
if (parent.isValid()) {
- if (parent.hasDefaultProperty()) {
+ if (parent.hasDefaultProperty())
parentProperty = parent.nodeAbstractProperty(parent.defaultProperty());
- } else {
+ else
parentProperty = parent.nodeAbstractProperty("data");
- }
foreach (FormEditorItem* item, m_itemList) {
if (!item || !item->qmlItemNode().isValid())
@@ -415,29 +408,23 @@ void MoveManipulator::moveBy(double deltaX, double deltaY)
QmlAnchors anchors(item->qmlItemNode().anchors());
- if (anchors.instanceHasAnchor(AnchorLine::Top)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Top))
anchors.setMargin(AnchorLine::Top, anchors.instanceMargin(AnchorLine::Top) + deltaY);
- }
- if (anchors.instanceHasAnchor(AnchorLine::Left)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Left))
anchors.setMargin(AnchorLine::Left, anchors.instanceMargin(AnchorLine::Left) + deltaX);
- }
- if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Bottom))
anchors.setMargin(AnchorLine::Bottom, anchors.instanceMargin(AnchorLine::Bottom) - deltaY);
- }
- if (anchors.instanceHasAnchor(AnchorLine::Right)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Right))
anchors.setMargin(AnchorLine::Right, anchors.instanceMargin(AnchorLine::Right) - deltaX);
- }
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
anchors.setMargin(AnchorLine::HorizontalCenter, anchors.instanceMargin(AnchorLine::HorizontalCenter) + deltaX);
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
anchors.setMargin(AnchorLine::VerticalCenter, anchors.instanceMargin(AnchorLine::VerticalCenter) + deltaY);
- }
setPosition(item->qmlItemNode(), QPointF(item->qmlItemNode().instanceValue("x").toDouble() + deltaX,
item->qmlItemNode().instanceValue("y").toDouble() + deltaY));
diff --git a/src/plugins/qmldesigner/components/formeditor/movetool.cpp b/src/plugins/qmldesigner/components/formeditor/movetool.cpp
index 83ce8bb206..0394a863ee 100644
--- a/src/plugins/qmldesigner/components/formeditor/movetool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/movetool.cpp
@@ -106,8 +106,8 @@ void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList,
}
}
- bool shouldSnapping = view()->widget()->snappingAction()->isChecked();
- bool shouldSnappingAndAnchoring = view()->widget()->snappingAndAnchoringAction()->isChecked();
+ bool shouldSnapping = view()->formEditorWidget()->snappingAction()->isChecked();
+ bool shouldSnappingAndAnchoring = view()->formEditorWidget()->snappingAndAnchoringAction()->isChecked();
MoveManipulator::Snapping useSnapping = MoveManipulator::NoSnapping;
if (event->modifiers().testFlag(Qt::ControlModifier) != (shouldSnapping || shouldSnappingAndAnchoring)) {
@@ -143,7 +143,7 @@ void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
void MoveTool::keyPressEvent(QKeyEvent *event)
{
- switch(event->key()) {
+ switch (event->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
@@ -168,7 +168,7 @@ void MoveTool::keyPressEvent(QKeyEvent *event)
m_moveManipulator.beginRewriterTransaction();
}
- switch(event->key()) {
+ switch (event->key()) {
case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break;
case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break;
case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break;
@@ -183,7 +183,7 @@ void MoveTool::keyPressEvent(QKeyEvent *event)
void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent)
{
- switch(keyEvent->key()) {
+ switch (keyEvent->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
diff --git a/src/plugins/qmldesigner/components/formeditor/onedimensionalcluster.cpp b/src/plugins/qmldesigner/components/formeditor/onedimensionalcluster.cpp
index 1c0e448323..b6d382d91e 100644
--- a/src/plugins/qmldesigner/components/formeditor/onedimensionalcluster.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/onedimensionalcluster.cpp
@@ -36,7 +36,7 @@ namespace QmlDesigner {
double sum(const QList<double> & list)
{
double sum = 0.0;
- for(QList<double>::const_iterator iterator = list.constBegin(); iterator != list.constEnd(); ++iterator)
+ for (QList<double>::const_iterator iterator = list.constBegin(); iterator != list.constEnd(); ++iterator)
{
sum += *iterator;
}
diff --git a/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp
index 2dbd3ae4b0..162a9e5bab 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/resizemanipulator.cpp
@@ -135,13 +135,11 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
}
boundingRect.setBottomRight(updatePointInLocalSpace);
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
boundingRect.setLeft(boundingRect.left() - (updatePointInLocalSpace.x() - m_beginBoundingRect.right()));
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
boundingRect.setTop(boundingRect.top() - (updatePointInLocalSpace.y() - m_beginBoundingRect.bottom()));
- }
if (boundingRect.width() < minimumWidth)
boundingRect.setWidth(minimumWidth);
@@ -174,13 +172,11 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
}
boundingRect.setTopLeft(updatePointInLocalSpace);
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
boundingRect.setRight(boundingRect.right() - (updatePointInLocalSpace.x() - m_beginBoundingRect.left()));
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
boundingRect.setBottom(boundingRect.bottom() - (updatePointInLocalSpace.y() - m_beginBoundingRect.top()));
- }
if (boundingRect.width() < minimumWidth)
@@ -216,13 +212,11 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
}
boundingRect.setTopRight(updatePointInLocalSpace);
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
boundingRect.setLeft(boundingRect.left() - (updatePointInLocalSpace.x() - m_beginBoundingRect.right()));
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
boundingRect.setBottom(boundingRect.bottom() - (updatePointInLocalSpace.y() - m_beginBoundingRect.top()));
- }
if (boundingRect.height() < minimumHeight)
boundingRect.setTop(boundingRect.top() - minimumHeight + boundingRect.height());
@@ -256,13 +250,11 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
boundingRect.setBottomLeft(updatePointInLocalSpace);
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
boundingRect.setRight(boundingRect.right() - (updatePointInLocalSpace.x() - m_beginBoundingRect.left()));
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
boundingRect.setTop(boundingRect.top() - (updatePointInLocalSpace.y() - m_beginBoundingRect.bottom()));
- }
if (boundingRect.height() < minimumHeight)
boundingRect.setHeight(minimumHeight);
@@ -292,9 +284,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
boundingRect.setBottom(updatePointInLocalSpace.y());
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
boundingRect.setTop(boundingRect.top() - (updatePointInLocalSpace.y() - m_beginBoundingRect.bottom()));
- }
if (boundingRect.height() < minimumHeight)
boundingRect.setHeight(minimumHeight);
@@ -316,9 +307,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
boundingRect.setTop(updatePointInLocalSpace.y());
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
boundingRect.setBottom(boundingRect.bottom() - (updatePointInLocalSpace.y() - m_beginBoundingRect.top()));
- }
if (boundingRect.height() < minimumHeight)
boundingRect.setTop(boundingRect.top() - minimumHeight + boundingRect.height());
@@ -341,9 +331,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
boundingRect.setRight(updatePointInLocalSpace.x());
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
boundingRect.setLeft(boundingRect.left() - (updatePointInLocalSpace.x() - m_beginBoundingRect.right()));
- }
if (boundingRect.width() < minimumWidth)
boundingRect.setWidth(minimumWidth);
@@ -366,9 +355,8 @@ void ResizeManipulator::update(const QPointF& updatePoint, Snapping useSnapping)
boundingRect.setLeft(updatePointInLocalSpace.x());
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
boundingRect.setRight(boundingRect.right() - (updatePointInLocalSpace.x() - m_beginBoundingRect.left()));
- }
if (boundingRect.width() < minimumWidth)
boundingRect.setLeft(boundingRect.left() - minimumWidth + boundingRect.width());
@@ -410,13 +398,11 @@ void ResizeManipulator::moveBy(double deltaX, double deltaY)
qmlItemNode.setVariantProperty("width", round(qmlItemNode.instanceValue("width").toDouble() - deltaX, 4));
- if (anchors.instanceHasAnchor(AnchorLine::Left)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Left))
anchors.setMargin(AnchorLine::Left, anchors.instanceMargin(AnchorLine::Left) + deltaX);
- }
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
qmlItemNode.setVariantProperty("width", round(qmlItemNode.instanceValue("width").toDouble() - (deltaX * 2), 4));
- }
}
if (m_resizeController.isRightHandle(resizeHandle())
@@ -424,13 +410,11 @@ void ResizeManipulator::moveBy(double deltaX, double deltaY)
|| m_resizeController.isBottomRightHandle(resizeHandle())) {
qmlItemNode.setVariantProperty("width", round(qmlItemNode.instanceValue("width").toDouble() + deltaX, 4));
- if (anchors.instanceHasAnchor(AnchorLine::Right)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Right))
anchors.setMargin(AnchorLine::Right, round(anchors.instanceMargin(AnchorLine::Right) - deltaX, 4));
- }
- if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::HorizontalCenter))
qmlItemNode.setVariantProperty("width", round(qmlItemNode.instanceValue("width").toDouble() + (deltaX * 2), 4));
- }
}
@@ -440,13 +424,11 @@ void ResizeManipulator::moveBy(double deltaX, double deltaY)
qmlItemNode.setVariantProperty("y", round(qmlItemNode.instanceValue("y").toDouble() + deltaY, 4));
qmlItemNode.setVariantProperty("height", round(qmlItemNode.instanceValue("height").toDouble() - deltaY, 4));
- if (anchors.instanceHasAnchor(AnchorLine::Top)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Top))
anchors.setMargin(AnchorLine::Top, anchors.instanceMargin(AnchorLine::Top) + deltaY);
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
qmlItemNode.setVariantProperty("height", round(qmlItemNode.instanceValue("height").toDouble() - (deltaY * 2), 4));
- }
}
if (m_resizeController.isBottomHandle(resizeHandle())
@@ -454,13 +436,11 @@ void ResizeManipulator::moveBy(double deltaX, double deltaY)
|| m_resizeController.isBottomRightHandle(resizeHandle())) {
qmlItemNode.setVariantProperty("height", round(qmlItemNode.instanceValue("height").toDouble() + deltaY, 4));
- if (anchors.instanceHasAnchor(AnchorLine::Bottom)) {
+ if (anchors.instanceHasAnchor(AnchorLine::Bottom))
anchors.setMargin(AnchorLine::Bottom, anchors.instanceMargin(AnchorLine::Bottom) - deltaY);
- }
- if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter)) {
+ if (anchors.instanceHasAnchor(AnchorLine::VerticalCenter))
qmlItemNode.setVariantProperty("height", round(qmlItemNode.instanceValue("height").toDouble() + (deltaY * 2), 4));
- }
}
}
diff --git a/src/plugins/qmldesigner/components/formeditor/resizetool.cpp b/src/plugins/qmldesigner/components/formeditor/resizetool.cpp
index d740622726..34ff0a7843 100644
--- a/src/plugins/qmldesigner/components/formeditor/resizetool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/resizetool.cpp
@@ -77,8 +77,8 @@ void ResizeTool::mouseMoveEvent(const QList<QGraphicsItem*> &,
QGraphicsSceneMouseEvent *event)
{
if (m_resizeManipulator.isActive()) {
- bool shouldSnapping = view()->widget()->snappingAction()->isChecked();
- bool shouldSnappingAndAnchoring = view()->widget()->snappingAndAnchoringAction()->isChecked();
+ bool shouldSnapping = view()->formEditorWidget()->snappingAction()->isChecked();
+ bool shouldSnappingAndAnchoring = view()->formEditorWidget()->snappingAndAnchoringAction()->isChecked();
ResizeManipulator::Snapping useSnapping = ResizeManipulator::NoSnapping;
if (event->modifiers().testFlag(Qt::ControlModifier) != (shouldSnapping || shouldSnappingAndAnchoring)) {
@@ -142,7 +142,7 @@ void ResizeTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> & /*itemList*
void ResizeTool::keyPressEvent(QKeyEvent * event)
{
- switch(event->key()) {
+ switch (event->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
@@ -156,7 +156,7 @@ void ResizeTool::keyPressEvent(QKeyEvent * event)
if (event->modifiers().testFlag(Qt::ShiftModifier))
moveStep = 10.0;
- switch(event->key()) {
+ switch (event->key()) {
case Qt::Key_Left: m_resizeManipulator.moveBy(-moveStep, 0.0); break;
case Qt::Key_Right: m_resizeManipulator.moveBy(moveStep, 0.0); break;
case Qt::Key_Up: m_resizeManipulator.moveBy(0.0, -moveStep); break;
@@ -167,7 +167,7 @@ void ResizeTool::keyPressEvent(QKeyEvent * event)
void ResizeTool::keyReleaseEvent(QKeyEvent * keyEvent)
{
- switch(keyEvent->key()) {
+ switch (keyEvent->key()) {
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Control:
diff --git a/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp
index 54613ace02..58d5012654 100644
--- a/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/rubberbandselectionmanipulator.cpp
@@ -118,7 +118,7 @@ void RubberBandSelectionManipulator::select(SelectionType selectionType)
QList<QmlItemNode> nodeList;
- switch(selectionType) {
+ switch (selectionType) {
case AddToSelection: {
nodeList.append(m_oldSelectionList);
nodeList.append(newNodeList);
diff --git a/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp b/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp
index 4835c8fe63..682bf7f0b0 100644
--- a/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/selectiontool.cpp
@@ -144,7 +144,7 @@ void SelectionTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
FormEditorItem *topSelectableItem = 0;
- foreach(QGraphicsItem* item, itemList)
+ foreach (QGraphicsItem* item, itemList)
{
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
@@ -165,9 +165,8 @@ void SelectionTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList,
void SelectionTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList,
QGraphicsSceneMouseEvent *event)
{
- if (m_singleSelectionManipulator.isActive()) {
+ if (m_singleSelectionManipulator.isActive())
m_singleSelectionManipulator.end(event->scenePos());
- }
else if (m_rubberbandSelectionManipulator.isActive()) {
QPointF mouseMovementVector = m_rubberbandSelectionManipulator.beginPoint() - event->scenePos();
@@ -206,7 +205,7 @@ void SelectionTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList,
void SelectionTool::keyPressEvent(QKeyEvent *event)
{
- switch(event->key()) {
+ switch (event->key()) {
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Up:
diff --git a/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp b/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp
index 5f02ae9ba0..52a3b79e41 100644
--- a/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/singleselectionmanipulator.cpp
@@ -75,7 +75,7 @@ void SingleSelectionManipulator::select(SelectionType selectionType, bool select
QmlItemNode selectedNode;
- foreach(QGraphicsItem* item, itemList)
+ foreach (QGraphicsItem* item, itemList)
{
FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);
@@ -90,7 +90,7 @@ void SingleSelectionManipulator::select(SelectionType selectionType, bool select
QList<QmlItemNode> nodeList;
- switch(selectionType) {
+ switch (selectionType) {
case AddToSelection: {
nodeList.append(m_oldSelectionList);
if (selectedNode.isValid())
diff --git a/src/plugins/qmldesigner/components/formeditor/snapper.cpp b/src/plugins/qmldesigner/components/formeditor/snapper.cpp
index 9c378b6b9c..9c9f715f98 100644
--- a/src/plugins/qmldesigner/components/formeditor/snapper.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/snapper.cpp
@@ -390,14 +390,12 @@ double Snapper::snappedOffsetForLines(const SnapLineMap &snappingLineMap,
double offset = value - snapLine;
double distance = qAbs(offset);
- if (distance < snappingDistance()) {
+ if (distance < snappingDistance())
minimumSnappingLineMap.insert(distance, offset);
- }
}
- if (!minimumSnappingLineMap.isEmpty()) {
+ if (!minimumSnappingLineMap.isEmpty())
return minimumSnappingLineMap.begin().value();
- }
return std::numeric_limits<double>::max();
}
@@ -437,9 +435,8 @@ double Snapper::snappedOffsetForOffsetLines(const SnapLineMap &snappingOffsetMap
}
}
- if (!minimumSnappingLineMap.isEmpty()) {
+ if (!minimumSnappingLineMap.isEmpty())
return minimumSnappingLineMap.begin().value();
- }
return std::numeric_limits<double>::max();
}
@@ -473,7 +470,7 @@ static QLineF mergedHorizontalLine(const QList<QLineF> &lineList)
double minimumX = std::numeric_limits<double>::max();
double maximumX = std::numeric_limits<double>::min();
- foreach(const QLineF &line, lineList) {
+ foreach (const QLineF &line, lineList) {
minimumX = qMin(minimumX, double(line.x1()));
minimumX = qMin(minimumX, double(line.x2()));
maximumX = qMax(maximumX, double(line.x1()));
@@ -491,7 +488,7 @@ static QLineF mergedVerticalLine(const QList<QLineF> &lineList)
double minimumY = std::numeric_limits<double>::max();
double maximumY = std::numeric_limits<double>::min();
- foreach(const QLineF &line, lineList) {
+ foreach (const QLineF &line, lineList) {
minimumY = qMin(minimumY, double(line.y1()));
minimumY = qMin(minimumY, double(line.y2()));
maximumY = qMax(maximumY, double(line.y1()));
@@ -585,13 +582,13 @@ QList<QGraphicsItem*> Snapper::generateSnappingLines(const QList<QRectF> &boundi
{
QList<QGraphicsItem*> graphicsItemList;
QList<QLineF> lineList;
- foreach(const QRectF &boundingRect, boundingRectList) {
+ foreach (const QRectF &boundingRect, boundingRectList) {
QList<QRectF> snappedBoundingRectList;
lineList += mergedHorizontalLines(horizontalSnappedLines(boundingRect, &snappedBoundingRectList));
lineList += mergedVerticalLines(verticalSnappedLines(boundingRect, &snappedBoundingRectList));
// snappedBoundingRectList.append(boundingRect);
-// foreach(const QRectF &snappedBoundingRect, snappedBoundingRectList) {
+// foreach (const QRectF &snappedBoundingRect, snappedBoundingRectList) {
// QPolygonF rect = transform.map(snappedBoundingRect);
// alignVertices(rect);
// QGraphicsPolygonItem * item = new QGraphicsPolygonItem(rect, layerItem);
@@ -607,7 +604,7 @@ QList<QGraphicsItem*> Snapper::generateSnappingLines(const QList<QRectF> &boundi
// }
}
- foreach(const QLineF &line, lineList) {
+ foreach (const QLineF &line, lineList) {
QLineF lineInTransformationSpace = transform.map(line);
// alignLine(lineInTransformationSpace);
QGraphicsLineItem * lineItem = new QGraphicsLineItem(lineInTransformationSpace, layerItem);
diff --git a/src/plugins/qmldesigner/components/formeditor/toolbox.cpp b/src/plugins/qmldesigner/components/formeditor/toolbox.cpp
index f378f34948..6af1ded4b8 100644
--- a/src/plugins/qmldesigner/components/formeditor/toolbox.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/toolbox.cpp
@@ -44,19 +44,19 @@ namespace QmlDesigner {
ToolBox::ToolBox(QWidget *parentWidget)
: Utils::StyledBar(parentWidget),
m_leftToolBar(new QToolBar("LeftSidebar", this)),
- m_rightToolBar(new QToolBar("RightSidebar", this))
+ m_rightToolBar(new QToolBar("RightSidebar", this)),
+ m_formEditorCrumbleBar(new FormEditorCrumbleBar(this))
{
setMaximumHeight(44);
setSingleRow(false);
QFrame *frame = new QFrame(this);
- m_crumblePath = new Utils::CrumblePath(frame);
frame->setStyleSheet("background-color: #4e4e4e;");
frame->setFrameShape(QFrame::NoFrame);
QHBoxLayout *layout = new QHBoxLayout(frame);
layout->setMargin(0);
layout->setSpacing(0);
frame->setLayout(layout);
- layout->addWidget(m_crumblePath);
+ layout->addWidget(m_formEditorCrumbleBar->crumblePath());
frame->setProperty("panelwidget", true);
frame->setProperty("panelwidget_singlerow", false);
QVBoxLayout *verticalLayout = new QVBoxLayout(this);
@@ -126,9 +126,9 @@ QList<QAction*> ToolBox::actions() const
return QList<QAction*>() << m_leftToolBar->actions() << m_rightToolBar->actions();
}
-Utils::CrumblePath *ToolBox::crumblePath() const
+FormEditorCrumbleBar *ToolBox::formEditorCrumbleBar() const
{
- return m_crumblePath;
+ return m_formEditorCrumbleBar;
}
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/toolbox.h b/src/plugins/qmldesigner/components/formeditor/toolbox.h
index 80dac553f1..8974ae6b71 100644
--- a/src/plugins/qmldesigner/components/formeditor/toolbox.h
+++ b/src/plugins/qmldesigner/components/formeditor/toolbox.h
@@ -32,6 +32,8 @@
#include "utils/styledbar.h"
+#include "formeditorcrumblebar.h"
+
QT_BEGIN_NAMESPACE
class QToolBar;
QT_END_NAMESPACE
@@ -51,13 +53,12 @@ public:
void addLeftSideAction(QAction *action);
void addRightSideAction(QAction *action);
QList<QAction*> actions() const;
- Utils::CrumblePath *crumblePath() const;
-
+ FormEditorCrumbleBar *formEditorCrumbleBar() const;
private:
QToolBar *m_leftToolBar;
QToolBar *m_rightToolBar;
- Utils::CrumblePath *m_crumblePath;
+ FormEditorCrumbleBar *m_formEditorCrumbleBar;
};
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/formeditor/zoomaction.cpp b/src/plugins/qmldesigner/components/formeditor/zoomaction.cpp
index bd9af4eebf..d517c7a765 100644
--- a/src/plugins/qmldesigner/components/formeditor/zoomaction.cpp
+++ b/src/plugins/qmldesigner/components/formeditor/zoomaction.cpp
@@ -64,13 +64,12 @@ void ZoomAction::zoomOut()
void ZoomAction::setZoomLevel(double zoomLevel)
{
- if (zoomLevel < .1) {
+ if (zoomLevel < .1)
m_zoomLevel = 0.1;
- } else if (zoomLevel > 16.0) {
+ else if (zoomLevel > 16.0)
m_zoomLevel = 16.0;
- } else {
+ else
m_zoomLevel = zoomLevel;
- }
emit zoomLevelChanged(m_zoomLevel);
}
diff --git a/src/plugins/qmldesigner/components/integration/componentaction.cpp b/src/plugins/qmldesigner/components/integration/componentaction.cpp
index d0d43d0566..6ba366532e 100644
--- a/src/plugins/qmldesigner/components/integration/componentaction.cpp
+++ b/src/plugins/qmldesigner/components/integration/componentaction.cpp
@@ -32,7 +32,8 @@
#include <QComboBox>
#include "componentview.h"
#include <QStandardItemModel>
-#include <QDebug>
+#include <qmldesignerplugin.h>
+#include <modelnode.h>
namespace QmlDesigner {
@@ -42,9 +43,9 @@ ComponentAction::ComponentAction(ComponentView *componentView)
{
}
-void ComponentAction::setCurrentIndex(int i)
+void ComponentAction::setCurrentIndex(int index)
{
- emit currentIndexChanged(i);
+ emit currentIndexChanged(index);
}
QWidget *ComponentAction::createWidget(QWidget *parent)
@@ -59,9 +60,21 @@ QWidget *ComponentAction::createWidget(QWidget *parent)
return comboBox;
}
+static const QString fileNameOfCurrentDocument()
+{
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument()->textEditor()->document()->fileName();
+}
+
void ComponentAction::emitCurrentComponentChanged(int index)
{
- emit currentComponentChanged(m_componentView->modelNode(index));
+ ModelNode componentNode = m_componentView->modelNode(index);
+
+ if ( index > 0)
+ QmlDesignerPlugin::instance()->viewManager().pushInFileComponentOnCrambleBar(componentNode.id());
+ else
+ QmlDesignerPlugin::instance()->viewManager().pushFileOnCrambleBar(fileNameOfCurrentDocument());
+
+ emit currentComponentChanged(componentNode);
}
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/integration/componentaction.h b/src/plugins/qmldesigner/components/integration/componentaction.h
index 1f77f6ddd4..45df922140 100644
--- a/src/plugins/qmldesigner/components/integration/componentaction.h
+++ b/src/plugins/qmldesigner/components/integration/componentaction.h
@@ -48,16 +48,17 @@ class ComponentAction : public QWidgetAction
Q_OBJECT
public:
ComponentAction(ComponentView *componentView);
- void setCurrentIndex(int);
+ void setCurrentIndex(int index);
+
protected:
QWidget *createWidget(QWidget *parent);
signals:
void currentComponentChanged(const ModelNode &node);
- void currentIndexChanged(int);
+ void currentIndexChanged(int index);
-private slots:
+public slots:
void emitCurrentComponentChanged(int index);
private:
diff --git a/src/plugins/qmldesigner/components/integration/componentview.cpp b/src/plugins/qmldesigner/components/integration/componentview.cpp
index 3932a929d7..888a13317f 100644
--- a/src/plugins/qmldesigner/components/integration/componentview.cpp
+++ b/src/plugins/qmldesigner/components/integration/componentview.cpp
@@ -34,6 +34,7 @@
#include <nodemetainfo.h>
#include <nodeabstractproperty.h>
#include <QStandardItemModel>
+#include <QAbstractItemView>
// silence gcc warnings about unused parameters
@@ -46,8 +47,6 @@ ComponentView::ComponentView(QObject *parent)
{
}
-
-
void ComponentView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
removeSingleNodeFromList(removedNode);
@@ -74,6 +73,11 @@ void ComponentView::setComponentNode(const ModelNode &node)
m_componentAction->setCurrentIndex(indexForNode(node));
}
+QWidget *ComponentView::widget()
+{
+ return 0;
+}
+
void ComponentView::appendWholeDocumentAsComponent()
{
QStandardItem *item = new QStandardItem(tr("whole document"));
@@ -110,7 +114,6 @@ void ComponentView::modelAttached(Model *model)
AbstractView::modelAttached(model);
- Q_ASSERT(model->masterModel());
appendWholeDocumentAsComponent();
searchForComponentAndAddToList(rootModelNode());
@@ -154,11 +157,10 @@ void ComponentView::searchForComponentAndAddToList(const ModelNode &node)
QString description;
ModelNode parentNode = node.parentProperty().parentModelNode();
if (parentNode.isValid()) {
- if (parentNode.id().isEmpty()) {
+ if (parentNode.id().isEmpty())
description = parentNode.simplifiedTypeName() + QLatin1Char(' ');
- } else {
+ else
description = parentNode.id() + QLatin1Char(' ');
- }
}
description += node.parentProperty().name();
QStandardItem *item = new QStandardItem(description);
@@ -183,9 +185,8 @@ void ComponentView::searchForComponentAndRemoveFromList(const ModelNode &node)
foreach (const ModelNode &childNode, nodeList) {
- if (childNode.nodeSourceType() == ModelNode::NodeWithComponentSource) {
+ if (childNode.nodeSourceType() == ModelNode::NodeWithComponentSource)
removeSingleNodeFromList(childNode);
- }
}
}
diff --git a/src/plugins/qmldesigner/components/integration/componentview.h b/src/plugins/qmldesigner/components/integration/componentview.h
index e6a23fa5a9..2e19948ef3 100644
--- a/src/plugins/qmldesigner/components/integration/componentview.h
+++ b/src/plugins/qmldesigner/components/integration/componentview.h
@@ -37,6 +37,7 @@
QT_BEGIN_NAMESPACE
class QStandardItemModel;
+class QComboBox;
QT_END_NAMESPACE
namespace QmlDesigner {
@@ -53,7 +54,7 @@ public:
ModelNodeRole = Qt::UserRole
};
- ComponentView(QObject *parent);
+ ComponentView(QObject *parent = 0);
void modelAttached(Model *model);
void modelAboutToBeDetached(Model *model);
@@ -106,6 +107,8 @@ public:
void setComponentNode(const ModelNode &node);
+ QWidget *widget();
+
signals:
void componentListChanged(const QStringList &componentList);
@@ -118,6 +121,7 @@ private: //functions
int indexForNode(const ModelNode &node);
private:
+ QList<QComboBox*> m_comboBoxList;
QStandardItemModel *m_standardItemModel;
ComponentAction *m_componentAction;
};
diff --git a/src/plugins/qmldesigner/components/integration/designdocument.cpp b/src/plugins/qmldesigner/components/integration/designdocument.cpp
new file mode 100644
index 0000000000..5c9409030a
--- /dev/null
+++ b/src/plugins/qmldesigner/components/integration/designdocument.cpp
@@ -0,0 +1,784 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "designdocument.h"
+#include "designdocumentview.h"
+#include "xuifiledialog.h"
+#include "componentview.h"
+
+#include <itemlibrarywidget.h>
+#include <formeditorwidget.h>
+#include <toolbox.h>
+#include <metainfo.h>
+#include <invalidargumentexception.h>
+#include <componentaction.h>
+#include <designeractionmanager.h>
+#include <qmlobjectnode.h>
+#include <rewritingexception.h>
+#include <nodelistproperty.h>
+#include <variantproperty.h>
+#include <rewritingexception.h>
+#include <modelnodeoperations.h>
+#include <qmldesignerplugin.h>
+
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/target.h>
+#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
+#include <qtsupport/qtkitinformation.h>
+#include <qtsupport/qtsupportconstants.h>
+#include <qtsupport/qtversionmanager.h>
+#include <utils/crumblepath.h>
+#include <utils/fileutils.h>
+
+#include <QCoreApplication>
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QUrl>
+#include <QProcess>
+#include <QTemporaryFile>
+#include <QDebug>
+#include <QEvent>
+
+#include <QBoxLayout>
+#include <QComboBox>
+#include <QErrorMessage>
+#include <QFileDialog>
+#include <QLabel>
+#include <QMdiArea>
+#include <QMdiSubWindow>
+#include <QMessageBox>
+#include <QUndoStack>
+#include <QPlainTextEdit>
+#include <QApplication>
+
+enum {
+ debug = false
+};
+
+namespace QmlDesigner {
+
+
+/**
+ \class QmlDesigner::DesignDocument
+
+ DesignDocument acts as a facade to a model representing a qml document,
+ and the different views/widgets accessing it.
+ */
+DesignDocument::DesignDocument(QObject *parent) :
+ QObject(parent),
+ m_documentModel(Model::create("QtQuick.Item", 1, 0)),
+ m_inFileComponentModel(Model::create("QtQuick.Item", 1, 0)),
+ m_currentModel(m_documentModel),
+ m_subComponentManager(new SubComponentManager(m_documentModel.data(), this)),
+ m_rewriterView (new RewriterView(RewriterView::Amend, m_documentModel.data())),
+ m_documentLoaded(false),
+ m_qtVersionId(-1)
+{
+ updateActiveQtVersion();
+}
+
+DesignDocument::~DesignDocument()
+{
+ delete m_documentModel.data();
+ delete m_inFileComponentModel.data();
+
+ delete rewriterView();
+
+ delete m_inFileComponentTextModifier.data();
+ delete m_documentTextModifier.data();
+}
+
+Model *DesignDocument::currentModel() const
+{
+ return m_currentModel.data();
+}
+
+Model *DesignDocument::documentModel() const
+{
+ return m_documentModel.data();
+}
+
+void DesignDocument::changeToDocumentModel()
+{
+ viewManager().detachRewriterView();
+ viewManager().detachViewsExceptRewriterAndComponetView();
+
+ m_currentModel = m_documentModel;
+
+ viewManager().attachRewriterView(m_documentTextModifier.data());
+ viewManager().attachViewsExceptRewriterAndComponetView();
+}
+
+void DesignDocument::changeToInFileComponentModel()
+{
+ viewManager().detachRewriterView();
+ viewManager().detachViewsExceptRewriterAndComponetView();
+
+ m_currentModel = m_inFileComponentModel;
+
+ viewManager().attachRewriterView(m_inFileComponentTextModifier.data());
+ viewManager().attachViewsExceptRewriterAndComponetView();
+}
+
+QWidget *DesignDocument::centralWidget() const
+{
+ return qobject_cast<QWidget*>(parent());
+}
+
+QString DesignDocument::pathToQt() const
+{
+ QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::instance()->version(m_qtVersionId);
+ if (activeQtVersion && (activeQtVersion->qtVersion() >= QtSupport::QtVersionNumber(4, 7, 1))
+ && (activeQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)
+ || activeQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)))
+ return activeQtVersion->qmakeProperty("QT_INSTALL_DATA");
+
+ return QString();
+}
+
+const ViewManager &DesignDocument::viewManager() const
+{
+ return QmlDesignerPlugin::instance()->viewManager();
+}
+
+ViewManager &DesignDocument::viewManager()
+{
+ return QmlDesignerPlugin::instance()->viewManager();
+}
+
+static ComponentTextModifier *createComponentTextModifier(TextModifier *originalModifier,
+ RewriterView *rewriterView,
+ const QString &componentText,
+ const ModelNode &componentNode)
+{
+ bool explicitComponent = componentText.contains("Component");
+
+ ModelNode rootModelNode = rewriterView->rootModelNode();
+
+ int componentStartOffset;
+ int componentEndOffset;
+
+ int rootStartOffset = rewriterView->nodeOffset(rootModelNode);
+
+ if (explicitComponent) { //the component is explciit we have to find the first definition inside
+ componentStartOffset = rewriterView->firstDefinitionInsideOffset(componentNode);
+ componentEndOffset = componentStartOffset + rewriterView->firstDefinitionInsideLength(componentNode);
+ } else { //the component is implicit
+ componentStartOffset = rewriterView->nodeOffset(componentNode);
+ componentEndOffset = componentStartOffset + rewriterView->nodeLength(componentNode);
+ }
+
+ return new ComponentTextModifier (originalModifier, componentStartOffset, componentEndOffset, rootStartOffset);
+}
+
+bool DesignDocument::loadSubComponent(const ModelNode &componentNode)
+{
+ QString componentText = rewriterView()->extractText(QList<ModelNode>() << componentNode).value(componentNode);
+
+ if (componentText.isEmpty())
+ return false;
+
+ if (!componentNode.isRootNode()) {
+ Q_ASSERT(m_currentModel == m_documentModel);
+ //change to subcomponent model
+ if (m_inFileComponentTextModifier)
+ delete m_inFileComponentTextModifier.data();
+
+ m_inFileComponentTextModifier = createComponentTextModifier(m_documentTextModifier.data(), rewriterView(), componentText, componentNode);
+
+ changeToInFileComponentModel();
+ }
+
+ return true;
+}
+
+/*!
+ Returns any errors that happened when parsing the latest qml file.
+ */
+QList<RewriterView::Error> DesignDocument::qmlSyntaxErrors() const
+{
+ return m_rewriterView->errors();
+}
+
+bool DesignDocument::hasQmlSyntaxErrors() const
+{
+ return !m_currentModel->rewriterView()->errors().isEmpty();
+}
+
+QString DesignDocument::displayName() const
+{
+ return fileName();
+}
+
+QString DesignDocument::simplfiedDisplayName() const
+{
+ if (rootModelNode().id().isEmpty()) {
+ return rootModelNode().id();
+ } else {
+ return rootModelNode().simplifiedTypeName();
+ }
+
+ QStringList list = displayName().split(QLatin1Char('/'));
+ return list.last();
+}
+
+void DesignDocument::updateFileName(const QString & /*oldFileName*/, const QString &newFileName)
+{
+ if (m_documentModel)
+ m_documentModel->setFileUrl(QUrl::fromLocalFile(newFileName));
+
+ if (m_inFileComponentModel)
+ m_inFileComponentModel->setFileUrl(QUrl::fromLocalFile(newFileName));
+
+ viewManager().setItemLibraryViewResourcePath(QFileInfo(newFileName).absolutePath());
+
+ emit displayNameChanged(displayName());
+}
+
+QString DesignDocument::fileName() const
+{
+ return editor()->document()->fileName();
+}
+
+int DesignDocument::qtVersionId() const
+{
+ return m_qtVersionId;
+}
+
+bool DesignDocument::isDocumentLoaded() const
+{
+ return m_documentLoaded;
+}
+
+void DesignDocument::resetToDocumentModel()
+{
+ m_currentModel = m_documentModel;
+ m_rewriterView->setTextModifier(m_documentTextModifier.data());
+}
+
+QList<RewriterView::Error> DesignDocument::loadDocument(QPlainTextEdit *edit)
+{
+ Q_CHECK_PTR(edit);
+
+ connect(edit, SIGNAL(undoAvailable(bool)),
+ this, SIGNAL(undoAvailable(bool)));
+ connect(edit, SIGNAL(redoAvailable(bool)),
+ this, SIGNAL(redoAvailable(bool)));
+ connect(edit, SIGNAL(modificationChanged(bool)),
+ this, SIGNAL(dirtyStateChanged(bool)));
+
+ m_documentTextModifier = new BaseTextEditModifier(dynamic_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit()));
+
+ m_inFileComponentTextModifier.clear();
+
+ //masterModel = Model::create(textModifier, searchPath, errors);
+
+ updateFileName(QString(), fileName());
+
+ m_subComponentManager->update(QUrl::fromLocalFile(fileName()), m_currentModel->imports());
+
+ activateCurrentModel(m_documentTextModifier.data());
+
+ return rewriterView()->errors();
+}
+
+void DesignDocument::changeCurrentModelTo(const ModelNode &node)
+{
+ if (QmlDesignerPlugin::instance()->currentDesignDocument() != this)
+ return;
+
+ if (rootModelNode() == node) {
+ changeToDocumentModel();
+ } else {
+ changeToSubComponent(node);
+ }
+
+
+
+// s_clearCrumblePath = false;
+// while (m_formEditorView->crumblePath()->dataForLastIndex().value<CrumbleBarInfo>().modelNode.isValid() &&
+// !m_formEditorView->crumblePath()->dataForLastIndex().value<CrumbleBarInfo>().modelNode.isRootNode())
+// m_formEditorView->crumblePath()->popElement();
+// if (node.isRootNode() && m_formEditorView->crumblePath()->dataForLastIndex().isValid())
+// m_formEditorView->crumblePath()->popElement();
+// s_clearCrumblePath = true;
+}
+
+void DesignDocument::changeToSubComponent(const ModelNode &componentNode)
+{
+ Q_ASSERT(m_documentModel);
+ QWeakPointer<Model> oldModel = m_currentModel;
+ Q_ASSERT(oldModel.data());
+
+ if (m_currentModel == m_inFileComponentModel) {
+ changeToDocumentModel();
+ }
+
+ bool subComponentLoaded = loadSubComponent(componentNode);
+
+ if (subComponentLoaded) {
+ Q_ASSERT(m_documentModel);
+ Q_ASSERT(m_currentModel);
+
+ activateCurrentModel(m_inFileComponentTextModifier.data());
+ }
+}
+
+void DesignDocument::changeToExternalSubComponent(const QString &fileName)
+{
+ Core::EditorManager::openEditor(fileName);
+}
+
+void DesignDocument::goIntoComponent()
+{
+ if (!m_currentModel)
+ return;
+
+ QList<ModelNode> selectedNodes;
+ if (rewriterView())
+ selectedNodes = rewriterView()->selectedModelNodes();
+
+ if (selectedNodes.count() == 1) {
+ viewManager().setComponentNode(selectedNodes.first());
+ ModelNodeOperations::goIntoComponent(selectedNodes.first());
+ }
+}
+
+void DesignDocument::activateCurrentModel(TextModifier *textModifier)
+{
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+ Q_ASSERT(m_documentModel);
+ Q_ASSERT(m_currentModel);
+
+ if (!plainTextEdit()->parent()) // hack to prevent changing owner of external text edit
+ m_stackedWidget->addWidget(plainTextEdit());
+
+ viewManager().attachRewriterView(textModifier);
+
+// if (s_clearCrumblePath)
+// m_formEditorView->crumblePath()->clear();
+
+// if (s_pushCrumblePath &&
+// !differentCrumbleBarOnTop(m_formEditorView.data(), createCrumbleBarInfo().value<CrumbleBarInfo>()))
+// m_formEditorView->crumblePath()->pushElement(simplfiedDisplayName(), createCrumbleBarInfo());
+
+ m_documentLoaded = true;
+ m_subComponentManager->update(QUrl::fromLocalFile(fileName()), m_currentModel->imports());
+ Q_ASSERT(m_documentModel);
+ QApplication::restoreOverrideCursor();
+}
+
+void DesignDocument::activateCurrentModel()
+{
+ if (currentModel() == documentModel())
+ activateCurrentModel(m_documentTextModifier.data());
+ else
+ activateCurrentModel(m_inFileComponentTextModifier.data());
+}
+
+void DesignDocument::activateDocumentModel()
+{
+ QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
+
+ Q_ASSERT(m_documentModel);
+ Q_ASSERT(m_currentModel);
+
+ if (!plainTextEdit()->parent()) // hack to prevent changing owner of external text edit
+ m_stackedWidget->addWidget(plainTextEdit());
+
+ m_currentModel = m_documentModel;
+ m_documentLoaded = true;
+ m_subComponentManager->update(QUrl::fromLocalFile(fileName()), m_currentModel->imports());
+ Q_ASSERT(m_documentModel);
+ QApplication::restoreOverrideCursor();
+}
+
+bool DesignDocument::isUndoAvailable() const
+{
+
+ if (plainTextEdit())
+ return plainTextEdit()->document()->isUndoAvailable();
+ return false;
+}
+
+bool DesignDocument::isRedoAvailable() const
+{
+ if (plainTextEdit())
+ return plainTextEdit()->document()->isRedoAvailable();
+ return false;
+}
+
+void DesignDocument::close()
+{
+ m_documentLoaded = false;
+ emit designDocumentClosed();
+}
+
+void DesignDocument::deleteSelected()
+{
+ if (!m_currentModel)
+ return;
+
+ try {
+ RewriterTransaction transaction(rewriterView());
+ QList<ModelNode> toDelete = rewriterView()->selectedModelNodes();
+ foreach (ModelNode node, toDelete) {
+ if (node.isValid() && !node.isRootNode() && QmlObjectNode(node).isValid())
+ QmlObjectNode(node).destroy();
+ }
+
+ } catch (RewritingException &e) {
+ QMessageBox::warning(0, tr("Error"), e.description());
+ }
+}
+
+void DesignDocument::copySelected()
+{
+ QScopedPointer<Model> copyModel(Model::create("QtQuick.Rectangle", 1, 0, currentModel()));
+ copyModel->setFileUrl(currentModel()->fileUrl());
+ copyModel->changeImports(currentModel()->imports(), QList<Import>());
+
+ Q_ASSERT(copyModel);
+
+ DesignDocumentView view;
+
+ m_currentModel->attachView(&view);
+
+ if (view.selectedModelNodes().isEmpty())
+ return;
+
+ QList<ModelNode> selectedNodes(view.selectedModelNodes());
+
+ foreach (const ModelNode &node, selectedNodes) {
+ foreach (const ModelNode &node2, selectedNodes) {
+ if (node.isAncestorOf(node2))
+ selectedNodes.removeAll(node2);
+ }
+ }
+
+ if (selectedNodes.count() == 1) {
+ ModelNode selectedNode(selectedNodes.first());
+
+ if (!selectedNode.isValid())
+ return;
+
+ m_currentModel->detachView(&view);
+
+ copyModel->attachView(&view);
+ view.replaceModel(selectedNode);
+
+ Q_ASSERT(view.rootModelNode().isValid());
+ Q_ASSERT(view.rootModelNode().type() != "empty");
+
+ view.toClipboard();
+ } else { //multi items selected
+ m_currentModel->detachView(&view);
+ copyModel->attachView(&view);
+
+ foreach (ModelNode node, view.rootModelNode().allDirectSubModelNodes()) {
+ node.destroy();
+ }
+ view.changeRootNodeType("QtQuick.Rectangle", 1, 0);
+ view.rootModelNode().setId("designer__Selection");
+
+ foreach (const ModelNode &selectedNode, selectedNodes) {
+ ModelNode newNode(view.insertModel(selectedNode));
+ view.rootModelNode().nodeListProperty("data").reparentHere(newNode);
+ }
+
+ view.toClipboard();
+ }
+}
+
+void DesignDocument::cutSelected()
+{
+ copySelected();
+ deleteSelected();
+}
+
+static void scatterItem(ModelNode pastedNode, const ModelNode targetNode, int offset = -2000)
+{
+
+ bool scatter = false;
+ foreach (const ModelNode &childNode, targetNode.allDirectSubModelNodes()) {
+ if ((childNode.variantProperty("x").value() == pastedNode.variantProperty("x").value()) &&
+ (childNode.variantProperty("y").value() == pastedNode.variantProperty("y").value()))
+ scatter = true;
+ }
+ if (!scatter)
+ return;
+
+ if (offset == -2000) {
+ double x = pastedNode.variantProperty("x").value().toDouble();
+ double y = pastedNode.variantProperty("y").value().toDouble();
+ double targetWidth = 20;
+ double targetHeight = 20;
+ x = x + double(qrand()) / RAND_MAX * targetWidth - targetWidth / 2;
+ y = y + double(qrand()) / RAND_MAX * targetHeight - targetHeight / 2;
+ pastedNode.variantProperty("x") = int(x);
+ pastedNode.variantProperty("y") = int(y);
+ } else {
+ double x = pastedNode.variantProperty("x").value().toDouble();
+ double y = pastedNode.variantProperty("y").value().toDouble();
+ x = x + offset;
+ y = y + offset;
+ pastedNode.variantProperty("x") = int(x);
+ pastedNode.variantProperty("y") = int(y);
+ }
+}
+
+void DesignDocument::paste()
+{
+ QScopedPointer<Model> pasteModel(Model::create("empty", 1, 0, currentModel()));
+ pasteModel->setFileUrl(currentModel()->fileUrl());
+ pasteModel->changeImports(currentModel()->imports(), QList<Import>());
+
+ Q_ASSERT(pasteModel);
+
+ if (!pasteModel)
+ return;
+
+ DesignDocumentView view;
+ pasteModel->attachView(&view);
+
+ view.fromClipboard();
+
+ ModelNode rootNode(view.rootModelNode());
+
+ if (rootNode.type() == "empty")
+ return;
+
+ if (rootNode.id() == "designer__Selection") {
+ QList<ModelNode> selectedNodes = rootNode.allDirectSubModelNodes();
+ qDebug() << rootNode;
+ qDebug() << selectedNodes;
+ pasteModel->detachView(&view);
+ m_currentModel->attachView(&view);
+
+ ModelNode targetNode;
+
+ if (!view.selectedModelNodes().isEmpty())
+ targetNode = view.selectedModelNodes().first();
+
+ //In case we copy and paste a selection we paste in the parent item
+ if ((view.selectedModelNodes().count() == selectedNodes.count()) && targetNode.isValid() && targetNode.parentProperty().isValid())
+ targetNode = targetNode.parentProperty().parentModelNode();
+
+ if (!targetNode.isValid())
+ targetNode = view.rootModelNode();
+
+ foreach (const ModelNode &node, selectedNodes) {
+ foreach (const ModelNode &node2, selectedNodes) {
+ if (node.isAncestorOf(node2))
+ selectedNodes.removeAll(node2);
+ }
+ }
+
+ QList<ModelNode> pastedNodeList;
+
+ try {
+ RewriterTransaction transaction(rewriterView());
+
+ int offset = double(qrand()) / RAND_MAX * 20 - 10;
+
+ foreach (const ModelNode &node, selectedNodes) {
+ QString defaultProperty(targetNode.metaInfo().defaultPropertyName());
+ ModelNode pastedNode(view.insertModel(node));
+ pastedNodeList.append(pastedNode);
+ scatterItem(pastedNode, targetNode, offset);
+ targetNode.nodeListProperty(defaultProperty).reparentHere(pastedNode);
+ }
+
+ view.setSelectedModelNodes(pastedNodeList);
+ } catch (RewritingException &e) {
+ qWarning() << e.description(); //silent error
+ }
+ } else {
+ try {
+ RewriterTransaction transaction(rewriterView());
+
+ pasteModel->detachView(&view);
+ m_currentModel->attachView(&view);
+ ModelNode pastedNode(view.insertModel(rootNode));
+ ModelNode targetNode;
+
+ if (!view.selectedModelNodes().isEmpty())
+ targetNode = view.selectedModelNodes().first();
+
+ if (!targetNode.isValid())
+ targetNode = view.rootModelNode();
+
+ if (targetNode.parentProperty().isValid() &&
+ (pastedNode.simplifiedTypeName() == targetNode.simplifiedTypeName()) &&
+ (pastedNode.variantProperty("width").value() == targetNode.variantProperty("width").value()) &&
+ (pastedNode.variantProperty("height").value() == targetNode.variantProperty("height").value()))
+
+ targetNode = targetNode.parentProperty().parentModelNode();
+
+ QString defaultProperty(targetNode.metaInfo().defaultPropertyName());
+
+ scatterItem(pastedNode, targetNode);
+ if (targetNode.nodeListProperty(defaultProperty).isValid())
+ targetNode.nodeListProperty(defaultProperty).reparentHere(pastedNode);
+
+ transaction.commit();
+ NodeMetaInfo::clearCache();
+
+ view.setSelectedModelNodes(QList<ModelNode>() << pastedNode);
+ } catch (RewritingException &e) {
+ qWarning() << e.description(); //silent error
+ }
+ }
+}
+
+void DesignDocument::selectAll()
+{
+ if (!m_currentModel)
+ return;
+
+ DesignDocumentView view;
+ m_currentModel->attachView(&view);
+
+
+ QList<ModelNode> allNodesExceptRootNode(view.allModelNodes());
+ allNodesExceptRootNode.removeOne(view.rootModelNode());
+ view.setSelectedModelNodes(allNodesExceptRootNode);
+}
+
+RewriterView *DesignDocument::rewriterView() const
+{
+ return m_rewriterView.data();
+}
+
+void DesignDocument::setEditor(Core::IEditor *editor)
+{
+ m_textEditor = editor;
+ connect(editor->document(),
+ SIGNAL(fileNameChanged(QString,QString)),
+ SLOT(updateFileName(QString,QString)));
+}
+
+Core::IEditor *DesignDocument::editor() const
+{
+ return m_textEditor.data();
+}
+
+TextEditor::ITextEditor *DesignDocument::textEditor() const
+{
+ return qobject_cast<TextEditor::ITextEditor*>(editor());
+}
+
+QPlainTextEdit *DesignDocument::plainTextEdit() const
+{
+ if (editor())
+ return qobject_cast<QPlainTextEdit*>(editor()->widget());
+
+ return 0;
+}
+
+ModelNode DesignDocument::rootModelNode() const
+{
+ return rewriterView()->rootModelNode();
+}
+
+void DesignDocument::undo()
+{
+ if (rewriterView() && !rewriterView()->modificationGroupActive())
+ plainTextEdit()->undo();
+
+ viewManager().resetPropertyEditorView();
+}
+
+void DesignDocument::redo()
+{
+ if (rewriterView() && !rewriterView()->modificationGroupActive())
+ plainTextEdit()->redo();
+
+ viewManager().resetPropertyEditorView();
+}
+
+static inline QtSupport::BaseQtVersion *getActiveQtVersion(DesignDocument *controller)
+{
+ ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
+ ProjectExplorer::Project *currentProject = projectExplorer->currentProject();
+
+ if (!currentProject)
+ return 0;
+
+ controller->disconnect(controller, SLOT(updateActiveQtVersion()));
+ controller->connect(projectExplorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), controller, SLOT(updateActiveQtVersion()));
+
+ controller->connect(currentProject, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)), controller, SLOT(updateActiveQtVersion()));
+
+
+ ProjectExplorer::Target *target = currentProject->activeTarget();
+
+ if (!target)
+ return 0;
+
+ controller->connect(target, SIGNAL(kitChanged()), controller, SLOT(updateActiveQtVersion()));
+ return QtSupport::QtKitInformation::qtVersion(target->kit());
+}
+
+void DesignDocument::updateActiveQtVersion()
+{
+ QtSupport::BaseQtVersion *newQtVersion = getActiveQtVersion(this);
+
+ if (!newQtVersion ) {
+ m_qtVersionId = -1;
+ return;
+ }
+
+ if (m_qtVersionId == newQtVersion->uniqueId())
+ return;
+
+ m_qtVersionId = newQtVersion->uniqueId();
+
+ viewManager().setNodeInstanceViewQtPath(pathToQt());
+}
+
+QString DesignDocument::contextHelpId() const
+{
+ DesignDocumentView view;
+ m_currentModel->attachView(&view);
+
+ QList<ModelNode> nodes = view.selectedModelNodes();
+ QString helpId;
+ if (!nodes.isEmpty()) {
+ helpId = nodes.first().type();
+ helpId.replace("QtQuick", "QML");
+ }
+
+ return helpId;
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/integration/designdocumentcontroller.h b/src/plugins/qmldesigner/components/integration/designdocument.h
index 754020a481..bf89161c36 100644
--- a/src/plugins/qmldesigner/components/integration/designdocumentcontroller.h
+++ b/src/plugins/qmldesigner/components/integration/designdocument.h
@@ -27,14 +27,30 @@
**
****************************************************************************/
-#ifndef DesignDocumentController_h
-#define DesignDocumentController_h
+#ifndef DesignDocument_h
+#define DesignDocument_h
#include "rewriterview.h"
+#include <model.h>
+#include <rewriterview.h>
+#include <itemlibraryview.h>
+#include <navigatorview.h>
+#include <stateseditorview.h>
+#include <formeditorview.h>
+#include <propertyeditor.h>
+#include <componentview.h>
+#include <basetexteditmodifier.h>
+#include <componenttextmodifier.h>
+#include <subcomponentmanager.h>
+#include <model/viewlogger.h>
+#include <viewmanager.h>
+
#include <QObject>
#include <QString>
+#include <QStackedWidget>
+
QT_BEGIN_NAMESPACE
class QUndoStack;
class QWidget;
@@ -46,63 +62,49 @@ QT_END_NAMESPACE
namespace QmlDesigner {
-class Model;
class ModelNode;
class TextModifier;
class QmlObjectNode;
-class RewriterView;
-class ItemLibraryView;
-class NavigatorView;
-class ComponentView;
-class PropertyEditor;
-class StatesEditorView;
-class FormEditorView;
-struct CrumbleBarInfo;
-
-class DesignDocumentController: public QObject
+class CrumbleBarInfo;
+
+class DesignDocument: public QObject
{
Q_OBJECT
-
public:
- DesignDocumentController(QObject *parent);
- ~DesignDocumentController();
+ DesignDocument(QObject *parent = 0);
+ ~DesignDocument();
QString displayName() const;
QString simplfiedDisplayName() const;
- QString fileName() const;
- void setFileName(const QString &fileName);
-
- QList<RewriterView::Error> loadMaster(QPlainTextEdit *edit);
- QList<RewriterView::Error> loadMaster(const QByteArray &qml);
- void loadCurrentModel();
+ QList<RewriterView::Error> loadDocument(QPlainTextEdit *edit);
+ void activateCurrentModel(TextModifier *textModifier);
+ void activateCurrentModel();
+ void activateDocumentModel();
void close();
- bool isDirty() const;
bool isUndoAvailable() const;
bool isRedoAvailable() const;
- Model *model() const;
- Model *masterModel() const;
+ Model *currentModel() const;
+ Model *documentModel() const;
- RewriterView *rewriterView() const;
+ QString contextHelpId() const;
+ QList<RewriterView::Error> qmlSyntaxErrors() const;
+ bool hasQmlSyntaxErrors() const;
- bool isModelSyncBlocked() const;
- void blockModelSync(bool block);
+ RewriterView *rewriterView() const;
- QString contextHelpId() const;
- QList<RewriterView::Error> qmlErrors() const;
+ void setEditor(Core::IEditor *editor);
+ Core::IEditor *editor() const;
- void setItemLibraryView(ItemLibraryView* itemLibraryView);
- void setNavigator(NavigatorView* navigatorView);
- void setPropertyEditorView(PropertyEditor *propertyEditor);
- void setStatesEditorView(StatesEditorView* statesEditorView);
- void setFormEditorView(FormEditorView *formEditorView);
- void setNodeInstanceView(NodeInstanceView *nodeInstanceView);
- void setComponentView(ComponentView *componentView);
+ TextEditor::ITextEditor *textEditor() const;
+ QPlainTextEdit *plainTextEdit() const;
+ QString fileName() const;
+ int qtVersionId() const; // maybe that is not working, because the id should be not cached!!!
+ bool isDocumentLoaded() const;
- void setCrumbleBarInfo(const CrumbleBarInfo &crumbleBarInfo);
- static void setBlockCrumbleBar(bool);
+ void resetToDocumentModel();
signals:
void displayNameChanged(const QString &newFileName);
@@ -116,8 +118,6 @@ signals:
void fileToOpen(const QString &path);
public slots:
- bool save(QWidget *parent = 0);
- void saveAs(QWidget *parent = 0);
void deleteSelected();
void copySelected();
void cutSelected();
@@ -125,41 +125,46 @@ public slots:
void selectAll();
void undo();
void redo();
- void activeQtVersionChanged();
+ void updateActiveQtVersion();
void changeCurrentModelTo(const ModelNode &node);
void changeToSubComponent(const ModelNode &node);
- void changeToExternalSubComponent(const QString &fileName);
+ void changeToExternalSubComponent(const QString &m_oldFileName);
void goIntoComponent();
-#ifdef ENABLE_TEXT_VIEW
- void showText();
- void showForm();
-#endif // ENABLE_TEXT_VIEW
-
private slots:
- void doRealSaveAs(const QString &fileName);
+ void updateFileName(const QString &oldFileName, const QString &newFileName);
-private:
- void detachNodeInstanceView();
- void attachNodeInstanceView();
- void changeToMasterModel();
- QVariant createCrumbleBarInfo();
+private: // functions
+ void changeToDocumentModel();
+ void changeToInFileComponentModel();
QWidget *centralWidget() const;
QString pathToQt() const;
+ const ViewManager &viewManager() const;
+ ViewManager &viewManager();
- class DesignDocumentControllerPrivate *d;
-};
+ ModelNode rootModelNode() const;
+
+ bool loadSubComponent(const ModelNode &componentNode);
+
+private: // variables
+ QWeakPointer<QStackedWidget> m_stackedWidget;
+ QWeakPointer<Model> m_documentModel;
+ QWeakPointer<Model> m_inFileComponentModel;
+ QWeakPointer<Model> m_currentModel;
+ QWeakPointer<Core::IEditor> m_textEditor;
+ QWeakPointer<BaseTextEditModifier> m_documentTextModifier;
+ QWeakPointer<ComponentTextModifier> m_inFileComponentTextModifier;
+ QWeakPointer<SubComponentManager> m_subComponentManager;
+ QWeakPointer<RewriterView> m_rewriterView;
-struct CrumbleBarInfo {
- ModelNode modelNode;
- QString fileName;
+ bool m_documentLoaded;
+ int m_qtVersionId;
};
} // namespace QmlDesigner
-Q_DECLARE_METATYPE(QmlDesigner::CrumbleBarInfo)
-#endif // DesignDocumentController_h
+#endif // DesignDocument_h
diff --git a/src/plugins/qmldesigner/components/integration/designdocumentcontroller.cpp b/src/plugins/qmldesigner/components/integration/designdocumentcontroller.cpp
deleted file mode 100644
index 3c17605a24..0000000000
--- a/src/plugins/qmldesigner/components/integration/designdocumentcontroller.cpp
+++ /dev/null
@@ -1,994 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "designdocumentcontroller.h"
-#include "designdocumentcontrollerview.h"
-#include "xuifiledialog.h"
-#include "componentview.h"
-#include "subcomponentmanager.h"
-#include "model/viewlogger.h"
-
-#include <itemlibraryview.h>
-#include <itemlibrarywidget.h>
-#include <navigatorview.h>
-#include <stateseditorview.h>
-#include <formeditorview.h>
-#include <propertyeditor.h>
-#include <formeditorwidget.h>
-#include <toolbox.h>
-#include <basetexteditmodifier.h>
-#include <componenttextmodifier.h>
-#include <metainfo.h>
-#include <invalidargumentexception.h>
-#include <componentview.h>
-#include <componentaction.h>
-#include <qmlobjectnode.h>
-#include <rewriterview.h>
-#include <rewritingexception.h>
-#include <nodelistproperty.h>
-#include <variantproperty.h>
-#include <rewritingexception.h>
-#include <model/modelnodecontextmenu.h>
-#include <designmodewidget.h>
-
-#include <projectexplorer/projectexplorer.h>
-#include <projectexplorer/project.h>
-#include <projectexplorer/target.h>
-#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
-#include <qtsupport/qtkitinformation.h>
-#include <qtsupport/qtsupportconstants.h>
-#include <qtsupport/qtversionmanager.h>
-#include <utils/crumblepath.h>
-#include <utils/fileutils.h>
-
-#include <QCoreApplication>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QUrl>
-#include <QProcess>
-#include <QTemporaryFile>
-#include <QDebug>
-#include <QEvent>
-
-#include <QBoxLayout>
-#include <QComboBox>
-#include <QErrorMessage>
-#include <QFileDialog>
-#include <QLabel>
-#include <QMdiArea>
-#include <QMdiSubWindow>
-#include <QMessageBox>
-#include <QUndoStack>
-#include <QPlainTextEdit>
-#include <QApplication>
-
-enum {
- debug = false
-};
-
-namespace QmlDesigner {
-
-class DesignDocumentControllerPrivate {
-public:
- QWeakPointer<FormEditorView> formEditorView;
-
- QWeakPointer<ItemLibraryView> itemLibraryView;
- QWeakPointer<NavigatorView> navigator;
- QWeakPointer<PropertyEditor> propertyEditorView;
- QWeakPointer<StatesEditorView> statesEditorView;
- QWeakPointer<QStackedWidget> stackedWidget;
- QWeakPointer<NodeInstanceView> nodeInstanceView;
- QWeakPointer<ComponentView> componentView;
-
- QWeakPointer<QmlDesigner::Model> model;
- QWeakPointer<QmlDesigner::Model> subComponentModel;
- QWeakPointer<QmlDesigner::Model> masterModel;
- QWeakPointer<QPlainTextEdit> textEdit;
- QWeakPointer<RewriterView> rewriterView;
- QmlDesigner::BaseTextEditModifier *textModifier;
- QmlDesigner::ComponentTextModifier *componentTextModifier;
- QWeakPointer<SubComponentManager> subComponentManager;
- QWeakPointer<Internal::ViewLogger> viewLogger;
- ModelNode componentNode;
-
- QString fileName;
- QUrl searchPath;
- bool documentLoaded;
- bool syncBlocked;
- int qt_versionId;
- static bool clearCrumblePath;
- static bool pushCrumblePath;
-};
-
-
-bool DesignDocumentControllerPrivate::clearCrumblePath = true;
-bool DesignDocumentControllerPrivate::pushCrumblePath = true;
-
-
-/**
- \class QmlDesigner::DesignDocumentController
-
- DesignDocumentController acts as a facade to a model representing a qml document,
- and the different views/widgets accessing it.
- */
-DesignDocumentController::DesignDocumentController(QObject *parent) :
- QObject(parent),
- d(new DesignDocumentControllerPrivate)
-{
- d->documentLoaded = false;
- d->syncBlocked = false;
-
- ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
- connect(projectExplorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), this, SLOT(activeQtVersionChanged()));
- activeQtVersionChanged();
-}
-
-DesignDocumentController::~DesignDocumentController()
-{
- delete d->model.data();
- delete d->subComponentModel.data();
-
- delete d->rewriterView.data();
-
- if (d->componentTextModifier) //componentTextModifier might not be created
- delete d->componentTextModifier;
-
- delete d;
-}
-
-Model *DesignDocumentController::model() const
-{
- return d->model.data();
-}
-
-Model *DesignDocumentController::masterModel() const
-{
- return d->masterModel.data();
-}
-
-
-void DesignDocumentController::detachNodeInstanceView()
-{
- if (d->nodeInstanceView)
- model()->detachView(d->nodeInstanceView.data());
-}
-
-void DesignDocumentController::attachNodeInstanceView()
-{
- if (d->nodeInstanceView) {
- model()->attachView(d->nodeInstanceView.data());
- }
- if (d->formEditorView) {
- d->formEditorView->resetView();
- }
-}
-
-void DesignDocumentController::changeToMasterModel()
-{
- d->model->detachView(d->rewriterView.data());
- d->rewriterView->setTextModifier(d->textModifier);
- d->model = d->masterModel;
- d->model->attachView(d->rewriterView.data());
- d->componentNode = d->rewriterView->rootModelNode();
-}
-
-QVariant DesignDocumentController::createCrumbleBarInfo()
-{
- CrumbleBarInfo info;
- info.fileName = fileName();
- info.modelNode = d->componentNode;
- return QVariant::fromValue<CrumbleBarInfo>(info);
-}
-
-QWidget *DesignDocumentController::centralWidget() const
-{
- return qobject_cast<QWidget*>(parent());
-}
-
-QString DesignDocumentController::pathToQt() const
-{
- QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::instance()->version(d->qt_versionId);
- if (activeQtVersion && (activeQtVersion->qtVersion().majorVersion > 3)
- && (activeQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)
- || activeQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)))
- return activeQtVersion->qmakeProperty("QT_INSTALL_DATA");
- return QString();
-}
-
-/*!
- Returns whether the model is automatically updated if the text editor changes.
- */
-bool DesignDocumentController::isModelSyncBlocked() const
-{
- return d->syncBlocked;
-}
-
-/*!
- Switches whether the model (and therefore the views) are updated if the text editor
- changes.
-
- If the synchronization is enabled again, the model is automatically resynchronized
- with the current state of the text editor.
- */
-void DesignDocumentController::blockModelSync(bool block)
-{
- if (d->syncBlocked == block)
- return;
-
- d->syncBlocked = block;
-
- if (d->textModifier) {
- if (d->syncBlocked) {
- detachNodeInstanceView();
- d->textModifier->deactivateChangeSignals();
- } else {
- activeQtVersionChanged();
- changeToMasterModel();
- QmlModelState state;
- //We go back to base state (and back again) to avoid side effects from text editing.
- if (d->statesEditorView && d->statesEditorView->model()) {
- state = d->statesEditorView->currentState();
- d->statesEditorView->setCurrentState(d->statesEditorView->baseState());
-
- }
-
- d->textModifier->reactivateChangeSignals();
-
- if (state.isValid() && d->statesEditorView)
- d->statesEditorView->setCurrentState(state);
- attachNodeInstanceView();
- if (d->propertyEditorView)
- d->propertyEditorView->resetView();
- if (d->formEditorView)
- d->formEditorView->resetView();
- }
- }
-}
-
-/*!
- Returns any errors that happened when parsing the latest qml file.
- */
-QList<RewriterView::Error> DesignDocumentController::qmlErrors() const
-{
- return d->rewriterView->errors();
-}
-
-void DesignDocumentController::setItemLibraryView(ItemLibraryView* itemLibraryView)
-{
- d->itemLibraryView = itemLibraryView;
-}
-
-void DesignDocumentController::setNavigator(NavigatorView* navigatorView)
-{
- d->navigator = navigatorView;
-}
-
-void DesignDocumentController::setPropertyEditorView(PropertyEditor *propertyEditor)
-{
- d->propertyEditorView = propertyEditor;
-}
-
-void DesignDocumentController::setStatesEditorView(StatesEditorView* statesEditorView)
-{
- d->statesEditorView = statesEditorView;
-}
-
-void DesignDocumentController::setFormEditorView(FormEditorView *formEditorView)
-{
- d->formEditorView = formEditorView;
-}
-
-void DesignDocumentController::setNodeInstanceView(NodeInstanceView *nodeInstanceView)
-{
- d->nodeInstanceView = nodeInstanceView;
-}
-
-void DesignDocumentController::setComponentView(ComponentView *componentView)
-{
- d->componentView = componentView;
- connect(d->componentView->action(), SIGNAL(currentComponentChanged(ModelNode)), SLOT(changeCurrentModelTo(ModelNode)));
-}
-
-static inline bool compareCrumbleBarInfo(const CrumbleBarInfo &crumbleBarInfo1, const CrumbleBarInfo &crumbleBarInfo2)
-{
- return crumbleBarInfo1.fileName == crumbleBarInfo2.fileName && crumbleBarInfo1.modelNode == crumbleBarInfo2.modelNode;
-}
-
-void DesignDocumentController::setCrumbleBarInfo(const CrumbleBarInfo &crumbleBarInfo)
-{
- DesignDocumentControllerPrivate::clearCrumblePath = false;
- DesignDocumentControllerPrivate::pushCrumblePath = false;
- while (!compareCrumbleBarInfo(d->formEditorView->crumblePath()->dataForLastIndex().value<CrumbleBarInfo>(), crumbleBarInfo))
- d->formEditorView->crumblePath()->popElement();
- Core::EditorManager::openEditor(crumbleBarInfo.fileName);
- DesignDocumentControllerPrivate::pushCrumblePath = true;
- Internal::DesignModeWidget::instance()->currentDesignDocumentController()->changeToSubComponent(crumbleBarInfo.modelNode);
- DesignDocumentControllerPrivate::clearCrumblePath = true;
-}
-
-void DesignDocumentController::setBlockCrumbleBar(bool b)
-{
- DesignDocumentControllerPrivate::clearCrumblePath = !b;
- DesignDocumentControllerPrivate::pushCrumblePath = !b;
-}
-
-QString DesignDocumentController::displayName() const
-{
- if (fileName().isEmpty())
- return tr("-New Form-");
- else
- return fileName();
-}
-
-QString DesignDocumentController::simplfiedDisplayName() const
-{
- if (!d->componentNode.isRootNode()) {
- if (d->componentNode.id().isEmpty()) {
- if (d->formEditorView->rootModelNode().id().isEmpty()) {
- return d->formEditorView->rootModelNode().simplifiedTypeName();
- }
- return d->formEditorView->rootModelNode().id();
- }
- return d->componentNode.id();
- }
-
- QStringList list = displayName().split(QLatin1Char('/'));
- return list.last();
-}
-
-QString DesignDocumentController::fileName() const
-{
- return d->fileName;
-}
-
-void DesignDocumentController::setFileName(const QString &fileName)
-{
- d->fileName = fileName;
-
- if (QFileInfo(fileName).exists()) {
- d->searchPath = QUrl::fromLocalFile(fileName);
- } else {
- d->searchPath = QUrl(fileName);
- }
-
- if (d->model)
- d->model->setFileUrl(d->searchPath);
-
- if (d->itemLibraryView)
- d->itemLibraryView->widget()->setResourcePath(QFileInfo(fileName).absolutePath());
- emit displayNameChanged(displayName());
-}
-
-QList<RewriterView::Error> DesignDocumentController::loadMaster(QPlainTextEdit *edit)
-{
- Q_CHECK_PTR(edit);
-
- d->textEdit = edit;
-
- connect(edit, SIGNAL(undoAvailable(bool)),
- this, SIGNAL(undoAvailable(bool)));
- connect(edit, SIGNAL(redoAvailable(bool)),
- this, SIGNAL(redoAvailable(bool)));
- connect(edit, SIGNAL(modificationChanged(bool)),
- this, SIGNAL(dirtyStateChanged(bool)));
-
- d->textModifier = new BaseTextEditModifier(dynamic_cast<TextEditor::BaseTextEditorWidget*>(d->textEdit.data()));
-
- d->componentTextModifier = 0;
-
- //d->masterModel = Model::create(d->textModifier, d->searchPath, errors);
-
- d->masterModel = Model::create("QtQuick.Rectangle", 1, 0);
-
-#if defined(VIEWLOGGER)
- d->viewLogger = new Internal::ViewLogger(d->model.data());
- d->masterModel->attachView(d->viewLogger.data());
-#endif
-
- d->masterModel->setFileUrl(d->searchPath);
-
- d->subComponentModel = Model::create("QtQuick.Rectangle", 1, 0);
- d->subComponentModel->setFileUrl(d->searchPath);
-
- d->rewriterView = new RewriterView(RewriterView::Amend, d->masterModel.data());
- d->rewriterView->setTextModifier( d->textModifier);
- connect(d->rewriterView.data(), SIGNAL(errorsChanged(QList<RewriterView::Error>)),
- this, SIGNAL(qmlErrorsChanged(QList<RewriterView::Error>)));
-
- d->masterModel->attachView(d->rewriterView.data());
- d->model = d->masterModel;
- d->componentNode = d->rewriterView->rootModelNode();
-
- d->subComponentManager = new SubComponentManager(d->masterModel.data(), this);
- d->subComponentManager->update(d->searchPath, d->model->imports());
-
- loadCurrentModel();
-
- d->masterModel->attachView(d->componentView.data());
-
- return d->rewriterView->errors();
-}
-
-void DesignDocumentController::changeCurrentModelTo(const ModelNode &node)
-{
- if (d->componentNode == node)
- return;
- if (Internal::DesignModeWidget::instance()->currentDesignDocumentController() != this)
- return;
- DesignDocumentControllerPrivate::clearCrumblePath = false;
- while (d->formEditorView->crumblePath()->dataForLastIndex().value<CrumbleBarInfo>().modelNode.isValid() &&
- !d->formEditorView->crumblePath()->dataForLastIndex().value<CrumbleBarInfo>().modelNode.isRootNode())
- d->formEditorView->crumblePath()->popElement();
- if (node.isRootNode() && d->formEditorView->crumblePath()->dataForLastIndex().isValid())
- d->formEditorView->crumblePath()->popElement();
- changeToSubComponent(node);
- DesignDocumentControllerPrivate::clearCrumblePath = true;
-}
-
-void DesignDocumentController::changeToSubComponent(const ModelNode &componentNode)
-{
- Q_ASSERT(d->masterModel);
- QWeakPointer<Model> oldModel = d->model;
- Q_ASSERT(oldModel.data());
-
- if (d->model == d->subComponentModel) {
- changeToMasterModel();
- }
-
- QString componentText = d->rewriterView->extractText(QList<ModelNode>() << componentNode).value(componentNode);
-
- if (componentText.isEmpty())
- return;
-
- bool explicitComponent = false;
- if (componentText.contains("Component")) { //explicit component
- explicitComponent = true;
- }
-
- d->componentNode = componentNode;
- if (!componentNode.isRootNode()) {
- Q_ASSERT(d->model == d->masterModel);
- Q_ASSERT(componentNode.isValid());
- //change to subcomponent model
- ModelNode rootModelNode = componentNode.view()->rootModelNode();
- Q_ASSERT(rootModelNode.isValid());
- if (d->componentTextModifier)
- delete d->componentTextModifier;
-
-
- int componentStartOffset;
- int componentEndOffset;
-
- int rootStartOffset = d->rewriterView->nodeOffset(rootModelNode);
-
- if (explicitComponent) { //the component is explciit we have to find the first definition inside
- componentStartOffset = d->rewriterView->firstDefinitionInsideOffset(componentNode);
- componentEndOffset = componentStartOffset + d->rewriterView->firstDefinitionInsideLength(componentNode);
- } else { //the component is implicit
- componentStartOffset = d->rewriterView->nodeOffset(componentNode);
- componentEndOffset = componentStartOffset + d->rewriterView->nodeLength(componentNode);
- }
-
- d->componentTextModifier = new ComponentTextModifier (d->textModifier, componentStartOffset, componentEndOffset, rootStartOffset);
-
-
- d->model->detachView(d->rewriterView.data());
-
- d->rewriterView->setTextModifier(d->componentTextModifier);
-
- d->subComponentModel->attachView(d->rewriterView.data());
-
- Q_ASSERT(d->rewriterView->rootModelNode().isValid());
-
- d->model = d->subComponentModel;
- }
-
- Q_ASSERT(d->masterModel);
- Q_ASSERT(d->model);
-
- loadCurrentModel();
- d->componentView->setComponentNode(componentNode);
-}
-
-void DesignDocumentController::changeToExternalSubComponent(const QString &fileName)
-{
- DesignDocumentControllerPrivate::clearCrumblePath = false;
- Core::EditorManager::openEditor(fileName);
- DesignDocumentControllerPrivate::clearCrumblePath = true;
-}
-
-void DesignDocumentController::goIntoComponent()
-{
- if (!d->model)
- return;
-
- QList<ModelNode> selectedNodes;
- if (d->formEditorView)
- selectedNodes = d->formEditorView->selectedModelNodes();
-
- DesignDocumentControllerPrivate::clearCrumblePath = false;
- if (selectedNodes.count() == 1)
- ModelNodeAction::goIntoComponent(selectedNodes.first());
- DesignDocumentControllerPrivate::clearCrumblePath = true;
-}
-
-void DesignDocumentController::loadCurrentModel()
-{
- QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
-
- Q_ASSERT(d->masterModel);
- Q_ASSERT(d->model);
- d->model->setMasterModel(d->masterModel.data());
- d->masterModel->attachView(d->componentView.data());
-
- d->nodeInstanceView->setPathToQt(pathToQt());
- d->model->attachView(d->nodeInstanceView.data());
- d->model->attachView(d->navigator.data());
- d->itemLibraryView->widget()->setResourcePath(QFileInfo(d->fileName).absolutePath());
-
- d->model->attachView(d->formEditorView.data());
- d->model->attachView(d->itemLibraryView.data());
-
- if (!d->textEdit->parent()) // hack to prevent changing owner of external text edit
- d->stackedWidget->addWidget(d->textEdit.data());
-
- // Will call setCurrentState (formEditorView etc has to be constructed first)
- d->model->attachView(d->statesEditorView.data());
-
- d->model->attachView(d->propertyEditorView.data());
-
-
- if (DesignDocumentControllerPrivate::clearCrumblePath)
- d->formEditorView->crumblePath()->clear();
-
- if (DesignDocumentControllerPrivate::pushCrumblePath &&
- !compareCrumbleBarInfo(d->formEditorView->crumblePath()->dataForLastIndex().value<CrumbleBarInfo>(),
- createCrumbleBarInfo().value<CrumbleBarInfo>()))
- d->formEditorView->crumblePath()->pushElement(simplfiedDisplayName(), createCrumbleBarInfo());
-
- d->documentLoaded = true;
- d->subComponentManager->update(d->searchPath, d->model->imports());
- Q_ASSERT(d->masterModel);
- QApplication::restoreOverrideCursor();
-}
-
-QList<RewriterView::Error> DesignDocumentController::loadMaster(const QByteArray &qml)
-{
- QPlainTextEdit *textEdit = new QPlainTextEdit;
- textEdit->setReadOnly(true);
- textEdit->setPlainText(QString(qml));
- return loadMaster(textEdit);
-}
-
-void DesignDocumentController::saveAs(QWidget *parent)
-{
- QFileInfo oldFileInfo(d->fileName);
- XUIFileDialog::runSaveFileDialog(oldFileInfo.path(), parent, this, SLOT(doRealSaveAs(QString)));
-}
-
-void DesignDocumentController::doRealSaveAs(const QString &fileName)
-{
- if (fileName.isNull())
- return;
-
- QFileInfo fileInfo(fileName);
- if (fileInfo.exists() && !fileInfo.isWritable()) {
- QMessageBox msgBox(centralWidget());
- msgBox.setIcon(QMessageBox::Warning);
- msgBox.setText(tr("Cannot save to file \"%1\": permission denied.").arg(fileInfo.baseName()));
- msgBox.exec();
- return;
- } else if (!fileInfo.exists() && !fileInfo.dir().exists()) {
- QMessageBox msgBox(centralWidget());
- msgBox.setIcon(QMessageBox::Warning);
- msgBox.setText(tr("Parent folder \"%1\" for file \"%2\" does not exist.")
- .arg(fileInfo.dir().dirName())
- .arg(fileInfo.baseName()));
- msgBox.exec();
- return;
- }
-
- setFileName(fileName);
- save(centralWidget());
-}
-
-bool DesignDocumentController::isDirty() const
-{
- if (d->textEdit)
- return d->textEdit->document()->isModified();
- else
- return false;
-}
-
-bool DesignDocumentController::isUndoAvailable() const
-{
-
- if (d->textEdit)
- return d->textEdit->document()->isUndoAvailable();
- return false;
-}
-
-bool DesignDocumentController::isRedoAvailable() const
-{
- if (d->textEdit)
- return d->textEdit->document()->isRedoAvailable();
- return false;
-}
-
-void DesignDocumentController::close()
-{
- d->documentLoaded = false;
- emit designDocumentClosed();
-}
-
-void DesignDocumentController::deleteSelected()
-{
- if (!d->model)
- return;
-
- try {
- if (d->formEditorView) {
- RewriterTransaction transaction(d->formEditorView.data());
- QList<ModelNode> toDelete = d->formEditorView->selectedModelNodes();
- foreach (ModelNode node, toDelete) {
- if (node.isValid() && !node.isRootNode() && QmlObjectNode(node).isValid())
- QmlObjectNode(node).destroy();
- }
- }
- } catch (RewritingException &e) {
- QMessageBox::warning(0, tr("Error"), e.description());
- }
-}
-
-void DesignDocumentController::copySelected()
-{
- QScopedPointer<Model> model(Model::create("QtQuick.Rectangle", 1, 0, this->model()));
- model->setFileUrl(d->model->fileUrl());
- model->changeImports(d->model->imports(), QList<Import>());
-
- Q_ASSERT(model);
-
- DesignDocumentControllerView view;
-
- d->model->attachView(&view);
-
- if (view.selectedModelNodes().isEmpty())
- return;
-
- QList<ModelNode> selectedNodes(view.selectedModelNodes());
-
- foreach (const ModelNode &node, selectedNodes) {
- foreach (const ModelNode &node2, selectedNodes) {
- if (node.isAncestorOf(node2))
- selectedNodes.removeAll(node2);
- }
- }
-
- if (selectedNodes.count() == 1) {
- ModelNode selectedNode(selectedNodes.first());
-
- if (!selectedNode.isValid())
- return;
-
- d->model->detachView(&view);
-
- model->attachView(&view);
- view.replaceModel(selectedNode);
-
- Q_ASSERT(view.rootModelNode().isValid());
- Q_ASSERT(view.rootModelNode().type() != "empty");
-
- view.toClipboard();
- } else { //multi items selected
- d->model->detachView(&view);
- model->attachView(&view);
-
- foreach (ModelNode node, view.rootModelNode().allDirectSubModelNodes()) {
- node.destroy();
- }
- view.changeRootNodeType("QtQuick.Rectangle", 1, 0);
- view.rootModelNode().setId("designer__Selection");
-
- foreach (const ModelNode &selectedNode, selectedNodes) {
- ModelNode newNode(view.insertModel(selectedNode));
- view.rootModelNode().nodeListProperty("data").reparentHere(newNode);
- }
-
- view.toClipboard();
- }
-}
-
-void DesignDocumentController::cutSelected()
-{
- copySelected();
- deleteSelected();
-}
-
-static void scatterItem(ModelNode pastedNode, const ModelNode targetNode, int offset = -2000)
-{
-
- bool scatter = false;
- foreach (const ModelNode &childNode, targetNode.allDirectSubModelNodes()) {
- if ((childNode.variantProperty("x").value() == pastedNode.variantProperty("x").value()) &&
- (childNode.variantProperty("y").value() == pastedNode.variantProperty("y").value()))
- scatter = true;
- }
- if (!scatter)
- return;
-
- if (offset == -2000) {
- double x = pastedNode.variantProperty("x").value().toDouble();
- double y = pastedNode.variantProperty("y").value().toDouble();
- double targetWidth = 20;
- double targetHeight = 20;
- x = x + double(qrand()) / RAND_MAX * targetWidth - targetWidth / 2;
- y = y + double(qrand()) / RAND_MAX * targetHeight - targetHeight / 2;
- pastedNode.variantProperty("x") = int(x);
- pastedNode.variantProperty("y") = int(y);
- } else {
- double x = pastedNode.variantProperty("x").value().toDouble();
- double y = pastedNode.variantProperty("y").value().toDouble();
- x = x + offset;
- y = y + offset;
- pastedNode.variantProperty("x") = int(x);
- pastedNode.variantProperty("y") = int(y);
- }
-}
-
-void DesignDocumentController::paste()
-{
- QScopedPointer<Model> model(Model::create("empty", 1, 0, this->model()));
- model->setFileUrl(d->model->fileUrl());
- model->changeImports(d->model->imports(), QList<Import>());
-
- Q_ASSERT(model);
-
- if (!d->model)
- return;
-
- DesignDocumentControllerView view;
- model->attachView(&view);
-
- view.fromClipboard();
-
- ModelNode rootNode(view.rootModelNode());
-
- if (rootNode.type() == "empty")
- return;
-
- if (rootNode.id() == "designer__Selection") {
- QList<ModelNode> selectedNodes = rootNode.allDirectSubModelNodes();
- qDebug() << rootNode;
- qDebug() << selectedNodes;
- model->detachView(&view);
- d->model->attachView(&view);
-
- ModelNode targetNode;
-
- if (!view.selectedModelNodes().isEmpty())
- targetNode = view.selectedModelNodes().first();
-
- //In case we copy and paste a selection we paste in the parent item
- if ((view.selectedModelNodes().count() == selectedNodes.count()) && targetNode.isValid() && targetNode.parentProperty().isValid()) {
- targetNode = targetNode.parentProperty().parentModelNode();
- }
-
- if (!targetNode.isValid())
- targetNode = view.rootModelNode();
-
- foreach (const ModelNode &node, selectedNodes) {
- foreach (const ModelNode &node2, selectedNodes) {
- if (node.isAncestorOf(node2))
- selectedNodes.removeAll(node2);
- }
- }
-
- QList<ModelNode> pastedNodeList;
-
- try {
- RewriterTransaction transaction(d->formEditorView.data());
-
- int offset = double(qrand()) / RAND_MAX * 20 - 10;
-
- foreach (const ModelNode &node, selectedNodes) {
- QString defaultProperty(targetNode.metaInfo().defaultPropertyName());
- ModelNode pastedNode(view.insertModel(node));
- pastedNodeList.append(pastedNode);
- scatterItem(pastedNode, targetNode, offset);
- targetNode.nodeListProperty(defaultProperty).reparentHere(pastedNode);
- }
-
- view.setSelectedModelNodes(pastedNodeList);
- } catch (RewritingException &e) {
- qWarning() << e.description(); //silent error
- }
- } else {
- try {
- RewriterTransaction transaction(d->formEditorView.data());
-
- model->detachView(&view);
- d->model->attachView(&view);
- ModelNode pastedNode(view.insertModel(rootNode));
- ModelNode targetNode;
-
- if (!view.selectedModelNodes().isEmpty())
- targetNode = view.selectedModelNodes().first();
-
- if (!targetNode.isValid())
- targetNode = view.rootModelNode();
-
- if (targetNode.parentProperty().isValid() &&
- (pastedNode.simplifiedTypeName() == targetNode.simplifiedTypeName()) &&
- (pastedNode.variantProperty("width").value() == targetNode.variantProperty("width").value()) &&
- (pastedNode.variantProperty("height").value() == targetNode.variantProperty("height").value()))
-
- targetNode = targetNode.parentProperty().parentModelNode();
-
- QString defaultProperty(targetNode.metaInfo().defaultPropertyName());
-
- scatterItem(pastedNode, targetNode);
- if (targetNode.nodeListProperty(defaultProperty).isValid()) {
- targetNode.nodeListProperty(defaultProperty).reparentHere(pastedNode);
- }
-
- transaction.commit();
- NodeMetaInfo::clearCache();
-
- view.setSelectedModelNodes(QList<ModelNode>() << pastedNode);
- } catch (RewritingException &e) {
- qWarning() << e.description(); //silent error
- }
- }
-}
-
-void DesignDocumentController::selectAll()
-{
- if (!d->model)
- return;
-
- DesignDocumentControllerView view;
- d->model->attachView(&view);
-
-
- QList<ModelNode> allNodesExceptRootNode(view.allModelNodes());
- allNodesExceptRootNode.removeOne(view.rootModelNode());
- view.setSelectedModelNodes(allNodesExceptRootNode);
-}
-
-RewriterView *DesignDocumentController::rewriterView() const
-{
- return d->rewriterView.data();
-}
-
-void DesignDocumentController::undo()
-{
- if (d->rewriterView && !d->rewriterView->modificationGroupActive())
- d->textEdit->undo();
- d->propertyEditorView->resetView();
-}
-
-void DesignDocumentController::redo()
-{
- if (d->rewriterView && !d->rewriterView->modificationGroupActive())
- d->textEdit->redo();
- d->propertyEditorView->resetView();
-}
-
-static inline QtSupport::BaseQtVersion *getActiveQtVersion(DesignDocumentController *controller)
-{
- ProjectExplorer::ProjectExplorerPlugin *projectExplorer = ProjectExplorer::ProjectExplorerPlugin::instance();
- ProjectExplorer::Project *currentProject = projectExplorer->currentProject();
-
- if (!currentProject)
- return 0;
-
- controller->disconnect(controller, SLOT(activeQtVersionChanged()));
- controller->connect(projectExplorer, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), controller, SLOT(activeQtVersionChanged()));
-
- controller->connect(currentProject, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)), controller, SLOT(activeQtVersionChanged()));
-
-
- ProjectExplorer::Target *target = currentProject->activeTarget();
-
- if (!target)
- return 0;
-
- controller->connect(target, SIGNAL(kitChanged()), controller, SLOT(activeQtVersionChanged()));
- return QtSupport::QtKitInformation::qtVersion(target->kit());
-}
-
-void DesignDocumentController::activeQtVersionChanged()
-{
- QtSupport::BaseQtVersion *newQtVersion = getActiveQtVersion(this);
-
- if (!newQtVersion ) {
- d->qt_versionId = -1;
- return;
- }
-
- if (d->qt_versionId == newQtVersion->uniqueId())
- return;
-
- d->qt_versionId = newQtVersion->uniqueId();
-
- if (d->nodeInstanceView)
- d->nodeInstanceView->setPathToQt(pathToQt());
-}
-
-#ifdef ENABLE_TEXT_VIEW
-void DesignDocumentController::showText()
-{
- d->stackedWidget->setCurrentWidget(d->textEdit.data());
-}
-#endif // ENABLE_TEXT_VIEW
-
-#ifdef ENABLE_TEXT_VIEW
-void DesignDocumentController::showForm()
-{
- d->stackedWidget->setCurrentWidget(d->formEditorView->widget());
-}
-#endif // ENABLE_TEXT_VIEW
-
-bool DesignDocumentController::save(QWidget *parent)
-{
- // qDebug() << "Saving document to file \"" << d->fileName << "\"...";
- //
- if (d->fileName.isEmpty()) {
- saveAs(parent);
- return true;
- }
- Utils::FileSaver saver(d->fileName, QIODevice::Text);
- if (d->model)
- saver.write(d->textEdit->toPlainText().toLatin1());
- if (!saver.finalize(parent ? parent : d->stackedWidget.data()))
- return false;
- if (d->model)
- d->textEdit->setPlainText(d->textEdit->toPlainText()); // clear undo/redo history
-
- return true;
-}
-
-
-QString DesignDocumentController::contextHelpId() const
-{
- DesignDocumentControllerView view;
- d->model->attachView(&view);
-
- QList<ModelNode> nodes = view.selectedModelNodes();
- QString helpId;
- if (!nodes.isEmpty()) {
- helpId = nodes.first().type();
- helpId.replace("QtQuick", "QML");
- }
-
- return helpId;
-}
-
-} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/integration/designdocumentcontrollerview.cpp b/src/plugins/qmldesigner/components/integration/designdocumentview.cpp
index a7bf9b8045..f82e7f5c8a 100644
--- a/src/plugins/qmldesigner/components/integration/designdocumentcontrollerview.cpp
+++ b/src/plugins/qmldesigner/components/integration/designdocumentview.cpp
@@ -27,7 +27,7 @@
**
****************************************************************************/
-#include "designdocumentcontrollerview.h"
+#include "designdocumentview.h"
#include <rewriterview.h>
#include <basetexteditmodifier.h>
#include <metainfo.h>
@@ -40,79 +40,88 @@
namespace QmlDesigner {
-void DesignDocumentControllerView::nodeCreated(const ModelNode & /*createdNode*/) {}
-void DesignDocumentControllerView::nodeAboutToBeRemoved(const ModelNode & /*removedNode*/) {}
-void DesignDocumentControllerView::nodeRemoved(const ModelNode & /*removedNode*/, const NodeAbstractProperty & /*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void DesignDocumentControllerView::nodeAboutToBeReparented(const ModelNode & /*node*/, const NodeAbstractProperty & /*newPropertyParent*/, const NodeAbstractProperty & /*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void DesignDocumentControllerView::nodeReparented(const ModelNode & /*node*/, const NodeAbstractProperty & /*newPropertyParent*/, const NodeAbstractProperty & /*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void DesignDocumentControllerView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
-void DesignDocumentControllerView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
-void DesignDocumentControllerView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
-void DesignDocumentControllerView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void DesignDocumentControllerView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
-void DesignDocumentControllerView::rootNodeTypeChanged(const QString & /*type*/, int /*majorVersion*/, int /*minorVersion*/) {}
-
-void DesignDocumentControllerView::selectedNodesChanged(const QList<ModelNode> & /*selectedNodeList*/,
+DesignDocumentView::DesignDocumentView(QObject *parent)
+ : AbstractView(parent), m_modelMerger(this)
+{
+}
+
+DesignDocumentView::~DesignDocumentView()
+{
+}
+
+void DesignDocumentView::nodeCreated(const ModelNode & /*createdNode*/) {}
+void DesignDocumentView::nodeAboutToBeRemoved(const ModelNode & /*removedNode*/) {}
+void DesignDocumentView::nodeRemoved(const ModelNode & /*removedNode*/, const NodeAbstractProperty & /*parentProperty*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
+void DesignDocumentView::nodeAboutToBeReparented(const ModelNode & /*node*/, const NodeAbstractProperty & /*newPropertyParent*/, const NodeAbstractProperty & /*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
+void DesignDocumentView::nodeReparented(const ModelNode & /*node*/, const NodeAbstractProperty & /*newPropertyParent*/, const NodeAbstractProperty & /*oldPropertyParent*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
+void DesignDocumentView::nodeIdChanged(const ModelNode& /*node*/, const QString& /*newId*/, const QString& /*oldId*/) {}
+void DesignDocumentView::propertiesAboutToBeRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
+void DesignDocumentView::propertiesRemoved(const QList<AbstractProperty>& /*propertyList*/) {}
+void DesignDocumentView::variantPropertiesChanged(const QList<VariantProperty>& /*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
+void DesignDocumentView::bindingPropertiesChanged(const QList<BindingProperty>& /*propertyList*/, AbstractView::PropertyChangeFlags /*propertyChange*/) {}
+void DesignDocumentView::rootNodeTypeChanged(const QString & /*type*/, int /*majorVersion*/, int /*minorVersion*/) {}
+
+void DesignDocumentView::selectedNodesChanged(const QList<ModelNode> & /*selectedNodeList*/,
const QList<ModelNode> & /*lastSelectedNodeList*/) {}
-void DesignDocumentControllerView::nodeOrderChanged(const NodeListProperty & /*listProperty*/, const ModelNode & /*movedNode*/, int /*oldIndex*/) {}
+void DesignDocumentView::nodeOrderChanged(const NodeListProperty & /*listProperty*/, const ModelNode & /*movedNode*/, int /*oldIndex*/) {}
-void DesignDocumentControllerView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/)
+void DesignDocumentView::scriptFunctionsChanged(const ModelNode &/*node*/, const QStringList &/*scriptFunctionList*/)
{
}
-void DesignDocumentControllerView::instancePropertyChange(const QList<QPair<ModelNode, QString> > &/*propertyList*/)
+void DesignDocumentView::instancePropertyChange(const QList<QPair<ModelNode, QString> > &/*propertyList*/)
{
}
-void DesignDocumentControllerView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
+void DesignDocumentView::instancesCompleted(const QVector<ModelNode> &/*completedNodeList*/)
{
}
-void DesignDocumentControllerView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
+void DesignDocumentView::instanceInformationsChange(const QMultiHash<ModelNode, InformationName> &/*informationChangeHash*/)
{
}
-void DesignDocumentControllerView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
+void DesignDocumentView::instancesRenderImageChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
-void DesignDocumentControllerView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
+void DesignDocumentView::instancesPreviewImageChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
-void DesignDocumentControllerView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
+void DesignDocumentView::instancesChildrenChanged(const QVector<ModelNode> &/*nodeList*/)
{
}
-void DesignDocumentControllerView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
+void DesignDocumentView::instancesToken(const QString &/*tokenName*/, int /*tokenNumber*/, const QVector<ModelNode> &/*nodeVector*/)
{
}
-void DesignDocumentControllerView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
+void DesignDocumentView::nodeSourceChanged(const ModelNode &, const QString & /*newNodeSource*/)
{
}
-void DesignDocumentControllerView::rewriterBeginTransaction()
+void DesignDocumentView::rewriterBeginTransaction()
{
}
-void DesignDocumentControllerView::rewriterEndTransaction()
+void DesignDocumentView::rewriterEndTransaction()
{
}
-void DesignDocumentControllerView::actualStateChanged(const ModelNode &/*node*/)
+void DesignDocumentView::actualStateChanged(const ModelNode &/*node*/)
{
}
-void DesignDocumentControllerView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
+void DesignDocumentView::importsChanged(const QList<Import> &/*addedImports*/, const QList<Import> &/*removedImports*/)
{
}
@@ -131,7 +140,7 @@ static QByteArray stringListToArray(const QStringList &stringList)
return str.toLatin1();
}
-void DesignDocumentControllerView::toClipboard() const
+void DesignDocumentView::toClipboard() const
{
QClipboard *clipboard = QApplication::clipboard();
@@ -146,7 +155,7 @@ void DesignDocumentControllerView::toClipboard() const
clipboard->setMimeData(data);
}
-void DesignDocumentControllerView::fromClipboard()
+void DesignDocumentView::fromClipboard()
{
QClipboard *clipboard = QApplication::clipboard();
fromText(clipboard->text());
@@ -158,7 +167,7 @@ void DesignDocumentControllerView::fromClipboard()
}
-QString DesignDocumentControllerView::toText() const
+QString DesignDocumentView::toText() const
{
QScopedPointer<Model> outputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
outputModel->setFileUrl(model()->fileUrl());
@@ -178,7 +187,7 @@ QString DesignDocumentControllerView::toText() const
QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
rewriterView->setCheckSemanticErrors(false);
rewriterView->setTextModifier(&modifier);
- outputModel->attachView(rewriterView.data());
+ outputModel->setRewriterView(rewriterView.data());
ModelMerger merger(rewriterView.data());
@@ -190,7 +199,7 @@ QString DesignDocumentControllerView::toText() const
return rewriterView->extractText(QList<ModelNode>() << rewriterNode).value(rewriterNode);
}
-void DesignDocumentControllerView::fromText(QString text)
+void DesignDocumentView::fromText(QString text)
{
QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
inputModel->setFileUrl(model()->fileUrl());
@@ -205,7 +214,7 @@ void DesignDocumentControllerView::fromText(QString text)
QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
rewriterView->setCheckSemanticErrors(false);
rewriterView->setTextModifier(&modifier);
- inputModel->attachView(rewriterView.data());
+ inputModel->setRewriterView(rewriterView.data());
if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
ModelMerger merger(this);
@@ -213,4 +222,9 @@ void DesignDocumentControllerView::fromText(QString text)
}
}
+QWidget *DesignDocumentView::widget()
+{
+ return 0;
+}
+
}// namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/integration/designdocumentcontrollerview.h b/src/plugins/qmldesigner/components/integration/designdocumentview.h
index eecccc5847..1739907b9e 100644
--- a/src/plugins/qmldesigner/components/integration/designdocumentcontrollerview.h
+++ b/src/plugins/qmldesigner/components/integration/designdocumentview.h
@@ -27,20 +27,20 @@
**
****************************************************************************/
-#ifndef DESIGNDOCUMENTCONTROLLERVIEW_H
-#define DESIGNDOCUMENTCONTROLLERVIEW_H
+#ifndef DesignDocumentVIEW_H
+#define DesignDocumentVIEW_H
#include <abstractview.h>
#include <modelmerger.h>
namespace QmlDesigner {
-class DesignDocumentControllerView : public AbstractView
+class DesignDocumentView : public AbstractView
{
Q_OBJECT
public:
- DesignDocumentControllerView(QObject *parent = 0)
- : AbstractView(parent), m_modelMerger(this) {}
+ DesignDocumentView(QObject *parent = 0);
+ ~DesignDocumentView();
virtual void nodeCreated(const ModelNode &createdNode);
virtual void nodeAboutToBeRemoved(const ModelNode &removedNode);
@@ -87,10 +87,12 @@ public:
QString toText() const;
void fromText(QString text);
+ QWidget *widget();
+
private:
ModelMerger m_modelMerger;
};
}// namespace QmlDesigner
-#endif // DESIGNDOCUMENTCONTROLLERVIEW_H
+#endif // DesignDocumentVIEW_H
diff --git a/src/plugins/qmldesigner/components/integration/integration.pri b/src/plugins/qmldesigner/components/integration/integration.pri
index 1548688998..586bf12324 100644
--- a/src/plugins/qmldesigner/components/integration/integration.pri
+++ b/src/plugins/qmldesigner/components/integration/integration.pri
@@ -1,9 +1,8 @@
VPATH += $$PWD
INCLUDEPATH += $$PWD
SOURCES += \
- integrationcore.cpp \
- designdocumentcontroller.cpp \
- designdocumentcontrollerview.cpp \
+ designdocument.cpp \
+ designdocumentview.cpp \
utilitypanelcontroller.cpp \
stackedutilitypanelcontroller.cpp \
componentaction.cpp \
@@ -11,9 +10,8 @@ SOURCES += \
xuifiledialog.cpp
HEADERS += \
- integrationcore.h \
- designdocumentcontrollerview.h \
- designdocumentcontroller.h \
+ designdocumentview.h \
+ designdocument.h \
utilitypanelcontroller.h \
stackedutilitypanelcontroller.h \
componentaction.h \
diff --git a/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.cpp b/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.cpp
index 428ff3a364..6d86f46685 100644
--- a/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.cpp
+++ b/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.cpp
@@ -29,7 +29,7 @@
#include <QStackedWidget>
-#include "designdocumentcontroller.h"
+#include "designdocument.h"
#include "stackedutilitypanelcontroller.h"
namespace QmlDesigner {
@@ -43,12 +43,12 @@ StackedUtilityPanelController::StackedUtilityPanelController(QObject* parent):
m_stackedWidget->setFrameStyle(QFrame::NoFrame);
}
-void StackedUtilityPanelController::show(DesignDocumentController* designDocumentController)
+void StackedUtilityPanelController::show(DesignDocument* DesignDocument)
{
- if (!designDocumentController)
+ if (!DesignDocument)
return;
- QWidget* page = stackedPageWidget(designDocumentController);
+ QWidget* page = stackedPageWidget(DesignDocument);
if (!m_stackedWidget->children().contains(page))
m_stackedWidget->addWidget(page);
@@ -57,9 +57,9 @@ void StackedUtilityPanelController::show(DesignDocumentController* designDocumen
page->show();
}
-void StackedUtilityPanelController::close(DesignDocumentController* designDocumentController)
+void StackedUtilityPanelController::close(DesignDocument* DesignDocument)
{
- QWidget* page = stackedPageWidget(designDocumentController);
+ QWidget* page = stackedPageWidget(DesignDocument);
if (m_stackedWidget->children().contains(page)) {
page->hide();
diff --git a/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.h b/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.h
index 0845e5c30f..969532fa9f 100644
--- a/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.h
+++ b/src/plugins/qmldesigner/components/integration/stackedutilitypanelcontroller.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class DesignDocumentController;
+class DesignDocument;
class StackedUtilityPanelController : public UtilityPanelController
{
@@ -44,12 +44,12 @@ public:
StackedUtilityPanelController(QObject* parent = 0);
public slots:
- void show(DesignDocumentController* designDocumentController);
- void close(DesignDocumentController* designDocumentController);
+ void show(DesignDocument* DesignDocument);
+ void close(DesignDocument* DesignDocument);
protected:
virtual QWidget* contentWidget() const;
- virtual QWidget* stackedPageWidget(DesignDocumentController* designDocumentController) const = 0;
+ virtual QWidget* stackedPageWidget(DesignDocument* DesignDocument) const = 0;
private:
class QStackedWidget* m_stackedWidget;
diff --git a/src/plugins/qmldesigner/components/integration/xuifiledialog.cpp b/src/plugins/qmldesigner/components/integration/xuifiledialog.cpp
index 3c3191cabc..3fed00cd85 100644
--- a/src/plugins/qmldesigner/components/integration/xuifiledialog.cpp
+++ b/src/plugins/qmldesigner/components/integration/xuifiledialog.cpp
@@ -27,6 +27,8 @@
**
****************************************************************************/
+#include <utils/hostosinfo.h>
+
#include <QDebug>
#include <QDir>
#include <QObject>
@@ -56,21 +58,21 @@ void XUIFileDialog::runSaveFileDialog(const QString& path, QWidget* parent, QObj
if (dir.isNull())
dir = XUIFileDialog::defaultFolder();
-#ifdef Q_OS_MAC
- QFileDialog *dialog = new QFileDialog(parent, Qt::Sheet);
- dialog->setFileMode(QFileDialog::AnyFile);
- dialog->setAcceptMode(QFileDialog::AcceptSave);
- dialog->setNameFilters(XUIFileDialog::fileNameFilters());
- dialog->setDirectory(dir);
- dialog->open(receiver, member);
-#else // !Q_OS_MAC
- QString caption = QCoreApplication::translate("QmlDesigner::XUIFileDialog", "Save File");
- QString fileName = QFileDialog::getSaveFileName(parent, caption, dir, XUIFileDialog::fileNameFilters().join(";;"));
+ if (Utils::HostOsInfo::isMacHost()) {
+ QFileDialog *dialog = new QFileDialog(parent, Qt::Sheet);
+ dialog->setFileMode(QFileDialog::AnyFile);
+ dialog->setAcceptMode(QFileDialog::AcceptSave);
+ dialog->setNameFilters(XUIFileDialog::fileNameFilters());
+ dialog->setDirectory(dir);
+ dialog->open(receiver, member);
+ } else {
+ QString caption = QCoreApplication::translate("QmlDesigner::XUIFileDialog", "Save File");
+ QString fileName = QFileDialog::getSaveFileName(parent, caption, dir, XUIFileDialog::fileNameFilters().join(";;"));
- QmlDesigner::Internal::SignalEmitter emitter;
- QObject::connect(&emitter, SIGNAL(fileNameSelected(QString)), receiver, member);
- emitter.emitFileNameSelected(fileName);
-#endif // Q_OS_MAC
+ QmlDesigner::Internal::SignalEmitter emitter;
+ QObject::connect(&emitter, SIGNAL(fileNameSelected(QString)), receiver, member);
+ emitter.emitFileNameSelected(fileName);
+ }
}
QStringList XUIFileDialog::fileNameFilters()
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp
index aa5732a1d6..6e3898cabd 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.cpp
@@ -32,7 +32,7 @@ namespace QmlDesigner {
namespace Internal {
-ItemLibraryImageProvider::ItemLibraryImageProvider() :
+ItemLibraryImageProvider::ItemLibraryImageProvider() :
QDeclarativeImageProvider(QDeclarativeImageProvider::Pixmap)
{
}
@@ -44,7 +44,7 @@ QPixmap ItemLibraryImageProvider::requestPixmap(const QString &id, QSize *size,
size->setWidth(pixmap.width());
size->setHeight(pixmap.height());
}
- if (requestedSize.isValid())
+ if (requestedSize.isValid())
return pixmap.scaled(requestedSize);
return pixmap;
}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h
index 5d8c71589b..10e4277b75 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryimageprovider.h
@@ -39,7 +39,7 @@ namespace Internal {
class ItemLibraryImageProvider : public QDeclarativeImageProvider
{
public:
- ItemLibraryImageProvider();
+ ItemLibraryImageProvider();
QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize);
};
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp
index 658b8f9dcd..a012d45097 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarymodel.cpp
@@ -403,9 +403,12 @@ void ItemLibraryModel::update(ItemLibraryInfo *itemLibraryInfo, Model *model)
foreach (ItemLibraryEntry entry, itemLibraryInfo->entries()) {
- bool valid = model->metaInfo(entry.typeName(), entry.majorVersion(), entry.minorVersion()).isValid();
+ NodeMetaInfo metaInfo = model->metaInfo(entry.typeName(), -1, -1);
+ bool valid = metaInfo.isValid() && metaInfo.majorVersion() == entry.majorVersion();
- if (valid && (entry.requiredImport().isEmpty() || model->hasImport(entryToImport(entry), true, true) || entry.forceImport())) {
+ if ((valid || entry.forceImport())
+ && (entry.requiredImport().isEmpty()
+ || model->hasImport(entryToImport(entry), true, false) || entry.forceImport())) {
QString itemSectionName = entry.category();
ItemLibrarySectionModel *sectionModel;
ItemLibraryItemModel *itemModel;
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp
index d46cc39027..a2098102f8 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.cpp
@@ -33,7 +33,7 @@
namespace QmlDesigner {
-ItemLibraryView::ItemLibraryView(QObject* parent) : AbstractView(parent), m_widget(new ItemLibraryWidget)
+ItemLibraryView::ItemLibraryView(QObject* parent) : AbstractView(parent)
{
}
@@ -43,8 +43,11 @@ ItemLibraryView::~ItemLibraryView()
}
-ItemLibraryWidget *ItemLibraryView::widget()
+QWidget *ItemLibraryView::widget()
{
+ if (m_widget.isNull())
+ m_widget = new ItemLibraryWidget;
+
return m_widget.data();
}
@@ -191,6 +194,14 @@ void ItemLibraryView::actualStateChanged(const ModelNode &/*node*/)
{
}
+void ItemLibraryView::setResourcePath(const QString &resourcePath)
+{
+ if (m_widget.isNull())
+ m_widget = new ItemLibraryWidget;
+
+ m_widget->setResourcePath(resourcePath);
+}
+
void ItemLibraryView::updateImports()
{
m_widget->updateModel();
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h
index 2ece25a138..2b1245693d 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibraryview.h
@@ -48,7 +48,7 @@ public:
ItemLibraryView(QObject* parent = 0);
~ItemLibraryView();
- ItemLibraryWidget *widget();
+ QWidget *widget();
// AbstractView
void modelAttached(Model *model);
@@ -90,6 +90,8 @@ public:
void actualStateChanged(const ModelNode &node);
+ void setResourcePath(const QString &resourcePath);
+
protected:
void updateImports();
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
index 5b082c4fd6..5d7d801f29 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.cpp
@@ -29,10 +29,8 @@
#include "itemlibrarywidget.h"
-#include <utils/filterlineedit.h>
#include <utils/fileutils.h>
#include <coreplugin/coreconstants.h>
-#include "itemlibrarycomponents.h"
#include "itemlibrarymodel.h"
#include "itemlibraryimageprovider.h"
#include "customdraganddrop.h"
@@ -41,7 +39,6 @@
#include "rewritingexception.h"
#include <QFileInfo>
-#include <QFileIconProvider>
#include <QFileSystemModel>
#include <QStackedWidget>
#include <QGridLayout>
@@ -52,131 +49,62 @@
#include <QMenu>
#include <QApplication>
-#include <QDeclarativeView>
#include <QDeclarativeItem>
#include <private/qdeclarativeengine_p.h>
namespace QmlDesigner {
-class MyFileIconProvider : public QFileIconProvider
-{
-public:
- MyFileIconProvider(const QSize &iconSize)
- : QFileIconProvider(),
- m_iconSize(iconSize)
- {}
-
- virtual QIcon icon ( const QFileInfo & info ) const
- {
- QPixmap pixmap(info.absoluteFilePath());
- if (pixmap.isNull()) {
- QIcon defaultIcon(QFileIconProvider::icon(info));
- pixmap = defaultIcon.pixmap(defaultIcon.actualSize(m_iconSize));
- }
-
- if (pixmap.width() == m_iconSize.width()
- && pixmap.height() == m_iconSize.height())
- return pixmap;
- if ((pixmap.width() > m_iconSize.width())
- || (pixmap.height() > m_iconSize.height()))
- return pixmap.scaled(m_iconSize, Qt::KeepAspectRatio,
- Qt::SmoothTransformation);
-
- QPoint offset((m_iconSize.width() - pixmap.width()) / 2,
- (m_iconSize.height() - pixmap.height()) / 2);
- QImage newIcon(m_iconSize, QImage::Format_ARGB32_Premultiplied);
- newIcon.fill(Qt::transparent);
- QPainter painter(&newIcon);
- painter.drawPixmap(offset, pixmap);
- return QPixmap::fromImage(newIcon);
- }
-private:
- QSize m_iconSize;
-};
-
-
-// ---------- ItemLibraryPrivate
-class ItemLibraryWidgetPrivate {
-public:
- ItemLibraryWidgetPrivate(QObject *object);
-
- Internal::ItemLibraryModel *m_itemLibraryModel;
- QFileSystemModel *m_resourcesFileSystemModel;
-
- QStackedWidget *m_stackedWidget;
- Utils::FilterLineEdit *m_lineEdit;
- QDeclarativeView *m_itemsView;
- Internal::ItemLibraryTreeView *m_resourcesView;
- QWeakPointer<ItemLibraryInfo> m_itemLibraryInfo;
-
- QSize m_itemIconSize, m_resIconSize;
- MyFileIconProvider m_iconProvider;
- Model *model;
-};
-
-ItemLibraryWidgetPrivate::ItemLibraryWidgetPrivate(QObject *object) :
- m_itemLibraryModel(0),
- m_resourcesFileSystemModel(0),
- m_stackedWidget(0),
- m_lineEdit(0),
- m_itemsView(0),
- m_resourcesView(0),
- m_itemIconSize(24, 24),
- m_resIconSize(24, 24),
- m_iconProvider(m_resIconSize),
- model(0)
-{
- Q_UNUSED(object);
-}
ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
QFrame(parent),
- d(new ItemLibraryWidgetPrivate(this)),
+ m_iconProvider(m_resIconSize),
+ m_itemIconSize(24, 24),
+ m_resIconSize(24, 24),
+ m_itemsView(new QDeclarativeView(this)),
+ m_resourcesView(new Internal::ItemLibraryTreeView(this)),
m_filterFlag(QtBasic)
{
setWindowTitle(tr("Library", "Title of library view"));
/* create Items view and its model */
- d->m_itemsView = new QDeclarativeView(this);
- d->m_itemsView->setAttribute(Qt::WA_OpaquePaintEvent);
- d->m_itemsView->setAttribute(Qt::WA_NoSystemBackground);
- d->m_itemsView->setAcceptDrops(false);
- d->m_itemsView->setFocusPolicy(Qt::ClickFocus);
- d->m_itemsView->setResizeMode(QDeclarativeView::SizeRootObjectToView);
- d->m_itemLibraryModel = new Internal::ItemLibraryModel(QDeclarativeEnginePrivate::getScriptEngine(d->m_itemsView->engine()), this);
- d->m_itemLibraryModel->setItemIconSize(d->m_itemIconSize);
-
- QDeclarativeContext *rootContext = d->m_itemsView->rootContext();
- rootContext->setContextProperty(QLatin1String("itemLibraryModel"), d->m_itemLibraryModel);
- rootContext->setContextProperty(QLatin1String("itemLibraryIconWidth"), d->m_itemIconSize.width());
- rootContext->setContextProperty(QLatin1String("itemLibraryIconHeight"), d->m_itemIconSize.height());
+ m_itemsView->setAttribute(Qt::WA_OpaquePaintEvent);
+ m_itemsView->setAttribute(Qt::WA_NoSystemBackground);
+ m_itemsView->setAcceptDrops(false);
+ m_itemsView->setFocusPolicy(Qt::ClickFocus);
+ m_itemsView->setResizeMode(QDeclarativeView::SizeRootObjectToView);
+ m_itemLibraryModel = new Internal::ItemLibraryModel(QDeclarativeEnginePrivate::getScriptEngine(m_itemsView->engine()), this);
+ m_itemLibraryModel->setItemIconSize(m_itemIconSize);
+
+ QDeclarativeContext *rootContext = m_itemsView->rootContext();
+ rootContext->setContextProperty(QLatin1String("itemLibraryModel"), m_itemLibraryModel.data());
+ rootContext->setContextProperty(QLatin1String("itemLibraryIconWidth"), m_itemIconSize.width());
+ rootContext->setContextProperty(QLatin1String("itemLibraryIconHeight"), m_itemIconSize.height());
QColor highlightColor = palette().highlight().color();
if (0.5*highlightColor.saturationF()+0.75-highlightColor.valueF() < 0)
highlightColor.setHsvF(highlightColor.hsvHueF(),0.1 + highlightColor.saturationF()*2.0, highlightColor.valueF());
- d->m_itemsView->rootContext()->setContextProperty(QLatin1String("highlightColor"), highlightColor);
+ m_itemsView->rootContext()->setContextProperty(QLatin1String("highlightColor"), highlightColor);
// loading the qml has to come after all needed context properties are set
- d->m_itemsView->setSource(QUrl("qrc:/ItemLibrary/qml/ItemsView.qml"));
+ m_itemsView->setSource(QUrl("qrc:/ItemLibrary/qml/ItemsView.qml"));
- QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(d->m_itemsView->rootObject());
+ QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(m_itemsView->rootObject());
connect(rootItem, SIGNAL(itemSelected(int)), this, SLOT(showItemInfo(int)));
connect(rootItem, SIGNAL(itemDragged(int)), this, SLOT(startDragAndDrop(int)));
connect(this, SIGNAL(scrollItemsView(QVariant)), rootItem, SLOT(scrollView(QVariant)));
connect(this, SIGNAL(resetItemsView()), rootItem, SLOT(resetView()));
/* create Resources view and its model */
- d->m_resourcesFileSystemModel = new QFileSystemModel(this);
- d->m_resourcesFileSystemModel->setIconProvider(&d->m_iconProvider);
- d->m_resourcesView = new Internal::ItemLibraryTreeView(this);
- d->m_resourcesView->setModel(d->m_resourcesFileSystemModel);
- d->m_resourcesView->setIconSize(d->m_resIconSize);
+ m_resourcesFileSystemModel = new QFileSystemModel(this);
+ m_resourcesFileSystemModel->setIconProvider(&m_iconProvider);
+ m_resourcesView->setModel(m_resourcesFileSystemModel.data());
+ m_resourcesView->setIconSize(m_resIconSize);
/* create image provider for loading item icons */
- d->m_itemsView->engine()->addImageProvider(QLatin1String("qmldesigner_itemlibrary"), new Internal::ItemLibraryImageProvider);
+ m_itemsView->engine()->addImageProvider(QLatin1String("qmldesigner_itemlibrary"), new Internal::ItemLibraryImageProvider);
/* other widgets */
QTabBar *tabBar = new QTabBar(this);
@@ -184,12 +112,12 @@ ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
tabBar->addTab(tr("Resources", "Title of library resources view"));
tabBar->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
- d->m_lineEdit = new Utils::FilterLineEdit(this);
- d->m_lineEdit->setObjectName(QLatin1String("itemLibrarySearchInput"));
- d->m_lineEdit->setPlaceholderText(tr("<Filter>", "Library search input hint text"));
- d->m_lineEdit->setDragEnabled(false);
- d->m_lineEdit->setMinimumWidth(75);
- d->m_lineEdit->setTextMargins(0, 0, 20, 0);
+ m_lineEdit = new Utils::FilterLineEdit(this);
+ m_lineEdit->setObjectName(QLatin1String("itemLibrarySearchInput"));
+ m_lineEdit->setPlaceholderText(tr("<Filter>", "Library search input hint text"));
+ m_lineEdit->setDragEnabled(false);
+ m_lineEdit->setMinimumWidth(75);
+ m_lineEdit->setTextMargins(0, 0, 20, 0);
QWidget *lineEditFrame = new QWidget(this);
lineEditFrame->setObjectName(QLatin1String("itemLibrarySearchInputFrame"));
QGridLayout *lineEditLayout = new QGridLayout(lineEditFrame);
@@ -197,15 +125,15 @@ ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
lineEditLayout->setSpacing(0);
lineEditLayout->addItem(new QSpacerItem(5, 3, QSizePolicy::Fixed, QSizePolicy::Fixed), 0, 0, 1, 3);
lineEditLayout->addItem(new QSpacerItem(5, 5, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 0);
- lineEditLayout->addWidget(d->m_lineEdit, 1, 1, 1, 1);
+ lineEditLayout->addWidget(m_lineEdit.data(), 1, 1, 1, 1);
lineEditLayout->addItem(new QSpacerItem(5, 5, QSizePolicy::Fixed, QSizePolicy::Fixed), 1, 2);
- connect(d->m_lineEdit, SIGNAL(filterChanged(QString)), this, SLOT(setSearchFilter(QString)));
+ connect(m_lineEdit.data(), SIGNAL(filterChanged(QString)), this, SLOT(setSearchFilter(QString)));
- d->m_stackedWidget = new QStackedWidget(this);
- d->m_stackedWidget->addWidget(d->m_itemsView);
- d->m_stackedWidget->addWidget(d->m_resourcesView);
+ m_stackedWidget = new QStackedWidget(this);
+ m_stackedWidget->addWidget(m_itemsView.data());
+ m_stackedWidget->addWidget(m_resourcesView.data());
connect(tabBar, SIGNAL(currentChanged(int)),
- d->m_stackedWidget, SLOT(setCurrentIndex(int)));
+ m_stackedWidget.data(), SLOT(setCurrentIndex(int)));
connect(tabBar, SIGNAL(currentChanged(int)),
this, SLOT(updateSearch()));
@@ -219,37 +147,28 @@ ItemLibraryWidget::ItemLibraryWidget(QWidget *parent) :
layout->addWidget(tabBar, 0, 0, 1, 1);
layout->addWidget(spacer, 1, 0);
layout->addWidget(lineEditFrame, 2, 0, 1, 1);
- layout->addWidget(d->m_stackedWidget, 3, 0, 1, 1);
+ layout->addWidget(m_stackedWidget.data(), 3, 0, 1, 1);
setResourcePath(QDir::currentPath());
setSearchFilter(QString());
/* style sheets */
setStyleSheet(QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/stylesheet.css")));
- d->m_resourcesView->setStyleSheet(
+ m_resourcesView->setStyleSheet(
QLatin1String(Utils::FileReader::fetchQrc(":/qmldesigner/scrollbar.css")));
}
-ItemLibraryWidget::~ItemLibraryWidget()
-{
- /* workaround: delete the items view before the model is deleted.
- This prevents qml warnings when the item library is destructed. */
- delete d->m_itemsView;
- delete d->m_resourcesView;
- delete d;
-}
-
void ItemLibraryWidget::setItemLibraryInfo(ItemLibraryInfo *itemLibraryInfo)
{
- if (d->m_itemLibraryInfo.data() == itemLibraryInfo)
+ if (m_itemLibraryInfo.data() == itemLibraryInfo)
return;
- if (d->m_itemLibraryInfo)
- disconnect(d->m_itemLibraryInfo.data(), SIGNAL(entriesChanged()),
+ if (m_itemLibraryInfo)
+ disconnect(m_itemLibraryInfo.data(), SIGNAL(entriesChanged()),
this, SLOT(updateModel()));
- d->m_itemLibraryInfo = itemLibraryInfo;
+ m_itemLibraryInfo = itemLibraryInfo;
if (itemLibraryInfo)
- connect(d->m_itemLibraryInfo.data(), SIGNAL(entriesChanged()),
+ connect(m_itemLibraryInfo.data(), SIGNAL(entriesChanged()),
this, SLOT(updateModel()));
updateModel();
@@ -260,9 +179,9 @@ void ItemLibraryWidget::updateImports()
{
FilterChangeFlag filter;
filter = QtBasic;
- if (d->model) {
+ if (m_model) {
QStringList imports;
- foreach (const Import &import, d->model->imports())
+ foreach (const Import &import, m_model->imports())
if (import.isLibraryImport())
imports << import.url();
if (imports.contains("com.nokia.meego", Qt::CaseInsensitive))
@@ -279,17 +198,17 @@ QList<QToolButton *> ItemLibraryWidget::createToolBarWidgets()
return buttons; //import management gets disabled for now (TODO ###)
buttons << new QToolButton();
- buttons.first()->setText("I ");
+ buttons.first()->setText(tr("I "));
buttons.first()->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
- buttons.first()->setToolTip("Manage imports for components");
+ buttons.first()->setToolTip(tr("Manage imports for components"));
buttons.first()->setPopupMode(QToolButton::InstantPopup);
QMenu * menu = new QMenu;
QAction * basicQtAction = new QAction(menu);
basicQtAction->setCheckable(true);
- basicQtAction->setText("Basic Qt Quick only");
+ basicQtAction->setText(tr("Basic Qt Quick only"));
QAction * meegoAction= new QAction(menu);
meegoAction->setCheckable(true);
- meegoAction->setText("Meego Components");
+ meegoAction->setText(tr("Meego Components"));
menu->addAction(basicQtAction);
menu->addAction(meegoAction);
buttons.first()->setMenu(menu);
@@ -307,31 +226,31 @@ QList<QToolButton *> ItemLibraryWidget::createToolBarWidgets()
void ItemLibraryWidget::setSearchFilter(const QString &searchFilter)
{
- if (d->m_stackedWidget->currentIndex() == 0) {
- d->m_itemLibraryModel->setSearchText(searchFilter);
+ if (m_stackedWidget->currentIndex() == 0) {
+ m_itemLibraryModel->setSearchText(searchFilter);
emit resetItemsView();
- d->m_itemsView->update();
+ m_itemsView->update();
} else {
QStringList nameFilterList;
if (searchFilter.contains('.')) {
nameFilterList.append(QString("*%1*").arg(searchFilter));
} else {
foreach (const QByteArray &extension, QImageReader::supportedImageFormats()) {
- nameFilterList.append(QString("*%1*.%2").arg(searchFilter, QString::fromAscii(extension)));
+ nameFilterList.append(QString("*%1*.%2").arg(searchFilter, QString::fromLatin1(extension)));
}
}
- d->m_resourcesFileSystemModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
- d->m_resourcesFileSystemModel->setNameFilterDisables(false);
- d->m_resourcesFileSystemModel->setNameFilters(nameFilterList);
- d->m_resourcesView->expandToDepth(1);
- d->m_resourcesView->scrollToTop();
+ m_resourcesFileSystemModel->setFilter(QDir::AllDirs | QDir::Files | QDir::NoDotAndDotDot);
+ m_resourcesFileSystemModel->setNameFilterDisables(false);
+ m_resourcesFileSystemModel->setNameFilters(nameFilterList);
+ m_resourcesView->expandToDepth(1);
+ m_resourcesView->scrollToTop();
}
}
void ItemLibraryWidget::setModel(Model *model)
{
- d->model = model;
+ m_model = model;
if (!model)
return;
setItemLibraryInfo(model->metaInfo().itemLibraryInfo());
@@ -340,13 +259,13 @@ void ItemLibraryWidget::setModel(Model *model)
void ItemLibraryWidget::emitImportChecked()
{
- if (!d->model)
+ if (!m_model)
return;
bool qtOnlyImport = false;
bool meegoImport = false;
- foreach (const Import &import, d->model->imports()) {
+ foreach (const Import &import, m_model->imports()) {
if (import.isLibraryImport()) {
if (import.url().contains(QString("meego"), Qt::CaseInsensitive))
meegoImport = true;
@@ -367,7 +286,7 @@ void ItemLibraryWidget::setImportFilter(FilterChangeFlag flag)
return;
static bool block = false;
- if (!d->model)
+ if (!m_model)
return;
if (flag == m_filterFlag)
return;
@@ -413,36 +332,36 @@ void ItemLibraryWidget::onMeegoChecked(bool b)
void ItemLibraryWidget::updateModel()
{
- d->m_itemLibraryModel->update(d->m_itemLibraryInfo.data(), d->model);
+ m_itemLibraryModel->update(m_itemLibraryInfo.data(), m_model.data());
updateImports();
updateSearch();
}
void ItemLibraryWidget::updateSearch()
{
- setSearchFilter(d->m_lineEdit->text());
+ setSearchFilter(m_lineEdit->text());
}
void ItemLibraryWidget::setResourcePath(const QString &resourcePath)
{
- if (d->m_resourcesView->model() == d->m_resourcesFileSystemModel) {
- d->m_resourcesFileSystemModel->setRootPath(resourcePath);
- d->m_resourcesView->setRootIndex(d->m_resourcesFileSystemModel->index(resourcePath));
+ if (m_resourcesView->model() == m_resourcesFileSystemModel.data()) {
+ m_resourcesFileSystemModel->setRootPath(resourcePath);
+ m_resourcesView->setRootIndex(m_resourcesFileSystemModel->index(resourcePath));
}
updateSearch();
}
void ItemLibraryWidget::startDragAndDrop(int itemLibId)
{
- QMimeData *mimeData = d->m_itemLibraryModel->getMimeData(itemLibId);
+ QMimeData *mimeData = m_itemLibraryModel->getMimeData(itemLibId);
CustomItemLibraryDrag *drag = new CustomItemLibraryDrag(this);
const QImage image = qvariant_cast<QImage>(mimeData->imageData());
- drag->setPixmap(d->m_itemLibraryModel->getIcon(itemLibId).pixmap(32, 32));
+ drag->setPixmap(m_itemLibraryModel->getIcon(itemLibId).pixmap(32, 32));
drag->setPreview(QPixmap::fromImage(image));
drag->setMimeData(mimeData);
- QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(d->m_itemsView->rootObject());
+ QDeclarativeItem *rootItem = qobject_cast<QDeclarativeItem*>(m_itemsView->rootObject());
connect(rootItem, SIGNAL(stopDragAndDrop()), drag, SLOT(stopDrag()));
drag->exec();
@@ -455,32 +374,62 @@ void ItemLibraryWidget::showItemInfo(int /*itemLibId*/)
void ItemLibraryWidget::wheelEvent(QWheelEvent *event)
{
- if (d->m_stackedWidget->currentIndex() == 0 &&
- d->m_itemsView->rect().contains(event->pos())) {
+ if (m_stackedWidget->currentIndex() == 0 &&
+ m_itemsView->rect().contains(event->pos())) {
emit scrollItemsView(event->delta());
event->accept();
} else
QFrame::wheelEvent(event);
}
- void ItemLibraryWidget::removeImport(const QString &name)
- {
- if (!d->model)
- return;
+void ItemLibraryWidget::removeImport(const QString &name)
+{
+ if (!m_model)
+ return;
+
+ QList<Import> toBeRemovedImportList;
+ foreach (const Import &import, m_model->imports())
+ if (import.isLibraryImport() && import.url().compare(name, Qt::CaseInsensitive) == 0)
+ toBeRemovedImportList.append(import);
- QList<Import> toBeRemovedImportList;
- foreach (const Import &import, d->model->imports())
- if (import.isLibraryImport() && import.url().compare(name, Qt::CaseInsensitive) == 0)
- toBeRemovedImportList.append(import);
+ m_model->changeImports(QList<Import>(), toBeRemovedImportList);
+}
- d->model->changeImports(QList<Import>(), toBeRemovedImportList);
- }
+void ItemLibraryWidget::addImport(const QString &name, const QString &version)
+{
+ if (!m_model)
+ return;
+ m_model->changeImports(QList<Import>() << Import::createLibraryImport(name, version), QList<Import>());
+}
- void ItemLibraryWidget::addImport(const QString &name, const QString &version)
- {
- if (!d->model)
- return;
- d->model->changeImports(QList<Import>() << Import::createLibraryImport(name, version), QList<Import>());
- }
+QIcon ItemLibraryFileIconProvider::icon(const QFileInfo &info) const
+{
+ QPixmap pixmap(info.absoluteFilePath());
+ if (pixmap.isNull()) {
+ QIcon defaultIcon(QFileIconProvider::icon(info));
+ pixmap = defaultIcon.pixmap(defaultIcon.actualSize(m_iconSize));
+ }
+
+ if (pixmap.width() == m_iconSize.width()
+ && pixmap.height() == m_iconSize.height())
+ return pixmap;
+
+ if ((pixmap.width() > m_iconSize.width())
+ || (pixmap.height() > m_iconSize.height()))
+ return pixmap.scaled(m_iconSize, Qt::KeepAspectRatio,
+ Qt::SmoothTransformation);
+
+ QPoint offset((m_iconSize.width() - pixmap.width()) / 2,
+ (m_iconSize.height() - pixmap.height()) / 2);
+ QImage newIcon(m_iconSize, QImage::Format_ARGB32_Premultiplied);
+ newIcon.fill(Qt::transparent);
+ QPainter painter(&newIcon);
+ painter.drawPixmap(offset, pixmap);
+ return QPixmap::fromImage(newIcon);
+}
+ItemLibraryFileIconProvider::ItemLibraryFileIconProvider(const QSize &iconSize)
+ : QFileIconProvider(),
+ m_iconSize(iconSize)
+{}
}
diff --git a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h
index cda224a9cd..7796a9a9be 100644
--- a/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h
+++ b/src/plugins/qmldesigner/components/itemlibrary/itemlibrarywidget.h
@@ -31,16 +31,43 @@
#define ITEMLIBRARYWIDGET_H
#include "itemlibraryinfo.h"
+#include "itemlibrarycomponents.h"
+
+#include <utils/filterlineedit.h>
+
#include <QFrame>
#include <QToolButton>
+#include <QFileIconProvider>
+#include <QDeclarativeView>
+
+QT_BEGIN_NAMESPACE
+class QFileSystemModel;
+class QStackedWidget;
+QT_END_NAMESPACE
namespace QmlDesigner {
-class ItemLibraryWidgetPrivate;
class MetaInfo;
class ItemLibraryEntry;
class Model;
+namespace Internal {
+ class ItemLibraryModel;
+ class ItemLibraryTreeView;
+}
+
+class ItemLibraryFileIconProvider : public QFileIconProvider
+{
+public:
+ ItemLibraryFileIconProvider(const QSize &iconSize);
+
+ QIcon icon( const QFileInfo & info ) const;
+
+private:
+ QSize m_iconSize;
+};
+
+
class ItemLibraryWidget : public QFrame
{
Q_OBJECT
@@ -52,7 +79,6 @@ class ItemLibraryWidget : public QFrame
public:
ItemLibraryWidget(QWidget *parent = 0);
- virtual ~ItemLibraryWidget();
void setItemLibraryInfo(ItemLibraryInfo *itemLibraryInfo);
QList<QToolButton *> createToolBarWidgets();
@@ -90,7 +116,21 @@ signals:
void meegoChecked(bool b);
private:
- ItemLibraryWidgetPrivate *d;
+ ItemLibraryFileIconProvider m_iconProvider;
+ QSize m_itemIconSize;
+ QSize m_resIconSize;
+
+ QWeakPointer<ItemLibraryInfo> m_itemLibraryInfo;
+
+ QWeakPointer<Internal::ItemLibraryModel> m_itemLibraryModel;
+ QWeakPointer<QFileSystemModel> m_resourcesFileSystemModel;
+
+ QWeakPointer<QStackedWidget> m_stackedWidget;
+ QWeakPointer<Utils::FilterLineEdit> m_lineEdit;
+ QScopedPointer<QDeclarativeView> m_itemsView;
+ QScopedPointer<Internal::ItemLibraryTreeView> m_resourcesView;
+
+ QWeakPointer<Model> m_model;
FilterChangeFlag m_filterFlag;
};
diff --git a/src/plugins/qmldesigner/components/logger/logger.cpp b/src/plugins/qmldesigner/components/logger/logger.cpp
index aa7dd9ba6b..0c26c575be 100644
--- a/src/plugins/qmldesigner/components/logger/logger.cpp
+++ b/src/plugins/qmldesigner/components/logger/logger.cpp
@@ -140,9 +140,8 @@ QLogger::~QLogger()
QLogger* QLogger::instance()
{
- if (!m_instance) {
+ if (!m_instance)
m_instance = new QLogger();
- }
return m_instance;
}
diff --git a/src/plugins/qmldesigner/components/navigator/navigator.pri b/src/plugins/qmldesigner/components/navigator/navigator.pri
index 3ce8bc6877..60b0527f5d 100644
--- a/src/plugins/qmldesigner/components/navigator/navigator.pri
+++ b/src/plugins/qmldesigner/components/navigator/navigator.pri
@@ -4,6 +4,7 @@ SOURCES += navigatorview.cpp \
navigatortreemodel.cpp \
navigatorwidget.cpp \
navigatortreeview.cpp
+
HEADERS += navigatorview.h \
navigatortreemodel.h \
navigatorwidget.h \
diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
index 15fecea7f8..a4576b12c1 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
+++ b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.cpp
@@ -39,6 +39,7 @@
#include <rewriterview.h>
#include <invalididexception.h>
#include <rewritingexception.h>
+#include <modelnodecontextmenu.h>
#include <QMimeData>
#include <QMessageBox>
@@ -207,11 +208,10 @@ NavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &n
idItem->setDropEnabled(dropEnabled);
idItem->setEditable(true);
idItem->setData(hash, NavigatorRole);
- if (node.metaInfo().isValid()) {
+ if (node.metaInfo().isValid())
idItem->setToolTip(node.type());
- } else {
+ else
idItem->setToolTip(msgUnknownItem(node.type()));
- }
# ifdef _LOCK_ITEMS_
QStandardItem *lockItem = new QStandardItem;
lockItem->setDragEnabled(true);
@@ -226,9 +226,8 @@ NavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &n
visibilityItem->setCheckable(true);
visibilityItem->setEditable(false);
visibilityItem->setData(hash, NavigatorRole);
- if (node.isRootNode()) {
+ if (node.isRootNode())
visibilityItem->setCheckable(false);
- }
QMap<QString, QStandardItem *> propertyItems;
foreach (const QString &propertyName, visibleProperties(node)) {
@@ -251,15 +250,14 @@ NavigatorTreeModel::ItemRow NavigatorTreeModel::createItemRow(const ModelNode &n
void NavigatorTreeModel::updateItemRow(const ModelNode &node, ItemRow items)
{
- bool blockSignal = blockItemChangedSignal(true);
+ bool blockSignal = blockItemChangedSignal(true);
items.idItem->setText(node.id());
items.visibilityItem->setCheckState(node.auxiliaryData("invisible").toBool() ? Qt::Unchecked : Qt::Checked);
- if (node.metaInfo().isValid()) {
+ if (node.metaInfo().isValid())
items.idItem->setToolTip(node.type());
- } else {
+ else
items.idItem->setToolTip(msgUnknownItem(node.type()));
- }
blockItemChangedSignal(blockSignal);
}
@@ -495,9 +493,8 @@ void NavigatorTreeModel::removeSubTree(const ModelNode &node)
QList<QStandardItem*> rowList;
ItemRow itemRow = itemRowForNode(node);
- if (itemRow.idItem->parent()) {
+ if (itemRow.idItem->parent())
rowList = itemRow.idItem->parent()->takeRow(itemRow.idItem->row());
- }
foreach (const ModelNode &childNode, modelNodeChildren(node)) {
removeSubTree(childNode);
@@ -530,9 +527,8 @@ void NavigatorTreeModel::moveNodesInteractive(NodeAbstractProperty parentPropert
if (parentProperty.isNodeProperty()) {
ModelNode propertyNode = parentProperty.toNodeProperty().modelNode();
// Destruction of ancestors is not allowed
- if (propertyNode.isAncestorOf(node)) {
+ if (propertyNode.isAncestorOf(node))
continue;
- }
if (propertyNode.isValid()) {
QApplication::setOverrideCursor(Qt::ArrowCursor);
if (QMessageBox::warning(0, tr("Warning"), tr("Reparenting the component %1 here will cause the component %2 to be deleted. Do you want to proceed?").arg(node.id(), propertyNode.id()), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) {
@@ -544,7 +540,7 @@ void NavigatorTreeModel::moveNodesInteractive(NodeAbstractProperty parentPropert
}
}
- if (parentProperty.isDefaultProperty() && parentProperty.parentModelNode().metaInfo().isSubclassOf("<cpp>.QDeclarativeBasePositioner", -1, -1)) {
+ if (parentProperty.isDefaultProperty() && parentProperty.parentModelNode().metaInfo().isPositioner()) {
ModelNode currentNode = node;
if (currentNode.hasProperty("x"))
currentNode.removeProperty("x");
@@ -568,9 +564,8 @@ void NavigatorTreeModel::moveNodesInteractive(NodeAbstractProperty parentPropert
if (index < targetIndex) { // item is first removed from oldIndex, then inserted at new index
--targetIndex;
}
- if (index != targetIndex) {
+ if (index != targetIndex)
parentProperty.toNodeListProperty().slide(index, targetIndex);
- }
}
}
}
@@ -627,11 +622,11 @@ QStringList NavigatorTreeModel::visibleProperties(const ModelNode &node) const
QString qmlType = qmlTypeInQtContainer(node.metaInfo().propertyTypeName(propertyName));
if (node.model()->metaInfo(qmlType).isValid() &&
- node.model()->metaInfo(qmlType).isSubclassOf("<cpp>.QGraphicsObject", -1, -1)) {
+ node.model()->metaInfo(qmlType).isSubclassOf("QtQuick.Item", -1, -1)) {
propertyList.append(propertyName);
}
}
- }
+ }
return propertyList;
}
@@ -658,10 +653,9 @@ void NavigatorTreeModel::setVisible(const QModelIndex &index, bool visible)
itemRow.visibilityItem->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
}
-void NavigatorTreeModel::openContextMenu(const QPoint &p)
+void NavigatorTreeModel::openContextMenu(const QPoint &position)
{
- if (m_view)
- m_view->showContextMenu(p, QPoint(), false);
+ ModelNodeContextMenu::showContextMenu(m_view.data(), position, QPoint(), false);
}
} // QmlDesigner
diff --git a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h
index 94f67d347d..417188089d 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h
+++ b/src/plugins/qmldesigner/components/navigator/navigatortreemodel.h
@@ -50,7 +50,7 @@ class NavigatorTreeModel : public QStandardItemModel
struct ItemRow {
ItemRow()
: idItem(0), lockItem(0), visibilityItem(0) {}
- ItemRow(QStandardItem *id, QStandardItem *lock, QStandardItem *visibility, const PropertyItemMap &properties)
+ ItemRow(QStandardItem *id, QStandardItem *lock, QStandardItem *visibility, const QMap<QString, QStandardItem *> &properties)
: idItem(id), lockItem(lock), visibilityItem(visibility), propertyItems(properties) {}
QList<QStandardItem*> toList() const {
diff --git a/src/plugins/qmldesigner/components/navigator/navigatorview.cpp b/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
index 953db6b93e..1f7daf805e 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
+++ b/src/plugins/qmldesigner/components/navigator/navigatorview.cpp
@@ -30,6 +30,7 @@
#include "navigatorview.h"
#include "navigatortreemodel.h"
#include "navigatorwidget.h"
+#include "modelnodecontextmenu.h"
#include <coreplugin/editormanager/editormanager.h>
@@ -93,7 +94,7 @@ NavigatorView::~NavigatorView()
delete m_widget.data();
}
-NavigatorWidget *NavigatorView::widget()
+QWidget *NavigatorView::widget()
{
return m_widget.data();
}
@@ -269,7 +270,7 @@ void NavigatorView::changeToComponent(const QModelIndex &index)
{
if (index.isValid() && m_treeModel->data(index, Qt::UserRole).isValid()) {
ModelNode doubleClickNode = m_treeModel->nodeForIndex(index);
- if (doubleClickNode.metaInfo().isComponent())
+ if (doubleClickNode.metaInfo().isFileComponent())
Core::EditorManager::openEditor(doubleClickNode.metaInfo().componentFileName());
}
}
@@ -400,7 +401,7 @@ void NavigatorView::updateItemSelection()
treeWidget()->scrollTo(m_treeModel->indexForNode(selectedModelNodes().first()));
// make sure selected nodes a visible
- foreach(const QModelIndex &selectedIndex, itemSelection.indexes()) {
+ foreach (const QModelIndex &selectedIndex, itemSelection.indexes()) {
if (selectedIndex.column() == 0)
expandRecursively(selectedIndex);
}
diff --git a/src/plugins/qmldesigner/components/navigator/navigatorview.h b/src/plugins/qmldesigner/components/navigator/navigatorview.h
index 03d77173b4..316eeff348 100644
--- a/src/plugins/qmldesigner/components/navigator/navigatorview.h
+++ b/src/plugins/qmldesigner/components/navigator/navigatorview.h
@@ -56,7 +56,7 @@ public:
NavigatorView(QObject* parent = 0);
~NavigatorView();
- NavigatorWidget *widget();
+ QWidget *widget();
// AbstractView
void modelAttached(Model *model);
diff --git a/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.cpp b/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.cpp
index 5c81d90d1b..f663e53e50 100644
--- a/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.cpp
+++ b/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.cpp
@@ -29,7 +29,6 @@
#include "pluginmanager.h"
#include "iplugin.h"
-#include "pluginpath.h"
#include <metainfo.h>
#include <QCoreApplication>
@@ -55,88 +54,28 @@ enum { debug = 0 };
namespace QmlDesigner {
-// Initialize and create instance of a plugin from scratch,
-// that is, make sure the library is loaded and has an instance
-// of the IPlugin type. Once something fails, mark it as failed
-// ignore it from then on.
-//static IPlugin *instance(PluginData &p)
-//{
-// // Go stale once something fails
-// if (p.failed)
-// return 0;
-// // Pull up the plugin, retrieve IPlugin instance.
-// if (!p.instanceGuard) {
-// p.instance = 0;
-// QPluginLoader loader(p.path);
-// if (!(loader.isLoaded() || loader.load())) {
-// p.failed = true;
-// p.errorMessage = loader.errorString();
-// return 0;
-// }
-// QObject *object = loader.instance();
-// if (!object) {
-// p.failed = true;
-// p.errorMessage = QCoreApplication::translate("PluginManager", "Failed to create instance.");
-// return 0;
-// }
-// IPlugin *iplugin = qobject_cast<IPlugin *>(object);
-// if (!iplugin) {
-// p.failed = true;
-// p.errorMessage = QCoreApplication::translate("PluginManager", "Not a QmlDesigner plugin.");
-// delete object;
-// return 0;
-// }
-// p.instanceGuard = object;
-// p.instance = iplugin;
-// }
-// // Ensure it is initialized
-// if (!p.instance->isInitialized()) {
-// if (!p.instance->initialize(&p.errorMessage)) {
-// p.failed = true;
-// delete p.instance;
-// p.instance = 0;
-// return 0;
-// }
-// }
-// return p.instance;
-//}
-
-
-// ---- PluginManager[Private]
-class PluginManagerPrivate {
-public:
- typedef QList<PluginPath> PluginPathList;
- PluginPathList m_paths;
-};
-
-PluginManager::PluginManager() :
- d(new PluginManagerPrivate)
-{
-}
-
-PluginManager::~PluginManager()
-{
- delete d;
-}
-
PluginManager::IPluginList PluginManager::instances()
{
IPluginList rc;
- const PluginManagerPrivate::PluginPathList::iterator end = d->m_paths.end();
- for (PluginManagerPrivate::PluginPathList::iterator it = d->m_paths.begin(); it != end; ++it)
+ const PluginPathList::iterator end = m_paths.end();
+ for (PluginPathList::iterator it = m_paths.begin(); it != end; ++it)
it->getInstances(&rc);
if (debug)
qDebug() << '<' << Q_FUNC_INFO << rc.size();
return rc;
}
+PluginManager::PluginManager()
+{
+}
+
void PluginManager::setPluginPaths(const QStringList &paths)
{
foreach (const QString &path, paths) {
const QDir dir(path);
if (!dir.exists())
continue;
- d->m_paths.push_back(PluginPath(dir));
+ m_paths.push_back(PluginPath(dir));
}
// also register path in widgetpluginmanager
@@ -146,8 +85,8 @@ void PluginManager::setPluginPaths(const QStringList &paths)
QAbstractItemModel *PluginManager::createModel(QObject *parent)
{
QStandardItemModel *model = new QStandardItemModel(parent);
- const PluginManagerPrivate::PluginPathList::iterator end = d->m_paths.end();
- for (PluginManagerPrivate::PluginPathList::iterator it = d->m_paths.begin(); it != end; ++it)
+ const PluginPathList::iterator end = m_paths.end();
+ for (PluginPathList::iterator it = m_paths.begin(); it != end; ++it)
model->appendRow(it->createModelItem());
return model;
}
diff --git a/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.h b/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.h
index 94ff5cc74e..8b0360539c 100644
--- a/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.h
+++ b/src/plugins/qmldesigner/components/pluginmanager/pluginmanager.h
@@ -30,6 +30,7 @@
#ifndef PLUGINMANAGER_H
#define PLUGINMANAGER_H
+#include "pluginpath.h"
#include <QObject>
#include <QList>
@@ -44,8 +45,6 @@ namespace QmlDesigner {
class IPlugin;
-class PluginManagerPrivate;
-
// PluginManager: Loads the plugin libraries on demand "as lazy as
// possible", that is, directories are scanned and
// instances are created only when instances() is called.
@@ -53,11 +52,13 @@ class PluginManagerPrivate;
class PluginManager
{
Q_DISABLE_COPY(PluginManager)
+
+ typedef QList<PluginPath> PluginPathList;
+
public:
typedef QList<IPlugin *> IPluginList;
PluginManager();
- ~PluginManager();
void setPluginPaths(const QStringList &paths);
@@ -65,12 +66,13 @@ public:
QDialog *createAboutPluginDialog(QWidget *parent);
-private:
+private: // functions
// Convenience to create a model for an "About Plugins"
// dialog. Forces plugin initialization.
QAbstractItemModel *createModel(QObject *parent = 0);
- PluginManagerPrivate *d;
+private: // variables
+ PluginPathList m_paths;
};
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp b/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp
index f9dfca3abd..b3ead86bc6 100644
--- a/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp
+++ b/src/plugins/qmldesigner/components/pluginmanager/pluginpath.cpp
@@ -28,6 +28,8 @@
****************************************************************************/
#include "pluginpath.h"
+#include "pluginmanager.h"
+
#include <iplugin.h>
#include <QLibrary>
#include <QWeakPointer>
diff --git a/src/plugins/qmldesigner/components/pluginmanager/pluginpath.h b/src/plugins/qmldesigner/components/pluginmanager/pluginpath.h
index 67c10c9544..0678f0460c 100644
--- a/src/plugins/qmldesigner/components/pluginmanager/pluginpath.h
+++ b/src/plugins/qmldesigner/components/pluginmanager/pluginpath.h
@@ -30,8 +30,6 @@
#ifndef PLUGINPATH_H
#define PLUGINPATH_H
-#include "pluginmanager.h"
-
#include <QObject>
#include <QWeakPointer>
#include <QList>
@@ -71,11 +69,13 @@ struct PluginData {
// IPlugins.
class PluginPath {
+
+ typedef QList<IPlugin *> IPluginList;
public:
explicit PluginPath(const QDir &path);
- void getInstances(PluginManager::IPluginList *list);
+ void getInstances(IPluginList *list);
QDir path() const { return m_path; }
diff --git a/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp b/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp
index ebf5973b49..b5a3376e93 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/basicwidgets.cpp
@@ -80,7 +80,7 @@ WindowsStyleSingleton* WindowsStyleSingleton::m_instance = 0;
WindowsStyleSingleton* WindowsStyleSingleton::instance()
{
static WindowsWatcher w;
- if( m_instance == 0 )
+ if ( m_instance == 0 )
m_instance = new WindowsStyleSingleton();
return m_instance;
}
@@ -618,11 +618,10 @@ private:
_url = url;
QString path;
- if (_url.scheme() == QLatin1String("qrc")) {
+ if (_url.scheme() == QLatin1String("qrc"))
path = QLatin1Char(':') + _url.path();
- } else {
+ else
path = _url.toLocalFile();
- }
QFile file(path);
if (file.open(QIODevice::ReadOnly)) {
@@ -652,7 +651,7 @@ protected:
QFontMetrics fm(font());
if (fm.width(text()) > (contentsRect().width() - 8) && text().length() > 4) {
QPainter p(this);
- QString elided_txt;
+ QString elided_txt;
elided_txt = fm.elidedText(text(), Qt::ElideRight, contentsRect().width() - 8, Qt::TextShowMnemonic);
p.drawText(contentsRect().adjusted(12, 0, 0, 0), Qt::TextSingleLine, elided_txt);
}
@@ -683,11 +682,10 @@ private:
_url = url;
QString path;
- if (_url.scheme() == QLatin1String("qrc")) {
+ if (_url.scheme() == QLatin1String("qrc"))
path = QLatin1Char(':') + _url.path();
- } else {
+ else
path = _url.toLocalFile();
- }
QFile file(path);
if (file.open(QIODevice::ReadOnly)) {
@@ -755,11 +753,10 @@ private:
_url = url;
QString path;
- if (_url.scheme() == QLatin1String("qrc")) {
+ if (_url.scheme() == QLatin1String("qrc"))
path = QLatin1Char(':') + _url.path();
- } else {
+ else
path = _url.toLocalFile();
- }
QFile file(path);
if (file.open(QIODevice::ReadOnly)) {
diff --git a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp b/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp
index 342fc8bb92..864d86fe52 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/behaviordialog.cpp
@@ -63,9 +63,8 @@ void BehaviorWidget::setComplexNode(PropertyEditorNodeWrapper* complexNode)
m_propertyName = complexNode->propertyName();
m_modelNode = complexNode->parentModelNode();
- if (!modelNode().isValid()) {
+ if (!modelNode().isValid())
m_BehaviorDialog->hide();
- }
m_BehaviorDialog->setup(modelNode(), propertyName());
}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp b/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp
index 19eade0adb..aa92166b92 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.cpp
@@ -37,94 +37,70 @@
namespace QmlDesigner {
-class DeclarativeWidgetViewPrivate
+void DeclarativeWidgetView::execute()
{
-public:
- DeclarativeWidgetViewPrivate(DeclarativeWidgetView *view)
- : q(view), root(0), component(0) {}
- ~DeclarativeWidgetViewPrivate() { delete root; }
- void execute();
-
- DeclarativeWidgetView *q;
-
- QPointer<QWidget> root;
- QUrl source;
- QDeclarativeEngine engine;
- QDeclarativeComponent *component;
-};
-
-void DeclarativeWidgetViewPrivate::execute()
-{
- if (root) {
- delete root;
- root = 0;
- }
- if (component) {
- delete component;
- component = 0;
- }
- if (!source.isEmpty()) {
- component = new QDeclarativeComponent(&engine, source, q);
- if (!component->isLoading()) {
- q->continueExecute();
- } else {
- QObject::connect(component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), q, SLOT(continueExecute()));
- }
+ if (m_root)
+ delete m_root.data();
+
+ if (m_component)
+ delete m_component.data();
+
+ if (!m_source.isEmpty()) {
+ m_component = new QDeclarativeComponent(&m_engine, m_source, this);
+ if (!m_component->isLoading())
+ continueExecute();
+ else
+ connect(m_component.data(), SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(continueExecute()));
}
}
DeclarativeWidgetView::DeclarativeWidgetView(QWidget *parent) :
- QWidget(parent), d(new DeclarativeWidgetViewPrivate(this))
-{
-}
-
-DeclarativeWidgetView::~DeclarativeWidgetView()
+ QWidget(parent)
{
- delete d;
}
QUrl DeclarativeWidgetView::source() const
{
- return d->source;
+ return m_source;
}
void DeclarativeWidgetView::setSource(const QUrl& url)
{
- d->source = url;
- d->execute();
+ m_source = url;
+ execute();
}
QDeclarativeEngine* DeclarativeWidgetView::engine()
{
- return &d->engine;
+ return &m_engine;
}
QWidget *DeclarativeWidgetView::rootWidget() const
{
- return d->root;
+ return m_root.data();
}
QDeclarativeContext* DeclarativeWidgetView::rootContext()
{
- return d->engine.rootContext();
+ return m_engine.rootContext();
}
DeclarativeWidgetView::Status DeclarativeWidgetView::status() const
{
- if (!d->component)
+ if (!m_component)
return DeclarativeWidgetView::Null;
- return DeclarativeWidgetView::Status(d->component->status());
+ return DeclarativeWidgetView::Status(m_component->status());
}
void DeclarativeWidgetView::continueExecute()
{
- disconnect(d->component, SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(continueExecute()));
+ disconnect(m_component.data(), SIGNAL(statusChanged(QDeclarativeComponent::Status)), this, SLOT(continueExecute()));
- if (d->component->isError()) {
- QList<QDeclarativeError> errorList = d->component->errors();
+ if (m_component->isError()) {
+ QList<QDeclarativeError> errorList = m_component->errors();
foreach (const QDeclarativeError &error, errorList) {
qWarning() << error;
}
@@ -132,10 +108,10 @@ void DeclarativeWidgetView::continueExecute()
return;
}
- QObject *obj = d->component->create();
+ QObject *obj = m_component->create();
- if(d->component->isError()) {
- QList<QDeclarativeError> errorList = d->component->errors();
+ if (m_component->isError()) {
+ QList<QDeclarativeError> errorList = m_component->errors();
foreach (const QDeclarativeError &error, errorList) {
qWarning() << error;
}
@@ -149,23 +125,21 @@ void DeclarativeWidgetView::continueExecute()
void DeclarativeWidgetView::setRootWidget(QWidget *widget)
{
- if (d->root == widget)
+ if (m_root.data() == widget)
return;
window()->setAttribute(Qt::WA_OpaquePaintEvent, false);
window()->setAttribute(Qt::WA_NoSystemBackground, false);
widget->setParent(this);
- if (isVisible()) {
+ if (isVisible())
widget->setVisible(true);
- }
resize(widget->size());
- d->root = widget;
+ m_root.reset(widget);
- if (d->root) {
- QSize initialSize = d->root->size();
- if (initialSize != size()) {
+ if (m_root) {
+ QSize initialSize = m_root->size();
+ if (initialSize != size())
resize(initialSize);
- }
}
}
diff --git a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h b/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h
index d857d16852..626814244d 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/declarativewidgetview.h
@@ -32,17 +32,16 @@
#include <QWidget>
#include <QUrl>
+#include <QDeclarativeEngine>
QT_BEGIN_NAMESPACE
-class QDeclarativeEngine;
class QDeclarativeContext;
class QDeclarativeError;
+class QDeclarativeComponent;
QT_END_NAMESPACE
namespace QmlDesigner {
-class DeclarativeWidgetViewPrivate;
-
class DeclarativeWidgetView : public QWidget
{
Q_OBJECT
@@ -51,8 +50,6 @@ class DeclarativeWidgetView : public QWidget
public:
explicit DeclarativeWidgetView(QWidget *parent = 0);
- virtual ~DeclarativeWidgetView();
-
QUrl source() const;
void setSource(const QUrl&);
@@ -68,14 +65,17 @@ signals:
void statusChanged(DeclarativeWidgetView::Status);
protected:
- virtual void setRootWidget(QWidget *);
+ void setRootWidget(QWidget *);
+ void execute();
private Q_SLOTS:
void continueExecute();
private:
- friend class DeclarativeWidgetViewPrivate;
- DeclarativeWidgetViewPrivate *d;
+ QScopedPointer<QWidget> m_root;
+ QUrl m_source;
+ QDeclarativeEngine m_engine;
+ QWeakPointer<QDeclarativeComponent> m_component;
};
diff --git a/src/plugins/qmldesigner/components/propertyeditor/filewidget.cpp b/src/plugins/qmldesigner/components/propertyeditor/filewidget.cpp
index 3c7ddff4f8..d31ba06288 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/filewidget.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/filewidget.cpp
@@ -38,6 +38,8 @@
QT_BEGIN_NAMESPACE
+static QString s_lastBrowserPath;
+
FileWidget::FileWidget(QWidget *parent) : QWidget(parent), m_filter("(*.*)"), m_showComboBox(false), m_lock(false)
{
m_pushButton = new QToolButton(this);
@@ -56,7 +58,6 @@ FileWidget::FileWidget(QWidget *parent) : QWidget(parent), m_filter("(*.*)"), m_
connect(m_lineEdit, SIGNAL(editingFinished()), this, SLOT(lineEditChanged()));
connect(m_pushButton, SIGNAL(pressed()), this, SLOT(buttonPressed()));
connect(m_comboBox, SIGNAL(editTextChanged(QString)), this, SLOT(comboBoxChanged()));
- m_currentPath = QDir::currentPath();
}
FileWidget::~FileWidget()
@@ -96,15 +97,43 @@ void FileWidget::comboBoxChanged()
void FileWidget::buttonPressed()
{
- QString path = m_currentPath;
- if (m_itemNode.isValid()) {
- path = QFileInfo(m_itemNode.modelNode().model()->fileUrl().toLocalFile()).absoluteDir().absolutePath();
+ QString modelPath;
+ if (m_itemNode.isValid())
+ modelPath = QFileInfo(m_itemNode.modelNode().model()->fileUrl().toLocalFile()).absoluteDir().absolutePath();
+
+ m_lastModelPath = modelPath;
+
+ bool documentChanged = m_lastModelPath == modelPath;
+
+ //First we try the last path this browser widget was opened with
+ //if the document was not changed
+ QString path = documentChanged ? QString() : m_currentPath;
+
+
+ //If that one is not valid we try the path for the current file
+ if (path.isEmpty() && !m_fileName.isEmpty())
+ path = QFileInfo(modelPath + QLatin1String("/") + m_fileName.toString()).absoluteDir().absolutePath();
+
+
+ //Next we try to fall back to the path any file browser was opened with
+ if (!QFileInfo(path).exists()) {
+ path = s_lastBrowserPath;
+
+ //The last fallback is to try the path of the document
+ if (!QFileInfo(path).exists()) {
+ if (m_itemNode.isValid())
+ path = modelPath;
+ }
}
+
QString newFile = QFileDialog::getOpenFileName(0, tr("Open File"), path, m_filter);
- if (!newFile.isEmpty())
+
+ if (!newFile.isEmpty()) {
setFileNameStr(newFile);
- m_currentPath = QFileInfo(newFile).absolutePath();
+ m_currentPath = QFileInfo(newFile).absolutePath();
+ s_lastBrowserPath = m_currentPath;
+ }
}
void FileWidget::setFileNameStr(const QString &fileName)
diff --git a/src/plugins/qmldesigner/components/propertyeditor/filewidget.h b/src/plugins/qmldesigner/components/propertyeditor/filewidget.h
index c3da156aa0..3df6dcd212 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/filewidget.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/filewidget.h
@@ -119,6 +119,7 @@ private:
bool m_showComboBox;
bool m_lock;
QString m_currentPath;
+ QString m_lastModelPath;
};
diff --git a/src/plugins/qmldesigner/components/propertyeditor/genericpropertieswidget.cpp b/src/plugins/qmldesigner/components/propertyeditor/genericpropertieswidget.cpp
index 1f5d535e85..5f54b981cd 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/genericpropertieswidget.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/genericpropertieswidget.cpp
@@ -129,9 +129,8 @@ QtProperty* GenericPropertiesWidget::addVariantProperty(const PropertyMetaInfo&
}
}
- if (!item->isModified()) {
+ if (!item->isModified())
item->setValue(instance.property(propertyMetaInfo.name())); //TODO fix this
- }
return item;
} else {
@@ -167,9 +166,8 @@ QtProperty* GenericPropertiesWidget::addEnumProperty(const PropertyMetaInfo& pro
if (!item->isModified()) {
int selectionIndex = elementNames.indexOf(instance.property(propertyMetaInfo.name()).toString()); // TODO Fix this
- if (selectionIndex != -1) {
+ if (selectionIndex != -1)
enumManager->setValue(item, selectionIndex);
- }
}
return item;
@@ -200,17 +198,15 @@ QtProperty* GenericPropertiesWidget::addProperties(const NodeMetaInfo& nodeMetaI
QtProperty* property = 0;
- if (propMetaInfo.isEnumType()) {
+ if (propMetaInfo.isEnumType())
property = addEnumProperty(propMetaInfo, propertiesWithValues, instance);
- } else if (propMetaInfo.isFlagType()) {
+ else if (propMetaInfo.isFlagType())
property = addFlagProperty(propMetaInfo, propertiesWithValues, instance);
- } else {
+ else
property = addVariantProperty(propMetaInfo, propertiesWithValues, instance);
- }
- if (property) {
+ if (property)
groupItem->addSubProperty(property);
- }
}
return groupItem;
@@ -218,9 +214,8 @@ QtProperty* GenericPropertiesWidget::addProperties(const NodeMetaInfo& nodeMetaI
void GenericPropertiesWidget::buildPropertyEditorItems()
{
- if (!selectedNode.isValid()) {
+ if (!selectedNode.isValid())
return;
- }
// qDebug() << "buildPropertyEditorItems for node" << selectedNode.name() << "...";
@@ -294,16 +289,14 @@ void GenericPropertiesWidget::nodeCreated(const ModelNode&)
void GenericPropertiesWidget::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
- if (selectedNode.isValid() && removedNode.isValid() && selectedNode == removedNode) {
+ if (selectedNode.isValid() && removedNode.isValid() && selectedNode == removedNode)
select(selectedNode.parentNode());
- }
}
void GenericPropertiesWidget::propertyAdded(const NodeState& state, const NodeProperty&)
{
- if (selectedNode.isValid() && state.isValid() && selectedNode == state.modelNode()) {
+ if (selectedNode.isValid() && state.isValid() && selectedNode == state.modelNode())
select(state.modelNode());
- }
}
void GenericPropertiesWidget::propertyAboutToBeRemoved(const NodeState& /* state */, const NodeProperty&)
diff --git a/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp b/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp
index e8134201eb..cf4edfe84f 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/gradientlineqmladaptor.cpp
@@ -137,7 +137,7 @@ void GradientLineQmlAdaptor::writeGradient()
gradientNode.setId(oldId);
for (int i = 0;i < stops.size(); i++) {
- ModelNode gradientStopNode = modelNode.view()->createModelNode("QtQuick.GradientStop", 1, 0);
+ ModelNode gradientStopNode = modelNode.view()->createModelNode("QtQuick.GradientStop", modelNode.majorQtQuickVersion(), 0);
gradientStopNode.variantProperty("position") = roundReal(stops.at(i).first);
gradientStopNode.variantProperty("color") = normalizeColor(stops.at(i).second);
gradientNode.nodeListProperty("stops").reparentHere(gradientStopNode);
diff --git a/src/plugins/qmldesigner/components/propertyeditor/originwidget.cpp b/src/plugins/qmldesigner/components/propertyeditor/originwidget.cpp
index 91525ebf6c..4eb119b903 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/originwidget.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/originwidget.cpp
@@ -108,7 +108,7 @@ void OriginWidget::mouseReleaseEvent(QMouseEvent *event)
}
void OriginWidget::mousePressEvent(QMouseEvent * event)
-{
+{
if (event->button() == Qt::LeftButton) {
m_pressed = true;
for (int i = 0; i < positions.size(); i++)
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp
index 8843b1e1f1..1feb76c64d 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.cpp
@@ -29,6 +29,8 @@
#include "propertyeditor.h"
+#include <qmldesignerconstants.h>
+
#include <nodemetainfo.h>
#include <metainfo.h>
@@ -55,6 +57,7 @@
#include "propertyeditortransaction.h"
#include "originwidget.h"
+#include <qmljs/qmljssimplereader.h>
#include <utils/fileutils.h>
#include <QCoreApplication>
@@ -86,6 +89,8 @@ const int collapseButtonOffset = 114;
namespace QmlDesigner {
+const char resourcePropertyEditorPath[] = ":/propertyeditor";
+
static QString applicationDirPath()
{
#ifdef Q_OS_WIN
@@ -109,6 +114,11 @@ static inline QString sharedDirPath()
return QFileInfo(appPath + SHARE_PATH).absoluteFilePath();
}
+static inline QString propertyTemplatesPath()
+{
+ return sharedDirPath() + QLatin1String("/propertyeditor/PropertyTemplates/");
+}
+
static QObject *variantToQObject(const QVariant &v)
{
if (v.userType() == QMetaType::QObjectStar || v.userType() > QMetaType::User)
@@ -117,6 +127,31 @@ static QObject *variantToQObject(const QVariant &v)
return 0;
}
+static QmlJS::SimpleReaderNode::Ptr s_templateConfiguration;
+
+QmlJS::SimpleReaderNode::Ptr templateConfiguration()
+{
+ if (!s_templateConfiguration) {
+ QmlJS::SimpleReader reader;
+ const QString fileName = propertyTemplatesPath() + QLatin1String("TemplateTypes.qml");
+ s_templateConfiguration = reader.readFile(fileName);
+
+ if (!s_templateConfiguration)
+ qWarning().nospace() << "template definitions:" << reader.errors();
+ }
+
+ return s_templateConfiguration;
+}
+
+QStringList variantToStringList(const QVariant &variant) {
+ QStringList stringList;
+
+ foreach (const QVariant &singleValue, variant.toList())
+ stringList << singleValue.toString();
+
+ return stringList;
+}
+
PropertyEditor::NodeType::NodeType(PropertyEditor *propertyEditor) :
m_view(new DeclarativeWidgetView), m_propertyEditorTransaction(new PropertyEditorTransaction(propertyEditor)), m_dummyPropertyEditorValue(new PropertyEditorValue()),
m_contextObject(new PropertyEditorContextObject())
@@ -125,6 +160,7 @@ PropertyEditor::NodeType::NodeType(PropertyEditor *propertyEditor) :
QDeclarativeContext *ctxt = m_view->rootContext();
m_view->engine()->setOutputWarningsToStandardError(debug);
+ m_view->engine()->addImportPath(sharedDirPath() + QLatin1String("/propertyeditor"));
m_dummyPropertyEditorValue->setValue("#000000");
ctxt->setContextProperty("dummyBackendValue", m_dummyPropertyEditorValue.data());
m_contextObject->setBackendValues(&m_backendValuesPropertyMap);
@@ -170,12 +206,11 @@ void createPropertyEditorValue(const QmlObjectNode &fxObjectNode, const QString
valueObject->setName(name);
valueObject->setModelNode(fxObjectNode);
- if (fxObjectNode.propertyAffectedByCurrentState(name) && !(fxObjectNode.modelNode().property(name).isBindingProperty())) {
+ if (fxObjectNode.propertyAffectedByCurrentState(name) && !(fxObjectNode.modelNode().property(name).isBindingProperty()))
valueObject->setValue(fxObjectNode.modelValue(name));
- } else {
+ else
valueObject->setValue(value);
- }
if (propertyName != QLatin1String("id") &&
fxObjectNode.currentState().isBaseState() &&
@@ -202,9 +237,8 @@ void PropertyEditor::NodeType::setValue(const QmlObjectNode & fxObjectNode, cons
void PropertyEditor::NodeType::setup(const QmlObjectNode &fxObjectNode, const QString &stateName, const QUrl &qmlSpecificsFile, PropertyEditor *propertyEditor)
{
- if (!fxObjectNode.isValid()) {
+ if (!fxObjectNode.isValid())
return;
- }
QDeclarativeContext *ctxt = m_view->rootContext();
@@ -235,11 +269,11 @@ void PropertyEditor::NodeType::setup(const QmlObjectNode &fxObjectNode, const QS
m_backendAnchorBinding.setup(QmlItemNode(fxObjectNode.modelNode()));
ctxt->setContextProperty("anchorBackend", &m_backendAnchorBinding);
-
+
ctxt->setContextProperty("transaction", m_propertyEditorTransaction.data());
-
+
m_contextObject->setSpecificsUrl(qmlSpecificsFile);
-
+
m_contextObject->setStateName(stateName);
if (!fxObjectNode.isValid())
return;
@@ -347,17 +381,17 @@ static inline QString fixTypeNameForPanes(const QString &typeName)
{
QString fixedTypeName = typeName;
fixedTypeName.replace('.', '/');
- fixedTypeName.replace("QtQuick/", "Qt/");
return fixedTypeName;
}
void PropertyEditor::setupPane(const QString &typeName)
{
+ NodeMetaInfo metaInfo = model()->metaInfo(typeName);
- QUrl qmlFile = fileToUrl(locateQmlFile(QLatin1String("Qt/ItemPane.qml")));
+ QUrl qmlFile = fileToUrl(locateQmlFile(metaInfo, QLatin1String("Qt/ItemPane.qml")));
QUrl qmlSpecificsFile;
- qmlSpecificsFile = fileToUrl(locateQmlFile(fixTypeNameForPanes(typeName) + "Specifics.qml"));
+ qmlSpecificsFile = fileToUrl(locateQmlFile(metaInfo, fixTypeNameForPanes(typeName) + "Specifics.qml"));
NodeType *type = m_typeHash.value(qmlFile.toString());
if (!type) {
@@ -432,9 +466,8 @@ void PropertyEditor::changeValue(const QString &propertyName)
underscoreName.replace(QLatin1Char('.'), QLatin1Char('_'));
PropertyEditorValue *value = qobject_cast<PropertyEditorValue*>(variantToQObject(m_currentType->m_backendValuesPropertyMap.value(underscoreName)));
- if (value ==0) {
+ if (value ==0)
return;
- }
QmlObjectNode fxObjectNode(m_selectedNode);
@@ -453,8 +486,9 @@ void PropertyEditor::changeValue(const QString &propertyName)
}
if (fxObjectNode.modelNode().metaInfo().isValid() && fxObjectNode.modelNode().metaInfo().hasProperty(propertyName))
- if (fxObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == QLatin1String("QUrl")) { //turn absolute local file paths into relative paths
- QString filePath = castedValue.toUrl().toString();
+ if (fxObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == QLatin1String("QUrl")
+ || fxObjectNode.modelNode().metaInfo().propertyTypeName(propertyName) == QLatin1String("url")) { //turn absolute local file paths into relative paths
+ QString filePath = castedValue.toUrl().toString();
if (QFileInfo(filePath).exists() && QFileInfo(filePath).isAbsolute()) {
QDir fileDir(QFileInfo(model()->fileUrl().toLocalFile()).absolutePath());
castedValue = QUrl(fileDir.relativeFilePath(filePath));
@@ -618,6 +652,7 @@ void PropertyEditor::setQmlDir(const QString &qmlDir)
{
m_qmlDir = qmlDir;
+
QFileSystemWatcher *watcher = new QFileSystemWatcher(this);
watcher->addPath(m_qmlDir);
connect(watcher, SIGNAL(directoryChanged(QString)), this, SLOT(reloadQml()));
@@ -631,14 +666,18 @@ void PropertyEditor::delayedResetView()
void PropertyEditor::timerEvent(QTimerEvent *timerEvent)
{
- if (m_timerId == timerEvent->timerId()) {
+ if (m_timerId == timerEvent->timerId())
resetView();
- }
}
QString templateGeneration(NodeMetaInfo type, NodeMetaInfo superType, const QmlObjectNode &objectNode)
{
- QString qmlTemplate = QLatin1String("import QtQuick 1.0\nimport Bauhaus 1.0\n");
+ if (!templateConfiguration() && templateConfiguration()->isValid())
+ return QString();
+
+ QStringList imports = variantToStringList(templateConfiguration()->property(QLatin1String("imports")));
+
+ QString qmlTemplate = imports.join(QLatin1String("\n")) + QLatin1Char('\n');
qmlTemplate += QLatin1String("GroupBox {\n");
qmlTemplate += QString(QLatin1String("caption: \"%1\"\n")).arg(objectNode.modelNode().simplifiedTypeName());
qmlTemplate += QLatin1String("layout: VerticalLayout {\n");
@@ -659,40 +698,23 @@ QString templateGeneration(NodeMetaInfo type, NodeMetaInfo superType, const QmlO
QString typeName = type.propertyTypeName(name);
//alias resolution only possible with instance
- if (typeName == QLatin1String("alias") && objectNode.isValid())
- typeName = objectNode.instanceType(name);
-
- if (!superType.hasProperty(name) && type.propertyIsWritable(name)) {
- if (typeName == "int") {
- qmlTemplate += QString(QLatin1String(
- "IntEditor { backendValue: backendValues.%2\n caption: \"%1\"\nbaseStateFlag: isBaseState\nslider: false\n}"
- )).arg(name).arg(properName);
- emptyTemplate = false;
- }
- if (typeName == "real" || typeName == "double" || typeName == "qreal") {
- qmlTemplate += QString(QLatin1String(
- "DoubleSpinBoxAlternate {\ntext: \"%1\"\nbackendValue: backendValues.%2\nbaseStateFlag: isBaseState\n}\n"
- )).arg(name).arg(properName);
- emptyTemplate = false;
- }
- if (typeName == "string" || typeName == "QString" || typeName == "QUrl" || typeName == "url") {
- qmlTemplate += QString(QLatin1String(
- "QWidget {\nlayout: HorizontalLayout {\nLabel {\ntext: \"%1\"\ntoolTip: \"%1\"\n}\nLineEdit {\nbackendValue: backendValues.%2\nbaseStateFlag: isBaseState\n}\n}\n}\n"
- )).arg(name).arg(properName);
- emptyTemplate = false;
- }
- if (typeName == "bool") {
- qmlTemplate += QString(QLatin1String(
- "QWidget {\nlayout: HorizontalLayout {\nLabel {\ntext: \"%1\"\ntoolTip: \"%1\"\n}\nCheckBox {text: backendValues.%2.value\nbackendValue: backendValues.%2\nbaseStateFlag: isBaseState\ncheckable: true\n}\n}\n}\n"
- )).arg(name).arg(properName);
- emptyTemplate = false;
- }
- if (typeName == "color" || typeName == "QColor") {
- qmlTemplate += QString(QLatin1String(
- "ColorGroupBox {\ncaption: \"%1\"\nfinished: finishedNotify\nbackendColor: backendValues.%2\n}\n\n"
- )).arg(name).arg(properName);
- emptyTemplate = false;
- }
+ if (typeName == QLatin1String("alias") && objectNode.isValid())
+ typeName = objectNode.instanceType(name);
+
+ if (!superType.hasProperty(name) && type.propertyIsWritable(name) && !name.contains(QLatin1String("."))) {
+ foreach (const QmlJS::SimpleReaderNode::Ptr &node, templateConfiguration()->children())
+ if (variantToStringList(node->property(QLatin1String("typeNames"))).contains(typeName)) {
+ const QString fileName = propertyTemplatesPath() + node->property(QLatin1String("sourceFile")).toString();
+ QFile file(fileName);
+ if (file.open(QIODevice::ReadOnly)) {
+ QString source = file.readAll();
+ file.close();
+ qmlTemplate += source.arg(name).arg(properName);
+ emptyTemplate = false;
+ } else {
+ qWarning().nospace() << "template definition source file not found:" << fileName;
+ }
+ }
}
}
qmlTemplate += QLatin1String("}\n"); //VerticalLayout
@@ -734,7 +756,7 @@ void PropertyEditor::resetView()
foreach (const NodeMetaInfo &info, hierarchy) {
if (QFileInfo(qmlSpecificsFile.toLocalFile()).exists())
break;
- qmlSpecificsFile = fileToUrl(locateQmlFile(fixTypeNameForPanes(info.typeName()) + "Specifics.qml"));
+ qmlSpecificsFile = fileToUrl(locateQmlFile(info, fixTypeNameForPanes(info.typeName()) + "Specifics.qml"));
diffClassName = info.typeName();
}
}
@@ -767,18 +789,17 @@ void PropertyEditor::resetView()
ctxt->setContextProperty("finishedNotify", QVariant(false));
if (specificQmlData.isEmpty())
type->m_contextObject->setSpecificQmlData(specificQmlData);
-
+
type->m_contextObject->setGlobalBaseUrl(qmlFile);
type->m_contextObject->setSpecificQmlData(specificQmlData);
type->m_view->setSource(qmlFile);
ctxt->setContextProperty("finishedNotify", QVariant(true));
} else {
QmlObjectNode fxObjectNode;
- if (m_selectedNode.isValid()) {
+ if (m_selectedNode.isValid())
fxObjectNode = QmlObjectNode(m_selectedNode);
- }
QDeclarativeContext *ctxt = type->m_view->rootContext();
-
+
ctxt->setContextProperty("finishedNotify", QVariant(false));
if (specificQmlData.isEmpty())
type->m_contextObject->setSpecificQmlData(specificQmlData);
@@ -948,9 +969,8 @@ void PropertyEditor::nodeIdChanged(const ModelNode& node, const QString& newId,
if (node == m_selectedNode) {
- if (m_currentType) {
+ if (m_currentType)
setValue(node, "id", newId);
- }
}
}
@@ -971,7 +991,6 @@ void PropertyEditor::select(const ModelNode &node)
QWidget *PropertyEditor::widget()
{
- delayedResetView();
return m_stackedWidget;
}
@@ -1008,7 +1027,7 @@ void PropertyEditor::reloadQml()
QString PropertyEditor::qmlFileName(const NodeMetaInfo &nodeInfo) const
{
if (nodeInfo.typeName().split('.').last() == "QDeclarativeItem")
- return "Qt/ItemPane.qml";
+ return "QtQuick/ItemPane.qml";
const QString fixedTypeName = fixTypeNameForPanes(nodeInfo.typeName());
return fixedTypeName + QLatin1String("Pane.qml");
}
@@ -1039,21 +1058,24 @@ QUrl PropertyEditor::qmlForNode(const ModelNode &modelNode, QString &className)
hierarchy << modelNode.metaInfo().superClasses();
foreach (const NodeMetaInfo &info, hierarchy) {
- QUrl fileUrl = fileToUrl(locateQmlFile(qmlFileName(info)));
+ QUrl fileUrl = fileToUrl(locateQmlFile(info, qmlFileName(info)));
if (fileUrl.isValid()) {
className = info.typeName();
return fileUrl;
}
}
}
- return fileToUrl(QDir(m_qmlDir).filePath("Qt/emptyPane.qml"));
+ return fileToUrl(QDir(m_qmlDir).filePath("QtQuick/emptyPane.qml"));
}
-QString PropertyEditor::locateQmlFile(const QString &relativePath) const
+QString PropertyEditor::locateQmlFile(const NodeMetaInfo &info, const QString &relativePath) const
{
QDir fileSystemDir(m_qmlDir);
- static QDir resourcesDir(":/propertyeditor");
+ static QDir resourcesDir(resourcePropertyEditorPath);
+ QDir importDir(info.importDirectoryPath() + QLatin1String(Constants::QML_DESIGNER_SUBFOLDER));
+ if (importDir.exists(relativePath))
+ return importDir.absoluteFilePath(relativePath);
if (fileSystemDir.exists(relativePath))
return fileSystemDir.absoluteFilePath(relativePath);
if (resourcesDir.exists(relativePath))
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h
index 8ee782f40c..50968c0e85 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditor.h
@@ -129,7 +129,7 @@ private: //functions
QString qmlFileName(const NodeMetaInfo &nodeInfo) const;
QUrl fileToUrl(const QString &filePath) const;
QUrl qmlForNode(const ModelNode &modelNode, QString &className) const;
- QString locateQmlFile(const QString &relativePath) const;
+ QString locateQmlFile(const NodeMetaInfo &info, const QString &relativePath) const;
void select(const ModelNode& node);
void delayedResetView();
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h
index c5cd9831fb..583a6f1fd8 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorcontextobject.h
@@ -33,6 +33,7 @@
#include <QObject>
#include <QUrl>
#include <QDeclarativePropertyMap>
+#include <QColor>
namespace QmlDesigner {
@@ -64,6 +65,8 @@ public:
QDeclarativePropertyMap* backendValues() const { return m_backendValues; }
+ Q_INVOKABLE QString convertColorToString(const QColor &color) { return color.name(); }
+
signals:
void globalBaseUrlChanged();
void specificsUrlChanged();
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp
index 84bfaedb3f..81f8e7a99e 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.cpp
@@ -29,6 +29,7 @@
#include "propertyeditorvalue.h"
#include <QRegExp>
+#include <QUrl>
#include <abstractview.h>
#include <nodeabstractproperty.h>
#include <nodeproperty.h>
@@ -54,9 +55,8 @@ QVariant PropertyEditorValue::value() const
{
QVariant returnValue = m_value;
if (modelNode().isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().hasProperty(name()))
- if (modelNode().metaInfo().propertyTypeName(name()) == QLatin1String("QUrl")) {
+ if (modelNode().metaInfo().propertyTypeName(name()) == QLatin1String("QUrl"))
returnValue = returnValue.toUrl().toString();
- }
return returnValue;
}
@@ -66,9 +66,8 @@ static bool cleverDoubleCompare(QVariant value1, QVariant value2)
int a = value1.toDouble() * 100;
int b = value2.toDouble() * 100;
- if (qFuzzyCompare((qreal(a) / 100), (qreal(b) / 100))) {
+ if (qFuzzyCompare((qreal(a) / 100), (qreal(b) / 100)))
return true;
- }
}
return false;
}
@@ -84,12 +83,10 @@ static bool cleverColorCompare(QVariant value1, QVariant value2)
return false;
return (c1.alpha() == c2.alpha());
}
- if ((value1.type() == QVariant::String) && (value2.type() == QVariant::Color)) {
+ if ((value1.type() == QVariant::String) && (value2.type() == QVariant::Color))
return cleverColorCompare(QVariant(QColor(value1.toString())), value2);
- }
- if ((value1.type() == QVariant::Color) && (value2.type() == QVariant::String)) {
+ if ((value1.type() == QVariant::Color) && (value2.type() == QVariant::String))
return cleverColorCompare(value1, QVariant(QColor(value2.toString())));
- }
return false;
}
@@ -113,14 +110,23 @@ static void fixAmbigousColorNames(const QmlDesigner::ModelNode &modelNode, const
}
}
+static void fixUrl(const QmlDesigner::ModelNode &modelNode, const QString &name, QVariant *value)
+{
+ if (modelNode.isValid() && modelNode.metaInfo().isValid()
+ && (modelNode.metaInfo().propertyTypeName(name) == "QUrl"
+ || modelNode.metaInfo().propertyTypeName(name) == "url")) {
+ if (!value->isValid())
+ *value = QString(QLatin1String(""));
+ }
+}
+
void PropertyEditorValue::setValueWithEmit(const QVariant &value)
{
if (m_value != value || isBound()) {
QVariant newValue = value;
if (modelNode().isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().hasProperty(name()))
- if (modelNode().metaInfo().propertyTypeName(name()) == QLatin1String("QUrl")) {
+ if (modelNode().metaInfo().propertyTypeName(name()) == QLatin1String("QUrl"))
newValue = QUrl(newValue.toString());
- }
if (cleverDoubleCompare(newValue, m_value))
return;
@@ -143,6 +149,7 @@ void PropertyEditorValue::setValue(const QVariant &value)
m_value = value;
fixAmbigousColorNames(modelNode(), name(), &m_value);
+ fixUrl(modelNode(), name(), &m_value);
if (m_value.isValid())
emit valueChangedQml();
@@ -172,6 +179,11 @@ void PropertyEditorValue::setExpression(const QString &expression)
}
}
+QString PropertyEditorValue::valueToString() const
+{
+ return value().toString();
+}
+
bool PropertyEditorValue::isInSubState() const
{
const QmlDesigner::QmlObjectNode objectNode(modelNode());
@@ -315,9 +327,8 @@ void PropertyEditorNodeWrapper::add(const QString &type)
propertyType.chop(1);
m_modelNode = m_editorValue->modelNode().view()->createModelNode(propertyType, 4, 7);
m_editorValue->modelNode().nodeAbstractProperty(m_editorValue->name()).reparentHere(m_modelNode);
- if (!m_modelNode.isValid()) {
+ if (!m_modelNode.isValid())
qWarning("PropertyEditorNodeWrapper::add failed");
- }
} else {
qWarning("PropertyEditorNodeWrapper::add failed - node invalid");
}
@@ -389,9 +400,8 @@ void PropertyEditorNodeWrapper::setup()
void PropertyEditorNodeWrapper::update()
{
if (m_editorValue && m_editorValue->modelNode().isValid()) {
- if (m_editorValue->modelNode().hasProperty(m_editorValue->name()) && m_editorValue->modelNode().property(m_editorValue->name()).isNodeProperty()) {
+ if (m_editorValue->modelNode().hasProperty(m_editorValue->name()) && m_editorValue->modelNode().property(m_editorValue->name()).isNodeProperty())
m_modelNode = m_editorValue->modelNode().nodeProperty(m_editorValue->name()).modelNode();
- }
setup();
emit existsChanged();
emit typeChanged();
diff --git a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h
index 6c9dd0951c..918de7bc8a 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h
+++ b/src/plugins/qmldesigner/components/propertyeditor/propertyeditorvalue.h
@@ -79,6 +79,7 @@ class PropertyEditorValue : public QObject
Q_OBJECT
Q_PROPERTY(QVariant value READ value WRITE setValueWithEmit NOTIFY valueChangedQml)
Q_PROPERTY(QString expression READ expression WRITE setExpressionWithEmit NOTIFY expressionChanged FINAL)
+ Q_PROPERTY(QString valueToString READ valueToString NOTIFY valueChangedQml FINAL)
Q_PROPERTY(bool isInModel READ isInModel NOTIFY valueChangedQml FINAL)
Q_PROPERTY(bool isInSubState READ isInSubState NOTIFY valueChangedQml FINAL)
Q_PROPERTY(bool isBound READ isBound NOTIFY isBoundChanged FINAL)
@@ -99,6 +100,8 @@ public:
void setExpressionWithEmit(const QString &expression);
void setExpression(const QString &expression);
+ QString valueToString() const;
+
bool isInSubState() const;
bool isInModel() const;
diff --git a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
index f853f57a2c..32af375c77 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/qmlanchorbindingproxy.cpp
@@ -363,9 +363,8 @@ void QmlAnchorBindingProxy::setBottomAnchor(bool anchor)
removeBottomAnchor();
} else {
calcBottomMargin();
- if (topAnchored()) {
+ if (topAnchored())
backupPropertyAndRemove(modelNode(), "height");
- }
}
emit bottomAnchorChanged();
@@ -388,9 +387,8 @@ void QmlAnchorBindingProxy::setLeftAnchor(bool anchor)
} else {
calcLeftMargin();
backupPropertyAndRemove(modelNode(), "x");
- if (rightAnchored()) {
+ if (rightAnchored())
backupPropertyAndRemove(modelNode(), "width");
- }
}
emit leftAnchorChanged();
@@ -412,9 +410,8 @@ void QmlAnchorBindingProxy::setRightAnchor(bool anchor)
removeRightAnchor();
} else {
calcRightMargin();
- if (leftAnchored()) {
+ if (leftAnchored())
backupPropertyAndRemove(modelNode(), "width");
- }
}
emit rightAnchorChanged();
if (hasAnchors() != anchor)
@@ -529,9 +526,8 @@ void QmlAnchorBindingProxy::setTopAnchor(bool anchor)
} else {
calcTopMargin();
backupPropertyAndRemove(modelNode(), "y");
- if (bottomAnchored()) {
+ if (bottomAnchored())
backupPropertyAndRemove(modelNode(), "height");
- }
}
emit topAnchorChanged();
if (hasAnchors() != anchor)
diff --git a/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp b/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp
index 8e37ce8af9..e766f7ac0e 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/resetwidget.cpp
@@ -51,7 +51,7 @@ ResetWidget::ResetWidget(QWidget *parent) : QGroupBox(parent), m_backendObject(0
m_vlayout->setContentsMargins(2,2,2,2);
QPushButton *b = new QPushButton(this);
- b->setText("reset all properties");
+ b->setText(tr("reset all properties"));
m_vlayout->addWidget(b);
setLayout(m_vlayout);
diff --git a/src/plugins/qmldesigner/components/propertyeditor/siblingcombobox.cpp b/src/plugins/qmldesigner/components/propertyeditor/siblingcombobox.cpp
index 62c29a0f0a..900732cc71 100644
--- a/src/plugins/qmldesigner/components/propertyeditor/siblingcombobox.cpp
+++ b/src/plugins/qmldesigner/components/propertyeditor/siblingcombobox.cpp
@@ -34,7 +34,7 @@ namespace QmlDesigner {
void SiblingComboBox::setItemNode(const QVariant &itemNode)
{
-
+
if (!itemNode.value<ModelNode>().isValid() || !QmlItemNode(itemNode.value<ModelNode>()).hasNodeParent())
return;
m_itemNode = itemNode.value<ModelNode>();
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp
index adb627a003..7e6808f177 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditormodel.cpp
@@ -106,22 +106,20 @@ QVariant StatesEditorModel::data(const QModelIndex &index, int role) const
if (index.row() == 0) {
return QString(tr("base state", "Implicit default state"));
} else {
- if (stateNode.hasVariantProperty("name")) {
+ if (stateNode.hasVariantProperty("name"))
return stateNode.variantProperty("name").value();
- } else {
+ else
return QVariant();
- }
}
}
case StateImageSourceRole: {
static int randomNumber = 0;
randomNumber++;
- if (index.row() == 0) {
+ if (index.row() == 0)
return QString("image://qmldesigner_stateseditor/baseState-%1").arg(randomNumber);
- } else {
+ else
return QString("image://qmldesigner_stateseditor/%1-%2").arg(index.internalId()).arg(randomNumber);
- }
}
case NodeId : return index.internalId();
}
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
index 896ce12007..7e9002213c 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.cpp
@@ -53,17 +53,15 @@ namespace QmlDesigner {
StatesEditorView::StatesEditorView(QObject *parent) :
QmlModelView(parent),
m_statesEditorModel(new StatesEditorModel(this)),
+ m_statesEditorWidget(new StatesEditorWidget(this, m_statesEditorModel.data())),
m_lastIndex(-1)
{
Q_ASSERT(m_statesEditorModel);
// base state
}
-StatesEditorWidget *StatesEditorView::widget()
+QWidget *StatesEditorView::widget()
{
- if (m_statesEditorWidget.isNull())
- m_statesEditorWidget = new StatesEditorWidget(this, m_statesEditorModel.data());
-
return m_statesEditorWidget.data();
}
@@ -79,11 +77,10 @@ void StatesEditorView::removeState(int nodeId)
setCurrentState(baseState());
} else if (parentProperty.isValid()){
int index = parentProperty.indexOf(stateNode);
- if (index == 0) {
+ if (index == 0)
setCurrentState(parentProperty.at(1));
- } else {
+ else
setCurrentState(parentProperty.at(index - 1));
- }
}
@@ -112,11 +109,10 @@ void StatesEditorView::synchonizeCurrentStateFromWidget()
void StatesEditorView::createNewState()
{
- if (currentState().isBaseState()) {
+ if (currentState().isBaseState())
addState();
- } else {
+ else
duplicateCurrentState();
- }
}
void StatesEditorView::addState()
@@ -137,8 +133,9 @@ void StatesEditorView::addState()
try {
if ((rootStateGroup().allStates().count() < 1) && //QtQuick import might be missing
- (!model()->hasImport(Import::createLibraryImport("QtQuick", "1.0"), true) &&
- !model()->hasImport(Import::createLibraryImport("QtQuick", "1.1"), true)))
+ (!model()->hasImport(Import::createLibraryImport("QtQuick", "1.0"), true)
+ && !model()->hasImport(Import::createLibraryImport("QtQuick", "1.1"), true)
+ && !model()->hasImport(Import::createLibraryImport("QtQuick", "2.0"), true)))
model()->changeImports(QList<Import>() << Import::createLibraryImport("QtQuick", "1.0"), QList<Import>());
ModelNode newState = rootStateGroup().addState(newStateName);
setCurrentState(newState);
@@ -153,11 +150,10 @@ void StatesEditorView::resetModel()
m_statesEditorModel->reset();
if (m_statesEditorWidget) {
- if (currentState().isBaseState()) {
+ if (currentState().isBaseState())
m_statesEditorWidget->setCurrentStateInternalId(currentState().modelNode().internalId());
- } else {
+ else
m_statesEditorWidget->setCurrentStateInternalId(0);
- }
}
}
@@ -257,9 +253,8 @@ void StatesEditorView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
if (removedNode.hasParentProperty()) {
const NodeAbstractProperty propertyParent = removedNode.parentProperty();
- if (propertyParent.parentModelNode().isRootNode() && propertyParent.name() == "states") {
+ if (propertyParent.parentModelNode().isRootNode() && propertyParent.name() == "states")
m_lastIndex = propertyParent.indexOf(removedNode);
- }
}
if (currentState().isValid() && removedNode == currentState())
setCurrentState(baseState());
@@ -309,11 +304,10 @@ void StatesEditorView::actualStateChanged(const ModelNode &node)
{
QmlModelState newQmlModelState(node);
- if (newQmlModelState.isBaseState()) {
+ if (newQmlModelState.isBaseState())
m_statesEditorWidget->setCurrentStateInternalId(0);
- } else {
+ else
m_statesEditorWidget->setCurrentStateInternalId(newQmlModelState.modelNode().internalId());
- }
QmlModelView::actualStateChanged(node);
}
@@ -336,7 +330,7 @@ void StatesEditorView::instancesPreviewImageChanged(const QVector<ModelNode> &no
{
int minimumIndex = 10000;
int maximumIndex = -1;
- foreach(const ModelNode &node, nodeList) {
+ foreach (const ModelNode &node, nodeList) {
if (node.isRootNode()) {
minimumIndex = qMin(minimumIndex, 0);
maximumIndex = qMax(maximumIndex, 0);
diff --git a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h
index 558b12337c..794bd1ce6a 100644
--- a/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h
+++ b/src/plugins/qmldesigner/components/stateseditor/stateseditorview.h
@@ -76,7 +76,7 @@ public:
void instancesPreviewImageChanged(const QVector<ModelNode> &nodeList);
- StatesEditorWidget *widget();
+ QWidget *widget();
public slots:
void synchonizeCurrentStateFromWidget();
@@ -84,6 +84,7 @@ public slots:
void removeState(int nodeId);
private:
+ StatesEditorWidget *statesEditorWidget() const;
void resetModel();
void addState();
void duplicateCurrentState();
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyle.metainfo b/src/plugins/qmldesigner/customstyleplugin/customstyle.metainfo
deleted file mode 100644
index c148923cd1..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/customstyle.metainfo
+++ /dev/null
@@ -1,93 +0,0 @@
-<metainfo>
- <node name="Qt.labs.components.custom.Button" icon=":/customstyleplugin/images/button16.png">
- <itemlibraryentry name="Button" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/button.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="30"/>
- <property name="text" type="QString" value="Button"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.BasicButton" icon=":/customstyleplugin/images/button16.png">
- <itemlibraryentry name="BasicButton" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/button.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.BusyIndicator" icon=":/customstyleplugin/images/busyindicator16.png">
- <itemlibraryentry name="BusyIndicator" category="ComponentsCustom Style" libraryIcon=":/customstyleplugin/images/busyindicator.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.CheckBox" icon=":/customstyleplugin/images/checkbox16.png">
- <itemlibraryentry name="CheckBox" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/checkbox.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="30"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.ChoiceList" icon=":/customstyleplugin/images/choicelist16.png">
- <itemlibraryentry name="ChoiceList" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/choicelist.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="40"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.ProgressBar" icon=":/customstyleplugin/images/progressbar16.png">
- <itemlibraryentry name="ProgressBar" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/progressbar.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.SpinBox">
- <itemlibraryentry name="SpinBox" category="Components Custom Style" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.RadioButton" icon=":/customstyleplugin/images/radiobutton16.png">
- <itemlibraryentry name="RadioButton" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/radiobutton.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="30"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.TextArea" icon=":/customstyleplugin/images/textarea16.png">
- <itemlibraryentry name="TextArea" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/textarea.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="180"/>
- <property name="text" type="QString" value="TextArea"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.ButtonRow" icon=":/customstyleplugin/images/buttonrow16.png">
- <itemlibraryentry name="ButtonRow" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/buttonrow.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="120"/>
- <property name="height" type="int" value="20"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.ButtonColumn" icon=":/customstyleplugin/images/buttoncolumn16.png">
- <itemlibraryentry name="ButtonColumn" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/buttoncolumn.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="120"/>
- <property name="height" type="int" value="20"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.Slider" icon=":/customstyleplugin/images/slider16.png">
- <itemlibraryentry name="Slider (horizontal)" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/slider.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="30"/>
- <property name="orientation" type="int" value="1"/>
- </itemlibraryentry>
- <itemlibraryentry name="Slider (vertical)" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/sliderh.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="30"/>
- <property name="height" type="int" value="180"/>
- <property name="orientation" type="int" value="2"/>
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.Switch" icon=":/customstyleplugin/images/switchbutton16.png">
- <itemlibraryentry name="Switch" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/switchbutton.png" version="1.0" requiredImport="Qt.labs.components.custom">
- </itemlibraryentry>
- </node>
- <node name="Qt.labs.components.custom.TextField" icon=":/customstyleplugin/images/textfield16.png">
- <itemlibraryentry name="TextField" category="Components Custom Style" libraryIcon=":/customstyleplugin/images/textfield.png" version="1.0" requiredImport="Qt.labs.components.custom">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="50"/>
- <property name="text" type="QString" value="TextField"/>
- </itemlibraryentry>
- </node>
-</metainfo>
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.json b/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.json
deleted file mode 100644
index d3a62366ae..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-
-
-"Vendor" : "Digia Plc",
-
-
-
-
-"Category" : "Qt Quick",
-
-
-"Description" : "Plugin for Custom Style Items.",
-
-
-"Url" : "http://www.qt-project.org"
-
-
-
-}
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pri b/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pri
deleted file mode 100644
index 3e30ea983e..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pri
+++ /dev/null
@@ -1,13 +0,0 @@
-TARGET = customstyleplugin
-TEMPLATE = lib
-CONFIG += plugin
-
-include (../designercore/iwidgetplugin.pri)
-
-SOURCES += $$PWD/customstyleplugin.cpp
-
-HEADERS += $$PWD/customstyleplugin.h $$PWD/../designercore/include/iwidgetplugin.h
-
-RESOURCES += $$PWD/customstyleplugin.qrc
-
-OTHER_FILES += $$PWD/customstyle.metainfo
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pro b/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pro
deleted file mode 100644
index 4db17c2462..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-include(../../../../qtcreator.pri)
-include(../../../private_headers.pri)
-include(customstyleplugin.pri)
-include(../plugindestdir.pri)
diff --git a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.qrc b/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.qrc
deleted file mode 100644
index f0ac6f5ba7..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/customstyleplugin.qrc
+++ /dev/null
@@ -1,41 +0,0 @@
-<RCC>
- <qresource prefix="/customstyleplugin">
- <file>customstyle.metainfo</file>
- <file>images/item-icon16.png</file>
- <file>images/item-icon.png</file>
- <file>images/button.png</file>
- <file>images/button16.png</file>
- <file>images/checkbox16.png</file>
- <file>images/checkbox.png</file>
- <file>images/choicelist16.png</file>
- <file>images/choicelist.png</file>
- <file>images/progressbar.png</file>
- <file>images/progressbar16.png</file>
- <file>images/radiobutton.png</file>
- <file>images/radiobutton16.png</file>
- <file>images/slider.png</file>
- <file>images/slider16.png</file>
- <file>images/textarea16.png</file>
- <file>images/textarea.png</file>
- <file>images/textfield16.png</file>
- <file>images/textfield.png</file>
- <file>images/window16.png</file>
- <file>images/window.png</file>
- <file>images/tabbutton16.png</file>
- <file>images/tabbutton.png</file>
- <file>images/busyindicator16.png</file>
- <file>images/busyindicator.png</file>
- <file>images/sliderh16.png</file>
- <file>images/sliderh.png</file>
- <file>images/switchbutton16.png</file>
- <file>images/switchbutton.png</file>
- <file>images/buttonrow.png</file>
- <file>images/buttonrow16.png</file>
- <file>images/tabbar.png</file>
- <file>images/tabbar16.png</file>
- <file>images/toolbar.png</file>
- <file>images/toolbar16.png</file>
- <file>images/buttoncolumn.png</file>
- <file>images/buttoncolumn16.png</file>
- </qresource>
-</RCC>
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/busyindicator.png b/src/plugins/qmldesigner/customstyleplugin/images/busyindicator.png
deleted file mode 100644
index 89d0283f26..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/busyindicator.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/busyindicator16.png b/src/plugins/qmldesigner/customstyleplugin/images/busyindicator16.png
deleted file mode 100644
index 7e3b2d3158..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/busyindicator16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/busyindicatora.png b/src/plugins/qmldesigner/customstyleplugin/images/busyindicatora.png
deleted file mode 100644
index 433f4d426b..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/busyindicatora.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/busyindicatora16.png b/src/plugins/qmldesigner/customstyleplugin/images/busyindicatora16.png
deleted file mode 100644
index 82de5b0a1b..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/busyindicatora16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/button.png b/src/plugins/qmldesigner/customstyleplugin/images/button.png
deleted file mode 100644
index 828af210ac..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/button.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/button16.png b/src/plugins/qmldesigner/customstyleplugin/images/button16.png
deleted file mode 100644
index 8d95760b27..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/button16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn.png b/src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn.png
deleted file mode 100644
index 46db8f6ab5..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn16.png b/src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn16.png
deleted file mode 100644
index 883258048f..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/buttoncolumn16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/buttonrow.png b/src/plugins/qmldesigner/customstyleplugin/images/buttonrow.png
deleted file mode 100644
index 9727749de9..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/buttonrow.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/buttonrow16.png b/src/plugins/qmldesigner/customstyleplugin/images/buttonrow16.png
deleted file mode 100644
index 420de41860..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/buttonrow16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/checkbox.png b/src/plugins/qmldesigner/customstyleplugin/images/checkbox.png
deleted file mode 100644
index 0f4a826f4d..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/checkbox.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/checkbox16.png b/src/plugins/qmldesigner/customstyleplugin/images/checkbox16.png
deleted file mode 100644
index 01f09e3515..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/checkbox16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/choicelist.png b/src/plugins/qmldesigner/customstyleplugin/images/choicelist.png
deleted file mode 100644
index 3fd9876ada..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/choicelist.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/choicelist16.png b/src/plugins/qmldesigner/customstyleplugin/images/choicelist16.png
deleted file mode 100644
index 602b28229e..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/choicelist16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/item-icon.png b/src/plugins/qmldesigner/customstyleplugin/images/item-icon.png
deleted file mode 100644
index fc53d38ae7..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/item-icon.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/item-icon16.png b/src/plugins/qmldesigner/customstyleplugin/images/item-icon16.png
deleted file mode 100644
index 7d2d7a5050..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/item-icon16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/progressbar.png b/src/plugins/qmldesigner/customstyleplugin/images/progressbar.png
deleted file mode 100644
index 040f5bac03..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/progressbar.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/progressbar16.png b/src/plugins/qmldesigner/customstyleplugin/images/progressbar16.png
deleted file mode 100644
index e2432475d5..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/progressbar16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/radiobutton.png b/src/plugins/qmldesigner/customstyleplugin/images/radiobutton.png
deleted file mode 100644
index 143b6a99f4..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/radiobutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/radiobutton16.png b/src/plugins/qmldesigner/customstyleplugin/images/radiobutton16.png
deleted file mode 100644
index 94912c2034..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/radiobutton16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/slider.png b/src/plugins/qmldesigner/customstyleplugin/images/slider.png
deleted file mode 100644
index 746ed51932..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/slider.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/slider16.png b/src/plugins/qmldesigner/customstyleplugin/images/slider16.png
deleted file mode 100644
index 10c4928b3c..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/slider16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/sliderh.png b/src/plugins/qmldesigner/customstyleplugin/images/sliderh.png
deleted file mode 100644
index 87cd55678f..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/sliderh.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/sliderh16.png b/src/plugins/qmldesigner/customstyleplugin/images/sliderh16.png
deleted file mode 100644
index c419911336..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/sliderh16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/switchbutton.png b/src/plugins/qmldesigner/customstyleplugin/images/switchbutton.png
deleted file mode 100644
index 48bf247cb8..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/switchbutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/switchbutton16.png b/src/plugins/qmldesigner/customstyleplugin/images/switchbutton16.png
deleted file mode 100644
index 238a1be632..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/switchbutton16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/tabbar.png b/src/plugins/qmldesigner/customstyleplugin/images/tabbar.png
deleted file mode 100644
index 2f44e62b3f..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/tabbar.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/tabbar16.png b/src/plugins/qmldesigner/customstyleplugin/images/tabbar16.png
deleted file mode 100644
index 57c7906982..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/tabbar16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/tabbutton.png b/src/plugins/qmldesigner/customstyleplugin/images/tabbutton.png
deleted file mode 100644
index d9f5fdb3f9..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/tabbutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/tabbutton16.png b/src/plugins/qmldesigner/customstyleplugin/images/tabbutton16.png
deleted file mode 100644
index 8e279cff65..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/tabbutton16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/textarea.png b/src/plugins/qmldesigner/customstyleplugin/images/textarea.png
deleted file mode 100644
index 86f2969d00..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/textarea.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/textarea16.png b/src/plugins/qmldesigner/customstyleplugin/images/textarea16.png
deleted file mode 100644
index 899a4bca2e..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/textarea16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/textfield.png b/src/plugins/qmldesigner/customstyleplugin/images/textfield.png
deleted file mode 100644
index b0f13da50d..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/textfield.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/textfield16.png b/src/plugins/qmldesigner/customstyleplugin/images/textfield16.png
deleted file mode 100644
index 7feb8c7158..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/textfield16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/toolbar.png b/src/plugins/qmldesigner/customstyleplugin/images/toolbar.png
deleted file mode 100644
index e67c042422..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/toolbar.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/toolbar16.png b/src/plugins/qmldesigner/customstyleplugin/images/toolbar16.png
deleted file mode 100644
index f4a0c5ef69..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/toolbar16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/window.png b/src/plugins/qmldesigner/customstyleplugin/images/window.png
deleted file mode 100644
index fc53d38ae7..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/window.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/customstyleplugin/images/window16.png b/src/plugins/qmldesigner/customstyleplugin/images/window16.png
deleted file mode 100644
index 7d2d7a5050..0000000000
--- a/src/plugins/qmldesigner/customstyleplugin/images/window16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/designercore/designercore.pri b/src/plugins/qmldesigner/designercore/designercore-lib.pri
index 4cd9644a99..96609f2ac6 100644
--- a/src/plugins/qmldesigner/designercore/designercore.pri
+++ b/src/plugins/qmldesigner/designercore/designercore-lib.pri
@@ -5,6 +5,7 @@ QT += script \
network
DEFINES += TEST_EXPORTS
+DEFINES += DESIGNER_CORE_LIBRARY
INCLUDEPATH += $$PWD \
$$PWD/include
@@ -16,7 +17,7 @@ include (../../../../share/qtcreator/qml/qmlpuppet/container/container.pri)
SOURCES += $$PWD/model/abstractview.cpp \
$$PWD/model/rewriterview.cpp \
$$PWD/metainfo/metainfo.cpp \
- $$PWD/metainfo/metainfoparser.cpp \
+ $$PWD/metainfo/metainforeader.cpp \
$$PWD/metainfo/nodemetainfo.cpp \
$$PWD/metainfo/itemlibraryinfo.cpp \
$$PWD/metainfo/subcomponentmanager.cpp \
@@ -75,14 +76,14 @@ SOURCES += $$PWD/model/abstractview.cpp \
$$PWD/model/qmltextgenerator.cpp \
$$PWD/model/modelmerger.cpp \
$$PWD/exceptions/rewritingexception.cpp \
- $$PWD/model/modelnodecontextmenu.cpp
+ $$PWD/model/viewmanager.cpp
-HEADERS += $$PWD/include/corelib_global.h \
+HEADERS += $$PWD/include/qmldesignercorelib_global.h \
$$PWD/include/abstractview.h \
$$PWD/include/nodeinstanceview.h \
$$PWD/include/rewriterview.h \
$$PWD/include/metainfo.h \
- $$PWD/include/metainfoparser.h \
+ $$PWD/include/metainforeader.h \
$$PWD/include/nodemetainfo.h \
$$PWD/include/itemlibraryinfo.h \
$$PWD/model/internalproperty.h \
@@ -103,6 +104,7 @@ HEADERS += $$PWD/include/corelib_global.h \
$$PWD/include/invalidargumentexception.h \
$$PWD/include/notimplementedexception.h \
$$PWD/include/invalidpropertyexception.h \
+ $$PWD/include/invalidmodelnodeexception.h \
$$PWD/include/invalidmodelstateexception.h \
$$PWD/include/removebasestateexception.h \
$$PWD/include/invalididexception.h \
@@ -145,7 +147,7 @@ HEADERS += $$PWD/include/corelib_global.h \
$$PWD/include/mathutils.h \
$$PWD/include/customnotifications.h \
$$PWD/include/rewritingexception.h \
- $$PWD//model/modelnodecontextmenu.h
+ $$PWD/include/viewmanager.h
contains(CONFIG, plugin) {
# If core.pri has been included in the qmldesigner plugin
diff --git a/src/plugins/qmldesigner/designercore/exceptions/invalididexception.cpp b/src/plugins/qmldesigner/designercore/exceptions/invalididexception.cpp
index 1b40e821a5..9fe318cb44 100644
--- a/src/plugins/qmldesigner/designercore/exceptions/invalididexception.cpp
+++ b/src/plugins/qmldesigner/designercore/exceptions/invalididexception.cpp
@@ -40,11 +40,10 @@ InvalidIdException::InvalidIdException(int line,
InvalidArgumentException(line, function, file, "id"),
m_id(id)
{
- if (reason == InvalidCharacters) {
+ if (reason == InvalidCharacters)
m_description = QCoreApplication::translate("InvalidIdException", "Only alphanumeric characters and underscore allowed.\nIds must begin with a lowercase letter.");
- } else {
+ else
m_description = QCoreApplication::translate("InvalidIdException", "Ids have to be unique.");
- }
}
InvalidIdException::InvalidIdException(int line,
diff --git a/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp
index 8159d752b6..74bf4ba42a 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/changeimportsvisitor.cpp
@@ -51,11 +51,10 @@ bool ChangeImportsVisitor::add(QmlJS::AST::UiProgram *ast, const Import &import)
if (ast->imports && ast->imports->import) {
int insertionPoint = 0;
- if (ast->members && ast->members->member) {
+ if (ast->members && ast->members->member)
insertionPoint = ast->members->member->firstSourceLocation().begin();
- } else {
+ else
insertionPoint = m_source.length();
- }
while (insertionPoint > 0) {
--insertionPoint;
const QChar c = m_source.at(insertionPoint);
@@ -93,11 +92,10 @@ bool ChangeImportsVisitor::remove(QmlJS::AST::UiProgram *ast, const Import &impo
bool ChangeImportsVisitor::equals(QmlJS::AST::UiImport *ast, const Import &import)
{
- if (import.isLibraryImport()) {
+ if (import.isLibraryImport())
return toString(ast->importUri) == import.url();
- } else if (import.isFileImport()) {
+ else if (import.isFileImport())
return ast->fileName == import.file();
- } else {
+ else
return false;
- }
}
diff --git a/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp
index a656ccd379..720a2e6cb5 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/changepropertyvisitor.cpp
@@ -120,9 +120,8 @@ void ChangePropertyVisitor::replaceInMembers(UiObjectInitializer *initializer,
// for grouped properties:
else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
- if (toString(def->qualifiedTypeNameId) == prefix) {
+ if (toString(def->qualifiedTypeNameId) == prefix)
replaceInMembers(def->initializer, suffix);
- }
}
}
}
@@ -172,27 +171,25 @@ void ChangePropertyVisitor::replaceMemberValue(UiObjectMember *propertyMember, b
bool ChangePropertyVisitor::isMatchingPropertyMember(const QString &propName,
UiObjectMember *member)
{
- if (UiObjectBinding *objectBinding = AST::cast<UiObjectBinding *>(member)) {
+ if (UiObjectBinding *objectBinding = AST::cast<UiObjectBinding *>(member))
return propName == toString(objectBinding->qualifiedId);
- } else if (UiScriptBinding *scriptBinding = AST::cast<UiScriptBinding *>(member)) {
+ else if (UiScriptBinding *scriptBinding = AST::cast<UiScriptBinding *>(member))
return propName == toString(scriptBinding->qualifiedId);
- } else if (UiArrayBinding *arrayBinding = AST::cast<UiArrayBinding *>(member)) {
+ else if (UiArrayBinding *arrayBinding = AST::cast<UiArrayBinding *>(member))
return propName == toString(arrayBinding->qualifiedId);
- } else if (UiPublicMember *publicMember = AST::cast<UiPublicMember *>(member)) {
+ else if (UiPublicMember *publicMember = AST::cast<UiPublicMember *>(member))
return propName == publicMember->name;
- } else {
+ else
return false;
- }
}
// FIXME: duplicate code in the QmlJS::Rewriter class, remove this
bool ChangePropertyVisitor::nextMemberOnSameLine(UiObjectMemberList *members)
{
- if (members && members->next && members->next->member) {
+ if (members && members->next && members->next->member)
return members->next->member->firstSourceLocation().startLine == members->member->lastSourceLocation().startLine;
- } else {
+ else
return false;
- }
}
// FIXME: duplicate code in the QmlJS::Rewriter class, remove this
diff --git a/src/plugins/qmldesigner/designercore/filemanager/filemanager.pri b/src/plugins/qmldesigner/designercore/filemanager/filemanager.pri
index a2a6933c03..ac11d4c4c6 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/filemanager.pri
+++ b/src/plugins/qmldesigner/designercore/filemanager/filemanager.pri
@@ -13,7 +13,8 @@ SOURCES += \
$$PWD/objectlengthcalculator.cpp \
$$PWD/firstdefinitionfinder.cpp \
$$PWD/moveobjectbeforeobjectvisitor.cpp \
- $$PWD/changeimportsvisitor.cpp
+ $$PWD/changeimportsvisitor.cpp \
+ $$PWD/qmlwarningdialog.cpp
HEADERS += \
$$PWD/qmlrewriter.h \
$$PWD/qmlrefactoring.h \
@@ -29,4 +30,8 @@ HEADERS += \
$$PWD/objectlengthcalculator.h \
$$PWD/firstdefinitionfinder.h \
$$PWD/moveobjectbeforeobjectvisitor.h \
- $$PWD/changeimportsvisitor.h
+ $$PWD/changeimportsvisitor.h \
+ $$PWD/qmlwarningdialog.h
+
+FORMS += \
+ $$PWD/qmlwarningdialog.ui
diff --git a/src/plugins/qmldesigner/designercore/filemanager/firstdefinitionfinder.cpp b/src/plugins/qmldesigner/designercore/filemanager/firstdefinitionfinder.cpp
index 28e1f12eb5..b1a7834b9a 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/firstdefinitionfinder.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/firstdefinitionfinder.cpp
@@ -78,9 +78,8 @@ void FirstDefinitionFinder::extractFirstObjectDefinition(UiObjectInitializer* as
return;
for (UiObjectMemberList *iter = ast->members; iter; iter = iter->next) {
- if (UiObjectDefinition *def = cast<UiObjectDefinition*>(iter->member)) {
+ if (UiObjectDefinition *def = cast<UiObjectDefinition*>(iter->member))
m_firstObjectDefinition = def;
- }
}
}
diff --git a/src/plugins/qmldesigner/designercore/filemanager/moveobjectbeforeobjectvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/moveobjectbeforeobjectvisitor.cpp
index d7c236fbad..38de16e036 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/moveobjectbeforeobjectvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/moveobjectbeforeobjectvisitor.cpp
@@ -69,9 +69,8 @@ bool MoveObjectBeforeObjectVisitor::operator ()(QmlJS::AST::UiProgram *ast)
QMLRewriter::operator ()(ast);
- if (foundEverything()) {
+ if (foundEverything())
doMove();
- }
return didRewriting();
}
@@ -140,12 +139,10 @@ void MoveObjectBeforeObjectVisitor::doMove()
int start = moveInfo.objectStart;
int end = moveInfo.objectEnd;
if (!inDefaultProperty) {
- if (arrayMember->commaToken.isValid()) {
+ if (arrayMember->commaToken.isValid())
start = arrayMember->commaToken.begin();
- }
- else {
+ else
end = otherArrayMember->commaToken.end();
- }
}
includeSurroundingWhitespace(start, end);
diff --git a/src/plugins/qmldesigner/designercore/filemanager/moveobjectvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/moveobjectvisitor.cpp
index d7a320dc88..08d8bce491 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/moveobjectvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/moveobjectvisitor.cpp
@@ -63,9 +63,8 @@ protected:
if (didRewriting())
return false;
- if (ast->qualifiedTypeNameId->identifierToken.offset == targetParentObjectLocation) {
+ if (ast->qualifiedTypeNameId->identifierToken.offset == targetParentObjectLocation)
insertInto(ast->initializer);
- }
return !didRewriting();
}
@@ -75,9 +74,8 @@ protected:
if (didRewriting())
return false;
- if (ast->firstSourceLocation().offset == targetParentObjectLocation) {
+ if (ast->firstSourceLocation().offset == targetParentObjectLocation)
insertInto(ast->initializer);
- }
return !didRewriting();
}
@@ -122,11 +120,10 @@ private:
moveInfo.prefixToInsert = QLatin1String("\n") + targetPropertyName + (targetIsArrayBinding ? QLatin1String(": [") : QLatin1String(": "));
moveInfo.suffixToInsert = targetIsArrayBinding ? QLatin1String("\n]") : QLatin1String("");
- if (insertAfter && insertAfter->member) {
+ if (insertAfter && insertAfter->member)
moveInfo.destination = insertAfter->member->lastSourceLocation().end();
- } else {
+ else
moveInfo.destination = ast->lbraceToken.end();
- }
move(moveInfo);
diff --git a/src/plugins/qmldesigner/designercore/filemanager/qmlrefactoring.cpp b/src/plugins/qmldesigner/designercore/filemanager/qmlrefactoring.cpp
index c3a134b0e6..d1afd11f40 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/qmlrefactoring.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/qmlrefactoring.cpp
@@ -104,7 +104,7 @@ bool QmlRefactoring::addToObjectMemberList(int parentLocation, const QString &co
bool QmlRefactoring::addProperty(int parentLocation, const QString &name, const QString &value, PropertyType propertyType)
{
- if(parentLocation < 0)
+ if (parentLocation < 0)
return false;
AddPropertyVisitor visit(*textModifier, (quint32) parentLocation, name, value, propertyType, m_propertyOrder);
diff --git a/src/plugins/qmldesigner/designercore/filemanager/qmlrewriter.h b/src/plugins/qmldesigner/designercore/filemanager/qmlrewriter.h
index 3fbb75f208..a11a79825c 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/qmlrewriter.h
+++ b/src/plugins/qmldesigner/designercore/filemanager/qmlrewriter.h
@@ -77,7 +77,7 @@ protected:
{ return m_textModifier; }
bool includeSurroundingWhitespace(int &start, int &end) const;
- void includeLeadingEmptyLine(int &start) const;
+ void includeLeadingEmptyLine(int &start) const;
static QmlJS::AST::UiObjectMemberList *searchMemberToInsertAfter(QmlJS::AST::UiObjectMemberList *members, const QStringList &propertyOrder);
static QmlJS::AST::UiObjectMemberList *searchMemberToInsertAfter(QmlJS::AST::UiObjectMemberList *members, const QString &propertyName, const QStringList &propertyOrder);
diff --git a/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.cpp b/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.cpp
new file mode 100644
index 0000000000..da730a0355
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.cpp
@@ -0,0 +1,77 @@
+#include "qmlwarningdialog.h"
+#include "ui_qmlwarningdialog.h"
+
+#include <qmldesignerplugin.h>
+
+namespace QmlDesigner {
+
+namespace Internal {
+
+QmlWarningDialog::QmlWarningDialog(QWidget *parent, const QStringList &warnings) :
+ QDialog(parent),
+ ui(new Ui::QmlWarningDialog),
+ m_warnings(warnings)
+{
+ ui->setupUi(this);
+ setResult (0);
+
+ ui->checkBox->setChecked(true);
+ connect(ui->ignoreButton, SIGNAL(clicked()), this, SLOT(ignoreButtonPressed()));
+ connect(ui->okButton, SIGNAL(clicked()), this, SLOT(okButtonPressed()));
+ connect(ui->checkBox, SIGNAL(toggled(bool)), this, SLOT(checkBoxToggled(bool)));
+
+ connect(ui->warnings, SIGNAL(linkActivated(QString)), this, SLOT(linkClicked(QString)));
+
+ QString warningText;
+ foreach (const QString &string, warnings)
+ warningText += QLatin1String(" ") + string + QLatin1String("\n");
+ ui->warnings->setText(warningText);
+
+ ui->warnings->setForegroundRole(QPalette::ToolTipText);
+ ui->warnings->setBackgroundRole(QPalette::ToolTipBase);
+ ui->warnings->setAutoFillBackground(true);
+}
+
+QmlWarningDialog::~QmlWarningDialog()
+{
+ delete ui;
+}
+
+void QmlWarningDialog::ignoreButtonPressed()
+{
+ done(0);
+}
+
+void QmlWarningDialog::okButtonPressed()
+{
+ done(-1);
+}
+
+bool QmlWarningDialog::warningsEnabled() const
+{
+#ifndef QMLDESIGNER_TEST
+ DesignerSettings settings = QmlDesignerPlugin::instance()->settings();
+ return settings.warningsInDesigner;
+#else
+ return false;
+#endif
+}
+
+void QmlWarningDialog::checkBoxToggled(bool b)
+{
+#ifndef QMLDESIGNER_TEST
+ DesignerSettings settings = QmlDesignerPlugin::instance()->settings();
+ settings.warningsInDesigner = b;
+ QmlDesignerPlugin::instance()->setSettings(settings);
+#else
+ Q_UNUSED(b);
+#endif
+}
+
+void QmlWarningDialog::linkClicked(const QString &link)
+{
+ done(link.toInt());
+}
+
+} //Internal
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.h b/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.h
new file mode 100644
index 0000000000..61cbaa2c7b
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.h
@@ -0,0 +1,41 @@
+#ifndef QMLWARNINGDIALOG_H
+#define QMLWARNINGDIALOG_H
+
+#include <QDialog>
+
+QT_BEGIN_NAMESPACE
+namespace Ui {
+ class QmlWarningDialog;
+}
+QT_END_NAMESPACE
+
+namespace QmlDesigner {
+
+namespace Internal {
+
+class QmlWarningDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit QmlWarningDialog(QWidget *parent, const QStringList &warnings);
+ ~QmlWarningDialog();
+
+ bool warningsEnabled() const;
+
+public slots:
+ void ignoreButtonPressed();
+ void okButtonPressed();
+ void checkBoxToggled(bool);
+ void linkClicked(const QString &link);
+
+private:
+ Ui::QmlWarningDialog *ui;
+ const QStringList m_warnings;
+};
+
+} //Internal
+
+} //QmlDesigner
+
+#endif // QMLWARNINGDIALOG_H
diff --git a/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.ui b/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.ui
new file mode 100644
index 0000000000..026881e434
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/filemanager/qmlwarningdialog.ui
@@ -0,0 +1,112 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>QmlWarningDialog</class>
+ <widget class="QDialog" name="QmlWarningDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>458</width>
+ <height>229</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Warning</string>
+ </property>
+ <property name="modal">
+ <bool>true</bool>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <property name="spacing">
+ <number>12</number>
+ </property>
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="minimumSize">
+ <size>
+ <width>440</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="font">
+ <font>
+ <weight>75</weight>
+ <bold>true</bold>
+ </font>
+ </property>
+ <property name="text">
+ <string>This QML file contains features which are not supported by Qt Quick Designer</string>
+ </property>
+ <property name="wordWrap">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="warnings">
+ <property name="minimumSize">
+ <size>
+ <width>0</width>
+ <height>120</height>
+ </size>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Raised</enum>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
+ </property>
+ <property name="margin">
+ <number>6</number>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QCheckBox" name="checkBox">
+ <property name="text">
+ <string>Warn about QML features which are not properly supported by the Qt Quick Designer</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>88</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="ignoreButton">
+ <property name="toolTip">
+ <string>Ignore this warning and open the file</string>
+ </property>
+ <property name="text">
+ <string>Ignore</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="okButton">
+ <property name="text">
+ <string>Ok</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp
index 29778d7870..29b565313a 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/removepropertyvisitor.cpp
@@ -84,15 +84,13 @@ void RemovePropertyVisitor::removeFrom(QmlJS::AST::UiObjectInitializer *ast)
UiObjectMember *member = it->member;
// run full name match (for ungrouped properties):
- if (memberNameMatchesPropertyName(propertyName, member)) {
+ if (memberNameMatchesPropertyName(propertyName, member))
removeMember(member);
- }
// check for grouped properties:
else if (!prefix.isEmpty()) {
if (UiObjectDefinition *def = cast<UiObjectDefinition *>(member)) {
- if (toString(def->qualifiedTypeNameId) == prefix) {
+ if (toString(def->qualifiedTypeNameId) == prefix)
removeGroupedProperty(def);
- }
}
}
}
@@ -113,9 +111,8 @@ void RemovePropertyVisitor::removeGroupedProperty(UiObjectDefinition *ast)
++memberCount;
UiObjectMember *member = it->member;
- if (!wanted && memberNameMatchesPropertyName(propName, member)) {
+ if (!wanted && memberNameMatchesPropertyName(propName, member))
wanted = member;
- }
}
if (!wanted)
diff --git a/src/plugins/qmldesigner/designercore/filemanager/removeuiobjectmembervisitor.cpp b/src/plugins/qmldesigner/designercore/filemanager/removeuiobjectmembervisitor.cpp
index d3f074367c..f0b8937683 100644
--- a/src/plugins/qmldesigner/designercore/filemanager/removeuiobjectmembervisitor.cpp
+++ b/src/plugins/qmldesigner/designercore/filemanager/removeuiobjectmembervisitor.cpp
@@ -75,11 +75,10 @@ bool RemoveUIObjectMemberVisitor::visitObjectMember(QmlJS::AST::UiObjectMember *
int start = objectLocation;
int end = ast->lastSourceLocation().end();
- if (UiArrayBinding *parentArray = containingArray()) {
+ if (UiArrayBinding *parentArray = containingArray())
extendToLeadingOrTrailingComma(parentArray, ast, start, end);
- } else {
+ else
includeSurroundingWhitespace(start, end);
- }
includeLeadingEmptyLine(start);
replace(start, end - start, QLatin1String(""));
@@ -99,9 +98,8 @@ bool RemoveUIObjectMemberVisitor::visitObjectMember(QmlJS::AST::UiObjectMember *
UiArrayBinding *RemoveUIObjectMemberVisitor::containingArray() const
{
if (parents.size() > 2) {
- if (cast<UiArrayMemberList*>(parents[parents.size() - 2])) {
+ if (cast<UiArrayMemberList*>(parents[parents.size() - 2]))
return cast<UiArrayBinding*>(parents[parents.size() - 3]);
- }
}
return 0;
diff --git a/src/plugins/qmldesigner/designercore/include/abstractproperty.h b/src/plugins/qmldesigner/designercore/include/abstractproperty.h
index e65bb776ef..96b2a2d2e3 100644
--- a/src/plugins/qmldesigner/designercore/include/abstractproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/abstractproperty.h
@@ -33,7 +33,7 @@
#include <QVariant>
#include <QWeakPointer>
#include <QSharedPointer>
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
QT_BEGIN_NAMESPACE
class QTextStream;
@@ -52,11 +52,11 @@ namespace QmlDesigner {
class Model;
class ModelNode;
class AbstractView;
-class CORESHARED_EXPORT VariantProperty;
-class CORESHARED_EXPORT NodeListProperty;
-class CORESHARED_EXPORT NodeAbstractProperty;
-class CORESHARED_EXPORT BindingProperty;
-class CORESHARED_EXPORT NodeProperty;
+class QMLDESIGNERCORE_EXPORT VariantProperty;
+class QMLDESIGNERCORE_EXPORT NodeListProperty;
+class QMLDESIGNERCORE_EXPORT NodeAbstractProperty;
+class QMLDESIGNERCORE_EXPORT BindingProperty;
+class QMLDESIGNERCORE_EXPORT NodeProperty;
class QmlObjectNode;
@@ -65,14 +65,14 @@ namespace Internal {
class ModelPrivate;
}
-class CORESHARED_EXPORT AbstractProperty
+class QMLDESIGNERCORE_EXPORT AbstractProperty
{
friend class QmlDesigner::ModelNode;
friend class QmlDesigner::Internal::ModelPrivate;
- friend CORESHARED_EXPORT bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2);
- friend CORESHARED_EXPORT bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2);
- friend CORESHARED_EXPORT uint qHash(const AbstractProperty& property);
+ friend QMLDESIGNERCORE_EXPORT bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2);
+ friend QMLDESIGNERCORE_EXPORT bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2);
+ friend QMLDESIGNERCORE_EXPORT uint qHash(const AbstractProperty& property);
public:
AbstractProperty();
@@ -117,11 +117,11 @@ private:
QWeakPointer<AbstractView> m_view;
};
-CORESHARED_EXPORT bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2);
-CORESHARED_EXPORT bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2);
-CORESHARED_EXPORT uint qHash(const AbstractProperty& property);
-CORESHARED_EXPORT QTextStream& operator<<(QTextStream &stream, const AbstractProperty &property);
-CORESHARED_EXPORT QDebug operator<<(QDebug debug, const AbstractProperty &AbstractProperty);
+QMLDESIGNERCORE_EXPORT bool operator ==(const AbstractProperty &property1, const AbstractProperty &property2);
+QMLDESIGNERCORE_EXPORT bool operator !=(const AbstractProperty &property1, const AbstractProperty &property2);
+QMLDESIGNERCORE_EXPORT uint qHash(const AbstractProperty& property);
+QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const AbstractProperty &property);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const AbstractProperty &AbstractProperty);
}
#endif //ABSTRACTPROPERTY_H
diff --git a/src/plugins/qmldesigner/designercore/include/abstractview.h b/src/plugins/qmldesigner/designercore/include/abstractview.h
index cc36f84007..f03b725454 100644
--- a/src/plugins/qmldesigner/designercore/include/abstractview.h
+++ b/src/plugins/qmldesigner/designercore/include/abstractview.h
@@ -30,7 +30,7 @@
#ifndef ABSTRACTVIEW_H
#define ABSTRACTVIEW_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <model.h>
#include <modelnode.h>
@@ -58,7 +58,7 @@ class QmlModelView;
class NodeInstanceView;
class RewriterView;
-class CORESHARED_EXPORT AbstractView : public QObject
+class QMLDESIGNERCORE_EXPORT AbstractView : public QObject
{
Q_OBJECT
public:
@@ -77,6 +77,7 @@ public:
virtual ~AbstractView();
Model* model() const;
+ bool isAttached() const;
RewriterTransaction beginRewriterTransaction();
@@ -104,7 +105,7 @@ public:
ModelNode modelNodeForInternalId(qint32 internalId);
bool hasModelNodeForInternalId(qint32 internalId) const;
- QList<ModelNode> allModelNodes();
+ QList<ModelNode> allModelNodes() const;
void emitCustomNotification(const QString &identifier);
void emitCustomNotification(const QString &identifier, const QList<ModelNode> &nodeList);
@@ -179,6 +180,8 @@ public:
void resetView();
+ virtual QWidget *widget() = 0;
+
protected:
void setModel(Model * model);
void removeModel();
@@ -191,8 +194,8 @@ private:
QWeakPointer<Model> m_model;
};
-CORESHARED_EXPORT QList<Internal::InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList);
-CORESHARED_EXPORT QList<ModelNode> toModelNodeList(const QList<Internal::InternalNodePointer> &nodeList, AbstractView *view);
+QMLDESIGNERCORE_EXPORT QList<Internal::InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList);
+QMLDESIGNERCORE_EXPORT QList<ModelNode> toModelNodeList(const QList<Internal::InternalNodePointer> &nodeList, AbstractView *view);
}
diff --git a/src/plugins/qmldesigner/designercore/include/basetexteditmodifier.h b/src/plugins/qmldesigner/designercore/include/basetexteditmodifier.h
index 310617a606..d6525be0ea 100644
--- a/src/plugins/qmldesigner/designercore/include/basetexteditmodifier.h
+++ b/src/plugins/qmldesigner/designercore/include/basetexteditmodifier.h
@@ -31,7 +31,7 @@
#ifndef BASETEXTEDITMODIFIER_H
#define BASETEXTEDITMODIFIER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "plaintexteditmodifier.h"
#include <texteditor/basetexteditor.h>
@@ -44,7 +44,7 @@ class Snapshot;
namespace QmlDesigner {
-class CORESHARED_EXPORT BaseTextEditModifier: public PlainTextEditModifier
+class QMLDESIGNERCORE_EXPORT BaseTextEditModifier: public PlainTextEditModifier
{
public:
BaseTextEditModifier(TextEditor::BaseTextEditorWidget *textEdit);
diff --git a/src/plugins/qmldesigner/designercore/include/bindingproperty.h b/src/plugins/qmldesigner/designercore/include/bindingproperty.h
index a18195abae..6e59eab3ca 100644
--- a/src/plugins/qmldesigner/designercore/include/bindingproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/bindingproperty.h
@@ -30,12 +30,12 @@
#ifndef BINDINGPROPERTY_H
#define BINDINGPROPERTY_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "abstractproperty.h"
namespace QmlDesigner {
-class CORESHARED_EXPORT BindingProperty : public QmlDesigner::AbstractProperty
+class QMLDESIGNERCORE_EXPORT BindingProperty : public QmlDesigner::AbstractProperty
{
friend class QmlDesigner::ModelNode;
friend class QmlDesigner::Internal::ModelPrivate;
diff --git a/src/plugins/qmldesigner/designercore/include/bytearraymodifier.h b/src/plugins/qmldesigner/designercore/include/bytearraymodifier.h
index fabe371d19..c7639af69b 100644
--- a/src/plugins/qmldesigner/designercore/include/bytearraymodifier.h
+++ b/src/plugins/qmldesigner/designercore/include/bytearraymodifier.h
@@ -36,7 +36,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT ByteArrayModifier: public PlainTextEditModifier
+class QMLDESIGNERCORE_EXPORT ByteArrayModifier: public PlainTextEditModifier
{
public:
static ByteArrayModifier* create(const QString& data);
diff --git a/src/plugins/qmldesigner/designercore/include/exception.h b/src/plugins/qmldesigner/designercore/include/exception.h
index 662aa9ed92..34d9d5b496 100644
--- a/src/plugins/qmldesigner/designercore/include/exception.h
+++ b/src/plugins/qmldesigner/designercore/include/exception.h
@@ -30,14 +30,14 @@
#ifndef EXCEPTION_H
#define EXCEPTION_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <QString>
#include <QDebug>
namespace QmlDesigner {
-class CORESHARED_EXPORT Exception
+class QMLDESIGNERCORE_EXPORT Exception
{
public:
Exception(int line,
@@ -64,7 +64,7 @@ private:
static bool s_shouldAssert;
};
-CORESHARED_EXPORT QDebug operator<<(QDebug debug, const Exception &exception);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const Exception &exception);
}
diff --git a/src/plugins/qmldesigner/designercore/include/import.h b/src/plugins/qmldesigner/designercore/include/import.h
index 05b4446447..29a6e04fc1 100644
--- a/src/plugins/qmldesigner/designercore/include/import.h
+++ b/src/plugins/qmldesigner/designercore/include/import.h
@@ -33,11 +33,11 @@
#include <QString>
#include <QStringList>
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
namespace QmlDesigner {
-class CORESHARED_EXPORT Import
+class QMLDESIGNERCORE_EXPORT Import
{
public:
static Import createLibraryImport(const QString &url, const QString &version = QString(), const QString &alias = QString(), const QStringList &importPaths = QStringList());
@@ -71,7 +71,7 @@ private:
QStringList m_importPathList;
};
-CORESHARED_EXPORT uint qHash(const Import &import);
+QMLDESIGNERCORE_EXPORT uint qHash(const Import &import);
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/include/invalidargumentexception.h b/src/plugins/qmldesigner/designercore/include/invalidargumentexception.h
index fd9a549e0c..592a84ce28 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidargumentexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidargumentexception.h
@@ -35,7 +35,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidArgumentException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidArgumentException : public Exception
{
public:
InvalidArgumentException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalididexception.h b/src/plugins/qmldesigner/designercore/include/invalididexception.h
index 6e9c93e69e..97493443ed 100644
--- a/src/plugins/qmldesigner/designercore/include/invalididexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalididexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidIdException : public InvalidArgumentException
+class QMLDESIGNERCORE_EXPORT InvalidIdException : public InvalidArgumentException
{
public:
enum Reason { InvalidCharacters, DuplicateId };
diff --git a/src/plugins/qmldesigner/designercore/include/invalidmetainfoexception.h b/src/plugins/qmldesigner/designercore/include/invalidmetainfoexception.h
index 011d42dcfb..036606dc74 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidmetainfoexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidmetainfoexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidMetaInfoException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidMetaInfoException : public Exception
{
public:
InvalidMetaInfoException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalidmodelnodeexception.h b/src/plugins/qmldesigner/designercore/include/invalidmodelnodeexception.h
index 84998f47b8..07ff7b3666 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidmodelnodeexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidmodelnodeexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidModelNodeException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidModelNodeException : public Exception
{
public:
InvalidModelNodeException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalidmodelstateexception.h b/src/plugins/qmldesigner/designercore/include/invalidmodelstateexception.h
index 78c7d28b8e..638971e61e 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidmodelstateexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidmodelstateexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidModelStateException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidModelStateException : public Exception
{
public:
InvalidModelStateException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalidpropertyexception.h b/src/plugins/qmldesigner/designercore/include/invalidpropertyexception.h
index e71e491171..35c076a3d1 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidpropertyexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidpropertyexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidPropertyException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidPropertyException : public Exception
{
public:
InvalidPropertyException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalidqmlsourceexception.h b/src/plugins/qmldesigner/designercore/include/invalidqmlsourceexception.h
index 3badd7799d..72fd0b9674 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidqmlsourceexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidqmlsourceexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidQmlSourceException : public QmlDesigner::Exception
+class QMLDESIGNERCORE_EXPORT InvalidQmlSourceException : public QmlDesigner::Exception
{
public:
InvalidQmlSourceException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalidreparentingexception.h b/src/plugins/qmldesigner/designercore/include/invalidreparentingexception.h
index 0b514c6bfa..715d644e4f 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidreparentingexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidreparentingexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidReparentingException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidReparentingException : public Exception
{
public:
InvalidReparentingException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/invalidslideindexexception.h b/src/plugins/qmldesigner/designercore/include/invalidslideindexexception.h
index fd68685d9c..9e5dadd806 100644
--- a/src/plugins/qmldesigner/designercore/include/invalidslideindexexception.h
+++ b/src/plugins/qmldesigner/designercore/include/invalidslideindexexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT InvalidSlideIndexException : public Exception
+class QMLDESIGNERCORE_EXPORT InvalidSlideIndexException : public Exception
{
public:
InvalidSlideIndexException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h b/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h
index 7fdbe67a95..49fdaee31d 100644
--- a/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h
+++ b/src/plugins/qmldesigner/designercore/include/itemlibraryinfo.h
@@ -30,7 +30,7 @@
#ifndef ITEMLIBRARYINFO_H
#define ITEMLIBRARYINFO_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "propertycontainer.h"
#include <QSharedPointer>
@@ -40,21 +40,22 @@ namespace QmlDesigner {
namespace Internal {
class ItemLibraryEntryData;
-class ItemLibraryInfoPrivate;
class MetaInfoPrivate;
}
class ItemLibraryEntry;
-CORESHARED_EXPORT QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry);
-CORESHARED_EXPORT QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry);
+QMLDESIGNERCORE_EXPORT QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry);
+QMLDESIGNERCORE_EXPORT QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const ItemLibraryEntry &itemLibraryEntry);
-class CORESHARED_EXPORT ItemLibraryEntry
+class QMLDESIGNERCORE_EXPORT ItemLibraryEntry
{
//friend class QmlDesigner::MetaInfo;
//friend class QmlDesigner::Internal::MetaInfoParser;
- friend CORESHARED_EXPORT QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry);
- friend CORESHARED_EXPORT QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry);
+ friend QMLDESIGNERCORE_EXPORT QDataStream& operator<<(QDataStream& stream, const ItemLibraryEntry &itemLibraryEntry);
+ friend QMLDESIGNERCORE_EXPORT QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry);
+ friend QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const ItemLibraryEntry &itemLibraryEntry);
public:
ItemLibraryEntry();
@@ -83,7 +84,7 @@ public:
void setName(const QString &name);
void setIconPath(const QString &iconPath);
void addProperty(const Property &p);
- void addProperty(QString &name, QString &type, QString &value);
+ void addProperty(QString &name, QString &type, QVariant &value);
void setDragIcon(const QIcon &icon);
void setIcon(const QIcon &icon);
void setCategory(const QString &category);
@@ -94,29 +95,31 @@ private:
QExplicitlySharedDataPointer<Internal::ItemLibraryEntryData> m_data;
};
-class CORESHARED_EXPORT ItemLibraryInfo : public QObject
+class QMLDESIGNERCORE_EXPORT ItemLibraryInfo : public QObject
{
Q_OBJECT
friend class Internal::MetaInfoPrivate;
public:
- ~ItemLibraryInfo();
QList<ItemLibraryEntry> entries() const;
QList<ItemLibraryEntry> entriesForType(const QString &typeName, int majorVersion, int minorVersion) const;
ItemLibraryEntry entry(const QString &name) const;
- void addEntry(const ItemLibraryEntry &entry);
+ void addEntry(const ItemLibraryEntry &entry, bool overwriteDuplicate = false);
bool containsEntry(const ItemLibraryEntry &entry);
void clearEntries();
signals:
void entriesChanged();
-private:
+private: // functions
ItemLibraryInfo(QObject *parent = 0);
- void setBaseInfo(ItemLibraryInfo *baseInfo);
- Internal::ItemLibraryInfoPrivate *d;
+ void setBaseInfo(ItemLibraryInfo *m_baseInfo);
+
+private: // variables
+ QHash<QString, ItemLibraryEntry> m_nameToEntryHash;
+ QWeakPointer<ItemLibraryInfo> m_baseInfo;
};
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/include/metainfo.h b/src/plugins/qmldesigner/designercore/include/metainfo.h
index f44e8ae5f2..ba96d46e5b 100644
--- a/src/plugins/qmldesigner/designercore/include/metainfo.h
+++ b/src/plugins/qmldesigner/designercore/include/metainfo.h
@@ -30,7 +30,7 @@
#ifndef METAINFO_H
#define METAINFO_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <QMultiHash>
#include <QString>
@@ -53,15 +53,15 @@ namespace Internal {
typedef QSharedPointer<MetaInfoPrivate> MetaInfoPrivatePointer;
}
-CORESHARED_EXPORT bool operator==(const MetaInfo &first, const MetaInfo &second);
-CORESHARED_EXPORT bool operator!=(const MetaInfo &first, const MetaInfo &second);
+QMLDESIGNERCORE_EXPORT bool operator==(const MetaInfo &first, const MetaInfo &second);
+QMLDESIGNERCORE_EXPORT bool operator!=(const MetaInfo &first, const MetaInfo &second);
-class CORESHARED_EXPORT MetaInfo
+class QMLDESIGNERCORE_EXPORT MetaInfo
{
friend class QmlDesigner::Internal::MetaInfoPrivate;
friend class QmlDesigner::Internal::ModelPrivate;
- friend class QmlDesigner::Internal::MetaInfoParser;
+ friend class QmlDesigner::Internal::MetaInfoReader;
friend class QmlDesigner::Internal::SubComponentManagerPrivate;
friend bool operator==(const MetaInfo &, const MetaInfo &);
diff --git a/src/plugins/qmldesigner/designercore/include/metainforeader.h b/src/plugins/qmldesigner/designercore/include/metainforeader.h
new file mode 100644
index 0000000000..a10e31a9e1
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/include/metainforeader.h
@@ -0,0 +1,125 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef METAINFOREADER_H
+#define METAINFOREADER_H
+
+#include "qmldesignercorelib_global.h"
+#include <metainfo.h>
+
+#include <qmljs/qmljssimplereader.h>
+
+#include <QString>
+#include <QFile>
+
+
+namespace QmlDesigner {
+
+class ItemLibraryEntry;
+
+namespace Internal {
+
+
+class MetaInfoReader : protected QmlJS::SimpleAbstractStreamReader
+{
+ Q_DECLARE_TR_FUNCTIONS(QmlDesigner::Internal::MetaInfoReader)
+
+public:
+ MetaInfoReader(const MetaInfo &metaInfo);
+
+ void readMetaInfoFile(const QString &path, bool overwriteDuplicates = false);
+
+
+ QStringList errors();
+
+ void setQualifcation(const QString &qualification);
+
+protected:
+ virtual void elementStart(const QString &name);
+ virtual void elementEnd();
+ virtual void propertyDefinition(const QString &name, const QVariant &value);
+
+private:
+ enum ParserSate { Error,
+ Finished,
+ Undefined,
+ ParsingDocument,
+ ParsingMetaInfo,
+ ParsingType,
+ ParsingItemLibrary,
+ ParsingProperty,
+ ParsingQmlSource
+ };
+
+ ParserSate readDocument(const QString &name);
+
+ ParserSate readMetaInfoRootElement(const QString &name);
+ ParserSate readTypeElement(const QString &name);
+ ParserSate readItemLibraryEntryElement(const QString &name);
+ ParserSate readPropertyElement(const QString &name);
+ ParserSate readQmlSourceElement(const QString &name);
+
+ void readTypeProperty(const QString &name, const QVariant &value);
+ void readItemLibraryEntryProperty(const QString &name, const QVariant &value);
+ void readPropertyProperty(const QString &name, const QVariant &value);
+ void readQmlSourceProperty(const QString &name, const QVariant &value);
+
+ void setVersion(const QString &versionNumber);
+
+ ParserSate parserState() const;
+ void setParserState(ParserSate newParserState);
+
+ void insertItemLibraryEntry();
+ void insertProperty();
+
+ void addErrorInvalidType(const QString &typeName);
+
+ QString absoluteFilePathForDocument(const QString &relativeFilePath);
+
+ QString m_documentPath;
+ ParserSate m_parserState;
+ MetaInfo m_metaInfo;
+
+ QString m_currentClassName;
+ QString m_currentIcon;
+ QString m_currentSource;
+ ItemLibraryEntry m_currentEntry;
+
+ QString m_currentPropertyName;
+ QString m_currentPropertyType;
+ QVariant m_currentPropertyValue;
+
+ bool m_overwriteDuplicates;
+
+ QString m_qualication;
+};
+
+}
+}
+#endif // METAINFOREADER_H
diff --git a/src/plugins/qmldesigner/designercore/include/model.h b/src/plugins/qmldesigner/designercore/include/model.h
index b983468af6..ce91e46c96 100644
--- a/src/plugins/qmldesigner/designercore/include/model.h
+++ b/src/plugins/qmldesigner/designercore/include/model.h
@@ -30,11 +30,10 @@
#ifndef DESIGNERMODEL_H
#define DESIGNERMODEL_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <QObject>
#include <QMimeData>
#include <QPair>
-#include <QDeclarativeError>
#include <import.h>
@@ -52,7 +51,6 @@ class AnchorLine;
class ModelNode;
class NodeState;
class AbstractView;
-class WidgetQueryView;
class NodeStateChangeSet;
class MetaInfo;
class NodeMetaInfo;
@@ -60,10 +58,11 @@ class ModelState;
class NodeAnchors;
class AbstractProperty;
class RewriterView;
+class NodeInstanceView;
typedef QList<QPair<QString, QVariant> > PropertyListType;
-class CORESHARED_EXPORT Model : public QObject
+class QMLDESIGNERCORE_EXPORT Model : public QObject
{
friend class QmlDesigner::ModelNode;
friend class QmlDesigner::NodeState;
@@ -80,10 +79,7 @@ public:
virtual ~Model();
- static Model *create(QString type, int major = 4, int minor = 7, Model *metaInfoPropxyModel = 0);
-
- Model *masterModel() const;
- void setMasterModel(Model *model);
+ static Model *create(QString type, int major = 1, int minor = 1, Model *metaInfoPropxyModel = 0);
QUrl fileUrl() const;
void setFileUrl(const QUrl &url);
@@ -102,8 +98,13 @@ public:
QList<Import> imports() const;
void changeImports(const QList<Import> &importsToBeAdded, const QList<Import> &importsToBeRemoved);
bool hasImport(const Import &import, bool ignoreAlias = true, bool allowHigherVersion = false);
+ QString pathForImport(const Import &import);
RewriterView *rewriterView() const;
+ void setRewriterView(RewriterView *rewriterView);
+
+ NodeInstanceView *nodeInstanceView() const;
+ void setNodeInstanceView(NodeInstanceView *nodeInstanceView);
Model *metaInfoProxyModel();
diff --git a/src/plugins/qmldesigner/designercore/include/modelnode.h b/src/plugins/qmldesigner/designercore/include/modelnode.h
index d0ad2168a7..ad1927ba62 100644
--- a/src/plugins/qmldesigner/designercore/include/modelnode.h
+++ b/src/plugins/qmldesigner/designercore/include/modelnode.h
@@ -30,7 +30,7 @@
#ifndef DESIGNERNODE_H
#define DESIGNERNODE_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <QWeakPointer>
#include <QList>
#include <QMetaType>
@@ -63,18 +63,18 @@ class NodeProperty;
class NodeAbstractProperty;
class ModelNode;
-CORESHARED_EXPORT QList<Internal::InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList);
+QMLDESIGNERCORE_EXPORT QList<Internal::InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList);
typedef QList<QPair<QString, QVariant> > PropertyListType;
-class CORESHARED_EXPORT ModelNode
+class QMLDESIGNERCORE_EXPORT ModelNode
{
- friend CORESHARED_EXPORT bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode);
- friend CORESHARED_EXPORT bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode);
- friend CORESHARED_EXPORT uint qHash(const ModelNode & node);
- friend CORESHARED_EXPORT QDebug operator<<(QDebug debug, const ModelNode &modelNode);
- friend CORESHARED_EXPORT bool operator <(const ModelNode &firstNode, const ModelNode &secondNode);
- friend CORESHARED_EXPORT QList<Internal::InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList);
+ friend QMLDESIGNERCORE_EXPORT bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode);
+ friend QMLDESIGNERCORE_EXPORT bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode);
+ friend QMLDESIGNERCORE_EXPORT uint qHash(const ModelNode & node);
+ friend QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const ModelNode &modelNode);
+ friend QMLDESIGNERCORE_EXPORT bool operator <(const ModelNode &firstNode, const ModelNode &secondNode);
+ friend QMLDESIGNERCORE_EXPORT QList<Internal::InternalNodePointer> toInternalNodeList(const QList<ModelNode> &nodeList);
friend class QmlDesigner::Model;
friend class QmlDesigner::AbstractView;
friend class QmlDesigner::NodeListProperty;
@@ -192,12 +192,12 @@ private: // variables
QWeakPointer<AbstractView> m_view;
};
-CORESHARED_EXPORT bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode);
-CORESHARED_EXPORT bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode);
-CORESHARED_EXPORT uint qHash(const ModelNode & node);
-CORESHARED_EXPORT bool operator <(const ModelNode &firstNode, const ModelNode &secondNode);
-CORESHARED_EXPORT QDebug operator<<(QDebug debug, const ModelNode &modelNode);
-CORESHARED_EXPORT QTextStream& operator<<(QTextStream &stream, const ModelNode &modelNode);
+QMLDESIGNERCORE_EXPORT bool operator ==(const ModelNode &firstNode, const ModelNode &secondNode);
+QMLDESIGNERCORE_EXPORT bool operator !=(const ModelNode &firstNode, const ModelNode &secondNode);
+QMLDESIGNERCORE_EXPORT uint qHash(const ModelNode & node);
+QMLDESIGNERCORE_EXPORT bool operator <(const ModelNode &firstNode, const ModelNode &secondNode);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const ModelNode &modelNode);
+QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const ModelNode &modelNode);
}
Q_DECLARE_METATYPE(QmlDesigner::ModelNode)
diff --git a/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h b/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h
index d534849746..02c5f432bf 100644
--- a/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/nodeabstractproperty.h
@@ -45,9 +45,9 @@ class NodeAbstractProperty : public AbstractProperty
friend class QmlDesigner::Internal::ModelPrivate;
friend class QmlDesigner::AbstractProperty;
- friend CORESHARED_EXPORT bool operator ==(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
- friend CORESHARED_EXPORT bool operator !=(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
- friend CORESHARED_EXPORT uint qHash(const NodeAbstractProperty& property);
+ friend QMLDESIGNERCORE_EXPORT bool operator ==(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
+ friend QMLDESIGNERCORE_EXPORT bool operator !=(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
+ friend QMLDESIGNERCORE_EXPORT uint qHash(const NodeAbstractProperty& property);
public:
NodeAbstractProperty();
@@ -66,11 +66,11 @@ protected:
};
-CORESHARED_EXPORT bool operator ==(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
-CORESHARED_EXPORT bool operator !=(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
-CORESHARED_EXPORT uint qHash(const NodeAbstractProperty& property);
-CORESHARED_EXPORT QTextStream& operator<<(QTextStream &stream, const NodeAbstractProperty &property);
-CORESHARED_EXPORT QDebug operator<<(QDebug debug, const NodeAbstractProperty &property);
+QMLDESIGNERCORE_EXPORT bool operator ==(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
+QMLDESIGNERCORE_EXPORT bool operator !=(const NodeAbstractProperty &property1, const NodeAbstractProperty &property2);
+QMLDESIGNERCORE_EXPORT uint qHash(const NodeAbstractProperty& property);
+QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const NodeAbstractProperty &property);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const NodeAbstractProperty &property);
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h b/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h
index 559473c138..48eea638b6 100644
--- a/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h
+++ b/src/plugins/qmldesigner/designercore/include/nodeinstanceview.h
@@ -30,7 +30,7 @@
#ifndef NODEINSTANCEVIEW_H
#define NODEINSTANCEVIEW_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "abstractview.h"
#include <modelnode.h>
@@ -69,7 +69,7 @@ class CompleteComponentCommand;
class InformationContainer;
class TokenCommand;
-class CORESHARED_EXPORT NodeInstanceView : public AbstractView, public NodeInstanceClientInterface
+class QMLDESIGNERCORE_EXPORT NodeInstanceView : public AbstractView, public NodeInstanceClientInterface
{
Q_OBJECT
@@ -135,6 +135,7 @@ public:
void statePreviewImagesChanged(const StatePreviewImageChangedCommand &command);
void componentCompleted(const ComponentCompletedCommand &command);
void token(const TokenCommand &command);
+ void debugOutput(const DebugOutputCommand &command);
QImage statePreviewImage(const ModelNode &stateNode) const;
@@ -142,6 +143,8 @@ public:
void sendToken(const QString &token, int number, const QVector<ModelNode> &nodeVector);
+ QWidget *widget();
+
signals:
void qmlPuppetCrashed();
@@ -183,6 +186,8 @@ private: // functions
RemoveInstancesCommand createRemoveInstancesCommand(const QList<ModelNode> &nodeList) const;
RemoveInstancesCommand createRemoveInstancesCommand(const ModelNode &node) const;
RemovePropertiesCommand createRemovePropertiesCommand(const QList<AbstractProperty> &propertyList) const;
+ RemoveSharedMemoryCommand createRemoveSharedMemoryCommand(const QString &sharedMemoryTypeName, quint32 keyNumber);
+ RemoveSharedMemoryCommand createRemoveSharedMemoryCommand(const QString &sharedMemoryTypeName, const QList<ModelNode> &nodeList);
void resetHorizontalAnchors(const ModelNode &node);
void resetVerticalAnchors(const ModelNode &node);
diff --git a/src/plugins/qmldesigner/designercore/include/nodelistproperty.h b/src/plugins/qmldesigner/designercore/include/nodelistproperty.h
index cfd852a614..5a9efc1a08 100644
--- a/src/plugins/qmldesigner/designercore/include/nodelistproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/nodelistproperty.h
@@ -31,7 +31,7 @@
#define NODELISTPROPERTY_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "nodeabstractproperty.h"
#include <QList>
@@ -45,7 +45,7 @@ namespace Internal {
}
-class CORESHARED_EXPORT NodeListProperty : public NodeAbstractProperty
+class QMLDESIGNERCORE_EXPORT NodeListProperty : public NodeAbstractProperty
{
friend class QmlDesigner::ModelNode;
friend class QmlDesigner::AbstractProperty;
diff --git a/src/plugins/qmldesigner/designercore/include/nodemetainfo.h b/src/plugins/qmldesigner/designercore/include/nodemetainfo.h
index 9110e801b5..d03c93fb6e 100644
--- a/src/plugins/qmldesigner/designercore/include/nodemetainfo.h
+++ b/src/plugins/qmldesigner/designercore/include/nodemetainfo.h
@@ -35,7 +35,7 @@
#include <QExplicitlySharedDataPointer>
#include <QIcon>
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "invalidmetainfoexception.h"
QT_BEGIN_NAMESPACE
@@ -50,13 +50,13 @@ class AbstractProperty;
namespace Internal {
class MetaInfoPrivate;
- class MetaInfoParser;
+ class MetaInfoReader;
class SubComponentManagerPrivate;
class ItemLibraryEntryData;
class NodeMetaInfoPrivate;
}
-class CORESHARED_EXPORT NodeMetaInfo
+class QMLDESIGNERCORE_EXPORT NodeMetaInfo
{
public:
NodeMetaInfo();
@@ -68,7 +68,7 @@ public:
NodeMetaInfo &operator=(const NodeMetaInfo &other);
bool isValid() const;
- bool isComponent() const;
+ bool isFileComponent() const;
bool hasProperty(const QString &propertyName) const;
QStringList propertyNames() const;
QStringList directPropertyNames() const;
@@ -97,6 +97,10 @@ public:
bool availableInVersion(int majorVersion, int minorVersion) const;
bool isSubclassOf(const QString& type, int majorVersion, int minorVersio) const;
+ bool isPositioner() const;
+
+ QString importDirectoryPath() const;
+
static void clearCache();
private:
diff --git a/src/plugins/qmldesigner/designercore/include/nodeproperty.h b/src/plugins/qmldesigner/designercore/include/nodeproperty.h
index 4cb55c6cd2..6c4d6089a9 100644
--- a/src/plugins/qmldesigner/designercore/include/nodeproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/nodeproperty.h
@@ -30,7 +30,7 @@
#ifndef NODEPROPERTY_H
#define NODEPROPERTY_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "nodeabstractproperty.h"
namespace QmlDesigner {
@@ -39,7 +39,7 @@ namespace Internal {
class ModelPrivate;
}
-class CORESHARED_EXPORT NodeProperty : public NodeAbstractProperty
+class QMLDESIGNERCORE_EXPORT NodeProperty : public NodeAbstractProperty
{
friend class QmlDesigner::ModelNode;
friend class QmlDesigner::Internal::ModelPrivate;
diff --git a/src/plugins/qmldesigner/designercore/include/notimplementedexception.h b/src/plugins/qmldesigner/designercore/include/notimplementedexception.h
index 2d5d18a5f1..aeb16c0acf 100644
--- a/src/plugins/qmldesigner/designercore/include/notimplementedexception.h
+++ b/src/plugins/qmldesigner/designercore/include/notimplementedexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT NotImplementedException : public Exception
+class QMLDESIGNERCORE_EXPORT NotImplementedException : public Exception
{
public:
NotImplementedException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/plaintexteditmodifier.h b/src/plugins/qmldesigner/designercore/include/plaintexteditmodifier.h
index aa3cf24393..08e76384e8 100644
--- a/src/plugins/qmldesigner/designercore/include/plaintexteditmodifier.h
+++ b/src/plugins/qmldesigner/designercore/include/plaintexteditmodifier.h
@@ -30,7 +30,7 @@
#ifndef PLAINTEXTEDITMODIFIER_H
#define PLAINTEXTEDITMODIFIER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "textmodifier.h"
QT_BEGIN_NAMESPACE
@@ -44,7 +44,7 @@ namespace Utils {
namespace QmlDesigner {
-class CORESHARED_EXPORT PlainTextEditModifier: public TextModifier
+class QMLDESIGNERCORE_EXPORT PlainTextEditModifier: public TextModifier
{
Q_OBJECT
@@ -98,7 +98,7 @@ private:
bool m_ongoingTextChange;
};
-class CORESHARED_EXPORT NotIndentingTextEditModifier: public PlainTextEditModifier
+class QMLDESIGNERCORE_EXPORT NotIndentingTextEditModifier: public PlainTextEditModifier
{
public:
NotIndentingTextEditModifier(QPlainTextEdit *textEdit)
diff --git a/src/plugins/qmldesigner/designercore/include/propertycontainer.h b/src/plugins/qmldesigner/designercore/include/propertycontainer.h
index 2db86d20ba..67f9aec6f6 100644
--- a/src/plugins/qmldesigner/designercore/include/propertycontainer.h
+++ b/src/plugins/qmldesigner/designercore/include/propertycontainer.h
@@ -30,7 +30,7 @@
#ifndef PROPERTYCONTAINER_H
#define PROPERTYCONTAINER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <QString>
#include <QExplicitlySharedDataPointer>
@@ -41,13 +41,15 @@ namespace QmlDesigner {
class PropertyContainer;
-CORESHARED_EXPORT QDataStream &operator<<(QDataStream &stream, const PropertyContainer &propertyContainer);
-CORESHARED_EXPORT QDataStream &operator>>(QDataStream &stream, PropertyContainer &propertyContainer);
+QMLDESIGNERCORE_EXPORT QDataStream &operator<<(QDataStream &stream, const PropertyContainer &propertyContainer);
+QMLDESIGNERCORE_EXPORT QDataStream &operator>>(QDataStream &stream, PropertyContainer &propertyContainer);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const PropertyContainer &propertyContainer);
-class CORESHARED_EXPORT PropertyContainer
+class QMLDESIGNERCORE_EXPORT PropertyContainer
{
- friend CORESHARED_EXPORT QDataStream &operator<<(QDataStream &stream, const PropertyContainer &propertyContainer);
- friend CORESHARED_EXPORT QDataStream &operator>>(QDataStream &stream, PropertyContainer &propertyContainer);
+ friend QMLDESIGNERCORE_EXPORT QDataStream &operator<<(QDataStream &stream, const PropertyContainer &propertyContainer);
+ friend QMLDESIGNERCORE_EXPORT QDataStream &operator>>(QDataStream &stream, PropertyContainer &propertyContainer);
+ friend QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const PropertyContainer &propertyContainer);
public:
PropertyContainer();
@@ -70,8 +72,9 @@ private:
mutable QVariant m_value;
};
-CORESHARED_EXPORT QDataStream &operator<<(QDataStream &stream, const QList<PropertyContainer> &propertyContainerList);
-CORESHARED_EXPORT QDataStream &operator>>(QDataStream &stream, QList<PropertyContainer> &propertyContainerList);
+QMLDESIGNERCORE_EXPORT QDataStream &operator<<(QDataStream &stream, const QList<PropertyContainer> &propertyContainerList);
+QMLDESIGNERCORE_EXPORT QDataStream &operator>>(QDataStream &stream, QList<PropertyContainer> &propertyContainerList);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, QList<PropertyContainer> &propertyContainerList);
} //namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/include/propertynode.h b/src/plugins/qmldesigner/designercore/include/propertynode.h
index b0a62abc1d..9b08929b42 100644
--- a/src/plugins/qmldesigner/designercore/include/propertynode.h
+++ b/src/plugins/qmldesigner/designercore/include/propertynode.h
@@ -30,11 +30,11 @@
#ifndef PROPERTYNODE_H
#define PROPERTYNODE_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
namespace QmlDesigner {
-class CORESHARED_EXPORT PropertyNode // : public BaseModelNode
+class QMLDESIGNERCORE_EXPORT PropertyNode // : public BaseModelNode
{
public:
PropertyNode();
diff --git a/src/plugins/qmldesigner/designercore/include/qmlanchors.h b/src/plugins/qmldesigner/designercore/include/qmlanchors.h
index 6b8fb97fda..a0565677df 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlanchors.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlanchors.h
@@ -30,13 +30,13 @@
#ifndef QmlAnchors_H
#define QmlAnchors_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <qmlitemnode.h>
namespace QmlDesigner {
-class CORESHARED_EXPORT AnchorLine
+class QMLDESIGNERCORE_EXPORT AnchorLine
{
public:
enum Type {
@@ -73,7 +73,7 @@ private:
};
-class CORESHARED_EXPORT QmlAnchors
+class QMLDESIGNERCORE_EXPORT QmlAnchors
{
public:
QmlAnchors(const QmlItemNode &fxItemNode);
diff --git a/src/plugins/qmldesigner/designercore/include/qmlchangeset.h b/src/plugins/qmldesigner/designercore/include/qmlchangeset.h
index f28bf6df50..11042559b2 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlchangeset.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlchangeset.h
@@ -30,13 +30,13 @@
#ifndef QMLCHANGESET_H
#define QMLCHANGESET_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <modelnode.h>
#include "qmlmodelnodefacade.h"
namespace QmlDesigner {
-class CORESHARED_EXPORT QmlModelStateOperation : public QmlModelNodeFacade
+class QMLDESIGNERCORE_EXPORT QmlModelStateOperation : public QmlModelNodeFacade
{
public:
QmlModelStateOperation() : QmlModelNodeFacade() {}
@@ -47,7 +47,7 @@ public:
};
-class CORESHARED_EXPORT QmlPropertyChanges : public QmlModelStateOperation
+class QMLDESIGNERCORE_EXPORT QmlPropertyChanges : public QmlModelStateOperation
{
public:
QmlPropertyChanges() : QmlModelStateOperation() {}
diff --git a/src/plugins/qmldesigner/designercore/include/corelib_global.h b/src/plugins/qmldesigner/designercore/include/qmldesignercorelib_global.h
index 8cc3f20ba5..449691b054 100644
--- a/src/plugins/qmldesigner/designercore/include/corelib_global.h
+++ b/src/plugins/qmldesigner/designercore/include/qmldesignercorelib_global.h
@@ -32,15 +32,14 @@
// Unnecessary since core isn't a dll any more.
-#define CORESHARED_EXPORT
#define TEST_CORESHARED_EXPORT
-//#if defined(CORE_LIBRARY)
-//# define CORESHARED_EXPORT Q_DECL_EXPORT
-//#else
-//# define CORESHARED_EXPORT Q_DECL_IMPORT
-//#endif
-//
+#if defined(DESIGNER_CORE_LIBRARY)
+# define QMLDESIGNERCORE_EXPORT Q_DECL_EXPORT
+#else
+# define QMLDESIGNERCORE_EXPORT Q_DECL_IMPORT
+#endif
+
//#if defined(TEST_EXPORTS)
//#if defined(CORE_LIBRARY)
//# define TEST_CORESHARED_EXPORT Q_DECL_EXPORT
diff --git a/src/plugins/qmldesigner/designercore/include/qmlitemnode.h b/src/plugins/qmldesigner/designercore/include/qmlitemnode.h
index 1d651ef91c..56a5783d94 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlitemnode.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlitemnode.h
@@ -30,7 +30,7 @@
#ifndef QmlItemNode_H
#define QmlItemNode_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <modelnode.h>
#include "qmlobjectnode.h"
#include "qmlstate.h"
@@ -44,9 +44,9 @@ namespace QmlDesigner {
class QmlModelStateGroup;
class QmlAnchors;
-class CORESHARED_EXPORT QmlItemNode : public QmlObjectNode
+class QMLDESIGNERCORE_EXPORT QmlItemNode : public QmlObjectNode
{
- friend class CORESHARED_EXPORT QmlAnchors;
+ friend class QMLDESIGNERCORE_EXPORT QmlAnchors;
public:
QmlItemNode() : QmlObjectNode() {}
QmlItemNode(const ModelNode &modelNode) : QmlObjectNode(modelNode) {}
@@ -97,9 +97,9 @@ public:
bool hasAnySubModelNodes() const;
};
-CORESHARED_EXPORT uint qHash(const QmlItemNode &node);
+QMLDESIGNERCORE_EXPORT uint qHash(const QmlItemNode &node);
-class CORESHARED_EXPORT QmlModelStateGroup
+class QMLDESIGNERCORE_EXPORT QmlModelStateGroup
{
friend class QmlItemNode;
friend class QmlModelView;
@@ -122,8 +122,8 @@ private:
ModelNode m_modelNode;
};
-CORESHARED_EXPORT QList<ModelNode> toModelNodeList(const QList<QmlItemNode> &fxItemNodeList);
-CORESHARED_EXPORT QList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList);
+QMLDESIGNERCORE_EXPORT QList<ModelNode> toModelNodeList(const QList<QmlItemNode> &fxItemNodeList);
+QMLDESIGNERCORE_EXPORT QList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList);
} //QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h b/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h
index dd5e8ca102..5576c291c6 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlmodelnodefacade.h
@@ -30,14 +30,14 @@
#ifndef FXMODELNODEFACADE_H
#define FXMODELNODEFACADE_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <modelnode.h>
namespace QmlDesigner {
class QmlModelView;
-class CORESHARED_EXPORT QmlModelNodeFacade
+class QMLDESIGNERCORE_EXPORT QmlModelNodeFacade
{
public:
operator ModelNode() const { return m_modelNode; }
@@ -47,10 +47,10 @@ public:
QmlModelNodeFacade();
bool isRootNode() const;
+ QmlModelView* qmlModelView() const;
protected:
QmlModelNodeFacade(const ModelNode &modelNode);
- QmlModelView* qmlModelView() const;
private:
ModelNode m_modelNode;
diff --git a/src/plugins/qmldesigner/designercore/include/qmlmodelview.h b/src/plugins/qmldesigner/designercore/include/qmlmodelview.h
index 92e98a10dd..dc0e47e4df 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlmodelview.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlmodelview.h
@@ -30,7 +30,7 @@
#ifndef QMLMODELVIEW_H
#define QMLMODELVIEW_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include <QPoint>
#include <abstractview.h>
#include "qmlitemnode.h"
@@ -42,11 +42,11 @@ namespace QmlDesigner {
class ItemLibraryEntry;
-class CORESHARED_EXPORT QmlModelView : public AbstractView
+class QMLDESIGNERCORE_EXPORT QmlModelView : public AbstractView
{
Q_OBJECT
- friend CORESHARED_EXPORT class QmlObjectNode;
- friend CORESHARED_EXPORT class QmlModelNodeFacade;
+ friend QMLDESIGNERCORE_EXPORT class QmlObjectNode;
+ friend QMLDESIGNERCORE_EXPORT class QmlModelNodeFacade;
public:
QmlModelView(QObject *parent) ;
@@ -67,6 +67,8 @@ public:
int minorVersion,
const PropertyListType &propertyList = PropertyListType());
+ ModelNode createQmlState(const PropertyListType &propertyList = PropertyListType());
+
QmlItemNode createQmlItemNode(const ItemLibraryEntry &itemLibraryEntry, const QPointF &position, QmlItemNode parentNode);
QmlItemNode createQmlItemNodeFromImage(const QString &imageName, const QPointF &position, QmlItemNode parentNode);
@@ -120,8 +122,6 @@ public:
void importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports);
void nodeSourceChanged(const ModelNode &modelNode, const QString &newNodeSource);
- void showContextMenu(const QPoint &globalPos, const QPoint &scenePos, bool showSelection);
-
protected:
NodeInstance instanceForModelNode(const ModelNode &modelNode);
bool hasInstanceForModelNode(const ModelNode &modelNode);
diff --git a/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h b/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h
index e669c1f265..c0a6545f36 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlobjectnode.h
@@ -30,7 +30,7 @@
#ifndef FXOBJECTNODE_H
#define FXOBJECTNODE_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include "qmlmodelnodefacade.h"
#include "qmlstate.h"
#include "qmlchangeset.h"
@@ -42,7 +42,7 @@ namespace QmlDesigner {
class QmlItemNode;
class QmlPropertyChanges;
-class CORESHARED_EXPORT QmlObjectNode : public QmlModelNodeFacade
+class QMLDESIGNERCORE_EXPORT QmlObjectNode : public QmlModelNodeFacade
{
public:
QmlObjectNode() : QmlModelNodeFacade() {}
@@ -106,9 +106,9 @@ protected:
QList<QmlModelState> allDefinedStates() const;
};
-CORESHARED_EXPORT uint qHash(const QmlObjectNode &node);
-CORESHARED_EXPORT QList<ModelNode> toModelNodeList(const QList<QmlObjectNode> &fxObjectNodeList);
-CORESHARED_EXPORT QList<QmlObjectNode> toQmlObjectNodeList(const QList<ModelNode> &modelNodeList);
+QMLDESIGNERCORE_EXPORT uint qHash(const QmlObjectNode &node);
+QMLDESIGNERCORE_EXPORT QList<ModelNode> toModelNodeList(const QList<QmlObjectNode> &fxObjectNodeList);
+QMLDESIGNERCORE_EXPORT QList<QmlObjectNode> toQmlObjectNodeList(const QList<ModelNode> &modelNodeList);
}// QmlDesigner
#endif // FXOBJECTNODE_H
diff --git a/src/plugins/qmldesigner/designercore/include/qmlstate.h b/src/plugins/qmldesigner/designercore/include/qmlstate.h
index 6418ffa964..f66087593b 100644
--- a/src/plugins/qmldesigner/designercore/include/qmlstate.h
+++ b/src/plugins/qmldesigner/designercore/include/qmlstate.h
@@ -30,7 +30,7 @@
#ifndef FXSTATE_H
#define FXSTATE_H
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
#include "qmlmodelnodefacade.h"
#include "qmlchangeset.h"
@@ -40,9 +40,9 @@ class QmlModelView;
class QmlModelStateGroup;
class QmlObjectNode;
-class CORESHARED_EXPORT QmlModelState : public QmlModelNodeFacade
+class QMLDESIGNERCORE_EXPORT QmlModelState : public QmlModelNodeFacade
{
- friend class CORESHARED_EXPORT QmlModelView;
+ friend class QMLDESIGNERCORE_EXPORT QmlModelView;
public:
QmlModelState();
diff --git a/src/plugins/qmldesigner/designercore/include/removebasestateexception.h b/src/plugins/qmldesigner/designercore/include/removebasestateexception.h
index a97f74caa7..51875067ca 100644
--- a/src/plugins/qmldesigner/designercore/include/removebasestateexception.h
+++ b/src/plugins/qmldesigner/designercore/include/removebasestateexception.h
@@ -34,7 +34,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT RemoveBaseStateException : public Exception
+class QMLDESIGNERCORE_EXPORT RemoveBaseStateException : public Exception
{
public:
RemoveBaseStateException(int line,
diff --git a/src/plugins/qmldesigner/designercore/include/rewriterview.h b/src/plugins/qmldesigner/designercore/include/rewriterview.h
index e39a5c3cf4..805763fc27 100644
--- a/src/plugins/qmldesigner/designercore/include/rewriterview.h
+++ b/src/plugins/qmldesigner/designercore/include/rewriterview.h
@@ -30,7 +30,7 @@
#ifndef REWRITERVIEW_H
#define REWRITERVIEW_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "abstractview.h"
#include "exception.h"
#include <modelnodepositionstorage.h>
@@ -39,6 +39,7 @@
#include <QPointer>
#include <QWeakPointer>
#include <QHash>
+#include <QUrl>
#include <modelnode.h>
#include <QScopedPointer>
@@ -54,7 +55,7 @@ class ScopeChain;
namespace QmlDesigner {
-class CORESHARED_EXPORT TextModifier;
+class TextModifier;
namespace Internal {
@@ -64,7 +65,7 @@ class ModelNodePositionStorage;
} //Internal
-class CORESHARED_EXPORT RewriterView : public AbstractView
+class QMLDESIGNERCORE_EXPORT RewriterView : public AbstractView
{
Q_OBJECT
@@ -162,6 +163,9 @@ public:
void setTextModifier(TextModifier *textModifier);
QString textModifierContent() const;
+ void reactivateTextMofifierChangeSignals();
+ void deactivateTextMofifierChangeSignals();
+
Internal::ModelNodePositionStorage *positionStorage() const
{ return m_positionStorage; }
@@ -181,6 +185,7 @@ public:
int firstDefinitionInsideOffset(const ModelNode &node) const;
int firstDefinitionInsideLength(const ModelNode &node) const;
bool modificationGroupActive();
+ ModelNode nodeAtTextCursorPosition(int cursorPosition) const;
bool renameId(const QString& oldId, const QString& newId);
@@ -195,6 +200,10 @@ public:
void setCheckSemanticErrors(bool b)
{ m_checkErrors = b; }
+ QString pathForImport(const Import &import);
+
+ QWidget *widget();
+
signals:
void errorsChanged(const QList<RewriterView::Error> &errors);
diff --git a/src/plugins/qmldesigner/designercore/include/subcomponentmanager.h b/src/plugins/qmldesigner/designercore/include/subcomponentmanager.h
index 4f6d139467..55bf886ca3 100644
--- a/src/plugins/qmldesigner/designercore/include/subcomponentmanager.h
+++ b/src/plugins/qmldesigner/designercore/include/subcomponentmanager.h
@@ -30,7 +30,7 @@
#ifndef SUBCOMPONENTMANAGER_H
#define SUBCOMPONENTMANAGER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <import.h>
@@ -45,7 +45,7 @@ namespace QmlDesigner {
class Model;
-class CORESHARED_EXPORT SubComponentManager : public QObject
+class QMLDESIGNERCORE_EXPORT SubComponentManager : public QObject
{
Q_OBJECT
public:
diff --git a/src/plugins/qmldesigner/designercore/include/textmodifier.h b/src/plugins/qmldesigner/designercore/include/textmodifier.h
index c61c49a61c..af9cde56d2 100644
--- a/src/plugins/qmldesigner/designercore/include/textmodifier.h
+++ b/src/plugins/qmldesigner/designercore/include/textmodifier.h
@@ -30,7 +30,7 @@
#ifndef TEXTMODIFIER_H
#define TEXTMODIFIER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <qmljs/qmljsdocument.h>
@@ -41,7 +41,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT TextModifier: public QObject
+class QMLDESIGNERCORE_EXPORT TextModifier: public QObject
{
Q_OBJECT
diff --git a/src/plugins/qmldesigner/designercore/include/variantproperty.h b/src/plugins/qmldesigner/designercore/include/variantproperty.h
index c2cf039071..54bc3df1c0 100644
--- a/src/plugins/qmldesigner/designercore/include/variantproperty.h
+++ b/src/plugins/qmldesigner/designercore/include/variantproperty.h
@@ -30,7 +30,7 @@
#ifndef VARIANTROPERTY_H
#define VARIANTROPERTY_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "abstractproperty.h"
QT_BEGIN_NAMESPACE
@@ -45,7 +45,7 @@ namespace Internal {
class ModelPrivate;
}
-class CORESHARED_EXPORT VariantProperty : public AbstractProperty
+class QMLDESIGNERCORE_EXPORT VariantProperty : public AbstractProperty
{
friend class QmlDesigner::ModelNode;
friend class QmlDesigner::Internal::ModelPrivate;
@@ -57,7 +57,7 @@ public:
VariantProperty& operator= (const QVariant &value);
void setDynamicTypeNameAndValue(const QString &type, const QVariant &value);
- VariantProperty& operator= (const QPair<QString, QVariant> &typeValuePair);
+ Q_DECL_DEPRECATED VariantProperty& operator= (const QPair<QString, QVariant> &typeValuePair);
VariantProperty();
VariantProperty(const VariantProperty &property, AbstractView *view);
@@ -65,8 +65,8 @@ protected:
VariantProperty(const QString &propertyName, const Internal::InternalNodePointer &internalNode, Model* model, AbstractView *view);
};
-CORESHARED_EXPORT QTextStream& operator<<(QTextStream &stream, const VariantProperty &property);
-CORESHARED_EXPORT QDebug operator<<(QDebug debug, const VariantProperty &VariantProperty);
+QMLDESIGNERCORE_EXPORT QTextStream& operator<<(QTextStream &stream, const VariantProperty &property);
+QMLDESIGNERCORE_EXPORT QDebug operator<<(QDebug debug, const VariantProperty &VariantProperty);
}
diff --git a/src/plugins/qmldesigner/designercore/include/viewmanager.h b/src/plugins/qmldesigner/designercore/include/viewmanager.h
new file mode 100644
index 0000000000..481c050d33
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/include/viewmanager.h
@@ -0,0 +1,115 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLDESIGNER_VIEWMANAGER_H
+#define QMLDESIGNER_VIEWMANAGER_H
+
+#include "abstractview.h"
+
+#include <rewriterview.h>
+#include <nodeinstanceview.h>
+#include <itemlibraryview.h>
+#include <navigatorview.h>
+#include <stateseditorview.h>
+#include <formeditorview.h>
+#include <propertyeditor.h>
+#include <componentview.h>
+#include <model/viewlogger.h>
+
+namespace QmlDesigner {
+
+class DesignDocument;
+
+namespace Internal {
+ class DesignModeWidget;
+}
+
+class ViewManager
+{
+public:
+ ViewManager();
+
+ void attachRewriterView(TextModifier *textModifier);
+ void detachRewriterView();
+
+ void attachComponentView();
+ void detachComponentView();
+
+ void attachViewsExceptRewriterAndComponetView();
+ void detachViewsExceptRewriterAndComponetView();
+
+ void setItemLibraryViewResourcePath(const QString &resourcePath);
+ void setComponentNode(const ModelNode &componentNode);
+ void setNodeInstanceViewQtPath(const QString & qtPath);
+
+ void resetPropertyEditorView();
+
+ QWidget *formEditorWidget();
+ QWidget *propertyEditorWidget();
+ QWidget *itemLibraryWidget();
+ QWidget *navigatorWidget();
+ QWidget *statesEditorWidget();
+
+ void pushFileOnCrambleBar(const QString &fileName);
+ void pushInFileComponentOnCrambleBar(const QString &componentId);
+ void nextFileIsCalledInternally();
+
+private: // functions
+ Q_DISABLE_COPY(ViewManager)
+
+ void attachNodeInstanceView();
+ void attachItemLibraryView();
+
+
+
+ Model *currentModel() const;
+ Model *documentModel() const;
+ DesignDocument *currentDesignDocument() const;
+ QString pathToQt() const;
+
+ void switchStateEditorViewToBaseState();
+ void switchStateEditorViewToSavedState();
+
+private: // variables
+ QmlModelState m_savedState;
+ Internal::ViewLogger m_viewLogger;
+ ComponentView m_componentView;
+ FormEditorView m_formEditorView;
+ ItemLibraryView m_itemLibraryView;
+ NavigatorView m_navigatorView;
+ PropertyEditor m_propertyEditorView;
+ StatesEditorView m_statesEditorView;
+ NodeInstanceView m_nodeInstanceView;
+
+ QList<QWeakPointer<AbstractView> > m_additionalViews;
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_VIEWMANAGER_H
diff --git a/src/plugins/qmldesigner/designercore/include/widgetqueryview.h b/src/plugins/qmldesigner/designercore/include/widgetqueryview.h
deleted file mode 100644
index 964aa92a81..0000000000
--- a/src/plugins/qmldesigner/designercore/include/widgetqueryview.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef WIDGETQUERYVIEW_H
-#define WIDGETQUERYVIEW_H
-
-#include "corelib_global.h"
-#include "nodeinstanceview.h"
-#include "propertycontainer.h"
-#include <QHash>
-#include <QList>
-#include <QString>
-#include <QVariant>
-#include <QImage>
-
-namespace QmlDesigner {
-
-class CORESHARED_EXPORT WidgetQueryView : public NodeInstanceView
-{
- Q_OBJECT
-public:
- WidgetQueryView(QObject *parent);
-
- QImage paintObject(const NodeMetaInfo &metaInfo);
- QImage paintObject(const NodeMetaInfo &metaInfo, const QList<PropertyContainer> &properties);
-};
-
-} //namespace QmlDesigner
-
-#endif // WIDGETQUERYVIEW_H
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp
index d0d668bfb0..7381ed2e42 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp
@@ -111,20 +111,18 @@ NodeInstance &NodeInstance::operator=(const NodeInstance &other)
ModelNode NodeInstance::modelNode() const
{
- if (d) {
+ if (d)
return d->modelNode;
- } else {
+ else
return ModelNode();
- }
}
qint32 NodeInstance::instanceId() const
{
- if (d) {
+ if (d)
return d->modelNode.internalId();
- } else {
+ else
return -1;
- }
}
bool NodeInstance::isValid() const
@@ -140,108 +138,96 @@ void NodeInstance::makeInvalid()
QRectF NodeInstance::boundingRect() const
{
- if (isValid()) {
+ if (isValid())
return d->boundingRect;
- } else {
+ else
return QRectF();
- }
}
bool NodeInstance::hasContent() const
{
- if (isValid()) {
+ if (isValid())
return d->hasContent;
- } else {
+ else
return false;
- }
}
bool NodeInstance::isAnchoredBySibling() const
{
- if (isValid()) {
+ if (isValid())
return d->isAnchoredBySibling;
- } else {
+ else
return false;
- }
}
bool NodeInstance::isAnchoredByChildren() const
{
- if (isValid()) {
+ if (isValid())
return d->isAnchoredByChildren;
- } else {
+ else
return false;
- }
}
bool NodeInstance::isMovable() const
{
- if (isValid()) {
+ if (isValid())
return d->isMovable;
- } else {
+ else
return false;
- }
}
bool NodeInstance::isResizable() const
{
- if (isValid()) {
+ if (isValid())
return d->isResizable;
- } else {
+ else
return false;
- }
}
QTransform NodeInstance::transform() const
{
- if (isValid()) {
+ if (isValid())
return d->transform;
- } else {
+ else
return QTransform();
- }
}
QTransform NodeInstance::sceneTransform() const
{
- if (isValid()) {
+ if (isValid())
return d->sceneTransform;
- } else {
+ else
return QTransform();
- }
}
bool NodeInstance::isInPositioner() const
{
- if (isValid()) {
+ if (isValid())
return d->isInPositioner;
- } else {
+ else
return false;
- }
}
QPointF NodeInstance::position() const
{
- if (isValid()) {
+ if (isValid())
return d->position;
- } else {
+ else
return QPointF();
- }
}
QSizeF NodeInstance::size() const
{
- if (isValid()) {
+ if (isValid())
return d->size;
- } else {
+ else
return QSizeF();
- }
}
int NodeInstance::penWidth() const
{
- if (isValid()) {
+ if (isValid())
return d->penWidth;
- } else {
+ else
return 1;
- }
}
void NodeInstance::paint(QPainter *painter)
@@ -276,11 +262,10 @@ QString NodeInstance::instanceType(const QString &name) const
qint32 NodeInstance::parentId() const
{
- if (isValid()) {
+ if (isValid())
return d->parentInstanceId;
- } else {
+ else
return false;
- }
}
bool NodeInstance::hasAnchor(const QString &name) const
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
index 510f8d64ba..b2decdfc28 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.cpp
@@ -35,6 +35,7 @@
#include <QCoreApplication>
#include <QUuid>
#include <QFileInfo>
+#include <QTimer>
#include "propertyabstractcontainer.h"
#include "propertyvaluecontainer.h"
@@ -63,14 +64,28 @@
#include "statepreviewimagechangedcommand.h"
#include "componentcompletedcommand.h"
#include "tokencommand.h"
-
+#include "removesharedmemorycommand.h"
+#include "endpuppetcommand.h"
#include "synchronizecommand.h"
+#include "debugoutputcommand.h"
#include "nodeinstanceview.h"
#include "import.h"
+
+#include <utils/hostosinfo.h>
+
#include <QMessageBox>
+namespace {
+static QLatin1String qmlPuppetApplicationDirectoryForTests()
+{
+ if (Utils::HostOsInfo::isWindowsHost())
+ //one more - debug/release dir
+ return QLatin1String("/../../../../../../bin/");
+ return QLatin1String("/../../../../../bin/");
+}
+} //namespace
namespace QmlDesigner {
@@ -108,7 +123,9 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
QString applicationPath = pathToQt + QLatin1String("/bin");
if (runModus == TestModus) {
- applicationPath = QCoreApplication::applicationDirPath() + QLatin1String("/../../../../../bin");
+ applicationPath = QCoreApplication::applicationDirPath()
+ + qmlPuppetApplicationDirectoryForTests()
+ + qmlPuppetApplicationName();
} else {
applicationPath = macOSBundlePath(applicationPath);
applicationPath += QLatin1Char('/') + qmlPuppetApplicationName();
@@ -121,12 +138,10 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
}
QByteArray envImportPath = qgetenv("QTCREATOR_QMLPUPPET_PATH");
- if (!envImportPath.isEmpty()) {
+ if (!envImportPath.isEmpty())
applicationPath = envImportPath;
- }
QProcessEnvironment enviroment = QProcessEnvironment::systemEnvironment();
- enviroment.insert("QML_NO_THREADED_RENDERER", "true");
if (QFileInfo(applicationPath).exists()) {
m_qmlPuppetEditorProcess = new QProcess;
@@ -194,7 +209,6 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
}
} else {
- if (!hasQtQuick2(m_nodeInstanceView.data()))
QMessageBox::warning(0, tr("Cannot Start QML Puppet Executable"),
tr("The executable of the QML Puppet process (%1) cannot be started. "
"Please check your installation. "
@@ -205,7 +219,6 @@ NodeInstanceServerProxy::NodeInstanceServerProxy(NodeInstanceView *nodeInstanceV
m_localServer->close();
} else {
- if (!hasQtQuick2(m_nodeInstanceView.data()))
QMessageBox::warning(0, tr("Cannot Find QML Puppet Executable"),
tr("The executable of the QML Puppet process (%1) cannot be found. "
"Please check your installation. "
@@ -218,24 +231,26 @@ NodeInstanceServerProxy::~NodeInstanceServerProxy()
{
disconnect(this, SLOT(processFinished(int,QProcess::ExitStatus)));
+ writeCommand(QVariant::fromValue(EndPuppetCommand()));
+
if (m_firstSocket)
m_firstSocket->close();
if (m_secondSocket)
m_secondSocket->close();
- if(m_thirdSocket)
+ if (m_thirdSocket)
m_thirdSocket->close();
if (m_qmlPuppetEditorProcess)
- m_qmlPuppetEditorProcess->kill();
+ QTimer::singleShot(3000, m_qmlPuppetEditorProcess.data(), SLOT(terminate()));
if (m_qmlPuppetPreviewProcess)
- m_qmlPuppetPreviewProcess->kill();
+ QTimer::singleShot(3000, m_qmlPuppetPreviewProcess.data(), SLOT(terminate()));
if (m_qmlPuppetRenderProcess)
- m_qmlPuppetRenderProcess->kill();
+ QTimer::singleShot(3000, m_qmlPuppetRenderProcess.data(), SLOT(terminate()));
}
void NodeInstanceServerProxy::dispatchCommand(const QVariant &command)
@@ -248,6 +263,7 @@ void NodeInstanceServerProxy::dispatchCommand(const QVariant &command)
static const int componentCompletedCommandType = QMetaType::type("ComponentCompletedCommand");
static const int synchronizeCommandType = QMetaType::type("SynchronizeCommand");
static const int tokenCommandType = QMetaType::type("TokenCommand");
+ static const int debugOutputCommandType = QMetaType::type("DebugOutputCommand");
if (command.userType() == informationChangedCommandType)
nodeInstanceClient()->informationChanged(command.value<InformationChangedCommand>());
@@ -263,6 +279,8 @@ void NodeInstanceServerProxy::dispatchCommand(const QVariant &command)
nodeInstanceClient()->componentCompleted(command.value<ComponentCompletedCommand>());
else if (command.userType() == tokenCommandType)
nodeInstanceClient()->token(command.value<TokenCommand>());
+ else if (command.userType() == debugOutputCommandType)
+ nodeInstanceClient()->debugOutput(command.value<DebugOutputCommand>());
else if (command.userType() == synchronizeCommandType) {
SynchronizeCommand synchronizeCommand = command.value<SynchronizeCommand>();
m_synchronizeId = synchronizeCommand.synchronizeId();
@@ -277,7 +295,7 @@ NodeInstanceClientInterface *NodeInstanceServerProxy::nodeInstanceClient() const
static void writeCommandToSocket(const QVariant &command, QLocalSocket *socket, unsigned int commandCounter)
{
- if(socket) {
+ if (socket) {
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_8);
@@ -305,7 +323,7 @@ void NodeInstanceServerProxy::writeCommand(const QVariant &command)
writeCommandToSocket(QVariant::fromValue(synchronizeCommand), m_firstSocket.data(), m_writeCommandCounter);
m_writeCommandCounter++;
- while(m_firstSocket->waitForReadyRead()) {
+ while (m_firstSocket->waitForReadyRead(100)) {
readFirstDataStream();
if (m_synchronizeId == synchronizeId)
return;
@@ -316,6 +334,9 @@ void NodeInstanceServerProxy::writeCommand(const QVariant &command)
void NodeInstanceServerProxy::processFinished(int /*exitCode*/, QProcess::ExitStatus exitStatus)
{
qDebug() << "Process finished:" << sender();
+
+ writeCommand(QVariant::fromValue(EndPuppetCommand()));
+
if (m_firstSocket)
m_firstSocket->close();
if (m_secondSocket)
@@ -339,9 +360,8 @@ void NodeInstanceServerProxy::readFirstDataStream()
QDataStream in(m_firstSocket.data());
in.setVersion(QDataStream::Qt_4_8);
- if (m_firstBlockSize == 0) {
+ if (m_firstBlockSize == 0)
in >> m_firstBlockSize;
- }
if (m_firstSocket->bytesAvailable() < m_firstBlockSize)
break;
@@ -377,9 +397,8 @@ void NodeInstanceServerProxy::readSecondDataStream()
QDataStream in(m_secondSocket.data());
in.setVersion(QDataStream::Qt_4_8);
- if (m_secondBlockSize == 0) {
+ if (m_secondBlockSize == 0)
in >> m_secondBlockSize;
- }
if (m_secondSocket->bytesAvailable() < m_secondBlockSize)
break;
@@ -415,9 +434,8 @@ void NodeInstanceServerProxy::readThirdDataStream()
QDataStream in(m_thirdSocket.data());
in.setVersion(QDataStream::Qt_4_8);
- if (m_thirdBlockSize == 0) {
+ if (m_thirdBlockSize == 0)
in >> m_thirdBlockSize;
- }
if (m_thirdSocket->bytesAvailable() < m_thirdBlockSize)
break;
@@ -444,25 +462,16 @@ void NodeInstanceServerProxy::readThirdDataStream()
QString NodeInstanceServerProxy::qmlPuppetApplicationName() const
{
- QString appName;
- if (hasQtQuick2(m_nodeInstanceView.data())) {
- appName = QLatin1String("qml2puppet");
- } else {
- appName = QLatin1String("qmlpuppet");
- }
- #ifdef Q_OS_WIN
- appName += QLatin1String(".exe");
- #endif
-
- return appName;
+ if (hasQtQuick2(m_nodeInstanceView.data()))
+ return QLatin1String("qml2puppet" QTC_HOST_EXE_SUFFIX);
+ return QLatin1String("qmlpuppet" QTC_HOST_EXE_SUFFIX);
}
QString NodeInstanceServerProxy::macOSBundlePath(const QString &path) const
{
QString applicationPath = path;
-#ifdef Q_OS_MACX
- applicationPath += QLatin1String("/qmlpuppet.app/Contents/MacOS");
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ applicationPath += QLatin1String("/qmlpuppet.app/Contents/MacOS");
return applicationPath;
}
@@ -541,4 +550,9 @@ void NodeInstanceServerProxy::token(const TokenCommand &command)
writeCommand(QVariant::fromValue(command));
}
+void NodeInstanceServerProxy::removeSharedMemory(const RemoveSharedMemoryCommand &command)
+{
+ writeCommand(QVariant::fromValue(command));
+}
+
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h
index 14be7a53a6..9667f0a4bb 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceserverproxy.h
@@ -69,6 +69,7 @@ public:
void completeComponent(const CompleteComponentCommand &command);
void changeNodeSource(const ChangeNodeSourceCommand &command);
void token(const TokenCommand &command);
+ void removeSharedMemory(const RemoveSharedMemoryCommand &command);
protected:
void writeCommand(const QVariant &command);
diff --git a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp
index da228f33c2..97037f34bd 100644
--- a/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp
+++ b/src/plugins/qmldesigner/designercore/instances/nodeinstanceview.cpp
@@ -29,10 +29,6 @@
#include "nodeinstanceview.h"
-#include <QDeclarativeEngine>
-#include <QDeclarativeContext>
-
-#include <QDebug>
#include <QUrl>
#include <QGraphicsView>
#include <QGraphicsScene>
@@ -77,6 +73,7 @@
#include "completecomponentcommand.h"
#include "componentcompletedcommand.h"
#include "tokencommand.h"
+#include "removesharedmemorycommand.h"
#include "nodeinstanceserverproxy.h"
@@ -194,11 +191,10 @@ void NodeInstanceView::handleChrash()
{
int elaspsedTimeSinceLastCrash = m_lastCrashTime.restart();
- if (elaspsedTimeSinceLastCrash > 2000) {
+ if (elaspsedTimeSinceLastCrash > 2000)
restartProcess();
- } else {
+ else
emit qmlPuppetCrashed();
- }
}
@@ -240,6 +236,7 @@ void NodeInstanceView::nodeCreated(const ModelNode &createdNode)
void NodeInstanceView::nodeAboutToBeRemoved(const ModelNode &removedNode)
{
nodeInstanceServer()->removeInstances(createRemoveInstancesCommand(removedNode));
+ nodeInstanceServer()->removeSharedMemory(createRemoveSharedMemoryCommand("Image", removedNode.internalId()));
removeInstanceAndSubInstances(removedNode);
}
@@ -252,17 +249,15 @@ void NodeInstanceView::resetHorizontalAnchors(const ModelNode &modelNode)
QList<BindingProperty> bindingList;
QList<VariantProperty> valueList;
- if (modelNode.hasBindingProperty("x")) {
+ if (modelNode.hasBindingProperty("x"))
bindingList.append(modelNode.bindingProperty("x"));
- } else if (modelNode.hasVariantProperty("x")) {
+ else if (modelNode.hasVariantProperty("x"))
valueList.append(modelNode.variantProperty("x"));
- }
- if (modelNode.hasBindingProperty("width")) {
+ if (modelNode.hasBindingProperty("width"))
bindingList.append(modelNode.bindingProperty("width"));
- } else if (modelNode.hasVariantProperty("width")) {
+ else if (modelNode.hasVariantProperty("width"))
valueList.append(modelNode.variantProperty("width"));
- }
if (!valueList.isEmpty())
nodeInstanceServer()->changePropertyValues(createChangeValueCommand(valueList));
@@ -277,17 +272,15 @@ void NodeInstanceView::resetVerticalAnchors(const ModelNode &modelNode)
QList<BindingProperty> bindingList;
QList<VariantProperty> valueList;
- if (modelNode.hasBindingProperty("yx")) {
+ if (modelNode.hasBindingProperty("yx"))
bindingList.append(modelNode.bindingProperty("yx"));
- } else if (modelNode.hasVariantProperty("y")) {
+ else if (modelNode.hasVariantProperty("y"))
valueList.append(modelNode.variantProperty("y"));
- }
- if (modelNode.hasBindingProperty("height")) {
+ if (modelNode.hasBindingProperty("height"))
bindingList.append(modelNode.bindingProperty("height"));
- } else if (modelNode.hasVariantProperty("height")) {
+ else if (modelNode.hasVariantProperty("height"))
valueList.append(modelNode.variantProperty("height"));
- }
if (!valueList.isEmpty())
nodeInstanceServer()->changePropertyValues(createChangeValueCommand(valueList));
@@ -303,14 +296,14 @@ void NodeInstanceView::propertiesAboutToBeRemoved(const QList<AbstractProperty>&
QList<AbstractProperty> nonNodePropertyList;
foreach (const AbstractProperty &property, propertyList) {
- if (property.isNodeAbstractProperty()) {
+ if (property.isNodeAbstractProperty())
nodeList.append(property.toNodeAbstractProperty().allSubNodes());
- } else {
+ else
nonNodePropertyList.append(property);
- }
}
nodeInstanceServer()->removeInstances(createRemoveInstancesCommand(nodeList));
+ nodeInstanceServer()->removeSharedMemory(createRemoveSharedMemoryCommand("Image", nodeList));
nodeInstanceServer()->removeProperties(createRemovePropertiesCommand(nonNodePropertyList));
foreach (const AbstractProperty &property, propertyList) {
@@ -348,7 +341,7 @@ void NodeInstanceView::propertiesRemoved(const QList<AbstractProperty>& /*proper
void NodeInstanceView::removeInstanceAndSubInstances(const ModelNode &node)
{
- foreach(const ModelNode &subNode, node.allSubModelNodes()) {
+ foreach (const ModelNode &subNode, node.allSubModelNodes()) {
if (hasInstanceForNode(subNode))
removeInstanceNodeRelationship(subNode);
}
@@ -428,7 +421,7 @@ void NodeInstanceView::nodeOrderChanged(const NodeListProperty & listProperty,
if (hasInstanceForNode(containerNode))
containerInstanceId = instanceForNode(containerNode).instanceId();
- foreach(const ModelNode &node, listProperty.toModelNodeList()) {
+ foreach (const ModelNode &node, listProperty.toModelNodeList()) {
qint32 instanceId = -1;
if (hasInstanceForNode(node)) {
instanceId = instanceForNode(node).instanceId();
@@ -552,11 +545,10 @@ void NodeInstanceView::actualStateChanged(const ModelNode &node)
{
NodeInstance newStateInstance = instanceForNode(node);
- if (newStateInstance.isValid() && node.metaInfo().isSubclassOf("QtQuick.State", 1, 0)) {
+ if (newStateInstance.isValid() && node.metaInfo().isSubclassOf("QtQuick.State", 1, 0))
nodeInstanceView()->activateState(newStateInstance);
- } else {
+ else
nodeInstanceView()->activateBaseState();
- }
}
@@ -658,7 +650,7 @@ NodeInstance NodeInstanceView::rootNodeInstance() const
void NodeInstanceView::insertInstanceRelationships(const NodeInstance &instance)
{
Q_ASSERT(instance.instanceId() >=0);
- if(m_nodeInstanceHash.contains(instance.modelNode()))
+ if (m_nodeInstanceHash.contains(instance.modelNode()))
return;
m_nodeInstanceHash.insert(instance.modelNode(), instance);
@@ -699,9 +691,8 @@ NodeInstance NodeInstanceView::loadNode(const ModelNode &node)
insertInstanceRelationships(instance);
- if (node.isRootNode()) {
+ if (node.isRootNode())
m_rootNodeInstance = instance;
- }
return instance;
}
@@ -739,7 +730,7 @@ QRectF NodeInstanceView::sceneRect() const
QList<ModelNode> filterNodesForSkipItems(const QList<ModelNode> &nodeList)
{
QList<ModelNode> filteredNodeList;
- foreach(const ModelNode &node, nodeList) {
+ foreach (const ModelNode &node, nodeList) {
if (isSkippedNode(node))
continue;
@@ -763,7 +754,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
nodeList = filterNodesForSkipItems(nodeList);
QList<VariantProperty> variantPropertyList;
- QList<BindingProperty> bindingPropertyList;
+ QList<BindingProperty> bindingPropertyList;
QVector<PropertyValueContainer> auxiliaryContainerVector;
foreach (const ModelNode &node, nodeList) {
@@ -782,7 +773,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
QVector<InstanceContainer> instanceContainerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
InstanceContainer::NodeSourceType nodeSourceType = static_cast<InstanceContainer::NodeSourceType>(instance.modelNode().nodeSourceType());
InstanceContainer::NodeMetaType nodeMetaType = InstanceContainer::ObjectMetaType;
@@ -803,7 +794,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
}
QVector<ReparentContainer> reparentContainerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
if (instance.modelNode().hasParentProperty()) {
NodeAbstractProperty parentProperty = instance.modelNode().parentProperty();
ReparentContainer container(instance.instanceId(), -1, QString(), instanceForNode(parentProperty.parentModelNode()).instanceId(), parentProperty.name());
@@ -812,7 +803,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
}
QVector<IdContainer> idContainerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
QString id = instance.modelNode().id();
if (!id.isEmpty()) {
IdContainer container(instance.instanceId(), id);
@@ -821,7 +812,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
}
QVector<PropertyValueContainer> valueContainerList;
- foreach(const VariantProperty &property, variantPropertyList) {
+ foreach (const VariantProperty &property, variantPropertyList) {
ModelNode node = property.parentModelNode();
if (node.isValid() && hasInstanceForNode(node)) {
NodeInstance instance = instanceForNode(node);
@@ -831,7 +822,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
}
QVector<PropertyBindingContainer> bindingContainerList;
- foreach(const BindingProperty &property, bindingPropertyList) {
+ foreach (const BindingProperty &property, bindingPropertyList) {
ModelNode node = property.parentModelNode();
if (node.isValid() && hasInstanceForNode(node)) {
NodeInstance instance = instanceForNode(node);
@@ -841,7 +832,7 @@ CreateSceneCommand NodeInstanceView::createCreateSceneCommand()
}
QVector<AddImportContainer> importVector;
- foreach(const Import &import, model()->imports())
+ foreach (const Import &import, model()->imports())
importVector.append(AddImportContainer(import.url(), import.file(), import.version(), import.alias(), import.importPaths()));
return CreateSceneCommand(instanceContainerList,
@@ -862,7 +853,7 @@ ClearSceneCommand NodeInstanceView::createClearSceneCommand() const
CompleteComponentCommand NodeInstanceView::createComponentCompleteCommand(const QList<NodeInstance> &instanceList) const
{
QVector<qint32> containerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
if (instance.instanceId() >= 0)
containerList.append(instance.instanceId());
}
@@ -873,7 +864,7 @@ CompleteComponentCommand NodeInstanceView::createComponentCompleteCommand(const
ComponentCompletedCommand NodeInstanceView::createComponentCompletedCommand(const QList<NodeInstance> &instanceList) const
{
QVector<qint32> containerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
if (instance.instanceId() >= 0)
containerList.append(instance.instanceId());
}
@@ -884,7 +875,7 @@ ComponentCompletedCommand NodeInstanceView::createComponentCompletedCommand(cons
CreateInstancesCommand NodeInstanceView::createCreateInstancesCommand(const QList<NodeInstance> &instanceList) const
{
QVector<InstanceContainer> containerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
InstanceContainer::NodeSourceType nodeSourceType = static_cast<InstanceContainer::NodeSourceType>(instance.modelNode().nodeSourceType());
InstanceContainer::NodeMetaType nodeMetaType = InstanceContainer::ObjectMetaType;
@@ -902,7 +893,7 @@ CreateInstancesCommand NodeInstanceView::createCreateInstancesCommand(const QLis
ReparentInstancesCommand NodeInstanceView::createReparentInstancesCommand(const QList<NodeInstance> &instanceList) const
{
QVector<ReparentContainer> containerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
if (instance.modelNode().hasParentProperty()) {
NodeAbstractProperty parentProperty = instance.modelNode().parentProperty();
ReparentContainer container(instance.instanceId(), -1, QString(), instanceForNode(parentProperty.parentModelNode()).instanceId(), parentProperty.name());
@@ -944,7 +935,7 @@ ChangeValuesCommand NodeInstanceView::createChangeValueCommand(const QList<Varia
{
QVector<PropertyValueContainer> containerList;
- foreach(const VariantProperty &property, propertyList) {
+ foreach (const VariantProperty &property, propertyList) {
ModelNode node = property.parentModelNode();
if (node.isValid() && hasInstanceForNode(node)) {
NodeInstance instance = instanceForNode(node);
@@ -961,7 +952,7 @@ ChangeBindingsCommand NodeInstanceView::createChangeBindingCommand(const QList<B
{
QVector<PropertyBindingContainer> containerList;
- foreach(const BindingProperty &property, propertyList) {
+ foreach (const BindingProperty &property, propertyList) {
ModelNode node = property.parentModelNode();
if (node.isValid() && hasInstanceForNode(node)) {
NodeInstance instance = instanceForNode(node);
@@ -977,7 +968,7 @@ ChangeBindingsCommand NodeInstanceView::createChangeBindingCommand(const QList<B
ChangeIdsCommand NodeInstanceView::createChangeIdsCommand(const QList<NodeInstance> &instanceList) const
{
QVector<IdContainer> containerList;
- foreach(const NodeInstance &instance, instanceList) {
+ foreach (const NodeInstance &instance, instanceList) {
QString id = instance.modelNode().id();
if (!id.isEmpty()) {
IdContainer container(instance.instanceId(), id);
@@ -993,13 +984,12 @@ ChangeIdsCommand NodeInstanceView::createChangeIdsCommand(const QList<NodeInstan
RemoveInstancesCommand NodeInstanceView::createRemoveInstancesCommand(const QList<ModelNode> &nodeList) const
{
QVector<qint32> idList;
- foreach(const ModelNode &node, nodeList) {
+ foreach (const ModelNode &node, nodeList) {
if (node.isValid() && hasInstanceForNode(node)) {
NodeInstance instance = instanceForNode(node);
- if (instance.instanceId() >= 0) {
+ if (instance.instanceId() >= 0)
idList.append(instance.instanceId());
- }
}
}
@@ -1020,7 +1010,7 @@ RemovePropertiesCommand NodeInstanceView::createRemovePropertiesCommand(const QL
{
QVector<PropertyAbstractContainer> containerList;
- foreach(const AbstractProperty &property, propertyList) {
+ foreach (const AbstractProperty &property, propertyList) {
ModelNode node = property.parentModelNode();
if (node.isValid() && hasInstanceForNode(node)) {
NodeInstance instance = instanceForNode(node);
@@ -1033,6 +1023,21 @@ RemovePropertiesCommand NodeInstanceView::createRemovePropertiesCommand(const QL
return RemovePropertiesCommand(containerList);
}
+RemoveSharedMemoryCommand NodeInstanceView::createRemoveSharedMemoryCommand(const QString &sharedMemoryTypeName, quint32 keyNumber)
+{
+ return RemoveSharedMemoryCommand(sharedMemoryTypeName, QVector<qint32>() << keyNumber);
+}
+
+RemoveSharedMemoryCommand NodeInstanceView::createRemoveSharedMemoryCommand(const QString &sharedMemoryTypeName, const QList<ModelNode> &nodeList)
+{
+ QVector<qint32> keyNumberVector;
+
+ foreach (const ModelNode &modelNode, nodeList)
+ keyNumberVector.append(modelNode.internalId());
+
+ return RemoveSharedMemoryCommand(sharedMemoryTypeName, keyNumberVector);
+}
+
void NodeInstanceView::valuesChanged(const ValuesChangedCommand &command)
{
if (!model())
@@ -1040,7 +1045,7 @@ void NodeInstanceView::valuesChanged(const ValuesChangedCommand &command)
QList<QPair<ModelNode, QString> > valuePropertyChangeList;
- foreach(const PropertyValueContainer &container, command.valueChanges()) {
+ foreach (const PropertyValueContainer &container, command.valueChanges()) {
if (hasInstanceForId(container.instanceId())) {
NodeInstance instance = instanceForId(container.instanceId());
if (instance.isValid()) {
@@ -1050,6 +1055,8 @@ void NodeInstanceView::valuesChanged(const ValuesChangedCommand &command)
}
}
+ nodeInstanceServer()->removeSharedMemory(createRemoveSharedMemoryCommand(QLatin1String("Values"), command.keyNumber()));
+
if (!valuePropertyChangeList.isEmpty())
emitInstancePropertyChange(valuePropertyChangeList);
}
@@ -1128,7 +1135,7 @@ void NodeInstanceView::statePreviewImagesChanged(const StatePreviewImageChangedC
QVector<ModelNode> previewImageChangeVector;
foreach (const ImageContainer &container, command.previews()) {
- if (container.instanceId() == 0) {
+ if (container.keyNumber() == -1) {
m_baseStatePreviewImage = container.image();
previewImageChangeVector.append(rootModelNode());
} else if (hasInstanceForId(container.instanceId())) {
@@ -1149,10 +1156,9 @@ void NodeInstanceView::componentCompleted(const ComponentCompletedCommand &comma
QVector<ModelNode> nodeVector;
- foreach(const qint32 &instanceId, command.instances()) {
- if (hasModelNodeForInternalId(instanceId)) {
+ foreach (const qint32 &instanceId, command.instances()) {
+ if (hasModelNodeForInternalId(instanceId))
nodeVector.append(modelNodeForInternalId(instanceId));
- }
}
if (!nodeVector.isEmpty())
@@ -1167,7 +1173,7 @@ void NodeInstanceView::childrenChanged(const ChildrenChangedCommand &command)
QVector<ModelNode> childNodeVector;
- foreach(qint32 instanceId, command.childrenInstances()) {
+ foreach (qint32 instanceId, command.childrenInstances()) {
if (hasInstanceForId(instanceId)) {
NodeInstance instance = instanceForId(instanceId);
instance.setParentId(command.parentInstanceId());
@@ -1192,15 +1198,18 @@ void NodeInstanceView::token(const TokenCommand &command)
QVector<ModelNode> nodeVector;
foreach (const qint32 &instanceId, command.instances()) {
- if (hasModelNodeForInternalId(instanceId)) {
+ if (hasModelNodeForInternalId(instanceId))
nodeVector.append(modelNodeForInternalId(instanceId));
- }
}
emitInstanceToken(command.tokenName(), command.tokenNumber(), nodeVector);
}
+void NodeInstanceView::debugOutput(const DebugOutputCommand & /*command*/)
+{
+}
+
void NodeInstanceView::sendToken(const QString &token, int number, const QVector<ModelNode> &nodeVector)
{
QVector<qint32> instanceIdVector;
@@ -1210,4 +1219,9 @@ void NodeInstanceView::sendToken(const QString &token, int number, const QVector
nodeInstanceServer()->token(TokenCommand(token, number, instanceIdVector));
}
+QWidget *NodeInstanceView::widget()
+{
+ return 0;
+}
+
}
diff --git a/src/plugins/qmldesigner/designercore/iwidgetplugin.pri b/src/plugins/qmldesigner/designercore/iwidgetplugin.pri
index 8dceea3244..14cba52687 100644
--- a/src/plugins/qmldesigner/designercore/iwidgetplugin.pri
+++ b/src/plugins/qmldesigner/designercore/iwidgetplugin.pri
@@ -1 +1,2 @@
INCLUDEPATH += $$PWD/include
+DEFINES -= QT_NO_CAST_FROM_ASCII
diff --git a/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
index bb22332d99..0063a1377d 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/itemlibraryinfo.cpp
@@ -55,14 +55,6 @@ public:
bool forceImport;
};
-class ItemLibraryInfoPrivate
-{
-public:
- QHash<QString, ItemLibraryEntry> nameToEntryHash;
-
- QWeakPointer<ItemLibraryInfo> baseInfo;
-};
-
} // namespace Internal
//
@@ -203,7 +195,7 @@ void ItemLibraryEntry::setForceImport(bool b)
m_data->forceImport = b;
}
-void ItemLibraryEntry::addProperty(QString &name, QString &type, QString &value)
+void ItemLibraryEntry::addProperty(QString &name, QString &type, QVariant &value)
{
Property property;
property.set(name, type, value);
@@ -248,68 +240,83 @@ QDataStream& operator>>(QDataStream& stream, ItemLibraryEntry &itemLibraryEntry)
return stream;
}
+QDebug operator<<(QDebug debug, const ItemLibraryEntry &itemLibraryEntry)
+{
+ debug << itemLibraryEntry.m_data->name;
+ debug << itemLibraryEntry.m_data->typeName;
+ debug << itemLibraryEntry.m_data->majorVersion;
+ debug << itemLibraryEntry.m_data->minorVersion;
+ debug << itemLibraryEntry.m_data->icon;
+ debug << itemLibraryEntry.m_data->iconPath;
+ debug << itemLibraryEntry.m_data->category;
+ debug << itemLibraryEntry.m_data->dragIcon;
+ debug << itemLibraryEntry.m_data->requiredImport;
+ debug << itemLibraryEntry.m_data->forceImport;
+
+ debug << itemLibraryEntry.m_data->properties;
+ debug << itemLibraryEntry.m_data->qml;
+
+ return debug.space();
+}
+
//
// ItemLibraryInfo
//
-ItemLibraryInfo::ItemLibraryInfo(QObject *parent) :
- QObject(parent),
- d(new Internal::ItemLibraryInfoPrivate())
+ItemLibraryInfo::ItemLibraryInfo(QObject *parent)
+ : QObject(parent)
{
}
-ItemLibraryInfo::~ItemLibraryInfo()
-{
- delete d;
-}
+
QList<ItemLibraryEntry> ItemLibraryInfo::entriesForType(const QString &typeName, int majorVersion, int minorVersion) const
{
QList<ItemLibraryEntry> entries;
- foreach (const ItemLibraryEntry &entry, d->nameToEntryHash) {
+ foreach (const ItemLibraryEntry &entry, m_nameToEntryHash) {
if (entry.typeName() == typeName
&& entry.majorVersion() >= majorVersion
&& entry.minorVersion() >= minorVersion)
entries += entry;
}
- if (d->baseInfo)
- entries += d->baseInfo->entriesForType(typeName, majorVersion, minorVersion);
+ if (m_baseInfo)
+ entries += m_baseInfo->entriesForType(typeName, majorVersion, minorVersion);
return entries;
}
ItemLibraryEntry ItemLibraryInfo::entry(const QString &name) const
{
- if (d->nameToEntryHash.contains(name))
- return d->nameToEntryHash.value(name);
+ if (m_nameToEntryHash.contains(name))
+ return m_nameToEntryHash.value(name);
- if (d->baseInfo)
- return d->baseInfo->entry(name);
+ if (m_baseInfo)
+ return m_baseInfo->entry(name);
return ItemLibraryEntry();
}
QList<ItemLibraryEntry> ItemLibraryInfo::entries() const
{
- QList<ItemLibraryEntry> list = d->nameToEntryHash.values();
- if (d->baseInfo)
- list += d->baseInfo->entries();
+ QList<ItemLibraryEntry> list = m_nameToEntryHash.values();
+ if (m_baseInfo)
+ list += m_baseInfo->entries();
return list;
}
static inline QString keyForEntry(const ItemLibraryEntry &entry)
{
- return entry.name() + entry.category();
+ return entry.name() + entry.category() + QString::number(entry.majorVersion());
}
-void ItemLibraryInfo::addEntry(const ItemLibraryEntry &entry)
+void ItemLibraryInfo::addEntry(const ItemLibraryEntry &entry, bool overwriteDuplicate)
{
const QString key = keyForEntry(entry);
- if (d->nameToEntryHash.contains(key))
+ if (!overwriteDuplicate && m_nameToEntryHash.contains(key))
throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__);
- d->nameToEntryHash.insert(key, entry);
+ m_nameToEntryHash.insert(key, entry);
emit entriesChanged();
}
@@ -317,18 +324,18 @@ void ItemLibraryInfo::addEntry(const ItemLibraryEntry &entry)
bool ItemLibraryInfo::containsEntry(const ItemLibraryEntry &entry)
{
const QString key = keyForEntry(entry);
- return d->nameToEntryHash.contains(key);
+ return m_nameToEntryHash.contains(key);
}
void ItemLibraryInfo::clearEntries()
{
- d->nameToEntryHash.clear();
+ m_nameToEntryHash.clear();
emit entriesChanged();
}
void ItemLibraryInfo::setBaseInfo(ItemLibraryInfo *baseInfo)
{
- d->baseInfo = baseInfo;
+ m_baseInfo = baseInfo;
}
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
index 20e66cecf0..429c7a3960 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/metainfo.cpp
@@ -33,12 +33,14 @@
#include "modelnode.h"
#include "invalidmodelnodeexception.h"
#include "invalidargumentexception.h"
-#include "metainfoparser.h"
+#include "metainforeader.h"
#include "iwidgetplugin.h"
#include "pluginmanager/widgetpluginmanager.h"
+
#include <QDebug>
+#include <QMessageBox>
#include <QPair>
#include <QtAlgorithms>
@@ -62,7 +64,7 @@ public:
void initialize();
- void parseXmlFiles();
+ void parseItemLibraryDescriptions();
QScopedPointer<ItemLibraryInfo> m_itemLibraryInfo;
@@ -87,7 +89,7 @@ void MetaInfoPrivate::clear()
void MetaInfoPrivate::initialize()
{
- parseXmlFiles();
+ parseItemLibraryDescriptions();
m_isInitialized = true;
}
@@ -107,15 +109,23 @@ static inline bool isDepricatedQtType(const QString &typeName)
return typeName.contains("Qt.");
}
-void MetaInfoPrivate::parseXmlFiles()
+void MetaInfoPrivate::parseItemLibraryDescriptions()
{
Internal::WidgetPluginManager pluginManager;
foreach (const QString &pluginDir, m_q->s_pluginDirs)
pluginManager.addPath(pluginDir);
QList<IWidgetPlugin *> widgetPluginList = pluginManager.instances();
foreach (IWidgetPlugin *plugin, widgetPluginList) {
- Internal::MetaInfoParser parser(*m_q);
- parser.parseFile(plugin->metaInfo());
+ Internal::MetaInfoReader reader(*m_q);
+ try {
+ reader.readMetaInfoFile(plugin->metaInfo());
+ } catch (InvalidMetaInfoException &e) {
+ qWarning() << e.description();
+ const QString errorMessage = plugin->metaInfo() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1String("\n"));
+ QMessageBox::critical(0,
+ QCoreApplication::translate("QmlDesigner::Internal::MetaInfoPrivate", "Invalid meta info"),
+ errorMessage);
+ }
}
}
@@ -195,9 +205,8 @@ MetaInfo MetaInfo::global()
*/
void MetaInfo::clearGlobal()
{
- if (s_global.m_p->m_isInitialized) {
+ if (s_global.m_p->m_isInitialized)
s_global.m_p->clear();
- }
}
void MetaInfo::setPluginPaths(const QStringList &paths)
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainfoparser.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainfoparser.cpp
deleted file mode 100644
index a9d5759a09..0000000000
--- a/src/plugins/qmldesigner/designercore/metainfo/metainfoparser.cpp
+++ /dev/null
@@ -1,245 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "metainfoparser.h"
-#include "metainfo.h"
-
-#include <propertyparser.h>
-#include <QXmlStreamReader>
-#include <QString>
-#include <QFile>
-#include <QDebug>
-#include <QIcon>
-
-namespace QmlDesigner {
-namespace Internal {
-
-
-MetaInfoParser::MetaInfoParser(const MetaInfo &metaInfo)
- : m_metaInfo(metaInfo)
-{
-}
-
-void MetaInfoParser::parseFile(const QString &path)
-{
- QFile file;
- file.setFileName(path);
- if (!file.open(QIODevice::ReadOnly))
- throw new InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__);
-
- QXmlStreamReader reader;
- reader.setDevice(&file);
-
- while (!reader.atEnd()) {
- reader.readNext();
- tokenHandler(reader);
- }
- errorHandling(reader, file);
-}
-
-void MetaInfoParser::tokenHandler(QXmlStreamReader &reader)
-{
- if (reader.isStartElement() && reader.name() == "metainfo")
- handleMetaInfoElement(reader);
-}
-
-void MetaInfoParser::handleMetaInfoElement(QXmlStreamReader &reader)
-{
- while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "metainfo")) {
- reader.readNext();
- metaInfoHandler(reader);
- }
-}
-
-void MetaInfoParser::metaInfoHandler(QXmlStreamReader &reader)
-{
- if (reader.isStartElement())
- {
- if (reader.name() == "node")
- handleNodeElement(reader);
- }
-}
-
-void MetaInfoParser::handleNodeElement(QXmlStreamReader &reader)
-{
- const QXmlStreamAttributes attributes = reader.attributes();
-
- const QString className = attributes.value("name").toString();
- const QIcon icon = QIcon(attributes.value("icon").toString());
-
- if (className.isEmpty()) {
- reader.raiseError("Invalid element 'node' - mandatory attribute 'name' is missing");
- return;
- }
-
- while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "node")) {
- reader.readNext();
-
- handleNodeItemLibraryEntryElement(reader, className, icon);
- }
-}
-
-void MetaInfoParser::handleNodeItemLibraryEntryElement(QXmlStreamReader &reader, const QString &className, const QIcon &icon)
-{
- if (reader.isStartElement() && reader.name() == "itemlibraryentry")
- {
- const QString versionNumber = reader.attributes().value("version").toString();
-
- int major = 1;
- int minor = 0;
-
- if (!versionNumber.isEmpty()) {
- int val;
- bool ok;
- if (versionNumber.contains('.')) {
- val = versionNumber.split('.').first().toInt(&ok);
- major = ok ? val : major;
- val = versionNumber.split('.').last().toInt(&ok);
- minor = ok ? val : minor;
- } else {
- val = versionNumber.toInt(&ok);
- major = ok ? val : major;
- }
- }
-
- const QString name = reader.attributes().value("name").toString();
-
- ItemLibraryEntry entry;
- entry.setType(className, major, minor);
- entry.setName(name);
- entry.setIcon(icon);
-
- QString iconPath = reader.attributes().value("libraryIcon").toString();
- if (!iconPath.isEmpty())
- entry.setIconPath(iconPath);
-
- QString category = reader.attributes().value("category").toString();
- if (!category.isEmpty())
- entry.setCategory(category);
-
- QString requiredImport = reader.attributes().value("requiredImport").toString();
- if (!requiredImport.isEmpty())
- entry.setRequiredImport(requiredImport);
-
- if (reader.attributes().hasAttribute("forceImport")) {
- QString forceImport = reader.attributes().value("forceImport").toString();
- if (forceImport == QLatin1String("true") || forceImport == QLatin1String("True"))
- entry.setForceImport(true);
- else
- entry.setForceImport(false);
- } else {
- entry.setForceImport(false);
- }
-
- while (!reader.atEnd() && !(reader.isEndElement() && reader.name() == "itemlibraryentry")) {
- reader.readNext();
- handleItemLibraryEntryPropertyElement(reader, entry);
- handleItemLibraryEntryQmlElement(reader, entry);
- }
-
- m_metaInfo.itemLibraryInfo()->addEntry(entry);
- }
-}
-
-void MetaInfoParser::handleItemLibraryEntryPropertyElement(QXmlStreamReader &reader, ItemLibraryEntry &itemLibraryEntry)
-{
- if (reader.isStartElement() && reader.name() == "property")
- {
- QXmlStreamAttributes attributes(reader.attributes());
- QString name = attributes.value("name").toString();
- QString type = attributes.value("type").toString();
- QString value = attributes.value("value").toString();
- itemLibraryEntry.addProperty(name, type, value);
-
- reader.readNext();
- }
-}
-
-void MetaInfoParser::handleItemLibraryEntryQmlElement(QXmlStreamReader &reader, ItemLibraryEntry &itemLibraryEntry)
-{
- if (reader.isStartElement() && reader.name() == "qml")
- {
- QXmlStreamAttributes attributes(reader.attributes());
- QString source = attributes.value("source").toString();
- itemLibraryEntry.setQml(source);
-
- reader.readNext();
- }
-}
-
-void MetaInfoParser::errorHandling(QXmlStreamReader &reader, QFile &file)
-{
- if (!reader.hasError())
- return;
-
- qDebug() << QString("Error at %1, %2:%3: %4")
- .arg(file.fileName())
- .arg(reader.lineNumber())
- .arg(reader.columnNumber())
- .arg(reader.errorString());
-
- file.reset();
-
- QString fileString = file.readAll();
- QString snippetString;
- int lineCount = 0;
- int position = reader.characterOffset();
- while (position >= 0)
- {
- if (fileString[position] == '\n') {
- if (lineCount > 3)
- break;
- lineCount++;
- }
-
- snippetString.prepend(fileString[position]);
- position--;
- }
-
- lineCount = 0;
- position = reader.characterOffset();
- while (position >= 0)
- {
- position++;
- if (fileString[position] == '\n') {
- if (lineCount > 1)
- break;
- lineCount++;
- }
-
- snippetString.append(fileString[position]);
- }
-
- qDebug() << snippetString;
-
-}
-
-
-}
-}
diff --git a/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
new file mode 100644
index 0000000000..df95d540ad
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/metainfo/metainforeader.cpp
@@ -0,0 +1,335 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "metainforeader.h"
+#include "metainfo.h"
+
+#include <propertyparser.h>
+#include <QXmlStreamReader>
+#include <QString>
+#include <QFile>
+#include <QFileInfo>
+#include <QDebug>
+#include <QIcon>
+
+namespace QmlDesigner {
+namespace Internal {
+
+enum {
+ debug = false
+};
+
+const char rootElementName[] = "MetaInfo";
+const char typeElementName[] = "Type";
+const char ItemLibraryEntryElementName[] = "ItemLibraryEntry";
+const char QmlSourceElementName[] = "QmlSource";
+const char PropertyElementName[] = "Property";
+
+MetaInfoReader::MetaInfoReader(const MetaInfo &metaInfo)
+ : m_parserState(Undefined),
+ m_metaInfo(metaInfo)
+{
+ m_overwriteDuplicates = false;
+}
+
+void MetaInfoReader::readMetaInfoFile(const QString &path, bool overwriteDuplicates)
+{
+ m_documentPath = path;
+ m_overwriteDuplicates = overwriteDuplicates;
+ m_parserState = ParsingDocument;
+ if (!SimpleAbstractStreamReader::readFile(path)) {
+ qWarning() << "readMetaInfoFile()" << path;
+ qWarning() << errors();
+ m_parserState = Error;
+ throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__);
+ }
+
+ if (!errors().isEmpty()) {
+ qWarning() << "readMetaInfoFile()" << path;
+ qWarning() << errors();
+ m_parserState = Error;
+ throw InvalidMetaInfoException(__LINE__, __FUNCTION__, __FILE__);
+ }
+}
+
+QStringList MetaInfoReader::errors()
+{
+ return QmlJS::SimpleAbstractStreamReader::errors();
+}
+
+void MetaInfoReader::setQualifcation(const QString &qualification)
+{
+ m_qualication = qualification;
+}
+
+void MetaInfoReader::elementStart(const QString &name)
+{
+ switch (parserState()) {
+ case ParsingDocument: setParserState(readDocument(name)); break;
+ case ParsingMetaInfo: setParserState(readMetaInfoRootElement(name)); break;
+ case ParsingType: setParserState(readTypeElement(name)); break;
+ case ParsingItemLibrary: setParserState(readItemLibraryEntryElement(name)); break;
+ case ParsingProperty: setParserState(readPropertyElement(name)); break;
+ case ParsingQmlSource: setParserState(readQmlSourceElement(name)); break;
+ case Finished:
+ case Undefined: setParserState(Error);
+ addError(tr("Illegal state while parsing"), currentSourceLocation());
+ case Error:
+ default: return;
+ }
+}
+
+void MetaInfoReader::elementEnd()
+{
+ switch (parserState()) {
+ case ParsingMetaInfo: setParserState(Finished); break;
+ case ParsingType: setParserState(ParsingMetaInfo); break;
+ case ParsingItemLibrary: insertItemLibraryEntry(); setParserState((ParsingType)); break;
+ case ParsingProperty: insertProperty(); setParserState(ParsingItemLibrary); break;
+ case ParsingQmlSource: setParserState(ParsingItemLibrary); break;
+ case ParsingDocument:
+ case Finished:
+ case Undefined: setParserState(Error);
+ addError(tr("Illegal state while parsing"), currentSourceLocation());
+ case Error:
+ default: return;
+ }
+}
+
+void MetaInfoReader::propertyDefinition(const QString &name, const QVariant &value)
+{
+ switch (parserState()) {
+ case ParsingType: readTypeProperty(name, value); break;
+ case ParsingItemLibrary: readItemLibraryEntryProperty(name, value); break;
+ case ParsingProperty: readPropertyProperty(name, value); break;
+ case ParsingQmlSource: readQmlSourceProperty(name, value); break;
+ case ParsingMetaInfo: addError(tr("No property definition allowed"), currentSourceLocation()); break;
+ case ParsingDocument:
+ case Finished:
+ case Undefined: setParserState(Error);
+ addError(tr("Illegal state while parsing"), currentSourceLocation());
+ case Error:
+ default: return;
+ }
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::readDocument(const QString &name)
+{
+ if (name == QLatin1String(rootElementName)) {
+ m_currentClassName = QString();
+ m_currentIcon = QString();
+ return ParsingMetaInfo;
+ } else {
+ addErrorInvalidType(name);
+ return Error;
+ }
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::readMetaInfoRootElement(const QString &name)
+{
+ if (name == QLatin1String(typeElementName)) {
+ m_currentClassName = QString();
+ m_currentIcon = QString();
+ return ParsingType;
+ } else {
+ addErrorInvalidType(name);
+ return Error;
+ }
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::readTypeElement(const QString &name)
+{
+ if (name == QLatin1String(ItemLibraryEntryElementName)) {
+ m_currentEntry = ItemLibraryEntry();
+ m_currentEntry.setForceImport(false);
+ m_currentEntry.setType(m_currentClassName, -1, -1);
+ m_currentEntry.setIcon(QIcon(m_currentIcon));
+ return ParsingItemLibrary;
+ } else {
+ addErrorInvalidType(name);
+ return Error;
+ }
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::readItemLibraryEntryElement(const QString &name)
+{
+ if (name == QmlSourceElementName) {
+ return ParsingQmlSource;
+ } else if (name == PropertyElementName) {
+ m_currentPropertyName = QString();
+ m_currentPropertyType = QString();
+ m_currentPropertyValue = QVariant();
+ return ParsingProperty;
+ } else {
+ addError(tr("Invalid type %1").arg(name), currentSourceLocation());
+ return Error;
+ }
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::readPropertyElement(const QString &name)
+{
+ addError(tr("Invalid type %1").arg(name), currentSourceLocation());
+ return Error;
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::readQmlSourceElement(const QString &name)
+{
+ addError(tr("Invalid type %1").arg(name), currentSourceLocation());
+ return Error;
+}
+
+void MetaInfoReader::readTypeProperty(const QString &name, const QVariant &value)
+{
+ if (name == QLatin1String("name")) {
+ m_currentClassName = value.toString();
+ if (!m_qualication.isEmpty()) //prepend qualification
+ m_currentClassName = m_qualication + QLatin1String(".") + m_currentClassName;
+ } else if (name == QLatin1String("icon")) {
+ m_currentIcon = absoluteFilePathForDocument(value.toString());
+ } else {
+ addError(tr("Unknown property for Type %1").arg(name), currentSourceLocation());
+ setParserState(Error);
+ }
+}
+
+void MetaInfoReader::readItemLibraryEntryProperty(const QString &name, const QVariant &value)
+{
+ if (name == QLatin1String("name")) {
+ m_currentEntry.setName(value.toString());
+ } else if (name == QLatin1String("category")) {
+ m_currentEntry.setCategory(value.toString());
+ } else if (name == QLatin1String("libraryIcon")) {
+ m_currentEntry.setIconPath(absoluteFilePathForDocument(value.toString()));
+ } else if (name == QLatin1String("version")) {
+ setVersion(value.toString());
+ } else if (name == QLatin1String("requiredImport")) {
+ m_currentEntry.setRequiredImport(value.toString());
+ } else if (name == QLatin1String("forceImport")) {
+ m_currentEntry.setForceImport(value.toBool());
+ } else {
+ addError(tr("Unknown property for ItemLibraryEntry %1").arg(name), currentSourceLocation());
+ setParserState(Error);
+ }
+}
+
+void MetaInfoReader::readPropertyProperty(const QString &name, const QVariant &value)
+{
+ if (name == QLatin1String("name")) {
+ m_currentPropertyName = value.toString();
+ } else if (name == QLatin1String("type")) {
+ m_currentPropertyType = value.toString();
+ } else if (name == QLatin1String("value")) {
+ m_currentPropertyValue = value;
+ } else {
+ addError(tr("Unknown property for Property %1").arg(name), currentSourceLocation());
+ setParserState(Error);
+ }
+}
+
+void MetaInfoReader::readQmlSourceProperty(const QString &name, const QVariant &value)
+{
+ if (name == QLatin1String("source")) {
+ m_currentEntry.setQml(value.toString());
+ } else {
+ addError(tr("Unknown property for QmlSource %1").arg(name), currentSourceLocation());
+ setParserState(Error);
+ }
+}
+
+void MetaInfoReader::setVersion(const QString &versionNumber)
+{
+ const QString typeName = m_currentEntry.typeName();
+ int major = 1;
+ int minor = 0;
+
+ if (!versionNumber.isEmpty()) {
+ int val;
+ bool ok;
+ if (versionNumber.contains('.')) {
+ val = versionNumber.split('.').first().toInt(&ok);
+ major = ok ? val : major;
+ val = versionNumber.split('.').last().toInt(&ok);
+ minor = ok ? val : minor;
+ } else {
+ val = versionNumber.toInt(&ok);
+ major = ok ? val : major;
+ }
+ }
+ m_currentEntry.setType(typeName, major, minor);
+}
+
+MetaInfoReader::ParserSate MetaInfoReader::parserState() const
+{
+ return m_parserState;
+}
+
+void MetaInfoReader::setParserState(ParserSate newParserState)
+{
+ if (debug && newParserState == Error)
+ qDebug() << "Error";
+
+ m_parserState = newParserState;
+}
+
+void MetaInfoReader::insertItemLibraryEntry()
+{
+ if (debug) {
+ qDebug() << "insertItemLibraryEntry()";
+ qDebug() << m_currentEntry;
+ }
+
+ try {
+ m_metaInfo.itemLibraryInfo()->addEntry(m_currentEntry, m_overwriteDuplicates);
+ } catch (InvalidMetaInfoException &) {
+ addError(tr("Invalid or duplicate item library entry %1").arg(m_currentEntry.name()), currentSourceLocation());
+ }
+}
+
+void MetaInfoReader::insertProperty()
+{
+ m_currentEntry.addProperty(m_currentPropertyName, m_currentPropertyType, m_currentPropertyValue);
+}
+
+void MetaInfoReader::addErrorInvalidType(const QString &typeName)
+{
+ addError(tr("Invalid type %1").arg(typeName), currentSourceLocation());
+}
+
+QString MetaInfoReader::absoluteFilePathForDocument(const QString &relativeFilePath)
+{
+
+ QFileInfo fileInfo(relativeFilePath);
+ if (fileInfo.isAbsolute() && fileInfo.exists())
+ return relativeFilePath;
+
+ return QFileInfo(QFileInfo(m_documentPath).absolutePath() + QLatin1String("/") + relativeFilePath).absoluteFilePath();
+}
+
+} //Internal
+} //QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp b/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp
index 735bb8f5d0..1609b0a28f 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/nodemetainfo.cpp
@@ -29,7 +29,6 @@
#include "nodemetainfo.h"
#include "model.h"
-#include "widgetqueryview.h"
#include "invalidargumentexception.h"
#include "metainfo.h"
@@ -40,9 +39,6 @@
#include <QSharedData>
#include <QDebug>
#include <QIcon>
-#include <QDeclarativeContext>
-#include <QDeclarativeEngine>
-#include <QDeclarativeComponent>
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljscontext.h>
@@ -87,17 +83,66 @@ using namespace QmlJS;
typedef QPair<QString, QString> PropertyInfo;
+QList<PropertyInfo> getObjectTypes(const ObjectValue *ov, const ContextPtr &context, bool local = false);
+
+static QString resolveTypeName(const ASTPropertyReference *ref, const ContextPtr &context, QList<PropertyInfo> &dotProperties)
+{
+ QString type = QLatin1String("unknown");
+
+ if (!ref->ast()->memberType.isEmpty()) {
+ type = ref->ast()->memberType.toString();
+
+ if (type == QLatin1String("alias")) {
+ const Value *value = context->lookupReference(ref);
+
+ if (!value)
+ return type;
+
+ if (const ASTObjectValue * astObjectValue = value->asAstObjectValue()) {
+ if (astObjectValue->typeName())
+ type = astObjectValue->typeName()->name.toString();
+ } else if (const ObjectValue * objectValue = value->asObjectValue()) {
+ type = objectValue->className();
+ dotProperties = getObjectTypes(objectValue, context);
+ } else if (value->asColorValue()) {
+ type = QLatin1String("color");
+ } else if (value->asUrlValue()) {
+ type = QLatin1String("url");
+ } else if (value->asStringValue()) {
+ type = QLatin1String("string");
+ } else if (value->asRealValue()) {
+ type = QLatin1String("real");
+ } else if (value->asIntValue()) {
+ type = QLatin1String("int");
+ } else if (value->asBooleanValue()) {
+ type = QLatin1String("boolean");
+ }
+ }
+ }
+
+ return type;
+}
+
class PropertyMemberProcessor : public MemberProcessor
{
public:
+ PropertyMemberProcessor(const ContextPtr &context) : m_context(context)
+ {}
virtual bool processProperty(const QString &name, const Value *value)
{
const ASTPropertyReference *ref = value_cast<ASTPropertyReference>(value);
if (ref) {
- QString type = "unknown";
- if (!ref->ast()->memberType.isEmpty())
- type = ref->ast()->memberType.toString();
+ QList<PropertyInfo> dotProperties;
+ const QString type = resolveTypeName(ref, m_context, dotProperties);
m_properties.append(qMakePair(name, type));
+ if (!dotProperties.isEmpty()) {
+ foreach (const PropertyInfo &propertyInfo, dotProperties) {
+ QString dotName = propertyInfo.first;
+ QString type = propertyInfo.second;
+ dotName = name + '.' + dotName;
+ m_properties.append(qMakePair(dotName, type));
+ }
+ }
} else {
if (const CppComponentValue * ov = value_cast<CppComponentValue>(value)) {
QString qualifiedTypeName = ov->moduleName().isEmpty() ? ov->className() : ov->moduleName() + '.' + ov->className();
@@ -106,11 +151,10 @@ public:
TypeId typeId;
QString typeName = typeId(value);
if (typeName == QLatin1String("number")) {
- if (value->asRealValue()) {
+ if (value->asRealValue())
typeName = "real";
- } else {
- typeName = "int";
- }
+ else
+ typeName = "int";
}
m_properties.append(qMakePair(name, typeName));
}
@@ -122,6 +166,7 @@ public:
private:
QList<PropertyInfo> m_properties;
+ const ContextPtr m_context;
};
static inline bool isValueType(const QString &type)
@@ -160,19 +205,16 @@ QStringList prototypes(const ObjectValue *ov, const ContextPtr &context, bool ve
list << qmlValue->moduleName() + QLatin1Char('.') + qmlValue->className();
}
} else {
- if (versions) {
+ if (versions)
list << ov->className() + " -1.-1";
- } else {
+ else
list << ov->className();
- }
}
ov = ov->prototype(context);
}
return list;
}
-QList<PropertyInfo> getObjectTypes(const ObjectValue *ov, const ContextPtr &context, bool local = false);
-
QList<PropertyInfo> getQmlTypes(const CppComponentValue *ov, const ContextPtr &context, bool local = false)
{
QList<PropertyInfo> list;
@@ -181,7 +223,7 @@ QList<PropertyInfo> getQmlTypes(const CppComponentValue *ov, const ContextPtr &c
if (ov->className().isEmpty())
return list;
- PropertyMemberProcessor processor;
+ PropertyMemberProcessor processor(context);
ov->processMembers(&processor);
QList<PropertyInfo> newList = processor.properties();
@@ -224,11 +266,10 @@ QList<PropertyInfo> getQmlTypes(const CppComponentValue *ov, const ContextPtr &c
const CppComponentValue * qmlObjectValue = value_cast<CppComponentValue>(prototype);
- if (qmlObjectValue) {
+ if (qmlObjectValue)
list << getQmlTypes(qmlObjectValue, context);
- } else {
+ else
list << getObjectTypes(prototype, context);
- }
}
return list;
@@ -240,11 +281,10 @@ QList<PropertyInfo> getTypes(const ObjectValue *ov, const ContextPtr &context, b
const CppComponentValue * qmlObjectValue = value_cast<CppComponentValue>(ov);
- if (qmlObjectValue) {
+ if (qmlObjectValue)
list << getQmlTypes(qmlObjectValue, context, local);
- } else {
+ else
list << getObjectTypes(ov, context, local);
- }
return list;
}
@@ -257,7 +297,7 @@ QList<PropertyInfo> getObjectTypes(const ObjectValue *ov, const ContextPtr &cont
if (ov->className().isEmpty())
return list;
- PropertyMemberProcessor processor;
+ PropertyMemberProcessor processor(context);
ov->processMembers(&processor);
list << processor.properties();
@@ -270,11 +310,10 @@ QList<PropertyInfo> getObjectTypes(const ObjectValue *ov, const ContextPtr &cont
const CppComponentValue * qmlObjectValue = value_cast<CppComponentValue>(prototype);
- if (qmlObjectValue) {
+ if (qmlObjectValue)
list << getQmlTypes(qmlObjectValue, context);
- } else {
+ else
list << getObjectTypes(prototype, context);
- }
}
return list;
@@ -288,29 +327,10 @@ public:
~NodeMetaInfoPrivate() {}
bool isValid() const;
-
- bool isComponent() const
- {
- return m_isComponent;
- }
-
- QStringList properties() const
- {
- return m_properties;
- }
-
- QStringList localProperties() const
- {
- return m_localProperties;
- }
-
- QString defaultPropertyName() const
- {
- if (!m_defaultPropertyName.isEmpty())
- return m_defaultPropertyName;
- return QLatin1String("data");
- }
-
+ bool isFileComponent() const;
+ QStringList properties() const;
+ QStringList localProperties() const;
+ QString defaultPropertyName() const;
QString propertyType(const QString &propertyName) const;
void setupPrototypes();
@@ -325,39 +345,24 @@ public:
bool cleverCheckType(const QString &otherType) const;
QVariant::Type variantTypeId(const QString &properyName) const;
- int majorVersion() const
- { return m_majorVersion; }
+ int majorVersion() const;
+ int minorVersion() const;
+ QString qualfiedTypeName() const;
+ Model *model() const;
- int minorVersion() const
- { return m_minorVersion; }
-
- QString qualfiedTypeName() const
- { return m_qualfiedTypeName; }
-
- Model *model() const
- { return m_model; }
-
- QString packageName() const;
+ QString cppPackageName() const;
QString componentSource() const;
QString componentFileName() const;
+ QString importDirectoryPath() const;
static Pointer create(Model *model, const QString &type, int maj = -1, int min = -1);
- QSet<QString> &prototypeCachePositives()
- {
- return m_prototypeCachePositives;
- }
+ QSet<QString> &prototypeCachePositives();
+ QSet<QString> &prototypeCacheNegatives();
- QSet<QString> &prototypeCacheNegatives()
- {
- return m_prototypeCacheNegatives;
- }
+ static void clearCache();
- static void clearCache()
- {
- m_nodeMetaInfoCache.clear();
- }
private:
NodeMetaInfoPrivate(Model *model, QString type, int maj = -1, int min = -1);
@@ -375,7 +380,7 @@ private:
int m_majorVersion;
int m_minorVersion;
bool m_isValid;
- bool m_isComponent;
+ bool m_isFileComponent;
QStringList m_properties;
QStringList m_propertyTypes;
QStringList m_localProperties;
@@ -394,6 +399,42 @@ private:
QHash<QString, NodeMetaInfoPrivate::Pointer> NodeMetaInfoPrivate::m_nodeMetaInfoCache;
+bool NodeMetaInfoPrivate::isFileComponent() const
+{
+ return m_isFileComponent;
+}
+
+QStringList NodeMetaInfoPrivate::properties() const
+{
+ return m_properties;
+}
+
+QStringList NodeMetaInfoPrivate::localProperties() const
+{
+ return m_localProperties;
+}
+
+QSet<QString> &NodeMetaInfoPrivate::prototypeCachePositives()
+{
+ return m_prototypeCachePositives;
+}
+
+QSet<QString> &NodeMetaInfoPrivate::prototypeCacheNegatives()
+{
+ return m_prototypeCacheNegatives;
+}
+
+void NodeMetaInfoPrivate::clearCache()
+{
+ m_nodeMetaInfoCache.clear();
+}
+
+QString NodeMetaInfoPrivate::defaultPropertyName() const
+{
+ if (!m_defaultPropertyName.isEmpty())
+ return m_defaultPropertyName;
+ return QLatin1String("data");
+}
static inline QString stringIdentifier( const QString &type, int maj, int min)
{
@@ -404,11 +445,10 @@ NodeMetaInfoPrivate::Pointer NodeMetaInfoPrivate::create(Model *model, const QSt
{
if (m_nodeMetaInfoCache.contains(stringIdentifier(type, maj, min))) {
const Pointer &info = m_nodeMetaInfoCache.value(stringIdentifier(type, maj, min));
- if (info->model() == model) {
+ if (info->model() == model)
return info;
- } else {
+ else
m_nodeMetaInfoCache.clear();
- }
}
Pointer newData(new NodeMetaInfoPrivate(model, type, maj, min));
@@ -424,12 +464,16 @@ NodeMetaInfoPrivate::NodeMetaInfoPrivate() : m_isValid(false)
NodeMetaInfoPrivate::NodeMetaInfoPrivate(Model *model, QString type, int maj, int min) :
m_qualfiedTypeName(type), m_majorVersion(maj),
- m_minorVersion(min), m_isValid(false), m_isComponent(false),
+ m_minorVersion(min), m_isValid(false), m_isFileComponent(false),
m_model(model)
{
if (context()) {
const CppComponentValue *objectValue = getCppComponentValue();
if (objectValue) {
+ if (m_majorVersion == -1 && m_minorVersion == -1) {
+ m_majorVersion = objectValue->componentVersion().majorVersion();
+ m_minorVersion = objectValue->componentVersion().minorVersion();
+ }
setupPropertyInfo(getTypes(objectValue, context()));
setupLocalPropertyInfo(getTypes(objectValue, context(), true));
m_defaultPropertyName = objectValue->defaultPropertyName();
@@ -440,11 +484,17 @@ NodeMetaInfoPrivate::NodeMetaInfoPrivate(Model *model, QString type, int maj, in
if (objectValue) {
const CppComponentValue *qmlValue = value_cast<CppComponentValue>(objectValue);
if (qmlValue) {
- m_majorVersion = qmlValue->componentVersion().majorVersion();
- m_minorVersion = qmlValue->componentVersion().minorVersion();
- m_qualfiedTypeName = qmlValue->moduleName() + '.' + qmlValue->className();
+ if (m_majorVersion == -1 && m_minorVersion == -1) {
+ m_majorVersion = qmlValue->componentVersion().majorVersion();
+ m_minorVersion = qmlValue->componentVersion().minorVersion();
+ m_qualfiedTypeName = qmlValue->moduleName() + '.' + qmlValue->className();
+ } else if (m_majorVersion == qmlValue->componentVersion().majorVersion() && m_minorVersion == qmlValue->componentVersion().minorVersion()) {
+ m_qualfiedTypeName = qmlValue->moduleName() + '.' + qmlValue->className();
+ } else {
+ return;
+ }
} else {
- m_isComponent = true;
+ m_isFileComponent = true;
}
setupPropertyInfo(getTypes(objectValue, context()));
setupLocalPropertyInfo(getTypes(objectValue, context(), true));
@@ -480,8 +530,12 @@ const QmlJS::CppComponentValue *NodeMetaInfoPrivate::getCppComponentValue() cons
if (import.info.path() != module)
continue;
const Value *lookupResult = import.object->lookupMember(type, context());
- if ((value = value_cast<CppComponentValue>(lookupResult)))
- return value;
+ const CppComponentValue *cppValue = value_cast<CppComponentValue>(lookupResult);
+ if (cppValue
+ && (m_majorVersion == -1 || m_majorVersion == cppValue->componentVersion().majorVersion())
+ && (m_minorVersion == -1 || m_minorVersion == cppValue->componentVersion().minorVersion())
+ )
+ return cppValue;
}
return 0;
@@ -494,17 +548,15 @@ const QmlJS::ObjectValue *NodeMetaInfoPrivate::getObjectValue() const
QmlJS::ContextPtr NodeMetaInfoPrivate::context() const
{
- if (m_model && m_model->rewriterView() && m_model->rewriterView()->scopeChain()) {
+ if (m_model && m_model->rewriterView() && m_model->rewriterView()->scopeChain())
return m_model->rewriterView()->scopeChain()->context();
- }
return QmlJS::ContextPtr(0);
}
const QmlJS::Document *NodeMetaInfoPrivate::document() const
{
- if (m_model && m_model->rewriterView()) {
+ if (m_model && m_model->rewriterView())
return m_model->rewriterView()->document();
- }
return 0;
}
@@ -534,9 +586,8 @@ bool NodeMetaInfoPrivate::isPropertyWritable(const QString &propertyName) const
const QString rawPropertyName = parts.last();
const QString objectType = propertyType(objectName);
- if (isValueType(objectType)) {
+ if (isValueType(objectType))
return true;
- }
QSharedPointer<NodeMetaInfoPrivate> objectInfo(create(m_model, objectType));
if (objectInfo->isValid())
@@ -566,9 +617,8 @@ bool NodeMetaInfoPrivate::isPropertyList(const QString &propertyName) const
const QString rawPropertyName = parts.last();
const QString objectType = propertyType(objectName);
- if (isValueType(objectType)) {
+ if (isValueType(objectType))
return false;
- }
QSharedPointer<NodeMetaInfoPrivate> objectInfo(create(m_model, objectType));
if (objectInfo->isValid())
@@ -594,9 +644,8 @@ bool NodeMetaInfoPrivate::isPropertyPointer(const QString &propertyName) const
const QString rawPropertyName = parts.last();
const QString objectType = propertyType(objectName);
- if (isValueType(objectType)) {
+ if (isValueType(objectType))
return false;
- }
QSharedPointer<NodeMetaInfoPrivate> objectInfo(create(m_model, objectType));
if (objectInfo->isValid())
@@ -622,9 +671,8 @@ bool NodeMetaInfoPrivate::isPropertyEnum(const QString &propertyName) const
const QString rawPropertyName = parts.last();
const QString objectType = propertyType(objectName);
- if (isValueType(objectType)) {
+ if (isValueType(objectType))
return false;
- }
QSharedPointer<NodeMetaInfoPrivate> objectInfo(create(m_model, objectType));
if (objectInfo->isValid())
@@ -650,9 +698,8 @@ QString NodeMetaInfoPrivate::propertyEnumScope(const QString &propertyName) cons
const QString rawPropertyName = parts.last();
const QString objectType = propertyType(objectName);
- if (isValueType(objectType)) {
+ if (isValueType(objectType))
return QString();
- }
QSharedPointer<NodeMetaInfoPrivate> objectInfo(create(m_model, objectType));
if (objectInfo->isValid())
@@ -672,12 +719,20 @@ QString NodeMetaInfoPrivate::propertyEnumScope(const QString &propertyName) cons
return QString();
}
+static QString getUnqualifiedName(const QString &name)
+{
+ const QStringList nameComponents = name.split('.');
+ if (nameComponents.size() < 2)
+ return QString();
+ return nameComponents.last();
+}
+
bool NodeMetaInfoPrivate::cleverCheckType(const QString &otherType) const
{
if (otherType == qualfiedTypeName())
return true;
- if (isComponent())
+ if (isFileComponent())
return false;
QStringList split = otherType.split('.');
@@ -687,8 +742,8 @@ bool NodeMetaInfoPrivate::cleverCheckType(const QString &otherType) const
package = split.first();
typeName = split.at(1);
}
- if (packageName() == package)
- return QString(package + '.' + typeName) == qualfiedTypeName();
+ if (cppPackageName() == package)
+ return QString(package + '.' + typeName) == cppPackageName() + '.' + getUnqualifiedName(qualfiedTypeName());
const CppComponentValue *qmlObjectValue = getCppComponentValue();
if (!qmlObjectValue)
@@ -739,6 +794,26 @@ QVariant::Type NodeMetaInfoPrivate::variantTypeId(const QString &properyName) co
return QVariant::nameToType(typeName.toLatin1().data());
}
+int NodeMetaInfoPrivate::majorVersion() const
+{
+ return m_majorVersion;
+}
+
+int NodeMetaInfoPrivate::minorVersion() const
+{
+ return m_minorVersion;
+}
+
+QString NodeMetaInfoPrivate::qualfiedTypeName() const
+{
+ return m_qualfiedTypeName;
+}
+
+Model *NodeMetaInfoPrivate::model() const
+{
+ return m_model;
+}
+
QStringList NodeMetaInfoPrivate::keysForEnum(const QString &enumName) const
{
@@ -751,9 +826,9 @@ QStringList NodeMetaInfoPrivate::keysForEnum(const QString &enumName) const
return qmlObjectValue->getEnum(enumName).keys();
}
-QString NodeMetaInfoPrivate::packageName() const
+QString NodeMetaInfoPrivate::cppPackageName() const
{
- if (!isComponent()) {
+ if (!isFileComponent()) {
if (const CppComponentValue *qmlObject = getCppComponentValue())
return qmlObject->moduleName();
}
@@ -762,7 +837,7 @@ QString NodeMetaInfoPrivate::packageName() const
QString NodeMetaInfoPrivate::componentSource() const
{
- if (isComponent()) {
+ if (isFileComponent()) {
const ASTObjectValue * astObjectValue = value_cast<ASTObjectValue>(getObjectValue());
if (astObjectValue)
return astObjectValue->document()->source().mid(astObjectValue->typeName()->identifierToken.begin(),
@@ -773,7 +848,7 @@ QString NodeMetaInfoPrivate::componentSource() const
QString NodeMetaInfoPrivate::componentFileName() const
{
- if (isComponent()) {
+ if (isFileComponent()) {
const ASTObjectValue * astObjectValue = value_cast<ASTObjectValue>(getObjectValue());
if (astObjectValue) {
QString fileName;
@@ -786,6 +861,16 @@ QString NodeMetaInfoPrivate::componentFileName() const
return QString();
}
+QString NodeMetaInfoPrivate::importDirectoryPath() const
+{
+ if (isValid()) {
+ const Imports *imports = context()->imports(document());
+ ImportInfo importInfo = imports->info(qualfiedTypeName(), context().data());
+
+ return importInfo.path();
+ }
+ return QString();
+}
QString NodeMetaInfoPrivate::lookupName() const
{
@@ -819,14 +904,14 @@ bool NodeMetaInfoPrivate::isValid() const
QString NodeMetaInfoPrivate::propertyType(const QString &propertyName) const
{
if (!m_properties.contains(propertyName))
- return QString();
+ return QLatin1String("Property does not exist...");
return m_propertyTypes.at(m_properties.indexOf(propertyName));
}
void NodeMetaInfoPrivate::setupPrototypes()
{
QList<const ObjectValue *> objects;
- if (m_isComponent)
+ if (m_isFileComponent)
objects = PrototypeIterator(getObjectValue(), context()).all();
else
objects = PrototypeIterator(getCppComponentValue(), context()).all();
@@ -841,13 +926,12 @@ void NodeMetaInfoPrivate::setupPrototypes()
description.majorVersion = qmlValue->componentVersion().majorVersion();
LanguageUtils::FakeMetaObject::Export qtquickExport = qmlValue->metaObject()->exportInPackage("QtQuick");
LanguageUtils::FakeMetaObject::Export cppExport = qmlValue->metaObject()->exportInPackage("<cpp>");
- if (qtquickExport.isValid()) {
+ if (qtquickExport.isValid())
description.className = qtquickExport.package + '.' + qtquickExport.type;
- } else if (qmlValue->moduleName().isEmpty() && cppExport.isValid()) {
+ else if (qmlValue->moduleName().isEmpty() && cppExport.isValid())
description.className = cppExport.package + '.' + cppExport.type;
- } else if (!qmlValue->moduleName().isEmpty()) {
+ else if (!qmlValue->moduleName().isEmpty())
description.className = qmlValue->moduleName() + '.' + description.className;
- }
m_prototypes.append(description);
} else {
if (context()->lookupType(document(), QStringList() << ov->className()))
@@ -864,7 +948,7 @@ QList<TypeDescription> NodeMetaInfoPrivate::prototypes() const
const QmlJS::CppComponentValue *NodeMetaInfoPrivate::getNearestCppComponentValue() const
{
- if (m_isComponent)
+ if (m_isFileComponent)
return findQmlPrototype(getObjectValue(), context());
return getCppComponentValue();
}
@@ -910,9 +994,9 @@ bool NodeMetaInfo::isValid() const
return m_privateData->isValid();
}
-bool NodeMetaInfo::isComponent() const
+bool NodeMetaInfo::isFileComponent() const
{
- return m_privateData->isComponent();
+ return m_privateData->isFileComponent();
}
bool NodeMetaInfo::hasProperty(const QString &propertyName) const
@@ -974,9 +1058,8 @@ QVariant NodeMetaInfo::propertyCastedValue(const QString &propertyName, const QV
{
QVariant variant = value;
- if (propertyIsEnumType(propertyName)) {
+ if (propertyIsEnumType(propertyName))
return variant;
- }
const QString typeName = propertyTypeName(propertyName);
@@ -1043,7 +1126,12 @@ QString NodeMetaInfo::componentSource() const
QString NodeMetaInfo::componentFileName() const
{
- return NodeMetaInfo::m_privateData->componentFileName();
+ return m_privateData->componentFileName();
+}
+
+QString NodeMetaInfo::importDirectoryPath() const
+{
+ return m_privateData->importDirectoryPath();
}
bool NodeMetaInfo::hasCustomParser() const
@@ -1096,4 +1184,11 @@ void NodeMetaInfo::clearCache()
Internal::NodeMetaInfoPrivate::clearCache();
}
+bool NodeMetaInfo::isPositioner() const
+{
+ if (majorVersion() < 2)
+ return isSubclassOf("<cpp>.QDeclarativeBasePositioner", -1, -1);
+ return isSubclassOf("QtQuick.Positioner", -1, -1);
+}
+
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp b/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
index 548c3a1379..2d4ca4c495 100644
--- a/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
+++ b/src/plugins/qmldesigner/designercore/metainfo/subcomponentmanager.cpp
@@ -27,14 +27,29 @@
**
****************************************************************************/
+#include <qmldesignerconstants.h>
+
#include "subcomponentmanager.h"
#include "model.h"
#include "metainfo.h"
+#include "metainforeader.h"
+
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QMetaType>
+#include <QMessageBox>
#include <QUrl>
+#include <qmljs/qmljsevaluate.h>
+#include <qmljs/qmljsinterpreter.h>
+#include <qmljs/qmljscontext.h>
+#include <qmljs/qmljslink.h>
+#include <qmljs/parser/qmljsast_p.h>
+#include <qmljs/qmljsscopebuilder.h>
+#include <qmljs/qmljsscopechain.h>
+#include <qmljs/qmljsmodelmanagerinterface.h>
+
enum { debug = false };
QT_BEGIN_NAMESPACE
@@ -55,17 +70,76 @@ static inline QStringList importPaths() {
// env import paths
QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");
if (!envImportPath.isEmpty()) {
-#if defined(Q_OS_WIN)
- QLatin1Char pathSep(';');
-#else
- QLatin1Char pathSep(':');
-#endif
- paths = QString::fromLatin1(envImportPath).split(pathSep, QString::SkipEmptyParts);
+ paths = QString::fromLatin1(envImportPath)
+ .split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts);
}
return paths;
}
+static inline bool checkIfDerivedFromItem(const QString &fileName)
+{
+ QmlJS::Snapshot snapshot;
+
+
+ QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
+ if (modelManager)
+ snapshot = modelManager->snapshot();
+
+ QFile file(fileName);
+ if (!file.open(QIODevice::ReadOnly))
+ return false;
+
+ QByteArray source = file.readAll();
+ file.close();
+
+ QmlJS::Document::MutablePtr document =
+ QmlJS::Document::create(fileName.isEmpty() ?
+ QLatin1String("<internal>") : fileName, QmlJS::Document::QmlLanguage);
+ document->setSource(source);
+ document->parseQml();
+
+
+ if (!document->isParsedCorrectly())
+ return false;
+
+ snapshot.insert(document);
+
+ QmlJS::Link link(snapshot, QStringList(), QmlJS::ModelManagerInterface::instance()->builtins(document));
+
+ QList<QmlJS::DiagnosticMessage> diagnosticLinkMessages;
+ QmlJS::ContextPtr context = link(document, &diagnosticLinkMessages);
+
+ QmlJS::AST::UiObjectMember *astRootNode = 0;
+ if (QmlJS::AST::UiProgram *program = document->qmlProgram())
+ if (program->members)
+ astRootNode = program->members->member;
+
+ QmlJS::AST::UiObjectDefinition *definition = QmlJS::AST::cast<QmlJS::AST::UiObjectDefinition *>(astRootNode);
+
+ if (!definition)
+ return false;
+
+ QString fullTypeName;
+ for (QmlJS::AST::UiQualifiedId *iter = definition->qualifiedTypeNameId; iter; iter = iter->next)
+ if (!iter->name.isEmpty())
+ fullTypeName += iter->name.toString() + QLatin1Char('.');
+
+ if (fullTypeName.endsWith(QLatin1Char('.')))
+ fullTypeName.chop(1);
+
+ const QmlJS::ObjectValue *objectValue = context->lookupType(document.data(), fullTypeName.split('.'));
+
+ QList<const QmlJS::ObjectValue *> prototypes = QmlJS::PrototypeIterator(objectValue, context).all();
+
+ foreach (const QmlJS::ObjectValue *prototype, prototypes) {
+ if (prototype->className() == "Item")
+ return true;
+ }
+
+ return false;
+}
+
namespace QmlDesigner {
static const QString s_qmlFilePattern = QString(QLatin1String("*.qml"));
@@ -79,7 +153,7 @@ SubComponentManager::SubComponentManager(Model *model, QObject *parent)
void SubComponentManager::addImport(int pos, const Import &import)
{
if (debug)
- qDebug() << Q_FUNC_INFO << pos << import.file().toAscii();
+ qDebug() << Q_FUNC_INFO << pos << import.file().toLatin1();
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
@@ -90,7 +164,7 @@ void SubComponentManager::addImport(int pos, const Import &import)
}
} else {
QString url = import.url();
-
+
url.replace(QLatin1Char('.'), QLatin1Char('/'));
foreach (const QString &path, importPaths()) {
@@ -137,14 +211,17 @@ void SubComponentManager::parseDirectories()
QFileInfo dirInfo = QFileInfo(QFileInfo(file).path());
if (dirInfo.exists() && dirInfo.isDir())
parseDirectory(dirInfo.canonicalFilePath());
+
+ foreach (const QString subDir, QDir(QFileInfo(file).path()).entryList(QDir::Dirs | QDir::NoDot | QDir::NoDotDot)) {
+ parseDirectory(dirInfo.canonicalFilePath() + "/" + subDir, true, subDir);
+ }
}
foreach (const Import &import, m_imports) {
if (import.isFileImport()) {
QFileInfo dirInfo = QFileInfo(m_filePath.resolved(import.file()).toLocalFile());
- if (dirInfo.exists() && dirInfo.isDir()) {
- parseDirectory(dirInfo.canonicalFilePath());
- }
+ if (dirInfo.exists() && dirInfo.isDir())
+ parseDirectory(dirInfo.canonicalFilePath(), true, dirInfo.baseName());
} else {
QString url = import.url();
foreach (const QString &path, importPaths()) {
@@ -162,6 +239,33 @@ void SubComponentManager::parseDirectories()
void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool addToLibrary, const QString& qualification)
{
+
+ QDir designerDir(canonicalDirPath + Constants::QML_DESIGNER_SUBFOLDER);
+ if (designerDir.exists()) {
+ QStringList filter;
+ filter << "*.metainfo";
+ designerDir.setNameFilters(filter);
+
+ QStringList metaFiles = designerDir.entryList(QDir::Files);
+ foreach (const QFileInfo &metaInfoFile, designerDir.entryInfoList(QDir::Files)) {
+ if (model() && model()->metaInfo().itemLibraryInfo()) {
+ Internal::MetaInfoReader reader(model()->metaInfo());
+ reader.setQualifcation(qualification);
+ try {
+ reader.readMetaInfoFile(metaInfoFile.absoluteFilePath(), true);
+ } catch (InvalidMetaInfoException &e) {
+ qWarning() << e.description();
+ const QString errorMessage = metaInfoFile.absoluteFilePath() + QLatin1Char('\n') + QLatin1Char('\n') + reader.errors().join(QLatin1String("\n"));
+ QMessageBox::critical(0,
+ QCoreApplication::translate("SubComponentManager::parseDirectory", "Invalid meta info"),
+ errorMessage);
+ }
+ }
+ }
+ if (!metaFiles.isEmpty())
+ return;
+ }
+
if (debug)
qDebug() << Q_FUNC_INFO << canonicalDirPath;
@@ -226,21 +330,20 @@ void SubComponentManager::parseDirectory(const QString &canonicalDirPath, bool a
}
}
-void SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& /* qualification */)
+void SubComponentManager::parseFile(const QString &canonicalFilePath, bool addToLibrary, const QString& qualification)
{
if (debug)
qDebug() << Q_FUNC_INFO << canonicalFilePath;
QFile file(canonicalFilePath);
- if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
- }
QString dir = QFileInfo(canonicalFilePath).path();
foreach (const QString &qualifier, m_dirToQualifier.values(dir)) {
registerQmlFile(canonicalFilePath, qualifier, addToLibrary);
}
- registerQmlFile(canonicalFilePath, QString(), addToLibrary);
+ registerQmlFile(canonicalFilePath, qualification, addToLibrary);
}
void SubComponentManager::parseFile(const QString &canonicalFilePath)
@@ -255,9 +358,8 @@ QList<QFileInfo> SubComponentManager::watchedFiles(const QString &canonicalDirPa
foreach (const QString &monitoredFile, m_watcher.files()) {
QFileInfo fileInfo(monitoredFile);
- if (fileInfo.dir().absolutePath() == canonicalDirPath) {
+ if (fileInfo.dir().absolutePath() == canonicalDirPath)
files.append(fileInfo);
- }
}
return files;
}
@@ -284,10 +386,15 @@ void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QStri
if (!model())
return;
+ if (!checkIfDerivedFromItem(fileInfo.absoluteFilePath()))
+ return;
+
QString componentName = fileInfo.baseName();
+ const QString baseComponentName = componentName;
+ QString fixedQualifier = qualifier;
if (!qualifier.isEmpty()) {
- QString fixedQualifier = qualifier;
+ fixedQualifier = qualifier;
if (qualifier.right(1) == QLatin1String("."))
fixedQualifier.chop(1); //remove last char if it is a dot
componentName = fixedQualifier + '.' + componentName;
@@ -300,12 +407,15 @@ void SubComponentManager::registerQmlFile(const QFileInfo &fileInfo, const QStri
// Add file components to the library
ItemLibraryEntry itemLibraryEntry;
itemLibraryEntry.setType(componentName, -1, -1);
- itemLibraryEntry.setName(componentName);
+ itemLibraryEntry.setName(baseComponentName);
itemLibraryEntry.setCategory("QML Components");
+ if (!qualifier.isEmpty()) {
+ itemLibraryEntry.setForceImport(true);
+ itemLibraryEntry.setRequiredImport(fixedQualifier);
+ }
- if (model()->metaInfo(componentName).isValid() && model()->metaInfo(componentName).isSubclassOf("QtQuick.Item", -1, -1) &&
- !model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {
+ if (!model()->metaInfo().itemLibraryInfo()->containsEntry(itemLibraryEntry)) {
model()->metaInfo().itemLibraryInfo()->addEntry(itemLibraryEntry);
}
@@ -363,9 +473,8 @@ void SubComponentManager::update(const QUrl &filePath, const QList<Import> &impo
m_watcher.removePath(oldDir.filePath());
}
- if (!newDir.filePath().isEmpty()) {
+ if (!newDir.filePath().isEmpty())
m_dirToQualifier.insertMulti(newDir.canonicalFilePath(), QString());
- }
}
//
diff --git a/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp b/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp
index b51ed2c204..785655578c 100644
--- a/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/abstractproperty.cpp
@@ -42,7 +42,6 @@
#include "nodelistproperty.h"
#include <QTextStream>
#include <qmlobjectnode.h>
-#include <QDeclarativeView>
namespace QmlDesigner {
diff --git a/src/plugins/qmldesigner/designercore/model/abstractview.cpp b/src/plugins/qmldesigner/designercore/model/abstractview.cpp
index d4309bb591..e306199243 100644
--- a/src/plugins/qmldesigner/designercore/model/abstractview.cpp
+++ b/src/plugins/qmldesigner/designercore/model/abstractview.cpp
@@ -132,6 +132,11 @@ Model* AbstractView::model() const
return m_model.data();
}
+bool AbstractView::isAttached() const
+{
+ return model();
+}
+
/*!
\brief is called if a view is being attached to a model
\param model which is being attached
@@ -252,7 +257,7 @@ QList<ModelNode> AbstractView::toModelNodeList(const QList<Internal::InternalNod
QList<ModelNode> toModelNodeList(const QList<Internal::InternalNode::Pointer> &nodeList, AbstractView *view)
{
QList<ModelNode> newNodeList;
- foreach(const Internal::InternalNode::Pointer &node, nodeList)
+ foreach (const Internal::InternalNode::Pointer &node, nodeList)
newNodeList.append(ModelNode(node, view->model(), view));
return newNodeList;
@@ -261,7 +266,7 @@ QList<ModelNode> toModelNodeList(const QList<Internal::InternalNode::Pointer> &n
QList<Internal::InternalNode::Pointer> toInternalNodeList(const QList<ModelNode> &nodeList)
{
QList<Internal::InternalNode::Pointer> newNodeList;
- foreach(const ModelNode &node, nodeList)
+ foreach (const ModelNode &node, nodeList)
newNodeList.append(node.internalNode());
return newNodeList;
@@ -338,20 +343,18 @@ QmlModelView *AbstractView::toQmlModelView()
NodeInstanceView *AbstractView::nodeInstanceView() const
{
- if (model()) {
+ if (model())
return model()->d->nodeInstanceView();
- } else {
+ else
return 0;
- }
}
RewriterView *AbstractView::rewriterView() const
{
- if (model()) {
+ if (model())
return model()->d->rewriterView();
- } else {
+ else
return 0;
- }
}
void AbstractView::resetView()
@@ -364,7 +367,7 @@ void AbstractView::resetView()
currentModel->attachView(this);
}
-QList<ModelNode> AbstractView::allModelNodes()
+QList<ModelNode> AbstractView::allModelNodes() const
{
return toModelNodeList(model()->d->allNodes());
}
diff --git a/src/plugins/qmldesigner/designercore/model/anchorline.cpp b/src/plugins/qmldesigner/designercore/model/anchorline.cpp
index dddafb1222..2563647436 100644
--- a/src/plugins/qmldesigner/designercore/model/anchorline.cpp
+++ b/src/plugins/qmldesigner/designercore/model/anchorline.cpp
@@ -84,9 +84,8 @@ AnchorLine &AnchorLine::operator =(const AnchorLine &other)
ModelNode AnchorLine::modelNode() const
{
- if (m_internalNode.isNull() || m_internalNodeState.isNull() || m_model.isNull()) {
+ if (m_internalNode.isNull() || m_internalNodeState.isNull() || m_model.isNull())
return ModelNode();
- }
return ModelNode(m_internalNode, m_model.data());
}
diff --git a/src/plugins/qmldesigner/designercore/model/basetexteditmodifier.cpp b/src/plugins/qmldesigner/designercore/model/basetexteditmodifier.cpp
index 053e911e6e..b38fc0bdd2 100644
--- a/src/plugins/qmldesigner/designercore/model/basetexteditmodifier.cpp
+++ b/src/plugins/qmldesigner/designercore/model/basetexteditmodifier.cpp
@@ -62,11 +62,10 @@ void BaseTextEditModifier::indent(int offset, int length)
int BaseTextEditModifier::indentDepth() const
{
- if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit())) {
+ if (TextEditor::BaseTextEditorWidget *bte = qobject_cast<TextEditor::BaseTextEditorWidget*>(plainTextEdit()))
return bte->tabSettings().m_indentSize;
- } else {
+ else
return 0;
- }
}
bool BaseTextEditModifier::renameId(const QString &oldId, const QString &newId)
diff --git a/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp b/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp
index 559e3c7b4e..9acb0bbc2e 100644
--- a/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/bindingproperty.cpp
@@ -212,9 +212,8 @@ void BindingProperty::setDynamicTypeNameAndExpression(const QString &typeName, c
if (expression.isEmpty())
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name());
- if (typeName.isEmpty()) {
+ if (typeName.isEmpty())
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name());
- }
if (internalNode()->hasProperty(name())) { //check if oldValue != value
Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name());
diff --git a/src/plugins/qmldesigner/designercore/model/internalnode.cpp b/src/plugins/qmldesigner/designercore/model/internalnode.cpp
index 01aafbf003..a981757864 100644
--- a/src/plugins/qmldesigner/designercore/model/internalnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/internalnode.cpp
@@ -36,7 +36,7 @@
#include "invalidpropertyexception.h"
#include <QDebug>
-#include <corelib_global.h>
+#include <qmldesignercorelib_global.h>
namespace QmlDesigner {
namespace Internal {
@@ -289,7 +289,7 @@ QList<InternalProperty::Pointer> InternalNode::propertyList() const
QList<InternalNodeAbstractProperty::Pointer> InternalNode::nodeAbstractPropertyList() const
{
QList<InternalNodeAbstractProperty::Pointer> abstractPropertyList;
- foreach(const InternalProperty::Pointer &property, propertyList()) {
+ foreach (const InternalProperty::Pointer &property, propertyList()) {
if (property->isNodeAbstractProperty())
abstractPropertyList.append(property->toNodeAbstractProperty());
}
@@ -301,7 +301,7 @@ QList<InternalNodeAbstractProperty::Pointer> InternalNode::nodeAbstractPropertyL
QList<InternalNode::Pointer> InternalNode::allSubNodes() const
{
QList<InternalNode::Pointer> nodeList;
- foreach(const InternalNodeAbstractProperty::Pointer &property, nodeAbstractPropertyList()) {
+ foreach (const InternalNodeAbstractProperty::Pointer &property, nodeAbstractPropertyList()) {
nodeList.append(property->allSubNodes());
}
@@ -311,7 +311,7 @@ QList<InternalNode::Pointer> InternalNode::allSubNodes() const
QList<InternalNode::Pointer> InternalNode::allDirectSubNodes() const
{
QList<InternalNode::Pointer> nodeList;
- foreach(const InternalNodeAbstractProperty::Pointer &property, nodeAbstractPropertyList()) {
+ foreach (const InternalNodeAbstractProperty::Pointer &property, nodeAbstractPropertyList()) {
nodeList.append(property->allDirectSubNodes());
}
diff --git a/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp
index d512a1cefe..10f08167dd 100644
--- a/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/internalnodelistproperty.cpp
@@ -109,7 +109,7 @@ void InternalNodeListProperty::slide(int from, int to)
QList<InternalNode::Pointer> InternalNodeListProperty::allSubNodes() const
{
QList<InternalNode::Pointer> nodeList;
- foreach(const InternalNode::Pointer &childNode, m_nodeList) {
+ foreach (const InternalNode::Pointer &childNode, m_nodeList) {
nodeList.append(childNode->allSubNodes());
nodeList.append(childNode);
}
diff --git a/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp b/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp
index 866e45952a..63209ead49 100644
--- a/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/internalnodeproperty.cpp
@@ -114,9 +114,8 @@ QList<InternalNodePointer> InternalNodeProperty::allDirectSubNodes() const
{
QList<InternalNode::Pointer> nodeList;
- if (node()) {
+ if (node())
nodeList.append(node());
- }
return nodeList;
}
diff --git a/src/plugins/qmldesigner/designercore/model/internalproperty.h b/src/plugins/qmldesigner/designercore/model/internalproperty.h
index 048be6db0e..2fbb6e1c69 100644
--- a/src/plugins/qmldesigner/designercore/model/internalproperty.h
+++ b/src/plugins/qmldesigner/designercore/model/internalproperty.h
@@ -30,7 +30,7 @@
#ifndef INTERNALPROPERTY_H
#define INTERNALPROPERTY_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <QVariant>
#include <QString>
@@ -55,7 +55,7 @@ class InternalNode;
typedef QSharedPointer<InternalNode> InternalNodePointer;
typedef QWeakPointer<InternalNode> InternalNodeWeakPointer;
-class CORESHARED_EXPORT InternalProperty
+class QMLDESIGNERCORE_EXPORT InternalProperty
{
public:
typedef QSharedPointer<InternalProperty> Pointer;
diff --git a/src/plugins/qmldesigner/designercore/model/model.cpp b/src/plugins/qmldesigner/designercore/model/model.cpp
index 043747313a..1b72e15d3c 100644
--- a/src/plugins/qmldesigner/designercore/model/model.cpp
+++ b/src/plugins/qmldesigner/designercore/model/model.cpp
@@ -91,7 +91,7 @@ ModelPrivate::ModelPrivate(Model *model) :
m_writeLock(false),
m_internalIdCounter(1)
{
- m_rootInternalNode = createNode("QtQuick/Item", 1, 0, PropertyListType(), PropertyListType(), QString(), ModelNode::NodeWithoutSource,true);
+ m_rootInternalNode = createNode("QtQuick.Item", 1, 0, PropertyListType(), PropertyListType(), QString(), ModelNode::NodeWithoutSource,true);
m_acutalStateNode = m_rootInternalNode;
}
@@ -107,15 +107,15 @@ void ModelPrivate::detachAllViews()
m_viewList.clear();
- if (m_rewriterView) {
- m_rewriterView->modelAboutToBeDetached(m_q);
- m_rewriterView.clear();
- }
-
if (m_nodeInstanceView) {
m_nodeInstanceView->modelAboutToBeDetached(m_q);
m_nodeInstanceView.clear();
}
+
+ if (m_rewriterView) {
+ m_rewriterView->modelAboutToBeDetached(m_q);
+ m_rewriterView.clear();
+ }
}
Model *ModelPrivate::create(QString type, int major, int minor, Model *metaInfoPropxyModel)
@@ -158,9 +158,8 @@ void ModelPrivate::notifyImportsChanged(const QList<Import> &addedImports, const
QString description;
try {
- if (rewriterView()) {
+ if (rewriterView())
rewriterView()->importsChanged(addedImports, removedImports);
- }
} catch (RewritingException &e) {
description = e.description();
resetModel = true;
@@ -174,9 +173,8 @@ void ModelPrivate::notifyImportsChanged(const QList<Import> &addedImports, const
foreach (const QWeakPointer<AbstractView> &view, m_viewList)
view->importsChanged(addedImports, removedImports);
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
QUrl ModelPrivate::fileUrl() const
@@ -359,9 +357,8 @@ void ModelPrivate::notifyAuxiliaryDataChanged(const InternalNodePointer &interna
nodeInstanceView()->auxiliaryDataChanged(node, name, data);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyNodeSourceChanged(const InternalNodePointer &internalNode, const QString &newNodeSource)
@@ -391,9 +388,8 @@ void ModelPrivate::notifyNodeSourceChanged(const InternalNodePointer &internalNo
nodeInstanceView()->nodeSourceChanged(node, newNodeSource);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyRootNodeTypeChanged(const QString &type, int majorVersion, int minorVersion)
@@ -418,9 +414,8 @@ void ModelPrivate::notifyRootNodeTypeChanged(const QString &type, int majorVersi
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyInstancePropertyChange(const QList<QPair<ModelNode, QString> > &propertyPairList)
@@ -461,13 +456,11 @@ void ModelPrivate::notifyInstancesCompleted(const QVector<ModelNode> &nodeVector
view->instancesCompleted(toModelNodeVector(internalVector, view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->instancesCompleted(toModelNodeVector(internalVector, nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
QMultiHash<ModelNode, InformationName> convertModelNodeInformationHash(const QMultiHash<ModelNode, InformationName> &informationChangeHash, AbstractView *view)
@@ -501,13 +494,11 @@ void ModelPrivate::notifyInstancesInformationsChange(const QMultiHash<ModelNode,
view->instanceInformationsChange(convertModelNodeInformationHash(informationChangeHash, view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->instanceInformationsChange(convertModelNodeInformationHash(informationChangeHash, nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyInstancesRenderImageChanged(const QVector<ModelNode> &nodeVector)
@@ -530,13 +521,11 @@ void ModelPrivate::notifyInstancesRenderImageChanged(const QVector<ModelNode> &n
view->instancesRenderImageChanged(toModelNodeVector(internalVector, view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->instancesRenderImageChanged(toModelNodeVector(internalVector, nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyInstancesPreviewImageChanged(const QVector<ModelNode> &nodeVector)
@@ -559,13 +548,11 @@ void ModelPrivate::notifyInstancesPreviewImageChanged(const QVector<ModelNode> &
view->instancesPreviewImageChanged(toModelNodeVector(internalVector, view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->instancesPreviewImageChanged(toModelNodeVector(internalVector, nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyInstancesChildrenChanged(const QVector<ModelNode> &nodeVector)
@@ -588,13 +575,11 @@ void ModelPrivate::notifyInstancesChildrenChanged(const QVector<ModelNode> &node
view->instancesChildrenChanged(toModelNodeVector(internalVector, view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->instancesChildrenChanged(toModelNodeVector(internalVector, nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyActualStateChanged(const ModelNode &node)
@@ -617,13 +602,11 @@ void ModelPrivate::notifyActualStateChanged(const ModelNode &node)
view->actualStateChanged(ModelNode(node.internalNode(), model(), view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->actualStateChanged(ModelNode(node.internalNode(), model(), nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyRewriterBeginTransaction()
@@ -644,13 +627,11 @@ void ModelPrivate::notifyRewriterBeginTransaction()
view->rewriterBeginTransaction();
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->rewriterBeginTransaction();
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyRewriterEndTransaction()
@@ -671,13 +652,11 @@ void ModelPrivate::notifyRewriterEndTransaction()
view->rewriterEndTransaction();
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->rewriterEndTransaction();
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyInstanceToken(const QString &token, int number, const QVector<ModelNode> &nodeVector)
@@ -701,13 +680,11 @@ void ModelPrivate::notifyInstanceToken(const QString &token, int number, const Q
view->instancesToken(token, number, toModelNodeVector(internalVector, view.data()));
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->instancesToken(token, number, toModelNodeVector(internalVector, nodeInstanceView()));
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyCustomNotification(const AbstractView *senderView, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
@@ -730,13 +707,11 @@ void ModelPrivate::notifyCustomNotification(const AbstractView *senderView, cons
view->customNotification(senderView, identifier, toModelNodeList(internalList, view.data()), data);
}
- if (nodeInstanceView()) {
+ if (nodeInstanceView())
nodeInstanceView()->customNotification(senderView, identifier, toModelNodeList(internalList, nodeInstanceView()), data);
- }
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
@@ -781,9 +756,8 @@ void ModelPrivate::notifyPropertiesRemoved(const QList<PropertyPair> &propertyPa
view->propertiesRemoved(propertyList);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyPropertiesAboutToBeRemoved(const QList<InternalProperty::Pointer> &internalPropertyList)
@@ -833,9 +807,8 @@ void ModelPrivate::notifyPropertiesAboutToBeRemoved(const QList<InternalProperty
nodeInstanceView()->propertiesAboutToBeRemoved(propertyList);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::setAuxiliaryData(const InternalNode::Pointer& node, const QString &name, const QVariant &data)
@@ -846,9 +819,8 @@ void ModelPrivate::setAuxiliaryData(const InternalNode::Pointer& node, const QSt
void ModelPrivate::resetModelByRewriter(const QString &description)
{
- if (rewriterView()) {
+ if (rewriterView())
rewriterView()->resetToLastCorrectQml();
- }
throw RewritingException(__LINE__, __FUNCTION__, __FILE__, description, rewriterView()->textModifierContent());
}
@@ -899,9 +871,8 @@ void ModelPrivate::notifyNodeCreated(const InternalNode::Pointer &newInternalNod
view->nodeCreated(createdNode);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyNodeAboutToBeRemoved(const InternalNode::Pointer &nodePointer)
@@ -930,9 +901,8 @@ void ModelPrivate::notifyNodeAboutToBeRemoved(const InternalNode::Pointer &nodeP
nodeInstanceView()->nodeAboutToBeRemoved(node);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &nodePointer, const InternalNodePointer &parentNodePointer, const QString &parentPropertyName, AbstractView::PropertyChangeFlags propertyChange)
@@ -965,9 +935,8 @@ void ModelPrivate::notifyNodeRemoved(const InternalNodePointer &nodePointer, con
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyNodeIdChanged(const InternalNode::Pointer& nodePointer, const QString& newId, const QString& oldId)
@@ -996,9 +965,8 @@ void ModelPrivate::notifyNodeIdChanged(const InternalNode::Pointer& nodePointer,
nodeInstanceView()->nodeIdChanged(node, newId, oldId);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPropertyPointer> &internalBropertyList, AbstractView::PropertyChangeFlags propertyChange)
@@ -1037,9 +1005,8 @@ void ModelPrivate::notifyBindingPropertiesChanged(const QList<InternalBindingPro
nodeInstanceView()->bindingPropertiesChanged(propertyList, propertyChange);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyScriptFunctionsChanged(const InternalNodePointer &internalNodePointer, const QStringList &scriptFunctionList)
@@ -1070,9 +1037,8 @@ void ModelPrivate::notifyScriptFunctionsChanged(const InternalNodePointer &inter
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
@@ -1127,9 +1093,8 @@ void ModelPrivate::notifyVariantPropertiesChanged(const InternalNodePointer &int
nodeInstanceView()->variantPropertiesChanged(propertyList, propertyChange);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &internalNodePointer, const InternalNodeAbstractPropertyPointer &newPropertyParent, const InternalNodePointer &oldParent, const QString &oldPropertyName, AbstractView::PropertyChangeFlags propertyChange)
@@ -1184,9 +1149,8 @@ void ModelPrivate::notifyNodeAboutToBeReparent(const InternalNodePointer &intern
nodeInstanceView()->nodeAboutToBeReparented(node, newProperty, oldProperty, propertyChange);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
@@ -1242,9 +1206,8 @@ void ModelPrivate::notifyNodeReparent(const InternalNode::Pointer &internalNodeP
nodeInstanceView()->nodeReparented(node, newProperty, oldProperty, propertyChange);
}
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::notifyNodeOrderChanged(const InternalNodeListPropertyPointer &internalListPropertyPointer,
@@ -1276,9 +1239,8 @@ void ModelPrivate::notifyNodeOrderChanged(const InternalNodeListPropertyPointer
ModelNode(internalNodePointer, model(), nodeInstanceView()),
oldIndex);
- if (resetModel) {
+ if (resetModel)
resetModelByRewriter(description);
- }
}
void ModelPrivate::setSelectedNodes(const QList<InternalNode::Pointer> &selectedNodeList)
@@ -1563,12 +1525,13 @@ void ModelPrivate::setRewriterView(RewriterView *rewriterView)
Q_ASSERT(!(rewriterView && m_rewriterView));
+ if (m_rewriterView)
+ m_rewriterView->modelAboutToBeDetached(model());
+
m_rewriterView = rewriterView;
if (rewriterView)
rewriterView->modelAttached(model());
- else if (m_rewriterView)
- m_rewriterView->modelAboutToBeDetached(model());
}
RewriterView *ModelPrivate::rewriterView() const
@@ -1755,11 +1718,34 @@ bool Model::hasImport(const Import &import, bool ignoreAlias, bool allowHigherVe
return false;
}
+QString Model::pathForImport(const Import &import)
+{
+ if (!rewriterView())
+ return QString();
+
+ return rewriterView()->pathForImport(import);
+}
+
RewriterView *Model::rewriterView() const
{
return d->rewriterView();
}
+void Model::setRewriterView(RewriterView *rewriterView)
+{
+ d->setRewriterView(rewriterView);
+}
+
+NodeInstanceView *Model::nodeInstanceView() const
+{
+ return d->nodeInstanceView();
+}
+
+void Model::setNodeInstanceView(NodeInstanceView *nodeInstanceView)
+{
+ d->setNodeInstanceView(nodeInstanceView);
+}
+
/*!
\brief Returns the model that is used for metainfo
\return Return itself if not other metaInfoProxyModel does exist
@@ -1785,16 +1771,6 @@ Model *Model::create(const QString &rootType)
}
#endif
-Model *Model::masterModel() const
-{
- return d->m_masterModel.data();
-}
-
-void Model::setMasterModel(Model *model)
-{
- d->m_masterModel = model;
-}
-
/*!
\brief Returns the URL against which relative URLs within the model should be resolved.
\return The base URL.
@@ -1864,13 +1840,11 @@ void Model::attachView(AbstractView *view)
// Internal::WriteLocker locker(d);
RewriterView *rewriterView = qobject_cast<RewriterView*>(view);
if (rewriterView) {
- d->setRewriterView(rewriterView);
return;
}
NodeInstanceView *nodeInstanceView = qobject_cast<NodeInstanceView*>(view);
if (nodeInstanceView) {
- d->setNodeInstanceView(nodeInstanceView);
return;
}
@@ -1892,13 +1866,11 @@ void Model::detachView(AbstractView *view, ViewNotification emitDetachNotify)
RewriterView *rewriterView = qobject_cast<RewriterView*>(view);
if (rewriterView) {
- d->setRewriterView(0);
return;
}
NodeInstanceView *nodeInstanceView = qobject_cast<NodeInstanceView*>(view);
if (nodeInstanceView) {
- d->setNodeInstanceView(0);
return;
}
diff --git a/src/plugins/qmldesigner/designercore/model/model_p.h b/src/plugins/qmldesigner/designercore/model/model_p.h
index 8339ca9c05..27605e35c9 100644
--- a/src/plugins/qmldesigner/designercore/model/model_p.h
+++ b/src/plugins/qmldesigner/designercore/model/model_p.h
@@ -39,7 +39,7 @@
#include "abstractview.h"
#include "metainfo.h"
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
QT_BEGIN_NAMESPACE
class QPlainTextEdit;
@@ -212,6 +212,8 @@ public:
void setRewriterView(RewriterView *rewriterView);
RewriterView *rewriterView() const;
+
+
void setNodeInstanceView(NodeInstanceView *nodeInstanceView);
NodeInstanceView *nodeInstanceView() const;
@@ -229,7 +231,6 @@ private: //functions
private:
Model *m_q;
MetaInfo m_metaInfo;
-
QList<Import> m_imports;
QList<QWeakPointer<AbstractView> > m_viewList;
QList<InternalNodePointer> m_selectedNodeList;
@@ -237,17 +238,11 @@ private:
QHash<qint32, InternalNodePointer> m_internalIdNodeHash;
QSet<InternalNodePointer> m_nodeSet;
InternalNodePointer m_acutalStateNode;
-
-
InternalNodePointer m_rootInternalNode;
-
QUrl m_fileUrl;
-
- QWeakPointer<Model> m_masterModel;
QWeakPointer<RewriterView> m_rewriterView;
QWeakPointer<NodeInstanceView> m_nodeInstanceView;
QWeakPointer<Model> m_metaInfoProxyModel;
-
bool m_writeLock;
qint32 m_internalIdCounter;
};
diff --git a/src/plugins/qmldesigner/designercore/model/modelmerger.cpp b/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
index 10679027ba..122977fbe0 100644
--- a/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modelmerger.cpp
@@ -33,6 +33,7 @@
#include "modelnode.h"
#include "abstractview.h"
#include "model.h"
+#include "nodemetainfo.h"
#include "nodeproperty.h"
#include "nodelistproperty.h"
#include "bindingproperty.h"
@@ -42,6 +43,7 @@
#include <QSet>
#include <QStringList>
+#include <QUrl>
#include <QDebug>
@@ -75,16 +77,15 @@ static void syncBindingProperties(ModelNode &outputNode, const ModelNode &inputN
static void syncId(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
- if (!inputNode.id().isEmpty()) {
+ if (!inputNode.id().isEmpty())
outputNode.setId(idRenamingHash.value(inputNode.id()));
- }
}
static void splitIdInBaseNameAndNumber(const QString &id, QString *baseId, int *number)
{
int counter = 0;
- while(counter < id.count()) {
+ while (counter < id.count()) {
bool canConvertToInteger = false;
int newNumber = id.right(counter +1).toInt(&canConvertToInteger);
if (canConvertToInteger)
@@ -144,7 +145,8 @@ static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QStri
foreach (const VariantProperty &variantProperty, modelNode.variantProperties()) {
propertyList.append(QPair<QString, QVariant>(variantProperty.name(), variantProperty.value()));
}
- ModelNode newNode(view->createModelNode(modelNode.type(),modelNode.majorVersion(),modelNode.minorVersion(),
+ NodeMetaInfo nodeMetaInfo = view->model()->metaInfo(modelNode.type());
+ ModelNode newNode(view->createModelNode(modelNode.type(), nodeMetaInfo.majorVersion(), nodeMetaInfo.minorVersion(),
propertyList, variantPropertyList, modelNode.nodeSource(), modelNode.nodeSourceType()));
syncBindingProperties(newNode, modelNode, idRenamingHash);
syncId(newNode, modelNode, idRenamingHash);
@@ -161,9 +163,8 @@ ModelNode ModelMerger::insertModel(const ModelNode &modelNode)
QList<Import> newImports;
foreach (const Import &import, modelNode.model()->imports()) {
- if (!view()->model()->hasImport(import, true, true)) {
+ if (!view()->model()->hasImport(import, true, true))
newImports.append(import);
- }
}
view()->model()->changeImports(newImports, QList<Import>());
@@ -198,7 +199,7 @@ void ModelMerger::replaceModel(const ModelNode &modelNode)
syncNodeProperties(rootNode, modelNode, idRenamingHash, view());
syncNodeListProperties(rootNode, modelNode, idRenamingHash, view());
m_view->changeRootNodeType(modelNode.type(), modelNode.majorVersion(), modelNode.minorVersion());
- } catch (RewritingException &e) {
+ } catch (RewritingException &e) {
qWarning() << e.description(); //silent error
}
}
diff --git a/src/plugins/qmldesigner/designercore/model/modelnode.cpp b/src/plugins/qmldesigner/designercore/model/modelnode.cpp
index 79b354965d..dbce22d4f0 100644
--- a/src/plugins/qmldesigner/designercore/model/modelnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modelnode.cpp
@@ -134,7 +134,7 @@ QString ModelNode::generateNewId() const
int counter = 1;
QString newId = QString("%1%2").arg(simplifiedTypeName().toLower()).arg(counter);
- while(view()->hasId(newId)) {
+ while (view()->hasId(newId)) {
counter += 1;
newId = QString("%1%2").arg(simplifiedTypeName().toLower()).arg(counter);
}
@@ -147,9 +147,8 @@ QString ModelNode::generateNewId() const
*/
QString ModelNode::id() const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
return m_internalNode->id();
}
@@ -248,10 +247,12 @@ int ModelNode::majorQtQuickVersion() const
}
if (metaInfo().isValid()) {
+ if (type() == "QtQuick.QtObject")
+ return majorVersion();
NodeMetaInfo superClass = metaInfo().directSuperClass();
while (superClass.isValid()) {
- if (superClass.typeName() == "QtQuick.Item")
+ if (superClass.typeName() == "QtQuick.QtObject")
return superClass.majorVersion();
superClass = superClass.directSuperClass();
}
@@ -351,9 +352,8 @@ void ModelNode::setParentProperty(NodeAbstractProperty parent)
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
}
- if (!parent.parentModelNode().isValid()) {
+ if (!parent.parentModelNode().isValid())
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, "newParentNode");
- }
if (*this == parent.parentModelNode()) {
Q_ASSERT_X(*this != parent.parentModelNode(), Q_FUNC_INFO, "cannot set parent to itself");
@@ -629,9 +629,8 @@ void ModelNode::destroy()
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
}
- if (isRootNode()) {
+ if (isRootNode())
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, "rootNode");
- }
removeModelNodeFromSelection(*this);
model()->d->removeNode(internalNode());
@@ -879,9 +878,8 @@ QTextStream& operator<<(QTextStream &stream, const ModelNode &modelNode)
void ModelNode::selectNode()
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
QList<ModelNode> selectedNodeList;
selectedNodeList.append(*this);
@@ -891,9 +889,8 @@ void ModelNode::selectNode()
void ModelNode::deselectNode()
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
QList<ModelNode> selectedNodeList(view()->selectedModelNodes());
selectedNodeList.removeAll(*this);
@@ -913,9 +910,8 @@ QVariant ModelNode::toVariant() const
QVariant ModelNode::auxiliaryData(const QString &name) const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
return internalNode()->auxiliaryData(name);
}
@@ -928,18 +924,16 @@ void ModelNode::setAuxiliaryData(const QString &name, const QVariant &data) cons
bool ModelNode::hasAuxiliaryData(const QString &name) const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
return internalNode()->hasAuxiliaryData(name);
}
QHash<QString, QVariant> ModelNode::auxiliaryData() const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
return internalNode()->auxiliaryData();
}
@@ -979,18 +973,16 @@ void ModelNode::setNodeSource(const QString &newNodeSource)
QString ModelNode::nodeSource() const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
return internalNode()->nodeSource();
}
QString ModelNode::convertTypeToImportAlias() const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
if (model()->rewriterView())
return model()->rewriterView()->convertTypeToImportAlias(type());
@@ -1000,9 +992,8 @@ QString ModelNode::convertTypeToImportAlias() const
ModelNode::NodeSourceType ModelNode::nodeSourceType() const
{
- if (!isValid()) {
+ if (!isValid())
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- }
return static_cast<ModelNode::NodeSourceType>(internalNode()->nodeSourceType());
diff --git a/src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.cpp b/src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.cpp
deleted file mode 100644
index 336dbaaa6b..0000000000
--- a/src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.cpp
+++ /dev/null
@@ -1,951 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include <cmath>
-#include "modelnodecontextmenu.h"
-#include <QApplication>
-#include <QMessageBox>
-#include <coreplugin/editormanager/editormanager.h>
-#include <nodeabstractproperty.h>
-#include <nodelistproperty.h>
-#include <nodemetainfo.h>
-#include <modelnode.h>
-#include <qmlitemnode.h>
-#include <variantproperty.h>
-#include <bindingproperty.h>
-#include <nodeproperty.h>
-#include <rewritingexception.h>
-#include <rewritertransaction.h>
-#include <designmodewidget.h>
-#include <qmlanchors.h>
-
-const QString auxDataString = QLatin1String("anchors_");
-
-namespace QmlDesigner {
-
-static inline DesignDocumentController* designDocumentController()
-{
- return Internal::DesignModeWidget::instance()->currentDesignDocumentController();
-}
-
-static inline QString captionForModelNode(const ModelNode &modelNode)
-{
- if (modelNode.id().isEmpty())
- return modelNode.simplifiedTypeName();
-
- return modelNode.id();
-}
-
-static inline bool contains(const QmlItemNode &node, const QPoint &p)
-{
- return node.instanceSceneTransform().mapRect(node.instanceBoundingRect()).contains(p);
-}
-
-static inline bool checkIfNodeIsAView(const ModelNode &node)
-{
- return node.metaInfo().isValid() &&
- (node.metaInfo().isSubclassOf("QtQuick.ListView", -1, -1) ||
- node.metaInfo().isSubclassOf("QtQuick.GridView", -1, -1) ||
- node.metaInfo().isSubclassOf("QtQuick.PathView", -1, -1));
-}
-
-static inline bool isItem(const ModelNode &node)
-{
- return node.isValid() && node.metaInfo().isValid() && node.metaInfo().isSubclassOf("QtQuick.Item", -1, -1);
-}
-
-static inline bool itemsHaveSameParent(const QList<ModelNode> &siblingList)
-{
- if (siblingList.isEmpty())
- return false;
-
-
- QmlItemNode item(siblingList.first());
- if (!item.isValid())
- return false;
-
- if (item.isRootModelNode())
- return false;
-
- QmlItemNode parent = item.instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return false;
-
- foreach (const ModelNode &node, siblingList) {
- QmlItemNode currentItem(node);
- if (!currentItem.isValid())
- return false;
- QmlItemNode currentParent = currentItem.instanceParent().toQmlItemNode();
- if (!currentParent.isValid())
- return false;
- if (currentItem.instanceIsInPositioner())
- return false;
- if (currentParent != parent)
- return false;
- }
- return true;
-}
-
-static inline QList<QmlItemNode> siblingsForNode(const QmlItemNode &itemNode)
-{
- QList<QmlItemNode> siblingList;
-
- if (itemNode.isValid() && itemNode.modelNode().parentProperty().isValid()) {
- QList<ModelNode> modelNodes = itemNode.modelNode().parentProperty().parentModelNode().allDirectSubModelNodes();
- foreach (const ModelNode &node, modelNodes) {
- QmlItemNode childItemNode = node;
- if (childItemNode.isValid())
- siblingList.append(childItemNode);
- }
- }
-
- return siblingList;
-}
-
-static signed int getMaxZValue(const QList<QmlItemNode> &siblingList)
-{
- signed int maximum = INT_MIN;
- foreach (const QmlItemNode &node, siblingList) {
- signed int z = node.instanceValue("z").toInt();
- if (z > maximum)
- maximum = z;
- }
- return maximum;
-}
-
-static signed int getMinZValue(const QList<QmlItemNode> &siblingList)
-{
- signed int minimum = INT_MAX;
- foreach (const QmlItemNode &node, siblingList) {
- signed int z = node.instanceValue("z").toInt();
- if (z < minimum)
- minimum = z;
- }
- return minimum;
-}
-
-
-static inline bool modelNodeIsComponent(const ModelNode &node)
-{
- if (!node.isValid() || !node.metaInfo().isValid())
- return false;
-
- if (node.metaInfo().isComponent())
- return true;
-
- if (node.nodeSourceType() == ModelNode::NodeWithComponentSource)
- return true;
- if (checkIfNodeIsAView(node) &&
- node.hasNodeProperty("delegate")) {
- if (node.nodeProperty("delegate").modelNode().metaInfo().isComponent())
- return true;
- if (node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource)
- return true;
- }
-
- return false;
-}
-
-static inline bool isFileComponent(const ModelNode &node)
-{
- if (!node.isValid() || !node.metaInfo().isValid())
- return false;
-
- if (node.metaInfo().isComponent())
- return true;
-
- if (checkIfNodeIsAView(node) &&
- node.hasNodeProperty("delegate")) {
- if (node.nodeProperty("delegate").modelNode().metaInfo().isComponent())
- return true;
- }
-
- return false;
-}
-
-static inline void getWidthHeight(const ModelNode &node, int &width, int &height)
-{
- QmlItemNode itemNode(node);
- if (itemNode.isValid()) {
- width = itemNode.instanceValue("width").toInt();
- height = itemNode.instanceValue("height").toInt();
- }
-}
-
-static inline void getProperties(const ModelNode node, QHash<QString, QVariant> &propertyHash)
-{
- if (QmlObjectNode(node).isValid()) {
- foreach (const QString &propertyName, node.propertyNames()) {
- if (node.property(propertyName).isVariantProperty() ||
- (node.property(propertyName).isBindingProperty() &&
- !propertyName.contains(QLatin1String("anchors.")))) {
- propertyHash.insert(propertyName, QmlObjectNode(node).instanceValue(propertyName));
- }
- }
- }
- QmlItemNode itemNode(node);
- if (itemNode.isValid()) {
- propertyHash.insert(QLatin1String("width"), itemNode.instanceValue(QLatin1String("width")));
- propertyHash.insert(QLatin1String("height"), itemNode.instanceValue(QLatin1String("height")));
- propertyHash.remove(QLatin1String("x"));
- propertyHash.remove(QLatin1String("y"));
- propertyHash.remove(QLatin1String("rotation"));
- propertyHash.remove(QLatin1String("opacity"));
- }
-}
-
-static inline void applyProperties(ModelNode &node, const QHash<QString, QVariant> &propertyHash)
-{
- QHash<QString, QVariant> auxiliaryData = node.auxiliaryData();
- foreach (const QString propertyName, auxiliaryData.keys()) {
- node.setAuxiliaryData(propertyName, QVariant());
- }
-
- QHashIterator<QString, QVariant> i(propertyHash);
- while (i.hasNext()) {
- i.next();
- if (i.key() == QLatin1String("width") || i.key() == QLatin1String("height")) {
- node.setAuxiliaryData(i.key(), i.value());
- } else if (node.property(i.key()).isDynamic() &&
- node.property(i.key()).dynamicTypeName() == QLatin1String("alias") &&
- node.property(i.key()).isBindingProperty()) {
- AbstractProperty targetProperty = node.bindingProperty(i.key()).resolveToProperty();
- if (targetProperty.isValid()) {
- targetProperty.parentModelNode().setAuxiliaryData(targetProperty.name() + QLatin1String("@NodeInstance"), i.value());
- }
- } else {
- node.setAuxiliaryData(i.key() + QLatin1String("@NodeInstance"), i.value());
- }
- }
-}
-
-static inline void openFileForComponent(const ModelNode &node)
-{
- //int width = 0;
- //int height = 0;
- QHash<QString, QVariant> propertyHash;
- if (node.metaInfo().isComponent()) {
- //getWidthHeight(node, width, height);
- getProperties(node, propertyHash);
- designDocumentController()->changeToExternalSubComponent(node.metaInfo().componentFileName());
- } else if (checkIfNodeIsAView(node) &&
- node.hasNodeProperty("delegate") &&
- node.nodeProperty("delegate").modelNode().metaInfo().isComponent()) {
- //getWidthHeight(node, width, height);
- getProperties(node, propertyHash);
- designDocumentController()->changeToExternalSubComponent(node.nodeProperty("delegate").modelNode().metaInfo().componentFileName());
- }
- ModelNode rootModelNode = designDocumentController()->model()->rewriterView()->rootModelNode();
- applyProperties(rootModelNode, propertyHash);
- //rootModelNode.setAuxiliaryData("width", width);
- //rootModelNode.setAuxiliaryData("height", height);
-}
-
-static inline void openInlineComponent(const ModelNode &node)
-{
- if (!node.isValid() || !node.metaInfo().isValid())
- return;
-
- if (!designDocumentController())
- return;
-
- //int width = 0;
- //int height = 0;
- QHash<QString, QVariant> propertyHash;
-
- if (node.nodeSourceType() == ModelNode::NodeWithComponentSource) {
- //getWidthHeight(node, width, height);
- getProperties(node, propertyHash);
- designDocumentController()->changeToSubComponent(node);
- } else if (checkIfNodeIsAView(node) &&
- node.hasNodeProperty("delegate")) {
- if (node.nodeProperty("delegate").modelNode().nodeSourceType() == ModelNode::NodeWithComponentSource) {
- //getWidthHeight(node, width, height);
- getProperties(node, propertyHash);
- designDocumentController()->changeToSubComponent(node.nodeProperty("delegate").modelNode());
- }
- }
-
- ModelNode rootModelNode = designDocumentController()->model()->rewriterView()->rootModelNode();
- applyProperties(rootModelNode, propertyHash);
- //rootModelNode.setAuxiliaryData("width", width);
- //rootModelNode.setAuxiliaryData("height", height);
-}
-
-static inline bool modelNodesHaveProperty(const QList<ModelNode> &modelNodeList, const QString &propertyName)
-{
- foreach (const ModelNode &modelNode, modelNodeList)
- if (modelNode.hasProperty(propertyName))
- return true;
-
- return false;
-}
-
-ModelNodeContextMenu::ModelNodeContextMenu(QmlModelView *view) : m_view(view)
-{
-}
-
-void ModelNodeContextMenu::execute(const QPoint &pos, bool selectionMenuBool)
-{
- QMenu* menu = new QMenu();
-
- bool singleSelected = false;
- bool selectionIsEmpty = m_view->selectedModelNodes().isEmpty();
- ModelNode currentSingleNode;
- const bool isInBaseState = m_view->currentState().isBaseState();
- const QList<ModelNode> &selectedModelNodes = m_view->selectedModelNodes();
- if (selectedModelNodes.count()== 1) {
- singleSelected = true;
- currentSingleNode = selectedModelNodes.first();
- }
-
- if (selectionMenuBool) {
- QMenu *selectionMenu = new QMenu(tr("Selection"), menu);
- menu->addMenu(selectionMenu);
- ModelNode parentNode;
- if (singleSelected) {
- //ModelNodeAction *selectionAction;
- //selectionAction = createModelNodeAction(tr("DeSelect: ") + captionForModelNode(currentSingleNode), selectionMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::DeSelectModelNode);
- //selectionMenu->addAction(selectionAction);
- if (!currentSingleNode.isRootNode()) {
- parentNode = currentSingleNode.parentProperty().parentModelNode();
- selectionMenu->addAction(createModelNodeAction(tr("Select parent: %1").arg(captionForModelNode(parentNode)),
- selectionMenu, QList<ModelNode>() << parentNode, ModelNodeAction::SelectModelNode));
- }
-
- selectionMenu->addSeparator();
- }
- foreach (const ModelNode &node, m_view->allModelNodes()) {
- if (node != currentSingleNode && node != parentNode && contains(node, m_scenePos) && !node.isRootNode())
- selectionMenu->addAction(createModelNodeAction(tr("Select: %1").arg(captionForModelNode(node)), selectionMenu, QList<ModelNode>() << node, ModelNodeAction::SelectModelNode));
- }
- }
-
- QMenu *stackMenu = new QMenu(tr("Stack (z)"), menu);
- menu->addMenu(stackMenu);
-
- stackMenu->addAction(createModelNodeAction(tr("To Front"), stackMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::ToFront, singleSelected));
- stackMenu->addAction(createModelNodeAction(tr("To Back"), stackMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::ToBack, singleSelected));
- stackMenu->addAction(createModelNodeAction(tr("Raise"), stackMenu, QList<ModelNode>() << selectedModelNodes, ModelNodeAction::Raise));
- stackMenu->addAction(createModelNodeAction(tr("Lower"), stackMenu, QList<ModelNode>() << selectedModelNodes, ModelNodeAction::Lower));
- stackMenu->addSeparator();
- stackMenu->addAction(createModelNodeAction(tr("Reset z property"), stackMenu, QList<ModelNode>() << selectedModelNodes, ModelNodeAction::ResetZ));
-
- QMenu *editMenu = new QMenu(tr("Edit"), menu);
- menu->addMenu(editMenu);
- if (!selectionIsEmpty) {
- //editMenu->addAction(createModelNodeAction(tr("Change Id"), editMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::SetId, singleSelected));
- ModelNodeAction* action = createModelNodeAction(tr("Reset Position"), editMenu, selectedModelNodes, ModelNodeAction::ResetPosition);
- if (!modelNodesHaveProperty(selectedModelNodes, QLatin1String("x")) && !modelNodesHaveProperty(selectedModelNodes, QLatin1String("y")))
- action->setEnabled(false);
- editMenu->addAction(action);
- action = createModelNodeAction(tr("Reset Size"), editMenu, selectedModelNodes, ModelNodeAction::ResetSize);
- if (!modelNodesHaveProperty(selectedModelNodes, QLatin1String("width")) && !modelNodesHaveProperty(selectedModelNodes, QLatin1String("height")))
- action->setEnabled(false);
- editMenu->addAction(action);
- action = createModelNodeAction(tr("Visibility"), editMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::ModelNodeVisibility, singleSelected);
- editMenu->addAction(action);
- if (singleSelected && !isItem(currentSingleNode))
- action->setEnabled(false);
-
- } else {
- editMenu->setEnabled(false);
- }
-
- QMenu *anchorMenu = new QMenu(tr("Anchors"), menu);
- menu->addMenu(anchorMenu);
-
-
- if (singleSelected && isInBaseState) {
- QmlItemNode itemNode(currentSingleNode);
-
- bool anchored = itemNode.instanceHasAnchors();
- bool isRootNode = itemNode.isRootNode();
-
- ModelNodeAction *action = createModelNodeAction(tr("Fill"), anchorMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::AnchorFill, !anchored && !isRootNode);
- anchorMenu->addAction(action);
- action = createModelNodeAction(tr("Reset"), anchorMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::AnchorReset, anchored && !isRootNode);
- anchorMenu->addAction(action);
- } else {
- anchorMenu->setEnabled(false);
- }
-
- QMenu *layoutMenu = new QMenu(tr("Layout"), menu);
- menu->addMenu(layoutMenu);
-
- bool layoutingIsPossible = itemsHaveSameParent(selectedModelNodes) && isInBaseState;
-
- if (!singleSelected && !selectionIsEmpty && layoutingIsPossible) {
-
- ModelNodeAction *action = createModelNodeAction(tr("Layout in Row"), layoutMenu, selectedModelNodes, ModelNodeAction::LayoutRow, true);
- layoutMenu->addAction(action);
- action = createModelNodeAction(tr("Layout in Column"), layoutMenu, selectedModelNodes, ModelNodeAction::LayoutColumn, true);
- layoutMenu->addAction(action);
- action = createModelNodeAction(tr("Layout in Grid"), layoutMenu, selectedModelNodes, ModelNodeAction::LayoutGrid, true);
- layoutMenu->addAction(action);
- action = createModelNodeAction(tr("Layout in Flow"), layoutMenu, selectedModelNodes, ModelNodeAction::LayoutFlow, true);
- layoutMenu->addAction(action);
-
- } else {
- layoutMenu->setEnabled(false);
- }
-
-
- menu->addSeparator();
- bool enterComponent = false;
- if (singleSelected) {
- enterComponent = modelNodeIsComponent(currentSingleNode);
- }
- menu->addAction(createModelNodeAction(tr("Go into Component"), editMenu, QList<ModelNode>() << currentSingleNode, ModelNodeAction::GoIntoComponent, enterComponent));
-
- menu->exec(pos);
- menu->deleteLater();
-}
-
-void ModelNodeContextMenu::setScenePos(const QPoint &pos)
-{
- m_scenePos = pos;
-}
-
-
-ModelNodeAction* ModelNodeContextMenu::createModelNodeAction(const QString &description, QMenu *menu, const QList<ModelNode> &modelNodeList, ModelNodeAction::ModelNodeActionType type, bool enabled)
-{
- ModelNodeAction* action = new ModelNodeAction(description, menu, m_view, modelNodeList, type);
- action->setEnabled(enabled);
- return action;
-}
-
-
-ModelNodeAction::ModelNodeAction( const QString & text, QObject *parent, QmlModelView *view, const QList<ModelNode> &modelNodeList, ModelNodeActionType type) :
- QAction(text, parent), m_view(view), m_modelNodeList(modelNodeList), m_type(type)
-{
- if (type == ModelNodeVisibility) {
- setCheckable(true);
- QmlItemNode itemNode = QmlItemNode(m_modelNodeList.first());
- if (itemNode.isValid())
- setChecked(itemNode.instanceValue("visible").toBool());
- else
- setEnabled(false);
- }
- connect(this, SIGNAL(triggered(bool)), this, SLOT(actionTriggered(bool)));
-}
-
-void ModelNodeAction::goIntoComponent(const ModelNode &modelNode)
-{
-
- if (modelNode.isValid() && modelNodeIsComponent(modelNode)) {
- if (isFileComponent(modelNode))
- openFileForComponent(modelNode);
- else
- openInlineComponent(modelNode);
- }
-}
-
-void ModelNodeAction::actionTriggered(bool b)
-{
- try {
- switch (m_type) {
- case ModelNodeAction::SelectModelNode: select(); break;
- case ModelNodeAction::DeSelectModelNode: deSelect(); break;
- case ModelNodeAction::CutSelection: cut(); break;
- case ModelNodeAction::CopySelection: copy(); break;
- case ModelNodeAction::DeleteSelection: deleteSelection(); break;
- case ModelNodeAction::ToFront: toFront(); break;
- case ModelNodeAction::ToBack: toBack(); break;
- case ModelNodeAction::Raise: raise(); break;
- case ModelNodeAction::Lower: lower(); break;
- case ModelNodeAction::Paste: paste(); break;
- case ModelNodeAction::Undo: undo(); break;
- case ModelNodeAction::Redo: redo(); break;
- case ModelNodeAction::ModelNodeVisibility: setVisible(b); break;
- case ModelNodeAction::ResetSize: resetSize(); break;
- case ModelNodeAction::ResetPosition: resetPosition(); break;
- case ModelNodeAction::GoIntoComponent: goIntoComponent(); break;
- case ModelNodeAction::SetId: setId(); break;
- case ModelNodeAction::ResetZ: resetZ(); break;
- case ModelNodeAction::AnchorFill: anchorsFill(); break;
- case ModelNodeAction::AnchorReset: anchorsReset(); break;
- case ModelNodeAction::LayoutColumn: layoutColumn(); break;
- case ModelNodeAction::LayoutRow: layoutRow(); break;
- case ModelNodeAction::LayoutGrid: layoutGrid(); break;
- case ModelNodeAction::LayoutFlow: layoutFlow(); break;
- }
- } catch (RewritingException e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void ModelNodeAction::select()
-{
- if (m_view)
- m_view->setSelectedModelNodes(m_modelNodeList);
-}
-
-void ModelNodeAction::deSelect()
-{
- if (m_view) {
- QList<ModelNode> selectedNodes = m_view->selectedModelNodes();
- foreach (const ModelNode &node, m_modelNodeList) {
- if (selectedNodes.contains(node))
- selectedNodes.removeAll(node);
- }
- m_view->setSelectedModelNodes(selectedNodes);
- }
-}
-
-void ModelNodeAction::cut()
-{
-}
-
-
-void ModelNodeAction::copy()
-{
-}
-
-void ModelNodeAction::deleteSelection()
-{
-}
-
-void ModelNodeAction::toFront()
-{
- if (!m_view)
- return;
-
- try {
- QmlItemNode node = m_modelNodeList.first();
- if (node.isValid()) {
- signed int maximumZ = getMaxZValue(siblingsForNode(node));
- maximumZ++;
- node.setVariantProperty("z", maximumZ);
- }
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-
-void ModelNodeAction::toBack()
-{
- if (!m_view)
- return;
- try {
- QmlItemNode node = m_modelNodeList.first();
- if (node.isValid()) {
- signed int minimumZ = getMinZValue(siblingsForNode(node));
- minimumZ--;
- node.setVariantProperty("z", minimumZ);
- }
-
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void ModelNodeAction::raise()
-{
- if (!m_view)
- return;
-
- try {
- RewriterTransaction transaction(m_view);
- foreach (ModelNode modelNode, m_modelNodeList) {
- QmlItemNode node = modelNode;
- if (node.isValid()) {
- signed int z = node.instanceValue("z").toInt();
- z++;
- node.setVariantProperty("z", z);
- }
- }
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void ModelNodeAction::lower()
-{
- if (!m_view)
- return;
- try {
- RewriterTransaction transaction(m_view);
- foreach (ModelNode modelNode, m_modelNodeList) {
- QmlItemNode node = modelNode;
- if (node.isValid()) {
- signed int z = node.instanceValue("z").toInt();
- z--;
- node.setVariantProperty("z", z);
- }
- }
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void ModelNodeAction::paste()
-{
-}
-
-void ModelNodeAction::undo()
-{
-}
-
-void ModelNodeAction::redo()
-{
-}
-
-void ModelNodeAction::setVisible(bool b)
-{
- if (!m_view)
- return;
- try {
- m_modelNodeList.first().variantProperty("visible") = b;
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-
-void ModelNodeAction::resetSize()
-{
- if (!m_view)
- return;
- try {
- RewriterTransaction transaction(m_view);
- foreach (ModelNode node, m_modelNodeList) {
- node.removeProperty("width");
- node.removeProperty("height");
- }
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void ModelNodeAction::resetPosition()
-{
- if (!m_view)
- return;
- try {
- RewriterTransaction transaction(m_view);
- foreach (ModelNode node, m_modelNodeList) {
- node.removeProperty("x");
- node.removeProperty("y");
- }
- } catch (RewritingException &e) { //better save then sorry
- QMessageBox::warning(0, "Error", e.description());
- }
-}
-
-void ModelNodeAction::goIntoComponent()
-{
- goIntoComponent(m_modelNodeList.first());
-}
-
-void ModelNodeAction::setId()
-{
-}
-
-void ModelNodeAction::resetZ()
-{
- if (!m_view)
- return;
-
- RewriterTransaction transaction(m_view);
- foreach (ModelNode node, m_modelNodeList) {
- node.removeProperty("z");
- }
-}
-
-static inline void backupPropertyAndRemove(ModelNode node, const QString &propertyName)
-{
- if (node.hasVariantProperty(propertyName)) {
- node.setAuxiliaryData(auxDataString + propertyName, node.variantProperty(propertyName).value());
- node.removeProperty(propertyName);
-
- }
- if (node.hasBindingProperty(propertyName)) {
- node.setAuxiliaryData(auxDataString + propertyName, QmlItemNode(node).instanceValue(propertyName));
- node.removeProperty(propertyName);
- }
-}
-
-
-static inline void restoreProperty(ModelNode node, const QString &propertyName)
-{
- if (node.hasAuxiliaryData(auxDataString + propertyName))
- node.variantProperty(propertyName) = node.auxiliaryData(auxDataString + propertyName);
-}
-
-void ModelNodeAction::anchorsFill()
-{
- if (!m_view)
- return;
-
- RewriterTransaction transaction(m_view);
-
- foreach (ModelNode modelNode, m_modelNodeList) {
- QmlItemNode node = modelNode;
- if (node.isValid()) {
- node.anchors().fill();
- backupPropertyAndRemove(modelNode, QLatin1String("x"));
- backupPropertyAndRemove(modelNode, QLatin1String("y"));
- backupPropertyAndRemove(modelNode, QLatin1String("width"));
- backupPropertyAndRemove(modelNode, QLatin1String("height"));
- }
- }
-}
-
-void ModelNodeAction::anchorsReset()
-{
- if (!m_view)
- return;
- RewriterTransaction transaction(m_view);
-
- foreach (ModelNode modelNode, m_modelNodeList) {
- QmlItemNode node = modelNode;
- if (node.isValid()) {
- node.anchors().removeAnchors();
- node.anchors().removeMargins();
- restoreProperty(node, "x");
- restoreProperty(node, "y");
- restoreProperty(node, "width");
- restoreProperty(node, "height");
- }
- }
-}
-
-static inline void reparentTo(const ModelNode &node, const QmlItemNode &parent)
-{
-
- if (parent.isValid() && node.isValid()) {
- NodeAbstractProperty parentProperty;
-
- if (parent.hasDefaultProperty()) {
- parentProperty = parent.nodeAbstractProperty(parent.defaultProperty());
- } else {
- parentProperty = parent.nodeAbstractProperty(QLatin1String("data"));
- }
-
- parentProperty.reparentHere(node);
- }
-}
-
-
-bool compareByX(const ModelNode &node1, const ModelNode &node2)
-{
- QmlItemNode itemNode1 = QmlItemNode(node1);
- QmlItemNode itemNode2 = QmlItemNode(node2);
- if (itemNode1.isValid() && itemNode2.isValid())
- return itemNode1.instancePosition().x() < itemNode2.instancePosition().x();
- return false;
-}
-
-bool compareByY(const ModelNode &node1, const ModelNode &node2)
-{
- QmlItemNode itemNode1 = QmlItemNode(node1);
- QmlItemNode itemNode2 = QmlItemNode(node2);
- if (itemNode1.isValid() && itemNode2.isValid())
- return itemNode1.instancePosition().y() < itemNode2.instancePosition().y();
- return false;
-}
-
-bool compareByGrid(const ModelNode &node1, const ModelNode &node2)
-{
- QmlItemNode itemNode1 = QmlItemNode(node1);
- QmlItemNode itemNode2 = QmlItemNode(node2);
- if (itemNode1.isValid() && itemNode2.isValid()) {
- if ((itemNode1.instancePosition().y() + itemNode1.instanceSize().height()) < itemNode2.instancePosition().y())
- return true;
- if ((itemNode2.instancePosition().y() + itemNode2.instanceSize().height()) < itemNode1.instancePosition().y())
- return false; //first sort y (rows)
- return itemNode1.instancePosition().x() < itemNode2.instancePosition().x();
- }
- return false;
-}
-
-static inline QPoint getUpperLeftPosition(const QList<ModelNode> &modelNodeList)
-{
- QPoint p(INT_MAX, INT_MAX);
- foreach (ModelNode modelNode, modelNodeList) {
- QmlItemNode itemNode = QmlItemNode(modelNode);
- if (itemNode.isValid()) {
- if (itemNode.instancePosition().x() < p.x())
- p.setX(itemNode.instancePosition().x());
- if (itemNode.instancePosition().y() < p.y())
- p.setY(itemNode.instancePosition().y());
- }
-
- }
- return p;
-}
-
-void ModelNodeAction::layoutRow()
-{
- if (!m_view)
- return;
-
- ModelNode row;
- {
- RewriterTransaction transaction(m_view);
-
- QmlItemNode parent = QmlItemNode(m_modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- row = m_view->createModelNode(QLatin1String("QtQuick.Row"), parent.modelNode().majorQtQuickVersion(), 0);
-
- reparentTo(row, parent);
- }
-
- {
- RewriterTransaction transaction(m_view);
-
- QPoint pos = getUpperLeftPosition(m_modelNodeList);
- row.variantProperty(QLatin1String("x")) = pos.x();
- row.variantProperty(QLatin1String("y")) = pos.y();
-
- QList<ModelNode> sortedList = m_modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByX);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, row);
- modelNode.removeProperty(QLatin1String("x"));
- modelNode.removeProperty(QLatin1String("y"));
- }
- }
-}
-
-void ModelNodeAction::layoutColumn()
-{
- if (!m_view)
- return;
-
- ModelNode column;
- {
- RewriterTransaction transaction(m_view);
-
- QmlItemNode parent = QmlItemNode(m_modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- column = m_view->createModelNode(QLatin1String("QtQuick.Column"), parent.modelNode().majorQtQuickVersion(), 0);
-
- reparentTo(column, parent);
- }
-
- {
- RewriterTransaction transaction(m_view);
-
- QPoint pos = getUpperLeftPosition(m_modelNodeList);
- column.variantProperty(QLatin1String("x")) = pos.x();
- column.variantProperty(QLatin1String("y")) = pos.y();
-
- QList<ModelNode> sortedList = m_modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByY);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, column);
- modelNode.removeProperty(QLatin1String("x"));
- modelNode.removeProperty(QLatin1String("y"));
- }
- }
-}
-
-void ModelNodeAction::layoutGrid()
-{
- if (!m_view)
- return;
-
- ModelNode grid;
- {
- RewriterTransaction transaction(m_view);
-
- QmlItemNode parent = QmlItemNode(m_modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- grid = m_view->createModelNode(QLatin1String("QtQuick.Grid"), parent.modelNode().majorQtQuickVersion(), 0);
- grid.variantProperty(QLatin1String("columns")) = int(sqrt(double(m_modelNodeList.count())));
-
- reparentTo(grid, parent);
- }
-
- {
- RewriterTransaction transaction(m_view);
-
- QPoint pos = getUpperLeftPosition(m_modelNodeList);
- grid.variantProperty(QLatin1String("x")) = pos.x();
- grid.variantProperty(QLatin1String("y")) = pos.y();
-
- QList<ModelNode> sortedList = m_modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByGrid);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, grid);
- modelNode.removeProperty(QLatin1String("x"));
- modelNode.removeProperty(QLatin1String("y"));
- }
- }
-}
-
-void ModelNodeAction::layoutFlow()
-{
- if (!m_view)
- return;
-
- ModelNode flow;
- {
- RewriterTransaction transaction(m_view);
-
- QmlItemNode parent = QmlItemNode(m_modelNodeList.first()).instanceParent().toQmlItemNode();
- if (!parent.isValid())
- return;
-
- flow = m_view->createModelNode(QLatin1String("QtQuick.Flow"), parent.modelNode().majorQtQuickVersion(), 0);
-
- reparentTo(flow, parent);
- }
-
- {
- RewriterTransaction transaction(m_view);
-
- QPoint pos = getUpperLeftPosition(m_modelNodeList);
- flow.variantProperty(QLatin1String("x")) = pos.x();
- flow.variantProperty(QLatin1String("y")) = pos.y();
-
- QList<ModelNode> sortedList = m_modelNodeList;
- qSort(sortedList.begin(), sortedList.end(), compareByGrid);
-
- foreach (ModelNode modelNode, sortedList) {
- reparentTo(modelNode, flow);
- modelNode.removeProperty(QLatin1String("x"));
- modelNode.removeProperty(QLatin1String("y"));
- }
- }
-}
-
-}
diff --git a/src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.h b/src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.h
deleted file mode 100644
index 903f64b257..0000000000
--- a/src/plugins/qmldesigner/designercore/model/modelnodecontextmenu.h
+++ /dev/null
@@ -1,131 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef MODELNODECONTEXTMENU_H
-#define MODELNODECONTEXTMENU_H
-
-#include <QObject>
-#include <QPoint>
-#include <QAction>
-#include <QCoreApplication>
-#include <QMenu>
-#include <qmlmodelview.h>
-
-namespace QmlDesigner {
-
-class ModelNodeAction : public QAction
-{
- Q_OBJECT
-public:
- enum ModelNodeActionType {
- SelectModelNode,
- DeSelectModelNode,
- CutSelection,
- CopySelection,
- DeleteSelection,
- ToFront,
- ToBack,
- Raise,
- Lower,
- Paste,
- Undo,
- Redo,
- ModelNodeVisibility,
- ResetSize,
- ResetPosition,
- GoIntoComponent,
- SetId,
- ResetZ,
- AnchorReset,
- AnchorFill,
- LayoutRow,
- LayoutColumn,
- LayoutGrid,
- LayoutFlow
- };
-
-
- ModelNodeAction( const QString & text, QObject *parent, QmlModelView *view, const QList<ModelNode> &modelNodeList, ModelNodeActionType type);
-
- static void goIntoComponent(const ModelNode &modelNode);
-
-public slots:
- void actionTriggered(bool);
-
-private:
- void select();
- void deSelect();
- void cut();
- void copy();
- void deleteSelection();
- void toFront();
- void toBack();
- void raise();
- void lower();
- void paste();
- void undo();
- void redo();
- void setVisible(bool);
- void resetSize();
- void resetPosition();
- void goIntoComponent();
- void setId();
- void resetZ();
- void anchorsFill();
- void anchorsReset();
- void layoutRow();
- void layoutColumn();
- void layoutGrid();
- void layoutFlow();
-
- QmlModelView *m_view;
- QList<ModelNode> m_modelNodeList;
- ModelNodeActionType m_type;
-};
-
-class ModelNodeContextMenu
-{
- Q_DECLARE_TR_FUNCTIONS(QmlDesigner::ModelNodeContextMenu)
-public:
- ModelNodeContextMenu(QmlModelView *view);
- void execute(const QPoint &pos, bool selectionMenu);
- void setScenePos(const QPoint &pos);
-
-private:
- ModelNodeAction* createModelNodeAction(const QString &description, QMenu *menu, const QList<ModelNode> &modelNodeList, ModelNodeAction::ModelNodeActionType type, bool enabled = true);
-
- QmlModelView *m_view;
- QPoint m_scenePos;
-
-};
-
-
-};
-
-#endif // MODELNODECONTEXTMENU_H
diff --git a/src/plugins/qmldesigner/designercore/model/modelrewriter.cpp b/src/plugins/qmldesigner/designercore/model/modelrewriter.cpp
index f715916f9e..f51239ebcf 100644
--- a/src/plugins/qmldesigner/designercore/model/modelrewriter.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modelrewriter.cpp
@@ -387,21 +387,17 @@ ModificationGroupToken ModelRewriter::beginModificationGroup()
void ModelRewriter::endModificationGroup(const ModificationGroupToken& token)
{
- if (m_activeModificationGroups.isEmpty()) {
+ if (m_activeModificationGroups.isEmpty())
throw ModificationGroupException(__LINE__, Q_FUNC_INFO, __FILE__);
- }
- if (m_activeModificationGroups.last() != token) {
+ if (m_activeModificationGroups.last() != token)
throw ModificationGroupException(__LINE__, Q_FUNC_INFO, __FILE__);
- }
- if (!m_activeModificationGroups.removeAll(token)) {
+ if (!m_activeModificationGroups.removeAll(token))
throw ModificationGroupException(__LINE__, Q_FUNC_INFO, __FILE__);
- }
- if (!modificationGroupActive()) {
+ if (!modificationGroupActive())
m_modelToTextMerger.applyChanges(*m_textModifier);
- }
}
bool ModelRewriter::lastRewriteFailed() const
@@ -438,9 +434,8 @@ bool ModelRewriter::paste(QMimeData *transferData, const InternalNode::Pointer &
Paster paster(transferData, intoNode);
if (paster.doPaste(m_modelToTextMerger)) {
- if (!modificationGroupActive()) {
+ if (!modificationGroupActive())
m_modelToTextMerger.applyChanges(*m_textModifier);
- }
return true;
} else {
m_modelToTextMerger.clear();
diff --git a/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp b/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp
index 219a33137f..9e171dd1a6 100644
--- a/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/modeltotextmerger.cpp
@@ -66,13 +66,12 @@ void ModelToTextMerger::nodeRemoved(const ModelNode &removedNode, const NodeAbst
if (!isInHierarchy(parentProperty))
return;
- if (parentProperty.isDefaultProperty()) {
+ if (parentProperty.isDefaultProperty())
schedule(new RemoveNodeRewriteAction(removedNode));
- } else if (AbstractView::EmptyPropertiesRemoved == propertyChange) {
+ else if (AbstractView::EmptyPropertiesRemoved == propertyChange)
schedule(new RemovePropertyRewriteAction(parentProperty));
- } else if (parentProperty.isNodeListProperty()) {
+ else if (parentProperty.isNodeListProperty())
schedule(new RemoveNodeRewriteAction(removedNode));
- }
}
void ModelToTextMerger::propertiesRemoved(const QList<AbstractProperty>& propertyList)
@@ -157,11 +156,10 @@ void ModelToTextMerger::nodeReparented(const ModelNode &node, const NodeAbstract
if (oldPropertyParent.isNodeProperty()) {
// ignore, the subsequent remove property will take care of all
} else if (oldPropertyParent.isNodeListProperty()) {
- if (!oldPropertyParent.isDefaultProperty() && oldPropertyParent.toNodeListProperty().toModelNodeList().size() == 0) {
+ if (!oldPropertyParent.isDefaultProperty() && oldPropertyParent.toNodeListProperty().toModelNodeList().size() == 0)
schedule(new RemovePropertyRewriteAction(oldPropertyParent));
- } else {
+ else
schedule(new RemoveNodeRewriteAction(node));
- }
} else {
schedule(new RemoveNodeRewriteAction(node));
}
@@ -253,9 +251,8 @@ void ModelToTextMerger::applyChanges()
for (int i = 0; i < m_rewriteActions.size(); ++i) {
RewriteAction* action = m_rewriteActions.at(i);
- if (DebugRewriteActions) {
+ if (DebugRewriteActions)
qDebug() << "Next rewrite action:" << qPrintable(action->info());
- }
ModelNodePositionStorage *positionStore = m_rewriterView->positionStorage();
bool success = action->execute(refactoring, *positionStore);
diff --git a/src/plugins/qmldesigner/designercore/model/modeltotextmerger.h b/src/plugins/qmldesigner/designercore/model/modeltotextmerger.h
index ca910dd674..d12481edb2 100644
--- a/src/plugins/qmldesigner/designercore/model/modeltotextmerger.h
+++ b/src/plugins/qmldesigner/designercore/model/modeltotextmerger.h
@@ -30,7 +30,7 @@
#ifndef MODELTOTEXTMERGER_H
#define MODELTOTEXTMERGER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include <modelnode.h>
#include "abstractview.h"
#include "nodeabstractproperty.h"
@@ -46,7 +46,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT RewriterView;
+class RewriterView;
namespace Internal {
diff --git a/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp b/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp
index 1f2bfafde3..9916a186ce 100644
--- a/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/nodelistproperty.cpp
@@ -76,9 +76,8 @@ const QList<ModelNode> NodeListProperty::toModelNodeList() const
if (internalNode()->hasProperty(name())) {
Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name());
- if (internalProperty->isNodeListProperty()) {
+ if (internalProperty->isNodeListProperty())
return internalNodesToModelNodes(internalProperty->toNodeListProperty()->nodeList(), model(), view());
- }
}
return QList<ModelNode>();
diff --git a/src/plugins/qmldesigner/designercore/model/painteventfilter.cpp b/src/plugins/qmldesigner/designercore/model/painteventfilter.cpp
index b7a48298c5..bf88ee9c8a 100644
--- a/src/plugins/qmldesigner/designercore/model/painteventfilter.cpp
+++ b/src/plugins/qmldesigner/designercore/model/painteventfilter.cpp
@@ -46,7 +46,7 @@ PaintEventFilter::PaintEventFilter(QObject *parent)
bool PaintEventFilter::eventFilter(QObject *object, QEvent *event)
{
- switch(event->type())
+ switch (event->type())
{
case QEvent::Paint :
{
diff --git a/src/plugins/qmldesigner/designercore/model/paster.cpp b/src/plugins/qmldesigner/designercore/model/paster.cpp
index 52f0662e8e..17c2fb4794 100644
--- a/src/plugins/qmldesigner/designercore/model/paster.cpp
+++ b/src/plugins/qmldesigner/designercore/model/paster.cpp
@@ -69,9 +69,8 @@ public:
Node::accept(sourceAST->imports, this);
- if (sourceAST->members && sourceAST->members->member) {
+ if (sourceAST->members && sourceAST->members->member)
visitRootMember(sourceAST->members->member);
- }
return m_locations.isEmpty();
}
@@ -136,18 +135,16 @@ protected:
switchStateName(prevStateName);
return false;
} else if (ast->qualifiedTypeNameId && ast->qualifiedTypeNameId->name && ast->qualifiedTypeNameId->name->asString() == "PropertyChanges") {
- if (m_locations.remove(toLocation(start, end))) {
+ if (m_locations.remove(toLocation(start, end)))
m_paster->addNodeState(m_stateName, textAt(start, end));
- }
return false;
} else {
return true;
}
} else {
- if (m_locations.remove(toLocation(start, end))) {
+ if (m_locations.remove(toLocation(start, end)))
m_paster->addNode(textAt(start, end));
- }
return false;
}
@@ -171,9 +168,8 @@ protected:
bool visit(UiScriptBinding *ast) {
if (m_inStates && ast->qualifiedId && ast->qualifiedId->name && ast->qualifiedId->name->asString() == "name") {
if (ExpressionStatement *stmt = AST::cast<ExpressionStatement *>(ast->statement)) {
- if (StringLiteral * str = AST::cast<StringLiteral *>(stmt->expression)) {
+ if (StringLiteral * str = AST::cast<StringLiteral *>(stmt->expression))
m_stateName = str->value->asString();
- }
}
}
diff --git a/src/plugins/qmldesigner/designercore/model/plaintexteditmodifier.cpp b/src/plugins/qmldesigner/designercore/model/plaintexteditmodifier.cpp
index ff86eb6c4c..0a1112a0a5 100644
--- a/src/plugins/qmldesigner/designercore/model/plaintexteditmodifier.cpp
+++ b/src/plugins/qmldesigner/designercore/model/plaintexteditmodifier.cpp
@@ -154,11 +154,10 @@ void PlainTextEditModifier::commitGroup()
void PlainTextEditModifier::textEditChanged()
{
- if (!m_ongoingTextChange && m_changeSignalsEnabled) {
+ if (!m_ongoingTextChange && m_changeSignalsEnabled)
emit textChanged();
- } else {
+ else
m_pendingChangeSignal = true;
- }
}
void PlainTextEditModifier::runRewriting(ChangeSet *changeSet)
diff --git a/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp b/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp
index c3b199cacc..54750f79e5 100644
--- a/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp
+++ b/src/plugins/qmldesigner/designercore/model/propertycontainer.cpp
@@ -115,6 +115,15 @@ QDataStream &operator>>(QDataStream &stream, PropertyContainer &propertyContaine
return stream;
}
+QDebug operator<<(QDebug debug, const PropertyContainer &propertyContainer)
+{
+ debug << propertyContainer.m_name;
+ debug << propertyContainer.m_type;
+ debug << propertyContainer.m_value;
+
+ return debug.space();
+}
+
QDataStream &operator<<(QDataStream &stream, const QList<PropertyContainer> &propertyContainerList)
{
stream << propertyContainerList.count();
@@ -129,7 +138,7 @@ QDataStream &operator>>(QDataStream &stream, QList<PropertyContainer> &propertyC
int count;
stream >> count;
Q_ASSERT(count >= 0);
- for( int i = 0; i < count; i++) {
+ for ( int i = 0; i < count; i++) {
PropertyContainer propertyContainer;
stream >> propertyContainer;
propertyContainerList.append(propertyContainer);
@@ -138,6 +147,14 @@ QDataStream &operator>>(QDataStream &stream, QList<PropertyContainer> &propertyC
return stream;
}
+QDebug operator<<(QDebug debug, QList<PropertyContainer> &propertyContainerList)
+{
+ foreach (const PropertyContainer &propertyContainer, propertyContainerList)
+ debug << propertyContainer;
+
+ return debug.space();
+}
+
} //namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/propertyparser.cpp b/src/plugins/qmldesigner/designercore/model/propertyparser.cpp
index bd43fa68de..c03f244072 100644
--- a/src/plugins/qmldesigner/designercore/model/propertyparser.cpp
+++ b/src/plugins/qmldesigner/designercore/model/propertyparser.cpp
@@ -59,8 +59,8 @@ static uchar fromHex(const uchar c, const uchar c2)
static uchar fromHex(const QString &s, int idx)
{
- uchar c = s.at(idx).toAscii();
- uchar c2 = s.at(idx + 1).toAscii();
+ uchar c = s.at(idx).toLatin1();
+ uchar c2 = s.at(idx + 1).toLatin1();
return fromHex(c, c2);
}
@@ -191,7 +191,7 @@ QVariant read(const QString &typeStr, const QString &str, const MetaInfo &)
QVariant read(const QString &typeStr, const QString &str)
{
- int type = QMetaType::type(typeStr.toAscii().constData());
+ int type = QMetaType::type(typeStr.toLatin1().constData());
if (type == 0) {
qWarning() << "Type " << typeStr
<< " is unknown to QMetaType system. Cannot create properly typed QVariant for value "
diff --git a/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp b/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp
index a2565e7e30..6b2e3cc362 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlanchors.cpp
@@ -69,25 +69,24 @@ bool AnchorLine::isVerticalAnchorLine(Type anchorline)
static AnchorLine::Type propertyNameToLineType(const QString & string)
{
- if (string == QLatin1String("left")) {
+ if (string == QLatin1String("left"))
return AnchorLine::Left;
- } else if (string == QLatin1String("top")) {
+ else if (string == QLatin1String("top"))
return AnchorLine::Top;
- } else if (string == QLatin1String("right")) {
+ else if (string == QLatin1String("right"))
return AnchorLine::Right;
- } else if (string == QLatin1String("bottom")) {
+ else if (string == QLatin1String("bottom"))
return AnchorLine::Bottom;
- } else if (string == QLatin1String("horizontalCenter")) {
+ else if (string == QLatin1String("horizontalCenter"))
return AnchorLine::HorizontalCenter;
- } else if (string == QLatin1String("verticalCenter")) {
+ else if (string == QLatin1String("verticalCenter"))
return AnchorLine::VerticalCenter;
- } else if (string == QLatin1String("baseline")) {
+ else if (string == QLatin1String("baseline"))
return AnchorLine::VerticalCenter;
- } else if (string == QLatin1String("centerIn")) {
+ else if (string == QLatin1String("centerIn"))
return AnchorLine::Center;
- } else if (string == QLatin1String("fill")) {
+ else if (string == QLatin1String("fill"))
return AnchorLine::Fill;
- }
return AnchorLine::Invalid;
}
diff --git a/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp b/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp
index 8603b9ae69..2e4773f163 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlchangeset.cpp
@@ -37,11 +37,10 @@ namespace QmlDesigner {
ModelNode QmlModelStateOperation::target() const
{
- if (modelNode().property("target").isBindingProperty()) {
+ if (modelNode().property("target").isBindingProperty())
return modelNode().bindingProperty("target").resolveToModelNode();
- } else {
+ else
return ModelNode(); //exception?
- }
}
void QmlModelStateOperation::setTarget(const ModelNode &target)
@@ -56,7 +55,9 @@ bool QmlPropertyChanges::isValid() const
bool QmlModelStateOperation::isValid() const
{
- return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isSubclassOf("<cpp>.QDeclarativeStateOperation", -1, -1);
+ return QmlModelNodeFacade::isValid() && (
+ modelNode().metaInfo().isSubclassOf("<cpp>.QDeclarative1StateOperation", -1, -1)
+ || modelNode().metaInfo().isSubclassOf("<cpp>.QDeclarativeStateOperation", -1, -1));
}
void QmlPropertyChanges::removeProperty(const QString &name)
diff --git a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
index 5c47e5474b..3e41936cf9 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlitemnode.cpp
@@ -29,7 +29,6 @@
#include "qmlitemnode.h"
#include <metainfo.h>
-#include <QDeclarativeView>
#include "qmlchangeset.h"
#include "variantproperty.h"
#include "nodeproperty.h"
@@ -328,7 +327,7 @@ QmlModelState QmlModelStateGroup::addState(const QString &name)
PropertyListType propertyList;
propertyList.append(qMakePair(QString("name"), QVariant(name)));
- ModelNode newState = modelNode().view()->createModelNode("QtQuick.State", 1, 0, propertyList);
+ ModelNode newState = QmlObjectNode(modelNode()).qmlModelView()->createQmlState(propertyList);
modelNode().nodeListProperty("states").reparentHere(newState);
return newState;
diff --git a/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp b/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp
index 03f3a30ae2..868327344a 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlmodelview.cpp
@@ -45,8 +45,9 @@
#include "rewriterview.h"
#include "plaintexteditmodifier.h"
#include "modelmerger.h"
-#include "modelnodecontextmenu.h"
+#include "nodemetainfo.h"
+#include <utils/qtcassert.h>
namespace QmlDesigner {
@@ -110,7 +111,7 @@ QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, c
RewriterTransaction transaction = beginRewriterTransaction();
{
const QString newImportUrl = QLatin1String("QtQuick");
- const QString newImportVersion = QLatin1String("1.0");
+ const QString newImportVersion = QLatin1String("1.1");
Import newImport = Import::createLibraryImport(newImportUrl, newImportVersion);
foreach (const Import &import, model()->imports()) {
@@ -123,9 +124,8 @@ QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, c
}
}
- if (!model()->imports().contains(newImport)) {
+ if (!model()->imports().contains(newImport))
model()->changeImports(QList<Import>() << newImport, QList<Import>());
- }
QList<QPair<QString, QVariant> > propertyPairList;
propertyPairList.append(qMakePair(QString("x"), QVariant( round(position.x(), 4))));
@@ -140,7 +140,7 @@ QmlItemNode QmlModelView::createQmlItemNodeFromImage(const QString &imageName, c
}
propertyPairList.append(qMakePair(QString("source"), QVariant(relativeImageName)));
- newNode = createQmlItemNode("QtQuick.Image", 1, 0, propertyPairList);
+ newNode = createQmlItemNode("QtQuick.Image", -1, -1, propertyPairList);
parentNode.nodeAbstractProperty("data").reparentHere(newNode);
Q_ASSERT(newNode.isValid());
@@ -179,6 +179,12 @@ QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryE
try {
RewriterTransaction transaction = beginRewriterTransaction();
+
+ NodeMetaInfo metaInfo = model()->metaInfo(itemLibraryEntry.typeName());
+
+ int minorVersion = metaInfo.minorVersion();
+ int majorVersion = metaInfo.majorVersion();
+
if (itemLibraryEntry.typeName().contains('.')) {
const QString newImportUrl = itemLibraryEntry.requiredImport();
@@ -197,9 +203,8 @@ QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryE
}
}
- if (!model()->hasImport(newImport, true, true)) {
+ if (!model()->hasImport(newImport, true, true))
model()->changeImports(QList<Import>() << newImport, QList<Import>());
- }
}
}
@@ -211,7 +216,7 @@ QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryE
foreach (const PropertyContainer &property, itemLibraryEntry.properties())
propertyPairList.append(qMakePair(property.name(), property.value()));
- newNode = createQmlItemNode(itemLibraryEntry.typeName(), itemLibraryEntry.majorVersion(), itemLibraryEntry.minorVersion(), propertyPairList);
+ newNode = createQmlItemNode(itemLibraryEntry.typeName(), majorVersion, minorVersion, propertyPairList);
} else {
QScopedPointer<Model> inputModel(Model::create("QtQuick.Rectangle", 1, 0, model()));
inputModel->setFileUrl(model()->fileUrl());
@@ -224,7 +229,7 @@ QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryE
QScopedPointer<RewriterView> rewriterView(new RewriterView(RewriterView::Amend, 0));
rewriterView->setCheckSemanticErrors(false);
rewriterView->setTextModifier(&modifier);
- inputModel->attachView(rewriterView.data());
+ inputModel->setRewriterView(rewriterView.data());
if (rewriterView->errors().isEmpty() && rewriterView->rootModelNode().isValid()) {
ModelNode rootModelNode = rewriterView->rootModelNode();
@@ -234,13 +239,12 @@ QmlItemNode QmlModelView::createQmlItemNode(const ItemLibraryEntry &itemLibraryE
rootModelNode.variantProperty("y") = propertyPairList.at(1).second;
ModelMerger merger(this);
- newNode = merger.insertModel(rootModelNode);
+ newNode = merger.insertModel(rootModelNode);
}
}
- if (parentNode.hasDefaultProperty()) {
+ if (parentNode.hasDefaultProperty())
parentNode.nodeAbstractProperty(parentNode.defaultProperty()).reparentHere(newNode);
- }
if (!newNode.isValid())
return newNode;
@@ -424,13 +428,6 @@ void QmlModelView::nodeSourceChanged(const ModelNode &, const QString & /*newNod
}
-void QmlModelView::showContextMenu(const QPoint &globalPos, const QPoint &scenePos, bool showSelection)
-{
- ModelNodeContextMenu contextMenu(this);
- contextMenu.setScenePos(scenePos);
- contextMenu.execute(globalPos, showSelection);
-}
-
void QmlModelView::rewriterBeginTransaction()
{
@@ -473,5 +470,16 @@ void QmlModelView::otherPropertyChanged(const QmlObjectNode &/*qmlObjectNode*/,
{
}
+ModelNode QmlModelView::createQmlState(const QmlDesigner::PropertyListType &propertyList)
+{
+
+ QTC_CHECK(rootModelNode().majorQtQuickVersion() < 3);
+
+ if (rootModelNode().majorQtQuickVersion() > 1)
+ return createModelNode("QtQuick.State", 2, 0, propertyList);
+ else
+ return createModelNode("QtQuick.State", 1, 0, propertyList);
+}
+
} //QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp b/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp
index 8f5b53b924..3d0af0bb6a 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlobjectnode.cpp
@@ -96,7 +96,7 @@ instanciated instance of this object.
*/
QVariant QmlObjectNode::instanceValue(const QString &name) const
-{
+{
return nodeInstance().property(name);
}
@@ -356,7 +356,7 @@ QList<ModelNode> toModelNodeList(const QList<QmlObjectNode> &fxObjectNodeList)
{
QList<ModelNode> modelNodeList;
- foreach(const QmlObjectNode &fxObjectNode, fxObjectNodeList)
+ foreach (const QmlObjectNode &fxObjectNode, fxObjectNodeList)
modelNodeList.append(fxObjectNode.modelNode());
return modelNodeList;
@@ -366,7 +366,7 @@ QList<QmlObjectNode> toQmlObjectNodeList(const QList<ModelNode> &modelNodeList)
{
QList<QmlObjectNode> qmlObjectNodeList;
- foreach(const ModelNode &modelNode, modelNodeList) {
+ foreach (const ModelNode &modelNode, modelNodeList) {
QmlObjectNode objectNode(modelNode);
if (objectNode.isValid())
qmlObjectNodeList.append(objectNode);
@@ -464,9 +464,8 @@ QString QmlObjectNode::defaultProperty() const
void QmlObjectNode::setParent(QmlObjectNode newParent)
{
- if (newParent.hasDefaultProperty()) {
+ if (newParent.hasDefaultProperty())
newParent.modelNode().nodeAbstractProperty(newParent.defaultProperty()).reparentHere(modelNode());
- }
}
QmlItemNode QmlObjectNode::toQmlItemNode() const
diff --git a/src/plugins/qmldesigner/designercore/model/qmlstate.cpp b/src/plugins/qmldesigner/designercore/model/qmlstate.cpp
index 9d183991b5..ba6ce14543 100644
--- a/src/plugins/qmldesigner/designercore/model/qmlstate.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmlstate.cpp
@@ -118,7 +118,7 @@ bool QmlModelState::hasPropertyChanges(const ModelNode &node) const
if (isBaseState())
return false;
- foreach(const QmlPropertyChanges &changeSet, propertyChanges()) {
+ foreach (const QmlPropertyChanges &changeSet, propertyChanges()) {
if (changeSet.target().isValid() && changeSet.target() == node)
return true;
}
@@ -132,7 +132,7 @@ bool QmlModelState::hasStateOperation(const ModelNode &node) const
if (isBaseState())
return false;
- foreach(const QmlModelStateOperation &stateOperation, stateOperations()) {
+ foreach (const QmlModelStateOperation &stateOperation, stateOperations()) {
if (stateOperation.target() == node)
return true;
}
@@ -173,11 +173,15 @@ void QmlModelState::addChangeSetIfNotExists(const ModelNode &node)
if (!isValid())
throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- if (hasPropertyChanges(node)) {
+ if (hasPropertyChanges(node))
return; //changeSet already there
- }
- ModelNode newChangeSet = modelNode().view()->createModelNode("QtQuick.PropertyChanges", 1, 0);
+ ModelNode newChangeSet;
+ if (qmlModelView()->rootModelNode().majorQtQuickVersion() > 1)
+ newChangeSet = modelNode().view()->createModelNode("QtQuick.PropertyChanges", 2, 0);
+ else
+ newChangeSet = modelNode().view()->createModelNode("QtQuick.PropertyChanges", 1, 0);
+
modelNode().nodeListProperty("changes").reparentHere(newChangeSet);
QmlPropertyChanges(newChangeSet).setTarget(node);
@@ -244,7 +248,7 @@ bool QmlModelState::isValid() const
{
return QmlModelNodeFacade::isValid() &&
modelNode().metaInfo().isValid() &&
- (modelNode().metaInfo().isSubclassOf("QtQuick.State", 1, 0) || isBaseState());
+ (modelNode().metaInfo().isSubclassOf("QtQuick.State", -1, -1) || isBaseState());
}
/**
@@ -278,7 +282,7 @@ QmlModelState QmlModelState::duplicate(const QString &name) const
// QmlModelState newState(stateGroup().addState(name));
PropertyListType propertyList;
propertyList.append(qMakePair(QString("name"), QVariant(name)));
- QmlModelState newState ( qmlModelView()->createModelNode("QtQuick.State", 1, 0, propertyList) );
+ QmlModelState newState ( qmlModelView()->createQmlState(propertyList) );
foreach (const ModelNode &childNode, modelNode().nodeListProperty("changes").toModelNodeList()) {
ModelNode newModelNode(qmlModelView()->createModelNode(childNode.type(), childNode.majorVersion(), childNode.minorVersion()));
diff --git a/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp b/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp
index 39db7c9710..08cc254a4d 100644
--- a/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp
+++ b/src/plugins/qmldesigner/designercore/model/qmltextgenerator.cpp
@@ -54,8 +54,12 @@ inline static QString properColorName(const QColor &color)
inline static QString doubleToString(double d)
{
QString string = QString::number(d, 'f', 3);
- if (string.endsWith(".000"))
- string.chop(4);
+ if (string.contains(QLatin1Char('.'))) {
+ while (string.at(string.length()- 1) == QLatin1Char('0'))
+ string.chop(1);
+ if (string.at(string.length()- 1) == QLatin1Char('.'))
+ string.chop(1);
+ }
return string;
}
diff --git a/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp b/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
index 183eadb167..608c6b9327 100644
--- a/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
+++ b/src/plugins/qmldesigner/designercore/model/rewriteactioncompressor.cpp
@@ -306,13 +306,11 @@ void RewriteActionCompressor::compressAddEditActions(QList<RewriteAction *> &act
dirtyActions.insert(action);
}
} else if (ChangeIdRewriteAction *changeIdAction = action->asChangeIdRewriteAction()) {
- if (nodeOrParentInSet(changeIdAction->node(), addedNodes)) {
+ if (nodeOrParentInSet(changeIdAction->node(), addedNodes))
actionsToRemove.append(action);
- }
} else if (ChangeTypeRewriteAction *changeTypeAction = action->asChangeTypeRewriteAction()) {
- if (nodeOrParentInSet(changeTypeAction->node(), addedNodes)) {
+ if (nodeOrParentInSet(changeTypeAction->node(), addedNodes))
actionsToRemove.append(action);
- }
}
}
@@ -337,9 +335,8 @@ void RewriteActionCompressor::compressAddEditActions(QList<RewriteAction *> &act
}
const int idx = actions.indexOf(action);
- if (newAction && idx >= 0) {
+ if (newAction && idx >= 0)
actions[idx] = newAction;
- }
}
}
@@ -355,11 +352,10 @@ void RewriteActionCompressor::compressAddReparentActions(QList<RewriteAction *>
if (action->asAddPropertyRewriteAction() || action->asChangePropertyRewriteAction()) {
ModelNode containedNode;
- if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction()) {
+ if (AddPropertyRewriteAction *addAction = action->asAddPropertyRewriteAction())
containedNode = addAction->containedModelNode();
- } else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction()) {
+ else if (ChangePropertyRewriteAction *changeAction = action->asChangePropertyRewriteAction())
containedNode = changeAction->containedModelNode();
- }
if (!containedNode.isValid())
continue;
diff --git a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
index a069ef5b9a..4014ffe549 100644
--- a/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
+++ b/src/plugins/qmldesigner/designercore/model/rewriterview.cpp
@@ -107,7 +107,7 @@ QString RewriterView::Error::toString() const
str += tr("line %1").arg(line());
}
- if(column() != -1) {
+ if (column() != -1) {
if (!str.isEmpty())
str += QLatin1Char(' ');
@@ -155,9 +155,8 @@ void RewriterView::modelAttached(Model *model)
ModelAmender differenceHandler(m_textToModelMerger.data());
const QString qmlSource = m_textModifier->text();
- if (m_textToModelMerger->load(qmlSource, differenceHandler)) {
+ if (m_textToModelMerger->load(qmlSource, differenceHandler))
lastCorrectQmlSource = qmlSource;
- }
}
void RewriterView::modelAboutToBeDetached(Model * /*model*/)
@@ -473,6 +472,16 @@ QString RewriterView::textModifierContent() const
return QString();
}
+void RewriterView::reactivateTextMofifierChangeSignals()
+{
+ textModifier()->reactivateChangeSignals();
+}
+
+void RewriterView::deactivateTextMofifierChangeSignals()
+{
+ textModifier()->deactivateChangeSignals();
+}
+
void RewriterView::applyModificationGroupChanges()
{
Q_ASSERT(transactionLevel == 0);
@@ -493,11 +502,12 @@ void RewriterView::applyChanges()
throw RewritingException(__LINE__, __FUNCTION__, __FILE__, "RewriterView::applyChanges() already in error state", content);
}
+ m_differenceHandling = Validate;
+
try {
modelToTextMerger()->applyChanges();
- if (!errors().isEmpty()) {
+ if (!errors().isEmpty())
enterErrorState(errors().first().description());
- }
} catch (Exception &e) {
const QString content = textModifierContent();
qDebug() << "RewriterException:" << m_rewritingErrorMessage;
@@ -505,6 +515,8 @@ void RewriterView::applyChanges()
enterErrorState(e.description());
}
+ m_differenceHandling = Amend;
+
if (inErrorState()) {
const QString content = textModifierContent();
qDebug() << "RewriterException:" << m_rewritingErrorMessage;
@@ -613,6 +625,31 @@ bool RewriterView::modificationGroupActive()
return m_modificationGroupActive;
}
+static bool isInNodeDefinition(int nodeTextOffset, int nodeTextLength, int cursorPosition)
+{
+ return (nodeTextOffset <= cursorPosition) && (nodeTextOffset + nodeTextLength > cursorPosition);
+}
+
+ModelNode RewriterView::nodeAtTextCursorPosition(int cursorPosition) const
+{
+ const QList<ModelNode> allNodes = allModelNodes();
+
+ ModelNode nearestNode;
+ int nearestNodeTextOffset = -1;
+
+ foreach (const ModelNode &currentNode, allNodes) {
+ const int nodeTextOffset = nodeOffset(currentNode);
+ const int nodeTextLength = nodeLength(currentNode);
+ if (isInNodeDefinition(nodeTextOffset, nodeTextLength, cursorPosition)
+ && (nodeTextOffset > nearestNodeTextOffset)) {
+ nearestNode = currentNode;
+ nearestNodeTextOffset = nodeTextOffset;
+ }
+ }
+
+ return nearestNode;
+}
+
bool RewriterView::renameId(const QString& oldId, const QString& newId)
{
if (textModifier())
@@ -677,6 +714,29 @@ QString RewriterView::convertTypeToImportAlias(const QString &type) const
return result;
}
+QString RewriterView::pathForImport(const Import &import)
+{
+ if (scopeChain() && scopeChain()->context() && document()) {
+ const QString importStr = import.isFileImport() ? import.file() : import.url();
+ const QmlJS::Imports *imports = scopeChain()->context()->imports(document());
+
+ QmlJS::ImportInfo importInfo;
+
+ foreach (QmlJS::Import qmljsImport, imports->all()) {
+ if (qmljsImport.info.name() == importStr)
+ importInfo = qmljsImport.info;
+ }
+ const QString importPath = importInfo.path();
+ return importPath;
+ }
+
+ return QString();
+}
+
+QWidget *RewriterView::widget()
+{
+ return 0;
+}
void RewriterView::qmlTextChanged()
{
@@ -695,9 +755,8 @@ void RewriterView::qmlTextChanged()
switch (m_differenceHandling) {
case Validate: {
ModelValidator differenceHandler(m_textToModelMerger.data());
- if (m_textToModelMerger->load(newQmlText.toUtf8(), differenceHandler)) {
+ if (m_textToModelMerger->load(newQmlText.toUtf8(), differenceHandler))
lastCorrectQmlSource = newQmlText;
- }
break;
}
@@ -705,9 +764,8 @@ void RewriterView::qmlTextChanged()
default: {
emitCustomNotification(StartRewriterAmend);
ModelAmender differenceHandler(m_textToModelMerger.data());
- if (m_textToModelMerger->load(newQmlText, differenceHandler)) {
+ if (m_textToModelMerger->load(newQmlText, differenceHandler))
lastCorrectQmlSource = newQmlText;
- }
emitCustomNotification(EndRewriterAmend);
break;
}
diff --git a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
index 4c425d9a4a..b439d850e5 100644
--- a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.cpp
@@ -32,6 +32,7 @@
#include "filemanager/firstdefinitionfinder.h"
#include "filemanager/objectlengthcalculator.h"
#include "filemanager/qmlrefactoring.h"
+#include "filemanager/qmlwarningdialog.h"
#include "rewriteaction.h"
#include "nodeproperty.h"
#include "propertyparser.h"
@@ -66,7 +67,7 @@ namespace {
static inline QStringList supportedVersionsList()
{
QStringList list;
- list << QLatin1String("1.0") << QLatin1String("1.1");
+ list << QLatin1String("1.0") << QLatin1String("1.1") << QLatin1String("2.0");
return list;
}
@@ -138,27 +139,6 @@ static inline QString fixEscapedUnicodeChar(const QString &value) //convert "\u2
}
return value;
}
-
-static inline int fixUpMajorVersionForQt(const QString &value, int i)
-{
- if (i == 4 && value == "Qt")
- return 1;
- else return i;
-}
-
-static inline int fixUpMinorVersionForQt(const QString &value, int i)
-{
- if (i == 7 && value == "Qt")
- return 0;
- else return i;
-}
-
-static inline QString fixUpPackeNameForQt(const QString &value)
-{
- if (value == "Qt")
- return "QtQuick";
- return value;
-}
static inline bool isSignalPropertyName(const QString &signalName)
{
@@ -278,15 +258,14 @@ static bool isCustomParserType(const QString &type)
static bool isPropertyChangesType(const QString &type)
-{
+{
return type == QLatin1String("PropertyChanges") || type == QLatin1String("QtQuick.PropertyChanges") || type == QLatin1String("Qt.PropertyChanges");
}
static bool propertyIsComponentType(const QmlDesigner::NodeAbstractProperty &property, const QString &type, QmlDesigner::Model *model)
{
- if (model->metaInfo(type, -1, -1).isSubclassOf(QLatin1String("QtQuick.Component"), -1, -1) && !isComponentType(type)) {
+ if (model->metaInfo(type, -1, -1).isSubclassOf(QLatin1String("QtQuick.Component"), -1, -1) && !isComponentType(type))
return false; //If the type is already a subclass of Component keep it
- }
return property.parentModelNode().isValid() &&
isComponentType(property.parentModelNode().metaInfo().propertyTypeName(property.name()));
@@ -301,16 +280,14 @@ static inline QString extractComponentFromQml(const QString &source)
if (source.contains("Component")) { //explicit component
QmlDesigner::FirstDefinitionFinder firstDefinitionFinder(source);
int offset = firstDefinitionFinder(0);
- if (offset < 0) {
+ if (offset < 0)
return QString(); //No object definition found
- }
QmlDesigner::ObjectLengthCalculator objectLengthCalculator;
unsigned length;
- if (objectLengthCalculator(source, offset, length)) {
+ if (objectLengthCalculator(source, offset, length))
result = source.mid(offset, length);
- } else {
+ else
result = source;
- }
} else {
result = source; //implicit component
}
@@ -357,11 +334,10 @@ public:
const CppComponentValue * qmlValue = value_cast<CppComponentValue>(value);
if (qmlValue) {
- typeName = fixUpPackeNameForQt(qmlValue->moduleName()) + QLatin1String(".") + qmlValue->className();
+ typeName = qmlValue->moduleName() + QLatin1String(".") + qmlValue->className();
- //### todo this is just a hack to support QtQuick 1.0
- majorVersion = fixUpMajorVersionForQt(qmlValue->moduleName(), qmlValue->componentVersion().majorVersion());
- minorVersion = fixUpMinorVersionForQt(qmlValue->moduleName(), qmlValue->componentVersion().minorVersion());
+ majorVersion = qmlValue->componentVersion().majorVersion();
+ minorVersion = qmlValue->componentVersion().minorVersion();
} else {
for (UiQualifiedId *iter = astTypeNode; iter; iter = iter->next)
if (!iter->next && !iter->name.isEmpty())
@@ -550,20 +526,25 @@ public:
}
}
- QVariant v(cleanedValue);
+ if (property->asColorValue())
+ return PropertyParser::read(QVariant::Color, cleanedValue);
+ else if (property->asUrlValue())
+ return PropertyParser::read(QVariant::Url, cleanedValue);
+
+ QVariant value(cleanedValue);
if (property->asBooleanValue()) {
- v.convert(QVariant::Bool);
- } else if (property->asColorValue()) {
- v.convert(QVariant::Color);
+ value.convert(QVariant::Bool);
+ return value;
} else if (property->asNumberValue()) {
- v.convert(QVariant::Double);
+ value.convert(QVariant::Double);
+ return value;
} else if (property->asStringValue()) {
// nothing to do
} else { //property alias et al
if (!hasQuotes)
return cleverConvert(cleanedValue);
}
- return v;
+ return value;
}
QVariant convertToEnum(Statement *rhs, const QString &propertyPrefix, UiQualifiedId *propertyId)
@@ -574,9 +555,8 @@ public:
const ObjectValue *containingObject = 0;
QString name;
- if (!lookupProperty(propertyPrefix, propertyId, 0, &containingObject, &name)) {
+ if (!lookupProperty(propertyPrefix, propertyId, 0, &containingObject, &name))
return QVariant();
- }
if (containingObject)
containingObject->lookupMember(name, m_context, &containingObject);
@@ -648,16 +628,14 @@ static inline bool smartVeryFuzzyCompare(QVariant value1, QVariant value2)
if (!ok1 || !ok2)
return false;
- if (qFuzzyCompare(a, b)) {
+ if (qFuzzyCompare(a, b))
return true;
- }
int ai = qRound(a * 1000);
int bi = qRound(b * 1000);
- if (qFuzzyCompare((qreal(ai) / 1000), (qreal(bi) / 1000))) {
+ if (qFuzzyCompare((qreal(ai) / 1000), (qreal(bi) / 1000)))
return true;
- }
}
return false;
}
@@ -762,6 +740,7 @@ bool TextToModelMerger::load(const QString &data, DifferenceHandler &differenceH
m_document = doc;
QList<RewriterView::Error> errors;
+ QList<RewriterView::Error> warnings;
foreach (const QmlJS::DiagnosticMessage &diagnosticMessage, ctxt.diagnosticLinkMessages()) {
errors.append(RewriterView::Error(diagnosticMessage, QUrl::fromLocalFile(doc->fileName())));
@@ -788,9 +767,26 @@ bool TextToModelMerger::load(const QString &data, DifferenceHandler &differenceH
check.disableMessage(StaticAnalysis::ErrPrototypeCycle);
check.disableMessage(StaticAnalysis::ErrCouldNotResolvePrototype);
check.disableMessage(StaticAnalysis::ErrCouldNotResolvePrototypeOf);
+
+ foreach (StaticAnalysis::Type type, StaticAnalysis::Message::allMessageTypes()) {
+ StaticAnalysis::Message message(type, AST::SourceLocation());
+ if (message.severity == StaticAnalysis::MaybeWarning
+ || message.severity == StaticAnalysis::Warning) {
+ check.disableMessage(type);
+ }
+ }
+
+ check.enableMessage(StaticAnalysis::WarnImperativeCodeNotEditableInVisualDesigner);
+ check.enableMessage(StaticAnalysis::WarnUnsupportedTypeInVisualDesigner);
+ check.enableMessage(StaticAnalysis::WarnReferenceToParentItemNotSupportedByVisualDesigner);
+ check.enableMessage(StaticAnalysis::WarnUndefinedValueForVisualDesigner);
+ check.enableMessage(StaticAnalysis::WarnStatesOnlyInRootItemForVisualDesigner);
+
foreach (const StaticAnalysis::Message &message, check()) {
if (message.severity == StaticAnalysis::Error)
errors.append(RewriterView::Error(message.toDiagnosticMessage(), QUrl::fromLocalFile(doc->fileName())));
+ if (message.severity == StaticAnalysis::Warning)
+ warnings.append(RewriterView::Error(message.toDiagnosticMessage(), QUrl::fromLocalFile(doc->fileName())));
}
if (!errors.isEmpty()) {
@@ -798,6 +794,27 @@ bool TextToModelMerger::load(const QString &data, DifferenceHandler &differenceH
setActive(false);
return false;
}
+
+ if (!warnings.isEmpty() && differenceHandler.isValidator()) {
+
+ QString title = QCoreApplication::translate("QmlDesigner::TextToModelMerger warning message", "This .qml file contains features"
+ "which are not supported by Qt Quick Designer");
+
+ QStringList message;
+
+ foreach (const RewriterView::Error &warning, warnings) {
+ QString string = QLatin1String("Line: ") + QString::number(warning.line()) + QLatin1String(": ") + warning.description();
+ //string += QLatin1String(" <a href=\"") + QString::number(warning.line()) + QLatin1String("\">Go to error</a>") + QLatin1String("<p>");
+ message << string;
+ }
+
+ QmlWarningDialog warningDialog(0, message);
+ if (warningDialog.warningsEnabled() && warningDialog.exec()) {
+ m_rewriterView->setErrors(warnings);
+ setActive(false);
+ return false;
+ }
+ }
}
UiObjectMember *astRootNode = 0;
@@ -929,11 +946,10 @@ void TextToModelMerger::syncNode(ModelNode &modelNode,
QString name;
if (context->lookupProperty(QString(), binding->qualifiedId, &propertyType, &containingObject, &name) || isPropertyChangesType(typeName)) {
AbstractProperty modelProperty = modelNode.property(astPropertyName);
- if (context->isArrayProperty(propertyType, containingObject, name)) {
+ if (context->isArrayProperty(propertyType, containingObject, name))
syncArrayProperty(modelProperty, QList<QmlJS::AST::UiObjectMember*>() << member, context, differenceHandler);
- } else {
+ else
syncNodeProperty(modelProperty, binding, context, differenceHandler);
- }
modelPropertyNames.remove(astPropertyName);
} else {
qWarning() << "Skipping invalid node property" << astPropertyName
@@ -1406,11 +1422,10 @@ void ModelAmender::bindingExpressionsDiffer(BindingProperty &modelProperty,
const QString &javascript,
const QString &astType)
{
- if (astType.isEmpty()) {
+ if (astType.isEmpty())
modelProperty.setExpression(javascript);
- } else {
+ else
modelProperty.setDynamicTypeNameAndExpression(astType, javascript);
- }
}
void ModelAmender::shouldBeBindingProperty(AbstractProperty &modelProperty,
@@ -1419,11 +1434,10 @@ void ModelAmender::shouldBeBindingProperty(AbstractProperty &modelProperty,
{
ModelNode theNode = modelProperty.parentModelNode();
BindingProperty newModelProperty = theNode.bindingProperty(modelProperty.name());
- if (astType.isEmpty()) {
+ if (astType.isEmpty())
newModelProperty.setExpression(javascript);
- } else {
+ else
newModelProperty.setDynamicTypeNameAndExpression(astType, javascript);
- }
}
void ModelAmender::shouldBeNodeListProperty(AbstractProperty &modelProperty,
@@ -1543,7 +1557,7 @@ ModelNode ModelAmender::listPropertyMissingModelNode(NodeListProperty &modelProp
modelProperty.reparentHere(newNode);
} else { //The default property could a NodeProperty implicitly (delegate:)
modelProperty.parentModelNode().removeProperty(modelProperty.name());
- modelProperty.reparentHere(newNode);
+ modelProperty.reparentHere(newNode);
}
} else {
modelProperty.reparentHere(newNode);
@@ -1611,9 +1625,8 @@ void TextToModelMerger::setupComponent(const ModelNode &node)
QString result = extractComponentFromQml(componentText);
- if (result.isEmpty()) {
+ if (result.isEmpty())
return; //No object definition found
- }
if (node.nodeSource() != result)
ModelNode(node).setNodeSource(result);
diff --git a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.h b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.h
index 6e304247d6..2299f8e9c6 100644
--- a/src/plugins/qmldesigner/designercore/model/texttomodelmerger.h
+++ b/src/plugins/qmldesigner/designercore/model/texttomodelmerger.h
@@ -30,7 +30,7 @@
#ifndef TEXTTOMODELMERGER_H
#define TEXTTOMODELMERGER_H
-#include "corelib_global.h"
+#include "qmldesignercorelib_global.h"
#include "import.h"
#include "nodelistproperty.h"
#include "modelnode.h"
@@ -43,7 +43,7 @@
namespace QmlDesigner {
-class CORESHARED_EXPORT RewriterView;
+class RewriterView;
namespace Internal {
diff --git a/src/plugins/qmldesigner/designercore/model/variantproperty.cpp b/src/plugins/qmldesigner/designercore/model/variantproperty.cpp
index 801081a334..a8418b5e8f 100644
--- a/src/plugins/qmldesigner/designercore/model/variantproperty.cpp
+++ b/src/plugins/qmldesigner/designercore/model/variantproperty.cpp
@@ -102,9 +102,8 @@ void VariantProperty::setDynamicTypeNameAndValue(const QString &type, const QVar
throw InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);
- if (type.isEmpty()) {
+ if (type.isEmpty())
throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, name());
- }
if (internalNode()->hasProperty(name())) { //check if oldValue != value
Internal::InternalProperty::Pointer internalProperty = internalNode()->property(name());
diff --git a/src/plugins/qmldesigner/designercore/model/viewlogger.cpp b/src/plugins/qmldesigner/designercore/model/viewlogger.cpp
index 7db3c3a025..584ff80b2e 100644
--- a/src/plugins/qmldesigner/designercore/model/viewlogger.cpp
+++ b/src/plugins/qmldesigner/designercore/model/viewlogger.cpp
@@ -31,6 +31,7 @@
#include <QDebug>
#include <QTemporaryFile>
#include <QDir>
+#include <QUrl>
#include <variantproperty.h>
#include <bindingproperty.h>
#include <nodeabstractproperty.h>
@@ -64,23 +65,24 @@ QString ViewLogger::time() const
ViewLogger::ViewLogger(QObject *parent)
: AbstractView(parent)
{
- const QString path = QDir::tempPath() + QString("/qmldesigner-logger-%1-XXXXXX.txt").
+ m_timer.start();
+}
+
+void ViewLogger::modelAttached(Model *model)
+{
+ static const QString path = QDir::tempPath() + QString("/qmldesigner-logger-%1-XXXXXX.txt").
arg(QDateTime::currentDateTime().toString(Qt::ISODate).
replace(':', '-'));
- QTemporaryFile *temporaryFile = new QTemporaryFile(path, this);
+ static QTemporaryFile *temporaryFile = new QTemporaryFile(path, this);
temporaryFile->setAutoRemove(false);
- if (temporaryFile->open()) {
+ static bool fileOpen = temporaryFile->open();
+ if (fileOpen) {
qDebug() << "QmlDesigner: Log file is:" << temporaryFile->fileName();
m_output.setDevice(temporaryFile);
} else {
qDebug() << "QmlDesigner: failed to open:" << temporaryFile->fileName();
}
- m_timer.start();
-}
-
-void ViewLogger::modelAttached(Model *model)
-{
m_output << time() << indent("modelAttached:") << model << endl;
AbstractView::modelAttached(model);
}
@@ -139,14 +141,14 @@ void ViewLogger::propertiesRemoved(const QList<AbstractProperty> &propertyList)
void ViewLogger::variantPropertiesChanged(const QList<VariantProperty>& propertyList, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("variantPropertiesChanged:") << serialize(propertyChange) << endl;
- foreach(const VariantProperty &property, propertyList)
+ foreach (const VariantProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
void ViewLogger::bindingPropertiesChanged(const QList<BindingProperty>& propertyList, PropertyChangeFlags propertyChange)
{
m_output << time() << indent("bindingPropertiesChanged:") << serialize(propertyChange) << endl;
- foreach(const BindingProperty &property, propertyList)
+ foreach (const BindingProperty &property, propertyList)
m_output << time() << indent() << property << endl;
}
@@ -159,9 +161,9 @@ void ViewLogger::selectedNodesChanged(const QList<ModelNode> &selectedNodeList,
const QList<ModelNode> &lastSelectedNodeList)
{
m_output << time() << indent("selectedNodesChanged:") << endl;
- foreach(const ModelNode &node, selectedNodeList)
+ foreach (const ModelNode &node, selectedNodeList)
m_output << time() << indent("new: ") << node << endl;
- foreach(const ModelNode &node, lastSelectedNodeList)
+ foreach (const ModelNode &node, lastSelectedNodeList)
m_output << time() << indent("old: ") << node << endl;
}
@@ -183,18 +185,18 @@ void ViewLogger::auxiliaryDataChanged(const ModelNode &node, const QString &name
void ViewLogger::importsChanged(const QList<Import> &addedImports, const QList<Import> &removedImports)
{
m_output << time() << indent("importsChanged:") << endl;
- foreach(const Import &import, addedImports)
+ foreach (const Import &import, addedImports)
m_output << time() << indent("import added: ") << import.toString() << endl;
- foreach(const Import &import, removedImports)
+ foreach (const Import &import, removedImports)
m_output << time() << indent("import removed: ") << import.toString() << endl;
}
void ViewLogger::customNotification(const AbstractView *view, const QString &identifier, const QList<ModelNode> &nodeList, const QList<QVariant> &data)
{
m_output << time() << indent("customNotification:") << view << identifier << endl;
- foreach(const ModelNode &node, nodeList)
+ foreach (const ModelNode &node, nodeList)
m_output << time() << indent("node: ") << node << endl;
- foreach(const QVariant &variant, data)
+ foreach (const QVariant &variant, data)
m_output << time() << indent("data: ") << variant.toString() << endl;
}
@@ -208,7 +210,7 @@ void ViewLogger::instancePropertyChange(const QList<QPair<ModelNode, QString> >
typedef QPair<ModelNode, QString> PropertyPair;
m_output << time() << indent("instancePropertyChange:") << endl;
- foreach(const PropertyPair &propertyPair, propertyList)
+ foreach (const PropertyPair &propertyPair, propertyList)
m_output << time() << indent("property: ") << propertyPair.first << propertyPair.second << endl;
}
@@ -216,7 +218,7 @@ void ViewLogger::instancesCompleted(const QVector<ModelNode> &completedNodeList)
{
m_output << time() << indent("instancesCompleted:") << endl;
- foreach(const ModelNode &node, completedNodeList)
+ foreach (const ModelNode &node, completedNodeList)
m_output << time() << indent("node: ") << node << endl;
}
@@ -237,7 +239,7 @@ void ViewLogger::instancesRenderImageChanged(const QVector<ModelNode> &nodeList)
{
m_output << time() << indent("instancesRenderImageChanged:") << endl;
- foreach(const ModelNode &node, nodeList)
+ foreach (const ModelNode &node, nodeList)
m_output << time() << indent("node: ") << node << endl;
}
@@ -245,7 +247,7 @@ void ViewLogger::instancesPreviewImageChanged(const QVector<ModelNode> &nodeList
{
m_output << time() << indent("instancesPreviewImageChanged:") << endl;
- foreach(const ModelNode &node, nodeList)
+ foreach (const ModelNode &node, nodeList)
m_output << time() << indent("node: ") << node << endl;
}
@@ -253,7 +255,7 @@ void ViewLogger::instancesChildrenChanged(const QVector<ModelNode> &nodeList)
{
m_output << time() << indent("instancesChildrenChanged:") << endl;
- foreach(const ModelNode &node, nodeList)
+ foreach (const ModelNode &node, nodeList)
m_output << time() << indent("node: ") << node << endl;
}
@@ -284,5 +286,10 @@ void ViewLogger::actualStateChanged(const ModelNode &node)
{
m_output << time() << indent("actualStateChanged:") << node << endl;
}
+
+QWidget *ViewLogger::widget()
+{
+ return 0;
+}
} // namespace Internal
} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/model/viewlogger.h b/src/plugins/qmldesigner/designercore/model/viewlogger.h
index 0ca17dad41..58ca0c167c 100644
--- a/src/plugins/qmldesigner/designercore/model/viewlogger.h
+++ b/src/plugins/qmldesigner/designercore/model/viewlogger.h
@@ -42,7 +42,7 @@ class ViewLogger : public QmlDesigner::AbstractView
{
Q_OBJECT
public:
- ViewLogger(QObject *parent);
+ ViewLogger(QObject *parent = 0);
void modelAttached(Model *model);
void modelAboutToBeDetached(Model *model);
@@ -87,6 +87,8 @@ public:
void actualStateChanged(const ModelNode &node);
+ QWidget *widget();
+
protected:
QString time() const;
diff --git a/src/plugins/qmldesigner/designercore/model/viewmanager.cpp b/src/plugins/qmldesigner/designercore/model/viewmanager.cpp
new file mode 100644
index 0000000000..24eda7730d
--- /dev/null
+++ b/src/plugins/qmldesigner/designercore/model/viewmanager.cpp
@@ -0,0 +1,201 @@
+#include "viewmanager.h"
+
+#include "designdocument.h"
+#include "componentaction.h"
+#include "itemlibrarywidget.h"
+#include "designmodewidget.h"
+#include "formeditorwidget.h"
+#include "toolbox.h"
+#include "designeractionmanager.h"
+
+#include <qmldesigner/qmldesignerplugin.h>
+
+#include <utils/crumblepath.h>
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtversionmanager.h>
+#include <qtsupport/qtsupportconstants.h>
+
+namespace QmlDesigner {
+
+ViewManager::ViewManager()
+{
+ //QObject::connect(&m_nodeInstanceView, SIGNAL(qmlPuppetCrashed()), designModeWidget, SLOT(qmlPuppetCrashed()));
+ //QObject::connect(m_formEditorView.crumblePath(), SIGNAL(elementClicked(QVariant)), designModeWidget, SLOT(onCrumblePathElementClicked(QVariant)));
+ m_formEditorView.formEditorWidget()->toolBox()->addLeftSideAction(m_componentView.action()); // ugly hack
+}
+
+DesignDocument *ViewManager::currentDesignDocument() const
+{
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
+}
+
+QString ViewManager::pathToQt() const
+{
+ QtSupport::BaseQtVersion *activeQtVersion = QtSupport::QtVersionManager::instance()->version(currentDesignDocument()->qtVersionId());
+ if (activeQtVersion && (activeQtVersion->qtVersion() >= QtSupport::QtVersionNumber(4, 7, 1))
+ && (activeQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)
+ || activeQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)))
+ return activeQtVersion->qmakeProperty("QT_INSTALL_DATA");
+
+ return QString();
+}
+
+void ViewManager::attachNodeInstanceView()
+{
+ setNodeInstanceViewQtPath(pathToQt());
+ currentModel()->setNodeInstanceView(&m_nodeInstanceView);
+}
+
+void ViewManager::attachRewriterView(TextModifier *textModifier)
+{
+ if (currentDesignDocument()->rewriterView()) {
+ currentDesignDocument()->rewriterView()->setTextModifier(textModifier);
+ currentDesignDocument()->rewriterView()->reactivateTextMofifierChangeSignals();
+ currentModel()->setRewriterView(currentDesignDocument()->rewriterView());
+ }
+}
+
+void ViewManager::detachRewriterView()
+{
+ if (currentDesignDocument()->rewriterView()) {
+ currentDesignDocument()->rewriterView()->deactivateTextMofifierChangeSignals();
+ currentModel()->setRewriterView(0);
+ }
+}
+
+void ViewManager::switchStateEditorViewToBaseState()
+{
+ if (m_statesEditorView.isAttached()) {
+ m_savedState = m_statesEditorView.currentState();
+ m_statesEditorView.setCurrentState(m_statesEditorView.baseState());
+ }
+}
+
+void ViewManager::switchStateEditorViewToSavedState()
+{
+ if (m_savedState.isValid() && m_statesEditorView.isAttached())
+ m_statesEditorView.setCurrentState(m_savedState);
+}
+
+void ViewManager::resetPropertyEditorView()
+{
+ m_propertyEditorView.resetView();
+}
+
+void ViewManager::detachViewsExceptRewriterAndComponetView()
+{
+ switchStateEditorViewToBaseState();
+ currentModel()->detachView(DesignerActionManager::view());
+ currentModel()->detachView(&m_formEditorView);
+ currentModel()->detachView(&m_navigatorView);
+ currentModel()->detachView(&m_itemLibraryView);
+ currentModel()->detachView(&m_statesEditorView);
+ currentModel()->detachView(&m_propertyEditorView);
+ currentModel()->setNodeInstanceView(0);
+
+ static bool enableViewLogger = !qgetenv("QTC_ENABLE_QMLDESIGNER_LOGGER").isEmpty();
+ if (enableViewLogger)
+ currentModel()->detachView(&m_viewLogger);
+}
+
+void ViewManager::attachItemLibraryView()
+{
+ setItemLibraryViewResourcePath(QFileInfo(currentDesignDocument()->fileName()).absolutePath());
+ currentModel()->attachView(&m_itemLibraryView);
+}
+
+void ViewManager::attachComponentView()
+{
+ documentModel()->attachView(&m_componentView);
+ QObject::connect(m_componentView.action(), SIGNAL(currentComponentChanged(ModelNode)), currentDesignDocument(), SLOT(changeCurrentModelTo(ModelNode)));
+}
+
+void ViewManager::detachComponentView()
+{
+ QObject::disconnect(m_componentView.action(), SIGNAL(currentComponentChanged(ModelNode)), currentDesignDocument(), SLOT(changeCurrentModelTo(ModelNode)));
+ documentModel()->detachView(&m_componentView);
+}
+
+void ViewManager::attachViewsExceptRewriterAndComponetView()
+{
+ static bool enableViewLogger = !qgetenv("QTC_ENABLE_QMLDESIGNER_LOGGER").isEmpty();
+ if (enableViewLogger)
+ currentModel()->attachView(&m_viewLogger);
+
+ attachNodeInstanceView();
+ currentModel()->attachView(&m_formEditorView);
+ currentModel()->attachView(&m_navigatorView);
+ attachItemLibraryView();
+ currentModel()->attachView(&m_statesEditorView);
+ currentModel()->attachView(&m_propertyEditorView);
+ currentModel()->attachView(DesignerActionManager::view());
+ switchStateEditorViewToSavedState();
+}
+
+void ViewManager::setItemLibraryViewResourcePath(const QString &resourcePath)
+{
+ m_itemLibraryView.setResourcePath(resourcePath);
+}
+
+void ViewManager::setComponentNode(const ModelNode &componentNode)
+{
+ m_componentView.setComponentNode(componentNode);
+}
+
+void ViewManager::setNodeInstanceViewQtPath(const QString &qtPath)
+{
+ m_nodeInstanceView.setPathToQt(qtPath);
+}
+
+QWidget *ViewManager::formEditorWidget()
+{
+ return m_formEditorView.widget();
+}
+
+QWidget *ViewManager::propertyEditorWidget()
+{
+ return m_propertyEditorView.widget();
+}
+
+QWidget *ViewManager::itemLibraryWidget()
+{
+ return m_itemLibraryView.widget();
+}
+
+QWidget *ViewManager::navigatorWidget()
+{
+ return m_navigatorView.widget();
+}
+
+QWidget *ViewManager::statesEditorWidget()
+{
+ return m_statesEditorView.widget();
+}
+
+void ViewManager::pushFileOnCrambleBar(const QString &fileName)
+{
+ m_formEditorView.formEditorWidget()->formEditorCrumbleBar()->pushFile(fileName);
+}
+
+void ViewManager::pushInFileComponentOnCrambleBar(const QString &componentId)
+
+{
+ m_formEditorView.formEditorWidget()->formEditorCrumbleBar()->pushInFileComponent(componentId);
+}
+
+void ViewManager::nextFileIsCalledInternally()
+{
+ m_formEditorView.formEditorWidget()->formEditorCrumbleBar()->nextFileIsCalledInternally();
+}
+
+Model *ViewManager::currentModel() const
+{
+ return currentDesignDocument()->currentModel();
+}
+
+Model *ViewManager::documentModel() const
+{
+ return currentDesignDocument()->documentModel();
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.cpp b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.cpp
index f0a3c0015f..e9e7d81006 100644
--- a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.cpp
+++ b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.cpp
@@ -28,7 +28,6 @@
****************************************************************************/
#include "widgetpluginmanager.h"
-#include "widgetpluginpath.h"
#include <iwidgetplugin.h>
#include <QCoreApplication>
@@ -51,28 +50,15 @@ namespace QmlDesigner {
namespace Internal {
-// ---- PluginManager[Private]
-class WidgetPluginManagerPrivate {
-public:
- typedef QList<WidgetPluginPath> PluginPathList;
- PluginPathList m_paths;
-};
-
-WidgetPluginManager::WidgetPluginManager() :
- d(new WidgetPluginManagerPrivate)
-{
-}
-
-WidgetPluginManager::~WidgetPluginManager()
+WidgetPluginManager::WidgetPluginManager()
{
- delete d;
}
WidgetPluginManager::IWidgetPluginList WidgetPluginManager::instances()
{
IWidgetPluginList rc;
- const WidgetPluginManagerPrivate::PluginPathList::iterator end = d->m_paths.end();
- for (WidgetPluginManagerPrivate::PluginPathList::iterator it = d->m_paths.begin(); it != end; ++it)
+ const PluginPathList::iterator end = m_paths.end();
+ for (PluginPathList::iterator it = m_paths.begin(); it != end; ++it)
it->getInstances(&rc);
if (debug)
qDebug() << '<' << Q_FUNC_INFO << rc.size();
@@ -84,15 +70,15 @@ bool WidgetPluginManager::addPath(const QString &path)
const QDir dir(path);
if (!dir.exists())
return false;
- d->m_paths.push_back(WidgetPluginPath(dir));
+ m_paths.push_back(WidgetPluginPath(dir));
return true;
}
QAbstractItemModel *WidgetPluginManager::createModel(QObject *parent)
{
QStandardItemModel *model = new QStandardItemModel(parent);
- const WidgetPluginManagerPrivate::PluginPathList::iterator end = d->m_paths.end();
- for (WidgetPluginManagerPrivate::PluginPathList::iterator it = d->m_paths.begin(); it != end; ++it)
+ const PluginPathList::iterator end = m_paths.end();
+ for (PluginPathList::iterator it = m_paths.begin(); it != end; ++it)
model->appendRow(it->createModelItem());
return model;
}
diff --git a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.h b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.h
index e5d4dde6fa..69e48331ee 100644
--- a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.h
+++ b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginmanager.h
@@ -33,6 +33,9 @@
#include <QObject>
#include <QList>
+#include "widgetpluginpath.h"
+
+
QT_BEGIN_NAMESPACE
class QString;
class QAbstractItemModel;
@@ -44,8 +47,6 @@ class IWidgetPlugin;
namespace Internal {
-class WidgetPluginManagerPrivate;
-
// PluginManager: Loads the plugin libraries on demand "as lazy as
// possible", that is, directories are scanned and
// instances are created only when instances() is called.
@@ -53,11 +54,11 @@ class WidgetPluginManagerPrivate;
class WidgetPluginManager
{
Q_DISABLE_COPY(WidgetPluginManager)
+ typedef QList<WidgetPluginPath> PluginPathList;
public:
typedef QList<IWidgetPlugin *> IWidgetPluginList;
WidgetPluginManager();
- ~WidgetPluginManager();
bool addPath(const QString &path);
@@ -68,7 +69,7 @@ public:
QAbstractItemModel *createModel(QObject *parent = 0);
private:
- WidgetPluginManagerPrivate *d;
+ PluginPathList m_paths;
};
} // namespace Internal
diff --git a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp
index 273595add9..bdd91667a2 100644
--- a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp
+++ b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.cpp
@@ -172,7 +172,7 @@ void WidgetPluginPath::ensureLoaded()
}
}
-void WidgetPluginPath::getInstances(WidgetPluginManager::IWidgetPluginList *list)
+void WidgetPluginPath::getInstances(IWidgetPluginList *list)
{
ensureLoaded();
// Compile list of instances
diff --git a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.h b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.h
index 2046dd0048..0857f1d1da 100644
--- a/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.h
+++ b/src/plugins/qmldesigner/designercore/pluginmanager/widgetpluginpath.h
@@ -30,8 +30,6 @@
#ifndef WIDGETPLUGINPATH_H
#define WIDGETPLUGINPATH_H
-#include "widgetpluginmanager.h"
-
#include <QObject>
#include <QWeakPointer>
#include <QList>
@@ -73,11 +71,12 @@ struct WidgetPluginData {
// IPlugins.
class WidgetPluginPath {
+ typedef QList<IWidgetPlugin *> IWidgetPluginList;
public:
explicit WidgetPluginPath(const QDir &path);
- void getInstances(WidgetPluginManager::IWidgetPluginList *list);
+ void getInstances(IWidgetPluginList *list);
QDir path() const { return m_path; }
diff --git a/src/plugins/qmldesigner/designercore/preview/stylemanager.cpp b/src/plugins/qmldesigner/designercore/preview/stylemanager.cpp
index 0c6340ef5d..be81bbae27 100644
--- a/src/plugins/qmldesigner/designercore/preview/stylemanager.cpp
+++ b/src/plugins/qmldesigner/designercore/preview/stylemanager.cpp
@@ -87,7 +87,7 @@ QString StyleManager::applicationStyle()
QStyle *applicationStyle = qApp->style();
QStyle *style;
if (applicationStyle)
- foreach(const QString &name, styles())
+ foreach (const QString &name, styles())
if ((style = QStyleFactory::create(name)) &&
(applicationStyle->metaObject()->className() ==
style->metaObject()->className()))
diff --git a/src/plugins/qmldesigner/designersettings.cpp b/src/plugins/qmldesigner/designersettings.cpp
index 3c0ce5c1d2..f1e30fb06a 100644
--- a/src/plugins/qmldesigner/designersettings.cpp
+++ b/src/plugins/qmldesigner/designersettings.cpp
@@ -39,7 +39,9 @@ DesignerSettings::DesignerSettings()
itemSpacing(0),
snapMargin(0),
canvasWidth(10000),
- canvasHeight(10000)
+ canvasHeight(10000),
+ warningsInDesigner(true),
+ designerWarningsInEditor(false)
{}
void DesignerSettings::fromSettings(QSettings *settings)
@@ -55,6 +57,11 @@ void DesignerSettings::fromSettings(QSettings *settings)
QLatin1String(QmlDesigner::Constants::QML_SNAPMARGIN_KEY), QVariant(0)).toInt();
canvasWidth = settings->value(QLatin1String(QmlDesigner::Constants::QML_CANVASWIDTH_KEY), QVariant(10000)).toInt();
canvasHeight = settings->value(QLatin1String(QmlDesigner::Constants::QML_CANVASHEIGHT_KEY), QVariant(10000)).toInt();
+ warningsInDesigner = settings->value(
+ QLatin1String(QmlDesigner::Constants::QML_WARNIN_FOR_FEATURES_IN_DESIGNER_KEY), QVariant(true)).toBool();
+ designerWarningsInEditor = settings->value(
+ QLatin1String(QmlDesigner::Constants::QML_WARNIN_FOR_DESIGNER_FEATURES_IN_EDITOR_KEY), QVariant(false)).toBool();
+
settings->endGroup();
settings->endGroup();
}
@@ -68,6 +75,9 @@ void DesignerSettings::toSettings(QSettings *settings) const
settings->setValue(QLatin1String(QmlDesigner::Constants::QML_SNAPMARGIN_KEY), snapMargin);
settings->setValue(QLatin1String(QmlDesigner::Constants::QML_CANVASWIDTH_KEY), canvasWidth);
settings->setValue(QLatin1String(QmlDesigner::Constants::QML_CANVASHEIGHT_KEY), canvasHeight);
+ settings->setValue(QLatin1String(QmlDesigner::Constants::QML_WARNIN_FOR_FEATURES_IN_DESIGNER_KEY), warningsInDesigner);
+ settings->setValue(QLatin1String(QmlDesigner::Constants::QML_WARNIN_FOR_DESIGNER_FEATURES_IN_EDITOR_KEY), designerWarningsInEditor);
+
settings->endGroup();
settings->endGroup();
}
@@ -77,5 +87,7 @@ bool DesignerSettings::equals(const DesignerSettings &other) const
return openDesignMode == other.openDesignMode
&& snapMargin == other.snapMargin
&& canvasWidth == other.canvasWidth
- && canvasHeight == other.canvasHeight;
+ && canvasHeight == other.canvasHeight
+ && warningsInDesigner == other.warningsInDesigner
+ && designerWarningsInEditor == other.designerWarningsInEditor;
}
diff --git a/src/plugins/qmldesigner/designersettings.h b/src/plugins/qmldesigner/designersettings.h
index 26f1a5eee7..3a6e3a8e83 100644
--- a/src/plugins/qmldesigner/designersettings.h
+++ b/src/plugins/qmldesigner/designersettings.h
@@ -49,9 +49,11 @@ public:
bool equals(const DesignerSettings &other) const;
bool openDesignMode;
int itemSpacing;
- int snapMargin;
+ int snapMargin;
int canvasWidth;
int canvasHeight;
+ bool warningsInDesigner;
+ bool designerWarningsInEditor;
};
inline bool operator==(const DesignerSettings &s1, const DesignerSettings &s2)
diff --git a/src/plugins/qmldesigner/designmodewidget.cpp b/src/plugins/qmldesigner/designmodewidget.cpp
index 122cacd715..dced711d08 100644
--- a/src/plugins/qmldesigner/designmodewidget.cpp
+++ b/src/plugins/qmldesigner/designmodewidget.cpp
@@ -31,14 +31,13 @@
#include "qmldesignerconstants.h"
#include "styledoutputpaneplaceholder.h"
#include "designmodecontext.h"
+#include "qmldesignerplugin.h"
#include <model.h>
#include <rewriterview.h>
-#include <formeditorwidget.h>
-#include <stateseditorwidget.h>
-#include <itemlibrarywidget.h>
#include <componentaction.h>
#include <toolbox.h>
+#include <itemlibrarywidget.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/designmode.h>
@@ -93,11 +92,9 @@ const char SB_OPENDOCUMENTS[] = "OpenDocuments";
namespace QmlDesigner {
namespace Internal {
-DesignModeWidget *DesignModeWidget::s_instance = 0;
-
DocumentWarningWidget::DocumentWarningWidget(DesignModeWidget *parent) :
Utils::FakeToolTip(parent),
- m_errorMessage(new QLabel("Placeholder", this)),
+ m_errorMessage(new QLabel(tr("Placeholder"), this)),
m_goToError(new QLabel(this)),
m_designModeWidget(parent)
{
@@ -137,13 +134,13 @@ void DocumentWarningWidget::setError(const RewriterView::Error &error)
class ItemLibrarySideBarItem : public Core::SideBarItem
{
public:
- explicit ItemLibrarySideBarItem(ItemLibraryWidget *widget, const QString &id);
+ explicit ItemLibrarySideBarItem(QWidget *widget, const QString &id);
virtual ~ItemLibrarySideBarItem();
virtual QList<QToolButton *> createToolBarWidgets();
};
-ItemLibrarySideBarItem::ItemLibrarySideBarItem(ItemLibraryWidget *widget, const QString &id) : Core::SideBarItem(widget, id) {}
+ItemLibrarySideBarItem::ItemLibrarySideBarItem(QWidget *widget, const QString &id) : Core::SideBarItem(widget, id) {}
ItemLibrarySideBarItem::~ItemLibrarySideBarItem()
{
@@ -158,13 +155,13 @@ QList<QToolButton *> ItemLibrarySideBarItem::createToolBarWidgets()
class NavigatorSideBarItem : public Core::SideBarItem
{
public:
- explicit NavigatorSideBarItem(NavigatorWidget *widget, const QString &id);
+ explicit NavigatorSideBarItem(QWidget *widget, const QString &id);
virtual ~NavigatorSideBarItem();
virtual QList<QToolButton *> createToolBarWidgets();
};
-NavigatorSideBarItem::NavigatorSideBarItem(NavigatorWidget *widget, const QString &id) : Core::SideBarItem(widget, id) {}
+NavigatorSideBarItem::NavigatorSideBarItem(QWidget *widget, const QString &id) : Core::SideBarItem(widget, id) {}
NavigatorSideBarItem::~NavigatorSideBarItem()
{
@@ -185,7 +182,6 @@ void DocumentWarningWidget::goToError()
// ---------- DesignModeWidget
DesignModeWidget::DesignModeWidget(QWidget *parent) :
QWidget(parent),
- m_syncWithTextEdit(false),
m_mainSplitter(0),
m_leftSideBar(0),
m_rightSideBar(0),
@@ -196,41 +192,10 @@ DesignModeWidget::DesignModeWidget(QWidget *parent) :
m_navigatorHistoryCounter(-1),
m_keepNavigatorHistory(false)
{
- s_instance = this;
- m_undoAction = new QAction(tr("&Undo"), this);
- connect(m_undoAction, SIGNAL(triggered()), this, SLOT(undo()));
- m_redoAction = new QAction(tr("&Redo"), this);
- connect(m_redoAction, SIGNAL(triggered()), this, SLOT(redo()));
- m_deleteAction = new Utils::ParameterAction(tr("Delete"), tr("Delete \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- connect(m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteSelected()));
- m_cutAction = new Utils::ParameterAction(tr("Cu&t"), tr("Cut \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- connect(m_cutAction, SIGNAL(triggered()), this, SLOT(cutSelected()));
- m_copyAction = new Utils::ParameterAction(tr("&Copy"), tr("Copy \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- connect(m_copyAction, SIGNAL(triggered()), this, SLOT(copySelected()));
- m_pasteAction = new Utils::ParameterAction(tr("&Paste"), tr("Paste \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- connect(m_pasteAction, SIGNAL(triggered()), this, SLOT(paste()));
- m_selectAllAction = new Utils::ParameterAction(tr("Select &All"), tr("Select All \"%1\""), Utils::ParameterAction::EnabledWithParameter, this);
- connect(m_selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll()));
- m_hideSidebarsAction = new QAction(tr("Toggle Full Screen"), this);
- connect(m_hideSidebarsAction, SIGNAL(triggered()), this, SLOT(toggleSidebars()));
- m_restoreDefaultViewAction = new QAction(tr("&Restore Default View"), this);
- m_goIntoComponentAction = new QAction(tr("&Go into Component"), this);
- connect(m_restoreDefaultViewAction, SIGNAL(triggered()), SLOT(restoreDefaultView()));
- connect(m_goIntoComponentAction, SIGNAL(triggered()), SLOT(goIntoComponent()));
- m_toggleLeftSidebarAction = new QAction(tr("Toggle &Left Sidebar"), this);
- connect(m_toggleLeftSidebarAction, SIGNAL(triggered()), SLOT(toggleLeftSidebar()));
- m_toggleRightSidebarAction = new QAction(tr("Toggle &Right Sidebar"), this);
- connect(m_toggleRightSidebarAction, SIGNAL(triggered()), SLOT(toggleRightSidebar()));
-
m_outputPlaceholderSplitter = new Core::MiniSplitter;
m_outputPanePlaceholder = new StyledOutputpanePlaceHolder(Core::DesignMode::instance(), m_outputPlaceholderSplitter);
}
-DesignModeWidget::~DesignModeWidget()
-{
- s_instance = 0;
-}
-
void DesignModeWidget::restoreDefaultView()
{
QSettings *settings = Core::ICore::settings();
@@ -265,19 +230,17 @@ void DesignModeWidget::toggleSidebars()
m_leftSideBar->setVisible(m_showSidebars);
if (m_rightSideBar)
m_rightSideBar->setVisible(m_showSidebars);
- if (!m_statesEditorView.isNull())
- m_statesEditorView->widget()->setVisible(m_showSidebars);
+
+ viewManager().statesEditorWidget()->setVisible(m_showSidebars);
}
void DesignModeWidget::showEditor(Core::IEditor *editor)
{
- if (m_textEditor && editor)
- if (m_textEditor->document()->fileName() != editor->document()->fileName()) {
- if (!m_keepNavigatorHistory)
- addNavigatorHistoryEntry(editor->document()->fileName());
- setupNavigatorHistory();
- }
+ if (textEditor()
+ && editor
+ && textEditor()->document()->fileName() != editor->document()->fileName())
+ setupNavigatorHistory(editor);
//
// Prevent recursive calls to function by explicitly managing initialization status
@@ -291,133 +254,16 @@ void DesignModeWidget::showEditor(Core::IEditor *editor)
setup();
}
- QString fileName;
- QPlainTextEdit *textEdit = 0;
- TextEditor::ITextEditor *textEditor = 0;
-
- if (editor) {
- fileName = editor->document()->fileName();
- textEdit = qobject_cast<QPlainTextEdit*>(editor->widget());
- textEditor = qobject_cast<TextEditor::ITextEditor*>(editor);
- if (textEditor)
- m_fakeToolBar->addEditor(textEditor);
- }
-
- if (debug)
- qDebug() << Q_FUNC_INFO << fileName;
-
- if (textEdit)
- m_currentTextEdit = textEdit;
-
- if (textEditor)
- m_textEditor = textEditor;
- DesignDocumentController *document = 0;
- if (textEdit && textEditor && fileName.endsWith(QLatin1String(".qml"))) {
- if (m_documentHash.contains(textEdit)) {
- document = m_documentHash.value(textEdit).data();
- } else {
- DesignDocumentController *newDocument = new DesignDocumentController(this);
+ if (textEditor())
+ m_fakeToolBar->addEditor(textEditor());
- newDocument->setNodeInstanceView(m_nodeInstanceView.data());
- newDocument->setPropertyEditorView(m_propertyEditorView.data());
- newDocument->setNavigator(m_navigatorView.data());
- newDocument->setStatesEditorView(m_statesEditorView.data());
- newDocument->setItemLibraryView(m_itemLibraryView.data());
- newDocument->setFormEditorView(m_formEditorView.data());
- newDocument->setComponentView(m_componentView.data());
-
- newDocument->setFileName(fileName);
-
- document = newDocument;
-
- m_documentHash.insert(textEdit, document);
- }
- }
- setCurrentDocument(document);
+ setCurrentDesignDocument(currentDesignDocument());
m_initStatus = Initialized;
}
-void DesignModeWidget::closeEditors(QList<Core::IEditor*> editors)
-{
- foreach (Core::IEditor* editor, editors) {
- if (QPlainTextEdit *textEdit = qobject_cast<QPlainTextEdit*>(editor->widget())) {
- if (m_currentTextEdit.data() == textEdit) {
- setCurrentDocument(0);
- }
- if (m_documentHash.contains(textEdit)) {
- if (debug)
- qDebug() << Q_FUNC_INFO << editor->document()->fileName();
- DesignDocumentController *document = m_documentHash.take(textEdit).data();
- delete document;
- }
- }
- }
-}
-
-QAction *DesignModeWidget::undoAction() const
-{
- return m_undoAction;
-}
-
-QAction *DesignModeWidget::redoAction() const
-{
- return m_redoAction;
-}
-
-QAction *DesignModeWidget::deleteAction() const
-{
- return m_deleteAction;
-}
-
-QAction *DesignModeWidget::cutAction() const
-{
- return m_cutAction;
-}
-
-QAction *DesignModeWidget::copyAction() const
-{
- return m_copyAction;
-}
-
-QAction *DesignModeWidget::pasteAction() const
-{
- return m_pasteAction;
-}
-
-QAction *DesignModeWidget::selectAllAction() const
-{
- return m_selectAllAction;
-}
-
-QAction *DesignModeWidget::hideSidebarsAction() const
-{
- return m_hideSidebarsAction;
-}
-
-QAction *DesignModeWidget::toggleLeftSidebarAction() const
-{
- return m_toggleLeftSidebarAction;
-}
-
-QAction *DesignModeWidget::toggleRightSidebarAction() const
-{
- return m_toggleRightSidebarAction;
-}
-
-
-QAction *DesignModeWidget::restoreDefaultViewAction() const
-{
- return m_restoreDefaultViewAction;
-}
-
-QAction *DesignModeWidget::goIntoComponentAction() const
-{
- return m_goIntoComponentAction;
-}
-
void DesignModeWidget::readSettings()
{
QSettings *settings = Core::ICore::settings();
@@ -444,98 +290,25 @@ void DesignModeWidget::saveSettings()
settings->endGroup();
}
-void DesignModeWidget::undo()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->undo();
-}
-
-void DesignModeWidget::redo()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->redo();
-}
-
-void DesignModeWidget::deleteSelected()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->deleteSelected();
-}
-
-void DesignModeWidget::cutSelected()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->cutSelected();
-}
-
-void DesignModeWidget::copySelected()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->copySelected();
-}
-
-void DesignModeWidget::paste()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->paste();
-}
-
-void DesignModeWidget::selectAll()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->selectAll();
-}
-
-void DesignModeWidget::closeCurrentEditor()
-{
-}
-
-void DesignModeWidget::undoAvailable(bool isAvailable)
-{
- DesignDocumentController *documentController = qobject_cast<DesignDocumentController*>(sender());
- if (m_currentDesignDocumentController &&
- m_currentDesignDocumentController.data() == documentController) {
- m_undoAction->setEnabled(isAvailable);
- }
-}
-
-void DesignModeWidget::redoAvailable(bool isAvailable)
-{
- DesignDocumentController *documentController = qobject_cast<DesignDocumentController*>(sender());
- if (m_currentDesignDocumentController &&
- m_currentDesignDocumentController.data() == documentController) {
- m_redoAction->setEnabled(isAvailable);
- }
-}
-
-void DesignModeWidget::goIntoComponent()
-{
- if (m_currentDesignDocumentController)
- m_currentDesignDocumentController->goIntoComponent();
-}
-
-void DesignModeWidget::enable()
+void DesignModeWidget::enableWidgets()
{
if (debug)
qDebug() << Q_FUNC_INFO;
m_warningWidget->setVisible(false);
- m_formEditorView->widget()->setEnabled(true);
- m_statesEditorView->widget()->setEnabled(true);
+ viewManager().formEditorWidget()->setEnabled(true);
+ viewManager().statesEditorWidget()->setEnabled(true);
m_leftSideBar->setEnabled(true);
m_rightSideBar->setEnabled(true);
m_isDisabled = false;
}
-void DesignModeWidget::disable(const QList<RewriterView::Error> &errors)
+void DesignModeWidget::disableWidgets()
{
if (debug)
qDebug() << Q_FUNC_INFO;
- Q_ASSERT(!errors.isEmpty());
- m_warningWidget->setError(errors.first());
- m_warningWidget->setVisible(true);
- m_warningWidget->move(width() / 2, height() / 2);
- m_formEditorView->widget()->setEnabled(false);
- m_statesEditorView->widget()->setEnabled(false);
+
+ viewManager().formEditorWidget()->setEnabled(false);
+ viewManager().statesEditorWidget()->setEnabled(false);
m_leftSideBar->setEnabled(false);
m_rightSideBar->setEnabled(false);
m_isDisabled = true;
@@ -547,113 +320,26 @@ void DesignModeWidget::updateErrorStatus(const QList<RewriterView::Error> &error
qDebug() << Q_FUNC_INFO << errors.count();
if (m_isDisabled && errors.isEmpty()) {
- enable();
- } else if (!errors.isEmpty()) {
- disable(errors);
+ enableWidgets();
+ } else if (!errors.isEmpty()) {
+ disableWidgets();
+ showErrorMessage(errors);
}
}
-void DesignModeWidget::setAutoSynchronization(bool sync)
+TextEditor::ITextEditor *DesignModeWidget::textEditor() const
{
- if (debug)
- qDebug() << Q_FUNC_INFO << sync;
-
- RewriterView *rewriter = m_currentDesignDocumentController->rewriterView();
-
- m_currentDesignDocumentController->blockModelSync(!sync);
-
- if (sync) {
- if (rewriter && m_currentDesignDocumentController->model())
- rewriter->setSelectedModelNodes(QList<ModelNode>());
- // text editor -> visual editor
- if (!m_currentDesignDocumentController->model()) {
- m_currentDesignDocumentController->loadMaster(m_currentTextEdit.data());
- } else {
- m_currentDesignDocumentController->loadCurrentModel();
- m_componentView->resetView();
- }
-
- QList<RewriterView::Error> errors = m_currentDesignDocumentController->qmlErrors();
- if (errors.isEmpty()) {
- // set selection to text cursor
- const int cursorPos = m_currentTextEdit->textCursor().position();
- ModelNode node = nodeForPosition(cursorPos);
- if (rewriter && node.isValid()) {
- rewriter->setSelectedModelNodes(QList<ModelNode>() << node);
- }
- enable();
- } else {
- disable(errors);
- }
-
- connect(m_currentDesignDocumentController.data(), SIGNAL(qmlErrorsChanged(QList<RewriterView::Error>)),
- this, SLOT(updateErrorStatus(QList<RewriterView::Error>)));
-
- } else {
- if (m_currentDesignDocumentController->model() && m_currentDesignDocumentController->qmlErrors().isEmpty()) {
- RewriterView *rewriter = m_currentDesignDocumentController->rewriterView();
- // visual editor -> text editor
- ModelNode selectedNode;
- if (!rewriter->selectedModelNodes().isEmpty())
- selectedNode = rewriter->selectedModelNodes().first();
-
- if (selectedNode.isValid()) {
- const int nodeOffset = rewriter->nodeOffset(selectedNode);
- if (nodeOffset > 0) {
- const ModelNode currentSelectedNode
- = nodeForPosition(m_currentTextEdit->textCursor().position());
- if (currentSelectedNode != selectedNode) {
- int line, column;
- m_textEditor->convertPosition(nodeOffset, &line, &column);
- m_textEditor->gotoLine(line, column);
- }
- }
- }
- }
-
- disconnect(m_currentDesignDocumentController.data(), SIGNAL(qmlErrorsChanged(QList<RewriterView::Error>)),
- this, SLOT(updateErrorStatus(QList<RewriterView::Error>)));
- }
+ return currentDesignDocument()->textEditor();
}
-void DesignModeWidget::setCurrentDocument(DesignDocumentController *newDesignDocumentController)
+void DesignModeWidget::setCurrentDesignDocument(DesignDocument *newDesignDocument)
{
if (debug)
- qDebug() << Q_FUNC_INFO << newDesignDocumentController;
-
- if (m_currentDesignDocumentController.data() == newDesignDocumentController)
- return;
- if (m_currentDesignDocumentController) {
- setAutoSynchronization(false);
- saveSettings();
- }
-
- if (currentDesignDocumentController()) {
- disconnect(currentDesignDocumentController(), SIGNAL(undoAvailable(bool)),
- this, SLOT(undoAvailable(bool)));
- disconnect(currentDesignDocumentController(), SIGNAL(redoAvailable(bool)),
- this, SLOT(redoAvailable(bool)));
- }
+ qDebug() << Q_FUNC_INFO << newDesignDocument;
- m_currentDesignDocumentController = newDesignDocumentController;
-
- if (currentDesignDocumentController()) {
- connect(currentDesignDocumentController(), SIGNAL(undoAvailable(bool)),
- this, SLOT(undoAvailable(bool)));
- connect(currentDesignDocumentController(), SIGNAL(redoAvailable(bool)),
- this, SLOT(redoAvailable(bool)));
- }
+ //viewManager().setDesignDocument(newDesignDocument);
- if (m_currentDesignDocumentController) {
- setAutoSynchronization(true);
- m_undoAction->setEnabled(m_currentDesignDocumentController->isUndoAvailable());
- m_redoAction->setEnabled(m_currentDesignDocumentController->isRedoAvailable());
- } else {
- //detach all views
- m_undoAction->setEnabled(false);
- m_redoAction->setEnabled(false);
- }
}
void DesignModeWidget::setup()
@@ -690,20 +376,6 @@ void DesignModeWidget::setup()
}
}
- m_nodeInstanceView = new NodeInstanceView(this);
- connect(m_nodeInstanceView.data(), SIGNAL(qmlPuppetCrashed()), this, SLOT(qmlPuppetCrashed()));
- // Sidebar takes ownership
- m_navigatorView = new NavigatorView;
- m_propertyEditorView = new PropertyEditor(this);
- m_itemLibraryView = new ItemLibraryView(this);
-
- m_statesEditorView = new StatesEditorView(this);
-
- m_formEditorView = new FormEditorView(this);
- connect(m_formEditorView->crumblePath(), SIGNAL(elementClicked(QVariant)), this, SLOT(onCrumblePathElementClicked(QVariant)));
-
- m_componentView = new ComponentView(this);
- m_formEditorView->widget()->toolBox()->addLeftSideAction(m_componentView->action());
m_fakeToolBar = Core::EditorManager::createToolBar(this);
m_mainSplitter = new MiniSplitter(this);
@@ -713,9 +385,9 @@ void DesignModeWidget::setup()
m_warningWidget = new DocumentWarningWidget(this);
m_warningWidget->setVisible(false);
- Core::SideBarItem *navigatorItem = new NavigatorSideBarItem(m_navigatorView->widget(), QLatin1String(SB_NAVIGATOR));
- Core::SideBarItem *libraryItem = new ItemLibrarySideBarItem(m_itemLibraryView->widget(), QLatin1String(SB_LIBRARY));
- Core::SideBarItem *propertiesItem = new Core::SideBarItem(m_propertyEditorView->widget(), QLatin1String(SB_PROPERTIES));
+ Core::SideBarItem *navigatorItem = new NavigatorSideBarItem(viewManager().navigatorWidget(), QLatin1String(SB_NAVIGATOR));
+ Core::SideBarItem *libraryItem = new ItemLibrarySideBarItem(viewManager().itemLibraryWidget(), QLatin1String(SB_LIBRARY));
+ Core::SideBarItem *propertiesItem = new Core::SideBarItem(viewManager().propertyEditorWidget(), QLatin1String(SB_PROPERTIES));
// default items
m_sideBarItems << navigatorItem << libraryItem << propertiesItem;
@@ -751,7 +423,9 @@ void DesignModeWidget::setup()
connect(m_fakeToolBar, SIGNAL(closeClicked()), this, SLOT(closeCurrentEditor()));
connect(m_fakeToolBar, SIGNAL(goForwardClicked()), this, SLOT(onGoForwardClicked()));
connect(m_fakeToolBar, SIGNAL(goBackClicked()), this, SLOT(onGoBackClicked()));
- setupNavigatorHistory();
+
+ if (currentDesignDocument())
+ setupNavigatorHistory(currentDesignDocument()->textEditor());
// right area:
QWidget *centerWidget = new QWidget;
@@ -761,16 +435,16 @@ void DesignModeWidget::setup()
rightLayout->setSpacing(0);
rightLayout->addWidget(m_fakeToolBar);
//### we now own these here
- rightLayout->addWidget(m_statesEditorView->widget());
+ rightLayout->addWidget(viewManager().statesEditorWidget());
- FormEditorContext *formEditorContext = new FormEditorContext(m_formEditorView->widget());
+ FormEditorContext *formEditorContext = new FormEditorContext(viewManager().formEditorWidget());
Core::ICore::addContextObject(formEditorContext);
- NavigatorContext *navigatorContext = new NavigatorContext(m_navigatorView->widget());
+ NavigatorContext *navigatorContext = new NavigatorContext(viewManager().navigatorWidget());
Core::ICore::addContextObject(navigatorContext);
// editor and output panes
- m_outputPlaceholderSplitter->addWidget(m_formEditorView->widget());
+ m_outputPlaceholderSplitter->addWidget(viewManager().formEditorWidget());
m_outputPlaceholderSplitter->addWidget(m_outputPanePlaceholder);
m_outputPlaceholderSplitter->setStretchFactor(0, 10);
m_outputPlaceholderSplitter->setStretchFactor(1, 0);
@@ -794,7 +468,7 @@ void DesignModeWidget::setup()
mainLayout->addWidget(m_mainSplitter);
m_warningWidget->setVisible(false);
- m_statesEditorView->widget()->setEnabled(true);
+ viewManager().statesEditorWidget()->setEnabled(true);
m_leftSideBar->setEnabled(true);
m_rightSideBar->setEnabled(true);
m_leftSideBar->setCloseWhenEmpty(true);
@@ -803,7 +477,6 @@ void DesignModeWidget::setup()
readSettings();
show();
- QApplication::processEvents();
}
void DesignModeWidget::updateAvailableSidebarItemsRight()
@@ -830,8 +503,10 @@ void DesignModeWidget::qmlPuppetCrashed()
{
QList<RewriterView::Error> errorList;
RewriterView::Error error(tr("Qt Quick emulation layer crashed"));
- errorList << error;
- disable(errorList);
+ errorList.append(error);
+
+ disableWidgets();
+ showErrorMessage(errorList);
}
void DesignModeWidget::onGoBackClicked()
@@ -854,17 +529,16 @@ void DesignModeWidget::onGoForwardClicked()
}
}
-void DesignModeWidget::onCrumblePathElementClicked(const QVariant &data)
+DesignDocument *DesignModeWidget::currentDesignDocument() const
{
- currentDesignDocumentController()->setCrumbleBarInfo(data.value<CrumbleBarInfo>());
+ return QmlDesignerPlugin::instance()->documentManager().currentDesignDocument();
}
-DesignModeWidget *DesignModeWidget::instance()
+ViewManager &DesignModeWidget::viewManager()
{
- return s_instance;
+ return QmlDesignerPlugin::instance()->viewManager();
}
-
void DesignModeWidget::resizeEvent(QResizeEvent *event)
{
if (m_warningWidget)
@@ -872,35 +546,11 @@ void DesignModeWidget::resizeEvent(QResizeEvent *event)
QWidget::resizeEvent(event);
}
-
-bool DesignModeWidget::isInNodeDefinition(int nodeOffset, int nodeLength, int cursorPos) const {
- return (nodeOffset <= cursorPos) && (nodeOffset + nodeLength > cursorPos);
-}
-
-
-ModelNode DesignModeWidget::nodeForPosition(int cursorPos) const
+void DesignModeWidget::setupNavigatorHistory(Core::IEditor *editor)
{
- RewriterView *rewriter = m_currentDesignDocumentController->rewriterView();
- QList<ModelNode> nodes = rewriter->allModelNodes();
-
- ModelNode bestNode;
- int bestNodeOffset = -1;
-
- foreach (const ModelNode &node, nodes) {
- const int nodeOffset = rewriter->nodeOffset(node);
- const int nodeLength = rewriter->nodeLength(node);
- if (isInNodeDefinition(nodeOffset, nodeLength, cursorPos)
- && (nodeOffset > bestNodeOffset)) {
- bestNode = node;
- bestNodeOffset = nodeOffset;
- }
- }
-
- return bestNode;
-}
+ if (!m_keepNavigatorHistory)
+ addNavigatorHistoryEntry(editor->document()->fileName());
-void DesignModeWidget::setupNavigatorHistory()
-{
const bool canGoBack = m_navigatorHistoryCounter > 0;
const bool canGoForward = m_navigatorHistoryCounter < (m_navigatorHistory.size() - 1);
m_fakeToolBar->setCanGoBack(canGoBack);
@@ -917,13 +567,30 @@ void DesignModeWidget::addNavigatorHistoryEntry(const QString &fileName)
++m_navigatorHistoryCounter;
}
+void DesignModeWidget::showErrorMessage(const QList<RewriterView::Error> &errors)
+{
+ Q_ASSERT(!errors.isEmpty());
+ m_warningWidget->setError(errors.first());
+ m_warningWidget->setVisible(true);
+ m_warningWidget->move(width() / 2, height() / 2);
+}
QString DesignModeWidget::contextHelpId() const
{
- if (m_currentDesignDocumentController)
- return m_currentDesignDocumentController->contextHelpId();
+ if (currentDesignDocument())
+ return currentDesignDocument()->contextHelpId();
return QString();
}
+void DesignModeWidget::initialize()
+{
+ if (m_initStatus == NotInitialized) {
+ m_initStatus = Initializing;
+ setup();
+ }
+
+ m_initStatus = Initialized;
+}
+
} // namespace Internal
} // namespace Designer
diff --git a/src/plugins/qmldesigner/designmodewidget.h b/src/plugins/qmldesigner/designmodewidget.h
index cd55fa20a7..b6ebe50409 100644
--- a/src/plugins/qmldesigner/designmodewidget.h
+++ b/src/plugins/qmldesigner/designmodewidget.h
@@ -35,9 +35,7 @@
#include <utils/faketooltip.h>
#include <texteditor/itexteditor.h>
-#include <integrationcore.h>
-
-#include <designdocumentcontroller.h>
+#include <designdocument.h>
#include <itemlibraryview.h>
#include <navigatorwidget.h>
#include <navigatorview.h>
@@ -105,54 +103,34 @@ class DesignModeWidget : public QWidget
public:
explicit DesignModeWidget(QWidget *parent = 0);
- ~DesignModeWidget();
void showEditor(Core::IEditor *editor);
void closeEditors(const QList<Core::IEditor*> editors);
QString contextHelpId() const;
- QAction *undoAction() const;
- QAction *redoAction() const;
- QAction *deleteAction() const;
- QAction *cutAction() const;
- QAction *copyAction() const;
- QAction *pasteAction() const;
- QAction *selectAllAction() const;
- QAction *hideSidebarsAction() const;
- QAction *toggleLeftSidebarAction() const;
- QAction *toggleRightSidebarAction() const;
- QAction *restoreDefaultViewAction() const;
- QAction *goIntoComponentAction() const;
+ void initialize();
+
void readSettings();
void saveSettings();
- void setAutoSynchronization(bool sync);
- TextEditor::ITextEditor *textEditor() const {return m_textEditor.data(); }
+ TextEditor::ITextEditor *textEditor() const;
- static DesignModeWidget *instance();
- DesignDocumentController *currentDesignDocumentController() const {return m_currentDesignDocumentController.data(); }
+ DesignDocument *currentDesignDocument() const;
+ ViewManager &viewManager();
-private slots:
- void undo();
- void redo();
- void deleteSelected();
- void cutSelected();
- void copySelected();
- void paste();
- void selectAll();
- void closeCurrentEditor();
+ void enableWidgets();
+ void disableWidgets();
+ void showErrorMessage(const QList<RewriterView::Error> &errors);
+
+public slots:
+ void updateErrorStatus(const QList<RewriterView::Error> &errors);
+ void restoreDefaultView();
void toggleSidebars();
void toggleLeftSidebar();
void toggleRightSidebar();
- void restoreDefaultView();
- void undoAvailable(bool isAvailable);
- void redoAvailable(bool isAvailable);
- void goIntoComponent();
- void enable();
- void disable(const QList<RewriterView::Error> &errors);
- void updateErrorStatus(const QList<RewriterView::Error> &errors);
+private slots:
void updateAvailableSidebarItemsLeft();
void updateAvailableSidebarItemsRight();
@@ -162,49 +140,20 @@ private slots:
void onGoBackClicked();
void onGoForwardClicked();
- void onCrumblePathElementClicked(const QVariant &data);
-
protected:
void resizeEvent(QResizeEvent *event);
-private:
- void setCurrentDocument(DesignDocumentController *newDesignDocumentController);
- //QStackedWidget *m_documentWidgetStack;
- QHash<QPlainTextEdit*,QWeakPointer<DesignDocumentController> > m_documentHash;
- QWeakPointer<DesignDocumentController> m_currentDesignDocumentController;
- QWeakPointer<QPlainTextEdit> m_currentTextEdit;
-
- QAction *m_undoAction;
- QAction *m_redoAction;
- QAction *m_deleteAction;
- QAction *m_cutAction;
- QAction *m_copyAction;
- QAction *m_pasteAction;
- QAction *m_selectAllAction;
- QAction *m_hideSidebarsAction;
- QAction *m_restoreDefaultViewAction;
- QAction *m_toggleLeftSidebarAction;
- QAction *m_toggleRightSidebarAction;
- QAction *m_goIntoComponentAction;
-
- QWeakPointer<ItemLibraryView> m_itemLibraryView;
- QWeakPointer<NavigatorView> m_navigatorView;
- QWeakPointer<PropertyEditor> m_propertyEditorView;
- QWeakPointer<StatesEditorView> m_statesEditorView;
- QWeakPointer<FormEditorView> m_formEditorView;
- QWeakPointer<ComponentView> m_componentView;
- QWeakPointer<NodeInstanceView> m_nodeInstanceView;
-
- bool m_syncWithTextEdit;
+private: // functions
+ enum InitializeStatus { NotInitialized, Initializing, Initialized };
+ void setCurrentDesignDocument(DesignDocument *newDesignDocument);
void setup();
bool isInNodeDefinition(int nodeOffset, int nodeLength, int cursorPos) const;
QmlDesigner::ModelNode nodeForPosition(int cursorPos) const;
- void setupNavigatorHistory();
+ void setupNavigatorHistory(Core::IEditor *editor);
void addNavigatorHistoryEntry(const QString &fileName);
- QWeakPointer<TextEditor::ITextEditor> m_textEditor;
-
+private: // variables
QSplitter *m_mainSplitter;
Core::SideBar *m_leftSideBar;
Core::SideBar *m_rightSideBar;
@@ -215,15 +164,12 @@ private:
bool m_isDisabled;
bool m_showSidebars;
- enum InitializeStatus { NotInitialized, Initializing, Initialized };
InitializeStatus m_initStatus;
DocumentWarningWidget *m_warningWidget;
QStringList m_navigatorHistory;
int m_navigatorHistoryCounter;
bool m_keepNavigatorHistory;
-
- static DesignModeWidget *s_instance;
};
} // namespace Internal
diff --git a/src/plugins/qmldesigner/desktopplugin/desktop.metainfo b/src/plugins/qmldesigner/desktopplugin/desktop.metainfo
index 07f4a5aed0..da774b58f0 100644
--- a/src/plugins/qmldesigner/desktopplugin/desktop.metainfo
+++ b/src/plugins/qmldesigner/desktopplugin/desktop.metainfo
@@ -1,139 +1,383 @@
-<metainfo>
- <node name="QtDesktop.Button" icon=":/desktopplugin/images/button16.png">
- <itemlibraryentry name="Button" category="Components Desktop" libraryIcon=":/desktopplugin/images/button.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="100"/>
- <property name="text" type="QString" value="Button"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ComboBox" icon=":/desktopplugin/images/button16.png">
- <itemlibraryentry name="ComboBox" category="Components Desktop" libraryIcon=":/desktopplugin/images/button.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ToolButton" icon=":/desktopplugin/images/button16.png">
- <itemlibraryentry name="ToolButton" category="Components Desktop" libraryIcon=":/desktopplugin/images/button.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="100"/>
- <property name="text" type="QString" value="Button"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.CheckBox" icon=":/desktopplugin/images/checkbox16.png">
- <itemlibraryentry name="CheckBox" category="Components Desktop" libraryIcon=":/desktopplugin/images/checkbox.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- <property name="text" type="QString" value="CheckBox"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ChoiceList" icon=":/desktopplugin/images/choicelist16.png">
- <itemlibraryentry name="ChoiceList" category="Components Desktop" libraryIcon=":/desktopplugin/images/choicelist.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ProgressBar" icon=":/desktopplugin/images/progressbar16.png">
- <itemlibraryentry name="ProgressBar" category="Components Desktop" libraryIcon=":/desktopplugin/images/progressbar.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.SpinBox">
- <itemlibraryentry name="SpinBox" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.Dial">
- <itemlibraryentry name="Dial" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.SplitterRow">
- <itemlibraryentry name="SplitterRow" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="200"/>
- <property name="height" type="int" value="200"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.RadioButton" icon=":/desktopplugin/images/radiobutton16.png">
- <itemlibraryentry name="RadioButton" category="Components Desktop" libraryIcon=":/desktopplugin/images/radiobutton.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- <property name="text" type="QString" value="RadioButton"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.TextArea" icon=":/desktopplugin/images/textarea16.png">
- <itemlibraryentry name="TextArea" category="Components Desktop" libraryIcon=":/desktopplugin/images/textarea.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="180"/>
- <property name="text" type="QString" value="TextArea"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ButtonRow" icon=":/desktopplugin/images/buttonrow16.png">
- <itemlibraryentry name="ButtonRow" category="Components Desktop" libraryIcon=":/desktopplugin/images/buttonrow.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="120"/>
- <property name="height" type="int" value="20"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.TabBar" icon=":/desktopplugin/images/tabbar16.png">
- <itemlibraryentry name="TabBar" category="Components Desktop" libraryIcon=":/desktopplugin/images/tabbar.png" version="0.1" requiredImport="QtDesktop">
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.Slider" icon=":/desktopplugin/images/slider16.png">
- <itemlibraryentry name="Slider (horizontal)" category="Components Desktop" libraryIcon=":/desktopplugin/images/slider.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- <property name="orientation" type="int" value="1"/>
- </itemlibraryentry>
- <itemlibraryentry name="Slider (vertical)" category="Components Desktop" libraryIcon=":/desktopplugin/images/sliderh.png" version="0.1" requiredImport="QtDesktop">
- <property name="height" type="int" value="180"/>
- <property name="orientation" type="int" value="2"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ScrollBar">
- <itemlibraryentry name="ScrollBar (horizontal)" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- <property name="orientation" type="int" value="1"/>
- </itemlibraryentry>
- <itemlibraryentry name="ScrollBar (vertical)" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="height" type="int" value="180"/>
- <property name="orientation" type="int" value="2"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.TabFrame" icon=":/desktopplugin//images/window16.png">
- <itemlibraryentry name="TabGroup" category="Components Desktop" libraryIcon=":/desktopplugin/images/window.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="360"/>
- <property name="height" type="int" value="40"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ScrollArea">
- <itemlibraryentry name="ScrollArea" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="300"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.GroupBox">
- <itemlibraryentry name="GroupBox" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="300"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.Frame">
- <itemlibraryentry name="Frame" category="Components Desktop" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="300"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.ToolBar" icon=":/desktopplugin/images/toolbar16.png">
- <itemlibraryentry name="ToolBar" category="Components Desktop" libraryIcon=":/desktopplugin/images/toolbar.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="50"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.Switch" icon=":/desktopplugin/images/switchbutton16.png">
- <itemlibraryentry name="Switch" category="Components Desktop" libraryIcon=":/desktopplugin/images/switchbutton.png" version="0.1" requiredImport="QtDesktop">
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.TextField" icon=":/desktopplugin/images/textfield16.png">
- <itemlibraryentry name="TextField" category="Components Desktop" libraryIcon=":/desktopplugin/images/textfield.png" version="0.1" requiredImport="QtDesktop">
- <property name="width" type="int" value="180"/>
- <property name="text" type="QString" value="TextField"/>
- </itemlibraryentry>
- </node>
- <node name="QtDesktop.Label" icon=":/desktopplugin/images/window16.png.png">
- <itemlibraryentry name="Label" category="Components Desktop" libraryIcon=":/desktopplugin/images/window.png" version="0.1" requiredImport="QtDesktop">
- <property name="text" type="QString" value="Label"/>
- </itemlibraryentry>
- </node>
-</metainfo>
+MetaInfo {
+
+ Type {
+ name: "QtDesktop.Button"
+ icon: ":/desktopplugin/images/button16.png"
+
+ ItemLibraryEntry {
+ name: "Button"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/button.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "text"; type: "QString"; value: "Button"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ComboBox"
+ icon: ":/desktopplugin/images/button16.png"
+
+ ItemLibraryEntry {
+ name: "ComboBox"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/button.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ToolButton"
+ icon: ":/desktopplugin/images/button16.png"
+
+ ItemLibraryEntry {
+ name: "Tool Button"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/button.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "text"; type: "QString"; value: "Tool Button"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.CheckBox"
+ icon: ":/desktopplugin/images/button16.png"
+
+ ItemLibraryEntry {
+ name: "Check Box"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/button.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "text"; type: "QString"; value: "CheckBox"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ChoiceList"
+ icon: ":/desktopplugin/images/choicelist16.png"
+
+ ItemLibraryEntry {
+ name: "Choice List"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/choicelist.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 180; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ProgressBar"
+ icon: ":/desktopplugin/images/progressbar16.png"
+
+ ItemLibraryEntry {
+ name: "Progress Bar"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/progressbar.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.SpinBox"
+ icon: ":/desktopplugin/images/progressbar16.png"
+
+ ItemLibraryEntry {
+ name: "Spin Box"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/progressbar.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.Dial"
+ //icon: ":/desktopplugin/images/progressbar16.png"
+
+ ItemLibraryEntry {
+ name: "Dial"
+ category: "Components Desktop"
+ //libraryIcon: ":/desktopplugin/images/progressbar.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.RadioButton"
+ icon: ":/desktopplugin/images/radiobutton16.png"
+
+ ItemLibraryEntry {
+ name: "Radio Button"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/radiobutton.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 180; }
+ Property { name: "text"; type: "QString"; value: "Radio Button"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.TextArea"
+ icon: ":/desktopplugin/images/textarea16.png"
+
+ ItemLibraryEntry {
+ name: "Text Area"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/textarea.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 180; }
+ Property { name: "height"; type: "int"; value: 180; }
+ Property { name: "text"; type: "QString"; value: "Text Area"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ButtonRow"
+ icon: ":/desktopplugin/images/buttonrow16.png"
+
+ ItemLibraryEntry {
+ name: "Button Row"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/buttonrow.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 120; }
+ Property { name: "height"; type: "int"; value: 120; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.SplitterRow"
+ icon: ":/desktopplugin/images/buttonrow16.png"
+
+ ItemLibraryEntry {
+ name: "Splitter Row"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/buttonrow.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 020; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.TabBar"
+ icon: ":/desktopplugin/images/tabbar16.png"
+
+ ItemLibraryEntry {
+ name: "Tab Bar"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/tabbar.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+ }
+ }
+
+ Type {
+ name: "QtDesktop.Slider"
+ icon: ":/desktopplugin/images/slider16.png"
+
+ ItemLibraryEntry {
+ name: "Slider (horizontal)"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/slider.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 180; }
+ Property { name: "orientation"; type: "int"; value: "1"; }
+
+ }
+
+ ItemLibraryEntry {
+ name: "Slider (vertical)"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/sliderh.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "height"; type: "int"; value: 180; }
+ Property { name: "orientation"; type: "int"; value: "2"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ScrollBar"
+ icon: ":/desktopplugin/images/slider16.png"
+
+ ItemLibraryEntry {
+ name: "ScrollBar (horizontal)"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/slider.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 180; }
+ Property { name: "orientation"; type: "int"; value: "1"; }
+
+ }
+
+ ItemLibraryEntry {
+ name: "ScrollBar (vertical)"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/sliderh.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "height"; type: "int"; value: 180; }
+ Property { name: "orientation"; type: "int"; value: "2"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.TabFrame"
+ icon: ":/desktopplugin//images/window16.png"
+
+ ItemLibraryEntry {
+ name: "Tab Frame"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/window.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 360; }
+ Property { name: "height"; type: "int"; value: 200; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ScrollArea"
+ icon: ":/desktopplugin//images/window16.png"
+
+ ItemLibraryEntry {
+ name: "Scroll Area"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/window.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 360; }
+ Property { name: "height"; type: "int"; value: 300; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.GroupBox"
+ icon: ":/desktopplugin//images/window16.png"
+
+ ItemLibraryEntry {
+ name: "Group Box"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/window.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 360; }
+ Property { name: "height"; type: "int"; value: 300; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.Frame"
+ icon: ":/desktopplugin//images/window16.png"
+
+ ItemLibraryEntry {
+ name: "Frame"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/window.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 360; }
+ Property { name: "height"; type: "int"; value: 300; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.ToolBar"
+ icon: ":/desktopplugin/images/toolbar16.png"
+
+ ItemLibraryEntry {
+ name: "Tool Bar"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/toolbar.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 360; }
+ Property { name: "height"; type: "int"; value: 50; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.Switch"
+ icon: ":/desktopplugin/images/switchbutton16.png"
+
+ ItemLibraryEntry {
+ name: "Switch"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/switchbutton.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+ }
+ }
+
+ Type {
+ name: "QtDesktop.TextField"
+ icon: ":/desktopplugin/images/textfield16.png"
+
+ ItemLibraryEntry {
+ name: "Text Field"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/textfield.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "width"; type: "int"; value: 180; }
+ Property { name: "text"; type: "QString"; value: "Text Field"; }
+ }
+ }
+
+ Type {
+ name: "QtDesktop.Label"
+ icon: ":/desktopplugin/images/window16.png.png"
+
+ ItemLibraryEntry {
+ name: "Label"
+ category: "Components Desktop"
+ libraryIcon: ":/desktopplugin/images/window.png"
+ version: "0.1"
+ requiredImport: "QtDesktop"
+
+ Property { name: "text"; type: "QString"; value: "Text Field"; }
+ }
+ }
+}
diff --git a/src/plugins/qmldesigner/documentmanager.cpp b/src/plugins/qmldesigner/documentmanager.cpp
new file mode 100644
index 0000000000..4a7af81f42
--- /dev/null
+++ b/src/plugins/qmldesigner/documentmanager.cpp
@@ -0,0 +1,80 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "documentmanager.h"
+
+#include <coreplugin/designmode.h>
+#include <coreplugin/modemanager.h>
+#include <qmljseditor/qmljseditorconstants.h>
+
+namespace QmlDesigner {
+
+DocumentManager::DocumentManager()
+ : QObject()
+{
+}
+
+DocumentManager::~DocumentManager()
+{
+ foreach (const QWeakPointer<DesignDocument> &designDocument, m_designDocumentHash)
+ delete designDocument.data();
+}
+
+void DocumentManager::setCurrentDesignDocument(Core::IEditor *editor)
+{
+ if (editor) {
+ m_currentDesignDocument = m_designDocumentHash.value(editor);
+ if (m_currentDesignDocument == 0) {
+ m_currentDesignDocument = new DesignDocument;
+ m_designDocumentHash.insert(editor, m_currentDesignDocument);
+ m_currentDesignDocument->setEditor(editor);
+ }
+ } else {
+ m_currentDesignDocument->resetToDocumentModel();
+ m_currentDesignDocument.clear();
+ }
+}
+
+DesignDocument *DocumentManager::currentDesignDocument() const
+{
+ return m_currentDesignDocument.data();
+}
+
+bool DocumentManager::hasCurrentDesignDocument() const
+{
+ return m_currentDesignDocument.data();
+}
+
+void DocumentManager::removeEditors(QList<Core::IEditor *> editors)
+{
+ foreach (Core::IEditor *editor, editors)
+ delete m_designDocumentHash.take(editor).data();
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/documentmanager.h b/src/plugins/qmldesigner/documentmanager.h
new file mode 100644
index 0000000000..43a6f67584
--- /dev/null
+++ b/src/plugins/qmldesigner/documentmanager.h
@@ -0,0 +1,65 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+
+#ifndef QMLDESIGNER_DOCUMENTMANAGER_H
+#define QMLDESIGNER_DOCUMENTMANAGER_H
+
+#include <QObject>
+#include <QList>
+
+#include <designdocument.h>
+
+namespace Core {
+class IEditor;
+}
+
+namespace QmlDesigner {
+
+class DocumentManager : public QObject
+{
+ Q_OBJECT
+public:
+ DocumentManager();
+ ~DocumentManager();
+
+ void setCurrentDesignDocument(Core::IEditor*editor);
+ DesignDocument *currentDesignDocument() const;
+ bool hasCurrentDesignDocument() const;
+
+ void removeEditors(QList<Core::IEditor*> editors);
+
+private:
+ QHash<Core::IEditor *,QWeakPointer<DesignDocument> > m_designDocumentHash;
+ QWeakPointer<DesignDocument> m_currentDesignDocument;
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_DOCUMENTMANAGER_H
diff --git a/src/plugins/qmldesigner/extrasplugin/extras.metainfo b/src/plugins/qmldesigner/extrasplugin/extras.metainfo
deleted file mode 100644
index d074cefe05..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/extras.metainfo
+++ /dev/null
@@ -1,54 +0,0 @@
-<metainfo>
- <node name="CountBubble" icon=":/extrasplugin/images/count-bubble-16.png">
- <itemlibraryentry name="CountBubble" category="Components Extras" libraryIcon=":/extrasplugin/images/count-bubble-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="DatePickerDialog" icon=":/extrasplugin/images/date-picker-16.png">
- <itemlibraryentry name="DatePickerDialog" category="Components Extras" libraryIcon=":/extrasplugin/images/date-picker-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="InfoBanner" icon=":/extrasplugin/images/info-banner-16.png">
- <itemlibraryentry name="InfoBanner" category="Components Extras" libraryIcon=":/extrasplugin/images/info-banner-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="ListButton" icon=":/extrasplugin/images/list-button-16.png">
- <itemlibraryentry name="ListButton" category="Components Extras" libraryIcon=":/extrasplugin/images/list-button-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="ListDelegate" icon=":/extrasplugin/images/list-delegate-16.png">
- <itemlibraryentry name="ListDelegate" category="Components Extras" libraryIcon=":/extrasplugin/images/list-delegate-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="MoreIndicator" icon=":/extrasplugin/images/more-indicator-16.png">
- <itemlibraryentry name="MoreIndicator" category="Components Extras" libraryIcon=":/extrasplugin/images/more-indicator-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="PageIndicator" icon=":/extrasplugin/images/page-indicator-16.png">
- <itemlibraryentry name="PageIndicator" category="Components Extras" libraryIcon=":/extrasplugin/images/page-indicator-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="RatingIndicator" icon=":/extrasplugin/images/rating-indicator-16.png">
- <itemlibraryentry name="RatingIndicator" category="Components Extras" libraryIcon=":/extrasplugin/images/rating-indicator-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="TimePickerDialog" icon=":/extrasplugin/images/time-picker-16.png">
- <itemlibraryentry name="TimePickerDialog" category="Components Extras" libraryIcon=":/extrasplugin/images/time-picker-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="Tumbler" icon=":/extrasplugin/images/tumbler-16.png">
- <itemlibraryentry name="Tumbler" category="Components Extras" libraryIcon=":/extrasplugin/images/tumbler-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="TumblerButton" icon=":/extrasplugin/images/tumbler-button-16.png">
- <itemlibraryentry name="TumblerButton" category="Components Extras" libraryIcon=":/extrasplugin/images/tumbler-button-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="TumblerColumn" icon=":/extrasplugin/images/tumbler-column-16.png">
- <itemlibraryentry name="TumblerColumn" category="Components Extras" libraryIcon=":/extrasplugin/images/tumbler-column-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
- <node name="TumblerDialog" icon=":/extrasplugin/images/tumbler-dialog-16.png">
- <itemlibraryentry name="TumblerDialog" category="Components Extras" libraryIcon=":/extrasplugin/images/tumbler-dialog-24.png" version="1.0" requiredImport="com.nokia.extras">
- </itemlibraryentry>
- </node>
-</metainfo>
diff --git a/src/plugins/qmldesigner/extrasplugin/extrasplugin.json b/src/plugins/qmldesigner/extrasplugin/extrasplugin.json
deleted file mode 100644
index 62ea9d2cfb..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/extrasplugin.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-
-
-"Vendor" : "Digia Plc",
-
-
-
-
-"Category" : "Qt Quick",
-
-
-"Description" : "Plugin for Extra Items.",
-
-
-"Url" : "http://www.qt-project.org"
-
-
-
-}
diff --git a/src/plugins/qmldesigner/extrasplugin/extrasplugin.pri b/src/plugins/qmldesigner/extrasplugin/extrasplugin.pri
deleted file mode 100644
index f7967d7769..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/extrasplugin.pri
+++ /dev/null
@@ -1,13 +0,0 @@
-TARGET = extrasplugin
-TEMPLATE = lib
-CONFIG += plugin
-
-include (../designercore/iwidgetplugin.pri)
-
-SOURCES += $$PWD/extrasplugin.cpp
-
-HEADERS += $$PWD/extrasplugin.h $$PWD/../designercore/include/iwidgetplugin.h
-
-RESOURCES += $$PWD/extrasplugin.qrc
-
-OTHER_FILES += $$PWD/extras.metainfo
diff --git a/src/plugins/qmldesigner/extrasplugin/extrasplugin.pro b/src/plugins/qmldesigner/extrasplugin/extrasplugin.pro
deleted file mode 100644
index af910266b4..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/extrasplugin.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-include(../../../../qtcreator.pri)
-include(../../../private_headers.pri)
-include(extrasplugin.pri)
-include(../plugindestdir.pri)
diff --git a/src/plugins/qmldesigner/extrasplugin/extrasplugin.qrc b/src/plugins/qmldesigner/extrasplugin/extrasplugin.qrc
deleted file mode 100644
index ae97ba05e9..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/extrasplugin.qrc
+++ /dev/null
@@ -1,31 +0,0 @@
-<RCC>
- <qresource prefix="/extrasplugin">
- <file>extras.metainfo</file>
- <file>images/count-bubble-16.png</file>
- <file>images/count-bubble-24.png</file>
- <file>images/date-picker-16.png</file>
- <file>images/date-picker-24.png</file>
- <file>images/info-banner-16.png</file>
- <file>images/info-banner-24.png</file>
- <file>images/list-button-16.png</file>
- <file>images/list-button-24.png</file>
- <file>images/list-delegate-16.png</file>
- <file>images/list-delegate-24.png</file>
- <file>images/more-indicator-16.png</file>
- <file>images/more-indicator-24.png</file>
- <file>images/page-indicator-16.png</file>
- <file>images/page-indicator-24.png</file>
- <file>images/rating-indicator-16.png</file>
- <file>images/rating-indicator-24.png</file>
- <file>images/time-picker-16.png</file>
- <file>images/time-picker-24.png</file>
- <file>images/tumbler-16.png</file>
- <file>images/tumbler-24.png</file>
- <file>images/tumbler-button-16.png</file>
- <file>images/tumbler-button-24.png</file>
- <file>images/tumbler-column-16.png</file>
- <file>images/tumbler-column-24.png</file>
- <file>images/tumbler-dialog-16.png</file>
- <file>images/tumbler-dialog-24.png</file>
- </qresource>
-</RCC>
diff --git a/src/plugins/qmldesigner/extrasplugin/images/count-bubble-16.png b/src/plugins/qmldesigner/extrasplugin/images/count-bubble-16.png
deleted file mode 100644
index 2ac1430602..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/count-bubble-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/count-bubble-24.png b/src/plugins/qmldesigner/extrasplugin/images/count-bubble-24.png
deleted file mode 100644
index ba444822d5..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/count-bubble-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/date-picker-16.png b/src/plugins/qmldesigner/extrasplugin/images/date-picker-16.png
deleted file mode 100644
index b8eb95b737..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/date-picker-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/date-picker-24.png b/src/plugins/qmldesigner/extrasplugin/images/date-picker-24.png
deleted file mode 100644
index a8ee7e0847..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/date-picker-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/info-banner-16.png b/src/plugins/qmldesigner/extrasplugin/images/info-banner-16.png
deleted file mode 100644
index 379413808b..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/info-banner-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/info-banner-24.png b/src/plugins/qmldesigner/extrasplugin/images/info-banner-24.png
deleted file mode 100644
index bf8aa614d0..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/info-banner-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/list-button-16.png b/src/plugins/qmldesigner/extrasplugin/images/list-button-16.png
deleted file mode 100644
index 2b1ce900b8..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/list-button-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/list-button-24.png b/src/plugins/qmldesigner/extrasplugin/images/list-button-24.png
deleted file mode 100644
index d432090f9c..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/list-button-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/list-delegate-16.png b/src/plugins/qmldesigner/extrasplugin/images/list-delegate-16.png
deleted file mode 100644
index 3c97433f08..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/list-delegate-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/list-delegate-24.png b/src/plugins/qmldesigner/extrasplugin/images/list-delegate-24.png
deleted file mode 100644
index c4d9886920..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/list-delegate-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/more-indicator-16.png b/src/plugins/qmldesigner/extrasplugin/images/more-indicator-16.png
deleted file mode 100644
index 81eff7306c..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/more-indicator-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/more-indicator-24.png b/src/plugins/qmldesigner/extrasplugin/images/more-indicator-24.png
deleted file mode 100644
index f5d8dedbfb..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/more-indicator-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/page-indicator-16.png b/src/plugins/qmldesigner/extrasplugin/images/page-indicator-16.png
deleted file mode 100644
index 29a8933751..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/page-indicator-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/page-indicator-24.png b/src/plugins/qmldesigner/extrasplugin/images/page-indicator-24.png
deleted file mode 100644
index 60dda334fc..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/page-indicator-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/rating-indicator-16.png b/src/plugins/qmldesigner/extrasplugin/images/rating-indicator-16.png
deleted file mode 100644
index 2df5418a84..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/rating-indicator-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/rating-indicator-24.png b/src/plugins/qmldesigner/extrasplugin/images/rating-indicator-24.png
deleted file mode 100644
index 393b2ffa69..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/rating-indicator-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/time-picker-16.png b/src/plugins/qmldesigner/extrasplugin/images/time-picker-16.png
deleted file mode 100644
index 1ee49cafbd..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/time-picker-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/time-picker-24.png b/src/plugins/qmldesigner/extrasplugin/images/time-picker-24.png
deleted file mode 100644
index 979981bd31..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/time-picker-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-16.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-16.png
deleted file mode 100644
index afcf864744..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-24.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-24.png
deleted file mode 100644
index 43783e6ee2..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-button-16.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-button-16.png
deleted file mode 100644
index 4368493c3e..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-button-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-button-24.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-button-24.png
deleted file mode 100644
index 6b0b71a65a..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-button-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-column-16.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-column-16.png
deleted file mode 100644
index 36e2d27608..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-column-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-column-24.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-column-24.png
deleted file mode 100644
index 8a043798f1..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-column-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-16.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-16.png
deleted file mode 100644
index 5a105a76db..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-24.png b/src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-24.png
deleted file mode 100644
index a6bbc2d795..0000000000
--- a/src/plugins/qmldesigner/extrasplugin/images/tumbler-dialog-24.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/Untitled-2.png b/src/plugins/qmldesigner/meegoplugin/images/Untitled-2.png
deleted file mode 100644
index 2e0bf73a26..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/Untitled-2.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/busyindicator.png b/src/plugins/qmldesigner/meegoplugin/images/busyindicator.png
deleted file mode 100644
index 89d0283f26..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/busyindicator.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/busyindicator16.png b/src/plugins/qmldesigner/meegoplugin/images/busyindicator16.png
deleted file mode 100644
index 7e3b2d3158..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/busyindicator16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/busyindicatora.png b/src/plugins/qmldesigner/meegoplugin/images/busyindicatora.png
deleted file mode 100644
index 433f4d426b..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/busyindicatora.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/busyindicatora16.png b/src/plugins/qmldesigner/meegoplugin/images/busyindicatora16.png
deleted file mode 100644
index 82de5b0a1b..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/busyindicatora16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/button.png b/src/plugins/qmldesigner/meegoplugin/images/button.png
deleted file mode 100644
index 828af210ac..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/button.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/button16.png b/src/plugins/qmldesigner/meegoplugin/images/button16.png
deleted file mode 100644
index 8d95760b27..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/button16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/buttoncolumn.png b/src/plugins/qmldesigner/meegoplugin/images/buttoncolumn.png
deleted file mode 100644
index 46db8f6ab5..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/buttoncolumn.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/buttoncolumn16.png b/src/plugins/qmldesigner/meegoplugin/images/buttoncolumn16.png
deleted file mode 100644
index 883258048f..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/buttoncolumn16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/buttonrow.png b/src/plugins/qmldesigner/meegoplugin/images/buttonrow.png
deleted file mode 100644
index 9727749de9..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/buttonrow.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/buttonrow16.png b/src/plugins/qmldesigner/meegoplugin/images/buttonrow16.png
deleted file mode 100644
index 420de41860..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/buttonrow16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/checkbox.png b/src/plugins/qmldesigner/meegoplugin/images/checkbox.png
deleted file mode 100644
index 0f4a826f4d..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/checkbox.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/checkbox16.png b/src/plugins/qmldesigner/meegoplugin/images/checkbox16.png
deleted file mode 100644
index 01f09e3515..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/checkbox16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/choicelist.png b/src/plugins/qmldesigner/meegoplugin/images/choicelist.png
deleted file mode 100644
index 3fd9876ada..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/choicelist.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/choicelist16.png b/src/plugins/qmldesigner/meegoplugin/images/choicelist16.png
deleted file mode 100644
index 602b28229e..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/choicelist16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/item-icon.png b/src/plugins/qmldesigner/meegoplugin/images/item-icon.png
deleted file mode 100644
index fc53d38ae7..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/item-icon.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/item-icon16.png b/src/plugins/qmldesigner/meegoplugin/images/item-icon16.png
deleted file mode 100644
index 7d2d7a5050..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/item-icon16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/label.png b/src/plugins/qmldesigner/meegoplugin/images/label.png
deleted file mode 100644
index e622f68687..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/label.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/label16.png b/src/plugins/qmldesigner/meegoplugin/images/label16.png
deleted file mode 100644
index 0478d429f6..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/label16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/lineedit.png b/src/plugins/qmldesigner/meegoplugin/images/lineedit.png
deleted file mode 100644
index f521cd513e..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/lineedit.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/lineedit16.png b/src/plugins/qmldesigner/meegoplugin/images/lineedit16.png
deleted file mode 100644
index 549803910d..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/lineedit16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/progressbar.png b/src/plugins/qmldesigner/meegoplugin/images/progressbar.png
deleted file mode 100644
index 040f5bac03..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/progressbar.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/progressbar16.png b/src/plugins/qmldesigner/meegoplugin/images/progressbar16.png
deleted file mode 100644
index e2432475d5..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/progressbar16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/radiobutton.png b/src/plugins/qmldesigner/meegoplugin/images/radiobutton.png
deleted file mode 100644
index 143b6a99f4..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/radiobutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/radiobutton16.png b/src/plugins/qmldesigner/meegoplugin/images/radiobutton16.png
deleted file mode 100644
index 94912c2034..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/radiobutton16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/slider.png b/src/plugins/qmldesigner/meegoplugin/images/slider.png
deleted file mode 100644
index 746ed51932..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/slider.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/slider16.png b/src/plugins/qmldesigner/meegoplugin/images/slider16.png
deleted file mode 100644
index 10c4928b3c..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/slider16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/sliderh.png b/src/plugins/qmldesigner/meegoplugin/images/sliderh.png
deleted file mode 100644
index 87cd55678f..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/sliderh.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/sliderh16.png b/src/plugins/qmldesigner/meegoplugin/images/sliderh16.png
deleted file mode 100644
index c419911336..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/sliderh16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/switchbutton.png b/src/plugins/qmldesigner/meegoplugin/images/switchbutton.png
deleted file mode 100644
index 48bf247cb8..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/switchbutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/switchbutton16.png b/src/plugins/qmldesigner/meegoplugin/images/switchbutton16.png
deleted file mode 100644
index 238a1be632..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/switchbutton16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/tabbutton.png b/src/plugins/qmldesigner/meegoplugin/images/tabbutton.png
deleted file mode 100644
index d9f5fdb3f9..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/tabbutton.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/tabbutton16.png b/src/plugins/qmldesigner/meegoplugin/images/tabbutton16.png
deleted file mode 100644
index 8e279cff65..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/tabbutton16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/textarea.png b/src/plugins/qmldesigner/meegoplugin/images/textarea.png
deleted file mode 100644
index 86f2969d00..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/textarea.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/textarea16.png b/src/plugins/qmldesigner/meegoplugin/images/textarea16.png
deleted file mode 100644
index 899a4bca2e..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/textarea16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/textfield.png b/src/plugins/qmldesigner/meegoplugin/images/textfield.png
deleted file mode 100644
index b0f13da50d..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/textfield.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/textfield16.png b/src/plugins/qmldesigner/meegoplugin/images/textfield16.png
deleted file mode 100644
index 7feb8c7158..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/textfield16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/toolbar.png b/src/plugins/qmldesigner/meegoplugin/images/toolbar.png
deleted file mode 100644
index e67c042422..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/toolbar.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/toolbar16.png b/src/plugins/qmldesigner/meegoplugin/images/toolbar16.png
deleted file mode 100644
index f4a0c5ef69..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/toolbar16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/window.png b/src/plugins/qmldesigner/meegoplugin/images/window.png
deleted file mode 100644
index fc53d38ae7..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/window.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/images/window16.png b/src/plugins/qmldesigner/meegoplugin/images/window16.png
deleted file mode 100644
index 7d2d7a5050..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/images/window16.png
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qmldesigner/meegoplugin/meego.metainfo b/src/plugins/qmldesigner/meegoplugin/meego.metainfo
deleted file mode 100644
index 8f5a6d6bf2..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/meego.metainfo
+++ /dev/null
@@ -1,110 +0,0 @@
-<metainfo>
- <node name="com.nokia.meego.Label" icon=":/meegoplugin/images/label16.png">
- <itemlibraryentry name="Label" category="Components MeeGo" libraryIcon=":/meegoplugin/images/label.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="text" type="QString" value="Label"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.BusyIndicator" icon=":/meegoplugin/images/busyindicator16.png">
- <itemlibraryentry name="BusyIndicator" category="Components MeeGo" libraryIcon=":/meegoplugin/images/busyindicator.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="180"/>
- <property name="height" type="int" value="30"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Button" icon=":/meegoplugin/images/button16.png">
- <itemlibraryentry name="Button" category="Components MeeGo" libraryIcon=":/meegoplugin/images/button.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ToolButton" icon=":/meegoplugin/images/button16.png">
- <itemlibraryentry name="ToolButton" category="Components MeeGo" libraryIcon=":/meegoplugin/images/button.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.TabButton" icon=":/meegoplugin/images/tabbutton16.png">
- <itemlibraryentry name="TabButton" category="Components MeeGo" libraryIcon=":/meegoplugin/images/tabbutton.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.SheetButton" icon=":/meegoplugin/images/button16.png">
- <itemlibraryentry name="SheetButton" category="Components MeeGo" libraryIcon=":/meegoplugin/images/button.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Slider" icon=":/meegoplugin/images/slider16.png">
- <itemlibraryentry name="Slider" category="Components MeeGo" libraryIcon=":/meegoplugin/images/slider.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.CheckBox" icon=":/meegoplugin/images/checkbox16.png">
- <itemlibraryentry name="CheckBox" category="Components MeeGo" libraryIcon=":/meegoplugin/images/checkbox.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.RadioButton" icon=":/meegoplugin/images/radiobutton16.png">
- <itemlibraryentry name="RadioButton" category="Components MeeGo" libraryIcon=":/meegoplugin/images/radiobutton.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Spinner" icon=":/meegoplugin/images/item-icon16.png">
- <itemlibraryentry name="Spinner" category="Components MeeGo" libraryIcon=":/meegoplugin/images/item-icon.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.TextField" icon=":/meegoplugin/images/textfield16.png">
- <itemlibraryentry name="TextField" category="Components MeeGo" libraryIcon=":/meegoplugin/images/textfield.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ProgressBar" icon=":/meegoplugin/images/progressbar16.png">
- <itemlibraryentry name="ProgressBar" category="Components MeeGo" libraryIcon=":/meegoplugin/images/progressbar.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Switch" icon=":/meegoplugin/images/switchbutton16.png">
- <itemlibraryentry name="Switch" category="Components MeeGo" libraryIcon=":/meegoplugin/images/switchbutton.png" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ToolItem">
- <itemlibraryentry name="ToolItem" category="Components MeeGo" version="1.0" requiredImport="com.nokia.meego">
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.TextArea" icon=":/meegoplugin/images/textarea16.png">
- <itemlibraryentry name="TextArea" category="Components MeeGo" libraryIcon=":/meegoplugin/images/textarea.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- <property name="text" type="QString" value="TextArea"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Window" icon=":/meegoplugin/images/window16.png">
- <itemlibraryentry name="Window" category="Components MeeGo" libraryIcon=":/meegoplugin/images/window.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="360"/>
- <property name="height" type="int" value="640"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Page" icon=":/meegoplugin/images/window16.png">
- <itemlibraryentry name="Page" category="Components MeeGo" libraryIcon=":/meegoplugin/images/window.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="360"/>
- <property name="height" type="int" value="640"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.Sheet" icon=":/meegoplugin/images/window16.png">
- <itemlibraryentry name="Sheet" category="Components MeeGo" libraryIcon=":/meegoplugin/images/window.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="360"/>
- <property name="height" type="int" value="640"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ToolBar" icon=":/meegoplugin/images/toolbar16.png">
- <itemlibraryentry name="ToolBar" category="Components MeeGo" libraryIcon=":/meegoplugin/images/toolbar.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="360"/>
- <property name="height" type="int" value="140"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ButtonColumn" icon=":/meegoplugin/images/buttoncolumn16.png">
- <itemlibraryentry name="ButtonColumn" category="Components MeeGo" libraryIcon=":/meegoplugin/images/buttoncolumn.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ButtonRow" icon=":/meegoplugin/images/buttonrow16.png">
- <itemlibraryentry name=" ButtonRow" category="Components MeeGo" libraryIcon=":/meegoplugin/images/buttonrow.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="com.nokia.meego.ToolButtonRow" icon=":/meegoplugin/images/window16.png">
- <itemlibraryentry name=" ToolButtonRow" category="Components MeeGo" libraryIcon=":/meegoplugin/images/window.png" version="1.0" requiredImport="com.nokia.meego">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- </itemlibraryentry>
- </node>
-</metainfo>
diff --git a/src/plugins/qmldesigner/meegoplugin/meegoplugin.json b/src/plugins/qmldesigner/meegoplugin/meegoplugin.json
deleted file mode 100644
index c9f0944388..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/meegoplugin.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-
-
-"Vendor" : "Digia Plc",
-
-
-
-
-"Category" : "Qt Quick",
-
-
-"Description" : "Plugin for Meego Items.",
-
-
-"Url" : "http://www.qt-project.org"
-
-
-
-}
diff --git a/src/plugins/qmldesigner/meegoplugin/meegoplugin.pri b/src/plugins/qmldesigner/meegoplugin/meegoplugin.pri
deleted file mode 100644
index 99e5519579..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/meegoplugin.pri
+++ /dev/null
@@ -1,13 +0,0 @@
-TARGET = meegoplugin
-TEMPLATE = lib
-CONFIG += plugin
-
-include (../designercore/iwidgetplugin.pri)
-
-SOURCES += $$PWD/meegoplugin.cpp
-
-HEADERS += $$PWD/meegoplugin.h $$PWD/../designercore/include/iwidgetplugin.h
-
-RESOURCES += $$PWD/meegoplugin.qrc
-
-OTHER_FILES += $$PWD/meego.metainfo
diff --git a/src/plugins/qmldesigner/meegoplugin/meegoplugin.pro b/src/plugins/qmldesigner/meegoplugin/meegoplugin.pro
deleted file mode 100644
index c7cfce0689..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/meegoplugin.pro
+++ /dev/null
@@ -1,4 +0,0 @@
-include(../../../../qtcreator.pri)
-include(../../../private_headers.pri)
-include(meegoplugin.pri)
-include(../plugindestdir.pri)
diff --git a/src/plugins/qmldesigner/meegoplugin/meegoplugin.qrc b/src/plugins/qmldesigner/meegoplugin/meegoplugin.qrc
deleted file mode 100644
index 34752a2fba..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/meegoplugin.qrc
+++ /dev/null
@@ -1,45 +0,0 @@
-<RCC>
- <qresource prefix="/meegoplugin">
- <file>meego.metainfo</file>
- <file>images/button.png</file>
- <file>images/button16.png</file>
- <file>images/checkbox.png</file>
- <file>images/checkbox16.png</file>
- <file>images/radiobutton.png</file>
- <file>images/radiobutton16.png</file>
- <file>images/window.png</file>
- <file>images/window16.png</file>
- <file>images/busyindicator.png</file>
- <file>images/busyindicator16.png</file>
- <file>images/busyindicatora.png</file>
- <file>images/busyindicatora16.png</file>
- <file>images/buttoncolumn.png</file>
- <file>images/buttoncolumn16.png</file>
- <file>images/buttonrow.png</file>
- <file>images/buttonrow16.png</file>
- <file>images/choicelist.png</file>
- <file>images/choicelist16.png</file>
- <file>images/item-icon.png</file>
- <file>images/item-icon16.png</file>
- <file>images/label.png</file>
- <file>images/label16.png</file>
- <file>images/lineedit.png</file>
- <file>images/lineedit16.png</file>
- <file>images/progressbar.png</file>
- <file>images/progressbar16.png</file>
- <file>images/slider.png</file>
- <file>images/slider16.png</file>
- <file>images/sliderh.png</file>
- <file>images/sliderh16.png</file>
- <file>images/switchbutton.png</file>
- <file>images/switchbutton16.png</file>
- <file>images/tabbutton.png</file>
- <file>images/tabbutton16.png</file>
- <file>images/textarea.png</file>
- <file>images/textarea16.png</file>
- <file>images/textfield.png</file>
- <file>images/textfield16.png</file>
- <file>images/toolbar.png</file>
- <file>images/toolbar16.png</file>
- </qresource>
-</RCC>
diff --git a/src/plugins/qmldesigner/meegoplugin/qtquickplugin.json b/src/plugins/qmldesigner/meegoplugin/qtquickplugin.json
deleted file mode 100644
index 97bcd69622..0000000000
--- a/src/plugins/qmldesigner/meegoplugin/qtquickplugin.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
-
-
-"Vendor" : "Digia Plc",
-
-
-
-
-"Category" : "Qt Quick",
-
-
-"Description" : "Plugin for Qt Quick Items.",
-
-
-"Url" : "http://www.qt-project.org"
-
-
-
-}
diff --git a/src/plugins/qmldesigner/qmldesigner.pro b/src/plugins/qmldesigner/qmldesigner.pro
index 35d3d36990..d8ef6fd563 100644
--- a/src/plugins/qmldesigner/qmldesigner.pro
+++ b/src/plugins/qmldesigner/qmldesigner.pro
@@ -1,3 +1,3 @@
TEMPLATE = subdirs
-SUBDIRS = qmldesignerplugin.pro qtquickplugin meegoplugin extrasplugin desktopplugin customstyleplugin
+SUBDIRS = qmldesignerplugin.pro qtquickplugin desktopplugin
diff --git a/src/plugins/qmldesigner/qmldesigner.qbs b/src/plugins/qmldesigner/qmldesigner.qbs
index 2db903d19d..7d709d37a5 100644
--- a/src/plugins/qmldesigner/qmldesigner.qbs
+++ b/src/plugins/qmldesigner/qmldesigner.qbs
@@ -20,440 +20,459 @@ QtcPlugin {
Depends { name: "QtSupport" }
Depends { name: "cpp" }
- cpp.defines: base.concat(project.additionalCppDefines.concat(["QWEAKPOINTER_ENABLE_ARROW"]))
- cpp.includePaths: [
- ".",
+ cpp.defines: base.concat(["QWEAKPOINTER_ENABLE_ARROW"])
+ cpp.includePaths: base.concat([
"designercore",
"designercore/include",
"../../../share/qtcreator/qml/qmlpuppet/interfaces",
"../../../share/qtcreator/qml/qmlpuppet/container",
"../../../share/qtcreator/qml/qmlpuppet/commands",
+ "components/componentcore",
"components/integration",
"components/propertyeditor",
"components/formeditor",
"components/itemlibrary",
"components/navigator",
"components/pluginmanager",
- "components/stateseditor",
- "..",
- "../../libs",
- buildDirectory
- ]
+ "components/stateseditor"
+ ])
+
+ Group {
+ prefix: "designercore/filemanager/"
+ files: [
+ "addarraymembervisitor.cpp",
+ "addarraymembervisitor.h",
+ "addobjectvisitor.cpp",
+ "addobjectvisitor.h",
+ "addpropertyvisitor.cpp",
+ "addpropertyvisitor.h",
+ "astobjecttextextractor.cpp",
+ "astobjecttextextractor.h",
+ "changeimportsvisitor.cpp",
+ "changeimportsvisitor.h",
+ "changeobjecttypevisitor.cpp",
+ "changeobjecttypevisitor.h",
+ "changepropertyvisitor.cpp",
+ "changepropertyvisitor.h",
+ "firstdefinitionfinder.cpp",
+ "firstdefinitionfinder.h",
+ "moveobjectbeforeobjectvisitor.cpp",
+ "moveobjectbeforeobjectvisitor.h",
+ "moveobjectvisitor.cpp",
+ "moveobjectvisitor.h",
+ "objectlengthcalculator.cpp",
+ "objectlengthcalculator.h",
+ "qmlrefactoring.cpp",
+ "qmlrefactoring.h",
+ "qmlrewriter.cpp",
+ "qmlrewriter.h",
+ "removepropertyvisitor.cpp",
+ "removepropertyvisitor.h",
+ "removeuiobjectmembervisitor.cpp",
+ "removeuiobjectmembervisitor.h",
+ ]
+ }
+
+ Group {
+ prefix: "../../../share/qtcreator/qml/qmlpuppet/"
+ files: [
+ "commands/changeauxiliarycommand.cpp",
+ "commands/changeauxiliarycommand.h",
+ "commands/changebindingscommand.cpp",
+ "commands/changebindingscommand.h",
+ "commands/changefileurlcommand.cpp",
+ "commands/changefileurlcommand.h",
+ "commands/changeidscommand.cpp",
+ "commands/changeidscommand.h",
+ "commands/changenodesourcecommand.cpp",
+ "commands/changenodesourcecommand.h",
+ "commands/changestatecommand.cpp",
+ "commands/changestatecommand.h",
+ "commands/changevaluescommand.cpp",
+ "commands/changevaluescommand.h",
+ "commands/childrenchangedcommand.cpp",
+ "commands/childrenchangedcommand.h",
+ "commands/clearscenecommand.cpp",
+ "commands/clearscenecommand.h",
+ "commands/completecomponentcommand.cpp",
+ "commands/completecomponentcommand.h",
+ "commands/componentcompletedcommand.cpp",
+ "commands/componentcompletedcommand.h",
+ "commands/createinstancescommand.cpp",
+ "commands/createinstancescommand.h",
+ "commands/createscenecommand.cpp",
+ "commands/createscenecommand.h",
+ "commands/informationchangedcommand.cpp",
+ "commands/informationchangedcommand.h",
+ "commands/pixmapchangedcommand.cpp",
+ "commands/pixmapchangedcommand.h",
+ "commands/removeinstancescommand.cpp",
+ "commands/removeinstancescommand.h",
+ "commands/removepropertiescommand.cpp",
+ "commands/removepropertiescommand.h",
+ "commands/reparentinstancescommand.cpp",
+ "commands/reparentinstancescommand.h",
+ "commands/statepreviewimagechangedcommand.cpp",
+ "commands/statepreviewimagechangedcommand.h",
+ "commands/synchronizecommand.cpp",
+ "commands/synchronizecommand.h",
+ "commands/tokencommand.cpp",
+ "commands/tokencommand.h",
+ "commands/valueschangedcommand.cpp",
+ "commands/valueschangedcommand.h",
+ "container/addimportcontainer.cpp",
+ "container/addimportcontainer.h",
+ "container/idcontainer.cpp",
+ "container/idcontainer.h",
+ "container/imagecontainer.cpp",
+ "container/imagecontainer.h",
+ "container/informationcontainer.cpp",
+ "container/informationcontainer.h",
+ "container/instancecontainer.cpp",
+ "container/instancecontainer.h",
+ "container/propertyabstractcontainer.cpp",
+ "container/propertyabstractcontainer.h",
+ "container/propertybindingcontainer.cpp",
+ "container/propertybindingcontainer.h",
+ "container/propertyvaluecontainer.cpp",
+ "container/propertyvaluecontainer.h",
+ "container/reparentcontainer.cpp",
+ "container/reparentcontainer.h",
+ "interfaces/commondefines.h",
+ "interfaces/nodeinstanceclientinterface.h",
+ "interfaces/nodeinstanceserverinterface.cpp",
+ "interfaces/nodeinstanceserverinterface.h",
+ ]
+ }
+
+ Group {
+ prefix: "designercore/"
+ files: [
+ "rewritertransaction.cpp",
+ "rewritertransaction.h",
+ "exceptions/exception.cpp",
+ "exceptions/invalidargumentexception.cpp",
+ "exceptions/invalididexception.cpp",
+ "exceptions/invalidmetainfoexception.cpp",
+ "exceptions/invalidmodelnodeexception.cpp",
+ "exceptions/invalidmodelstateexception.cpp",
+ "exceptions/invalidpropertyexception.cpp",
+ "exceptions/invalidqmlsourceexception.cpp",
+ "exceptions/invalidreparentingexception.cpp",
+ "exceptions/invalidslideindexexception.cpp",
+ "exceptions/notimplementedexception.cpp",
+ "exceptions/removebasestateexception.cpp",
+ "exceptions/rewritingexception.cpp",
+ "include/abstractproperty.h",
+ "include/abstractview.h",
+ "include/basetexteditmodifier.h",
+ "include/basetexteditmodifier.h",
+ "include/bindingproperty.h",
+ "include/componenttextmodifier.h",
+ "include/corelib_global.h",
+ "include/customnotifications.h",
+ "include/exception.h",
+ "include/forwardview.h",
+ "include/import.h",
+ "include/invalidargumentexception.h",
+ "include/invalididexception.h",
+ "include/invalidmetainfoexception.h",
+ "include/invalidmodelnodeexception.h",
+ "include/invalidmodelstateexception.h",
+ "include/invalidpropertyexception.h",
+ "include/invalidqmlsourceexception.h",
+ "include/invalidreparentingexception.h",
+ "include/invalidslideindexexception.h",
+ "include/itemlibraryinfo.h",
+ "include/mathutils.h",
+ "include/metainfo.h",
+ "include/metainfoparser.h",
+ "include/model.h",
+ "include/modelmerger.h",
+ "include/modelnode.h",
+ "include/modelnodepositionstorage.h",
+ "include/nodeabstractproperty.h",
+ "include/nodeinstance.h",
+ "include/nodeinstanceview.h",
+ "include/nodelistproperty.h",
+ "include/nodemetainfo.h",
+ "include/nodeproperty.h",
+ "include/notimplementedexception.h",
+ "include/plaintexteditmodifier.h",
+ "include/propertycontainer.h",
+ "include/propertynode.h",
+ "include/propertyparser.h",
+ "include/qmlanchors.h",
+ "include/qmlchangeset.h",
+ "include/qmlitemnode.h",
+ "include/qmlmodelnodefacade.h",
+ "include/qmlmodelview.h",
+ "include/qmlobjectnode.h",
+ "include/qmlstate.h",
+ "include/removebasestateexception.h",
+ "include/rewriterview.h",
+ "include/rewritingexception.h",
+ "include/subcomponentmanager.h",
+ "include/textmodifier.h",
+ "include/variantproperty.h",
+ "instances/nodeinstance.cpp",
+ "instances/nodeinstanceserverproxy.cpp",
+ "instances/nodeinstanceserverproxy.h",
+ "instances/nodeinstanceview.cpp",
+ "metainfo/itemlibraryinfo.cpp",
+ "metainfo/metainfo.cpp",
+ "metainfo/metainfoparser.cpp",
+ "metainfo/nodemetainfo.cpp",
+ "metainfo/subcomponentmanager.cpp",
+ "model/abstractproperty.cpp",
+ "model/abstractview.cpp",
+ "model/basetexteditmodifier.cpp",
+ "model/bindingproperty.cpp",
+ "model/componenttextmodifier.cpp",
+ "model/import.cpp",
+ "model/internalbindingproperty.cpp",
+ "model/internalbindingproperty.h",
+ "model/internalnode.cpp",
+ "model/internalnode_p.h",
+ "model/internalnodeabstractproperty.cpp",
+ "model/internalnodeabstractproperty.h",
+ "model/internalnodelistproperty.cpp",
+ "model/internalnodelistproperty.h",
+ "model/internalnodeproperty.cpp",
+ "model/internalnodeproperty.h",
+ "model/internalproperty.cpp",
+ "model/internalproperty.h",
+ "model/internalvariantproperty.cpp",
+ "model/internalvariantproperty.h",
+ "model/model.cpp",
+ "model/model_p.h",
+ "model/modelmerger.cpp",
+ "model/modelnode.cpp",
+ "model/modelnodepositionrecalculator.cpp",
+ "model/modelnodepositionrecalculator.h",
+ "model/modelnodepositionstorage.cpp",
+ "model/modeltotextmerger.cpp",
+ "model/modeltotextmerger.h",
+ "model/nodeabstractproperty.cpp",
+ "model/nodelistproperty.cpp",
+ "model/nodeproperty.cpp",
+ "model/painteventfilter.cpp",
+ "model/painteventfilter_p.h",
+ "model/plaintexteditmodifier.cpp",
+ "model/propertycontainer.cpp",
+ "model/propertynode.cpp",
+ "model/propertyparser.cpp",
+ "model/qmlanchors.cpp",
+ "model/qmlchangeset.cpp",
+ "model/qmlitemnode.cpp",
+ "model/qmlmodelnodefacade.cpp",
+ "model/qmlmodelview.cpp",
+ "model/qmlobjectnode.cpp",
+ "model/qmlstate.cpp",
+ "model/qmltextgenerator.cpp",
+ "model/qmltextgenerator.h",
+ "model/rewriteaction.cpp",
+ "model/rewriteaction.h",
+ "model/rewriteactioncompressor.cpp",
+ "model/rewriteactioncompressor.h",
+ "model/rewriterview.cpp",
+ "model/textmodifier.cpp",
+ "model/texttomodelmerger.cpp",
+ "model/texttomodelmerger.h",
+ "model/variantproperty.cpp",
+ "model/viewlogger.cpp",
+ "model/viewlogger.h",
+ "pluginmanager/widgetpluginmanager.cpp",
+ "pluginmanager/widgetpluginmanager.h",
+ "pluginmanager/widgetpluginpath.cpp",
+ "pluginmanager/widgetpluginpath.h",
+ ]
+ }
+
+ Group {
+ prefix: "components/"
+ files: [
+ "componentcore/modelnodecontextmenu.cpp",
+ "componentcore/modelnodecontextmenu.h",
+ "formeditor/abstractformeditortool.cpp",
+ "formeditor/abstractformeditortool.h",
+ "formeditor/controlelement.cpp",
+ "formeditor/controlelement.h",
+ "formeditor/dragtool.cpp",
+ "formeditor/dragtool.h",
+ "formeditor/formeditor.qrc",
+ "formeditor/formeditorgraphicsview.cpp",
+ "formeditor/formeditorgraphicsview.h",
+ "formeditor/formeditoritem.cpp",
+ "formeditor/formeditoritem.h",
+ "formeditor/formeditorscene.cpp",
+ "formeditor/formeditorscene.h",
+ "formeditor/formeditorview.cpp",
+ "formeditor/formeditorview.h",
+ "formeditor/formeditorwidget.cpp",
+ "formeditor/formeditorwidget.h",
+ "formeditor/itemutilfunctions.cpp",
+ "formeditor/itemutilfunctions.h",
+ "formeditor/layeritem.cpp",
+ "formeditor/layeritem.h",
+ "formeditor/lineeditaction.cpp",
+ "formeditor/lineeditaction.h",
+ "formeditor/movemanipulator.cpp",
+ "formeditor/movemanipulator.h",
+ "formeditor/movetool.cpp",
+ "formeditor/movetool.h",
+ "formeditor/numberseriesaction.cpp",
+ "formeditor/numberseriesaction.h",
+ "formeditor/onedimensionalcluster.cpp",
+ "formeditor/onedimensionalcluster.h",
+ "formeditor/resizecontroller.cpp",
+ "formeditor/resizecontroller.h",
+ "formeditor/resizehandleitem.cpp",
+ "formeditor/resizehandleitem.h",
+ "formeditor/resizeindicator.cpp",
+ "formeditor/resizeindicator.h",
+ "formeditor/resizemanipulator.cpp",
+ "formeditor/resizemanipulator.h",
+ "formeditor/resizetool.cpp",
+ "formeditor/resizetool.h",
+ "formeditor/rubberbandselectionmanipulator.cpp",
+ "formeditor/rubberbandselectionmanipulator.h",
+ "formeditor/scaleitem.cpp",
+ "formeditor/scaleitem.h",
+ "formeditor/scalemanipulator.cpp",
+ "formeditor/scalemanipulator.h",
+ "formeditor/selectionindicator.cpp",
+ "formeditor/selectionindicator.h",
+ "formeditor/selectionrectangle.cpp",
+ "formeditor/selectionrectangle.h",
+ "formeditor/selectiontool.cpp",
+ "formeditor/selectiontool.h",
+ "formeditor/singleselectionmanipulator.cpp",
+ "formeditor/singleselectionmanipulator.h",
+ "formeditor/snapper.cpp",
+ "formeditor/snapper.h",
+ "formeditor/snappinglinecreator.cpp",
+ "formeditor/snappinglinecreator.h",
+ "formeditor/toolbox.cpp",
+ "formeditor/toolbox.h",
+ "formeditor/zoomaction.cpp",
+ "formeditor/zoomaction.h",
+ "integration/componentaction.cpp",
+ "integration/componentaction.h",
+ "integration/componentview.cpp",
+ "integration/componentview.h",
+ "integration/designdocumentcontroller.cpp",
+ "integration/designdocumentcontroller.h",
+ "integration/designdocumentcontrollerview.cpp",
+ "integration/designdocumentcontrollerview.h",
+ "integration/stackedutilitypanelcontroller.cpp",
+ "integration/stackedutilitypanelcontroller.h",
+ "integration/utilitypanelcontroller.cpp",
+ "integration/utilitypanelcontroller.h",
+ "integration/xuifiledialog.cpp",
+ "integration/xuifiledialog.h",
+ "itemlibrary/customdraganddrop.cpp",
+ "itemlibrary/customdraganddrop.h",
+ "itemlibrary/itemlibrary.qrc",
+ "itemlibrary/itemlibrarycomponents.cpp",
+ "itemlibrary/itemlibrarycomponents.h",
+ "itemlibrary/itemlibraryimageprovider.cpp",
+ "itemlibrary/itemlibraryimageprovider.h",
+ "itemlibrary/itemlibrarymodel.cpp",
+ "itemlibrary/itemlibrarymodel.h",
+ "itemlibrary/itemlibraryview.cpp",
+ "itemlibrary/itemlibraryview.h",
+ "itemlibrary/itemlibrarywidget.cpp",
+ "itemlibrary/itemlibrarywidget.h",
+ "itemlibrary/qml/ItemView.qml",
+ "itemlibrary/qml/ItemsView.qml",
+ "itemlibrary/qml/ItemsViewStyle.qml",
+ "itemlibrary/qml/Scrollbar.qml",
+ "itemlibrary/qml/SectionView.qml",
+ "itemlibrary/qml/Selector.qml",
+ "navigator/navigator.qrc",
+ "navigator/navigatortreemodel.cpp",
+ "navigator/navigatortreemodel.h",
+ "navigator/navigatortreeview.cpp",
+ "navigator/navigatortreeview.h",
+ "navigator/navigatorview.cpp",
+ "navigator/navigatorview.h",
+ "navigator/navigatorwidget.cpp",
+ "navigator/navigatorwidget.h",
+ "pluginmanager/iplugin.cpp",
+ "pluginmanager/iplugin.h",
+ "pluginmanager/pluginmanager.cpp",
+ "pluginmanager/pluginmanager.h",
+ "pluginmanager/pluginpath.cpp",
+ "pluginmanager/pluginpath.h",
+ "propertyeditor/basiclayouts.cpp",
+ "propertyeditor/basiclayouts.h",
+ "propertyeditor/basicwidgets.cpp",
+ "propertyeditor/basicwidgets.h",
+ "propertyeditor/behaviordialog.cpp",
+ "propertyeditor/behaviordialog.h",
+ "propertyeditor/behaviordialog.ui",
+ "propertyeditor/declarativewidgetview.cpp",
+ "propertyeditor/declarativewidgetview.h",
+ "propertyeditor/designerpropertymap.h",
+ "propertyeditor/filewidget.cpp",
+ "propertyeditor/filewidget.h",
+ "propertyeditor/fontwidget.cpp",
+ "propertyeditor/fontwidget.h",
+ "propertyeditor/gradientlineqmladaptor.cpp",
+ "propertyeditor/gradientlineqmladaptor.h",
+ "propertyeditor/layoutwidget.cpp",
+ "propertyeditor/layoutwidget.h",
+ "propertyeditor/originwidget.cpp",
+ "propertyeditor/originwidget.h",
+ "propertyeditor/propertyeditor.cpp",
+ "propertyeditor/propertyeditor.h",
+ "propertyeditor/propertyeditor.qrc",
+ "propertyeditor/propertyeditorcontextobject.cpp",
+ "propertyeditor/propertyeditorcontextobject.h",
+ "propertyeditor/propertyeditortransaction.cpp",
+ "propertyeditor/propertyeditortransaction.h",
+ "propertyeditor/propertyeditorvalue.cpp",
+ "propertyeditor/propertyeditorvalue.h",
+ "propertyeditor/qlayoutobject.cpp",
+ "propertyeditor/qlayoutobject.h",
+ "propertyeditor/qmlanchorbindingproxy.cpp",
+ "propertyeditor/qmlanchorbindingproxy.h",
+ "propertyeditor/qproxylayoutitem.cpp",
+ "propertyeditor/qproxylayoutitem.h",
+ "propertyeditor/resetwidget.cpp",
+ "propertyeditor/resetwidget.h",
+ "propertyeditor/siblingcombobox.cpp",
+ "propertyeditor/siblingcombobox.h",
+ "resources/resources.qrc",
+ "stateseditor/HorizontalScrollBar.qml",
+ "stateseditor/stateseditor.qrc",
+ "stateseditor/stateseditorimageprovider.cpp",
+ "stateseditor/stateseditorimageprovider.cpp",
+ "stateseditor/stateseditormodel.cpp",
+ "stateseditor/stateseditormodel.h",
+ "stateseditor/stateseditorview.cpp",
+ "stateseditor/stateseditorview.h",
+ "stateseditor/stateseditorwidget.cpp",
+ "stateseditor/stateseditorwidget.h",
+ "stateseditor/stateslist.qml",
+ ]
+ }
files: [
- "designercore/filemanager/qmlrewriter.h",
- "designercore/filemanager/qmlrefactoring.h",
- "designercore/filemanager/changeobjecttypevisitor.h",
- "designercore/filemanager/changepropertyvisitor.h",
- "designercore/filemanager/removeuiobjectmembervisitor.h",
- "designercore/filemanager/removepropertyvisitor.h",
- "designercore/filemanager/addpropertyvisitor.h",
- "designercore/filemanager/moveobjectvisitor.h",
- "designercore/filemanager/addobjectvisitor.h",
- "designercore/filemanager/addarraymembervisitor.h",
- "designercore/filemanager/astobjecttextextractor.h",
- "designercore/filemanager/objectlengthcalculator.h",
- "designercore/filemanager/firstdefinitionfinder.h",
- "designercore/filemanager/moveobjectbeforeobjectvisitor.h",
- "designercore/filemanager/changeimportsvisitor.h",
- "designercore/include/nodeinstance.h",
- "designercore/instances/nodeinstanceserverproxy.h",
- "../../../share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceclientinterface.h",
- "../../../share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.h",
- "../../../share/qtcreator/qml/qmlpuppet/interfaces/commondefines.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/synchronizecommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/tokencommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/statepreviewimagechangedcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/childrenchangedcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changebindingscommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changefileurlcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changeidscommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changestatecommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changevaluescommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/createscenecommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/clearscenecommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/createinstancescommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/informationchangedcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/pixmapchangedcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/removepropertiescommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changeauxiliarycommand.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/addimportcontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/imagecontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/idcontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/informationcontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/instancecontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/reparentcontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/propertyabstractcontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/propertybindingcontainer.h",
- "../../../share/qtcreator/qml/qmlpuppet/container/propertyvaluecontainer.h",
- "designercore/include/corelib_global.h",
- "designercore/include/abstractview.h",
- "designercore/include/nodeinstanceview.h",
- "designercore/include/rewriterview.h",
- "designercore/include/metainfo.h",
- "designercore/include/metainfoparser.h",
- "designercore/include/nodemetainfo.h",
- "designercore/include/itemlibraryinfo.h",
- "designercore/model/internalproperty.h",
- "designercore/include/modelnode.h",
- "designercore/include/model.h",
- "designercore/include/nodeproperty.h",
- "designercore/include/subcomponentmanager.h",
- "designercore/include/propertycontainer.h",
- "designercore/model/internalnode_p.h",
- "designercore/model/model_p.h",
- "designercore/model/painteventfilter_p.h",
- "designercore/include/propertyparser.h",
- "designercore/pluginmanager/widgetpluginmanager.h",
- "designercore/pluginmanager/widgetpluginpath.h",
- "designercore/include/exception.h",
- "designercore/include/invalidreparentingexception.h",
- "designercore/include/invalidmetainfoexception.h",
- "designercore/include/invalidargumentexception.h",
- "designercore/include/notimplementedexception.h",
- "designercore/include/invalidpropertyexception.h",
- "designercore/include/invalidmodelstateexception.h",
- "designercore/include/removebasestateexception.h",
- "designercore/include/invalididexception.h",
- "designercore/include/propertynode.h",
- "designercore/include/invalidslideindexexception.h",
- "designercore/include/import.h",
- "designercore/include/invalidqmlsourceexception.h",
- "designercore/model/viewlogger.h",
- "designercore/model/internalvariantproperty.h",
- "designercore/model/internalnodelistproperty.h",
- "designercore/include/variantproperty.h",
- "designercore/include/nodelistproperty.h",
- "designercore/include/abstractproperty.h",
- "designercore/model/internalbindingproperty.h",
- "designercore/include/bindingproperty.h",
- "designercore/model/internalnodeproperty.h",
- "designercore/model/internalnodeabstractproperty.h",
- "designercore/include/nodeabstractproperty.h",
- "designercore/include/plaintexteditmodifier.h",
- "designercore/include/basetexteditmodifier.h",
- "designercore/include/componenttextmodifier.h",
- "designercore/include/textmodifier.h",
- "designercore/model/modeltotextmerger.h",
- "designercore/model/texttomodelmerger.h",
- "designercore/include/qmlmodelview.h",
- "designercore/include/qmlitemnode.h",
- "designercore/include/qmlstate.h",
- "designercore/include/qmlchangeset.h",
- "designercore/include/qmlmodelnodefacade.h",
- "designercore/include/forwardview.h",
- "designercore/include/qmlobjectnode.h",
- "designercore/include/qmlanchors.h",
- "designercore/rewritertransaction.h",
- "designercore/model/rewriteaction.h",
- "designercore/include/modelnodepositionstorage.h",
- "designercore/model/modelnodepositionrecalculator.h",
- "designercore/model/rewriteactioncompressor.h",
- "designercore/model/qmltextgenerator.h",
- "designercore/include/modelmerger.h",
- "designercore/include/mathutils.h",
- "designercore/include/customnotifications.h",
- "designercore/include/rewritingexception.h",
- "designercore/model/modelnodecontextmenu.h",
- "designercore/include/basetexteditmodifier.h",
- "components/integration/integrationcore.h",
- "components/integration/designdocumentcontrollerview.h",
- "components/integration/designdocumentcontroller.h",
- "components/integration/utilitypanelcontroller.h",
- "components/integration/stackedutilitypanelcontroller.h",
- "components/integration/componentaction.h",
- "components/integration/componentview.h",
- "components/integration/xuifiledialog.h",
- "components/integration/integrationcore.cpp",
- "components/integration/designdocumentcontroller.cpp",
- "components/integration/designdocumentcontrollerview.cpp",
- "components/integration/utilitypanelcontroller.cpp",
- "components/integration/stackedutilitypanelcontroller.cpp",
- "components/integration/componentaction.cpp",
- "components/integration/componentview.cpp",
- "components/integration/xuifiledialog.cpp",
- "components/propertyeditor/propertyeditor.h",
- "components/propertyeditor/qmlanchorbindingproxy.h",
- "components/propertyeditor/resetwidget.h",
- "components/propertyeditor/qlayoutobject.h",
- "components/propertyeditor/basiclayouts.h",
- "components/propertyeditor/basicwidgets.h",
- "components/propertyeditor/behaviordialog.h",
- "components/propertyeditor/qproxylayoutitem.h",
- "components/propertyeditor/layoutwidget.h",
- "components/propertyeditor/filewidget.h",
- "components/propertyeditor/propertyeditorvalue.h",
- "components/propertyeditor/fontwidget.h",
- "components/propertyeditor/originwidget.h",
- "components/propertyeditor/siblingcombobox.h",
- "components/propertyeditor/propertyeditortransaction.h",
- "components/propertyeditor/designerpropertymap.h",
- "components/propertyeditor/propertyeditorcontextobject.h",
- "components/propertyeditor/declarativewidgetview.h",
- "components/propertyeditor/gradientlineqmladaptor.h",
- "components/propertyeditor/propertyeditor.cpp",
- "components/propertyeditor/qmlanchorbindingproxy.cpp",
- "components/propertyeditor/resetwidget.cpp",
- "components/propertyeditor/qlayoutobject.cpp",
- "components/propertyeditor/basiclayouts.cpp",
- "components/propertyeditor/basicwidgets.cpp",
- "components/propertyeditor/behaviordialog.cpp",
- "components/propertyeditor/qproxylayoutitem.cpp",
- "components/propertyeditor/layoutwidget.cpp",
- "components/propertyeditor/filewidget.cpp",
- "components/propertyeditor/propertyeditorvalue.cpp",
- "components/propertyeditor/fontwidget.cpp",
- "components/propertyeditor/originwidget.cpp",
- "components/propertyeditor/siblingcombobox.cpp",
- "components/propertyeditor/propertyeditortransaction.cpp",
- "components/propertyeditor/propertyeditorcontextobject.cpp",
- "components/propertyeditor/declarativewidgetview.cpp",
- "components/propertyeditor/gradientlineqmladaptor.cpp",
- "components/propertyeditor/propertyeditor.qrc",
- "components/formeditor/formeditorscene.h",
- "components/formeditor/formeditorwidget.h",
- "components/formeditor/formeditoritem.h",
- "components/formeditor/formeditorview.h",
- "components/formeditor/selectiontool.h",
- "components/formeditor/abstractformeditortool.h",
- "components/formeditor/controlelement.h",
- "components/formeditor/resizemanipulator.h",
- "components/formeditor/movemanipulator.h",
- "components/formeditor/layeritem.h",
- "components/formeditor/itemutilfunctions.h",
- "components/formeditor/selectionrectangle.h",
- "components/formeditor/rubberbandselectionmanipulator.h",
- "components/formeditor/movetool.h",
- "components/formeditor/selectionindicator.h",
- "components/formeditor/snappinglinecreator.h",
- "components/formeditor/snapper.h",
- "components/formeditor/onedimensionalcluster.h",
- "components/formeditor/singleselectionmanipulator.h",
- "components/formeditor/scalemanipulator.h",
- "components/formeditor/resizetool.h",
- "components/formeditor/resizeindicator.h",
- "components/formeditor/scaleitem.h",
- "components/formeditor/resizecontroller.h",
- "components/formeditor/resizehandleitem.h",
- "components/formeditor/dragtool.h",
- "components/formeditor/toolbox.h",
- "components/formeditor/zoomaction.h",
- "components/formeditor/formeditorgraphicsview.h",
- "components/formeditor/numberseriesaction.h",
- "components/formeditor/lineeditaction.h",
- "components/formeditor/formeditoritem.cpp",
- "components/formeditor/formeditorview.cpp",
- "components/formeditor/formeditorscene.cpp",
- "components/formeditor/formeditorwidget.cpp",
- "components/formeditor/selectiontool.cpp",
- "components/formeditor/abstractformeditortool.cpp",
- "components/formeditor/controlelement.cpp",
- "components/formeditor/resizemanipulator.cpp",
- "components/formeditor/movemanipulator.cpp",
- "components/formeditor/layeritem.cpp",
- "components/formeditor/itemutilfunctions.cpp",
- "components/formeditor/selectionrectangle.cpp",
- "components/formeditor/rubberbandselectionmanipulator.cpp",
- "components/formeditor/movetool.cpp",
- "components/formeditor/selectionindicator.cpp",
- "components/formeditor/snappinglinecreator.cpp",
- "components/formeditor/snapper.cpp",
- "components/formeditor/onedimensionalcluster.cpp",
- "components/formeditor/singleselectionmanipulator.cpp",
- "components/formeditor/scalemanipulator.cpp",
- "components/formeditor/resizetool.cpp",
- "components/formeditor/resizeindicator.cpp",
- "components/formeditor/scaleitem.cpp",
- "components/formeditor/resizecontroller.cpp",
- "components/formeditor/resizehandleitem.cpp",
- "components/formeditor/dragtool.cpp",
- "components/formeditor/toolbox.cpp",
- "components/formeditor/zoomaction.cpp",
- "components/formeditor/formeditorgraphicsview.cpp",
- "components/formeditor/numberseriesaction.cpp",
- "components/formeditor/lineeditaction.cpp",
- "components/formeditor/formeditor.qrc",
- "qmldesignerconstants.h",
- "qmldesignerplugin.h",
- "designmodewidget.h",
+ "designersettings.cpp",
"designersettings.h",
- "settingspage.h",
+ "designmodecontext.cpp",
"designmodecontext.h",
- "styledoutputpaneplaceholder.h",
- "designercore/filemanager/qmlrewriter.cpp",
- "designercore/filemanager/qmlrefactoring.cpp",
- "designercore/filemanager/changeobjecttypevisitor.cpp",
- "designercore/filemanager/changepropertyvisitor.cpp",
- "designercore/filemanager/removeuiobjectmembervisitor.cpp",
- "designercore/filemanager/removepropertyvisitor.cpp",
- "designercore/filemanager/addpropertyvisitor.cpp",
- "designercore/filemanager/moveobjectvisitor.cpp",
- "designercore/filemanager/addobjectvisitor.cpp",
- "designercore/filemanager/addarraymembervisitor.cpp",
- "designercore/filemanager/astobjecttextextractor.cpp",
- "designercore/filemanager/objectlengthcalculator.cpp",
- "designercore/filemanager/firstdefinitionfinder.cpp",
- "designercore/filemanager/moveobjectbeforeobjectvisitor.cpp",
- "designercore/filemanager/changeimportsvisitor.cpp",
- "designercore/instances/nodeinstanceserverproxy.cpp",
- "designercore/instances/nodeinstance.cpp",
- "designercore/instances/nodeinstanceview.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/interfaces/nodeinstanceserverinterface.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/synchronizecommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/tokencommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/componentcompletedcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/completecomponentcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/statepreviewimagechangedcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/childrenchangedcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changebindingscommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changefileurlcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changeidscommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changenodesourcecommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changestatecommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changevaluescommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/informationchangedcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/removeinstancescommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/removepropertiescommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/reparentinstancescommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/valueschangedcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/clearscenecommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/createinstancescommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/createscenecommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/pixmapchangedcommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/commands/changeauxiliarycommand.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/addimportcontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/imagecontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/idcontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/informationcontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/instancecontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/reparentcontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/propertyabstractcontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/propertybindingcontainer.cpp",
- "../../../share/qtcreator/qml/qmlpuppet/container/propertyvaluecontainer.cpp",
- "designercore/model/abstractview.cpp",
- "designercore/model/rewriterview.cpp",
- "designercore/metainfo/metainfo.cpp",
- "designercore/metainfo/metainfoparser.cpp",
- "designercore/metainfo/nodemetainfo.cpp",
- "designercore/metainfo/itemlibraryinfo.cpp",
- "designercore/metainfo/subcomponentmanager.cpp",
- "designercore/model/internalproperty.cpp",
- "designercore/model/model.cpp",
- "designercore/model/modelnode.cpp",
- "designercore/model/painteventfilter.cpp",
- "designercore/model/internalnode.cpp",
- "designercore/model/propertyparser.cpp",
- "designercore/model/propertycontainer.cpp",
- "designercore/pluginmanager/widgetpluginmanager.cpp",
- "designercore/pluginmanager/widgetpluginpath.cpp",
- "designercore/exceptions/exception.cpp",
- "designercore/exceptions/invalidpropertyexception.cpp",
- "designercore/exceptions/invalidmodelnodeexception.cpp",
- "designercore/exceptions/invalidreparentingexception.cpp",
- "designercore/exceptions/invalidmetainfoexception.cpp",
- "designercore/exceptions/invalidargumentexception.cpp",
- "designercore/exceptions/notimplementedexception.cpp",
- "designercore/exceptions/invalidmodelstateexception.cpp",
- "designercore/exceptions/removebasestateexception.cpp",
- "designercore/exceptions/invalididexception.cpp",
- "designercore/model/propertynode.cpp",
- "designercore/exceptions/invalidslideindexexception.cpp",
- "designercore/model/import.cpp",
- "designercore/exceptions/invalidqmlsourceexception.cpp",
- "designercore/model/viewlogger.cpp",
- "designercore/model/internalvariantproperty.cpp",
- "designercore/model/internalnodelistproperty.cpp",
- "designercore/model/variantproperty.cpp",
- "designercore/model/nodelistproperty.cpp",
- "designercore/model/abstractproperty.cpp",
- "designercore/model/internalbindingproperty.cpp",
- "designercore/model/bindingproperty.cpp",
- "designercore/model/internalnodeproperty.cpp",
- "designercore/model/internalnodeabstractproperty.cpp",
- "designercore/model/nodeabstractproperty.cpp",
- "designercore/model/nodeproperty.cpp",
- "designercore/model/modeltotextmerger.cpp",
- "designercore/model/texttomodelmerger.cpp",
- "designercore/model/plaintexteditmodifier.cpp",
- "designercore/model/componenttextmodifier.cpp",
- "designercore/model/textmodifier.cpp",
- "designercore/model/qmlmodelview.cpp",
- "designercore/model/qmlitemnode.cpp",
- "designercore/model/qmlstate.cpp",
- "designercore/model/qmlchangeset.cpp",
- "designercore/model/qmlmodelnodefacade.cpp",
- "designercore/model/qmlobjectnode.cpp",
- "designercore/model/qmlanchors.cpp",
- "designercore/rewritertransaction.cpp",
- "designercore/model/rewriteaction.cpp",
- "designercore/model/modelnodepositionstorage.cpp",
- "designercore/model/modelnodepositionrecalculator.cpp",
- "designercore/model/rewriteactioncompressor.cpp",
- "designercore/model/qmltextgenerator.cpp",
- "designercore/model/modelmerger.cpp",
- "designercore/exceptions/rewritingexception.cpp",
- "designercore/model/modelnodecontextmenu.cpp",
- "designercore/model/basetexteditmodifier.cpp",
- "components/propertyeditor/behaviordialog.ui",
- "components/itemlibrary/itemlibraryview.cpp",
- "components/itemlibrary/itemlibrarywidget.cpp",
- "components/itemlibrary/customdraganddrop.cpp",
- "components/itemlibrary/itemlibrarymodel.cpp",
- "components/itemlibrary/itemlibrarycomponents.cpp",
- "components/itemlibrary/itemlibraryimageprovider.cpp",
- "components/itemlibrary/itemlibraryview.h",
- "components/itemlibrary/itemlibrarywidget.h",
- "components/itemlibrary/customdraganddrop.h",
- "components/itemlibrary/itemlibrarymodel.h",
- "components/itemlibrary/itemlibrarycomponents.h",
- "components/itemlibrary/itemlibraryimageprovider.h",
- "components/itemlibrary/itemlibrary.qrc",
- "components/navigator/navigatorview.h",
- "components/navigator/navigatortreemodel.h",
- "components/navigator/navigatorwidget.h",
- "components/navigator/navigatortreeview.h",
- "components/navigator/navigatorview.cpp",
- "components/navigator/navigatortreemodel.cpp",
- "components/navigator/navigatorwidget.cpp",
- "components/navigator/navigatortreeview.cpp",
- "components/navigator/navigator.qrc",
- "components/pluginmanager/pluginmanager.cpp",
- "components/pluginmanager/pluginpath.cpp",
- "components/pluginmanager/iplugin.cpp",
- "components/pluginmanager/pluginmanager.h",
- "components/pluginmanager/pluginpath.h",
- "components/pluginmanager/iplugin.h",
- "components/stateseditor/stateseditorwidget.h",
- "components/stateseditor/stateseditormodel.h",
- "components/stateseditor/stateseditorview.h",
- "components/stateseditor/stateseditorimageprovider.cpp",
- "components/stateseditor/stateseditorwidget.cpp",
- "components/stateseditor/stateseditormodel.cpp",
- "components/stateseditor/stateseditorview.cpp",
- "components/stateseditor/stateseditorimageprovider.cpp",
- "components/stateseditor/stateseditor.qrc",
- "components/stateseditor/stateslist.qml",
- "components/stateseditor/HorizontalScrollBar.qml",
- "qmldesignerplugin.cpp",
"designmodewidget.cpp",
- "designersettings.cpp",
+ "designmodewidget.h",
+ "qmldesignerconstants.h",
+ "qmldesignerplugin.cpp",
+ "qmldesignerplugin.h",
"settingspage.cpp",
- "designmodecontext.cpp",
- "styledoutputpaneplaceholder.cpp",
+ "settingspage.h",
"settingspage.ui",
- "components/resources/resources.qrc",
- "components/itemlibrary/qml/Selector.qml",
- "components/itemlibrary/qml/SectionView.qml",
- "components/itemlibrary/qml/Scrollbar.qml",
- "components/itemlibrary/qml/ItemView.qml",
- "components/itemlibrary/qml/ItemsViewStyle.qml",
- "components/itemlibrary/qml/ItemsView.qml"
+ "styledoutputpaneplaceholder.cpp",
+ "styledoutputpaneplaceholder.h",
]
}
-
diff --git a/src/plugins/qmldesigner/qmldesignerconstants.h b/src/plugins/qmldesigner/qmldesignerconstants.h
index 054c90bdde..ef62c14073 100644
--- a/src/plugins/qmldesigner/qmldesignerconstants.h
+++ b/src/plugins/qmldesigner/qmldesignerconstants.h
@@ -60,10 +60,14 @@ const char QML_CANVASWIDTH_KEY[] = "CanvasWidth";
const char QML_CANVASHEIGHT_KEY[] = "CanvasHeight";
const char QML_CONTEXTPANE_KEY[] = "ContextPaneEnabled";
const char QML_CONTEXTPANEPIN_KEY[] = "ContextPanePinned";
+const char QML_WARNIN_FOR_FEATURES_IN_DESIGNER_KEY[] = "WarnAboutQtQuickFeaturesInDesigner";
+const char QML_WARNIN_FOR_DESIGNER_FEATURES_IN_EDITOR_KEY[] = "WarnAboutQtQuickDesignerFeaturesInCodeEditor";
enum { QML_OPENDESIGNMODE_DEFAULT = 0 }; // 0 for text mode, 1 for design mode
const char SETTINGS_CATEGORY_QML_ICON[] = ":/core/images/category_qml.png";
+const char QML_DESIGNER_SUBFOLDER[] = "/designer/";
+
namespace Internal {
enum { debug = 0 };
}
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.cpp b/src/plugins/qmldesigner/qmldesignerplugin.cpp
index f7117009f9..abd3d9c67d 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.cpp
+++ b/src/plugins/qmldesigner/qmldesignerplugin.cpp
@@ -52,12 +52,13 @@
#include <coreplugin/mimedatabase.h>
#include <coreplugin/modemanager.h>
+#include <projectexplorer/projectexplorerconstants.h>
+
#include <extensionsystem/pluginmanager.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
-#include <integrationcore.h>
-
#include <QAction>
#include <QFileInfo>
@@ -67,9 +68,18 @@
#include <QProcessEnvironment>
namespace QmlDesigner {
-namespace Internal {
-BauhausPlugin *BauhausPlugin::m_pluginInstance = 0;
+QmlDesignerPlugin *QmlDesignerPlugin::m_instance = 0;
+
+static bool isQmlFile(Core::IEditor *editor)
+{
+ return editor && editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID;
+}
+
+static bool isInDesignerMode()
+{
+ return Core::ModeManager::currentMode() == Core::DesignMode::instance();
+}
bool shouldAssertInException()
{
@@ -77,16 +87,8 @@ bool shouldAssertInException()
return !processEnvironment.value("QMLDESIGNER_ASSERT_ON_EXCEPTION").isEmpty();
}
-BauhausPlugin::BauhausPlugin() :
- m_designerCore(0),
- m_designMode(0),
- m_isActive(false),
- m_revertToSavedAction(new QAction(this)),
- m_saveAction(new QAction(this)),
- m_saveAsAction(new QAction(this)),
- m_closeCurrentEditorAction(new QAction(this)),
- m_closeAllEditorsAction(new QAction(this)),
- m_closeOtherEditorsAction(new QAction(this))
+QmlDesignerPlugin::QmlDesignerPlugin() :
+ m_isActive(false)
{
// Exceptions should never ever assert: they are handled in a number of
@@ -103,10 +105,11 @@ BauhausPlugin::BauhausPlugin() :
Exception::setShouldAssert(shouldAssertInException());
}
-BauhausPlugin::~BauhausPlugin()
+QmlDesignerPlugin::~QmlDesignerPlugin()
{
- delete m_designerCore;
Core::ICore::removeContextObject(m_context);
+ m_context = 0;
+ m_instance = 0;
}
////////////////////////////////////////////////////
@@ -114,7 +117,7 @@ BauhausPlugin::~BauhausPlugin()
// INHERITED FROM ExtensionSystem::Plugin
//
////////////////////////////////////////////////////
-bool BauhausPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage/* = 0*/) // =0;
+bool QmlDesignerPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage/* = 0*/) // =0;
{
const Core::Context switchContext(QmlDesigner::Constants::C_QMLDESIGNER,
QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
@@ -124,22 +127,18 @@ bool BauhausPlugin::initialize(const QStringList & /*arguments*/, QString *error
switchAction, QmlDesigner::Constants::SWITCH_TEXT_DESIGN, switchContext);
command->setDefaultKeySequence(QKeySequence(Qt::Key_F4));
- m_designerCore = new QmlDesigner::IntegrationCore;
- m_pluginInstance = this;
-
-#ifdef Q_OS_MAC
- const QString pluginPath = QCoreApplication::applicationDirPath() + "/../PlugIns/QmlDesigner";
-#else
- const QString pluginPath = QCoreApplication::applicationDirPath() + "/../"
- + QLatin1String(IDE_LIBRARY_BASENAME) + "/qtcreator/qmldesigner";
-#endif
+ m_instance = this;
- m_designerCore->pluginManager()->setPluginPaths(QStringList() << pluginPath);
+ const QString pluginPath = Utils::HostOsInfo::isMacHost()
+ ? QString(QCoreApplication::applicationDirPath() + "/../PlugIns/QmlDesigner")
+ : QString(QCoreApplication::applicationDirPath() + "/../"
+ + QLatin1String(IDE_LIBRARY_BASENAME) + "/qtcreator/qmldesigner");
+ m_pluginManager.setPluginPaths(QStringList() << pluginPath);
createDesignModeWidget();
connect(switchAction, SIGNAL(triggered()), this, SLOT(switchTextDesign()));
- addAutoReleasedObject(new SettingsPage);
+ addAutoReleasedObject(new Internal::SettingsPage);
m_settings.fromSettings(Core::ICore::settings());
@@ -149,240 +148,302 @@ bool BauhausPlugin::initialize(const QStringList & /*arguments*/, QString *error
return true;
}
-void BauhausPlugin::createDesignModeWidget()
+void QmlDesignerPlugin::createDesignModeWidget()
{
- m_editorManager = Core::ICore::editorManager();
- Core::ActionContainer *editMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT);
+ m_mainWidget = new Internal::DesignModeWidget;
- m_mainWidget = new DesignModeWidget;
-
- m_context = new DesignModeContext(m_mainWidget);
+ m_context = new Internal::DesignModeContext(m_mainWidget);
Core::ICore::addContextObject(m_context);
Core::Context qmlDesignerMainContext(Constants::C_QMLDESIGNER);
Core::Context qmlDesignerFormEditorContext(Constants::C_QMLFORMEDITOR);
Core::Context qmlDesignerNavigatorContext(Constants::C_QMLNAVIGATOR);
- // Revert to saved
- Core::ActionManager::registerAction(m_revertToSavedAction,
- Core::Constants::REVERTTOSAVED, qmlDesignerMainContext);
- connect(m_revertToSavedAction, SIGNAL(triggered()), m_editorManager, SLOT(revertToSaved()));
-
- //Save
- Core::ActionManager::registerAction(m_saveAction, Core::Constants::SAVE, qmlDesignerMainContext);
- connect(m_saveAction, SIGNAL(triggered()), m_editorManager, SLOT(saveDocument()));
-
- //Save As
- Core::ActionManager::registerAction(m_saveAsAction, Core::Constants::SAVEAS, qmlDesignerMainContext);
- connect(m_saveAsAction, SIGNAL(triggered()), m_editorManager, SLOT(saveDocumentAs()));
-
- //Close Editor
- Core::ActionManager::registerAction(m_closeCurrentEditorAction, Core::Constants::CLOSE, qmlDesignerMainContext);
- connect(m_closeCurrentEditorAction, SIGNAL(triggered()), m_editorManager, SLOT(closeEditor()));
-
- //Close All
- Core::ActionManager::registerAction(m_closeAllEditorsAction, Core::Constants::CLOSEALL, qmlDesignerMainContext);
- connect(m_closeAllEditorsAction, SIGNAL(triggered()), m_editorManager, SLOT(closeAllEditors()));
-
- //Close All Others Action
- Core::ActionManager::registerAction(m_closeOtherEditorsAction, Core::Constants::CLOSEOTHERS, qmlDesignerMainContext);
- connect(m_closeOtherEditorsAction, SIGNAL(triggered()), m_editorManager, SLOT(closeOtherEditors()));
-
- // Undo / Redo
- Core::ActionManager::registerAction(m_mainWidget->undoAction(), Core::Constants::UNDO, qmlDesignerMainContext);
- Core::ActionManager::registerAction(m_mainWidget->redoAction(), Core::Constants::REDO, qmlDesignerMainContext);
-
- Core::Command *command;
-
- //GoIntoComponent
- command = Core::ActionManager::registerAction(m_mainWidget->goIntoComponentAction(),
- Constants::GO_INTO_COMPONENT, qmlDesignerMainContext);
- command->setDefaultKeySequence(QKeySequence(Qt::Key_F2));
-
- //Edit Menu
-
- command = Core::ActionManager::registerAction(m_mainWidget->deleteAction(),
- QmlDesigner::Constants::DELETE, qmlDesignerFormEditorContext);
- command = Core::ActionManager::registerAction(m_mainWidget->deleteAction(),
- QmlDesigner::Constants::DELETE, qmlDesignerNavigatorContext);
- command->setDefaultKeySequence(QKeySequence::Delete);
- command->setAttribute(Core::Command::CA_Hide); // don't show delete in other modes
- editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
-
- command = Core::ActionManager::registerAction(m_mainWidget->cutAction(),
- Core::Constants::CUT, qmlDesignerFormEditorContext);
- command = Core::ActionManager::registerAction(m_mainWidget->cutAction(),
- Core::Constants::CUT, qmlDesignerNavigatorContext);
- command->setDefaultKeySequence(QKeySequence::Cut);
- editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
-
- command = Core::ActionManager::registerAction(m_mainWidget->copyAction(),
- Core::Constants::COPY, qmlDesignerFormEditorContext);
- command = Core::ActionManager::registerAction(m_mainWidget->copyAction(),
- Core::Constants::COPY, qmlDesignerNavigatorContext);
- command->setDefaultKeySequence(QKeySequence::Copy);
- editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
-
- command = Core::ActionManager::registerAction(m_mainWidget->pasteAction(),
- Core::Constants::PASTE, qmlDesignerFormEditorContext);
- command = Core::ActionManager::registerAction(m_mainWidget->pasteAction(),
- Core::Constants::PASTE, qmlDesignerNavigatorContext);
- command->setDefaultKeySequence(QKeySequence::Paste);
- editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
-
- command = Core::ActionManager::registerAction(m_mainWidget->selectAllAction(),
- Core::Constants::SELECTALL, qmlDesignerFormEditorContext);
- command = Core::ActionManager::registerAction(m_mainWidget->selectAllAction(),
- Core::Constants::SELECTALL, qmlDesignerNavigatorContext);
-
- command->setDefaultKeySequence(QKeySequence::SelectAll);
- editMenu->addAction(command, Core::Constants::G_EDIT_SELECTALL);
-
- Core::ActionContainer *viewsMenu = Core::ActionManager::actionContainer(Core::Constants::M_WINDOW_VIEWS);
-
- command = Core::ActionManager::registerAction(m_mainWidget->toggleLeftSidebarAction(),
- Constants::TOGGLE_LEFT_SIDEBAR, qmlDesignerMainContext);
- command->setAttribute(Core::Command::CA_Hide);
- command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+0"));
- viewsMenu->addAction(command);
-
- command = Core::ActionManager::registerAction(m_mainWidget->toggleRightSidebarAction(),
- Constants::TOGGLE_RIGHT_SIDEBAR, qmlDesignerMainContext);
- command->setAttribute(Core::Command::CA_Hide);
- command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+Shift+0"));
- viewsMenu->addAction(command);
-
- command = Core::ActionManager::registerAction(m_mainWidget->restoreDefaultViewAction(),
- Constants::RESTORE_DEFAULT_VIEW, qmlDesignerMainContext);
- command->setAttribute(Core::Command::CA_Hide);
- viewsMenu->addAction(command);
-
- command = Core::ActionManager::registerAction(m_mainWidget->hideSidebarsAction(),
- Core::Constants::TOGGLE_SIDEBAR, qmlDesignerMainContext);
-
-#ifdef Q_OS_MACX
- // add second shortcut to trigger delete
- QAction *deleteAction = new QAction(m_mainWidget);
- deleteAction->setShortcut(QKeySequence(QLatin1String("Backspace")));
- connect(deleteAction, SIGNAL(triggered()), m_mainWidget->deleteAction(),
- SIGNAL(triggered()));
-
- m_mainWidget->addAction(deleteAction);
-#endif // Q_OS_MACX
-
- connect(m_editorManager, SIGNAL(currentEditorChanged(Core::IEditor*)),
- this, SLOT(updateEditor(Core::IEditor*)));
-
- connect(m_editorManager, SIGNAL(editorsClosed(QList<Core::IEditor*>)),
- this, SLOT(textEditorsClosed(QList<Core::IEditor*>)));
-
- connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext*,Core::Context)),
- this, SLOT(contextChanged(Core::IContext*,Core::Context)));
+ m_context->context().add(qmlDesignerMainContext);
+ m_context->context().add(qmlDesignerFormEditorContext);
+ m_context->context().add(qmlDesignerNavigatorContext);
+ m_context->context().add(ProjectExplorer::Constants::LANG_QMLJS);
+
+ m_shortCutManager.registerActions();
+
+ connect(Core::ICore::editorManager(),
+ SIGNAL(currentEditorChanged(Core::IEditor*)),
+ this,
+ SLOT(onCurrentEditorChanged(Core::IEditor*)));
+
+ connect(Core::ICore::editorManager(),
+ SIGNAL(editorsClosed(QList<Core::IEditor*>)),
+ this,
+ SLOT(onTextEditorsClosed(QList<Core::IEditor*>)));
+
+// connect(Core::ICore::editorManager(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+// &m_documentManager, SLOT(currentTextEditorChanged(Core::IEditor*)));
+
+// connect(Core::ICore::instance(), SIGNAL(contextChanged(Core::IContext*,Core::Context)),
+// this, SLOT(contextChanged(Core::IContext*,Core::Context)));
+
+ connect(Core::ModeManager::instance(),
+ SIGNAL(currentModeChanged(Core::IMode*,Core::IMode*)),
+ SLOT(onCurrentModeChanged(Core::IMode*,Core::IMode*)));
}
-void BauhausPlugin::updateEditor(Core::IEditor *editor)
+void QmlDesignerPlugin::showDesigner()
{
- if (editor && editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID
- && Core::ModeManager::currentMode() == m_designMode)
- {
- m_mainWidget->showEditor(editor);
+ Q_ASSERT(!m_documentManager.hasCurrentDesignDocument());
+
+ m_shortCutManager.disconnectUndoActions(currentDesignDocument());
+
+ m_documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
+
+ m_shortCutManager.connectUndoActions(currentDesignDocument());
+
+ m_mainWidget->initialize();
+
+ if (m_documentManager.hasCurrentDesignDocument()) {
+ activateAutoSynchronization();
+ m_viewManager.pushFileOnCrambleBar(m_documentManager.currentDesignDocument()->fileName());
+ }
+
+ m_shortCutManager.updateUndoActions(currentDesignDocument());
+}
+
+void QmlDesignerPlugin::hideDesigner()
+{
+ if (currentDesignDocument()->currentModel()
+ && !currentDesignDocument()->hasQmlSyntaxErrors())
+ jumpTextCursorToSelectedModelNode();
+
+
+ if (m_documentManager.hasCurrentDesignDocument()) {
+ deactivateAutoSynchronization();
+ m_mainWidget->saveSettings();
}
+
+ m_shortCutManager.disconnectUndoActions(currentDesignDocument());
+
+ m_documentManager.setCurrentDesignDocument(0);
+
+ m_shortCutManager.updateUndoActions(0);
}
-void BauhausPlugin::contextChanged(Core::IContext *context, const Core::Context &additionalContexts)
+void QmlDesignerPlugin::changeEditor()
{
- Q_UNUSED(context)
+ if (m_documentManager.hasCurrentDesignDocument()) {
+ deactivateAutoSynchronization();
+ m_mainWidget->saveSettings();
+ }
+
+ m_shortCutManager.disconnectUndoActions(currentDesignDocument());
+
+ m_documentManager.setCurrentDesignDocument(Core::EditorManager::currentEditor());
- foreach (int additionalContext, additionalContexts) {
- if (m_context->context().contains(additionalContext)) {
- m_isActive = true;
- m_mainWidget->showEditor(Core::EditorManager::currentEditor());
- return;
+ m_mainWidget->initialize();
+
+ m_shortCutManager.connectUndoActions(currentDesignDocument());
+
+ if (m_documentManager.hasCurrentDesignDocument()) {
+ m_viewManager.pushFileOnCrambleBar(m_documentManager.currentDesignDocument()->fileName());
+ activateAutoSynchronization();
+ }
+
+ m_shortCutManager.updateUndoActions(currentDesignDocument());
+}
+
+void QmlDesignerPlugin::jumpTextCursorToSelectedModelNode()
+{
+ // visual editor -> text editor
+ ModelNode selectedNode;
+ if (!currentDesignDocument()->rewriterView()->selectedModelNodes().isEmpty())
+ selectedNode = currentDesignDocument()->rewriterView()->selectedModelNodes().first();
+
+ if (selectedNode.isValid()) {
+ const int nodeOffset = currentDesignDocument()->rewriterView()->nodeOffset(selectedNode);
+ if (nodeOffset > 0) {
+ const ModelNode currentSelectedNode
+ = currentDesignDocument()->rewriterView()->nodeAtTextCursorPosition(currentDesignDocument()->plainTextEdit()->textCursor().position());
+ if (currentSelectedNode != selectedNode) {
+ int line, column;
+ currentDesignDocument()->textEditor()->convertPosition(nodeOffset, &line, &column);
+ currentDesignDocument()->textEditor()->gotoLine(line, column);
+ }
}
}
+}
+
+void QmlDesignerPlugin::selectModelNodeUnderTextCursor()
+{
+ const int cursorPos = currentDesignDocument()->plainTextEdit()->textCursor().position();
+ ModelNode node = currentDesignDocument()->rewriterView()->nodeAtTextCursorPosition(cursorPos);
+ if (currentDesignDocument()->rewriterView() && node.isValid()) {
+ currentDesignDocument()->rewriterView()->setSelectedModelNodes(QList<ModelNode>() << node);
+ }
+}
+
+void QmlDesignerPlugin::activateAutoSynchronization()
+{
+ // text editor -> visual editor
+ if (!currentDesignDocument()->isDocumentLoaded()) {
+ currentDesignDocument()->loadDocument(currentDesignDocument()->plainTextEdit());
+ } else {
+ currentDesignDocument()->activateCurrentModel();
+ }
+
+ resetModelSelection();
+
- if (m_isActive) {
- m_isActive = false;
- m_mainWidget->showEditor(0);
+ QList<RewriterView::Error> errors = currentDesignDocument()->qmlSyntaxErrors();
+ if (errors.isEmpty()) {
+ viewManager().attachComponentView();
+ viewManager().attachViewsExceptRewriterAndComponetView();
+ selectModelNodeUnderTextCursor();
+ m_mainWidget->enableWidgets();
+ } else {
+ m_mainWidget->disableWidgets();
+ m_mainWidget->showErrorMessage(errors);
}
+
+
+ connect(currentDesignDocument()->rewriterView(),
+ SIGNAL(errorsChanged(QList<RewriterView::Error>)),
+ m_mainWidget,
+ SLOT(updateErrorStatus(QList<RewriterView::Error>)));
}
-void BauhausPlugin::textEditorsClosed(QList<Core::IEditor*> editors)
+void QmlDesignerPlugin::deactivateAutoSynchronization()
{
- m_mainWidget->closeEditors(editors);
+ viewManager().detachViewsExceptRewriterAndComponetView();
+ viewManager().detachComponentView();
+
+ disconnect(currentDesignDocument()->rewriterView(),
+ SIGNAL(errorsChanged(QList<RewriterView::Error>)),
+ m_mainWidget,
+ SLOT(updateErrorStatus(QList<RewriterView::Error>)));
+
}
-// copied from EditorManager::updateActions
-void BauhausPlugin::updateActions(Core::IEditor* editor)
+void QmlDesignerPlugin::resetModelSelection()
{
- Core::IEditor *curEditor = editor;
- int openedCount = m_editorManager->openedEditors().count()
- + m_editorManager->openedEditorsModel()->restoredEditors().count();
-
- QString fName;
- if (curEditor) {
- if (!curEditor->document()->fileName().isEmpty()) {
- QFileInfo fi(curEditor->document()->fileName());
- fName = fi.fileName();
- } else {
- fName = curEditor->displayName();
- }
+ if (currentDesignDocument()->rewriterView() && currentDesignDocument()->currentModel())
+ currentDesignDocument()->rewriterView()->setSelectedModelNodes(QList<ModelNode>());
+}
+
+
+
+void QmlDesignerPlugin::onCurrentEditorChanged(Core::IEditor *editor)
+{
+ if (editor
+ && editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID
+ && isInDesignerMode())
+ {
+ m_shortCutManager.updateActions(editor);
+ changeEditor();
}
+}
+
+static bool isDesignerMode(Core::IMode *mode)
+{
+ return mode == Core::DesignMode::instance();
+}
+
+void QmlDesignerPlugin::onCurrentModeChanged(Core::IMode *newMode, Core::IMode *oldMode)
+{
+ if (!Core::EditorManager::currentEditor())
+ return;
+
+ if (Core::EditorManager::currentEditor()
+ && Core::EditorManager::currentEditor()->id() != QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
+ return;
+
+ if ((currentDesignDocument()
+ && Core::EditorManager::currentEditor() == currentDesignDocument()->editor())
+ && isDesignerMode(newMode))
+ return;
+
+ if (!isDesignerMode(newMode) && isDesignerMode(oldMode))
+ hideDesigner();
+ else if (Core::EditorManager::currentEditor()
+ && isDesignerMode(newMode)
+ && isQmlFile(Core::EditorManager::currentEditor()))
+ showDesigner();
+ else if (currentDesignDocument())
+ hideDesigner();
- m_saveAction->setEnabled(curEditor != 0 && curEditor->document()->isModified());
- m_saveAsAction->setEnabled(curEditor != 0 && curEditor->document()->isSaveAsAllowed());
- m_revertToSavedAction->setEnabled(curEditor != 0
- && !curEditor->document()->fileName().isEmpty()
- && curEditor->document()->isModified());
-
- QString quotedName;
- if (!fName.isEmpty())
- quotedName = '"' + fName + '"';
- m_saveAsAction->setText(tr("Save %1 As...").arg(quotedName));
- m_saveAction->setText(tr("&Save %1").arg(quotedName));
- m_revertToSavedAction->setText(tr("Revert %1 to Saved").arg(quotedName));
-
- m_closeCurrentEditorAction->setEnabled(curEditor != 0);
- m_closeCurrentEditorAction->setText(tr("Close %1").arg(quotedName));
- m_closeAllEditorsAction->setEnabled(openedCount > 0);
- m_closeOtherEditorsAction->setEnabled(openedCount > 1);
- m_closeOtherEditorsAction->setText((openedCount > 1 ? tr("Close All Except %1").arg(quotedName) : tr("Close Others")));
}
-void BauhausPlugin::extensionsInitialized()
+DesignDocument *QmlDesignerPlugin::currentDesignDocument() const
{
- m_designMode = Core::DesignMode::instance();
+ return m_documentManager.currentDesignDocument();
+}
+
+Internal::DesignModeWidget *QmlDesignerPlugin::mainWidget() const
+{
+ return m_mainWidget;
+}
+
+void QmlDesignerPlugin::onTextEditorsClosed(QList<Core::IEditor*> editors)
+{
+ if (m_documentManager.hasCurrentDesignDocument()
+ && editors.contains(m_documentManager.currentDesignDocument()->textEditor()))
+ hideDesigner();
- m_mimeTypes << "application/x-qml";
+ m_documentManager.removeEditors(editors);
+}
+
+void QmlDesignerPlugin::extensionsInitialized()
+{
+ QStringList mimeTypes;
+ mimeTypes.append("application/x-qml");
+
+ Core::DesignMode::instance()->registerDesignWidget(m_mainWidget, mimeTypes, m_context->context());
+ connect(Core::DesignMode::instance(),
+ SIGNAL(actionsUpdated(Core::IEditor*)),
+ &m_shortCutManager,
+ SLOT(updateActions(Core::IEditor*)));
+}
- m_designMode->registerDesignWidget(m_mainWidget, m_mimeTypes, m_context->context());
- connect(m_designMode, SIGNAL(actionsUpdated(Core::IEditor*)), SLOT(updateActions(Core::IEditor*)));
+QmlDesignerPlugin *QmlDesignerPlugin::instance()
+{
+ return m_instance;
}
-BauhausPlugin *BauhausPlugin::pluginInstance()
+DocumentManager &QmlDesignerPlugin::documentManager()
{
- return m_pluginInstance;
+ return m_documentManager;
}
-void BauhausPlugin::switchTextDesign()
+const DocumentManager &QmlDesignerPlugin::documentManager() const
+{
+ return m_documentManager;
+}
+
+ViewManager &QmlDesignerPlugin::viewManager()
+{
+ return m_viewManager;
+}
+
+const ViewManager &QmlDesignerPlugin::viewManager() const
+{
+ return m_viewManager;
+}
+
+void QmlDesignerPlugin::switchTextDesign()
{
if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_EDIT) {
Core::IEditor *editor = Core::EditorManager::currentEditor();
- if (editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID) {
+ if (editor->id() == QmlJSEditor::Constants::C_QMLJSEDITOR_ID)
Core::ModeManager::activateMode(Core::Constants::MODE_DESIGN);
- m_mainWidget->setFocus();
- }
} else if (Core::ModeManager::currentMode()->id() == Core::Constants::MODE_DESIGN) {
Core::ModeManager::activateMode(Core::Constants::MODE_EDIT);
}
}
-DesignerSettings BauhausPlugin::settings() const
+DesignerSettings QmlDesignerPlugin::settings()
{
+ m_settings.fromSettings(Core::ICore::settings());
return m_settings;
}
-void BauhausPlugin::setSettings(const DesignerSettings &s)
+void QmlDesignerPlugin::setSettings(const DesignerSettings &s)
{
if (s != m_settings) {
m_settings = s;
@@ -391,6 +452,5 @@ void BauhausPlugin::setSettings(const DesignerSettings &s)
}
}
-}
-Q_EXPORT_PLUGIN(QmlDesigner::Internal::BauhausPlugin)
+Q_EXPORT_PLUGIN(QmlDesigner::QmlDesignerPlugin)
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.h b/src/plugins/qmldesigner/qmldesignerplugin.h
index 11f6b15e2a..c106c0a393 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.h
+++ b/src/plugins/qmldesigner/qmldesignerplugin.h
@@ -31,9 +31,14 @@
#define QMLDESIGNERPLUGIN_H
#include <qmldesigner/designersettings.h>
+#include <qmldesigner/components/pluginmanager/pluginmanager.h>
#include <extensionsystem/iplugin.h>
+#include "documentmanager.h"
+#include "viewmanager.h"
+#include "shortcutmanager.h"
+
#include <QWeakPointer>
#include <QStringList>
@@ -50,64 +55,70 @@ namespace Core {
}
namespace QmlDesigner {
- class IntegrationCore;
-}
-namespace QmlDesigner {
namespace Internal {
-
class DesignModeWidget;
class DesignModeContext;
+}
-class BauhausPlugin : public ExtensionSystem::IPlugin
+class QmlDesignerPlugin : public ExtensionSystem::IPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QtCreatorPlugin" FILE "QmlDesigner.json")
public:
- BauhausPlugin();
- virtual ~BauhausPlugin();
+ QmlDesignerPlugin();
+ virtual ~QmlDesignerPlugin();
//Plugin
virtual bool initialize(const QStringList &arguments, QString *errorMessage = 0);
virtual void extensionsInitialized();
- static BauhausPlugin *pluginInstance();
+ static QmlDesignerPlugin *instance();
+
+ DocumentManager &documentManager();
+ const DocumentManager &documentManager() const;
- DesignerSettings settings() const;
+ ViewManager &viewManager();
+ const ViewManager &viewManager() const;
+
+ DesignerSettings settings();
void setSettings(const DesignerSettings &s);
-private slots:
+ DesignDocument *currentDesignDocument() const;
+ Internal::DesignModeWidget *mainWidget() const;
+private slots:
void switchTextDesign();
- void textEditorsClosed(QList<Core::IEditor *> editors);
- void updateActions(Core::IEditor* editor);
- void updateEditor(Core::IEditor *editor);
- void contextChanged(Core::IContext *context, const Core::Context &additionalContexts);
+ void onTextEditorsClosed(QList<Core::IEditor *> editors);
+ void onCurrentEditorChanged(Core::IEditor *editor);
+ void onCurrentModeChanged(Core::IMode *mode, Core::IMode *oldMode);
-private:
+private: // functions
void createDesignModeWidget();
-
- QStringList m_mimeTypes;
- DesignModeWidget *m_mainWidget;
-
- QmlDesigner::IntegrationCore *m_designerCore;
- static BauhausPlugin *m_pluginInstance;
+ void showDesigner();
+ void hideDesigner();
+ void changeEditor();
+ void jumpTextCursorToSelectedModelNode();
+ void selectModelNodeUnderTextCursor();
+ void activateAutoSynchronization();
+ void deactivateAutoSynchronization();
+ void resetModelSelection();
+
+private: // variables
+ ViewManager m_viewManager;
+ DocumentManager m_documentManager;
+ ShortCutManager m_shortCutManager;
+
+ Internal::DesignModeWidget *m_mainWidget;
+
+ QmlDesigner::PluginManager m_pluginManager;
+ static QmlDesignerPlugin *m_instance;
DesignerSettings m_settings;
- DesignModeContext *m_context;
- Core::DesignMode *m_designMode;
- Core::EditorManager *m_editorManager;
+ Internal::DesignModeContext *m_context;
bool m_isActive;
-
- QAction *m_revertToSavedAction;
- QAction *m_saveAction;
- QAction *m_saveAsAction;
- QAction *m_closeCurrentEditorAction;
- QAction *m_closeAllEditorsAction;
- QAction *m_closeOtherEditorsAction;
};
-} // namespace Internal
} // namespace QmlDesigner
#endif // QMLDESIGNERPLUGIN_H
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.pri b/src/plugins/qmldesigner/qmldesignerplugin.pri
new file mode 100644
index 0000000000..7c52f0aaf4
--- /dev/null
+++ b/src/plugins/qmldesigner/qmldesignerplugin.pri
@@ -0,0 +1,20 @@
+HEADERS += $$PWD/qmldesignerconstants.h \
+ $$PWD/shortcutmanager.h \
+ $$PWD/qmldesignerplugin.h \
+ $$PWD/designmodewidget.h \
+ $$PWD/designersettings.h \
+ $$PWD/settingspage.h \
+ $$PWD/designmodecontext.h \
+ $$PWD/documentmanager.h \
+ $$PWD/styledoutputpaneplaceholder.h
+
+SOURCES += $$PWD/qmldesignerplugin.cpp \
+ $$PWD/shortcutmanager.cpp \
+ $$PWD/designmodewidget.cpp \
+ $$PWD/designersettings.cpp \
+ $$PWD/settingspage.cpp \
+ $$PWD/designmodecontext.cpp \
+ $$PWD/documentmanager.cpp \
+ $$PWD/styledoutputpaneplaceholder.cpp
+
+FORMS += $$PWD/settingspage.ui
diff --git a/src/plugins/qmldesigner/qmldesignerplugin.pro b/src/plugins/qmldesigner/qmldesignerplugin.pro
index d042701c19..a2066c59b7 100644
--- a/src/plugins/qmldesigner/qmldesignerplugin.pro
+++ b/src/plugins/qmldesigner/qmldesignerplugin.pro
@@ -9,7 +9,8 @@ include(../../qtcreatorplugin.pri)
include(../../private_headers.pri)
include(qmldesigner_dependencies.pri)
-include(designercore/designercore.pri)
+include(designercore/designercore-lib.pri)
+include(components/componentcore/componentcore.pri)
include(components/integration/integration.pri)
include(components/propertyeditor/propertyeditor.pri)
include(components/formeditor/formeditor.pri)
@@ -18,20 +19,6 @@ include(components/navigator/navigator.pri)
include(components/pluginmanager/pluginmanager.pri)
include(components/stateseditor/stateseditor.pri)
include(components/resources/resources.pri)
+include(qmldesignerplugin.pri)
-HEADERS += qmldesignerconstants.h \
- qmldesignerplugin.h \
- designmodewidget.h \
- designersettings.h \
- settingspage.h \
- designmodecontext.h \
- styledoutputpaneplaceholder.h
-
-SOURCES += qmldesignerplugin.cpp \
- designmodewidget.cpp \
- designersettings.cpp \
- settingspage.cpp \
- designmodecontext.cpp \
- styledoutputpaneplaceholder.cpp
-
-FORMS += settingspage.ui
+DEFINES -= QT_NO_CAST_FROM_ASCII
diff --git a/src/plugins/qmldesigner/qtquickplugin/qtquickplugin.qrc b/src/plugins/qmldesigner/qtquickplugin/qtquickplugin.qrc
index 3293af8962..b2dcfce06a 100644
--- a/src/plugins/qmldesigner/qtquickplugin/qtquickplugin.qrc
+++ b/src/plugins/qmldesigner/qtquickplugin/qtquickplugin.qrc
@@ -32,10 +32,16 @@
<file>images/text-input-icon16.png</file>
<file>images/webview-icon16.png</file>
<file>source/listview.qml</file>
+ <file>source/listviewv2.qml</file>
<file>source/gridview.qml</file>
+ <file>source/gridviewv2.qml</file>
<file>source/pathview.qml</file>
+ <file>source/pathviewv2.qml</file>
<file>source/text.qml</file>
+ <file>source/textv2.qml</file>
<file>source/textedit.qml</file>
+ <file>source/texteditv2.qml</file>
<file>source/textinput.qml</file>
+ <file>source/textinputv2.qml</file>
</qresource>
</RCC>
diff --git a/src/plugins/qmldesigner/qtquickplugin/quick.metainfo b/src/plugins/qmldesigner/qtquickplugin/quick.metainfo
index be74404a75..15e87c1299 100644
--- a/src/plugins/qmldesigner/qtquickplugin/quick.metainfo
+++ b/src/plugins/qmldesigner/qtquickplugin/quick.metainfo
@@ -1,117 +1,479 @@
-<metainfo>
- <node name="QtQuick.Item" icon=":/qtquickplugin/images/item-icon16.png">
- <itemlibraryentry name="Item" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/item-icon.png" version="1.0">
- <property name="width" type="int" value="200"/>
- <property name="height" type="int" value="200"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Rectangle" icon=":/qtquickplugin/images/rect-icon16.png">
- <itemlibraryentry name="Rectangle" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/rect-icon.png" version="1.0">
- <property name="color" type="QColor" value="#ffffff"/>
- <property name="width" type="int" value="200"/>
- <property name="height" type="int" value="200"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Text" icon=":/qtquickplugin/images/text-icon16.png">
- <itemlibraryentry name="Text" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/text-icon.png" version="1.0">
- <qml source=":/qtquickplugin/source/text.qml"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.TextEdit" icon=":/qtquickplugin/images/text-edit-icon16.png">
- <itemlibraryentry name="Text Edit" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/text-edit-icon.png" version="1.0">
- <qml source=":/qtquickplugin/source/textedit.qml"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.TextInput" icon=":/qtquickplugin/images/text-input-icon16.png">
- <itemlibraryentry name="Text Input" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/text-input-icon.png" version="1.0">
- <qml source=":/qtquickplugin/source/textinput.qml"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.MouseArea" icon=":/qtquickplugin/images/mouse-area-icon16.png">
- <itemlibraryentry name="Mouse Area" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/mouse-area-icon.png" version="1.0">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Image" icon=":/qtquickplugin/images/image-icon16.png">
- <itemlibraryentry name="Image" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/image-icon.png" version="1.0">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- <property name="source" type="QUrl" value="qrc:/qtquickplugin/images/template_image.png"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.BorderImage" icon=":/qtquickplugin/images/border-image-icon16.png">
- <itemlibraryentry name="Border Image" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/border-image-icon.png" version="1.0">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- <property name="source" type="QUrl" value="qrc:/qtquickplugin/images/template_image.png"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Flickable" icon=":/qtquickplugin/images/flickable-icon16.png">
- <itemlibraryentry name="Flickable" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/flickable-icon.png" version="1.0">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="300"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Flipable" icon=":/qtquickplugin/images/flipable-icon16.png">
- <itemlibraryentry name="Flipable" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/flipable-icon.png" version="1.0">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="300"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.GridView" icon=":/qtquickplugin/images/gridview-icon16.png">
- <itemlibraryentry name="Grid View" category="Qt Quick - Views" libraryIcon=":/qtquickplugin/images/gridview-icon.png" version="1.0">
- <qml source=":/qtquickplugin/source/gridview.qml"/>
- </itemlibraryentry>
- </node>
-
- <node name="QtQuick.ListView" icon=":/qtquickplugin/images/listview-icon16.png">
- <itemlibraryentry name="List View" category="Qt Quick - Views" libraryIcon=":/qtquickplugin/images/listview-icon.png" version="1.0">
- <qml source=":/qtquickplugin/source/listview.qml"/>
- </itemlibraryentry>
- </node>
-
- <node name="QtQuick.PathView" icon=":/qtquickplugin/images/pathview-icon16.png">
- <itemlibraryentry name="Path View" category="Qt Quick - Views" libraryIcon=":/qtquickplugin/images/pathview-icon.png" version="1.0">
- <qml source=":/qtquickplugin/source/pathview.qml"/>
- </itemlibraryentry>
- </node>
-
- <node name="QtQuick.FocusScope" icon=":/qtquickplugin/images/focusscope-icon16.png">
- <itemlibraryentry name="Focus Scope" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/focusscope-icon.png" version="1.0">
- <property name="width" type="int" value="100"/>
- <property name="height" type="int" value="100"/>
- </itemlibraryentry>
- </node>
- <node name="QtWebKit.WebView" icon=":/qtquickplugin/images/webview-icon16.png">
- <itemlibraryentry name="Web View" category="Qt Quick - Basic" libraryIcon=":/qtquickplugin/images/webview-icon.png" version="1.0" requiredImport="QtWebKit" forceImport="true">
- <property name="width" type="int" value="300"/>
- <property name="height" type="int" value="300"/>
- <property name="url" type="QString" value="qrc:/qtquickplugin/html/welcome.html"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Row" icon=":/qtquickplugin/images/item-icon16.png">
- <itemlibraryentry name="Row" category="Qt Quick - Positioner" libraryIcon=":/qtquickplugin/images/item-icon.png" version="1.0">
- <property name="width" type="int" value="400"/>
- <property name="height" type="int" value="200"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Column" icon=":/qtquickplugin/images/item-icon16.png">
- <itemlibraryentry name="Column" category="Qt Quick - Positioner" libraryIcon=":/qtquickplugin/images/item-icon.png" version="1.0">
- <property name="width" type="int" value="200"/>
- <property name="height" type="int" value="400"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Grid" icon=":/qtquickplugin/images/item-icon16.png">
- <itemlibraryentry name="Grid" category="Qt Quick - Positioner" libraryIcon=":/qtquickplugin/images/item-icon.png" version="1.0">
- <property name="width" type="int" value="400"/>
- <property name="height" type="int" value="400"/>
- </itemlibraryentry>
- </node>
- <node name="QtQuick.Flow" icon=":/qtquickplugin/images/item-icon16.png">
- <itemlibraryentry name="Flow" category="Qt Quick - Positioner" libraryIcon=":/qtquickplugin/images/item-icon.png" version="1.0">
- <property name="width" type="int" value="400"/>
- <property name="height" type="int" value="400"/>
- </itemlibraryentry>
- </node>
- </metainfo>
+MetaInfo {
+
+ Type {
+ name: "QtQuick.Item"
+ icon: ":/qtquickplugin/images/item-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Item"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 200; }
+ }
+
+ ItemLibraryEntry {
+ name: "Item"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 200; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Rectangle"
+ icon: ":/qtquickplugin/images/rect-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Rectangle"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/rect-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 200; }
+ Property { name: "color"; type: "QColor"; value: "#ffffff"; }
+
+ }
+
+ ItemLibraryEntry {
+ name: "Rectangle"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/rect-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 200; }
+ Property { name: "color"; type: "QColor"; value: "#ffffff"; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Text"
+ icon: ":/qtquickplugin/images/text-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Text"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/text-icon.png"
+ version: "1.0"
+
+ QmlSource { source: ":/qtquickplugin/source/text.qml" }
+ }
+
+ ItemLibraryEntry {
+ name: "Text"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/text-icon.png"
+ version: "2.0"
+
+ QmlSource { source: ":/qtquickplugin/source/textv2.qml" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.TextEdit"
+ icon: ":/qtquickplugin/images/text-edit-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Text Edit"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/text-edit-icon.png"
+ version: "1.0"
+
+ QmlSource { source: ":/qtquickplugin/source/textedit.qml" }
+ }
+
+ ItemLibraryEntry {
+ name: "Text Edit"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/text-edit-icon.png"
+ version: "2.0"
+
+ QmlSource { source: ":/qtquickplugin/source/texteditv2.qml" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.TextInput"
+ icon: ":/qtquickplugin/images/text-input-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Text Input"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/text-edit-icon.png"
+ version: "1.0"
+
+ QmlSource { source: ":/qtquickplugin/source/textinput.qml" }
+ }
+
+ ItemLibraryEntry {
+ name: "Text Input"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/text-input-icon.png"
+ version: "2.0"
+
+ QmlSource { source: ":/qtquickplugin/source/textinput.qml" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.MouseArea"
+ icon: ":/qtquickplugin/images/mouse-area-icon16.png"
+
+ ItemLibraryEntry {
+ name: "MouseArea"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/mouse-area-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+
+ }
+
+ ItemLibraryEntry {
+ name: "MouseArea"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/mouse-area-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Image"
+ icon: ":/qtquickplugin/images/image-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Image"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/image-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ Property { name: "source"; type: "QUrl"; value:"qrc:/qtquickplugin/images/template_image.png"; }
+ }
+
+ ItemLibraryEntry {
+ name: "Image"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/image-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ Property { name: "source"; type: "QUrl"; value:"qrc:/qtquickplugin/images/template_image.png"; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.BorderImage"
+ icon: ":/qtquickplugin/images/border-image-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Border Image"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/border-image-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ Property { name: "source"; type: "QUrl"; value:"qrc:/qtquickplugin/images/template_image.png"; }
+ }
+
+ ItemLibraryEntry {
+ name: "Border Image"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/border-image-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ Property { name: "source"; type: "QUrl"; value:"qrc:/qtquickplugin/images/template_image.png"; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Flickable"
+ icon: ":/qtquickplugin/images/flickable-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Flickable"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/flickable-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 300; }
+ Property { name: "height"; type: "int"; value: 300; }
+ }
+
+ ItemLibraryEntry {
+ name: "Flickable"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/flickable-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 300; }
+ Property { name: "height"; type: "int"; value: 300; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Flipable"
+ icon: ":/qtquickplugin/images/flipable-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Flipable"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/flipable-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 200; }
+ }
+
+ ItemLibraryEntry {
+ name: "Flipable"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/flipable-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 200; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.GridView"
+ icon: ":/qtquickplugin/images/gridview-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Grid View"
+ category: "Qt Quick - Views"
+ libraryIcon: ":/qtquickplugin/images/gridview-icon.png"
+ version: "1.0"
+
+ QmlSource { source: ":/qtquickplugin/source/gridview.qml" }
+ }
+
+ ItemLibraryEntry {
+ name: "Grid View"
+ category: "Qt Quick - Views"
+ libraryIcon: ":/qtquickplugin/images/gridview-icon.png"
+ version: "2.0"
+
+ QmlSource { source: ":/qtquickplugin/source/gridviewv2.qml" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.ListView"
+ icon: ":/qtquickplugin/images/listview-icon16.png"
+
+ ItemLibraryEntry {
+ name: "List View"
+ category: "Qt Quick - Views"
+ libraryIcon: ":/qtquickplugin/images/pathview-icon.png"
+ version: "1.1"
+
+ QmlSource { source: ":/qtquickplugin/source/listview.qml" }
+ }
+
+ ItemLibraryEntry {
+ name: "List View"
+ category: "Qt Quick - Views"
+ libraryIcon: ":/qtquickplugin/images/pathview-icon.png"
+ version: "2.0"
+
+ QmlSource { source: ":/qtquickplugin/source/listviewv2.qml" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.PathView"
+ icon: ":/qtquickplugin/images/pathview-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Path View"
+ category: "Qt Quick - Views"
+ libraryIcon: ":/qtquickplugin/images/pathview-icon.png"
+ version: "1.0"
+
+ QmlSource { source: ":/qtquickplugin/source/pathview.qml" }
+ }
+
+ ItemLibraryEntry {
+ name: "Path View"
+ category: "Qt Quick - Views"
+ libraryIcon: ":/qtquickplugin/images/pathview-icon.png"
+ version: "2.0"
+
+ QmlSource { source: ":/qtquickplugin/source/pathviewv2.qml" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.FocusScope"
+ icon: ":/qtquickplugin/images/focusscope-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Focus Scope"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/focusscope-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ }
+
+ ItemLibraryEntry {
+ name: "Focus Scope"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/focusscope-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 100; }
+ Property { name: "height"; type: "int"; value: 100; }
+ }
+ }
+
+ Type {
+ name: "QtWebKit.WebView"
+ icon: ":/qtquickplugin/images/webview-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Web View"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/webview-icon.png"
+ version: "1.0"
+ requiredImport: "QtWebKit"
+ forceImport: "true"
+
+ Property { name: "width"; type: "int"; value: 300; }
+ Property { name: "height"; type: "int"; value: 300; }
+ Property { name: "url"; type: "QString"; value: "qrc:/qtquickplugin/html/welcome.html" }
+ }
+
+ ItemLibraryEntry {
+ name: "Web View"
+ category: "Qt Quick - Basic"
+ libraryIcon: ":/qtquickplugin/images/webview-icon.png"
+ version: "2.0"
+ requiredImport: "QtWebKit"
+ forceImport: "true"
+
+ Property { name: "width"; type: "int"; value: 300; }
+ Property { name: "height"; type: "int"; value: 300; }
+ Property { name: "url"; type: "QString"; value: "qrc:/qtquickplugin/html/welcome.html" }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Column"
+ icon: ":/qtquickplugin/images/item-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Column"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+
+ ItemLibraryEntry {
+ name: "Column"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Column"
+ icon: ":/qtquickplugin/images/item-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Row"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+
+ ItemLibraryEntry {
+ name: "Row"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 200; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Grid"
+ icon: ":/qtquickplugin/images/item-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Grid"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 400; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+
+ ItemLibraryEntry {
+ name: "Grid"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 400; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+ }
+
+ Type {
+ name: "QtQuick.Flow"
+ icon: ":/qtquickplugin/images/item-icon16.png"
+
+ ItemLibraryEntry {
+ name: "Flow"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "1.0"
+
+ Property { name: "width"; type: "int"; value: 400; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+
+ ItemLibraryEntry {
+ name: "Flow"
+ category: "Qt Quick - Positioner"
+ libraryIcon: ":/qtquickplugin/images/item-icon.png"
+ version: "2.0"
+
+ Property { name: "width"; type: "int"; value: 400; }
+ Property { name: "height"; type: "int"; value: 400; }
+ }
+ }
+}
diff --git a/src/plugins/qmldesigner/qtquickplugin/source/gridviewv2.qml b/src/plugins/qmldesigner/qtquickplugin/source/gridviewv2.qml
new file mode 100644
index 0000000000..9532a65daf
--- /dev/null
+++ b/src/plugins/qmldesigner/qtquickplugin/source/gridviewv2.qml
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+GridView {
+ width: 140
+ height: 140
+ cellWidth: 70
+ cellHeight: 70
+
+ model: ListModel {
+
+ ListElement {
+ name: "Grey"
+ colorCode: "grey"
+
+ }
+
+ ListElement {
+ name: "Red"
+ colorCode: "red"
+
+ }
+
+ ListElement {
+ name: "Blue"
+ colorCode: "blue"
+
+ }
+
+ ListElement {
+ name: "Green"
+ colorCode: "green"
+
+ }
+ }
+
+ delegate: Item {
+ height: 50
+ x: 5
+
+ Column {
+ spacing: 5
+ Rectangle {
+ width: 40
+ height: 40
+ color: colorCode
+ anchors.horizontalCenter: parent.horizontalCenter
+ }
+
+ Text {
+ x: 5
+ text: name
+ anchors.horizontalCenter: parent.horizontalCenter
+ font.bold: true
+ }
+
+ }
+ }
+}
diff --git a/src/plugins/qmldesigner/qtquickplugin/source/listviewv2.qml b/src/plugins/qmldesigner/qtquickplugin/source/listviewv2.qml
new file mode 100644
index 0000000000..70338dfde1
--- /dev/null
+++ b/src/plugins/qmldesigner/qtquickplugin/source/listviewv2.qml
@@ -0,0 +1,68 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+ListView {
+ width: 110
+ height: 160
+ model: ListModel {
+ ListElement {
+ name: "Grey"
+ colorCode: "grey"
+ }
+ ListElement {
+ name: "Red"
+ colorCode: "red"
+ }
+ ListElement {
+ name: "Blue"
+ colorCode: "blue"
+ }
+ ListElement {
+ name: "Green"
+ colorCode: "green"
+ }
+ }
+
+ delegate: Item {
+ height: 40
+ x: 5
+ Row {
+ id: row1
+ spacing: 10
+ Rectangle { width: 40; height: 40; color: colorCode; }
+ Text {
+ text: name
+ anchors.verticalCenter: parent.verticalCenter
+ font.bold: true
+ }
+ }
+ }
+}
diff --git a/src/plugins/qmldesigner/qtquickplugin/source/pathviewv2.qml b/src/plugins/qmldesigner/qtquickplugin/source/pathviewv2.qml
new file mode 100644
index 0000000000..97fbf887a5
--- /dev/null
+++ b/src/plugins/qmldesigner/qtquickplugin/source/pathviewv2.qml
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+PathView {
+ width: 250
+ height: 130
+
+ path: Path {
+ startX: 120
+ startY: 100
+ PathQuad { x: 120; y: 25; controlX: 260; controlY: 75 }
+ PathQuad { x: 120; y: 100; controlX: -20; controlY: 75 }
+ }
+ model: ListModel {
+ ListElement {
+ name: "Grey"
+ colorCode: "grey"
+ }
+ ListElement {
+ name: "Red"
+ colorCode: "red"
+ }
+ ListElement {
+ name: "Blue"
+ colorCode: "blue"
+ }
+ ListElement {
+ name: "Green"
+ colorCode: "green"
+ }
+ }
+ delegate: Component {
+ Column {
+ spacing: 5
+ Rectangle {
+ width: 40
+ height: 40
+ color: colorCode
+ anchors.horizontalCenter: parent.horizontalCenter
+ }
+ Text {
+ x: 5
+ text: name
+ anchors.horizontalCenter: parent.horizontalCenter
+ font.bold: true
+ }
+ }
+ }
+}
+
diff --git a/src/plugins/qmldesigner/qtquickplugin/source/texteditv2.qml b/src/plugins/qmldesigner/qtquickplugin/source/texteditv2.qml
new file mode 100644
index 0000000000..6c72cb2e7b
--- /dev/null
+++ b/src/plugins/qmldesigner/qtquickplugin/source/texteditv2.qml
@@ -0,0 +1,37 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+TextEdit {
+ width: 80
+ height: 20
+ text: qsTr("text edit")
+ font.pixelSize: 12
+}
diff --git a/src/plugins/qmldesigner/qtquickplugin/source/textinputv2.qml b/src/plugins/qmldesigner/qtquickplugin/source/textinputv2.qml
new file mode 100644
index 0000000000..0a4772bc88
--- /dev/null
+++ b/src/plugins/qmldesigner/qtquickplugin/source/textinputv2.qml
@@ -0,0 +1,37 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+TextInput {
+ width: 80
+ height: 20
+ text: qsTr("text")
+ font.pixelSize: 12
+}
diff --git a/src/plugins/qmldesigner/qtquickplugin/source/textv2.qml b/src/plugins/qmldesigner/qtquickplugin/source/textv2.qml
new file mode 100644
index 0000000000..40d59d7145
--- /dev/null
+++ b/src/plugins/qmldesigner/qtquickplugin/source/textv2.qml
@@ -0,0 +1,35 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Text {
+ text: qsTr("text")
+ font.pixelSize: 12
+}
diff --git a/src/plugins/qmldesigner/settingspage.cpp b/src/plugins/qmldesigner/settingspage.cpp
index f04f036cef..5158a8a96a 100644
--- a/src/plugins/qmldesigner/settingspage.cpp
+++ b/src/plugins/qmldesigner/settingspage.cpp
@@ -53,6 +53,9 @@ DesignerSettings SettingsPageWidget::settings() const
ds.snapMargin = m_ui.spinSnapMargin->value();
ds.canvasWidth = m_ui.spinCanvasWidth->value();
ds.canvasHeight = m_ui.spinCanvasHeight->value();
+ ds.warningsInDesigner = m_ui.designerWarningsCheckBox->isChecked();
+ ds.designerWarningsInEditor = m_ui.designerWarningsInEditorCheckBox->isChecked();
+
return ds;
}
@@ -62,6 +65,8 @@ void SettingsPageWidget::setSettings(const DesignerSettings &s)
m_ui.spinSnapMargin->setValue(s.snapMargin);
m_ui.spinCanvasWidth->setValue(s.canvasWidth);
m_ui.spinCanvasHeight->setValue(s.canvasHeight);
+ m_ui.designerWarningsCheckBox->setChecked(s.warningsInDesigner);
+ m_ui.designerWarningsInEditorCheckBox->setChecked(s.designerWarningsInEditor);
}
QString SettingsPageWidget::searchKeywords() const
@@ -79,9 +84,9 @@ QString SettingsPageWidget::searchKeywords() const
SettingsPage::SettingsPage() :
m_widget(0)
{
- setId(QLatin1String("B.QmlDesigner"));
+ setId("B.QmlDesigner");
setDisplayName(tr("Qt Quick Designer"));
- setCategory(QLatin1String(QmlJSEditor::Constants::SETTINGS_CATEGORY_QML));
+ setCategory(QmlJSEditor::Constants::SETTINGS_CATEGORY_QML);
setDisplayCategory(QCoreApplication::translate("QmlJSEditor",
QmlJSEditor::Constants::SETTINGS_TR_CATEGORY_QML));
setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_QML_ICON));
@@ -90,7 +95,7 @@ SettingsPage::SettingsPage() :
QWidget *SettingsPage::createPage(QWidget *parent)
{
m_widget = new SettingsPageWidget(parent);
- m_widget->setSettings(BauhausPlugin::pluginInstance()->settings());
+ m_widget->setSettings(QmlDesignerPlugin::instance()->settings());
if (m_searchKeywords.isEmpty())
m_searchKeywords = m_widget->searchKeywords();
return m_widget;
@@ -100,7 +105,7 @@ void SettingsPage::apply()
{
if (!m_widget) // page was never shown
return;
- BauhausPlugin::pluginInstance()->setSettings(m_widget->settings());
+ QmlDesignerPlugin::instance()->setSettings(m_widget->settings());
}
bool SettingsPage::matches(const QString &s) const
diff --git a/src/plugins/qmldesigner/settingspage.ui b/src/plugins/qmldesigner/settingspage.ui
index a98006ba46..3bbf633e01 100644
--- a/src/plugins/qmldesigner/settingspage.ui
+++ b/src/plugins/qmldesigner/settingspage.ui
@@ -6,15 +6,15 @@
<rect>
<x>0</x>
<y>0</y>
- <width>275</width>
- <height>275</height>
+ <width>574</width>
+ <height>472</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
<widget class="QGroupBox" name="groupBox_3">
<property name="title">
<string>Snapping</string>
@@ -67,7 +67,7 @@
</layout>
</widget>
</item>
- <item>
+ <item row="1" column="0">
<widget class="QGroupBox" name="groupBox">
<property name="title">
<string>Canvas</string>
@@ -132,7 +132,40 @@
</layout>
</widget>
</item>
- <item>
+ <item row="2" column="0">
+ <widget class="QGroupBox" name="groupBox_2">
+ <property name="title">
+ <string>Warnings</string>
+ </property>
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <layout class="QFormLayout" name="formLayout_3">
+ <item row="0" column="1">
+ <widget class="QCheckBox" name="designerWarningsCheckBox">
+ <property name="toolTip">
+ <string>Warn about QML features which are not properly supported by the Qt Quick Designer</string>
+ </property>
+ <property name="text">
+ <string>Warn about unsupported features in the Qt Quick Designer</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QCheckBox" name="designerWarningsInEditorCheckBox">
+ <property name="toolTip">
+ <string>Also warn in the code editor about QML features which are not properly supported by the Qt Quick Designer</string>
+ </property>
+ <property name="text">
+ <string>Warn about unsupported features of Qt Quick Designer in the code editor</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item row="3" column="1">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
diff --git a/src/plugins/qmldesigner/shortcutmanager.cpp b/src/plugins/qmldesigner/shortcutmanager.cpp
new file mode 100644
index 0000000000..3852f4958c
--- /dev/null
+++ b/src/plugins/qmldesigner/shortcutmanager.cpp
@@ -0,0 +1,326 @@
+#include "shortcutmanager.h"
+
+#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/actionmanager/actioncontainer.h>
+#include <coreplugin/icore.h>
+#include <coreplugin/editormanager/openeditorsmodel.h>
+#include <coreplugin/coreconstants.h>
+#include <utils/hostosinfo.h>
+
+#include "qmldesignerconstants.h"
+#include "designdocument.h"
+#include "qmldesignerplugin.h"
+#include "designmodewidget.h"
+
+
+namespace QmlDesigner {
+
+ShortCutManager::ShortCutManager()
+ : QObject(),
+ m_revertToSavedAction(0),
+ m_saveAction(0),
+ m_saveAsAction(0),
+ m_closeCurrentEditorAction(0),
+ m_closeAllEditorsAction(0),
+ m_closeOtherEditorsAction(0),
+ m_undoAction(tr("&Undo"), 0),
+ m_redoAction(tr("&Redo"), 0),
+ m_deleteAction(tr("Delete"), tr("Delete \"%1\""), Utils::ParameterAction::EnabledWithParameter),
+ m_cutAction(tr("Cu&t"), tr("Cut \"%1\""), Utils::ParameterAction::EnabledWithParameter),
+ m_copyAction(tr("&Copy"), tr("Copy \"%1\""), Utils::ParameterAction::EnabledWithParameter),
+ m_pasteAction(tr("&Paste"), tr("Paste \"%1\""), Utils::ParameterAction::EnabledWithParameter),
+ m_selectAllAction(tr("Select &All"), tr("Select All \"%1\""), Utils::ParameterAction::EnabledWithParameter),
+ m_hideSidebarsAction(tr("Toggle Full Screen"), 0),
+ m_restoreDefaultViewAction(tr("&Restore Default View"), 0),
+ m_toggleLeftSidebarAction(tr("Toggle &Left Sidebar"), 0),
+ m_toggleRightSidebarAction(tr("Toggle &Right Sidebar"), 0),
+ m_goIntoComponentAction (tr("&Go into Component"), 0)
+{
+
+}
+
+void ShortCutManager::registerActions()
+{
+ Core::ActionContainer *editMenu = Core::ActionManager::actionContainer(Core::Constants::M_EDIT);
+
+ Core::Context qmlDesignerMainContext(Constants::C_QMLDESIGNER);
+ Core::Context qmlDesignerFormEditorContext(Constants::C_QMLFORMEDITOR);
+ Core::Context qmlDesignerNavigatorContext(Constants::C_QMLNAVIGATOR);
+
+ connect(&m_undoAction, SIGNAL(triggered()), this, SLOT(undo()));
+
+ connect(&m_redoAction, SIGNAL(triggered()), this, SLOT(redo()));
+
+ connect(&m_deleteAction, SIGNAL(triggered()), this, SLOT(deleteSelected()));
+
+ connect(&m_cutAction, SIGNAL(triggered()), this, SLOT(cutSelected()));
+
+ connect(&m_copyAction, SIGNAL(triggered()), this, SLOT(copySelected()));
+
+ connect(&m_pasteAction, SIGNAL(triggered()), this, SLOT(paste()));
+
+ connect(&m_selectAllAction, SIGNAL(triggered()), this, SLOT(selectAll()));
+
+ connect(&m_hideSidebarsAction, SIGNAL(triggered()), this, SLOT(toggleSidebars()));
+
+ connect(&m_restoreDefaultViewAction,
+ SIGNAL(triggered()),
+ QmlDesignerPlugin::instance()->mainWidget(),
+ SLOT(restoreDefaultView()));
+
+ connect(&m_goIntoComponentAction, SIGNAL(triggered()), SLOT(goIntoComponent()));
+
+ connect(&m_toggleLeftSidebarAction,
+ SIGNAL(triggered()),
+ QmlDesignerPlugin::instance()->mainWidget(),
+ SLOT(toggleLeftSidebar()));
+
+ connect(&m_toggleRightSidebarAction,
+ SIGNAL(triggered()),
+ QmlDesignerPlugin::instance()->mainWidget(),
+ SLOT(toggleRightSidebar()));
+
+ // Revert to saved
+ Core::ActionManager::registerAction(&m_revertToSavedAction,Core::Constants::REVERTTOSAVED, qmlDesignerMainContext);
+ connect(&m_revertToSavedAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(revertToSaved()));
+
+ //Save
+ Core::ActionManager::registerAction(&m_saveAction, Core::Constants::SAVE, qmlDesignerMainContext);
+ connect(&m_saveAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(saveDocument()));
+
+ //Save As
+ Core::ActionManager::registerAction(&m_saveAsAction, Core::Constants::SAVEAS, qmlDesignerMainContext);
+ connect(&m_saveAsAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(saveDocumentAs()));
+
+ //Close Editor
+ Core::ActionManager::registerAction(&m_closeCurrentEditorAction, Core::Constants::CLOSE, qmlDesignerMainContext);
+ connect(&m_closeCurrentEditorAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(closeEditor()));
+
+ //Close All
+ Core::ActionManager::registerAction(&m_closeAllEditorsAction, Core::Constants::CLOSEALL, qmlDesignerMainContext);
+ connect(&m_closeAllEditorsAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(closeAllEditors()));
+
+ //Close All Others Action
+ Core::ActionManager::registerAction(&m_closeOtherEditorsAction, Core::Constants::CLOSEOTHERS, qmlDesignerMainContext);
+ connect(&m_closeOtherEditorsAction, SIGNAL(triggered()), Core::ICore::editorManager(), SLOT(closeOtherEditors()));
+
+ // Undo / Redo
+ Core::ActionManager::registerAction(&m_undoAction, Core::Constants::UNDO, qmlDesignerMainContext);
+ Core::ActionManager::registerAction(&m_redoAction, Core::Constants::REDO, qmlDesignerMainContext);
+
+ Core::Command *command;
+
+ //GoIntoComponent
+ command = Core::ActionManager::registerAction(&m_goIntoComponentAction,
+ Constants::GO_INTO_COMPONENT, qmlDesignerMainContext);
+ command->setDefaultKeySequence(QKeySequence(Qt::Key_F2));
+
+ //Edit Menu
+
+ command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::DELETE, qmlDesignerFormEditorContext);
+ command = Core::ActionManager::registerAction(&m_deleteAction, QmlDesigner::Constants::DELETE, qmlDesignerNavigatorContext);
+ command->setDefaultKeySequence(QKeySequence::Delete);
+ command->setAttribute(Core::Command::CA_Hide); // don't show delete in other modes
+ editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
+
+ command = Core::ActionManager::registerAction(&m_cutAction, Core::Constants::CUT, qmlDesignerFormEditorContext);
+ command = Core::ActionManager::registerAction(&m_cutAction, Core::Constants::CUT, qmlDesignerNavigatorContext);
+ command->setDefaultKeySequence(QKeySequence::Cut);
+ editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
+
+ command = Core::ActionManager::registerAction(&m_copyAction, Core::Constants::COPY, qmlDesignerFormEditorContext);
+ command = Core::ActionManager::registerAction(&m_copyAction, Core::Constants::COPY, qmlDesignerNavigatorContext);
+ command->setDefaultKeySequence(QKeySequence::Copy);
+ editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
+
+ command = Core::ActionManager::registerAction(&m_pasteAction, Core::Constants::PASTE, qmlDesignerFormEditorContext);
+ command = Core::ActionManager::registerAction(&m_pasteAction, Core::Constants::PASTE, qmlDesignerNavigatorContext);
+ command->setDefaultKeySequence(QKeySequence::Paste);
+ editMenu->addAction(command, Core::Constants::G_EDIT_COPYPASTE);
+
+ command = Core::ActionManager::registerAction(&m_selectAllAction, Core::Constants::SELECTALL, qmlDesignerFormEditorContext);
+ command = Core::ActionManager::registerAction(&m_selectAllAction, Core::Constants::SELECTALL, qmlDesignerNavigatorContext);
+
+ command->setDefaultKeySequence(QKeySequence::SelectAll);
+ editMenu->addAction(command, Core::Constants::G_EDIT_SELECTALL);
+
+ Core::ActionContainer *viewsMenu = Core::ActionManager::actionContainer(Core::Constants::M_WINDOW_VIEWS);
+
+ command = Core::ActionManager::registerAction(&m_toggleLeftSidebarAction, Constants::TOGGLE_LEFT_SIDEBAR, qmlDesignerMainContext);
+ command->setAttribute(Core::Command::CA_Hide);
+ command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+0"));
+ viewsMenu->addAction(command);
+
+ command = Core::ActionManager::registerAction(&m_toggleRightSidebarAction, Constants::TOGGLE_RIGHT_SIDEBAR, qmlDesignerMainContext);
+ command->setAttribute(Core::Command::CA_Hide);
+ command->setDefaultKeySequence(QKeySequence("Ctrl+Alt+Shift+0"));
+ viewsMenu->addAction(command);
+
+ command = Core::ActionManager::registerAction(&m_restoreDefaultViewAction, Constants::RESTORE_DEFAULT_VIEW, qmlDesignerMainContext);
+ command->setAttribute(Core::Command::CA_Hide);
+ viewsMenu->addAction(command);
+
+ command = Core::ActionManager::registerAction(&m_hideSidebarsAction, Core::Constants::TOGGLE_SIDEBAR, qmlDesignerMainContext);
+
+ if (Utils::HostOsInfo::isMacHost()) {
+ // add second shortcut to trigger delete
+ QAction *deleteAction = new QAction(this);
+ deleteAction->setShortcut(QKeySequence(QLatin1String("Backspace")));
+ connect(deleteAction,
+ SIGNAL(triggered()),
+ &m_deleteAction,
+ SIGNAL(triggered()));
+ }
+}
+
+void ShortCutManager::updateActions(Core::IEditor* editor)
+{
+ Core::IEditor *currentEditor = editor;
+ int openedCount = Core::ICore::editorManager()->openedEditors().count()
+ + Core::ICore::editorManager()->openedEditorsModel()->restoredEditors().count();
+
+ QString fileName;
+ if (currentEditor) {
+ if (!currentEditor->document()->fileName().isEmpty()) {
+ QFileInfo fileInfo(currentEditor->document()->fileName());
+ fileName = fileInfo.fileName();
+ } else {
+ fileName = currentEditor->displayName();
+ }
+ }
+
+ m_saveAction.setEnabled(currentEditor != 0 && currentEditor->document()->isModified());
+ m_saveAsAction.setEnabled(currentEditor != 0 && currentEditor->document()->isSaveAsAllowed());
+ m_revertToSavedAction.setEnabled(currentEditor != 0
+ && !currentEditor->document()->fileName().isEmpty()
+ && currentEditor->document()->isModified());
+
+ QString quotedName;
+ if (!fileName.isEmpty())
+ quotedName = '"' + fileName + '"';
+
+ m_saveAsAction.setText(tr("Save %1 As...").arg(quotedName));
+ m_saveAction.setText(tr("&Save %1").arg(quotedName));
+ m_revertToSavedAction.setText(tr("Revert %1 to Saved").arg(quotedName));
+
+ m_closeCurrentEditorAction.setEnabled(currentEditor != 0);
+ m_closeCurrentEditorAction.setText(tr("Close %1").arg(quotedName));
+ m_closeAllEditorsAction.setEnabled(openedCount > 0);
+ m_closeOtherEditorsAction.setEnabled(openedCount > 1);
+ m_closeOtherEditorsAction.setText((openedCount > 1 ? tr("Close All Except %1").arg(quotedName) : tr("Close Others")));
+}
+
+void ShortCutManager::undo()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->undo();
+}
+
+void ShortCutManager::redo()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->redo();
+}
+
+void ShortCutManager::deleteSelected()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->deleteSelected();
+}
+
+void ShortCutManager::cutSelected()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->cutSelected();
+}
+
+void ShortCutManager::copySelected()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->copySelected();
+}
+
+void ShortCutManager::paste()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->paste();
+}
+
+void ShortCutManager::selectAll()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->selectAll();
+}
+
+void ShortCutManager::toggleSidebars()
+{
+ QmlDesignerPlugin::instance()->mainWidget()->toggleSidebars();
+}
+
+void ShortCutManager::toggleLeftSidebar()
+{
+ QmlDesignerPlugin::instance()->mainWidget()->toggleLeftSidebar();
+}
+
+void ShortCutManager::toggleRightSidebar()
+{
+ QmlDesignerPlugin::instance()->mainWidget()->toggleRightSidebar();
+}
+
+void ShortCutManager::connectUndoActions(DesignDocument *designDocument)
+{
+ if (designDocument) {
+ connect(designDocument, SIGNAL(undoAvailable(bool)), this, SLOT(undoAvailable(bool)));
+ connect(designDocument, SIGNAL(redoAvailable(bool)), this, SLOT(redoAvailable(bool)));
+ }
+}
+
+void ShortCutManager::disconnectUndoActions(DesignDocument *designDocument)
+{
+ if (currentDesignDocument()) {
+ disconnect(designDocument, SIGNAL(undoAvailable(bool)), this, SLOT(undoAvailable(bool)));
+ disconnect(designDocument, SIGNAL(redoAvailable(bool)), this, SLOT(redoAvailable(bool)));
+ }
+}
+
+void ShortCutManager::updateUndoActions(DesignDocument *designDocument)
+{
+ if (designDocument) {
+ m_undoAction.setEnabled(designDocument->isUndoAvailable());
+ m_redoAction.setEnabled(designDocument->isRedoAvailable());
+ } else {
+ m_undoAction.setEnabled(false);
+ m_redoAction.setEnabled(false);
+ }
+}
+
+DesignDocument *ShortCutManager::currentDesignDocument() const
+{
+ return QmlDesignerPlugin::instance()->currentDesignDocument();
+}
+
+void ShortCutManager::undoAvailable(bool isAvailable)
+{
+ DesignDocument *documentController = qobject_cast<DesignDocument*>(sender());
+ if (currentDesignDocument() &&
+ currentDesignDocument() == documentController) {
+ m_undoAction.setEnabled(isAvailable);
+ }
+}
+
+void ShortCutManager::redoAvailable(bool isAvailable)
+{
+ DesignDocument *documentController = qobject_cast<DesignDocument*>(sender());
+ if (currentDesignDocument() &&
+ currentDesignDocument() == documentController) {
+ m_redoAction.setEnabled(isAvailable);
+ }
+}
+
+void ShortCutManager::goIntoComponent()
+{
+ if (currentDesignDocument())
+ currentDesignDocument()->goIntoComponent();
+}
+
+} // namespace QmlDesigner
diff --git a/src/plugins/qmldesigner/shortcutmanager.h b/src/plugins/qmldesigner/shortcutmanager.h
new file mode 100644
index 0000000000..03a5450eb6
--- /dev/null
+++ b/src/plugins/qmldesigner/shortcutmanager.h
@@ -0,0 +1,72 @@
+#ifndef QMLDESIGNER_SHORTCUTMANAGER_H
+#define QMLDESIGNER_SHORTCUTMANAGER_H
+
+#include <QObject>
+#include <QAction>
+#include <utils/parameteraction.h>
+
+
+namespace Core {
+ class IEditor;
+}
+
+namespace QmlDesigner {
+
+class DesignDocument;
+
+class ShortCutManager : public QObject
+{
+ Q_OBJECT
+
+public:
+ ShortCutManager();
+
+ void registerActions();
+
+ void connectUndoActions(DesignDocument *designDocument);
+ void disconnectUndoActions(DesignDocument *designDocument);
+ void updateUndoActions(DesignDocument *designDocument);
+ DesignDocument *currentDesignDocument() const;
+
+public slots:
+ void updateActions(Core::IEditor* editor);
+
+private slots:
+ void undo();
+ void redo();
+ void deleteSelected();
+ void cutSelected();
+ void copySelected();
+ void paste();
+ void selectAll();
+ void toggleSidebars();
+ void toggleLeftSidebar();
+ void toggleRightSidebar();
+ void undoAvailable(bool isAvailable);
+ void redoAvailable(bool isAvailable);
+ void goIntoComponent();
+
+private:
+ QAction m_revertToSavedAction;
+ QAction m_saveAction;
+ QAction m_saveAsAction;
+ QAction m_closeCurrentEditorAction;
+ QAction m_closeAllEditorsAction;
+ QAction m_closeOtherEditorsAction;
+ QAction m_undoAction;
+ QAction m_redoAction;
+ Utils::ParameterAction m_deleteAction;
+ Utils::ParameterAction m_cutAction;
+ Utils::ParameterAction m_copyAction;
+ Utils::ParameterAction m_pasteAction;
+ Utils::ParameterAction m_selectAllAction;
+ QAction m_hideSidebarsAction;
+ QAction m_restoreDefaultViewAction;
+ QAction m_toggleLeftSidebarAction;
+ QAction m_toggleRightSidebarAction;
+ QAction m_goIntoComponentAction;
+};
+
+} // namespace QmlDesigner
+
+#endif // QMLDESIGNER_SHORTCUTMANAGER_H
diff --git a/src/plugins/qmljseditor/QmlJSEditor.mimetypes.xml b/src/plugins/qmljseditor/QmlJSEditor.mimetypes.xml
index 6c17c14689..a1bdef531e 100644
--- a/src/plugins/qmljseditor/QmlJSEditor.mimetypes.xml
+++ b/src/plugins/qmljseditor/QmlJSEditor.mimetypes.xml
@@ -5,10 +5,24 @@
<sub-class-of type="text/plain"/>
<comment>QML file</comment>
<glob pattern="*.qml"/>
+ </mime-type>
+ <mime-type type="application/x-qt.qbs+qml">
+ <alias type="text/x-qt.qbs+qml"/>
+ <sub-class-of type="application/x-qml"/>
+ <comment>Qt Build Suite file</comment>
+ <glob pattern="*.qbs"/>
+ </mime-type>
+ <mime-type type="application/x-qmlproject">
+ <alias type="text/x-qmlproject"/>
+ <sub-class-of type="application/x-qml"/>
+ <comment>Qt Creator Qt UI project file</comment>
<glob pattern="*.qmlproject"/>
+ </mime-type>
+ <mime-type type="application/x-qt.meta-info+qml">
+ <alias type="text/x-qt.meta-info+qml"/>
+ <sub-class-of type="application/x-qml"/>
+ <comment>QML file</comment>
<glob pattern="*.qmltypes"/>
- <glob pattern="*.qbs"/>
- <glob pattern="*.qbp"/>
</mime-type>
<mime-type type="application/javascript">
<alias type="application/x-javascript"/>
diff --git a/src/plugins/qmljseditor/jsfilewizard.cpp b/src/plugins/qmljseditor/jsfilewizard.cpp
index 0a724ad525..8a4427dc0a 100644
--- a/src/plugins/qmljseditor/jsfilewizard.cpp
+++ b/src/plugins/qmljseditor/jsfilewizard.cpp
@@ -121,9 +121,8 @@ QString JsFileWizard::fileContents(const QString &, bool statelessLibrary) const
QString contents;
QTextStream str(&contents);
- if (statelessLibrary) {
+ if (statelessLibrary)
str << QLatin1String(".pragma library\n\n");
- }
str << QLatin1String("function func() {\n")
<< QLatin1String("\n")
<< QLatin1String("}\n");
diff --git a/src/plugins/qmljseditor/qmljscompletionassist.cpp b/src/plugins/qmljseditor/qmljscompletionassist.cpp
index cf5adf6ef4..9f5819480e 100644
--- a/src/plugins/qmljseditor/qmljscompletionassist.cpp
+++ b/src/plugins/qmljseditor/qmljscompletionassist.cpp
@@ -138,9 +138,8 @@ public:
if (const FunctionValue *func = value->asFunctionValue()) {
// constructors usually also have other interesting members,
// don't consider them pure functions and complete the '()'
- if (!func->lookupMember("prototype", 0, 0, false)) {
+ if (!func->lookupMember(QLatin1String("prototype"), 0, 0, false))
data = QVariant::fromValue(CompleteFunctionCall(func->namedArgumentCount() || func->isVariadic()));
- }
}
addCompletion(completions, name, icon, order, data);
}
@@ -498,7 +497,7 @@ IAssistProcessor *QmlJSCompletionAssistProvider::createProcessor() const
// ------------------------------
QmlJSCompletionAssistProcessor::QmlJSCompletionAssistProcessor()
: m_startPosition(0)
- , m_snippetCollector(Constants::QML_SNIPPETS_GROUP_ID, iconForColor(Qt::red), SnippetOrder)
+ , m_snippetCollector(QLatin1String(Constants::QML_SNIPPETS_GROUP_ID), iconForColor(Qt::red), SnippetOrder)
{}
QmlJSCompletionAssistProcessor::~QmlJSCompletionAssistProcessor()
@@ -753,9 +752,9 @@ IAssistProposal *QmlJSCompletionAssistProcessor::perform(const IAssistInterface
foreach (const QString &key, enumValue->keys()) {
QString completion;
if (name.isEmpty())
- completion = QString("\"%1\"").arg(key);
+ completion = QString::fromLatin1("\"%1\"").arg(key);
else
- completion = QString("%1.%2").arg(name, key);
+ completion = QString::fromLatin1("%1.%2").arg(name, key);
addCompletion(&m_completions, key, m_interface->symbolIcon(),
EnumValueOrder, completion);
}
diff --git a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
index 99e62e876d..4997652888 100644
--- a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
+++ b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.cpp
@@ -122,8 +122,7 @@ public:
}
QString replacement = componentName + QLatin1String(" {\n");
if (!m_idName.isEmpty())
- replacement += QLatin1String("id: ") + m_idName
- + QLatin1Char('\n');
+ replacement += QLatin1String("id: ") + m_idName + QLatin1Char('\n');
Utils::ChangeSet changes;
changes.replace(start, end, replacement);
@@ -136,8 +135,7 @@ public:
} // end of anonymous namespace
-QList<QmlJSQuickFixOperation::Ptr> ComponentFromObjectDef::match(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface)
+void ComponentFromObjectDef::match(const QmlJSQuickFixInterface &interface, QuickFixOperations &result)
{
const int pos = interface->currentFile()->cursor().position();
@@ -146,13 +144,12 @@ QList<QmlJSQuickFixOperation::Ptr> ComponentFromObjectDef::match(
Node *node = path.at(i);
if (UiObjectDefinition *objDef = cast<UiObjectDefinition *>(node)) {
if (!interface->currentFile()->isCursorOn(objDef->qualifiedTypeNameId))
- return noResult();
+ return;
// check that the node is not the root node
if (i > 0 && !cast<UiProgram*>(path.at(i - 1))) {
- return singleResult(new Operation(interface, objDef));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, objDef)));
+ return;
}
}
}
-
- return noResult();
}
diff --git a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.h b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.h
index a06ef8d00c..6d791a14a3 100644
--- a/src/plugins/qmljseditor/qmljscomponentfromobjectdef.h
+++ b/src/plugins/qmljseditor/qmljscomponentfromobjectdef.h
@@ -38,8 +38,7 @@ namespace Internal {
class ComponentFromObjectDef: public QmlJSQuickFixFactory
{
public:
- virtual QList<QmlJSQuickFixOperation::Ptr> match(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface);
+ void match(const QmlJSQuickFixInterface &interface, QuickFixOperations &result);
};
} // namespace Internal
diff --git a/src/plugins/qmljseditor/qmljseditor.cpp b/src/plugins/qmljseditor/qmljseditor.cpp
index b2cf774571..679a299a70 100644
--- a/src/plugins/qmljseditor/qmljseditor.cpp
+++ b/src/plugins/qmljseditor/qmljseditor.cpp
@@ -64,7 +64,6 @@
#include <texteditor/texteditorsettings.h>
#include <texteditor/syntaxhighlighter.h>
#include <texteditor/refactoroverlay.h>
-#include <texteditor/tooltip/tooltip.h>
#include <texteditor/codeassist/genericproposal.h>
#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <qmldesigner/qmldesignerconstants.h>
@@ -406,9 +405,8 @@ protected:
virtual bool visit(AST::UiScriptBinding *ast)
{
- if (AST::Block *block = AST::cast<AST::Block *>(ast->statement)) {
+ if (AST::Block *block = AST::cast<AST::Block *>(ast->statement))
_ranges.append(createRange(ast, block));
- }
return true;
}
@@ -580,7 +578,7 @@ Core::IEditor *QmlJSEditorEditable::duplicate(QWidget *parent)
Core::Id QmlJSEditorEditable::id() const
{
- return QmlJSEditor::Constants::C_QMLJSEDITOR_ID;
+ return Core::Id(QmlJSEditor::Constants::C_QMLJSEDITOR_ID);
}
bool QmlJSEditorEditable::open(QString *errorString, const QString &fileName, const QString &realFileName)
@@ -663,13 +661,12 @@ static void appendExtraSelectionsForMessages(
sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, d.location.length);
}
- if (d.severity == StaticAnalysis::Warning || d.severity == StaticAnalysis::MaybeWarning) {
+ if (d.severity == StaticAnalysis::Warning || d.severity == StaticAnalysis::MaybeWarning)
sel.format.setUnderlineColor(Qt::darkYellow);
- } else if (d.severity == StaticAnalysis::Error || d.severity == StaticAnalysis::MaybeError) {
+ else if (d.severity == StaticAnalysis::Error || d.severity == StaticAnalysis::MaybeError)
sel.format.setUnderlineColor(Qt::red);
- } else if (d.severity == StaticAnalysis::Hint) {
+ else if (d.severity == StaticAnalysis::Hint)
sel.format.setUnderlineColor(Qt::darkGreen);
- }
sel.format.setUnderlineStyle(QTextCharFormat::WaveUnderline);
sel.format.setToolTip(d.message);
@@ -896,9 +893,8 @@ protected:
UiQualifiedId *id = qualifiedTypeNameId(member);
if (id) {
const QStringRef &name = id->name;
- if (!name.isEmpty() && name.at(0).isUpper()) {
+ if (!name.isEmpty() && name.at(0).isUpper())
return true;
- }
}
return false;
@@ -988,7 +984,7 @@ void QmlJSTextEditorWidget::setSelectedElements()
QList<UiObjectMember *> members = selectedMembers(m_semanticInfo.document,
startPos, endPos);
if (!members.isEmpty()) {
- foreach(UiObjectMember *m, members) {
+ foreach (UiObjectMember *m, members) {
offsets << m;
}
}
@@ -1128,7 +1124,7 @@ TextEditor::BaseTextEditorWidget::Link QmlJSTextEditorWidget::findLinkAt(const Q
link.fileName = text;
return link;
}
- const QString relative = QString("%1/%2").arg(
+ const QString relative = QString::fromLatin1("%1/%2").arg(
semanticInfo.document->path(),
text);
if (semanticInfo.snapshot.document(relative)) {
@@ -1243,9 +1239,9 @@ void QmlJSTextEditorWidget::contextMenuEvent(QContextMenuEvent *e)
QMenu *contextMenu = mcontext->menu();
foreach (QAction *action, contextMenu->actions()) {
menu->addAction(action);
- if (action->objectName() == QmlJSEditor::Constants::M_REFACTORING_MENU_INSERTION_POINT)
+ if (action->objectName() == QLatin1String(QmlJSEditor::Constants::M_REFACTORING_MENU_INSERTION_POINT))
menu->addMenu(refactoringMenu);
- if (action->objectName() == QmlJSEditor::Constants::SHOW_QT_QUICK_HELPER) {
+ if (action->objectName() == QLatin1String(QmlJSEditor::Constants::SHOW_QT_QUICK_HELPER)) {
bool enabled = m_contextPane->isAvailable(editor(), semanticInfo().document, m_semanticInfo.declaringMemberNoProperties(position()));
action->setEnabled(enabled);
}
@@ -1286,9 +1282,8 @@ void QmlJSTextEditorWidget::wheelEvent(QWheelEvent *event)
BaseTextEditorWidget::wheelEvent(event);
- if (visible) {
+ if (visible)
m_contextPane->apply(editor(), semanticInfo().document, 0, m_semanticInfo.declaringMemberNoProperties(m_oldCursorPosition), false, true);
- }
}
void QmlJSTextEditorWidget::resizeEvent(QResizeEvent *event)
@@ -1424,9 +1419,8 @@ QModelIndex QmlJSTextEditorWidget::indexForPosition(unsigned cursorPosition, con
bool QmlJSTextEditorWidget::hideContextPane()
{
bool b = (m_contextPane) && m_contextPane->widget()->isVisible();
- if (b) {
+ if (b)
m_contextPane->apply(editor(), semanticInfo().document, 0, 0, false);
- }
return b;
}
diff --git a/src/plugins/qmljseditor/qmljseditor.qbs b/src/plugins/qmljseditor/qmljseditor.qbs
index b78578ca99..11d06ce5d7 100644
--- a/src/plugins/qmljseditor/qmljseditor.qbs
+++ b/src/plugins/qmljseditor/qmljseditor.qbs
@@ -17,17 +17,9 @@ QtcPlugin {
Depends { name: "CPlusPlus" }
Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_CREATOR"])
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- buildDirectory
- ]
+ cpp.defines: base.concat("QT_CREATOR")
files: [
- "qmljseditor.qrc",
- "quicktoolbarsettingspage.ui",
"QmlJSEditor.mimetypes.xml",
"jsfilewizard.cpp",
"jsfilewizard.h",
@@ -46,6 +38,7 @@ QtcPlugin {
"qmljscomponentnamedialog.ui",
"qmljseditor.cpp",
"qmljseditor.h",
+ "qmljseditor.qrc",
"qmljseditor_global.h",
"qmljseditoractionhandler.cpp",
"qmljseditoractionhandler.h",
@@ -82,6 +75,7 @@ QtcPlugin {
"qmljssnippetprovider.cpp",
"qmljssnippetprovider.h",
"qmljswrapinloader.cpp",
+ "qmljswrapinloader.h",
"qmloutlinemodel.cpp",
"qmloutlinemodel.h",
"qmltaskmanager.cpp",
@@ -90,12 +84,11 @@ QtcPlugin {
"quicktoolbar.h",
"quicktoolbarsettingspage.cpp",
"quicktoolbarsettingspage.h",
- "qmljswrapinloader.h",
- "images/qmlfile.png"
+ "quicktoolbarsettingspage.ui",
+ "images/qmlfile.png",
]
ProductModule {
Depends { name: "QmlJSTools" }
}
}
-
diff --git a/src/plugins/qmljseditor/qmljseditoreditable.cpp b/src/plugins/qmljseditor/qmljseditoreditable.cpp
index dd997f60bb..ddbb9516b2 100644
--- a/src/plugins/qmljseditor/qmljseditoreditable.cpp
+++ b/src/plugins/qmljseditor/qmljseditoreditable.cpp
@@ -85,7 +85,7 @@ Core::Id QmlJSEditorEditable::preferredModeType() const
// have the user also access to this failsafe setting.
if (editorWidget()->mimeType() == QLatin1String(QmlJSTools::Constants::QML_MIMETYPE)
&& openInDesignMode())
- return Core::Constants::MODE_DESIGN_TYPE;
+ return Core::Id(Core::Constants::MODE_DESIGN_TYPE);
return Core::Id();
}
diff --git a/src/plugins/qmljseditor/qmljseditorfactory.cpp b/src/plugins/qmljseditor/qmljseditorfactory.cpp
index 406a8b6887..f7b52da4b0 100644
--- a/src/plugins/qmljseditor/qmljseditorfactory.cpp
+++ b/src/plugins/qmljseditor/qmljseditorfactory.cpp
@@ -59,6 +59,9 @@ QmlJSEditorFactory::QmlJSEditorFactory(QObject *parent)
{
m_mimeTypes
<< QLatin1String(QmlJSTools::Constants::QML_MIMETYPE)
+ << QLatin1String(QmlJSTools::Constants::QMLPROJECT_MIMETYPE)
+ << QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE)
+ << QLatin1String(QmlJSTools::Constants::QMLTYPES_MIMETYPE)
<< QLatin1String(QmlJSTools::Constants::JS_MIMETYPE)
<< QLatin1String(QmlJSTools::Constants::JSON_MIMETYPE)
;
@@ -66,7 +69,7 @@ QmlJSEditorFactory::QmlJSEditorFactory(QObject *parent)
Core::Id QmlJSEditorFactory::id() const
{
- return C_QMLJSEDITOR_ID;
+ return Core::Id(C_QMLJSEDITOR_ID);
}
QString QmlJSEditorFactory::displayName() const
diff --git a/src/plugins/qmljseditor/qmljseditorplugin.cpp b/src/plugins/qmljseditor/qmljseditorplugin.cpp
index 9d50fcd033..21044644d2 100644
--- a/src/plugins/qmljseditor/qmljseditorplugin.cpp
+++ b/src/plugins/qmljseditor/qmljseditorplugin.cpp
@@ -217,7 +217,7 @@ bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *e
// Insert marker for "Refactoring" menu:
Core::Command *sep = contextMenu->addSeparator(globalContext);
- sep->action()->setObjectName(Constants::M_REFACTORING_MENU_INSERTION_POINT);
+ sep->action()->setObjectName(QLatin1String(Constants::M_REFACTORING_MENU_INSERTION_POINT));
contextMenu->addSeparator(globalContext);
cmd = Core::ActionManager::command(TextEditor::Constants::AUTO_INDENT_SELECTION);
@@ -235,7 +235,7 @@ bool QmlJSEditorPlugin::initialize(const QStringList & /*arguments*/, QString *e
errorMessage->clear();
Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmljseditor/images/qmlfile.png")), "qml");
+ iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmljseditor/images/qmlfile.png")), QLatin1String("qml"));
registerQuickFixes(this);
diff --git a/src/plugins/qmljseditor/qmljsfindreferences.cpp b/src/plugins/qmljseditor/qmljsfindreferences.cpp
index 0fb59b13f7..50ebf9a6b2 100644
--- a/src/plugins/qmljseditor/qmljsfindreferences.cpp
+++ b/src/plugins/qmljseditor/qmljsfindreferences.cpp
@@ -250,9 +250,8 @@ private:
if (idEnv && idEnv->lookupMember(_name, _scopeChain.context()))
return idEnv == _scope;
const ObjectValue *root = chain->document()->bind()->rootObjectValue();
- if (root && root->lookupMember(_name, _scopeChain.context())) {
+ if (root && root->lookupMember(_name, _scopeChain.context()))
return check(root);
- }
foreach (const QmlComponentChain *parent, chain->instantiatingComponents()) {
if (contains(parent))
@@ -506,13 +505,12 @@ protected:
virtual bool preVisit(Node *node)
{
- if (Statement *stmt = node->statementCast()) {
+ if (Statement *stmt = node->statementCast())
return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation());
- } else if (ExpressionNode *exp = node->expressionCast()) {
+ else if (ExpressionNode *exp = node->expressionCast())
return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation());
- } else if (UiObjectMember *ui = node->uiObjectMemberCast()) {
+ else if (UiObjectMember *ui = node->uiObjectMemberCast())
return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation());
- }
return true;
}
@@ -933,8 +931,8 @@ void FindReferences::displayResults(int first, int last)
m_currentSearch = Find::SearchResultWindow::instance()->startNewSearch(
label, QString(), symbolName, Find::SearchResultWindow::SearchAndReplace);
m_currentSearch->setTextToReplace(replacement);
- connect(m_currentSearch, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
- SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>)));
+ connect(m_currentSearch, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)),
+ SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)));
}
connect(m_currentSearch, SIGNAL(activated(Find::SearchResultItem)),
this, SLOT(openEditor(Find::SearchResultItem)));
@@ -945,7 +943,7 @@ void FindReferences::displayResults(int first, int last)
Core::ProgressManager *progressManager = Core::ICore::progressManager();
Core::FutureProgress *progress = progressManager->addTask(
m_watcher.future(), tr("Searching"),
- QmlJSEditor::Constants::TASK_SEARCH);
+ QLatin1String(QmlJSEditor::Constants::TASK_SEARCH));
connect(progress, SIGNAL(clicked()), m_currentSearch, SLOT(popup()));
++first;
@@ -996,9 +994,9 @@ void FindReferences::openEditor(const Find::SearchResultItem &item)
}
}
-void FindReferences::onReplaceButtonClicked(const QString &text, const QList<Find::SearchResultItem> &items)
+void FindReferences::onReplaceButtonClicked(const QString &text, const QList<Find::SearchResultItem> &items, bool preserveCase)
{
- const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items);
+ const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items, preserveCase);
// files that are opened in an editor are changed, but not saved
QStringList changedOnDisk;
diff --git a/src/plugins/qmljseditor/qmljsfindreferences.h b/src/plugins/qmljseditor/qmljsfindreferences.h
index 06078c9667..779724e603 100644
--- a/src/plugins/qmljseditor/qmljsfindreferences.h
+++ b/src/plugins/qmljseditor/qmljsfindreferences.h
@@ -86,7 +86,7 @@ private Q_SLOTS:
void cancel();
void setPaused(bool paused);
void openEditor(const Find::SearchResultItem &item);
- void onReplaceButtonClicked(const QString &text, const QList<Find::SearchResultItem> &items);
+ void onReplaceButtonClicked(const QString &text, const QList<Find::SearchResultItem> &items, bool preserveCase);
private:
QPointer<Find::SearchResult> m_currentSearch;
diff --git a/src/plugins/qmljseditor/qmljshighlighter.cpp b/src/plugins/qmljseditor/qmljshighlighter.cpp
index 4877713f5c..31f4e3cbc4 100644
--- a/src/plugins/qmljseditor/qmljshighlighter.cpp
+++ b/src/plugins/qmljseditor/qmljshighlighter.cpp
@@ -87,12 +87,12 @@ void Highlighter::highlightBlock(const QString &text)
case Token::Comment:
if (m_inMultilineComment && text.midRef(token.end() - 2, 2) == QLatin1String("*/")) {
- onClosingParenthesis('-', token.end() - 1, index == tokens.size()-1);
+ onClosingParenthesis(QLatin1Char('-'), token.end() - 1, index == tokens.size()-1);
m_inMultilineComment = false;
} else if (!m_inMultilineComment
&& (m_scanner.state() & Scanner::MultiLineMask) == Scanner::MultiLineComment
&& index == tokens.size() - 1) {
- onOpeningParenthesis('+', token.offset, index == 0);
+ onOpeningParenthesis(QLatin1Char('+'), token.offset, index == 0);
m_inMultilineComment = true;
}
setFormat(token.offset, token.length, m_formats[CommentFormat]);
@@ -103,27 +103,27 @@ void Highlighter::highlightBlock(const QString &text)
break;
case Token::LeftParenthesis:
- onOpeningParenthesis('(', token.offset, index == 0);
+ onOpeningParenthesis(QLatin1Char('('), token.offset, index == 0);
break;
case Token::RightParenthesis:
- onClosingParenthesis(')', token.offset, index == tokens.size()-1);
+ onClosingParenthesis(QLatin1Char(')'), token.offset, index == tokens.size()-1);
break;
case Token::LeftBrace:
- onOpeningParenthesis('{', token.offset, index == 0);
+ onOpeningParenthesis(QLatin1Char('{'), token.offset, index == 0);
break;
case Token::RightBrace:
- onClosingParenthesis('}', token.offset, index == tokens.size()-1);
+ onClosingParenthesis(QLatin1Char('}'), token.offset, index == tokens.size()-1);
break;
case Token::LeftBracket:
- onOpeningParenthesis('[', token.offset, index == 0);
+ onOpeningParenthesis(QLatin1Char('['), token.offset, index == 0);
break;
case Token::RightBracket:
- onClosingParenthesis(']', token.offset, index == tokens.size()-1);
+ onClosingParenthesis(QLatin1Char(']'), token.offset, index == tokens.size()-1);
break;
case Token::Identifier: {
@@ -203,23 +203,22 @@ bool Highlighter::maybeQmlKeyword(const QStringRef &text) const
return false;
const QChar ch = text.at(0);
- if (ch == QLatin1Char('p') && text == QLatin1String("property")) {
+ if (ch == QLatin1Char('p') && text == QLatin1String("property"))
return true;
- } else if (ch == QLatin1Char('a') && text == QLatin1String("alias")) {
+ else if (ch == QLatin1Char('a') && text == QLatin1String("alias"))
return true;
- } else if (ch == QLatin1Char('s') && text == QLatin1String("signal")) {
+ else if (ch == QLatin1Char('s') && text == QLatin1String("signal"))
return true;
- } else if (ch == QLatin1Char('p') && text == QLatin1String("property")) {
+ else if (ch == QLatin1Char('p') && text == QLatin1String("property"))
return true;
- } else if (ch == QLatin1Char('r') && text == QLatin1String("readonly")) {
+ else if (ch == QLatin1Char('r') && text == QLatin1String("readonly"))
return true;
- } else if (ch == QLatin1Char('i') && text == QLatin1String("import")) {
+ else if (ch == QLatin1Char('i') && text == QLatin1String("import"))
return true;
- } else if (ch == QLatin1Char('o') && text == QLatin1String("on")) {
+ else if (ch == QLatin1Char('o') && text == QLatin1String("on"))
return true;
- } else {
+ else
return false;
- }
}
bool Highlighter::maybeQmlBuiltinType(const QStringRef &text) const
@@ -229,47 +228,46 @@ bool Highlighter::maybeQmlBuiltinType(const QStringRef &text) const
const QChar ch = text.at(0);
- if (ch == QLatin1Char('a') && text == QLatin1String("action")) {
+ if (ch == QLatin1Char('a') && text == QLatin1String("action"))
return true;
- } else if (ch == QLatin1Char('b') && text == QLatin1String("bool")) {
+ else if (ch == QLatin1Char('b') && text == QLatin1String("bool"))
return true;
- } else if (ch == QLatin1Char('c') && text == QLatin1String("color")) {
+ else if (ch == QLatin1Char('c') && text == QLatin1String("color"))
return true;
- } else if (ch == QLatin1Char('d') && text == QLatin1String("date")) {
+ else if (ch == QLatin1Char('d') && text == QLatin1String("date"))
return true;
- } else if (ch == QLatin1Char('d') && text == QLatin1String("double")) {
+ else if (ch == QLatin1Char('d') && text == QLatin1String("double"))
return true;
- } else if (ch == QLatin1Char('e') && text == QLatin1String("enumeration")) {
+ else if (ch == QLatin1Char('e') && text == QLatin1String("enumeration"))
return true;
- } else if (ch == QLatin1Char('f') && text == QLatin1String("font")) {
+ else if (ch == QLatin1Char('f') && text == QLatin1String("font"))
return true;
- } else if (ch == QLatin1Char('i') && text == QLatin1String("int")) {
+ else if (ch == QLatin1Char('i') && text == QLatin1String("int"))
return true;
- } else if (ch == QLatin1Char('l') && text == QLatin1String("list")) {
+ else if (ch == QLatin1Char('l') && text == QLatin1String("list"))
return true;
- } else if (ch == QLatin1Char('p') && text == QLatin1String("point")) {
+ else if (ch == QLatin1Char('p') && text == QLatin1String("point"))
return true;
- } else if (ch == QLatin1Char('r') && text == QLatin1String("real")) {
+ else if (ch == QLatin1Char('r') && text == QLatin1String("real"))
return true;
- } else if (ch == QLatin1Char('r') && text == QLatin1String("rect")) {
+ else if (ch == QLatin1Char('r') && text == QLatin1String("rect"))
return true;
- } else if (ch == QLatin1Char('s') && text == QLatin1String("size")) {
+ else if (ch == QLatin1Char('s') && text == QLatin1String("size"))
return true;
- } else if (ch == QLatin1Char('s') && text == QLatin1String("string")) {
+ else if (ch == QLatin1Char('s') && text == QLatin1String("string"))
return true;
- } else if (ch == QLatin1Char('t') && text == QLatin1String("time")) {
+ else if (ch == QLatin1Char('t') && text == QLatin1String("time"))
return true;
- } else if (ch == QLatin1Char('u') && text == QLatin1String("url")) {
+ else if (ch == QLatin1Char('u') && text == QLatin1String("url"))
return true;
- } else if (ch == QLatin1Char('v') && text == QLatin1String("variant")) {
+ else if (ch == QLatin1Char('v') && text == QLatin1String("variant"))
return true;
- } else if (ch == QLatin1Char('v') && text == QLatin1String("var")) {
+ else if (ch == QLatin1Char('v') && text == QLatin1String("var"))
return true;
- } else if (ch == QLatin1Char('v') && text == QLatin1String("vector3d")) {
+ else if (ch == QLatin1Char('v') && text == QLatin1String("vector3d"))
return true;
- } else {
+ else
return false;
- }
}
int Highlighter::onBlockStart()
diff --git a/src/plugins/qmljseditor/qmljshoverhandler.cpp b/src/plugins/qmljseditor/qmljshoverhandler.cpp
index 9891d0de90..fff9076f2a 100644
--- a/src/plugins/qmljseditor/qmljshoverhandler.cpp
+++ b/src/plugins/qmljseditor/qmljshoverhandler.cpp
@@ -46,8 +46,8 @@
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <texteditor/helpitem.h>
-#include <texteditor/tooltip/tooltip.h>
-#include <texteditor/tooltip/tipcontents.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <QDir>
#include <QList>
@@ -265,15 +265,15 @@ void HoverHandler::reset()
void HoverHandler::operateTooltip(TextEditor::ITextEditor *editor, const QPoint &point)
{
if (toolTip().isEmpty())
- TextEditor::ToolTip::instance()->hide();
+ Utils::ToolTip::instance()->hide();
else {
if (m_colorTip.isValid()) {
- TextEditor::ToolTip::instance()->show(point,
- TextEditor::ColorContent(m_colorTip),
+ Utils::ToolTip::instance()->show(point,
+ Utils::ColorContent(m_colorTip),
editor->widget());
} else {
- TextEditor::ToolTip::instance()->show(point,
- TextEditor::TextContent(toolTip()),
+ Utils::ToolTip::instance()->show(point,
+ Utils::TextContent(toolTip()),
editor->widget());
}
}
diff --git a/src/plugins/qmljseditor/qmljsoutline.cpp b/src/plugins/qmljseditor/qmljsoutline.cpp
index 9ff16574e7..e8f4a41c53 100644
--- a/src/plugins/qmljseditor/qmljsoutline.cpp
+++ b/src/plugins/qmljseditor/qmljsoutline.cpp
@@ -64,9 +64,8 @@ bool QmlJSOutlineFilterModel::filterAcceptsRow(int sourceRow,
if (m_filterBindings) {
QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0, sourceParent);
QVariant itemType = sourceIndex.data(QmlOutlineModel::ItemTypeRole);
- if (itemType == QmlOutlineModel::NonElementBindingType) {
+ if (itemType == QmlOutlineModel::NonElementBindingType)
return false;
- }
}
return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}
@@ -157,14 +156,15 @@ void QmlJSOutlineWidget::setCursorSynchronization(bool syncWithCursor)
void QmlJSOutlineWidget::restoreSettings(int position)
{
QSettings *settings = Core::ICore::settings();
- bool showBindings = settings->value("QmlJSOutline."+QString::number(position)+".ShowBindings", true).toBool();
+ bool showBindings = settings->value(
+ QString::fromLatin1("QmlJSOutline.%1.ShowBindings").arg(position), true).toBool();
m_showBindingsAction->setChecked(showBindings);
}
void QmlJSOutlineWidget::saveSettings(int position)
{
QSettings *settings = Core::ICore::settings();
- settings->setValue("QmlJSOutline."+QString::number(position)+".ShowBindings",
+ settings->setValue(QString::fromLatin1("QmlJSOutline.%1.ShowBindings").arg(position),
m_showBindingsAction->isChecked());
}
diff --git a/src/plugins/qmljseditor/qmljspreviewrunner.cpp b/src/plugins/qmljseditor/qmljspreviewrunner.cpp
index 4fab605c99..4f58957275 100644
--- a/src/plugins/qmljseditor/qmljspreviewrunner.cpp
+++ b/src/plugins/qmljseditor/qmljspreviewrunner.cpp
@@ -30,6 +30,7 @@
#include "qmljspreviewrunner.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcprocess.h>
#include <utils/synchronousprocess.h>
@@ -46,8 +47,8 @@ QmlJSPreviewRunner::QmlJSPreviewRunner(QObject *parent) :
{
// prepend creator/bin dir to search path (only useful for special creator-qml package)
const QString searchPath = QCoreApplication::applicationDirPath()
- + Utils::SynchronousProcess::pathSeparator()
- + QString(qgetenv("PATH"));
+ + Utils::HostOsInfo::pathListSeparator()
+ + QString::fromLocal8Bit(qgetenv("PATH"));
m_qmlViewerDefaultPath = Utils::SynchronousProcess::locateBinary(searchPath, QLatin1String("qmlviewer"));
Utils::Environment environment = Utils::Environment::systemEnvironment();
diff --git a/src/plugins/qmljseditor/qmljsquickfix.cpp b/src/plugins/qmljseditor/qmljsquickfix.cpp
index b9f7fab423..e1ece15032 100644
--- a/src/plugins/qmljseditor/qmljsquickfix.cpp
+++ b/src/plugins/qmljseditor/qmljsquickfix.cpp
@@ -45,21 +45,15 @@ using namespace QmlJS::AST;
using namespace QmlJSEditor;
using namespace QmlJSEditor::Internal;
using namespace QmlJSTools;
-using namespace TextEditor;
using TextEditor::RefactoringChanges;
-QmlJSQuickFixOperation::QmlJSQuickFixOperation(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface,
- int priority)
+QmlJSQuickFixOperation::QmlJSQuickFixOperation(const QmlJSQuickFixInterface &interface,
+ int priority)
: QuickFixOperation(priority)
, m_interface(interface)
{
}
-QmlJSQuickFixOperation::~QmlJSQuickFixOperation()
-{
-}
-
void QmlJSQuickFixOperation::perform()
{
QmlJSRefactoringChanges refactoring(QmlJS::ModelManagerInterface::instance(),
@@ -79,28 +73,9 @@ QString QmlJSQuickFixOperation::fileName() const
return m_interface->semanticInfo().document->fileName();
}
-QmlJSQuickFixFactory::QmlJSQuickFixFactory()
-{
-}
-
-QmlJSQuickFixFactory::~QmlJSQuickFixFactory()
-{
-}
-
-QList<QuickFixOperation::Ptr> QmlJSQuickFixFactory::matchingOperations(
- const QSharedPointer<const TextEditor::IAssistInterface> &interface)
-{
- return match(interface.staticCast<const QmlJSQuickFixAssistInterface>());
-}
-
-QList<QmlJSQuickFixOperation::Ptr> QmlJSQuickFixFactory::noResult()
-{
- return QList<QmlJSQuickFixOperation::Ptr>();
-}
-QList<QmlJSQuickFixOperation::Ptr> QmlJSQuickFixFactory::singleResult(QmlJSQuickFixOperation *operation)
+void QmlJSQuickFixFactory::matchingOperations(const QuickFixInterface &interface,
+ QuickFixOperations &result)
{
- QList<QmlJSQuickFixOperation::Ptr> result;
- result.append(QmlJSQuickFixOperation::Ptr(operation));
- return result;
+ match(interface.staticCast<const QmlJSQuickFixAssistInterface>(), result);
}
diff --git a/src/plugins/qmljseditor/qmljsquickfix.h b/src/plugins/qmljseditor/qmljsquickfix.h
index 2cbc7c8c30..ba01ecb4cd 100644
--- a/src/plugins/qmljseditor/qmljsquickfix.h
+++ b/src/plugins/qmljseditor/qmljsquickfix.h
@@ -39,20 +39,16 @@
#include <QSharedPointer>
-namespace ExtensionSystem {
-class IPlugin;
-}
-
-namespace QmlJS {
- class ModelManagerInterface;
-}
+namespace QmlJS { class ModelManagerInterface; }
namespace QmlJSEditor {
-namespace Internal {
-class QmlJSQuickFixAssistInterface;
-} // namespace Internal
+namespace Internal { class QmlJSQuickFixAssistInterface; }
+typedef QSharedPointer<const Internal::QmlJSQuickFixAssistInterface> QmlJSQuickFixInterface;
+typedef TextEditor::QuickFixOperation QuickFixOperation;
+typedef TextEditor::QuickFixOperations QuickFixOperations;
+typedef TextEditor::QuickFixInterface QuickFixInterface;
/*!
A quick-fix operation for the QML/JavaScript editor.
@@ -66,10 +62,7 @@ public:
\param interface The interface on which the operation is performed.
\param priority The priority for this operation.
*/
- explicit QmlJSQuickFixOperation(
- const QSharedPointer<const Internal::QmlJSQuickFixAssistInterface> &interface,
- int priority = -1);
- virtual ~QmlJSQuickFixOperation();
+ explicit QmlJSQuickFixOperation(const QmlJSQuickFixInterface &interface, int priority = -1);
virtual void perform();
@@ -85,29 +78,23 @@ protected:
QString fileName() const;
private:
- QSharedPointer<const Internal::QmlJSQuickFixAssistInterface> m_interface;
+ QmlJSQuickFixInterface m_interface;
};
class QmlJSQuickFixFactory: public TextEditor::QuickFixFactory
{
Q_OBJECT
-public:
- QmlJSQuickFixFactory();
- virtual ~QmlJSQuickFixFactory();
+protected:
+ QmlJSQuickFixFactory() {}
- virtual QList<TextEditor::QuickFixOperation::Ptr>
- matchingOperations(const QSharedPointer<const TextEditor::IAssistInterface> &interface);
+ void matchingOperations(const QuickFixInterface &interface, QuickFixOperations &result);
/*!
Implement this method to match and create the appropriate
QmlJSQuickFixOperation objects.
*/
- virtual QList<QmlJSQuickFixOperation::Ptr> match(
- const QSharedPointer<const Internal::QmlJSQuickFixAssistInterface> &interface) = 0;
-
- static QList<QmlJSQuickFixOperation::Ptr> noResult();
- static QList<QmlJSQuickFixOperation::Ptr> singleResult(QmlJSQuickFixOperation *operation);
+ virtual void match(const QmlJSQuickFixInterface &interface, TextEditor::QuickFixOperations &result) = 0;
};
} // namespace QmlJSEditor
diff --git a/src/plugins/qmljseditor/qmljsquickfixes.cpp b/src/plugins/qmljseditor/qmljsquickfixes.cpp
index 0f456150f9..3bb16e826b 100644
--- a/src/plugins/qmljseditor/qmljsquickfixes.cpp
+++ b/src/plugins/qmljseditor/qmljsquickfixes.cpp
@@ -45,7 +45,6 @@ using namespace QmlJS::AST;
using namespace QmlJSEditor;
using namespace QmlJSEditor::Internal;
using namespace QmlJSTools;
-using namespace TextEditor;
using TextEditor::RefactoringChanges;
namespace {
@@ -62,9 +61,7 @@ namespace {
*/
class SplitInitializerOp: public QmlJSQuickFixFactory
{
-public:
- virtual QList<QmlJSQuickFixOperation::Ptr> match(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface)
+ void match(const QmlJSQuickFixInterface &interface, QuickFixOperations &result)
{
UiObjectInitializer *objectInitializer = 0;
@@ -82,12 +79,9 @@ public:
}
if (objectInitializer)
- return singleResult(new Operation(interface, objectInitializer));
- else
- return noResult();
+ result.append(TextEditor::QuickFixOperation::Ptr(new Operation(interface, objectInitializer)));
}
-private:
class Operation: public QmlJSQuickFixOperation
{
UiObjectInitializer *_objectInitializer;
@@ -102,7 +96,7 @@ private:
"Split Initializer"));
}
- virtual void performChanges(QmlJSRefactoringFilePtr currentFile,
+ void performChanges(QmlJSRefactoringFilePtr currentFile,
const QmlJSRefactoringChanges &)
{
Q_ASSERT(_objectInitializer != 0);
@@ -137,18 +131,16 @@ class AddAnalysisMessageSuppressionComment: public QmlJSQuickFixFactory
{
Q_DECLARE_TR_FUNCTIONS(QmlJSEditor::AddAnalysisMessageSuppressionComment)
public:
- virtual QList<QmlJSQuickFixOperation::Ptr> match(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface)
+ void match(const QmlJSQuickFixInterface &interface, QuickFixOperations &result)
{
const QList<StaticAnalysis::Message> &messages = interface->semanticInfo().staticAnalysisMessages;
foreach (const StaticAnalysis::Message &message, messages) {
if (interface->currentFile()->isCursorOn(message.location)) {
- return singleResult(new Operation(interface, message));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, message)));
+ return;
}
}
-
- return noResult();
}
private:
@@ -170,7 +162,7 @@ private:
{
Utils::ChangeSet changes;
const int insertLoc = _message.location.begin() - _message.location.startColumn + 1;
- changes.insert(insertLoc, QString("// %1\n").arg(_message.suppressionString()));
+ changes.insert(insertLoc, QString::fromLatin1("// %1\n").arg(_message.suppressionString()));
currentFile->setChangeSet(changes);
currentFile->appendIndentRange(Range(insertLoc, insertLoc + 1));
currentFile->apply();
diff --git a/src/plugins/qmljseditor/qmljssemantichighlighter.cpp b/src/plugins/qmljseditor/qmljssemantichighlighter.cpp
index a01f3dc81d..3040584864 100644
--- a/src/plugins/qmljseditor/qmljssemantichighlighter.cpp
+++ b/src/plugins/qmljseditor/qmljssemantichighlighter.cpp
@@ -270,11 +270,10 @@ protected:
bool visit(UiObjectDefinition *ast)
{
- if (m_scopeChain.document()->bind()->isGroupedPropertyBinding(ast)) {
+ if (m_scopeChain.document()->bind()->isGroupedPropertyBinding(ast))
processBindingName(ast->qualifiedTypeNameId);
- } else {
+ else
processTypeId(ast->qualifiedTypeNameId);
- }
scopedAccept(ast, ast->initializer);
return false;
}
@@ -342,9 +341,8 @@ protected:
return false;
const QString &value = ast->value.toString();
- if (m_stateNames.contains(value)) {
+ if (m_stateNames.contains(value))
addUse(ast->literalToken, SemanticHighlighter::LocalStateNameType);
- }
return false;
}
@@ -438,7 +436,7 @@ void SemanticHighlighter::applyResults(int from, int to)
if (m_startRevision != m_editor->editorRevision())
return;
- TextEditor::BaseTextDocument *baseTextDocument = m_editor->baseTextDocument();
+ TextEditor::BaseTextDocument *baseTextDocument = m_editor->baseTextDocument().data();
QTC_ASSERT(baseTextDocument, return);
TextEditor::SyntaxHighlighter *highlighter = qobject_cast<TextEditor::SyntaxHighlighter *>(baseTextDocument->syntaxHighlighter());
QTC_ASSERT(highlighter, return);
@@ -454,7 +452,7 @@ void SemanticHighlighter::finished()
if (m_startRevision != m_editor->editorRevision())
return;
- TextEditor::BaseTextDocument *baseTextDocument = m_editor->baseTextDocument();
+ TextEditor::BaseTextDocument *baseTextDocument = m_editor->baseTextDocument().data();
QTC_ASSERT(baseTextDocument, return);
TextEditor::SyntaxHighlighter *highlighter = qobject_cast<TextEditor::SyntaxHighlighter *>(baseTextDocument->syntaxHighlighter());
QTC_ASSERT(highlighter, return);
diff --git a/src/plugins/qmljseditor/qmljswrapinloader.cpp b/src/plugins/qmljseditor/qmljswrapinloader.cpp
index c14ecd3796..ffb204ffdd 100644
--- a/src/plugins/qmljseditor/qmljswrapinloader.cpp
+++ b/src/plugins/qmljseditor/qmljswrapinloader.cpp
@@ -144,8 +144,8 @@ public:
const QString innerId = it.key();
comment += tr("// Rename all outer uses of the id '%1' to '%2.item.%1'.\n").arg(
innerId, loaderId);
- changes.replace(it.value().begin(), it.value().end(), QString("inner_%1").arg(innerId));
- innerIdForwarders += QString("\nproperty alias %1: inner_%1").arg(innerId);
+ changes.replace(it.value().begin(), it.value().end(), QString::fromLatin1("inner_%1").arg(innerId));
+ innerIdForwarders += QString::fromLatin1("\nproperty alias %1: inner_%1").arg(innerId);
}
if (!innerIdForwarders.isEmpty()) {
innerIdForwarders.append(QLatin1Char('\n'));
@@ -156,14 +156,14 @@ public:
const int objDefStart = m_objDef->firstSourceLocation().begin();
const int objDefEnd = m_objDef->lastSourceLocation().end();
changes.insert(objDefStart, comment +
- QString("Component {\n"
- " id: %1\n").arg(componentId));
- changes.insert(objDefEnd, QString("\n"
- "}\n"
- "Loader {\n"
- " id: %2\n"
- " sourceComponent: %1\n"
- "}\n").arg(componentId, loaderId));
+ QString::fromLatin1("Component {\n"
+ " id: %1\n").arg(componentId));
+ changes.insert(objDefEnd, QString::fromLatin1("\n"
+ "}\n"
+ "Loader {\n"
+ " id: %2\n"
+ " sourceComponent: %1\n"
+ "}\n").arg(componentId, loaderId));
currentFile->setChangeSet(changes);
currentFile->appendIndentRange(Range(objDefStart, objDefEnd));
currentFile->apply();
@@ -173,8 +173,7 @@ public:
} // end of anonymous namespace
-QList<QmlJSQuickFixOperation::Ptr> WrapInLoader::match(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface)
+void WrapInLoader::match(const QmlJSQuickFixInterface &interface, QuickFixOperations &result)
{
const int pos = interface->currentFile()->cursor().position();
@@ -183,13 +182,12 @@ QList<QmlJSQuickFixOperation::Ptr> WrapInLoader::match(
Node *node = path.at(i);
if (UiObjectDefinition *objDef = cast<UiObjectDefinition *>(node)) {
if (!interface->currentFile()->isCursorOn(objDef->qualifiedTypeNameId))
- return noResult();
+ return;
// check that the node is not the root node
if (i > 0 && !cast<UiProgram*>(path.at(i - 1))) {
- return singleResult(new Operation(interface, objDef));
+ result.append(QuickFixOperation::Ptr(new Operation(interface, objDef)));
+ return;
}
}
}
-
- return noResult();
}
diff --git a/src/plugins/qmljseditor/qmljswrapinloader.h b/src/plugins/qmljseditor/qmljswrapinloader.h
index 3aee9f17bb..c9781e998a 100644
--- a/src/plugins/qmljseditor/qmljswrapinloader.h
+++ b/src/plugins/qmljseditor/qmljswrapinloader.h
@@ -37,9 +37,7 @@ namespace Internal {
class WrapInLoader: public QmlJSQuickFixFactory
{
-public:
- virtual QList<QmlJSQuickFixOperation::Ptr> match(
- const QSharedPointer<const QmlJSQuickFixAssistInterface> &interface);
+ void match(const QmlJSQuickFixInterface &interface, QuickFixOperations &result);
};
} // namespace Internal
diff --git a/src/plugins/qmljseditor/qmloutlinemodel.cpp b/src/plugins/qmljseditor/qmloutlinemodel.cpp
index 68f5e044f6..0dab481dfb 100644
--- a/src/plugins/qmljseditor/qmloutlinemodel.cpp
+++ b/src/plugins/qmljseditor/qmloutlinemodel.cpp
@@ -76,9 +76,8 @@ QVariant QmlOutlineItem::data(int role) const
return prettyPrint(value, scopeChain.context());
}
- if (role == Qt::DecorationRole) {
+ if (role == Qt::DecorationRole)
return m_outlineModel->icon(index());
- }
return QStandardItem::data(role);
}
@@ -104,15 +103,13 @@ QString QmlOutlineItem::prettyPrint(const Value *value, const ContextPtr &contex
if (const ObjectValue *objectValue = value->asObjectValue()) {
const QString className = objectValue->className();
- if (!className.isEmpty()) {
+ if (!className.isEmpty())
return className;
- }
}
const QString typeId = context->valueOwner()->typeId(value);
- if (typeId == QLatin1String("undefined")) {
+ if (typeId == QLatin1String("undefined"))
return QString();
- }
return typeId;
}
@@ -145,9 +142,8 @@ private:
{
if (AST::UiObjectMember *objMember = node->uiObjectMemberCast()) {
stack.removeLast();
- if (!stack.isEmpty()) {
+ if (!stack.isEmpty())
parent.insert(objMember, stack.last());
- }
}
}
};
@@ -269,7 +265,7 @@ private:
AST::IdentifierExpression *lhsIdent = AST::cast<AST::IdentifierExpression *>(binExp->left);
AST::ObjectLiteral *rhsObjLit = AST::cast<AST::ObjectLiteral *>(binExp->right);
- if (lhsIdent && rhsObjLit && (lhsIdent->name == "testcase")
+ if (lhsIdent && rhsObjLit && (lhsIdent->name == QLatin1String("testcase"))
&& (binExp->op == QSOperator::Assign)) {
QModelIndex index = m_model->enterTestCase(rhsObjLit);
m_nodeToIndex.insert(rhsObjLit, index);
@@ -308,7 +304,7 @@ QmlOutlineModel::QmlOutlineModel(QmlJSTextEditorWidget *editor) :
{
m_icons = Icons::instance();
const QString resourcePath = Core::ICore::resourcePath();
- Icons::instance()->setIconFilesPath(resourcePath + "/qmlicons");
+ Icons::instance()->setIconFilesPath(resourcePath + QLatin1String("/qmlicons"));
// TODO: Maybe add a Copy Action?
setSupportedDragActions(Qt::MoveAction);
@@ -462,9 +458,8 @@ QModelIndex QmlOutlineModel::enterObjectDefinition(AST::UiObjectDefinition *objD
data.insert(ItemTypeRole, ElementType);
data.insert(AnnotationRole, getAnnotation(objDef->initializer));
idNode = objDef->qualifiedTypeNameId;
- if (!m_typeToIcon.contains(typeName)) {
+ if (!m_typeToIcon.contains(typeName))
m_typeToIcon.insert(typeName, getIcon(objDef->qualifiedTypeNameId));
- }
icon = m_typeToIcon.value(typeName);
} else {
// it's a grouped propery like 'anchors'
@@ -492,9 +487,8 @@ QModelIndex QmlOutlineModel::enterObjectBinding(AST::UiObjectBinding *objBinding
QmlOutlineItem *bindingItem = enterNode(bindingData, objBinding, objBinding->qualifiedId, m_icons->scriptBindingIcon());
const QString typeName = asString(objBinding->qualifiedTypeNameId);
- if (!m_typeToIcon.contains(typeName)) {
+ if (!m_typeToIcon.contains(typeName))
m_typeToIcon.insert(typeName, getIcon(objBinding->qualifiedTypeNameId));
- }
QMap<int, QVariant> objectData;
objectData.insert(Qt::DisplayRole, typeName);
@@ -588,7 +582,7 @@ QModelIndex QmlOutlineModel::enterTestCase(AST::ObjectLiteral *objectLiteral)
{
QMap<int, QVariant> objectData;
- objectData.insert(Qt::DisplayRole, "testcase");
+ objectData.insert(Qt::DisplayRole, QLatin1String("testcase"));
objectData.insert(ItemTypeRole, ElementBindingType);
QmlOutlineItem *item = enterNode(objectData, objectLiteral, 0, m_icons->objectDefinitionIcon());
@@ -608,13 +602,12 @@ QModelIndex QmlOutlineModel::enterTestCaseProperties(AST::PropertyNameAndValueLi
objectData.insert(Qt::DisplayRole, propertyName->id.toString());
objectData.insert(ItemTypeRole, ElementBindingType);
QmlOutlineItem *item;
- if (propertyNameAndValueList->value->kind == AST::Node::Kind_FunctionExpression) {
+ if (propertyNameAndValueList->value->kind == AST::Node::Kind_FunctionExpression)
item = enterNode(objectData, propertyNameAndValueList, 0, m_icons->functionDeclarationIcon());
- } else if (propertyNameAndValueList->value->kind == AST::Node::Kind_ObjectLiteral) {
+ else if (propertyNameAndValueList->value->kind == AST::Node::Kind_ObjectLiteral)
item = enterNode(objectData, propertyNameAndValueList, 0, m_icons->objectDefinitionIcon());
- } else {
+ else
item = enterNode(objectData, propertyNameAndValueList, 0, m_icons->scriptBindingIcon());
- }
return item->index();
} else {
@@ -645,13 +638,12 @@ AST::SourceLocation QmlOutlineModel::sourceLocation(const QModelIndex &index) co
QTC_ASSERT(index.isValid() && (index.model() == this), return location);
AST::Node *node = nodeForIndex(index);
if (node) {
- if (AST::UiObjectMember *member = node->uiObjectMemberCast()) {
+ if (AST::UiObjectMember *member = node->uiObjectMemberCast())
location = getLocation(member);
- } else if (AST::ExpressionNode *expression = node->expressionCast()) {
+ else if (AST::ExpressionNode *expression = node->expressionCast())
location = getLocation(expression);
- } else if (AST::PropertyNameAndValueList *propertyNameAndValueList = AST::cast<AST::PropertyNameAndValueList *>(node)) {
+ else if (AST::PropertyNameAndValueList *propertyNameAndValueList = AST::cast<AST::PropertyNameAndValueList *>(node))
location = getLocation(propertyNameAndValueList);
- }
}
return location;
}
@@ -830,11 +822,10 @@ void QmlOutlineModel::moveObjectMember(AST::UiObjectMember *toMove,
}
Rewriter::BindingType bindingType = Rewriter::ScriptBinding;
- if (insertionOrderSpecified) {
+ if (insertionOrderSpecified)
*addedRange = rewriter.addBinding(objDefinition->initializer, propertyName, propertyValue, bindingType, listInsertAfter);
- } else {
+ else
*addedRange = rewriter.addBinding(objDefinition->initializer, propertyName, propertyValue, bindingType);
- }
} else {
QString strToMove;
{
@@ -843,11 +834,10 @@ void QmlOutlineModel::moveObjectMember(AST::UiObjectMember *toMove,
strToMove = documentText.mid(offset, length);
}
- if (insertionOrderSpecified) {
+ if (insertionOrderSpecified)
*addedRange = rewriter.addObject(objDefinition->initializer, strToMove, listInsertAfter);
- } else {
+ else
*addedRange = rewriter.addObject(objDefinition->initializer, strToMove);
- }
}
} else if (AST::UiArrayBinding *arrayBinding = AST::cast<AST::UiArrayBinding*>(newParent)) {
AST::UiArrayMemberList *listInsertAfter = 0;
@@ -865,11 +855,10 @@ void QmlOutlineModel::moveObjectMember(AST::UiObjectMember *toMove,
strToMove = documentText.mid(offset, length);
}
- if (insertionOrderSpecified) {
+ if (insertionOrderSpecified)
*addedRange = rewriter.addObject(arrayBinding, strToMove, listInsertAfter);
- } else {
+ else
*addedRange = rewriter.addObject(arrayBinding, strToMove);
- }
} else if (AST::cast<AST::UiObjectBinding*>(newParent)) {
qDebug() << "TODO: Reparent to UiObjectBinding";
return;
@@ -940,9 +929,9 @@ QIcon QmlOutlineModel::getIcon(AST::UiQualifiedId *qualifiedId) {
name = name.split(QLatin1Char('.')).last();
// TODO: get rid of namespace prefixes.
- icon = m_icons->icon("Qt", name);
+ icon = m_icons->icon(QLatin1String("Qt"), name);
if (icon.isNull())
- icon = m_icons->icon("QtWebkit", name);
+ icon = m_icons->icon(QLatin1String("QtWebkit"), name);
}
return icon;
}
@@ -950,14 +939,14 @@ QIcon QmlOutlineModel::getIcon(AST::UiQualifiedId *qualifiedId) {
QString QmlOutlineModel::getAnnotation(AST::UiObjectInitializer *objectInitializer) {
const QHash<QString,QString> bindings = getScriptBindings(objectInitializer);
- if (bindings.contains("id"))
- return bindings.value("id");
+ if (bindings.contains(QLatin1String("id")))
+ return bindings.value(QLatin1String("id"));
- if (bindings.contains("name"))
- return bindings.value("name");
+ if (bindings.contains(QLatin1String("name")))
+ return bindings.value(QLatin1String("name"));
- if (bindings.contains("target"))
- return bindings.value("target");
+ if (bindings.contains(QLatin1String("target")))
+ return bindings.value(QLatin1String("target"));
return QString();
}
diff --git a/src/plugins/qmljseditor/quicktoolbar.cpp b/src/plugins/qmljseditor/quicktoolbar.cpp
index 8a40105401..b3923574a4 100644
--- a/src/plugins/qmljseditor/quicktoolbar.cpp
+++ b/src/plugins/qmljseditor/quicktoolbar.cpp
@@ -28,10 +28,11 @@
****************************************************************************/
#include "quicktoolbar.h"
-#include <contextpanewidget.h>
-#include <quicktoolbarsettingspage.h>
+#include "quicktoolbarsettingspage.h"
#include <utils/changeset.h>
+#include <qmleditorwidgets/contextpanewidget.h>
+#include <qmleditorwidgets/customcolordialog.h>
#include <qmljs/parser/qmljsast_p.h>
#include <qmljs/qmljsdocument.h>
#include <qmljs/qmljspropertyreader.h>
@@ -45,7 +46,6 @@
#include <texteditor/basetexteditor.h>
#include <texteditor/tabsettings.h>
#include <coreplugin/icore.h>
-#include <customcolordialog.h>
#include <QDebug>
@@ -73,11 +73,10 @@ static inline const ObjectValue * getPropertyChangesTarget(Node *node, const Sco
&& ! scriptBinding->qualifiedId->next) {
Evaluate evaluator(&scopeChain);
const Value *targetValue = evaluator(scriptBinding->statement);
- if (const ObjectValue *targetObject = value_cast<ObjectValue>(targetValue)) {
+ if (const ObjectValue *targetObject = value_cast<ObjectValue>(targetValue))
return targetObject;
- } else {
+ else
return 0;
- }
}
}
}
@@ -122,7 +121,7 @@ QuickToolBar::~QuickToolBar()
//if the pane was never activated the widget is not in a widget tree
if (!m_widget.isNull())
delete m_widget.data();
- m_widget.clear();
+ m_widget = 0;
}
void QuickToolBar::apply(TextEditor::BaseTextEditor *editor, Document::Ptr document, const ScopeChain *scopeChain, AST::Node *node, bool update, bool force)
@@ -151,7 +150,7 @@ void QuickToolBar::apply(TextEditor::BaseTextEditor *editor, Document::Ptr docum
m_prototypes.append(object->className());
}
- if (m_prototypes.contains("PropertyChanges")) {
+ if (m_prototypes.contains(QLatin1String("PropertyChanges"))) {
isPropertyChanges = true;
const ObjectValue *targetObject = getPropertyChangesTarget(node, *scopeChain);
m_prototypes.clear();
@@ -213,13 +212,13 @@ void QuickToolBar::apply(TextEditor::BaseTextEditor *editor, Document::Ptr docum
rect.setHeight(widget()->height() + 10);
rect.setWidth(reg.boundingRect().width() - reg.boundingRect().left());
rect.moveTo(reg.boundingRect().topLeft());
- reg = reg.intersect(rect);
+ reg = reg.intersected(rect);
if (contextWidget()->acceptsType(m_prototypes)) {
m_node = 0;
PropertyReader propertyReader(document, initializer);
QTextCursor tc(editor->editorWidget()->document());
- tc.setPosition(offset);
+ tc.setPosition(offset);
QPoint p1 = editor->editorWidget()->mapToParent(editor->editorWidget()->viewport()->mapToParent(editor->editorWidget()->cursorRect(tc).topLeft()) - QPoint(0, contextWidget()->height() + 10));
tc.setPosition(end);
QPoint p2 = editor->editorWidget()->mapToParent(editor->editorWidget()->viewport()->mapToParent(editor->editorWidget()->cursorRect(tc).bottomLeft()) + QPoint(0, 10));
@@ -237,7 +236,7 @@ void QuickToolBar::apply(TextEditor::BaseTextEditor *editor, Document::Ptr docum
contextWidget()->rePosition(p3 , p1, p2, QuickToolBarSettings::get().pinContextPane);
contextWidget()->setOptions(QuickToolBarSettings::get().enableContextPane, QuickToolBarSettings::get().pinContextPane);
contextWidget()->setPath(document->path());
- contextWidget()->setProperties(&propertyReader);
+ contextWidget()->setProperties(&propertyReader);
m_doc = document;
m_node = node;
} else {
@@ -267,25 +266,24 @@ bool QuickToolBar::isAvailable(TextEditor::BaseTextEditor *, Document::Ptr docum
UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(node);
UiObjectBinding *objectBinding = cast<UiObjectBinding*>(node);
- if (objectDefinition) {
+ if (objectDefinition)
name = objectDefinition->qualifiedTypeNameId->name.toString();
- } else if (objectBinding) {
+ else if (objectBinding)
name = objectBinding->qualifiedTypeNameId->name.toString();
- }
QStringList prototypes;
prototypes.append(name);
- if (prototypes.contains("Rectangle") ||
- prototypes.contains("Image") ||
- prototypes.contains("BorderImage") ||
- prototypes.contains("TextEdit") ||
- prototypes.contains("TextInput") ||
- prototypes.contains("PropertyAnimation") ||
- prototypes.contains("NumberAnimation") ||
- prototypes.contains("Text") ||
- prototypes.contains("PropertyChanges"))
+ if (prototypes.contains(QLatin1String("Rectangle")) ||
+ prototypes.contains(QLatin1String("Image")) ||
+ prototypes.contains(QLatin1String("BorderImage")) ||
+ prototypes.contains(QLatin1String("TextEdit")) ||
+ prototypes.contains(QLatin1String("TextInput")) ||
+ prototypes.contains(QLatin1String("PropertyAnimation")) ||
+ prototypes.contains(QLatin1String("NumberAnimation")) ||
+ prototypes.contains(QLatin1String("Text")) ||
+ prototypes.contains(QLatin1String("PropertyChanges")))
return true;
return false;
@@ -296,7 +294,7 @@ void QuickToolBar::setProperty(const QString &propertyName, const QVariant &valu
QString stringValue = value.toString();
if (value.type() == QVariant::Color)
- stringValue = QChar('\"') + value.toString() + QChar('\"');
+ stringValue = QLatin1Char('\"') + value.toString() + QLatin1Char('\"');
if (cast<UiObjectDefinition*>(m_node) || cast<UiObjectBinding*>(m_node)) {
UiObjectDefinition *objectDefinition = cast<UiObjectDefinition*>(m_node);
@@ -316,15 +314,14 @@ void QuickToolBar::setProperty(const QString &propertyName, const QVariant &valu
Rewriter::BindingType bindingType = Rewriter::ScriptBinding;
- if (stringValue.contains("{") && stringValue.contains("}"))
+ if (stringValue.contains(QLatin1Char('{')) && stringValue.contains(QLatin1Char('}')))
bindingType = Rewriter::ObjectBinding;
PropertyReader propertyReader(m_doc, initializer);
- if (propertyReader.hasProperty(propertyName)) {
+ if (propertyReader.hasProperty(propertyName))
rewriter.changeBinding(initializer, propertyName, stringValue, bindingType);
- } else {
+ else
rewriter.addBinding(initializer, propertyName, stringValue, bindingType);
- }
int column;
diff --git a/src/plugins/qmljseditor/quicktoolbar.h b/src/plugins/qmljseditor/quicktoolbar.h
index 1a3a49efeb..b90ab78954 100644
--- a/src/plugins/qmljseditor/quicktoolbar.h
+++ b/src/plugins/qmljseditor/quicktoolbar.h
@@ -32,6 +32,8 @@
#include <qmljs/qmljsicontextpane.h>
+#include <QPointer>
+
namespace TextEditor {
class BaseTextEditor;
}
@@ -65,7 +67,7 @@ public slots:
private:
QmlEditorWidgets::ContextPaneWidget* contextWidget();
- QWeakPointer<QmlEditorWidgets::ContextPaneWidget> m_widget;
+ QPointer<QmlEditorWidgets::ContextPaneWidget> m_widget;
QmlJS::Document::Ptr m_doc;
QmlJS::AST::Node *m_node;
TextEditor::BaseTextEditor *m_editor;
diff --git a/src/plugins/qmljseditor/quicktoolbarsettingspage.cpp b/src/plugins/qmljseditor/quicktoolbarsettingspage.cpp
index 296c0d249a..59d0b858ea 100644
--- a/src/plugins/qmljseditor/quicktoolbarsettingspage.cpp
+++ b/src/plugins/qmljseditor/quicktoolbarsettingspage.cpp
@@ -121,9 +121,9 @@ QuickToolBarSettings QuickToolBarSettings::get()
QuickToolBarSettingsPage::QuickToolBarSettingsPage() :
m_widget(0)
{
- setId(QLatin1String("C.QmlToolbar"));
+ setId("C.QmlToolbar");
setDisplayName(tr("Qt Quick ToolBar"));
- setCategory(QLatin1String(Constants::SETTINGS_CATEGORY_QML));
+ setCategory(Constants::SETTINGS_CATEGORY_QML);
setDisplayCategory(QCoreApplication::translate("QmlJSEditor",
QmlJSEditor::Constants::SETTINGS_TR_CATEGORY_QML));
setCategoryIcon(QLatin1String(QmlDesigner::Constants::SETTINGS_CATEGORY_QML_ICON));
diff --git a/src/plugins/debugger/images/collapse.png b/src/plugins/qmljstools/images/collapse.png
index 64ae3720c1..64ae3720c1 100644
--- a/src/plugins/debugger/images/collapse.png
+++ b/src/plugins/qmljstools/images/collapse.png
Binary files differ
diff --git a/src/plugins/debugger/images/error.png b/src/plugins/qmljstools/images/error.png
index 39768b9f39..39768b9f39 100644
--- a/src/plugins/debugger/images/error.png
+++ b/src/plugins/qmljstools/images/error.png
Binary files differ
diff --git a/src/plugins/debugger/images/expand.png b/src/plugins/qmljstools/images/expand.png
index 7959bfc97e..7959bfc97e 100644
--- a/src/plugins/debugger/images/expand.png
+++ b/src/plugins/qmljstools/images/expand.png
Binary files differ
diff --git a/src/plugins/debugger/images/log.png b/src/plugins/qmljstools/images/log.png
index e4766f228b..e4766f228b 100644
--- a/src/plugins/debugger/images/log.png
+++ b/src/plugins/qmljstools/images/log.png
Binary files differ
diff --git a/src/plugins/debugger/images/prompt.png b/src/plugins/qmljstools/images/prompt.png
index a333a87198..a333a87198 100644
--- a/src/plugins/debugger/images/prompt.png
+++ b/src/plugins/qmljstools/images/prompt.png
Binary files differ
diff --git a/src/plugins/debugger/images/warning.png b/src/plugins/qmljstools/images/warning.png
index 3200efc4fd..3200efc4fd 100644
--- a/src/plugins/debugger/images/warning.png
+++ b/src/plugins/qmljstools/images/warning.png
Binary files differ
diff --git a/src/plugins/debugger/qtmessagelogeditor.cpp b/src/plugins/qmljstools/qmlconsoleedit.cpp
index e4590b6420..9793abc190 100644
--- a/src/plugins/debugger/qtmessagelogeditor.cpp
+++ b/src/plugins/qmljstools/qmlconsoleedit.cpp
@@ -27,11 +27,10 @@
**
****************************************************************************/
-#include "qtmessagelogeditor.h"
-#include "qtmessageloghandler.h"
-#include "debuggerstringutils.h"
-#include "debuggercore.h"
-#include "debuggerengine.h"
+#include "qmlconsoleedit.h"
+#include "qmlconsoleitemmodel.h"
+#include "qmlconsolemodel.h"
+#include "qmlconsolemanager.h"
#include <utils/qtcassert.h>
@@ -39,54 +38,58 @@
#include <QMenu>
#include <QKeyEvent>
-namespace Debugger {
+using namespace QmlJS;
+
+namespace QmlJSTools {
namespace Internal {
///////////////////////////////////////////////////////////////////////
//
-// QtMessageLogEditor
+// QmlConsoleEdit
//
///////////////////////////////////////////////////////////////////////
-QtMessageLogEditor::QtMessageLogEditor(const QModelIndex &index,
- QWidget *parent) :
+QmlConsoleEdit::QmlConsoleEdit(const QModelIndex &index, QWidget *parent) :
QTextEdit(parent),
m_historyIndex(index),
- m_prompt(_(":/debugger/images/prompt.png")),
+ m_prompt(QLatin1String(":/qmljstools/images/prompt.png")),
m_startOfEditableArea(0)
{
setFrameStyle(QFrame::NoFrame);
setUndoRedoEnabled(false);
setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
- document()->addResource(QTextDocument::ImageResource,
- QUrl(_("prompt")), m_prompt);
+ document()->addResource(QTextDocument::ImageResource, QUrl(QLatin1String("prompt")), m_prompt);
QTextImageFormat format;
- format.setName(_("prompt"));
+ format.setName(QLatin1String("prompt"));
format.setHeight(9);
format.setWidth(9);
- textCursor().insertText(_(" "));
+ textCursor().insertText(QLatin1String(" "));
textCursor().insertImage(format);
- textCursor().insertText(_(" "));
+ textCursor().insertText(QLatin1String(" "));
m_startOfEditableArea = textCursor().position();
ensureCursorVisible();
setTextInteractionFlags(Qt::TextEditorInteraction);
}
-void QtMessageLogEditor::keyPressEvent(QKeyEvent *e)
+void QmlConsoleEdit::keyPressEvent(QKeyEvent *e)
{
bool keyConsumed = false;
switch (e->key()) {
case Qt::Key_Return:
case Qt::Key_Enter: {
- keyConsumed = debuggerCore()->evaluateScriptExpression(getCurrentScript());
- if (keyConsumed) {
+ m_interpreter.clearText();
+ QString currentScript = getCurrentScript();
+ m_interpreter.appendText(currentScript);
+ if (currentScript.isEmpty()) {
+ emit editingFinished();
+ } else if (m_interpreter.canEvaluate()) {
+ QmlConsoleModel::evaluate(currentScript);
emit editingFinished();
- debuggerCore()->currentEngine()->qtMessageLogHandler()->appendEditableRow();
}
- }
break;
+ }
case Qt::Key_Backspace:
if (textCursor().selectionStart() <= m_startOfEditableArea)
@@ -98,14 +101,13 @@ void QtMessageLogEditor::keyPressEvent(QKeyEvent *e)
keyConsumed = true;
break;
- case Qt::Key_Home:
- {
+ case Qt::Key_Home: {
QTextCursor c(textCursor());
c.setPosition(m_startOfEditableArea);
setTextCursor(c);
keyConsumed = true;
- }
break;
+ }
case Qt::Key_Up:
handleUpKey();
@@ -160,10 +162,9 @@ void QtMessageLogEditor::keyPressEvent(QKeyEvent *e)
QTextEdit::keyPressEvent(e);
}
-void QtMessageLogEditor::contextMenuEvent(QContextMenuEvent *event)
+void QmlConsoleEdit::contextMenuEvent(QContextMenuEvent *event)
{
- //TODO:: on right click the editor closes
- //FIXIT
+ // TODO:: on right click the editor closes
return QTextEdit::contextMenuEvent(event);
QTextCursor cursor = textCursor();
@@ -192,12 +193,12 @@ void QtMessageLogEditor::contextMenuEvent(QContextMenuEvent *event)
delete menu;
}
-void QtMessageLogEditor::focusOutEvent(QFocusEvent * /*e*/)
+void QmlConsoleEdit::focusOutEvent(QFocusEvent * /*e*/)
{
emit editingFinished();
}
-void QtMessageLogEditor::handleUpKey()
+void QmlConsoleEdit::handleUpKey()
{
QTC_ASSERT(m_historyIndex.isValid(), return);
int currentRow = m_historyIndex.row();
@@ -209,19 +210,17 @@ void QtMessageLogEditor::handleUpKey()
currentRow--;
if (model->hasIndex(currentRow, 0)) {
QModelIndex index = model->index(currentRow, 0);
- if (QtMessageLogHandler::InputType == (QtMessageLogHandler::ItemType)model->data(
- index, QtMessageLogHandler::TypeRole).toInt()) {
+ if (ConsoleItem::InputType == (ConsoleItem::ItemType)model->data(
+ index, QmlConsoleItemModel::TypeRole).toInt()) {
m_historyIndex = index;
- replaceCurrentScript(model->data(
- index, Qt::DisplayRole).
- toString());
+ replaceCurrentScript(model->data(index, Qt::DisplayRole).toString());
break;
}
}
}
}
-void QtMessageLogEditor::handleDownKey()
+void QmlConsoleEdit::handleDownKey()
{
QTC_ASSERT(m_historyIndex.isValid(), return);
int currentRow = m_historyIndex.row();
@@ -230,32 +229,29 @@ void QtMessageLogEditor::handleDownKey()
currentRow++;
if (model->hasIndex(currentRow, 0)) {
QModelIndex index = model->index(currentRow, 0);
- if (QtMessageLogHandler::InputType == (QtMessageLogHandler::ItemType)model->data(
- index, QtMessageLogHandler::TypeRole).toInt()) {
+ if (ConsoleItem::InputType == (ConsoleItem::ItemType)model->data(
+ index, QmlConsoleItemModel::TypeRole).toInt()) {
m_historyIndex = index;
if (currentRow == model->rowCount() - 1)
replaceCurrentScript(m_cachedScript);
else
- replaceCurrentScript(model->data(
- index, Qt::DisplayRole).
- toString());
+ replaceCurrentScript(model->data(index, Qt::DisplayRole).toString());
break;
}
}
}
}
-QString QtMessageLogEditor::getCurrentScript() const
+QString QmlConsoleEdit::getCurrentScript() const
{
QTextCursor cursor = textCursor();
cursor.setPosition(m_startOfEditableArea);
cursor.movePosition(QTextCursor::End, QTextCursor::KeepAnchor);
QString script = cursor.selectedText();
- //remove WS
return script.trimmed();
}
-void QtMessageLogEditor::replaceCurrentScript(const QString &script)
+void QmlConsoleEdit::replaceCurrentScript(const QString &script)
{
QTextCursor cursor = textCursor();
cursor.setPosition(m_startOfEditableArea);
@@ -265,5 +261,5 @@ void QtMessageLogEditor::replaceCurrentScript(const QString &script)
setTextCursor(cursor);
}
-} //Internal
-} //Debugger
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/debugger/qtmessagelogeditor.h b/src/plugins/qmljstools/qmlconsoleedit.h
index bd6ec93942..0b0d8f2326 100644
--- a/src/plugins/debugger/qtmessagelogeditor.h
+++ b/src/plugins/qmljstools/qmlconsoleedit.h
@@ -27,21 +27,22 @@
**
****************************************************************************/
-#ifndef QTMESSAGELOGEDITOR_H
-#define QTMESSAGELOGEDITOR_H
+#ifndef QMLCONSOLEEDIT_H
+#define QMLCONSOLEEDIT_H
+
+#include "qmljsinterpreter.h"
-#include <QModelIndex>
#include <QTextEdit>
+#include <QModelIndex>
-namespace Debugger {
+namespace QmlJSTools {
namespace Internal {
-class QtMessageLogEditor : public QTextEdit
+class QmlConsoleEdit : public QTextEdit
{
Q_OBJECT
public:
- explicit QtMessageLogEditor(const QModelIndex &index,
- QWidget *parent = 0);
+ QmlConsoleEdit(const QModelIndex &index, QWidget *parent);
QString getCurrentScript() const;
@@ -64,9 +65,10 @@ private:
QString m_cachedScript;
QImage m_prompt;
int m_startOfEditableArea;
+ QmlJSInterpreter m_interpreter;
};
-} //Internal
-} //Debugger
+} // QmlJSTools
+} // Internal
-#endif // QTMESSAGELOGEDITOR_H
+#endif // QMLCONSOLEEDIT_H
diff --git a/src/plugins/debugger/qtmessagelogitemdelegate.cpp b/src/plugins/qmljstools/qmlconsoleitemdelegate.cpp
index 6e62d1824d..57435986df 100644
--- a/src/plugins/debugger/qtmessagelogitemdelegate.cpp
+++ b/src/plugins/qmljstools/qmlconsoleitemdelegate.cpp
@@ -27,8 +27,8 @@
**
****************************************************************************/
-#include "qtmessagelogitemdelegate.h"
-#include "qtmessagelogeditor.h"
+#include "qmlconsoleitemdelegate.h"
+#include "qmlconsoleedit.h"
#include <QPainter>
#include <QTreeView>
@@ -53,55 +53,56 @@ const char CONSOLE_BORDER_COLOR[] = "#C9C9C9";
const int ELLIPSIS_GRADIENT_WIDTH = 16;
-namespace Debugger {
+using namespace QmlJS;
+
+namespace QmlJSTools {
namespace Internal {
///////////////////////////////////////////////////////////////////////
//
-// QtMessageLogItemDelegate
+// QmlConsoleItemDelegate
//
///////////////////////////////////////////////////////////////////////
-QtMessageLogItemDelegate::QtMessageLogItemDelegate(QObject *parent) :
+QmlConsoleItemDelegate::QmlConsoleItemDelegate(QObject *parent) :
QStyledItemDelegate(parent),
- m_logIcon(QLatin1String(":/debugger/images/log.png")),
- m_warningIcon(QLatin1String(":/debugger/images/warning.png")),
- m_errorIcon(QLatin1String(":/debugger/images/error.png")),
- m_expandIcon(QLatin1String(":/debugger/images/expand.png")),
- m_collapseIcon(QLatin1String(":/debugger/images/collapse.png")),
- m_prompt(QLatin1String(":/debugger/images/prompt.png")),
- m_itemModel(0),
+ m_logIcon(QLatin1String(":/qmljstools/images/log.png")),
+ m_warningIcon(QLatin1String(":/qmljstools/images/warning.png")),
+ m_errorIcon(QLatin1String(":/qmljstools/images/error.png")),
+ m_expandIcon(QLatin1String(":/qmljstools/images/expand.png")),
+ m_collapseIcon(QLatin1String(":/qmljstools/images/collapse.png")),
+ m_prompt(QLatin1String(":/qmljstools/images/prompt.png")),
m_cachedHeight(0)
{
}
-void QtMessageLogItemDelegate::emitSizeHintChanged(const QModelIndex &index)
+void QmlConsoleItemDelegate::emitSizeHintChanged(const QModelIndex &index)
{
emit sizeHintChanged(index);
}
-QColor QtMessageLogItemDelegate::drawBackground(QPainter *painter, const QRect &rect,
- const QModelIndex &index,
- bool selected) const
+QColor QmlConsoleItemDelegate::drawBackground(QPainter *painter, const QRect &rect,
+ const QModelIndex &index,
+ bool selected) const
{
painter->save();
- QtMessageLogHandler::ItemType itemType = (QtMessageLogHandler::ItemType)index.data(
- QtMessageLogHandler::TypeRole).toInt();
+ ConsoleItem::ItemType itemType = (ConsoleItem::ItemType)index.data(
+ QmlConsoleItemModel::TypeRole).toInt();
QColor backgroundColor;
switch (itemType) {
- case QtMessageLogHandler::DebugType:
+ case ConsoleItem::DebugType:
backgroundColor = selected ? QColor(CONSOLE_LOG_BACKGROUND_SELECTED_COLOR) :
QColor(CONSOLE_LOG_BACKGROUND_COLOR);
break;
- case QtMessageLogHandler::WarningType:
+ case ConsoleItem::WarningType:
backgroundColor = selected ? QColor(CONSOLE_WARNING_BACKGROUND_SELECTED_COLOR) :
QColor(CONSOLE_WARNING_BACKGROUND_COLOR);
break;
- case QtMessageLogHandler::ErrorType:
+ case ConsoleItem::ErrorType:
backgroundColor = selected ? QColor(CONSOLE_ERROR_BACKGROUND_SELECTED_COLOR) :
QColor(CONSOLE_ERROR_BACKGROUND_COLOR);
break;
- case QtMessageLogHandler::InputType:
+ case ConsoleItem::InputType:
default:
backgroundColor = selected ? QColor(CONSOLE_EDITOR_BACKGROUND_SELECTED_COLOR) :
QColor(CONSOLE_EDITOR_BACKGROUND_COLOR);
@@ -116,37 +117,37 @@ QColor QtMessageLogItemDelegate::drawBackground(QPainter *painter, const QRect &
painter->setPen(QColor(CONSOLE_BORDER_COLOR));
if (!(index.flags() & Qt::ItemIsEditable))
painter->drawLine(0, rect.bottom(), rect.right(),
- rect.bottom());
+ rect.bottom());
painter->restore();
return backgroundColor;
}
-void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
- const QModelIndex &index) const
+void QmlConsoleItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
+ const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt, index);
painter->save();
- //Set Colors
+ // Set Colors
QColor textColor;
QIcon taskIcon;
- QtMessageLogHandler::ItemType type = (QtMessageLogHandler::ItemType)index.data(
- QtMessageLogHandler::TypeRole).toInt();
+ ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data(
+ QmlConsoleItemModel::TypeRole).toInt();
switch (type) {
- case QtMessageLogHandler::DebugType:
+ case ConsoleItem::DebugType:
textColor = QColor(CONSOLE_LOG_TEXT_COLOR);
taskIcon = m_logIcon;
break;
- case QtMessageLogHandler::WarningType:
+ case ConsoleItem::WarningType:
textColor = QColor(CONSOLE_WARNING_TEXT_COLOR);
taskIcon = m_warningIcon;
break;
- case QtMessageLogHandler::ErrorType:
+ case ConsoleItem::ErrorType:
textColor = QColor(CONSOLE_ERROR_TEXT_COLOR);
taskIcon = m_errorIcon;
break;
- case QtMessageLogHandler::InputType:
+ case ConsoleItem::InputType:
textColor = QColor(CONSOLE_EDITOR_TEXT_COLOR);
taskIcon = m_prompt;
break;
@@ -155,11 +156,11 @@ void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt
break;
}
- //Paint background
+ // Paint background
QColor backgroundColor = drawBackground(painter, opt.rect, index,
- bool(opt.state & QStyle::State_Selected));
+ bool(opt.state & QStyle::State_Selected));
- //Calculate positions
+ // Calculate positions
const QTreeView *view = qobject_cast<const QTreeView *>(opt.widget);
int level = 0;
QModelIndex idx(index);
@@ -167,14 +168,12 @@ void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt
idx = idx.parent();
level++;
}
- int width = view->width() - level * view->indentation() -
- view->verticalScrollBar()->width();
+ int width = view->width() - level * view->indentation() - view->verticalScrollBar()->width();
bool showTypeIcon = index.parent() == QModelIndex();
- bool showExpandableIcon = type == QtMessageLogHandler::UndefinedType;
+ bool showExpandableIcon = type == ConsoleItem::UndefinedType;
QRect rect(opt.rect.x(), opt.rect.top(), width, opt.rect.height());
- ConsoleItemPositions positions(rect, opt.font, showTypeIcon,
- showExpandableIcon, m_itemModel);
+ ConsoleItemPositions positions(rect, opt.font, showTypeIcon, showExpandableIcon);
// Paint TaskIconArea:
if (showTypeIcon)
@@ -195,11 +194,10 @@ void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt
tl.draw(painter, QPoint(positions.textAreaLeft(), positions.adjustedTop()));
} else {
QFontMetrics fm(opt.font);
- painter->drawText(positions.textArea(),
- fm.elidedText(str, Qt::ElideRight,
- positions.textAreaWidth()));
+ painter->drawText(positions.textArea(), fm.elidedText(str, Qt::ElideRight,
+ positions.textAreaWidth()));
}
- //skip if area is editable
+ // skip if area is editable
if (showExpandableIcon) {
// Paint ExpandableIconArea:
QIcon expandCollapseIcon;
@@ -209,16 +207,14 @@ void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt
else
expandCollapseIcon = m_expandIcon;
}
- painter->drawPixmap(positions.expandCollapseIconLeft(),
- positions.adjustedTop(),
- expandCollapseIcon.pixmap(
- positions.expandCollapseIconWidth(),
- positions.expandCollapseIconHeight()));
+ painter->drawPixmap(positions.expandCollapseIconLeft(), positions.adjustedTop(),
+ expandCollapseIcon.pixmap(positions.expandCollapseIconWidth(),
+ positions.expandCollapseIconHeight()));
}
if (showFileLineInfo) {
- //Check for file info
- QString file = index.data(QtMessageLogHandler::FileRole).toString();
+ // Check for file info
+ QString file = index.data(QmlConsoleItemModel::FileRole).toString();
if (!file.isEmpty()) {
QFontMetrics fm(option.font);
// Paint FileArea
@@ -227,22 +223,20 @@ void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt
file = file.mid(pos +1);
const int realFileWidth = fm.width(file);
painter->setClipRect(positions.fileArea());
- painter->drawText(positions.fileAreaLeft(),
- positions.adjustedTop() + fm.ascent(), file);
+ painter->drawText(positions.fileAreaLeft(), positions.adjustedTop() + fm.ascent(),
+ file);
if (realFileWidth > positions.fileAreaWidth()) {
// draw a gradient to mask the text
int gradientStart = positions.fileAreaLeft() - 1;
- QLinearGradient lg(gradientStart +
- ELLIPSIS_GRADIENT_WIDTH, 0, gradientStart, 0);
+ QLinearGradient lg(gradientStart + ELLIPSIS_GRADIENT_WIDTH, 0, gradientStart, 0);
lg.setColorAt(0, Qt::transparent);
lg.setColorAt(1, backgroundColor);
painter->fillRect(gradientStart, positions.adjustedTop(),
- ELLIPSIS_GRADIENT_WIDTH, positions.lineHeight(),
- lg);
+ ELLIPSIS_GRADIENT_WIDTH, positions.lineHeight(), lg);
}
// Paint LineArea
- QString lineText = index.data(QtMessageLogHandler::LineRole).toString();
+ QString lineText = index.data(QmlConsoleItemModel::LineRole).toString();
painter->setClipRect(positions.lineArea());
const int realLineWidth = fm.width(lineText);
painter->drawText(positions.lineAreaRight() - realLineWidth,
@@ -253,8 +247,8 @@ void QtMessageLogItemDelegate::paint(QPainter *painter, const QStyleOptionViewIt
painter->restore();
}
-QSize QtMessageLogItemDelegate::sizeHint(const QStyleOptionViewItem &option,
- const QModelIndex &index) const
+QSize QmlConsoleItemDelegate::sizeHint(const QStyleOptionViewItem &option,
+ const QModelIndex &index) const
{
QStyleOptionViewItemV4 opt = option;
initStyleOption(&opt, index);
@@ -266,8 +260,7 @@ QSize QtMessageLogItemDelegate::sizeHint(const QStyleOptionViewItem &option,
idx = idx.parent();
level++;
}
- int width = view->width() - level * view->indentation() -
- view->verticalScrollBar()->width();
+ int width = view->width() - level * view->indentation() - view->verticalScrollBar()->width();
if (index.flags() & Qt::ItemIsEditable)
return QSize(width, view->height() * 1/2);
@@ -275,14 +268,13 @@ QSize QtMessageLogItemDelegate::sizeHint(const QStyleOptionViewItem &option,
if (!selected && option.font == m_cachedFont && m_cachedHeight > 0)
return QSize(width, m_cachedHeight);
- QtMessageLogHandler::ItemType type = (QtMessageLogHandler::ItemType)index.data(
- QtMessageLogHandler::TypeRole).toInt();
+ ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data(
+ QmlConsoleItemModel::TypeRole).toInt();
bool showTypeIcon = index.parent() == QModelIndex();
- bool showExpandableIcon = type == QtMessageLogHandler::UndefinedType;
+ bool showExpandableIcon = type == ConsoleItem::UndefinedType;
QRect rect(level * view->indentation(), 0, width, 0);
- ConsoleItemPositions positions(rect, opt.font,
- showTypeIcon, showExpandableIcon, m_itemModel);
+ ConsoleItemPositions positions(rect, opt.font, showTypeIcon, showExpandableIcon);
QFontMetrics fm(option.font);
qreal height = fm.height();
@@ -307,58 +299,56 @@ QSize QtMessageLogItemDelegate::sizeHint(const QStyleOptionViewItem &option,
return QSize(width, height);
}
-QWidget *QtMessageLogItemDelegate::createEditor(QWidget *parent,
- const QStyleOptionViewItem &/*option*/,
- const QModelIndex &index) const
+QWidget *QmlConsoleItemDelegate::createEditor(QWidget *parent,
+ const QStyleOptionViewItem &/*option*/,
+ const QModelIndex &index) const
{
- QtMessageLogEditor *editor = new QtMessageLogEditor(index, parent);
- connect(editor, SIGNAL(editingFinished()),
- this, SLOT(commitAndCloseEditor()));
+ QmlConsoleEdit *editor = new QmlConsoleEdit(index, parent);
+ connect(editor, SIGNAL(editingFinished()), this, SLOT(commitAndCloseEditor()));
return editor;
}
-void QtMessageLogItemDelegate::setEditorData(QWidget *editor,
- const QModelIndex &index) const
+void QmlConsoleItemDelegate::setEditorData(QWidget *editor,
+ const QModelIndex &index) const
{
- QtMessageLogEditor *edtr = qobject_cast<QtMessageLogEditor *>(editor);
+ QmlConsoleEdit *edtr = qobject_cast<QmlConsoleEdit *>(editor);
edtr->insertPlainText(index.data(Qt::DisplayRole).toString());
}
-void QtMessageLogItemDelegate::setModelData(QWidget *editor,
- QAbstractItemModel *model,
- const QModelIndex &index) const
+void QmlConsoleItemDelegate::setModelData(QWidget *editor,
+ QAbstractItemModel *model,
+ const QModelIndex &index) const
{
- QtMessageLogEditor *edtr = qobject_cast<QtMessageLogEditor *>(editor);
+ QmlConsoleEdit *edtr = qobject_cast<QmlConsoleEdit *>(editor);
model->setData(index, edtr->getCurrentScript(), Qt::DisplayRole);
- model->setData(index, QtMessageLogHandler::InputType, QtMessageLogHandler::TypeRole);
+ model->setData(index, ConsoleItem::InputType, QmlConsoleItemModel::TypeRole);
}
-void QtMessageLogItemDelegate::updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
- const QModelIndex &/*index*/) const
+void QmlConsoleItemDelegate::updateEditorGeometry(QWidget *editor,
+ const QStyleOptionViewItem &option,
+ const QModelIndex &/*index*/) const
{
QStyleOptionViewItemV4 opt = option;
- editor->setGeometry(QRect(opt.rect.x(), opt.rect.top(),
- opt.rect.width(), opt.rect.bottom()));
+ editor->setGeometry(QRect(opt.rect.x(), opt.rect.top(), opt.rect.width(), opt.rect.bottom()));
}
-void QtMessageLogItemDelegate::currentChanged(const QModelIndex &current,
- const QModelIndex &previous)
+void QmlConsoleItemDelegate::currentChanged(const QModelIndex &current,
+ const QModelIndex &previous)
{
emit sizeHintChanged(current);
emit sizeHintChanged(previous);
}
-void QtMessageLogItemDelegate::commitAndCloseEditor()
+void QmlConsoleItemDelegate::commitAndCloseEditor()
{
- QtMessageLogEditor *editor = qobject_cast<QtMessageLogEditor *>(sender());
+ QmlConsoleEdit *editor = qobject_cast<QmlConsoleEdit *>(sender());
emit commitData(editor);
emit closeEditor(editor);
}
-qreal QtMessageLogItemDelegate::layoutText(QTextLayout &tl, int width,
- bool *showFileLineInfo) const
+qreal QmlConsoleItemDelegate::layoutText(QTextLayout &tl, int width,
+ bool *showFileLineInfo) const
{
qreal height = 0;
tl.beginLayout();
@@ -378,10 +368,5 @@ qreal QtMessageLogItemDelegate::layoutText(QTextLayout &tl, int width,
return height;
}
-void QtMessageLogItemDelegate::setItemModel(QtMessageLogHandler *model)
-{
- m_itemModel = model;
-}
-
-} //Internal
-} //Debugger
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/debugger/qtmessagelogitemdelegate.h b/src/plugins/qmljstools/qmlconsoleitemdelegate.h
index 1c370de230..d4e2dd9857 100644
--- a/src/plugins/debugger/qtmessagelogitemdelegate.h
+++ b/src/plugins/qmljstools/qmlconsoleitemdelegate.h
@@ -27,28 +27,28 @@
**
****************************************************************************/
-#ifndef QTMESSAGELOGITEMDELEGATE_H
-#define QTMESSAGELOGITEMDELEGATE_H
+#ifndef QMLCONSOLEITEMDELEGATE_H
+#define QMLCONSOLEITEMDELEGATE_H
-#include "qtmessageloghandler.h"
+#include "qmlconsoleitemmodel.h"
+#include "qmlconsolemodel.h"
+#include "qmlconsolemanager.h"
-#include <QTextLayout>
#include <QStyledItemDelegate>
+#include <QTextLayout>
-namespace Debugger {
+namespace QmlJSTools {
namespace Internal {
-class QtMessageLogItemDelegate : public QStyledItemDelegate
+class QmlConsoleItemDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
- explicit QtMessageLogItemDelegate(QObject *parent = 0);
- void emitSizeHintChanged(const QModelIndex &index);
- QColor drawBackground(QPainter *painter, const QRect &rect,
- const QModelIndex &index,
- bool selected) const;
+ QmlConsoleItemDelegate(QObject *parent);
- void setItemModel(QtMessageLogHandler *model);
+ void emitSizeHintChanged(const QModelIndex &index);
+ QColor drawBackground(QPainter *painter, const QRect &rect, const QModelIndex &index,
+ bool selected) const;
public slots:
void currentChanged(const QModelIndex &current, const QModelIndex &previous);
@@ -61,11 +61,9 @@ protected:
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
void setEditorData(QWidget *editor, const QModelIndex &index) const;
- void setModelData(QWidget *editor, QAbstractItemModel *model,
- const QModelIndex &index) const;
+ void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const;
- void updateEditorGeometry(QWidget *editor,
- const QStyleOptionViewItem &option,
+ void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
const QModelIndex &index) const;
private slots:
@@ -81,7 +79,6 @@ private:
const QIcon m_expandIcon;
const QIcon m_collapseIcon;
const QIcon m_prompt;
- QtMessageLogHandler *m_itemModel;
mutable int m_cachedHeight;
mutable QFont m_cachedFont;
};
@@ -101,11 +98,8 @@ private:
class ConsoleItemPositions
{
public:
- ConsoleItemPositions(const QRect &rect,
- const QFont &font,
- bool showTaskIconArea,
- bool showExpandableIconArea,
- QtMessageLogHandler *model = 0)
+ ConsoleItemPositions(const QRect &rect, const QFont &font, bool showTaskIconArea,
+ bool showExpandableIconArea)
: m_x(rect.x()),
m_width(rect.width()),
m_top(rect.top()),
@@ -116,10 +110,9 @@ public:
m_showExpandableIconArea(showExpandableIconArea)
{
m_fontHeight = QFontMetrics(font).height();
- if (model) {
- m_maxFileLength = model->sizeOfFile(font);
- m_maxLineLength = model->sizeOfLineNumber(font);
- }
+ QmlConsoleItemModel *model = QmlConsoleModel::qmlConsoleItemModel();
+ m_maxFileLength = model->sizeOfFile(font);
+ m_maxLineLength = model->sizeOfLineNumber(font);
}
int adjustedTop() const { return m_top + ITEM_PADDING; }
@@ -129,44 +122,41 @@ public:
int lineHeight() const { return m_fontHeight + 1; }
int minimumHeight() const { return typeIconHeight() + 2 * ITEM_PADDING; }
- //PROMPTAREA is same as TYPEICONAREA
+ // PROMPTAREA is same as TYPEICONAREA
int typeIconLeft() const { return adjustedLeft(); }
int typeIconWidth() const { return TASK_ICON_SIZE; }
int typeIconHeight() const { return TASK_ICON_SIZE; }
- int typeIconRight() const { return m_showTaskIconArea ?
- typeIconLeft() + typeIconWidth() : adjustedLeft(); }
- QRect typeIcon() const { return
- QRect(typeIconLeft(), adjustedTop(),
- typeIconWidth(), typeIconHeight()); }
-
- int expandCollapseIconLeft() const { return typeIconRight() +
- ITEM_SPACING; }
+ int typeIconRight() const { return m_showTaskIconArea ? typeIconLeft() + typeIconWidth()
+ : adjustedLeft(); }
+ QRect typeIcon() const { return QRect(typeIconLeft(), adjustedTop(), typeIconWidth(),
+ typeIconHeight()); }
+
+ int expandCollapseIconLeft() const { return typeIconRight() + ITEM_SPACING; }
int expandCollapseIconWidth() const { return TASK_ICON_SIZE; }
int expandCollapseIconHeight() const { return TASK_ICON_SIZE; }
int expandCollapseIconRight() const { return m_showExpandableIconArea ?
- expandCollapseIconLeft() + expandCollapseIconWidth() :
- typeIconRight(); }
- QRect expandCollapseIcon() const { return
- QRect(expandCollapseIconLeft(), adjustedTop(),
- expandCollapseIconWidth(), expandCollapseIconHeight()); }
+ expandCollapseIconLeft() + expandCollapseIconWidth() : typeIconRight(); }
+ QRect expandCollapseIcon() const { return QRect(expandCollapseIconLeft(), adjustedTop(),
+ expandCollapseIconWidth(),
+ expandCollapseIconHeight()); }
int textAreaLeft() const { return expandCollapseIconRight() + ITEM_SPACING; }
int textAreaWidth() const { return textAreaRight() - textAreaLeft(); }
int textAreaRight() const { return fileAreaLeft() - ITEM_SPACING; }
- QRect textArea() const { return
- QRect(textAreaLeft(), adjustedTop(), textAreaWidth(), lineHeight()); }
+ QRect textArea() const { return QRect(textAreaLeft(), adjustedTop(), textAreaWidth(),
+ lineHeight()); }
int fileAreaLeft() const { return fileAreaRight() - fileAreaWidth(); }
int fileAreaWidth() const { return m_maxFileLength; }
int fileAreaRight() const { return lineAreaLeft() - ITEM_SPACING; }
- QRect fileArea() const { return
- QRect(fileAreaLeft(), adjustedTop(), fileAreaWidth(), lineHeight()); }
+ QRect fileArea() const { return QRect(fileAreaLeft(), adjustedTop(), fileAreaWidth(),
+ lineHeight()); }
int lineAreaLeft() const { return lineAreaRight() - lineAreaWidth(); }
int lineAreaWidth() const { return m_maxLineLength; }
int lineAreaRight() const { return adjustedRight() - ITEM_SPACING; }
- QRect lineArea() const { return
- QRect(lineAreaLeft(), adjustedTop(), lineAreaWidth(), lineHeight()); }
+ QRect lineArea() const { return QRect(lineAreaLeft(), adjustedTop(), lineAreaWidth(),
+ lineHeight()); }
private:
int m_x;
@@ -185,7 +175,8 @@ public:
static const int ITEM_SPACING = 4;
};
-} //Internal
-} //Debugger
-#endif // QTMESSAGELOGITEMDELEGATE_H
+} // namespace Internal
+} // namespace QmlJSTools
+
+#endif // QMLCONSOLEITEMDELEGATE_H
diff --git a/src/plugins/qmljstools/qmlconsoleitemmodel.cpp b/src/plugins/qmljstools/qmlconsoleitemmodel.cpp
new file mode 100644
index 0000000000..aa8b07737d
--- /dev/null
+++ b/src/plugins/qmljstools/qmlconsoleitemmodel.cpp
@@ -0,0 +1,282 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlconsoleitemmodel.h"
+
+#include <utils/qtcassert.h>
+
+#include <QFontMetrics>
+
+using namespace QmlJS;
+
+namespace QmlJSTools {
+namespace Internal {
+
+///////////////////////////////////////////////////////////////////////
+//
+// QmlConsoleItemModel
+//
+///////////////////////////////////////////////////////////////////////
+
+QmlConsoleItemModel::QmlConsoleItemModel(QObject *parent) :
+ QAbstractItemModel(parent),
+ m_hasEditableRow(false),
+ m_rootItem(new ConsoleItem(0)),
+ m_maxSizeOfFileName(0)
+{
+}
+
+QmlConsoleItemModel::~QmlConsoleItemModel()
+{
+ delete m_rootItem;
+}
+
+void QmlConsoleItemModel::clear()
+{
+ beginResetModel();
+ delete m_rootItem;
+ m_rootItem = new ConsoleItem(0);
+ endResetModel();
+
+ if (m_hasEditableRow)
+ appendEditableRow();
+}
+
+bool QmlConsoleItemModel::appendItem(ConsoleItem *item, int position)
+{
+ if (position < 0)
+ position = m_rootItem->childCount() - 1;
+
+ if (position < 0)
+ position = 0;
+
+ beginInsertRows(QModelIndex(), position, position);
+ bool success = m_rootItem->insertChild(position, item);
+ endInsertRows();
+
+ return success;
+}
+
+bool QmlConsoleItemModel::appendMessage(ConsoleItem::ItemType itemType,
+ const QString &message, int position)
+{
+ return appendItem(new ConsoleItem(m_rootItem, itemType, message), position);
+}
+
+void QmlConsoleItemModel::setHasEditableRow(bool hasEditableRow)
+{
+ if (m_hasEditableRow && !hasEditableRow)
+ removeEditableRow();
+
+ if (!m_hasEditableRow && hasEditableRow)
+ appendEditableRow();
+
+ m_hasEditableRow = hasEditableRow;
+}
+
+bool QmlConsoleItemModel::hasEditableRow() const
+{
+ return m_hasEditableRow;
+}
+
+void QmlConsoleItemModel::appendEditableRow()
+{
+ int position = m_rootItem->childCount();
+ if (appendItem(new ConsoleItem(m_rootItem, ConsoleItem::InputType), position))
+ emit selectEditableRow(index(position, 0), QItemSelectionModel::ClearAndSelect);
+}
+
+void QmlConsoleItemModel::removeEditableRow()
+{
+ if (m_rootItem->child(m_rootItem->childCount() - 1)->itemType == ConsoleItem::InputType)
+ removeRow(m_rootItem->childCount() - 1);
+}
+
+int QmlConsoleItemModel::sizeOfFile(const QFont &font)
+{
+ int lastReadOnlyRow = m_rootItem->childCount();
+ if (m_hasEditableRow)
+ lastReadOnlyRow -= 2;
+ else
+ lastReadOnlyRow -= 1;
+ if (lastReadOnlyRow < 0)
+ return 0;
+ QString filename = m_rootItem->child(lastReadOnlyRow)->file;
+ const int pos = filename.lastIndexOf(QLatin1Char('/'));
+ if (pos != -1)
+ filename = filename.mid(pos + 1);
+
+ QFontMetrics fm(font);
+ m_maxSizeOfFileName = qMax(m_maxSizeOfFileName, fm.width(filename));
+
+ return m_maxSizeOfFileName;
+}
+
+int QmlConsoleItemModel::sizeOfLineNumber(const QFont &font)
+{
+ QFontMetrics fm(font);
+ return fm.width(QLatin1String("88888"));
+}
+
+QVariant QmlConsoleItemModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid())
+ return QVariant();
+
+ ConsoleItem *item = getItem(index);
+
+ if (role == Qt::DisplayRole )
+ return item->text();
+ else if (role == QmlConsoleItemModel::TypeRole)
+ return int(item->itemType);
+ else if (role == QmlConsoleItemModel::FileRole)
+ return item->file;
+ else if (role == QmlConsoleItemModel::LineRole)
+ return item->line;
+ else
+ return QVariant();
+}
+
+QModelIndex QmlConsoleItemModel::index(int row, int column, const QModelIndex &parent) const
+{
+ if (parent.isValid() && parent.column() != 0)
+ return QModelIndex();
+
+ if (column > 0)
+ return QModelIndex();
+
+ ConsoleItem *parentItem = getItem(parent);
+
+ ConsoleItem *childItem = parentItem->child(row);
+ if (childItem)
+ return createIndex(row, column, childItem);
+ else
+ return QModelIndex();
+}
+
+QModelIndex QmlConsoleItemModel::parent(const QModelIndex &index) const
+{
+ if (!index.isValid())
+ return QModelIndex();
+
+ ConsoleItem *childItem = getItem(index);
+ ConsoleItem *parentItem = childItem->parent();
+
+ if (parentItem == m_rootItem)
+ return QModelIndex();
+
+ if (!parentItem)
+ return QModelIndex();
+ return createIndex(parentItem->childNumber(), 0, parentItem);
+}
+
+int QmlConsoleItemModel::rowCount(const QModelIndex &parent) const
+{
+ ConsoleItem *parentItem = getItem(parent);
+
+ return parentItem->childCount();
+}
+
+int QmlConsoleItemModel::columnCount(const QModelIndex & /* parent */) const
+{
+ return 1;
+}
+
+Qt::ItemFlags QmlConsoleItemModel::flags(const QModelIndex &index) const
+{
+ if (!index.isValid())
+ return 0;
+
+ ConsoleItem *item = getItem(index);
+ if (m_hasEditableRow && item->parent() == m_rootItem
+ && index.row() == m_rootItem->childCount() - 1)
+ return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
+ return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
+}
+
+bool QmlConsoleItemModel::setData(const QModelIndex &index, const QVariant &value, int role)
+{
+ ConsoleItem *item = getItem(index);
+ bool result = false;
+ if (role == Qt::DisplayRole) {
+ item->setText(value.toString());
+ result = true;
+ } else if (role == QmlConsoleItemModel::TypeRole) {
+ item->itemType = (ConsoleItem::ItemType)value.toInt();
+ result = true;
+ } else if (role == QmlConsoleItemModel::FileRole) {
+ item->file = value.toString();
+ result = true;
+ } else if (role == QmlConsoleItemModel::LineRole) {
+ item->line = value.toInt();
+ result = true;
+ }
+
+ if (result)
+ emit dataChanged(index, index);
+
+ return result;
+}
+
+bool QmlConsoleItemModel::insertRows(int position, int rows, const QModelIndex &parent)
+{
+ ConsoleItem *parentItem = getItem(parent);
+ bool success;
+
+ beginInsertRows(parent, position, position + rows - 1);
+ success = parentItem->insertChildren(position, rows);
+ endInsertRows();
+
+ return success;
+}
+
+bool QmlConsoleItemModel::removeRows(int position, int rows, const QModelIndex &parent)
+{
+ ConsoleItem *parentItem = getItem(parent);
+ bool success = true;
+
+ beginRemoveRows(parent, position, position + rows - 1);
+ success = parentItem->removeChildren(position, rows);
+ endRemoveRows();
+
+ return success;
+}
+
+ConsoleItem *QmlConsoleItemModel::getItem(const QModelIndex &index) const
+{
+ if (index.isValid()) {
+ ConsoleItem *item = static_cast<ConsoleItem*>(index.internalPointer());
+ if (item)
+ return item;
+ }
+ return m_rootItem;
+}
+
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/debugger/qtmessageloghandler.h b/src/plugins/qmljstools/qmlconsoleitemmodel.h
index c1db571269..5cc4f6787f 100644
--- a/src/plugins/debugger/qtmessageloghandler.h
+++ b/src/plugins/qmljstools/qmlconsoleitemmodel.h
@@ -1,4 +1,4 @@
-/****************************************************************************
+/**************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
@@ -27,46 +27,35 @@
**
****************************************************************************/
-#ifndef QTMESSAGELOGHANDLER_H
-#define QTMESSAGELOGHANDLER_H
+#ifndef QMLCONSOLEITEMMODEL_H
+#define QMLCONSOLEITEMMODEL_H
+
+#include <qmljs/consoleitem.h>
#include <QAbstractItemModel>
#include <QItemSelectionModel>
#include <QFont>
-namespace Debugger {
+namespace QmlJSTools {
namespace Internal {
-class QtMessageLogItem;
-class QtMessageLogHandler : public QAbstractItemModel
+class QmlConsoleItemModel : public QAbstractItemModel
{
Q_OBJECT
-
public:
- enum ItemType
- {
- InputType = 0x01,
- DebugType = 0x02,
- WarningType = 0x04,
- ErrorType = 0x08,
- UndefinedType = 0x10, //Can be used for unknown and for Return values
- DefaultTypes = InputType | UndefinedType
- };
- Q_DECLARE_FLAGS(ItemTypes, ItemType)
-
enum Roles { TypeRole = Qt::UserRole, FileRole, LineRole };
- explicit QtMessageLogHandler(QObject *parent = 0);
- ~QtMessageLogHandler();
+ explicit QmlConsoleItemModel(QObject *parent = 0);
+ ~QmlConsoleItemModel();
void setHasEditableRow(bool hasEditableRow);
bool hasEditableRow() const;
void appendEditableRow();
void removeEditableRow();
- bool appendItem(QtMessageLogItem *item, int position = -1);
- bool appendMessage(QtMessageLogHandler::ItemType itemType,
- const QString &message, int position = -1);
+ bool appendItem(QmlJS::ConsoleItem *item, int position = -1);
+ bool appendMessage(QmlJS::ConsoleItem::ItemType itemType, const QString &message,
+ int position = -1);
QAbstractItemModel *model() { return this; }
@@ -75,75 +64,39 @@ public:
int sizeOfFile(const QFont &font);
int sizeOfLineNumber(const QFont &font);
- QtMessageLogItem *root() const { return m_rootItem; }
+ QmlJS::ConsoleItem *root() const { return m_rootItem; }
public slots:
void clear();
signals:
- void selectEditableRow(const QModelIndex &index,
- QItemSelectionModel::SelectionFlags flags);
+ void selectEditableRow(const QModelIndex &index, QItemSelectionModel::SelectionFlags flags);
void rowInserted(const QModelIndex &index);
protected:
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- QModelIndex index(int row, int column,
- const QModelIndex &parent = QModelIndex()) const;
+ QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const;
QModelIndex parent(const QModelIndex &index) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
- bool setData(const QModelIndex &index, const QVariant &value,
- int role = Qt::EditRole);
+ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
- bool insertRows(int position, int rows,
- const QModelIndex &parent = QModelIndex());
- bool removeRows(int position, int rows,
- const QModelIndex &parent = QModelIndex());
+ bool insertRows(int position, int rows, const QModelIndex &parent = QModelIndex());
+ bool removeRows(int position, int rows, const QModelIndex &parent = QModelIndex());
- QtMessageLogItem *getItem(const QModelIndex &index) const;
+ QmlJS::ConsoleItem *getItem(const QModelIndex &index) const;
private:
bool m_hasEditableRow;
- QtMessageLogItem *m_rootItem;
+ QmlJS::ConsoleItem *m_rootItem;
int m_maxSizeOfFileName;
};
-class QtMessageLogItem
-{
-public:
- QtMessageLogItem(QtMessageLogItem *parent,
- QtMessageLogHandler::ItemType type = QtMessageLogHandler::UndefinedType,
- const QString &data = QString());
- ~QtMessageLogItem();
-
- QtMessageLogItem *child(int number);
- int childCount() const;
- bool insertChildren(int position, int count);
- void insertChild(QtMessageLogItem *item);
- bool insertChild(int position, QtMessageLogItem *item);
- QtMessageLogItem *parent();
- bool removeChildren(int position, int count);
- bool detachChild(int position);
- int childNumber() const;
- void setText(const QString &text);
- const QString &text() const;
-
-private:
- QtMessageLogItem *m_parentItem;
- QList<QtMessageLogItem *> m_childItems;
- QString m_text;
-
-public:
- QtMessageLogHandler::ItemType itemType;
- QString file;
- int line;
-};
-
-} //Internal
-} //Debugger
+} // Internal
+} // QmlJSTools
-#endif // QTMESSAGELOGHANDLER_H
+#endif // QMLCONSOLEITEMMODEL_H
diff --git a/src/plugins/qmljstools/qmlconsolemanager.cpp b/src/plugins/qmljstools/qmlconsolemanager.cpp
new file mode 100644
index 0000000000..7332c39e56
--- /dev/null
+++ b/src/plugins/qmljstools/qmlconsolemanager.cpp
@@ -0,0 +1,190 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlconsolemanager.h"
+#include "qmlconsolepane.h"
+#include "qmlconsoleitemmodel.h"
+#include "qmlconsolemodel.h"
+
+#include <extensionsystem/pluginmanager.h>
+
+#include <qmljs/iscriptevaluator.h>
+
+#include <QVariant>
+#include <QCoreApplication>
+
+using namespace QmlJS;
+
+namespace QmlJSTools {
+
+class QmlConsoleManagerPrivate
+{
+public:
+ Internal::QmlConsoleItemModel *qmlConsoleItemModel;
+ Internal::QmlConsolePane *qmlConsolePane;
+ QmlJS::IScriptEvaluator *scriptEvaluator;
+};
+
+QmlConsoleManager::QmlConsoleManager(QObject *parent)
+ : ConsoleManagerInterface(parent),
+ d(new QmlConsoleManagerPrivate)
+{
+ d->qmlConsoleItemModel = new Internal::QmlConsoleItemModel(this);
+ d->qmlConsoleItemModel->setHasEditableRow(true);
+ d->qmlConsolePane = new Internal::QmlConsolePane(this);
+ d->scriptEvaluator = 0;
+ ExtensionSystem::PluginManager::addObject(d->qmlConsolePane);
+}
+
+QmlConsoleManager::~QmlConsoleManager()
+{
+ if (d->qmlConsolePane)
+ ExtensionSystem::PluginManager::removeObject(d->qmlConsolePane);
+ delete d;
+}
+
+void QmlConsoleManager::showConsolePane()
+{
+ if (d->qmlConsolePane)
+ d->qmlConsolePane->popup(Core::IOutputPane::ModeSwitch);
+}
+
+ConsoleItem *QmlConsoleManager::rootItem() const
+{
+ return d->qmlConsoleItemModel->root();
+}
+
+void QmlConsoleManager::setScriptEvaluator(QmlJS::IScriptEvaluator *scriptEvaluator)
+{
+ d->scriptEvaluator = scriptEvaluator;
+ if (!scriptEvaluator)
+ setContext(QString());
+}
+
+void QmlConsoleManager::setContext(const QString &context)
+{
+ d->qmlConsolePane->setContext(context);
+}
+
+void QmlConsoleManager::printToConsolePane(ConsoleItem::ItemType itemType,
+ const QString &text, bool bringToForeground)
+{
+ if (!d->qmlConsolePane)
+ return;
+ if (itemType == ConsoleItem::ErrorType)
+ bringToForeground = true;
+ if (bringToForeground)
+ d->qmlConsolePane->popup(Core::IOutputPane::ModeSwitch);
+ d->qmlConsoleItemModel->appendMessage(itemType, text);
+}
+
+void QmlConsoleManager::printToConsolePane(ConsoleItem *item, bool bringToForeground)
+{
+ if (!d->qmlConsolePane)
+ return;
+ if (item->itemType == ConsoleItem::ErrorType)
+ bringToForeground = true;
+ if (bringToForeground)
+ d->qmlConsolePane->popup(Core::IOutputPane::ModeSwitch);
+ d->qmlConsoleItemModel->appendItem(item);
+}
+
+namespace Internal {
+
+ConsoleItem *constructLogItemTree(ConsoleItem *parent, const QVariant &result,
+ const QString &key = QString())
+{
+ if (!result.isValid())
+ return 0;
+
+ ConsoleItem *item = new ConsoleItem(parent);
+ if (result.type() == QVariant::Map) {
+ if (key.isEmpty())
+ item->setText(QLatin1String("Object"));
+ else
+ item->setText(key + QLatin1String(" : Object"));
+
+ QMapIterator<QString, QVariant> i(result.toMap());
+ while (i.hasNext()) {
+ i.next();
+ ConsoleItem *child = constructLogItemTree(item, i.value(), i.key());
+ if (child)
+ item->insertChild(child, true);
+ }
+ } else if (result.type() == QVariant::List) {
+ if (key.isEmpty())
+ item->setText(QLatin1String("List"));
+ else
+ item->setText(QString(QLatin1String("[%1] : List")).arg(key));
+ QVariantList resultList = result.toList();
+ for (int i = 0; i < resultList.count(); i++) {
+ ConsoleItem *child = constructLogItemTree(item, resultList.at(i),
+ QString::number(i));
+ if (child)
+ item->insertChild(child, true);
+ }
+ } else if (result.canConvert(QVariant::String)) {
+ item->setText(result.toString());
+ } else {
+ item->setText(QLatin1String("Unknown Value"));
+ }
+
+ return item;
+}
+
+QmlConsoleItemModel *QmlConsoleModel::qmlConsoleItemModel()
+{
+ QmlConsoleManager *manager = qobject_cast<QmlConsoleManager *>(QmlConsoleManager::instance());
+ if (manager)
+ return manager->d->qmlConsoleItemModel;
+ return 0;
+}
+
+void QmlConsoleModel::evaluate(const QString &expression)
+{
+ QmlConsoleManager *manager = qobject_cast<QmlConsoleManager *>(QmlConsoleManager::instance());
+ if (manager) {
+ if (manager->d->scriptEvaluator) {
+ QmlConsoleModel::qmlConsoleItemModel()->appendEditableRow();
+ manager->d->scriptEvaluator->evaluateScript(expression);
+ } else {
+ ConsoleItem *root = manager->rootItem();
+ ConsoleItem *item = constructLogItemTree(
+ root, QCoreApplication::translate("QmlJSTools::Internal::QmlConsoleModel",
+ "Can only evaluate during a QML debug session."));
+ if (item) {
+ QmlConsoleModel::qmlConsoleItemModel()->appendEditableRow();
+ manager->printToConsolePane(item);
+ }
+ }
+ }
+}
+
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/qmljstools/qmlconsolemanager.h b/src/plugins/qmljstools/qmlconsolemanager.h
new file mode 100644
index 0000000000..218e8506c3
--- /dev/null
+++ b/src/plugins/qmljstools/qmlconsolemanager.h
@@ -0,0 +1,74 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLCONSOLEMANAGER_H
+#define QMLCONSOLEMANAGER_H
+
+#include "qmljstools_global.h"
+
+#include <qmljs/consolemanagerinterface.h>
+
+#include <QObject>
+
+namespace QmlJS {
+class IScriptEvaluator;
+}
+namespace QmlJSTools {
+
+namespace Internal {
+class QmlConsoleModel;
+}
+
+class QmlConsoleManagerPrivate;
+class QMLJSTOOLS_EXPORT QmlConsoleManager : public QmlJS::ConsoleManagerInterface
+{
+ Q_OBJECT
+public:
+ QmlConsoleManager(QObject *parent);
+ ~QmlConsoleManager();
+
+ void showConsolePane();
+
+ QmlJS::ConsoleItem *rootItem() const;
+
+ void setScriptEvaluator(QmlJS::IScriptEvaluator *scriptEvaluator);
+ void setContext(const QString &context);
+
+ void printToConsolePane(QmlJS::ConsoleItem::ItemType itemType, const QString &text,
+ bool bringToForeground = false);
+ void printToConsolePane(QmlJS::ConsoleItem *item, bool bringToForeground = false);
+
+private:
+ QmlConsoleManagerPrivate *d;
+ friend class Internal::QmlConsoleModel;
+};
+
+} // namespace QmlJSTools
+
+#endif // QMLCONSOLEMANAGER_H
diff --git a/src/plugins/texteditor/tooltip/tipfactory.h b/src/plugins/qmljstools/qmlconsolemodel.h
index a1e0b1b644..6b3be267ae 100644
--- a/src/plugins/texteditor/tooltip/tipfactory.h
+++ b/src/plugins/qmljstools/qmlconsolemodel.h
@@ -27,29 +27,24 @@
**
****************************************************************************/
-#ifndef TIPFACTORY_H
-#define TIPFACTORY_H
+#ifndef QMLCONSOLEMODEL_H
+#define QMLCONSOLEMODEL_H
-#include <QWidget>
-
-namespace TextEditor {
-
-class TipContent;
+#include <QString>
+namespace QmlJSTools {
namespace Internal {
-class QTipLabel;
-class TipFactory
+class QmlConsoleItemModel;
+
+class QmlConsoleModel
{
public:
- TipFactory();
- virtual ~TipFactory();
- Q_DISABLE_COPY(TipFactory)
-
- virtual QTipLabel *createTip(const TipContent &content, QWidget *w);
+ static QmlConsoleItemModel *qmlConsoleItemModel();
+ static void evaluate(const QString &expression);
};
} // namespace Internal
-} // namespace TextEditor
+} // namespace QmlJSTools
-#endif // TIPFACTORY_H
+#endif // QMLCONSOLEMODEL_H
diff --git a/src/plugins/qmljstools/qmlconsolepane.cpp b/src/plugins/qmljstools/qmlconsolepane.cpp
new file mode 100644
index 0000000000..1a9a7ffbb2
--- /dev/null
+++ b/src/plugins/qmljstools/qmlconsolepane.cpp
@@ -0,0 +1,244 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlconsolepane.h"
+#include "qmlconsoleview.h"
+#include "qmlconsoleproxymodel.h"
+#include "qmlconsoleitemmodel.h"
+#include "qmlconsolemanager.h"
+#include "qmlconsoleitemdelegate.h"
+
+#include <coreplugin/icore.h>
+#include <coreplugin/icontext.h>
+#include <coreplugin/findplaceholder.h>
+#include <utils/savedaction.h>
+#include <aggregation/aggregate.h>
+#include <find/treeviewfind.h>
+
+#include <QToolButton>
+#include <QLabel>
+#include <QVBoxLayout>
+
+static const char CONSOLE[] = "Console";
+static const char SHOW_LOG[] = "showLog";
+static const char SHOW_WARNING[] = "showWarning";
+static const char SHOW_ERROR[] = "showError";
+
+namespace QmlJSTools {
+namespace Internal {
+
+/////////////////////////////////////////////////////////////////////
+//
+// QmlConsolePane
+//
+/////////////////////////////////////////////////////////////////////
+
+QmlConsolePane::QmlConsolePane(QObject *parent)
+ : Core::IOutputPane(parent)
+{
+ m_consoleWidget = new QWidget;
+ m_consoleWidget->setWindowTitle(displayName());
+ m_consoleWidget->setEnabled(true);
+
+ QVBoxLayout *vbox = new QVBoxLayout(m_consoleWidget);
+ vbox->setMargin(0);
+ vbox->setSpacing(0);
+
+ m_consoleView = new QmlConsoleView(m_consoleWidget);
+ m_proxyModel = new QmlConsoleProxyModel(this);
+ m_proxyModel->setSourceModel(QmlConsoleModel::qmlConsoleItemModel());
+ connect(QmlConsoleModel::qmlConsoleItemModel(),
+ SIGNAL(selectEditableRow(QModelIndex, QItemSelectionModel::SelectionFlags)),
+ m_proxyModel,
+ SLOT(selectEditableRow(QModelIndex,QItemSelectionModel::SelectionFlags)));
+
+ //Scroll to bottom when rows matching current filter settings are inserted
+ //Not connecting rowsRemoved as the only way to remove rows is to clear the
+ //model which will automatically reset the view.
+ connect(QmlConsoleModel::qmlConsoleItemModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
+ m_proxyModel, SLOT(onRowsInserted(QModelIndex,int,int)));
+ m_consoleView->setModel(m_proxyModel);
+
+ connect(m_proxyModel,
+ SIGNAL(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)),
+ m_consoleView->selectionModel(),
+ SLOT(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)));
+ connect(m_proxyModel, SIGNAL(scrollToBottom()), m_consoleView, SLOT(onScrollToBottom()));
+
+ m_itemDelegate = new QmlConsoleItemDelegate(this);
+ connect(m_consoleView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
+ m_itemDelegate, SLOT(currentChanged(QModelIndex,QModelIndex)));
+ m_consoleView->setItemDelegate(m_itemDelegate);
+
+ Aggregation::Aggregate *aggregate = new Aggregation::Aggregate();
+ aggregate->add(m_consoleView);
+ aggregate->add(new Find::TreeViewFind(m_consoleView));
+
+ vbox->addWidget(m_consoleView);
+ vbox->addWidget(new Core::FindToolBarPlaceHolder(m_consoleWidget));
+
+ m_showDebugButton = new QToolButton(m_consoleWidget);
+ m_showDebugButton->setAutoRaise(true);
+
+ m_showDebugButtonAction = new Utils::SavedAction(this);
+ m_showDebugButtonAction->setDefaultValue(true);
+ m_showDebugButtonAction->setSettingsKey(QLatin1String(CONSOLE), QLatin1String(SHOW_LOG));
+ m_showDebugButtonAction->setToolTip(tr("Show debug, log, and info messages."));
+ m_showDebugButtonAction->setCheckable(true);
+ m_showDebugButtonAction->setIcon(QIcon(QLatin1String(":/qmljstools/images/log.png")));
+ connect(m_showDebugButtonAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowLogs(bool)));
+ m_showDebugButton->setDefaultAction(m_showDebugButtonAction);
+
+ m_showWarningButton = new QToolButton(m_consoleWidget);
+ m_showWarningButton->setAutoRaise(true);
+
+ m_showWarningButtonAction = new Utils::SavedAction(this);
+ m_showWarningButtonAction->setDefaultValue(true);
+ m_showWarningButtonAction->setSettingsKey(QLatin1String(CONSOLE), QLatin1String(SHOW_WARNING));
+ m_showWarningButtonAction->setToolTip(tr("Show debug, log, and info messages."));
+ m_showWarningButtonAction->setCheckable(true);
+ m_showWarningButtonAction->setIcon(QIcon(QLatin1String(":/qmljstools/images/warning.png")));
+ connect(m_showWarningButtonAction, SIGNAL(toggled(bool)), m_proxyModel,
+ SLOT(setShowWarnings(bool)));
+ m_showWarningButton->setDefaultAction(m_showWarningButtonAction);
+
+ m_showErrorButton = new QToolButton(m_consoleWidget);
+ m_showErrorButton->setAutoRaise(true);
+
+ m_showErrorButtonAction = new Utils::SavedAction(this);
+ m_showErrorButtonAction->setDefaultValue(true);
+ m_showErrorButtonAction->setSettingsKey(QLatin1String(CONSOLE), QLatin1String(SHOW_ERROR));
+ m_showErrorButtonAction->setToolTip(tr("Show debug, log, and info messages."));
+ m_showErrorButtonAction->setCheckable(true);
+ m_showErrorButtonAction->setIcon(QIcon(QLatin1String(":/qmljstools/images/error.png")));
+ connect(m_showErrorButtonAction, SIGNAL(toggled(bool)), m_proxyModel,
+ SLOT(setShowErrors(bool)));
+ m_showErrorButton->setDefaultAction(m_showErrorButtonAction);
+
+ m_spacer = new QWidget(m_consoleWidget);
+ m_spacer->setMinimumWidth(30);
+
+ m_statusLabel = new QLabel(m_consoleWidget);
+
+ readSettings();
+ connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), SLOT(writeSettings()));
+}
+
+QmlConsolePane::~QmlConsolePane()
+{
+ writeSettings();
+ delete m_consoleWidget;
+}
+
+QWidget *QmlConsolePane::outputWidget(QWidget *)
+{
+ return m_consoleWidget;
+}
+
+QList<QWidget *> QmlConsolePane::toolBarWidgets() const
+{
+ return QList<QWidget *>() << m_showDebugButton << m_showWarningButton << m_showErrorButton
+ << m_spacer << m_statusLabel;
+}
+
+int QmlConsolePane::priorityInStatusBar() const
+{
+ return 20;
+}
+
+void QmlConsolePane::clearContents()
+{
+ QmlConsoleModel::qmlConsoleItemModel()->clear();
+}
+
+void QmlConsolePane::visibilityChanged(bool /*visible*/)
+{
+}
+
+bool QmlConsolePane::canFocus() const
+{
+ return true;
+}
+
+bool QmlConsolePane::hasFocus() const
+{
+ return m_consoleWidget->hasFocus();
+}
+
+void QmlConsolePane::setFocus()
+{
+ m_consoleWidget->setFocus();
+}
+
+bool QmlConsolePane::canNext() const
+{
+ return false;
+}
+
+bool QmlConsolePane::canPrevious() const
+{
+ return false;
+}
+
+void QmlConsolePane::goToNext()
+{
+}
+
+void QmlConsolePane::goToPrev()
+{
+}
+
+bool QmlConsolePane::canNavigate() const
+{
+ return false;
+}
+
+void QmlConsolePane::readSettings()
+{
+ QSettings *settings = Core::ICore::settings();
+ m_showDebugButtonAction->readSettings(settings);
+ m_showWarningButtonAction->readSettings(settings);
+ m_showErrorButtonAction->readSettings(settings);
+}
+
+void QmlConsolePane::setContext(const QString &context)
+{
+ m_statusLabel->setText(context);
+}
+
+void QmlConsolePane::writeSettings() const
+{
+ QSettings *settings = Core::ICore::settings();
+ m_showDebugButtonAction->writeSettings(settings);
+ m_showWarningButtonAction->writeSettings(settings);
+ m_showErrorButtonAction->writeSettings(settings);
+}
+
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/qmljstools/qmlconsolepane.h b/src/plugins/qmljstools/qmlconsolepane.h
new file mode 100644
index 0000000000..62d6e80755
--- /dev/null
+++ b/src/plugins/qmljstools/qmlconsolepane.h
@@ -0,0 +1,100 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLCONSOLEPANE_H
+#define QMLCONSOLEPANE_H
+
+#include <coreplugin/ioutputpane.h>
+
+QT_BEGIN_NAMESPACE
+class QToolButton;
+class QLabel;
+QT_END_NAMESPACE
+
+namespace Utils {
+class SavedAction;
+}
+
+namespace QmlJSTools {
+
+namespace Internal {
+
+class QmlConsoleView;
+class QmlConsoleItemDelegate;
+class QmlConsoleProxyModel;
+class QmlConsoleItemModel;
+
+class QmlConsolePane : public Core::IOutputPane
+{
+ Q_OBJECT
+public:
+ QmlConsolePane(QObject *parent);
+ ~QmlConsolePane();
+
+ QWidget *outputWidget(QWidget *);
+ QList<QWidget *> toolBarWidgets() const;
+ QString displayName() const { return tr("QML/JS Console"); }
+ int priorityInStatusBar() const;
+ void clearContents();
+ void visibilityChanged(bool visible);
+ bool canFocus() const;
+ bool hasFocus() const;
+ void setFocus();
+
+ bool canNext() const;
+ bool canPrevious() const;
+ void goToNext();
+ void goToPrev();
+ bool canNavigate() const;
+
+ void readSettings();
+ void setContext(const QString &context);
+
+public slots:
+ void writeSettings() const;
+
+private:
+ QToolButton *m_showDebugButton;
+ QToolButton *m_showWarningButton;
+ QToolButton *m_showErrorButton;
+ Utils::SavedAction *m_showDebugButtonAction;
+ Utils::SavedAction *m_showWarningButtonAction;
+ Utils::SavedAction *m_showErrorButtonAction;
+ QWidget *m_spacer;
+ QLabel *m_statusLabel;
+ QmlConsoleView *m_consoleView;
+ QmlConsoleItemDelegate *m_itemDelegate;
+ QmlConsoleProxyModel *m_proxyModel;
+ QWidget *m_consoleWidget;
+};
+
+} // namespace Internal
+} // namespace QmlJSTools
+
+#endif // QMLCONSOLEPANE_H
diff --git a/src/plugins/debugger/qtmessagelogproxymodel.cpp b/src/plugins/qmljstools/qmlconsoleproxymodel.cpp
index bf1b43e770..01cacf2ed9 100644
--- a/src/plugins/debugger/qtmessagelogproxymodel.cpp
+++ b/src/plugins/qmljstools/qmlconsoleproxymodel.cpp
@@ -27,54 +27,54 @@
**
****************************************************************************/
-#include "qtmessagelogproxymodel.h"
+#include "qmlconsoleproxymodel.h"
+#include "qmlconsoleitemmodel.h"
-namespace Debugger {
+using namespace QmlJS;
+
+namespace QmlJSTools {
namespace Internal {
-QtMessageLogProxyModel::QtMessageLogProxyModel(QObject *parent) :
+QmlConsoleProxyModel::QmlConsoleProxyModel(QObject *parent) :
QSortFilterProxyModel(parent),
- m_filter(QtMessageLogHandler::DefaultTypes)
+ m_filter(ConsoleItem::DefaultTypes)
{
}
-void QtMessageLogProxyModel::setShowLogs(bool show)
+void QmlConsoleProxyModel::setShowLogs(bool show)
{
- m_filter = show ? m_filter | QtMessageLogHandler::DebugType :
- m_filter & ~QtMessageLogHandler::DebugType;
+ m_filter = show ? m_filter | ConsoleItem::DebugType : m_filter & ~ConsoleItem::DebugType;
setFilterRegExp(QString());
}
-void QtMessageLogProxyModel::setShowWarnings(bool show)
+void QmlConsoleProxyModel::setShowWarnings(bool show)
{
- m_filter = show ? m_filter | QtMessageLogHandler::WarningType :
- m_filter & ~QtMessageLogHandler::WarningType;
+ m_filter = show ? m_filter | ConsoleItem::WarningType
+ : m_filter & ~ConsoleItem::WarningType;
setFilterRegExp(QString());
}
-void QtMessageLogProxyModel::setShowErrors(bool show)
+void QmlConsoleProxyModel::setShowErrors(bool show)
{
- m_filter = show ? m_filter | QtMessageLogHandler::ErrorType :
- m_filter & ~QtMessageLogHandler::ErrorType;
+ m_filter = show ? m_filter | ConsoleItem::ErrorType : m_filter & ~ConsoleItem::ErrorType;
setFilterRegExp(QString());
}
-void QtMessageLogProxyModel::selectEditableRow(const QModelIndex &index,
+void QmlConsoleProxyModel::selectEditableRow(const QModelIndex &index,
QItemSelectionModel::SelectionFlags command)
{
emit setCurrentIndex(mapFromSource(index), command);
}
-bool QtMessageLogProxyModel::filterAcceptsRow(int sourceRow,
+bool QmlConsoleProxyModel::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const
{
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
- return m_filter.testFlag((QtMessageLogHandler::ItemType)
- sourceModel()->data(
- index, QtMessageLogHandler::TypeRole).toInt());
+ return m_filter.testFlag((ConsoleItem::ItemType)sourceModel()->data(
+ index, QmlConsoleItemModel::TypeRole).toInt());
}
-void QtMessageLogProxyModel::onRowsInserted(const QModelIndex &index, int start, int end)
+void QmlConsoleProxyModel::onRowsInserted(const QModelIndex &index, int start, int end)
{
int rowIndex = end;
do {
@@ -85,5 +85,5 @@ void QtMessageLogProxyModel::onRowsInserted(const QModelIndex &index, int start,
} while (--rowIndex >= start);
}
-} // namespace Internal
-} // namespace Debugger
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/debugger/qtmessagelogproxymodel.h b/src/plugins/qmljstools/qmlconsoleproxymodel.h
index 72a820979c..e0d320ea94 100644
--- a/src/plugins/debugger/qtmessagelogproxymodel.h
+++ b/src/plugins/qmljstools/qmlconsoleproxymodel.h
@@ -27,22 +27,22 @@
**
****************************************************************************/
-#ifndef QTMESSAGELOGPROXYMODEL_H
-#define QTMESSAGELOGPROXYMODEL_H
+#ifndef QMLCONSOLEPROXYMODEL_H
+#define QMLCONSOLEPROXYMODEL_H
-#include "qtmessageloghandler.h"
+#include <qmljs/consoleitem.h>
#include <QSortFilterProxyModel>
#include <QItemSelectionModel>
-namespace Debugger {
+namespace QmlJSTools {
namespace Internal {
-class QtMessageLogProxyModel : public QSortFilterProxyModel
+class QmlConsoleProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
public:
- explicit QtMessageLogProxyModel(QObject *parent = 0);
+ explicit QmlConsoleProxyModel(QObject *parent);
public slots:
void setShowLogs(bool show);
@@ -61,10 +61,10 @@ protected:
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const;
private:
- QFlags<QtMessageLogHandler::ItemType> m_filter;
+ QFlags<QmlJS::ConsoleItem::ItemType> m_filter;
};
-} // namespace Internal
-} // namespace Debugger
+} // Internal
+} // QmlJSTools
-#endif // QTMESSAGELOGPROXYMODEL_H
+#endif // QMLCONSOLEPROXYMODEL_H
diff --git a/src/plugins/debugger/qtmessagelogview.cpp b/src/plugins/qmljstools/qmlconsoleview.cpp
index 4a53ca2ec9..4e22626a2c 100644
--- a/src/plugins/debugger/qtmessagelogview.cpp
+++ b/src/plugins/qmljstools/qmlconsoleview.cpp
@@ -27,17 +27,14 @@
**
****************************************************************************/
-#include "qtmessagelogview.h"
-#include "qtmessagelogitemdelegate.h"
-#include "qtmessageloghandler.h"
-#include "debuggerstringutils.h"
-#include "debuggercore.h"
-#include "debuggerengine.h"
+#include "qmlconsoleview.h"
+#include "qmlconsoleitemdelegate.h"
+#include "qmlconsoleitemmodel.h"
#include <texteditor/basetexteditor.h>
+#include <coreplugin/manhattanstyle.h>
#include <QMouseEvent>
-#include <QProxyStyle>
#include <QPainter>
#include <QApplication>
#include <QClipboard>
@@ -45,40 +42,42 @@
#include <QFileInfo>
#include <QUrl>
#include <QScrollBar>
+#include <QStyleFactory>
+#include <QString>
-namespace Debugger {
+using namespace QmlJS;
+
+namespace QmlJSTools {
namespace Internal {
-class QtMessageLogViewViewStyle : public QProxyStyle
+class QmlConsoleViewStyle : public ManhattanStyle
{
public:
- void drawPrimitive(PrimitiveElement element,
- const QStyleOption *option,
- QPainter *painter,
+ QmlConsoleViewStyle(const QString &baseStyleName) : ManhattanStyle(baseStyleName) {}
+
+ void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter,
const QWidget *widget = 0) const
{
if (element != QStyle::PE_PanelItemViewRow)
- QProxyStyle::drawPrimitive(element, option, painter, widget);
+ ManhattanStyle::drawPrimitive(element, option, painter, widget);
}
- int styleHint(StyleHint hint,
- const QStyleOption *option = 0,
- const QWidget *widget = 0,
+ int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0,
QStyleHintReturn *returnData = 0) const {
if (hint == SH_ItemView_ShowDecorationSelected)
return 0;
else
- return QProxyStyle::styleHint(hint, option, widget, returnData);
+ return ManhattanStyle::styleHint(hint, option, widget, returnData);
}
};
///////////////////////////////////////////////////////////////////////
//
-// QtMessageLogView
+// QmlConsoleView
//
///////////////////////////////////////////////////////////////////////
-QtMessageLogView::QtMessageLogView(QWidget *parent) :
+QmlConsoleView::QmlConsoleView(QWidget *parent) :
QTreeView(parent)
{
setFrameStyle(QFrame::NoFrame);
@@ -102,36 +101,52 @@ QtMessageLogView::QtMessageLogView(QWidget *parent) :
"QTreeView::branch:open:has-children:has-siblings {"
"border-image: none;"
"image: none; }"));
- QtMessageLogViewViewStyle *style = new QtMessageLogViewViewStyle;
+
+ QString baseName = QApplication::style()->objectName();
+#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
+ if (baseName == QLatin1String("windows")) {
+ // Sometimes we get the standard windows 95 style as a fallback
+ if (QStyleFactory::keys().contains(QLatin1String("Fusion")))
+ baseName = QLatin1String("fusion"); // Qt5
+ else { // Qt4
+ // e.g. if we are running on a KDE4 desktop
+ QByteArray desktopEnvironment = qgetenv("DESKTOP_SESSION");
+ if (desktopEnvironment == "kde")
+ baseName = QLatin1String("plastique");
+ else
+ baseName = QLatin1String("cleanlooks");
+ }
+ }
+#endif
+ QmlConsoleViewStyle *style = new QmlConsoleViewStyle(baseName);
setStyle(style);
style->setParent(this);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
- connect(this, SIGNAL(activated(QModelIndex)),
- SLOT(onRowActivated(QModelIndex)));
+ connect(this, SIGNAL(activated(QModelIndex)), SLOT(onRowActivated(QModelIndex)));
}
-void QtMessageLogView::onScrollToBottom()
+void QmlConsoleView::onScrollToBottom()
{
- //Keep scrolling to bottom if scroll bar is at maximum()
+ // Keep scrolling to bottom if scroll bar is at maximum()
if (verticalScrollBar()->value() == verticalScrollBar()->maximum())
scrollToBottom();
}
-void QtMessageLogView::mousePressEvent(QMouseEvent *event)
+void QmlConsoleView::mousePressEvent(QMouseEvent *event)
{
QPoint pos = event->pos();
QModelIndex index = indexAt(pos);
if (index.isValid()) {
- QtMessageLogHandler::ItemType type = (QtMessageLogHandler::ItemType)index.data(
- QtMessageLogHandler::TypeRole).toInt();
+ ConsoleItem::ItemType type = (ConsoleItem::ItemType)index.data(
+ QmlConsoleItemModel::TypeRole).toInt();
bool handled = false;
- if (type == QtMessageLogHandler::UndefinedType) {
+ if (type == ConsoleItem::UndefinedType) {
bool showTypeIcon = index.parent() == QModelIndex();
- ConsoleItemPositions positions(visualRect(index), viewOptions().font,
- showTypeIcon, true);
+ ConsoleItemPositions positions(visualRect(index), viewOptions().font, showTypeIcon,
+ true);
if (positions.expandCollapseIcon().contains(pos)) {
if (isExpanded(index))
@@ -144,13 +159,12 @@ void QtMessageLogView::mousePressEvent(QMouseEvent *event)
if (!handled)
QTreeView::mousePressEvent(event);
} else {
- selectionModel()->setCurrentIndex(model()->index(
- model()->rowCount() - 1, 0),
- QItemSelectionModel::ClearAndSelect);
+ selectionModel()->setCurrentIndex(model()->index(model()->rowCount() - 1, 0),
+ QItemSelectionModel::ClearAndSelect);
}
}
-void QtMessageLogView::keyPressEvent(QKeyEvent *e)
+void QmlConsoleView::keyPressEvent(QKeyEvent *e)
{
if (!e->modifiers() && e->key() == Qt::Key_Return) {
emit activated(currentIndex());
@@ -160,22 +174,22 @@ void QtMessageLogView::keyPressEvent(QKeyEvent *e)
QTreeView::keyPressEvent(e);
}
-void QtMessageLogView::resizeEvent(QResizeEvent *e)
+void QmlConsoleView::resizeEvent(QResizeEvent *e)
{
- static_cast<QtMessageLogItemDelegate *>(itemDelegate())->emitSizeHintChanged(
+ static_cast<QmlConsoleItemDelegate *>(itemDelegate())->emitSizeHintChanged(
selectionModel()->currentIndex());
QTreeView::resizeEvent(e);
}
-void QtMessageLogView::drawBranches(QPainter *painter, const QRect &rect,
- const QModelIndex &index) const
+void QmlConsoleView::drawBranches(QPainter *painter, const QRect &rect,
+ const QModelIndex &index) const
{
- static_cast<QtMessageLogItemDelegate *>(itemDelegate())->drawBackground(
- painter, rect, index, false);
+ static_cast<QmlConsoleItemDelegate *>(itemDelegate())->drawBackground(painter, rect, index,
+ false);
QTreeView::drawBranches(painter, rect, index);
}
-void QtMessageLogView::contextMenuEvent(QContextMenuEvent *event)
+void QmlConsoleView::contextMenuEvent(QContextMenuEvent *event)
{
QModelIndex itemIndex = indexAt(event->pos());
QMenu menu;
@@ -194,76 +208,65 @@ void QtMessageLogView::contextMenuEvent(QContextMenuEvent *event)
if (a == 0)
return;
- if (a == copy)
+ if (a == copy) {
copyToClipboard(itemIndex);
- else if (a == show)
+ } else if (a == show) {
onRowActivated(itemIndex);
- else if (a == clear) {
- QAbstractProxyModel *proxyModel =
- qobject_cast<QAbstractProxyModel *>(model());
- QtMessageLogHandler *handler =
- qobject_cast<QtMessageLogHandler *>(proxyModel->sourceModel());
+ } else if (a == clear) {
+ QAbstractProxyModel *proxyModel = qobject_cast<QAbstractProxyModel *>(model());
+ QmlConsoleItemModel *handler = qobject_cast<QmlConsoleItemModel *>(
+ proxyModel->sourceModel());
handler->clear();
}
}
-void QtMessageLogView::onRowActivated(const QModelIndex &index)
+void QmlConsoleView::onRowActivated(const QModelIndex &index)
{
if (!index.isValid())
return;
- //See if we have file and line Info
+ // See if we have file and line Info
QString filePath = model()->data(index,
- QtMessageLogHandler::FileRole).toString();
+ QmlConsoleItemModel::FileRole).toString();
if (!filePath.isEmpty()) {
- filePath = debuggerCore()->currentEngine()->toFileInProject(
- QUrl(filePath));
QFileInfo fi(filePath);
if (fi.exists() && fi.isFile() && fi.isReadable()) {
- int line = model()->data(index,
- QtMessageLogHandler::LineRole).toInt();
- TextEditor::BaseTextEditorWidget::openEditorAt(
- fi.canonicalFilePath(), line);
+ int line = model()->data(index, QmlConsoleItemModel::LineRole).toInt();
+ TextEditor::BaseTextEditorWidget::openEditorAt(fi.canonicalFilePath(), line);
}
}
}
-void QtMessageLogView::copyToClipboard(const QModelIndex &index)
+void QmlConsoleView::copyToClipboard(const QModelIndex &index)
{
if (!index.isValid())
return;
QString contents = model()->data(index).toString();
- //See if we have file and line Info
- QString filePath = model()->data(index,
- QtMessageLogHandler::FileRole).toString();
+ // See if we have file and line Info
+ QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
if (!filePath.isEmpty()) {
- contents = QString(_("%1 %2: %3")).arg(contents).arg(filePath).arg(
- model()->data(index,
- QtMessageLogHandler::LineRole).toString());
+ contents = QString(QLatin1String("%1 %2: %3")).arg(contents).arg(filePath).arg(
+ model()->data(index, QmlConsoleItemModel::LineRole).toString());
}
QClipboard *cb = QApplication::clipboard();
cb->setText(contents);
}
-bool QtMessageLogView::canShowItemInTextEditor(const QModelIndex &index)
+bool QmlConsoleView::canShowItemInTextEditor(const QModelIndex &index)
{
if (!index.isValid())
return false;
- //See if we have file and line Info
- QString filePath = model()->data(index,
- QtMessageLogHandler::FileRole).toString();
+ // See if we have file and line Info
+ QString filePath = model()->data(index, QmlConsoleItemModel::FileRole).toString();
if (!filePath.isEmpty()) {
- filePath = debuggerCore()->currentEngine()->toFileInProject(
- QUrl(filePath));
QFileInfo fi(filePath);
- if (fi.exists() && fi.isFile() && fi.isReadable()) {
+ if (fi.exists() && fi.isFile() && fi.isReadable())
return true;
- }
}
return false;
}
-} //Internal
-} //Debugger
+} // Internal
+} // QmlJSTools
diff --git a/src/plugins/debugger/qtmessagelogview.h b/src/plugins/qmljstools/qmlconsoleview.h
index cfad227fe0..2208570401 100644
--- a/src/plugins/debugger/qtmessagelogview.h
+++ b/src/plugins/qmljstools/qmlconsoleview.h
@@ -27,19 +27,19 @@
**
****************************************************************************/
-#ifndef QTMESSAGELOGVIEW_H
-#define QTMESSAGELOGVIEW_H
+#ifndef QMLCONSOLEVIEW_H
+#define QMLCONSOLEVIEW_H
#include <QTreeView>
-namespace Debugger {
+namespace QmlJSTools {
namespace Internal {
-class QtMessageLogView : public QTreeView
+class QmlConsoleView : public QTreeView
{
Q_OBJECT
public:
- explicit QtMessageLogView(QWidget *parent = 0);
+ QmlConsoleView(QWidget *parent);
public slots:
void onScrollToBottom();
@@ -60,7 +60,7 @@ private:
bool canShowItemInTextEditor(const QModelIndex &index);
};
-} //Internal
-} //Debugger
+} // Internal
+} // QmlJSTools
-#endif // QTMESSAGELOGVIEW_H
+#endif // QMLCONSOLEVIEW_H
diff --git a/src/plugins/qmljstools/qmljscodestylepreferencesfactory.cpp b/src/plugins/qmljstools/qmljscodestylepreferencesfactory.cpp
index e051636ed3..fa35cc3048 100644
--- a/src/plugins/qmljstools/qmljscodestylepreferencesfactory.cpp
+++ b/src/plugins/qmljstools/qmljscodestylepreferencesfactory.cpp
@@ -62,14 +62,14 @@ QmlJSCodeStylePreferencesFactory::QmlJSCodeStylePreferencesFactory()
{
}
-QString QmlJSCodeStylePreferencesFactory::languageId()
+Core::Id QmlJSCodeStylePreferencesFactory::languageId()
{
return Constants::QML_JS_SETTINGS_ID;
}
QString QmlJSCodeStylePreferencesFactory::displayName()
{
- return Constants::QML_JS_SETTINGS_NAME;
+ return QLatin1String(Constants::QML_JS_SETTINGS_NAME);
}
TextEditor::ICodeStylePreferences *QmlJSCodeStylePreferencesFactory::createCodeStyle() const
diff --git a/src/plugins/qmljstools/qmljscodestylepreferencesfactory.h b/src/plugins/qmljstools/qmljscodestylepreferencesfactory.h
index 6e44c119d7..35e9a6b4ff 100644
--- a/src/plugins/qmljstools/qmljscodestylepreferencesfactory.h
+++ b/src/plugins/qmljstools/qmljscodestylepreferencesfactory.h
@@ -39,13 +39,13 @@ class QmlJSCodeStylePreferencesFactory : public TextEditor::ICodeStylePreference
public:
QmlJSCodeStylePreferencesFactory();
- virtual QString languageId();
- virtual QString displayName();
- virtual TextEditor::ICodeStylePreferences *createCodeStyle() const;
- virtual QWidget *createEditor(TextEditor::ICodeStylePreferences *settings,
- QWidget *parent) const;
- virtual TextEditor::Indenter *createIndenter() const;
- virtual TextEditor::ISnippetProvider *snippetProvider() const;
+ Core::Id languageId();
+ QString displayName();
+ TextEditor::ICodeStylePreferences *createCodeStyle() const;
+ QWidget *createEditor(TextEditor::ICodeStylePreferences *settings,
+ QWidget *parent) const;
+ TextEditor::Indenter *createIndenter() const;
+ TextEditor::ISnippetProvider *snippetProvider() const;
QString previewText() const;
};
diff --git a/src/plugins/qmljstools/qmljscodestylesettingspage.cpp b/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
index 4ccf57921d..107cd7e644 100644
--- a/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
+++ b/src/plugins/qmljstools/qmljscodestylesettingspage.cpp
@@ -166,9 +166,9 @@ QmlJSCodeStyleSettingsPage::QmlJSCodeStyleSettingsPage(/*QSharedPointer<CppFileS
Core::IOptionsPage(parent),
m_pageTabPreferences(0)
{
- setId(QLatin1String(Constants::QML_JS_CODE_STYLE_SETTINGS_ID));
+ setId(Constants::QML_JS_CODE_STYLE_SETTINGS_ID);
setDisplayName(QCoreApplication::translate("QmlJSTools", Constants::QML_JS_CODE_STYLE_SETTINGS_NAME));
- setCategory(QLatin1String(QmlJSEditor::Constants::SETTINGS_CATEGORY_QML));
+ setCategory(QmlJSEditor::Constants::SETTINGS_CATEGORY_QML);
setDisplayCategory(QCoreApplication::translate("QmlJSEditor", QmlJSEditor::Constants::SETTINGS_TR_CATEGORY_QML));
setCategoryIcon(QLatin1String(QmlDesigner::Constants::SETTINGS_CATEGORY_QML_ICON));
}
@@ -176,7 +176,7 @@ QmlJSCodeStyleSettingsPage::QmlJSCodeStyleSettingsPage(/*QSharedPointer<CppFileS
QWidget *QmlJSCodeStyleSettingsPage::createPage(QWidget *parent)
{
TextEditor::SimpleCodeStylePreferences *originalTabPreferences
- = QmlJSToolsSettings::instance()->qmlJSCodeStyle();
+ = QmlJSToolsSettings::globalCodeStyle();
m_pageTabPreferences = new TextEditor::SimpleCodeStylePreferences(m_widget);
m_pageTabPreferences->setDelegatingPool(originalTabPreferences->delegatingPool());
m_pageTabPreferences->setTabSettings(originalTabPreferences->tabSettings());
@@ -194,16 +194,16 @@ void QmlJSCodeStyleSettingsPage::apply()
if (m_widget) {
QSettings *s = Core::ICore::settings();
- TextEditor::SimpleCodeStylePreferences *originalTabPreferences = QmlJSToolsSettings::instance()->qmlJSCodeStyle();
+ TextEditor::SimpleCodeStylePreferences *originalTabPreferences = QmlJSToolsSettings::globalCodeStyle();
if (originalTabPreferences->tabSettings() != m_pageTabPreferences->tabSettings()) {
originalTabPreferences->setTabSettings(m_pageTabPreferences->tabSettings());
if (s)
- originalTabPreferences->toSettings(QmlJSTools::Constants::QML_JS_SETTINGS_ID, s);
+ originalTabPreferences->toSettings(QLatin1String(QmlJSTools::Constants::QML_JS_SETTINGS_ID), s);
}
if (originalTabPreferences->currentDelegate() != m_pageTabPreferences->currentDelegate()) {
originalTabPreferences->setCurrentDelegate(m_pageTabPreferences->currentDelegate());
if (s)
- originalTabPreferences->toSettings(QmlJSTools::Constants::QML_JS_SETTINGS_ID, s);
+ originalTabPreferences->toSettings(QLatin1String(QmlJSTools::Constants::QML_JS_SETTINGS_ID), s);
}
}
}
diff --git a/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp b/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp
index 00c1e18f64..369a764371 100644
--- a/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp
+++ b/src/plugins/qmljstools/qmljsfindexportedcpptypes.cpp
@@ -282,7 +282,7 @@ protected:
// and the expression
const Token begin = translationUnit()->tokenAt(typeId->firstToken());
const Token last = translationUnit()->tokenAt(typeId->lastToken() - 1);
- exportedType.typeExpression = _doc->utf8Source().mid(begin.begin(), last.end() - begin.begin());
+ exportedType.typeExpression = QString::fromUtf8(_doc->utf8Source().mid(begin.begin(), last.end() - begin.begin()));
_exportedTypes += exportedType;
@@ -410,12 +410,12 @@ private:
{
const Token firstToken = translationUnit()->tokenAt(first);
const Token lastToken = translationUnit()->tokenAt(last);
- return _doc->utf8Source().mid(firstToken.begin(), lastToken.end() - firstToken.begin());
+ return QString::fromUtf8(_doc->utf8Source().mid(firstToken.begin(), lastToken.end() - firstToken.begin()));
}
QString stringOf(const Token &token)
{
- return _doc->utf8Source().mid(token.begin(), token.length());
+ return QString::fromUtf8(_doc->utf8Source().mid(token.begin(), token.length()));
}
ExpressionAST *skipStringCall(ExpressionAST *exp)
@@ -516,7 +516,7 @@ static FullySpecifiedType stripPointerAndReference(const FullySpecifiedType &typ
static QString toQmlType(const FullySpecifiedType &type)
{
Overview overview;
- QString result = overview(stripPointerAndReference(type));
+ QString result = overview.prettyType(stripPointerAndReference(type));
if (result == QLatin1String("QString"))
result = QLatin1String("string");
return result;
@@ -553,7 +553,7 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
Overview namePrinter;
- fmo->setClassName(namePrinter(klass->name()));
+ fmo->setClassName(namePrinter.prettyName(klass->name()));
// add the no-package export, so the cpp name can be used in properties
fmo->addExport(fmo->className(), QmlJS::CppQmlTypes::cppPackage, ComponentVersion());
@@ -564,7 +564,7 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
if (Function *func = member->type()->asFunctionType()) {
if (!func->isSlot() && !func->isInvokable() && !func->isSignal())
continue;
- FakeMetaMethod method(namePrinter(func->name()), toQmlType(func->returnType()));
+ FakeMetaMethod method(namePrinter.prettyName(func->name()), toQmlType(func->returnType()));
if (func->isSignal())
method.setMethodType(FakeMetaMethod::Signal);
else
@@ -573,7 +573,7 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
Symbol *arg = func->argumentAt(a);
QString name;
if (arg->name())
- name = namePrinter(arg->name());
+ name = namePrinter.prettyName(arg->name());
method.addParameter(name, toQmlType(arg->type()));
}
fmo->addMethod(method);
@@ -585,7 +585,7 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
const bool isPointer = type.type() && type.type()->isPointerType();
const int revision = 0; // ### fixme
FakeMetaProperty property(
- namePrinter(propDecl->name()),
+ namePrinter.prettyName(propDecl->name()),
toQmlType(type),
isList, isWritable, isPointer,
revision);
@@ -594,7 +594,7 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
if (QtEnum *qtEnum = member->asQtEnum()) {
// find the matching enum
Enum *e = 0;
- QList<LookupItem> result = typeOf(namePrinter(qtEnum->name()).toUtf8(), klass);
+ QList<LookupItem> result = typeOf(namePrinter.prettyName(qtEnum->name()).toUtf8(), klass);
foreach (const LookupItem &item, result) {
if (item.declaration()) {
e = item.declaration()->asEnum();
@@ -605,12 +605,12 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
if (!e)
continue;
- FakeMetaEnum metaEnum(namePrinter(e->name()));
+ FakeMetaEnum metaEnum(namePrinter.prettyName(e->name()));
for (unsigned j = 0; j < e->memberCount(); ++j) {
Symbol *enumMember = e->memberAt(j);
if (!enumMember->name())
continue;
- metaEnum.addKey(namePrinter(enumMember->name()), 0);
+ metaEnum.addKey(namePrinter.prettyName(enumMember->name()), 0);
}
fmo->addEnum(metaEnum);
}
@@ -622,7 +622,7 @@ static LanguageUtils::FakeMetaObject::Ptr buildFakeMetaObject(
if (!base->name())
return fmo;
- const QString baseClassName = namePrinter(base->name());
+ const QString baseClassName = namePrinter.prettyName(base->name());
fmo->setSuperclassName(baseClassName);
Class *baseClass = lookupClass(baseClassName, klass, typeOf);
diff --git a/src/plugins/qmljstools/qmljsfunctionfilter.cpp b/src/plugins/qmljstools/qmljsfunctionfilter.cpp
index f48a6b3123..c8e8273d17 100644
--- a/src/plugins/qmljstools/qmljsfunctionfilter.cpp
+++ b/src/plugins/qmljstools/qmljsfunctionfilter.cpp
@@ -43,6 +43,8 @@ FunctionFilter::FunctionFilter(LocatorData *data, QObject *parent)
: Locator::ILocatorFilter(parent)
, m_data(data)
{
+ setId("Functions");
+ setDisplayName(tr("QML Methods and Functions"));
setShortcutString(QString(QLatin1Char('m')));
setIncludedByDefault(false);
}
@@ -70,7 +72,7 @@ QList<Locator::FilterEntry> FunctionFilter::matchesFor(QFutureInterface<Locator:
QRegExp regexp(asterisk + entry+ asterisk, Qt::CaseInsensitive, QRegExp::Wildcard);
if (!regexp.isValid())
return goodEntries;
- bool hasWildcard = (entry.contains(asterisk) || entry.contains('?'));
+ bool hasWildcard = (entry.contains(asterisk) || entry.contains(QLatin1Char('?')));
QHashIterator<QString, QList<LocatorData::Entry> > it(m_data->entries());
while (it.hasNext()) {
diff --git a/src/plugins/qmljstools/qmljsfunctionfilter.h b/src/plugins/qmljstools/qmljsfunctionfilter.h
index 780fedfe63..5632847ebc 100644
--- a/src/plugins/qmljstools/qmljsfunctionfilter.h
+++ b/src/plugins/qmljstools/qmljsfunctionfilter.h
@@ -40,13 +40,11 @@ class LocatorData;
class FunctionFilter : public Locator::ILocatorFilter
{
Q_OBJECT
+
public:
explicit FunctionFilter(LocatorData *data, QObject *parent = 0);
~FunctionFilter();
- QString displayName() const { return tr("Methods and Functions"); }
- QString id() const { return QLatin1String("Functions"); }
- Priority priority() const { return Medium; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &future);
diff --git a/src/plugins/qmljstools/qmljsinterpreter.cpp b/src/plugins/qmljstools/qmljsinterpreter.cpp
new file mode 100644
index 0000000000..a4ce7e4c54
--- /dev/null
+++ b/src/plugins/qmljstools/qmljsinterpreter.cpp
@@ -0,0 +1,87 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmljsinterpreter.h"
+
+namespace QmlJSTools {
+namespace Internal {
+
+bool QmlJSInterpreter::canEvaluate()
+{
+ int yyaction = 0;
+ int yytoken = -1;
+ int yytos = -1;
+
+ setCode(m_code, 1);
+ m_tokens.append(T_FEED_JS_PROGRAM);
+
+ do {
+ if (++yytos == m_stateStack.size())
+ m_stateStack.resize(m_stateStack.size() * 2);
+
+ m_stateStack[yytos] = yyaction;
+
+again:
+ if (yytoken == -1 && action_index[yyaction] != -TERMINAL_COUNT) {
+ if (m_tokens.isEmpty())
+ yytoken = lex();
+ else
+ yytoken = m_tokens.takeFirst();
+ }
+
+ yyaction = t_action(yyaction, yytoken);
+ if (yyaction > 0) {
+ if (yyaction == ACCEPT_STATE) {
+ --yytos;
+ return true;
+ }
+ yytoken = -1;
+ } else if (yyaction < 0) {
+ const int ruleno = -yyaction - 1;
+ yytos -= rhs[ruleno];
+ yyaction = nt_action(m_stateStack[yytos], lhs[ruleno] - TERMINAL_COUNT);
+ }
+ } while (yyaction);
+
+ const int errorState = m_stateStack[yytos];
+ if (t_action(errorState, T_AUTOMATIC_SEMICOLON) && canInsertAutomaticSemicolon(yytoken)) {
+ yyaction = errorState;
+ m_tokens.prepend(yytoken);
+ yytoken = T_SEMICOLON;
+ goto again;
+ }
+
+ if (yytoken != EOF_SYMBOL)
+ return true;
+
+ return false;
+}
+
+} // namespace Internal
+} // namespace QmlJSTools
diff --git a/src/plugins/qmljstools/qmljsinterpreter.h b/src/plugins/qmljstools/qmljsinterpreter.h
new file mode 100644
index 0000000000..28ff401c9c
--- /dev/null
+++ b/src/plugins/qmljstools/qmljsinterpreter.h
@@ -0,0 +1,69 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLJSINTERPRETER_H
+#define QMLJSINTERPRETER_H
+
+#include <qmljs/parser/qmljslexer_p.h>
+#include <qmljs/parser/qmljsengine_p.h>
+
+#include <QVector>
+#include <QString>
+#include <QList>
+
+namespace QmlJSTools {
+namespace Internal {
+
+class QmlJSInterpreter: QmlJS::Lexer
+{
+public:
+ QmlJSInterpreter()
+ : Lexer(&m_engine),
+ m_stateStack(128)
+ {
+
+ }
+
+ void clearText() { m_code.clear(); }
+ void appendText(const QString &text) { m_code += text; }
+
+ QString code() const { return m_code; }
+ bool canEvaluate();
+
+private:
+ QmlJS::Engine m_engine;
+ QVector<int> m_stateStack;
+ QList<int> m_tokens;
+ QString m_code;
+};
+
+} // namespace Internal
+} // namespace QmlJSTools
+
+#endif // QMLJSINTERPRETER_H
diff --git a/src/plugins/qmljstools/qmljslocatordata.cpp b/src/plugins/qmljstools/qmljslocatordata.cpp
index 32f71c0b08..72e73b3767 100644
--- a/src/plugins/qmljstools/qmljslocatordata.cpp
+++ b/src/plugins/qmljstools/qmljslocatordata.cpp
@@ -70,11 +70,10 @@ public:
QList<LocatorData::Entry> run(const Document::Ptr &doc)
{
m_doc = doc;
- if (!doc->componentName().isEmpty()) {
+ if (!doc->componentName().isEmpty())
m_documentContext = doc->componentName();
- } else {
+ else
m_documentContext = QFileInfo(doc->fileName()).fileName();
- }
accept(doc->ast(), m_documentContext);
return m_entries;
}
@@ -82,7 +81,7 @@ public:
protected:
QString contextString(const QString &extra)
{
- return QString("%1, %2").arg(extra, m_documentContext);
+ return QString::fromLatin1("%1, %2").arg(extra, m_documentContext);
}
LocatorData::Entry basicEntry(SourceLocation loc)
@@ -130,7 +129,7 @@ protected:
m_entries += entry;
- accept(ast->body, contextString(QString("function %1").arg(entry.displayName)));
+ accept(ast->body, contextString(QString::fromLatin1("function %1").arg(entry.displayName)));
return false;
}
@@ -159,7 +158,7 @@ protected:
QString context = toString(ast->qualifiedTypeNameId);
const QString id = idOfObject(ast);
if (!id.isEmpty())
- context = QString("%1 (%2)").arg(id, context);
+ context = QString::fromLatin1("%1 (%2)").arg(id, context);
accept(ast->initializer, contextString(context));
return false;
}
@@ -172,7 +171,7 @@ protected:
QString context = toString(ast->qualifiedTypeNameId);
const QString id = idOfObject(ast);
if (!id.isEmpty())
- context = QString("%1 (%2)").arg(id, context);
+ context = QString::fromLatin1("%1 (%2)").arg(id, context);
accept(ast->initializer, contextString(context));
return false;
}
diff --git a/src/plugins/qmljstools/qmljsmodelmanager.cpp b/src/plugins/qmljstools/qmljsmodelmanager.cpp
index 3062d462ce..6020dd9e55 100644
--- a/src/plugins/qmljstools/qmljsmodelmanager.cpp
+++ b/src/plugins/qmljstools/qmljsmodelmanager.cpp
@@ -50,6 +50,7 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/session.h>
#include <qtsupport/baseqtversion.h>
+#include <utils/hostosinfo.h>
#include <QDir>
#include <QFile>
@@ -69,27 +70,41 @@ using namespace QmlJSTools::Internal;
static QStringList environmentImportPaths();
+static void mergeSuffixes(QStringList &l1, const QStringList &l2)
+{
+ if (!l2.isEmpty())
+ l1 = l2;
+}
+
QmlJS::Document::Language QmlJSTools::languageOfFile(const QString &fileName)
{
- QStringList jsSuffixes("js");
- QStringList qmlSuffixes("qml");
- QStringList jsonSuffixes("json");
+ QStringList jsSuffixes(QLatin1String("js"));
+ QStringList qmlSuffixes(QLatin1String("qml"));
+ QStringList qmlProjectSuffixes(QLatin1String("qmlproject"));
+ QStringList jsonSuffixes(QLatin1String("json"));
+ QStringList qbsSuffixes(QLatin1String("qbs"));
if (Core::ICore::instance()) {
Core::MimeDatabase *db = Core::ICore::mimeDatabase();
- Core::MimeType jsSourceTy = db->findByType(Constants::JS_MIMETYPE);
- jsSuffixes = jsSourceTy.suffixes();
- Core::MimeType qmlSourceTy = db->findByType(Constants::QML_MIMETYPE);
- qmlSuffixes = qmlSourceTy.suffixes();
- Core::MimeType jsonSourceTy = db->findByType(Constants::JSON_MIMETYPE);
- jsonSuffixes = jsonSourceTy.suffixes();
+ Core::MimeType jsSourceTy = db->findByType(QLatin1String(Constants::JS_MIMETYPE));
+ mergeSuffixes(jsSuffixes, jsSourceTy.suffixes());
+ Core::MimeType qmlSourceTy = db->findByType(QLatin1String(Constants::QML_MIMETYPE));
+ mergeSuffixes(qmlSuffixes, qmlSourceTy.suffixes());
+ Core::MimeType qbsSourceTy = db->findByType(QLatin1String(Constants::QBS_MIMETYPE));
+ mergeSuffixes(qbsSuffixes, qbsSourceTy.suffixes());
+ Core::MimeType qmlProjectSourceTy = db->findByType(QLatin1String(Constants::QMLPROJECT_MIMETYPE));
+ mergeSuffixes(qbsSuffixes, qmlProjectSourceTy.suffixes());
+ Core::MimeType jsonSourceTy = db->findByType(QLatin1String(Constants::JSON_MIMETYPE));
+ mergeSuffixes(jsonSuffixes, jsonSourceTy.suffixes());
}
const QFileInfo info(fileName);
const QString fileSuffix = info.suffix();
if (jsSuffixes.contains(fileSuffix))
return QmlJS::Document::JavaScriptLanguage;
- if (qmlSuffixes.contains(fileSuffix))
+ if (qbsSuffixes.contains(fileSuffix))
+ return QmlJS::Document::QmlQbsLanguage;
+ if (qmlSuffixes.contains(fileSuffix) || qmlProjectSuffixes.contains(fileSuffix))
return QmlJS::Document::QmlLanguage;
if (jsonSuffixes.contains(fileSuffix))
return QmlJS::Document::JsonLanguage;
@@ -101,8 +116,8 @@ QStringList QmlJSTools::qmlAndJsGlobPatterns()
QStringList pattern;
if (Core::ICore::instance()) {
Core::MimeDatabase *db = Core::ICore::mimeDatabase();
- Core::MimeType jsSourceTy = db->findByType(Constants::JS_MIMETYPE);
- Core::MimeType qmlSourceTy = db->findByType(Constants::QML_MIMETYPE);
+ Core::MimeType jsSourceTy = db->findByType(QLatin1String(Constants::JS_MIMETYPE));
+ Core::MimeType qmlSourceTy = db->findByType(QLatin1String(Constants::QML_MIMETYPE));
QStringList pattern;
foreach (const Core::MimeGlobPattern &glob, jsSourceTy.globPatterns())
@@ -110,7 +125,7 @@ QStringList QmlJSTools::qmlAndJsGlobPatterns()
foreach (const Core::MimeGlobPattern &glob, qmlSourceTy.globPatterns())
pattern << glob.regExp().pattern();
} else {
- pattern << "*.qml" << "*.js";
+ pattern << QLatin1String("*.qml") << QLatin1String("*.js");
}
return pattern;
}
@@ -212,9 +227,8 @@ ModelManagerInterface::WorkingCopy ModelManager::workingCopy() const
if (TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor)) {
if (textEditor->context().contains(ProjectExplorer::Constants::LANG_QMLJS)) {
- if (TextEditor::BaseTextEditorWidget *ed = qobject_cast<TextEditor::BaseTextEditorWidget *>(textEditor->widget())) {
+ if (TextEditor::BaseTextEditorWidget *ed = qobject_cast<TextEditor::BaseTextEditorWidget *>(textEditor->widget()))
workingCopy.insert(key, ed->toPlainText(), ed->document()->revision());
- }
}
}
}
@@ -243,9 +257,8 @@ void ModelManager::updateSourceFiles(const QStringList &files,
QFuture<void> ModelManager::refreshSourceFiles(const QStringList &sourceFiles,
bool emitDocumentOnDiskChanged)
{
- if (sourceFiles.isEmpty()) {
+ if (sourceFiles.isEmpty())
return QFuture<void>();
- }
QFuture<void> result = QtConcurrent::run(&ModelManager::parse,
workingCopy(), sourceFiles,
@@ -267,7 +280,7 @@ QFuture<void> ModelManager::refreshSourceFiles(const QStringList &sourceFiles,
if (sourceFiles.count() > 1) {
Core::ICore::progressManager()->addTask(result, tr("Indexing"),
- Constants::TASK_INDEX);
+ QLatin1String(Constants::TASK_INDEX));
}
return result;
@@ -464,9 +477,9 @@ static bool findNewQmlLibraryInPath(const QString &path,
return false;
}
-#ifdef Q_OS_WIN
- // QTCREATORBUG-3402 - be case sensitive even here?
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ // QTCREATORBUG-3402 - be case sensitive even here?
+ }
// found a new library!
qmldirFile.open(QFile::ReadOnly);
@@ -503,7 +516,7 @@ static void findNewQmlLibrary(
QSet<QString> *scannedPaths,
QSet<QString> *newLibraries)
{
- QString libraryPath = QString("%1.%2.%3").arg(
+ QString libraryPath = QString::fromLatin1("%1.%2.%3").arg(
path,
QString::number(version.majorVersion()),
QString::number(version.minorVersion()));
@@ -511,7 +524,7 @@ static void findNewQmlLibrary(
libraryPath, snapshot, modelManager,
importedFiles, scannedPaths, newLibraries);
- libraryPath = QString("%1.%2").arg(
+ libraryPath = QString::fromLatin1("%1.%2").arg(
path,
QString::number(version.majorVersion()));
findNewQmlLibraryInPath(
@@ -653,12 +666,8 @@ static QStringList environmentImportPaths()
QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");
-#if defined(Q_OS_WIN)
- QLatin1Char pathSep(';');
-#else
- QLatin1Char pathSep(':');
-#endif
- foreach (const QString &path, QString::fromLatin1(envImportPath).split(pathSep, QString::SkipEmptyParts)) {
+ foreach (const QString &path, QString::fromLatin1(envImportPath)
+ .split(Utils::HostOsInfo::pathListSeparator(), QString::SkipEmptyParts)) {
QString canonicalPath = QDir(path).canonicalPath();
if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
paths.append(canonicalPath);
diff --git a/src/plugins/qmljstools/qmljsplugindumper.cpp b/src/plugins/qmljstools/qmljsplugindumper.cpp
index d85197e573..24bcc8fc3f 100644
--- a/src/plugins/qmljstools/qmljsplugindumper.cpp
+++ b/src/plugins/qmljstools/qmljsplugindumper.cpp
@@ -135,7 +135,7 @@ static QString makeAbsolute(const QString &path, const QString &base)
{
if (QFileInfo(path).isAbsolute())
return path;
- return QString("%1%2%3").arg(base, QDir::separator(), path);
+ return QString::fromLatin1("%1%2%3").arg(base, QDir::separator(), path);
}
void PluginDumper::onLoadPluginTypes(const QString &libraryPath, const QString &importPath, const QString &importUri, const QString &importVersion)
@@ -269,7 +269,7 @@ void PluginDumper::qmlPluginTypeDumpDone(int exitCode)
if (exitCode != 0) {
Core::MessageManager *messageManager = Core::MessageManager::instance();
- const QString errorMessages = process->readAllStandardError();
+ const QString errorMessages = QString::fromLocal8Bit(process->readAllStandardError());
messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
libraryInfo.setPluginTypeInfoStatus(LibraryInfo::DumpError, qmldumpFailedMessage(libraryPath, errorMessages));
}
@@ -309,7 +309,7 @@ void PluginDumper::qmlPluginTypeDumpError(QProcess::ProcessError)
return;
Core::MessageManager *messageManager = Core::MessageManager::instance();
- const QString errorMessages = process->readAllStandardError();
+ const QString errorMessages = QString::fromLocal8Bit(process->readAllStandardError());
messageManager->printToOutputPane(qmldumpErrorMessage(libraryPath, errorMessages));
if (!libraryPath.isEmpty()) {
diff --git a/src/plugins/qmljstools/qmljssemanticinfo.cpp b/src/plugins/qmljstools/qmljssemanticinfo.cpp
index 0682f386db..031bba46a1 100644
--- a/src/plugins/qmljstools/qmljssemanticinfo.cpp
+++ b/src/plugins/qmljstools/qmljssemanticinfo.cpp
@@ -89,13 +89,12 @@ protected:
virtual bool preVisit(AST::Node *node)
{
- if (Statement *stmt = node->statementCast()) {
+ if (Statement *stmt = node->statementCast())
return handleLocationAst(stmt);
- } else if (ExpressionNode *exp = node->expressionCast()) {
+ else if (ExpressionNode *exp = node->expressionCast())
return handleLocationAst(exp);
- } else if (UiObjectMember *ui = node->uiObjectMemberCast()) {
+ else if (UiObjectMember *ui = node->uiObjectMemberCast())
return handleLocationAst(ui);
- }
return true;
}
@@ -160,14 +159,14 @@ QmlJS::AST::Node *SemanticInfo::declaringMemberNoProperties(int cursorPosition)
QList<AST::Node *> path = rangePath(cursorPosition);
if (path.size() > 1)
return path.at(path.size() - 2);
- } else if (name.contains("GradientStop")) {
+ } else if (name.contains(QLatin1String("GradientStop"))) {
QList<AST::Node *> path = rangePath(cursorPosition);
if (path.size() > 2)
return path.at(path.size() - 3);
}
} else if (UiObjectBinding *objectBinding = cast<UiObjectBinding*>(node)) {
const QString &name = objectBinding->qualifiedTypeNameId->name.toString();
- if (name.contains("Gradient")) {
+ if (name.contains(QLatin1String("Gradient"))) {
QList<AST::Node *> path = rangePath(cursorPosition);
if (path.size() > 1)
return path.at(path.size() - 2);
@@ -182,11 +181,10 @@ QList<AST::Node *> SemanticInfo::rangePath(int cursorPosition) const
QList<AST::Node *> path;
foreach (const Range &range, ranges) {
- if (range.begin.isNull() || range.end.isNull()) {
+ if (range.begin.isNull() || range.end.isNull())
continue;
- } else if (cursorPosition >= range.begin.position() && cursorPosition <= range.end.position()) {
+ else if (cursorPosition >= range.begin.position() && cursorPosition <= range.end.position())
path += range.ast;
- }
}
return path;
diff --git a/src/plugins/qmljstools/qmljstools-lib.pri b/src/plugins/qmljstools/qmljstools-lib.pri
deleted file mode 100644
index e618816549..0000000000
--- a/src/plugins/qmljstools/qmljstools-lib.pri
+++ /dev/null
@@ -1,45 +0,0 @@
-!dll {
- DEFINES += QMLJSTOOLS_STATIC
-}
-
-INCLUDEPATH += $$PWD/..
-
-HEADERS += \
- $$PWD/qmljstools_global.h \
- $$PWD/qmljstoolsplugin.h \
- $$PWD/qmljstoolsconstants.h \
- $$PWD/qmljstoolssettings.h \
- $$PWD/qmljscodestylepreferencesfactory.h \
- $$PWD/qmljsmodelmanager.h \
- $$PWD/qmljsqtstylecodeformatter.h \
- $$PWD/qmljsrefactoringchanges.h \
- $$PWD/qmljsplugindumper.h \
- $$PWD/qmljsfunctionfilter.h \
- $$PWD/qmljslocatordata.h \
- $$PWD/qmljsindenter.h \
- $$PWD/qmljscodestylesettingspage.h \
- $$PWD/qmljsfindexportedcpptypes.h \
- $$PWD/qmljssemanticinfo.h
-
-SOURCES += \
- $$PWD/qmljstoolsplugin.cpp \
- $$PWD/qmljstoolssettings.cpp \
- $$PWD/qmljscodestylepreferencesfactory.cpp \
- $$PWD/qmljsmodelmanager.cpp \
- $$PWD/qmljsqtstylecodeformatter.cpp \
- $$PWD/qmljsrefactoringchanges.cpp \
- $$PWD/qmljsplugindumper.cpp \
- $$PWD/qmljsfunctionfilter.cpp \
- $$PWD/qmljslocatordata.cpp \
- $$PWD/qmljsindenter.cpp \
- $$PWD/qmljscodestylesettingspage.cpp \
- $$PWD/qmljsfindexportedcpptypes.cpp \
- $$PWD/qmljssemanticinfo.cpp
-
-FORMS += \
- $$PWD/qmljscodestylesettingspage.ui
-
-equals(TEST, 1) {
- SOURCES += \
- $$PWD/qmljstools_test.cpp
-}
diff --git a/src/plugins/qmljstools/qmljstools.pri b/src/plugins/qmljstools/qmljstools.pri
index 75415d0c1f..1d36f5e406 100644
--- a/src/plugins/qmljstools/qmljstools.pri
+++ b/src/plugins/qmljstools/qmljstools.pri
@@ -1,5 +1,3 @@
include(qmljstools_dependencies.pri)
-INCLUDEPATH *= $$PWD/..
-
LIBS *= -l$$qtLibraryName(QmlJSTools)
diff --git a/src/plugins/qmljstools/qmljstools.pro b/src/plugins/qmljstools/qmljstools.pro
index 86426bb3b7..b653f9b084 100644
--- a/src/plugins/qmljstools/qmljstools.pro
+++ b/src/plugins/qmljstools/qmljstools.pro
@@ -3,8 +3,68 @@ TARGET = QmlJSTools
include(../../qtcreatorplugin.pri)
include(qmljstools_dependencies.pri)
-# DEFINES += QT_NO_CAST_FROM_ASCII
-DEFINES += QT_NO_CAST_TO_ASCII
DEFINES += QMLJSTOOLS_LIBRARY
-include(qmljstools-lib.pri)
+!dll {
+ DEFINES += QMLJSTOOLS_STATIC
+}
+
+HEADERS += \
+ $$PWD/qmljstoolsplugin.h \
+ $$PWD/qmljstoolsconstants.h \
+ $$PWD/qmljstoolssettings.h \
+ $$PWD/qmljscodestylepreferencesfactory.h \
+ $$PWD/qmljsmodelmanager.h \
+ $$PWD/qmljsqtstylecodeformatter.h \
+ $$PWD/qmljsrefactoringchanges.h \
+ $$PWD/qmljsplugindumper.h \
+ $$PWD/qmljsfunctionfilter.h \
+ $$PWD/qmljslocatordata.h \
+ $$PWD/qmljsindenter.h \
+ $$PWD/qmljscodestylesettingspage.h \
+ $$PWD/qmljsfindexportedcpptypes.h \
+ $$PWD/qmljssemanticinfo.h \
+ $$PWD/qmljstools_global.h \
+ $$PWD/qmlconsolemanager.h \
+ $$PWD/qmlconsoleitemmodel.h \
+ $$PWD/qmlconsolemodel.h \
+ $$PWD/qmlconsolepane.h \
+ $$PWD/qmlconsoleview.h \
+ $$PWD/qmlconsoleitemdelegate.h \
+ $$PWD/qmlconsoleedit.h \
+ $$PWD/qmljsinterpreter.h \
+ $$PWD/qmlconsoleproxymodel.h
+
+SOURCES += \
+ $$PWD/qmljstoolsplugin.cpp \
+ $$PWD/qmljstoolssettings.cpp \
+ $$PWD/qmljscodestylepreferencesfactory.cpp \
+ $$PWD/qmljsmodelmanager.cpp \
+ $$PWD/qmljsqtstylecodeformatter.cpp \
+ $$PWD/qmljsrefactoringchanges.cpp \
+ $$PWD/qmljsplugindumper.cpp \
+ $$PWD/qmljsfunctionfilter.cpp \
+ $$PWD/qmljslocatordata.cpp \
+ $$PWD/qmljsindenter.cpp \
+ $$PWD/qmljscodestylesettingspage.cpp \
+ $$PWD/qmljsfindexportedcpptypes.cpp \
+ $$PWD/qmljssemanticinfo.cpp \
+ $$PWD/qmlconsolemanager.cpp \
+ $$PWD/qmlconsoleitemmodel.cpp \
+ $$PWD/qmlconsolepane.cpp \
+ $$PWD/qmlconsoleview.cpp \
+ $$PWD/qmlconsoleitemdelegate.cpp \
+ $$PWD/qmlconsoleedit.cpp \
+ $$PWD/qmljsinterpreter.cpp \
+ $$PWD/qmlconsoleproxymodel.cpp
+
+RESOURCES += \
+ qmljstools.qrc
+
+FORMS += \
+ $$PWD/qmljscodestylesettingspage.ui
+
+equals(TEST, 1) {
+ SOURCES += \
+ $$PWD/qmljstools_test.cpp
+}
diff --git a/src/plugins/qmljstools/qmljstools.qbs b/src/plugins/qmljstools/qmljstools.qbs
index 2d5d58c64f..9f62253750 100644
--- a/src/plugins/qmljstools/qmljstools.qbs
+++ b/src/plugins/qmljstools/qmljstools.qbs
@@ -1,11 +1,12 @@
import qbs.base 1.0
import "../QtcPlugin.qbs" as QtcPlugin
+import "../../../qbs/defaults.js" as Defaults
QtcPlugin {
name: "QmlJSTools"
- Depends { name: "Qt.widgets" }
+ Depends { name: "Qt"; submodules: ["script", "widgets"] }
Depends { name: "Core" }
Depends { name: "LanguageUtils" }
Depends { name: "CppTools" }
@@ -17,17 +18,11 @@ QtcPlugin {
Depends { name: "QtSupport" }
Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_NO_CAST_TO_ASCII"])
- cpp.includePaths: [
- "..",
- "../../libs",
- "../../libs/3rdparty",
- buildDirectory
- ]
+ cpp.includePaths: base.concat("../../libs/3rdparty")
files: [
- "qmljsmodelmanager.cpp",
- "qmljsmodelmanager.h",
+ "qmljscodestylepreferencesfactory.cpp",
+ "qmljscodestylepreferencesfactory.h",
"qmljscodestylesettingspage.cpp",
"qmljscodestylesettingspage.h",
"qmljscodestylesettingspage.ui",
@@ -40,6 +35,8 @@ QtcPlugin {
"qmljslocatordata.cpp",
"qmljslocatordata.h",
"qmljsmodelmanager.cpp",
+ "qmljsmodelmanager.cpp",
+ "qmljsmodelmanager.h",
"qmljsmodelmanager.h",
"qmljsplugindumper.cpp",
"qmljsplugindumper.h",
@@ -47,21 +44,40 @@ QtcPlugin {
"qmljsqtstylecodeformatter.h",
"qmljsrefactoringchanges.cpp",
"qmljsrefactoringchanges.h",
+ "qmljssemanticinfo.cpp",
+ "qmljssemanticinfo.h",
"qmljstools_global.h",
"qmljstoolsconstants.h",
"qmljstoolsplugin.cpp",
"qmljstoolsplugin.h",
"qmljstoolssettings.cpp",
"qmljstoolssettings.h",
- "qmljscodestylepreferencesfactory.cpp",
- "qmljscodestylepreferencesfactory.h",
- "qmljssemanticinfo.cpp",
- "qmljssemanticinfo.h"
+ "qmlconsolemanager.cpp",
+ "qmlconsolemanager.h",
+ "qmlconsoleitemmodel.cpp",
+ "qmlconsoleitemmodel.h",
+ "qmlconsolepane.cpp",
+ "qmlconsolepane.h",
+ "qmlconsoleview.cpp",
+ "qmlconsoleview.h",
+ "qmlconsoleitemdelegate.cpp",
+ "qmlconsoleitemdelegate.h",
+ "qmlconsoleedit.cpp",
+ "qmlconsoleedit.h",
+ "qmlconsoleproxymodel.cpp",
+ "qmlconsoleproxymodel.h",
+ "qmljsinterpreter.cpp",
+ "qmljsinterpreter.h",
+ "qmljstools.qrc"
]
+ Group {
+ condition: Defaults.testsEnabled(qbs)
+ files: ["qmljstools_test.cpp"]
+ }
+
ProductModule {
Depends { name: "CppTools" }
Depends { name: "QmlDebug" }
}
}
-
diff --git a/src/plugins/qmljstools/qmljstools.qrc b/src/plugins/qmljstools/qmljstools.qrc
new file mode 100644
index 0000000000..9e396a3995
--- /dev/null
+++ b/src/plugins/qmljstools/qmljstools.qrc
@@ -0,0 +1,10 @@
+<RCC>
+ <qresource prefix="/qmljstools">
+ <file>images/prompt.png</file>
+ <file>images/collapse.png</file>
+ <file>images/warning.png</file>
+ <file>images/log.png</file>
+ <file>images/expand.png</file>
+ <file>images/error.png</file>
+ </qresource>
+</RCC>
diff --git a/src/plugins/qmljstools/qmljstools_test.cpp b/src/plugins/qmljstools/qmljstools_test.cpp
index e7a7ed4e46..d25cbdd1e3 100644
--- a/src/plugins/qmljstools/qmljstools_test.cpp
+++ b/src/plugins/qmljstools/qmljstools_test.cpp
@@ -55,7 +55,7 @@ void QmlJSTools::Internal::QmlJSToolsPlugin::test_basic()
{
QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
- const QString welcomescreenRootPath = Core::ICore::resourcePath() + "/welcomescreen/welcomescreen.qml";
+ const QString welcomescreenRootPath = Core::ICore::resourcePath() + QLatin1String("/welcomescreen/welcomescreen.qml");
modelManager->updateSourceFiles(QStringList(welcomescreenRootPath), false);
modelManager->joinAllThreads();
@@ -67,34 +67,34 @@ void QmlJSTools::Internal::QmlJSToolsPlugin::test_basic()
QVERIFY(context);
const CppComponentValue *rectangleValue = context->valueOwner()->cppQmlTypes().objectByQualifiedName(
- "QtQuick", "QDeclarative1Rectangle", LanguageUtils::ComponentVersion(1, 0));
+ QLatin1String("QtQuick"), QLatin1String("QDeclarative1Rectangle"), LanguageUtils::ComponentVersion(1, 0));
QVERIFY(rectangleValue);
- QVERIFY(!rectangleValue->isWritable("border"));
- QVERIFY(rectangleValue->hasProperty("border"));
- QVERIFY(rectangleValue->isPointer("border"));
- QVERIFY(rectangleValue->isWritable("color"));
- QVERIFY(!rectangleValue->isPointer("color"));
+ QVERIFY(!rectangleValue->isWritable(QLatin1String("border")));
+ QVERIFY(rectangleValue->hasProperty(QLatin1String("border")));
+ QVERIFY(rectangleValue->isPointer(QLatin1String("border")));
+ QVERIFY(rectangleValue->isWritable(QLatin1String("color")));
+ QVERIFY(!rectangleValue->isPointer(QLatin1String("color")));
- const ObjectValue *ovItem = context->lookupType(doc.data(), QStringList() << "Item");
+ const ObjectValue *ovItem = context->lookupType(doc.data(), QStringList(QLatin1String("Item")));
QVERIFY(ovItem);
- QCOMPARE(ovItem->className(), QString("Item"));
- QCOMPARE(context->imports(doc.data())->info("Item", context.data()).name(), QString("QtQuick"));
+ QCOMPARE(ovItem->className(), QLatin1String("Item"));
+ QCOMPARE(context->imports(doc.data())->info(QLatin1String("Item"), context.data()).name(), QLatin1String("QtQuick"));
- const ObjectValue *ovProperty = context->lookupType(doc.data(), QStringList() << "Item" << "states");
+ const ObjectValue *ovProperty = context->lookupType(doc.data(), QStringList() << QLatin1String("Item") << QLatin1String("states"));
QVERIFY(ovProperty);
- QCOMPARE(ovProperty->className(), QString("State"));
+ QCOMPARE(ovProperty->className(), QLatin1String("State"));
- const CppComponentValue * qmlItemValue = value_cast<CppComponentValue>(ovItem);
+ const CppComponentValue *qmlItemValue = value_cast<CppComponentValue>(ovItem);
QVERIFY(qmlItemValue);
- QCOMPARE(qmlItemValue->defaultPropertyName(), QString("data"));
- QCOMPARE(qmlItemValue->propertyType("state"), QString("string"));
+ QCOMPARE(qmlItemValue->defaultPropertyName(), QLatin1String("data"));
+ QCOMPARE(qmlItemValue->propertyType(QLatin1String("state")), QLatin1String("string"));
- const ObjectValue *ovState = context->lookupType(doc.data(), QStringList() << "State");
- const CppComponentValue * qmlState2Value = value_cast<CppComponentValue>(ovState);
- QCOMPARE(qmlState2Value->className(), QString("State"));
+ const ObjectValue *ovState = context->lookupType(doc.data(), QStringList(QLatin1String("State")));
+ const CppComponentValue *qmlState2Value = value_cast<CppComponentValue>(ovState);
+ QCOMPARE(qmlState2Value->className(), QLatin1String("State"));
- const ObjectValue *ovImage = context->lookupType(doc.data(), QStringList() << "Image");
- const CppComponentValue * qmlImageValue = value_cast<CppComponentValue>(ovImage);
- QCOMPARE(qmlImageValue->className(), QString("Image"));
- QCOMPARE(qmlImageValue->propertyType("source"), QString("QUrl"));
+ const ObjectValue *ovImage = context->lookupType(doc.data(), QStringList(QLatin1String("Image")));
+ const CppComponentValue *qmlImageValue = value_cast<CppComponentValue>(ovImage);
+ QCOMPARE(qmlImageValue->className(), QLatin1String("Image"));
+ QCOMPARE(qmlImageValue->propertyType(QLatin1String("source")), QLatin1String("QUrl"));
}
diff --git a/src/plugins/qmljstools/qmljstoolsconstants.h b/src/plugins/qmljstools/qmljstoolsconstants.h
index cb1ccf7071..4662204fe0 100644
--- a/src/plugins/qmljstools/qmljstoolsconstants.h
+++ b/src/plugins/qmljstools/qmljstoolsconstants.h
@@ -35,7 +35,10 @@
namespace QmlJSTools {
namespace Constants {
-const char QML_MIMETYPE[] = "application/x-qml";
+const char QML_MIMETYPE[] = "application/x-qml"; // separate def also in projectexplorerconstants.h
+const char QBS_MIMETYPE[] = "application/x-qt.qbs+qml";
+const char QMLPROJECT_MIMETYPE[] = "application/x-qmlproject";
+const char QMLTYPES_MIMETYPE[] = "application/x-qt.meta-info+qml";
const char JS_MIMETYPE[] = "application/javascript";
const char JSON_MIMETYPE[] = "application/json";
diff --git a/src/plugins/qmljstools/qmljstoolsplugin.cpp b/src/plugins/qmljstools/qmljstoolsplugin.cpp
index 25224f4834..22d6717294 100644
--- a/src/plugins/qmljstools/qmljstoolsplugin.cpp
+++ b/src/plugins/qmljstools/qmljstoolsplugin.cpp
@@ -34,6 +34,7 @@
#include "qmljscodestylesettingspage.h"
#include "qmljstoolsconstants.h"
#include "qmljstoolssettings.h"
+#include "qmlconsolemanager.h"
#include <extensionsystem/pluginmanager.h>
@@ -51,6 +52,7 @@
#include <QSettings>
#include <QMenu>
+using namespace QmlJSTools;
using namespace QmlJSTools::Internal;
enum { debug = 0 };
@@ -67,6 +69,7 @@ QmlJSToolsPlugin::~QmlJSToolsPlugin()
{
m_instance = 0;
m_modelManager = 0; // deleted automatically
+ m_consoleManager = 0; // deleted automatically
}
bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
@@ -78,6 +81,8 @@ bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error)
// Objects
m_modelManager = new ModelManager(this);
+ m_consoleManager = new QmlConsoleManager(this);
+
// Core::VCSManager *vcsManager = core->vcsManager();
// Core::DocumentManager *fileManager = core->fileManager();
// connect(vcsManager, SIGNAL(repositoryChanged(QString)),
@@ -127,16 +132,14 @@ ExtensionSystem::IPlugin::ShutdownFlag QmlJSToolsPlugin::aboutToShutdown()
void QmlJSToolsPlugin::onTaskStarted(const QString &type)
{
- if (type == QmlJSTools::Constants::TASK_INDEX) {
+ if (type == QLatin1String(QmlJSTools::Constants::TASK_INDEX))
m_resetCodeModelAction->setEnabled(false);
- }
}
void QmlJSToolsPlugin::onAllTasksFinished(const QString &type)
{
- if (type == QmlJSTools::Constants::TASK_INDEX) {
+ if (type == QLatin1String(QmlJSTools::Constants::TASK_INDEX))
m_resetCodeModelAction->setEnabled(true);
- }
}
Q_EXPORT_PLUGIN(QmlJSToolsPlugin)
diff --git a/src/plugins/qmljstools/qmljstoolsplugin.h b/src/plugins/qmljstools/qmljstoolsplugin.h
index 4ba68e1bce..5f5dcdaecf 100644
--- a/src/plugins/qmljstools/qmljstoolsplugin.h
+++ b/src/plugins/qmljstools/qmljstoolsplugin.h
@@ -45,6 +45,7 @@ QT_END_NAMESPACE
namespace QmlJSTools {
class QmlJSToolsSettings;
+class QmlConsoleManager;
namespace Internal {
@@ -76,6 +77,7 @@ private slots:
private:
ModelManager *m_modelManager;
+ QmlConsoleManager *m_consoleManager;
QmlJSToolsSettings *m_settings;
QAction *m_resetCodeModelAction;
diff --git a/src/plugins/qmljstools/qmljstoolssettings.cpp b/src/plugins/qmljstools/qmljstoolssettings.cpp
index b041fa1b3f..46159d467b 100644
--- a/src/plugins/qmljstools/qmljstoolssettings.cpp
+++ b/src/plugins/qmljstools/qmljstoolssettings.cpp
@@ -42,53 +42,40 @@
#include <QSettings>
-static const char *idKey = "QmlJSGlobal";
-
-using namespace QmlJSTools;
-using TextEditor::TabSettings;
+using namespace TextEditor;
namespace QmlJSTools {
-namespace Internal {
-
-class QmlJSToolsSettingsPrivate
-{
-public:
- TextEditor::SimpleCodeStylePreferences *m_globalCodeStyle;
-};
-} // namespace Internal
-} // namespace QmlJSTools
+const char idKey[] = "QmlJSGlobal";
-QmlJSToolsSettings *QmlJSToolsSettings::m_instance = 0;
+static TextEditor::SimpleCodeStylePreferences *m_globalCodeStyle = 0;
QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
: QObject(parent)
- , d(new Internal::QmlJSToolsSettingsPrivate)
{
- QTC_ASSERT(!m_instance, return);
- m_instance = this;
+ QTC_ASSERT(!m_globalCodeStyle, return);
- TextEditor::TextEditorSettings *textEditorSettings = TextEditor::TextEditorSettings::instance();
+ TextEditorSettings *textEditorSettings = TextEditorSettings::instance();
// code style factory
- TextEditor::ICodeStylePreferencesFactory *factory = new QmlJSTools::QmlJSCodeStylePreferencesFactory();
+ ICodeStylePreferencesFactory *factory = new QmlJSCodeStylePreferencesFactory();
textEditorSettings->registerCodeStyleFactory(factory);
// code style pool
- TextEditor::CodeStylePool *pool = new TextEditor::CodeStylePool(factory, this);
+ CodeStylePool *pool = new CodeStylePool(factory, this);
textEditorSettings->registerCodeStylePool(Constants::QML_JS_SETTINGS_ID, pool);
// global code style settings
- d->m_globalCodeStyle = new TextEditor::SimpleCodeStylePreferences(this);
- d->m_globalCodeStyle->setDelegatingPool(pool);
- d->m_globalCodeStyle->setDisplayName(tr("Global", "Settings"));
- d->m_globalCodeStyle->setId(idKey);
- pool->addCodeStyle(d->m_globalCodeStyle);
- textEditorSettings->registerCodeStyle(QmlJSTools::Constants::QML_JS_SETTINGS_ID, d->m_globalCodeStyle);
+ m_globalCodeStyle = new SimpleCodeStylePreferences(this);
+ m_globalCodeStyle->setDelegatingPool(pool);
+ m_globalCodeStyle->setDisplayName(tr("Global", "Settings"));
+ m_globalCodeStyle->setId(QLatin1String(idKey));
+ pool->addCodeStyle(m_globalCodeStyle);
+ textEditorSettings->registerCodeStyle(QmlJSTools::Constants::QML_JS_SETTINGS_ID, m_globalCodeStyle);
// built-in settings
// Qt style
- TextEditor::SimpleCodeStylePreferences *qtCodeStyle = new TextEditor::SimpleCodeStylePreferences();
+ SimpleCodeStylePreferences *qtCodeStyle = new SimpleCodeStylePreferences();
qtCodeStyle->setId(QLatin1String("qt"));
qtCodeStyle->setDisplayName(tr("Qt"));
qtCodeStyle->setReadOnly(true);
@@ -101,13 +88,13 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
pool->addCodeStyle(qtCodeStyle);
// default delegate for global preferences
- d->m_globalCodeStyle->setCurrentDelegate(qtCodeStyle);
+ m_globalCodeStyle->setCurrentDelegate(qtCodeStyle);
pool->loadCustomCodeStyles();
// load global settings (after built-in settings are added to the pool)
QSettings *s = Core::ICore::settings();
- d->m_globalCodeStyle->fromSettings(QmlJSTools::Constants::QML_JS_SETTINGS_ID, s);
+ m_globalCodeStyle->fromSettings(QLatin1String(QmlJSTools::Constants::QML_JS_SETTINGS_ID), s);
// legacy handling start (Qt Creator Version < 2.4)
const bool legacyTransformed =
@@ -136,13 +123,13 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
}
// create custom code style out of old settings
- TextEditor::ICodeStylePreferences *oldCreator = pool->createCodeStyle(
+ ICodeStylePreferences *oldCreator = pool->createCodeStyle(
QLatin1String("legacy"), legacyTabSettings,
QVariant(), tr("Old Creator"));
// change the current delegate and save
- d->m_globalCodeStyle->setCurrentDelegate(oldCreator);
- d->m_globalCodeStyle->toSettings(QmlJSTools::Constants::QML_JS_SETTINGS_ID, s);
+ m_globalCodeStyle->setCurrentDelegate(oldCreator);
+ m_globalCodeStyle->toSettings(QLatin1String(QmlJSTools::Constants::QML_JS_SETTINGS_ID), s);
}
// mark old settings as transformed
s->setValue(QLatin1String("QmlJSTabPreferences/LegacyTransformed"), true);
@@ -154,6 +141,15 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
QLatin1String(Constants::QML_MIMETYPE),
Constants::QML_JS_SETTINGS_ID);
textEditorSettings->registerMimeTypeForLanguageId(
+ QLatin1String(Constants::QBS_MIMETYPE),
+ Constants::QML_JS_SETTINGS_ID);
+ textEditorSettings->registerMimeTypeForLanguageId(
+ QLatin1String(Constants::QMLPROJECT_MIMETYPE),
+ Constants::QML_JS_SETTINGS_ID);
+ textEditorSettings->registerMimeTypeForLanguageId(
+ QLatin1String(Constants::QMLTYPES_MIMETYPE),
+ Constants::QML_JS_SETTINGS_ID);
+ textEditorSettings->registerMimeTypeForLanguageId(
QLatin1String(Constants::JS_MIMETYPE),
Constants::QML_JS_SETTINGS_ID);
textEditorSettings->registerMimeTypeForLanguageId(
@@ -163,19 +159,13 @@ QmlJSToolsSettings::QmlJSToolsSettings(QObject *parent)
QmlJSToolsSettings::~QmlJSToolsSettings()
{
- delete d;
-
- m_instance = 0;
-}
-
-QmlJSToolsSettings *QmlJSToolsSettings::instance()
-{
- return m_instance;
+ delete m_globalCodeStyle;
+ m_globalCodeStyle = 0;
}
-TextEditor::SimpleCodeStylePreferences *QmlJSToolsSettings::qmlJSCodeStyle() const
+SimpleCodeStylePreferences *QmlJSToolsSettings::globalCodeStyle()
{
- return d->m_globalCodeStyle;
+ return m_globalCodeStyle;
}
-
+} // namespace QmlJSTools
diff --git a/src/plugins/qmljstools/qmljstoolssettings.h b/src/plugins/qmljstools/qmljstoolssettings.h
index e039e74057..364688ab13 100644
--- a/src/plugins/qmljstools/qmljstoolssettings.h
+++ b/src/plugins/qmljstools/qmljstoolssettings.h
@@ -34,18 +34,9 @@
#include <QObject>
-namespace TextEditor
-{
-class SimpleCodeStylePreferences;
-}
-
-namespace QmlJSTools
-{
+namespace TextEditor { class SimpleCodeStylePreferences; }
-namespace Internal
-{
-class QmlJSToolsSettingsPrivate;
-}
+namespace QmlJSTools {
/**
* This class provides a central place for cpp tools settings.
@@ -58,14 +49,7 @@ public:
explicit QmlJSToolsSettings(QObject *parent);
~QmlJSToolsSettings();
- static QmlJSToolsSettings *instance();
-
- TextEditor::SimpleCodeStylePreferences *qmlJSCodeStyle() const;
-
-private:
- Internal::QmlJSToolsSettingsPrivate *d;
-
- static QmlJSToolsSettings *m_instance;
+ static TextEditor::SimpleCodeStylePreferences *globalCodeStyle();
};
} // namespace QmlJSTools
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp
index b093b74353..70a849f39b 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas.cpp
@@ -127,9 +127,8 @@ void Canvas::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget
painter->setWorldTransform(scale * old);
painter->drawPixmap(0, 0, m_context->pixmap());
painter->setWorldTransform(old);
- if (clip()) {
+ if (clip())
painter->restore();
- }
}
} else {
painter->drawPixmap(0, 0, m_context->pixmap());
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h
index 770b6757cc..429097d5b4 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvas_p.h
@@ -65,7 +65,7 @@ public:
public Q_SLOTS:
- Context2D *getContext(const QString & = QString("2d"));
+ Context2D *getContext(const QString & = QLatin1String("2d"));
void requestPaint();
FillMode fillMode() const;
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp b/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp
index 58c91439e6..f1b836721b 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecanvastimer.cpp
@@ -46,9 +46,8 @@ void CanvasTimer::handleTimeout()
{
Q_ASSERT(m_value.isFunction());
m_value.call();
- if (isSingleShot()) {
+ if (isSingleShot())
removeTimer(this);
- }
}
void CanvasTimer::createTimer(QObject *parent, const QScriptValue &val, long timeout, bool singleshot)
diff --git a/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp b/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp
index 379d34e191..62e7f09207 100644
--- a/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp
+++ b/src/plugins/qmlprofiler/canvas/qdeclarativecontext2d.cpp
@@ -66,22 +66,22 @@ static QList<qreal> parseNumbersList(QString::const_iterator &itr)
while ((*itr).isSpace())
++itr;
while ((*itr).isNumber() ||
- (*itr) == '-' || (*itr) == '+' || (*itr) == '.') {
+ (*itr) == QLatin1Char('-') || (*itr) == QLatin1Char('+') || (*itr) == QLatin1Char('.')) {
temp.clear();
- if ((*itr) == '-')
+ if ((*itr) == QLatin1Char('-'))
temp += *itr++;
- else if ((*itr) == '+')
+ else if ((*itr) == QLatin1Char('+'))
temp += *itr++;
while ((*itr).isDigit())
temp += *itr++;
- if ((*itr) == '.')
+ if ((*itr) == QLatin1Char('.'))
temp += *itr++;
while ((*itr).isDigit())
temp += *itr++;
while ((*itr).isSpace())
++itr;
- if ((*itr) == ',')
+ if ((*itr) == QLatin1Char(','))
++itr;
points.append(temp.toDouble());
//eat spaces
@@ -96,39 +96,35 @@ QColor colorFromString(const QString &name)
{
QString::const_iterator itr = name.constBegin();
QList<qreal> compo;
- if (name.startsWith("rgba(")) {
+ if (name.startsWith(QLatin1String("rgba("))) {
++itr; ++itr; ++itr; ++itr; ++itr;
compo = parseNumbersList(itr);
- if (compo.size() != 4) {
+ if (compo.size() != 4)
return QColor();
- }
//alpha seems to be always between 0-1
compo[3] *= 255;
return QColor((int)compo[0], (int)compo[1],
(int)compo[2], (int)compo[3]);
- } else if (name.startsWith("rgb(")) {
+ } else if (name.startsWith(QLatin1String("rgb("))) {
++itr; ++itr; ++itr; ++itr;
compo = parseNumbersList(itr);
- if (compo.size() != 3) {
+ if (compo.size() != 3)
return QColor();
- }
return QColor((int)qClamp(compo[0], qreal(0), qreal(255)),
(int)qClamp(compo[1], qreal(0), qreal(255)),
(int)qClamp(compo[2], qreal(0), qreal(255)));
- } else if (name.startsWith("hsla(")){
+ } else if (name.startsWith(QLatin1String("hsla("))) {
++itr; ++itr; ++itr; ++itr; ++itr;
compo = parseNumbersList(itr);
- if (compo.size() != 4) {
+ if (compo.size() != 4)
return QColor();
- }
return QColor::fromHslF(compo[0], compo[1],
compo[2], compo[3]);
- } else if (name.startsWith("hsl(")){
+ } else if (name.startsWith(QLatin1String("hsl("))) {
++itr; ++itr; ++itr; ++itr; ++itr;
compo = parseNumbersList(itr);
- if (compo.size() != 3) {
+ if (compo.size() != 3)
return QColor();
- }
return QColor::fromHslF(compo[0], compo[1],
compo[2]);
} else {
@@ -141,31 +137,30 @@ QColor colorFromString(const QString &name)
static QPainter::CompositionMode compositeOperatorFromString(const QString &compositeOperator)
{
- if (compositeOperator == QLatin1String("source-over")) {
+ if (compositeOperator == QLatin1String("source-over"))
return QPainter::CompositionMode_SourceOver;
- } else if (compositeOperator == QLatin1String("source-out")) {
+ else if (compositeOperator == QLatin1String("source-out"))
return QPainter::CompositionMode_SourceOut;
- } else if (compositeOperator == QLatin1String("source-in")) {
+ else if (compositeOperator == QLatin1String("source-in"))
return QPainter::CompositionMode_SourceIn;
- } else if (compositeOperator == QLatin1String("source-atop")) {
+ else if (compositeOperator == QLatin1String("source-atop"))
return QPainter::CompositionMode_SourceAtop;
- } else if (compositeOperator == QLatin1String("destination-atop")) {
+ else if (compositeOperator == QLatin1String("destination-atop"))
return QPainter::CompositionMode_DestinationAtop;
- } else if (compositeOperator == QLatin1String("destination-in")) {
+ else if (compositeOperator == QLatin1String("destination-in"))
return QPainter::CompositionMode_DestinationIn;
- } else if (compositeOperator == QLatin1String("destination-out")) {
+ else if (compositeOperator == QLatin1String("destination-out"))
return QPainter::CompositionMode_DestinationOut;
- } else if (compositeOperator == QLatin1String("destination-over")) {
+ else if (compositeOperator == QLatin1String("destination-over"))
return QPainter::CompositionMode_DestinationOver;
- } else if (compositeOperator == QLatin1String("darker")) {
+ else if (compositeOperator == QLatin1String("darker"))
return QPainter::CompositionMode_SourceOver;
- } else if (compositeOperator == QLatin1String("lighter")) {
+ else if (compositeOperator == QLatin1String("lighter"))
return QPainter::CompositionMode_SourceOver;
- } else if (compositeOperator == QLatin1String("copy")) {
+ else if (compositeOperator == QLatin1String("copy"))
return QPainter::CompositionMode_Source;
- } else if (compositeOperator == QLatin1String("xor")) {
+ else if (compositeOperator == QLatin1String("xor"))
return QPainter::CompositionMode_Xor;
- }
return QPainter::CompositionMode_SourceOver;
}
@@ -174,53 +169,53 @@ static QString compositeOperatorToString(QPainter::CompositionMode op)
{
switch (op) {
case QPainter::CompositionMode_SourceOver:
- return "source-over";
+ return QLatin1String("source-over");
case QPainter::CompositionMode_DestinationOver:
- return "destination-over";
+ return QLatin1String("destination-over");
case QPainter::CompositionMode_Clear:
- return "clear";
+ return QLatin1String("clear");
case QPainter::CompositionMode_Source:
- return "source";
+ return QLatin1String("source");
case QPainter::CompositionMode_Destination:
- return "destination";
+ return QLatin1String("destination");
case QPainter::CompositionMode_SourceIn:
- return "source-in";
+ return QLatin1String("source-in");
case QPainter::CompositionMode_DestinationIn:
- return "destination-in";
+ return QLatin1String("destination-in");
case QPainter::CompositionMode_SourceOut:
- return "source-out";
+ return QLatin1String("source-out");
case QPainter::CompositionMode_DestinationOut:
- return "destination-out";
+ return QLatin1String("destination-out");
case QPainter::CompositionMode_SourceAtop:
- return "source-atop";
+ return QLatin1String("source-atop");
case QPainter::CompositionMode_DestinationAtop:
- return "destination-atop";
+ return QLatin1String("destination-atop");
case QPainter::CompositionMode_Xor:
- return "xor";
+ return QLatin1String("xor");
case QPainter::CompositionMode_Plus:
- return "plus";
+ return QLatin1String("plus");
case QPainter::CompositionMode_Multiply:
- return "multiply";
+ return QLatin1String("multiply");
case QPainter::CompositionMode_Screen:
- return "screen";
+ return QLatin1String("screen");
case QPainter::CompositionMode_Overlay:
- return "overlay";
+ return QLatin1String("overlay");
case QPainter::CompositionMode_Darken:
- return "darken";
+ return QLatin1String("darken");
case QPainter::CompositionMode_Lighten:
- return "lighten";
+ return QLatin1String("lighten");
case QPainter::CompositionMode_ColorDodge:
- return "color-dodge";
+ return QLatin1String("color-dodge");
case QPainter::CompositionMode_ColorBurn:
- return "color-burn";
+ return QLatin1String("color-burn");
case QPainter::CompositionMode_HardLight:
- return "hard-light";
+ return QLatin1String("hard-light");
case QPainter::CompositionMode_SoftLight:
- return "soft-light";
+ return QLatin1String("soft-light");
case QPainter::CompositionMode_Difference:
- return "difference";
+ return QLatin1String("difference");
case QPainter::CompositionMode_Exclusion:
- return "exclusion";
+ return QLatin1String("exclusion");
default:
break;
}
@@ -379,11 +374,11 @@ QString Context2D::lineCap() const
{
switch (m_state.lineCap) {
case Qt::FlatCap:
- return "butt";
+ return QLatin1String("butt");
case Qt::SquareCap:
- return "square";
+ return QLatin1String("square");
case Qt::RoundCap:
- return "round";
+ return QLatin1String("round");
default: ;
}
return QString();
@@ -396,7 +391,7 @@ void Context2D::setLineCap(const QString &capString)
style = Qt::RoundCap;
else if (capString == QLatin1String("square"))
style = Qt::SquareCap;
- else //if (capString == "butt")
+ else //if (capString == QLatin1String("butt"))
style = Qt::FlatCap;
m_state.lineCap = style;
m_state.flags |= DirtyLineCap;
@@ -528,7 +523,7 @@ void Context2D::setTextBaseline(const QString &baseline)
m_state.textBaseline = Context2D::Middle;
else {
m_state.textBaseline = Context2D::Alphabetic;
- qWarning() << ("Context2D: invalid baseline:" + baseline);
+ qWarning() << (QLatin1String("Context2D: invalid baseline:") + baseline);
}
m_state.flags |= DirtyTextBaseline;
}
@@ -577,7 +572,7 @@ void Context2D::setFont(const QString &fontString)
{
QFont font;
// ### this is simplified and incomplete
- QStringList tokens = fontString.split(QLatin1Char(' '));
+ QStringList tokens = fontString.split(QLatin1Char(QLatin1Char(' ')));
foreach (const QString &token, tokens) {
if (token == QLatin1String("italic"))
font.setItalic(true);
@@ -585,7 +580,7 @@ void Context2D::setFont(const QString &fontString)
font.setBold(true);
else if (token.endsWith(QLatin1String("px"))) {
QString number = token;
- number.remove("px");
+ number.remove(QLatin1String("px"));
#ifdef Q_OS_MACX
// compensating the extra antialias space with bigger fonts
// this class is only used by the QML Profiler
@@ -833,11 +828,10 @@ void Context2D::arc(qreal xc, qreal yc, qreal radius,
double width = radius*2;
double height = radius*2;
- if (!anticlockwise && (ea < sa)) {
+ if (!anticlockwise && (ea < sa))
span += 360;
- } else if (anticlockwise && (sa < ea)) {
+ else if (anticlockwise && (sa < ea))
span -= 360;
- }
//### this is also due to switched coordinate system
// we would end up with a 0 span instead of 360
diff --git a/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp b/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp
index cee7a1ffad..d6b3dccf97 100644
--- a/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp
+++ b/src/plugins/qmlprofiler/localqmlprofilerrunner.cpp
@@ -43,11 +43,10 @@ LocalQmlProfilerRunner::LocalQmlProfilerRunner(const Configuration &configuratio
void LocalQmlProfilerRunner::start()
{
- QString arguments = QString("-qmljsdebugger=port:%1,block").arg(
- QString::number(m_configuration.port));
+ QString arguments = QString::fromLatin1("-qmljsdebugger=port:%1,block").arg(m_configuration.port);
if (!m_configuration.executableArguments.isEmpty())
- arguments += QChar(' ') + m_configuration.executableArguments;
+ arguments += QLatin1Char(' ') + m_configuration.executableArguments;
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: Launching %s:%d", qPrintable(m_configuration.executable),
@@ -77,9 +76,8 @@ void LocalQmlProfilerRunner::stop()
if (QmlProfilerPlugin::debugOutput)
qWarning("QmlProfiler: Stopping application ...");
- if (m_launcher.isRunning()) {
+ if (m_launcher.isRunning())
m_launcher.stop();
- }
}
quint16 LocalQmlProfilerRunner::debugPort() const
diff --git a/src/plugins/qmlprofiler/qmlprofiler.qbs b/src/plugins/qmlprofiler/qmlprofiler.qbs
index 345a5354e0..7a97fec0b7 100644
--- a/src/plugins/qmlprofiler/qmlprofiler.qbs
+++ b/src/plugins/qmlprofiler/qmlprofiler.qbs
@@ -20,17 +20,13 @@ QtcPlugin {
Depends { name: "CPlusPlus" }
Depends { name: "cpp" }
- cpp.includePaths: [
- "canvas",
- "..",
- "../../libs",
- buildDirectory
- ]
+ cpp.includePaths: base.concat("canvas")
files: [
"abstractqmlprofilerrunner.h",
"localqmlprofilerrunner.cpp",
"localqmlprofilerrunner.h",
+ "qmlprofiler_global.h",
"qmlprofilerattachdialog.cpp",
"qmlprofilerattachdialog.h",
"qmlprofilerattachdialog.ui",
@@ -45,7 +41,6 @@ QtcPlugin {
"qmlprofilerengine.h",
"qmlprofilereventview.cpp",
"qmlprofilereventview.h",
- "qmlprofiler_global.h",
"qmlprofilerplugin.cpp",
"qmlprofilerplugin.h",
"qmlprofilerstatemanager.cpp",
@@ -75,6 +70,7 @@ QtcPlugin {
"qml/Detail.qml",
"qml/Label.qml",
"qml/MainView.qml",
+ "qml/Overview.js",
"qml/Overview.qml",
"qml/RangeDetails.qml",
"qml/RangeMover.qml",
@@ -84,7 +80,5 @@ QtcPlugin {
"qml/TimeDisplay.qml",
"qml/TimeMarks.qml",
"qml/qmlprofiler.qrc",
- "qml/Overview.js"
]
}
-
diff --git a/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp b/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
index 0c6dad3b25..3082bed5da 100644
--- a/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerclientmanager.cpp
@@ -36,7 +36,7 @@
#include <qmldebug/qv8profilerclient.h>
#include <utils/qtcassert.h>
-#include <QWeakPointer>
+#include <QPointer>
#include <QTimer>
#include <QMessageBox>
@@ -53,8 +53,8 @@ public:
QmlProfilerStateManager* profilerState;
QmlDebugConnection *connection;
- QWeakPointer<QmlProfilerTraceClient> qmlclientplugin;
- QWeakPointer<QV8ProfilerClient> v8clientplugin;
+ QPointer<QmlProfilerTraceClient> qmlclientplugin;
+ QPointer<QV8ProfilerClient> v8clientplugin;
QTimer connectionTimer;
int connectionAttempts;
@@ -75,7 +75,7 @@ public:
QmlProfilerClientManager::QmlProfilerClientManager(QObject *parent) :
QObject(parent), d(new QmlProfilerClientManagerPrivate(this))
{
- setObjectName("QML Profiler Connections");
+ setObjectName(QLatin1String("QML Profiler Connections"));
d->profilerState = 0;
@@ -224,7 +224,8 @@ void QmlProfilerClientManager::connectToClient()
if (!d->connection || d->connection->state() != QAbstractSocket::UnconnectedState)
return;
- QmlProfilerTool::logStatus(QString("QML Profiler: Connecting to %1:%2 ...").arg(d->tcpHost, QString::number(d->tcpPort)));
+ QmlProfilerTool::logStatus(QString::fromLatin1("QML Profiler: Connecting to %1:%2 ...")
+ .arg(d->tcpHost, QString::number(d->tcpPort)));
d->connection->connectToHost(d->tcpHost, d->tcpPort);
}
@@ -321,15 +322,14 @@ void QmlProfilerClientManager::retryMessageBoxFinished(int result)
break;
}
case QMessageBox::Help: {
- QmlProfilerTool::handleHelpRequest(QString("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
+ QmlProfilerTool::handleHelpRequest(QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"));
// fall through
}
default: {
- if (d->connection) {
- QmlProfilerTool::logStatus("QML Profiler: Failed to connect! " + d->connection->errorString());
- } else {
- QmlProfilerTool::logStatus("QML Profiler: Failed to connect!");
- }
+ if (d->connection)
+ QmlProfilerTool::logStatus(QLatin1String("QML Profiler: Failed to connect! ") + d->connection->errorString());
+ else
+ QmlProfilerTool::logStatus(QLatin1String("QML Profiler: Failed to connect!"));
emit connectionFailed();
break;
@@ -398,9 +398,8 @@ void QmlProfilerClientManager::profilerStateChanged()
QTC_ASSERT(d->profilerState, return);
switch (d->profilerState->currentState()) {
case QmlProfilerStateManager::AppStopRequested :
- if (d->profilerState->serverRecording()) {
+ if (d->profilerState->serverRecording())
stopClientsRecording();
- }
else
d->profilerState->setCurrentState(QmlProfilerStateManager::AppReadyToStop);
break;
diff --git a/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp b/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
index 648f99756e..fab94e86c0 100644
--- a/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerdatamodel.cpp
@@ -215,7 +215,7 @@ public:
QmlProfilerDataModel::QmlProfilerDataModel(QObject *parent) :
QObject(parent), d(new QmlProfilerDataModelPrivate(this))
{
- setObjectName("QmlProfilerDataModel");
+ setObjectName(QLatin1String("QmlProfilerDataModel"));
d->listState = Empty;
@@ -309,14 +309,13 @@ void QmlProfilerDataModel::addRangedEvent(int type, int bindingType, qint64 star
if (data.isEmpty())
details = tr("Source code not available");
else {
- details = data.join(" ").replace('\n'," ").simplified();
- QRegExp rewrite("\\(function \\$(\\w+)\\(\\) \\{ (return |)(.+) \\}\\)");
+ details = data.join(QLatin1String(" ")).replace(QLatin1Char('\n'),QLatin1Char(' ')).simplified();
+ QRegExp rewrite(QLatin1String("\\(function \\$(\\w+)\\(\\) \\{ (return |)(.+) \\}\\)"));
bool match = rewrite.exactMatch(details);
- if (match) {
- details = rewrite.cap(1) + ": " + rewrite.cap(3);
- }
- if (details.startsWith(QString("file://")))
- details = details.mid(details.lastIndexOf(QChar('/')) + 1);
+ if (match)
+ details = rewrite.cap(1) + QLatin1String(": ") + rewrite.cap(3);
+ if (details.startsWith(QLatin1String("file://")))
+ details = details.mid(details.lastIndexOf(QLatin1Char('/')) + 1);
}
// backwards compatibility: "compiling" events don't have a proper location in older
@@ -333,7 +332,7 @@ void QmlProfilerDataModel::addRangedEvent(int type, int bindingType, qint64 star
eventHashStr = getHashStringForQmlEvent(eventLocation, type);
} else {
const QString filePath = QUrl(eventLocation.filename).path();
- displayName = filePath.mid(filePath.lastIndexOf(QChar('/')) + 1) + colon +
+ displayName = filePath.mid(filePath.lastIndexOf(QLatin1Char('/')) + 1) + colon +
QString::number(eventLocation.line);
eventHashStr = getHashStringForQmlEvent(eventLocation, type);
}
@@ -450,7 +449,7 @@ void QmlProfilerDataModel::setTraceStartTime(qint64 time)
QString QmlProfilerDataModel::getHashStringForQmlEvent(
const QmlDebug::QmlEventLocation &location, int eventType)
{
- return QString("%1:%2:%3:%4").arg(location.filename,
+ return QString::fromLatin1("%1:%2:%3:%4").arg(location.filename,
QString::number(location.line),
QString::number(location.column),
QString::number(eventType));
@@ -459,7 +458,7 @@ QString QmlProfilerDataModel::getHashStringForQmlEvent(
QString QmlProfilerDataModel::getHashStringForV8Event(const QString &displayName,
const QString &function)
{
- return QString("%1:%2").arg(displayName, function);
+ return QString::fromLatin1("%1:%2").arg(displayName, function);
}
QString QmlProfilerDataModel::rootEventName()
@@ -510,11 +509,10 @@ QmlEventType QmlProfilerDataModel::qmlEventTypeAsEnum(const QString &typeString)
} else {
bool isNumber = false;
int type = typeString.toUInt(&isNumber);
- if (isNumber) {
+ if (isNumber)
return (QmlEventType)type;
- } else {
+ else
return MaximumQmlEventType;
- }
}
}
@@ -843,9 +841,8 @@ void QmlProfilerDataModel::QmlProfilerDataModelPrivate::prepareForDisplay()
typeCounts[typeNumber] = new QmlRangeEventTypeCount;
typeCounts[typeNumber]->nestingCount = 0;
}
- if (eventStartData.nestingLevel > typeCounts[typeNumber]->nestingCount) {
+ if (eventStartData.nestingLevel > typeCounts[typeNumber]->nestingCount)
typeCounts[typeNumber]->nestingCount = eventStartData.nestingLevel;
- }
if (!typeCounts[typeNumber]->eventIds.contains(eventStartData.statsInfo->eventId))
typeCounts[typeNumber]->eventIds << eventStartData.statsInfo->eventId;
}
@@ -1133,9 +1130,8 @@ void QmlProfilerDataModel::QmlProfilerDataModelPrivate::redoTree(qint64 fromTime
int level = startInstanceList[index].level;
QmlRangeEventData *parentEvent = listedRootEvent;
- if (level > Constants::QML_MIN_LEVEL && lastParent.contains(level-1)) {
+ if (level > Constants::QML_MIN_LEVEL && lastParent.contains(level-1))
parentEvent = lastParent[level-1];
- }
if (!eventDescription->parentHash.contains(parentEvent->eventHashStr)) {
QmlRangeEventRelative *newParentEvent = new QmlRangeEventRelative(parentEvent);
@@ -1165,9 +1161,8 @@ void QmlProfilerDataModel::QmlProfilerDataModelPrivate::redoTree(qint64 fromTime
lastParent[level] = eventDescription;
- if (level == Constants::QML_MIN_LEVEL) {
+ if (level == Constants::QML_MIN_LEVEL)
totalTime += duration;
- }
}
// fake rootEvent statistics
@@ -1363,42 +1358,42 @@ bool QmlProfilerDataModel::save(const QString &filename)
stream.setAutoFormatting(true);
stream.writeStartDocument();
- stream.writeStartElement("trace");
- stream.writeAttribute("version", Constants::PROFILER_FILE_VERSION);
+ stream.writeStartElement(QLatin1String("trace"));
+ stream.writeAttribute(QLatin1String("version"), QLatin1String(Constants::PROFILER_FILE_VERSION));
- stream.writeAttribute("traceStart", QString::number(traceStartTime()));
- stream.writeAttribute("traceEnd", QString::number(traceEndTime()));
+ stream.writeAttribute(QLatin1String("traceStart"), QString::number(traceStartTime()));
+ stream.writeAttribute(QLatin1String("traceEnd"), QString::number(traceEndTime()));
- stream.writeStartElement("eventData");
- stream.writeAttribute("totalTime", QString::number(d->qmlMeasuredTime));
+ stream.writeStartElement(QLatin1String("eventData"));
+ stream.writeAttribute(QLatin1String("totalTime"), QString::number(d->qmlMeasuredTime));
foreach (const QmlRangeEventData *eventData, d->rangeEventDictionary.values()) {
- stream.writeStartElement("event");
- stream.writeAttribute("index", QString::number(d->rangeEventDictionary.keys().indexOf(eventData->eventHashStr)));
- stream.writeTextElement("displayname", eventData->displayName);
- stream.writeTextElement("type", qmlEventTypeAsString(eventData->eventType));
+ stream.writeStartElement(QLatin1String("event"));
+ stream.writeAttribute(QLatin1String("index"), QString::number(d->rangeEventDictionary.keys().indexOf(eventData->eventHashStr)));
+ stream.writeTextElement(QLatin1String("displayname"), eventData->displayName);
+ stream.writeTextElement(QLatin1String("type"), qmlEventTypeAsString(eventData->eventType));
if (!eventData->location.filename.isEmpty()) {
- stream.writeTextElement("filename", eventData->location.filename);
- stream.writeTextElement("line", QString::number(eventData->location.line));
- stream.writeTextElement("column", QString::number(eventData->location.column));
+ stream.writeTextElement(QLatin1String("filename"), eventData->location.filename);
+ stream.writeTextElement(QLatin1String("line"), QString::number(eventData->location.line));
+ stream.writeTextElement(QLatin1String("column"), QString::number(eventData->location.column));
}
- stream.writeTextElement("details", eventData->details);
+ stream.writeTextElement(QLatin1String("details"), eventData->details);
if (eventData->eventType == Binding)
- stream.writeTextElement("bindingType", QString::number((int)eventData->bindingType));
+ stream.writeTextElement(QLatin1String("bindingType"), QString::number((int)eventData->bindingType));
stream.writeEndElement();
}
stream.writeEndElement(); // eventData
- stream.writeStartElement("profilerDataModel");
+ stream.writeStartElement(QLatin1String("profilerDataModel"));
foreach (const QmlRangeEventStartInstance &rangedEvent, d->startInstanceList) {
- stream.writeStartElement("range");
- stream.writeAttribute("startTime", QString::number(rangedEvent.startTime));
- stream.writeAttribute("duration", QString::number(rangedEvent.duration));
- stream.writeAttribute("eventIndex", QString::number(d->rangeEventDictionary.keys().indexOf(rangedEvent.statsInfo->eventHashStr)));
+ stream.writeStartElement(QLatin1String("range"));
+ stream.writeAttribute(QLatin1String("startTime"), QString::number(rangedEvent.startTime));
+ stream.writeAttribute(QLatin1String("duration"), QString::number(rangedEvent.duration));
+ stream.writeAttribute(QLatin1String("eventIndex"), QString::number(d->rangeEventDictionary.keys().indexOf(rangedEvent.statsInfo->eventHashStr)));
if (rangedEvent.statsInfo->eventType == QmlDebug::Painting && rangedEvent.animationCount >= 0) {
// animation frame
- stream.writeAttribute("framerate", QString::number(rangedEvent.frameRate));
- stream.writeAttribute("animationcount", QString::number(rangedEvent.animationCount));
+ stream.writeAttribute(QLatin1String("framerate"), QString::number(rangedEvent.frameRate));
+ stream.writeAttribute(QLatin1String("animationcount"), QString::number(rangedEvent.animationCount));
}
stream.writeEndElement();
}
@@ -1458,52 +1453,52 @@ void QmlProfilerDataModel::load()
switch (token) {
case QXmlStreamReader::StartDocument : continue;
case QXmlStreamReader::StartElement : {
- if (elementName == "trace") {
+ if (elementName == QLatin1String("trace")) {
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("version"))
- validVersion = attributes.value("version").toString() == Constants::PROFILER_FILE_VERSION;
+ if (attributes.hasAttribute(QLatin1String("version")))
+ validVersion = attributes.value(QLatin1String("version")).toString() == QLatin1String(Constants::PROFILER_FILE_VERSION);
else
validVersion = false;
- if (attributes.hasAttribute("traceStart"))
- setTraceStartTime(attributes.value("traceStart").toString().toLongLong());
- if (attributes.hasAttribute("traceEnd"))
- setTraceEndTime(attributes.value("traceEnd").toString().toLongLong());
+ if (attributes.hasAttribute(QLatin1String("traceStart")))
+ setTraceStartTime(attributes.value(QLatin1String("traceStart")).toString().toLongLong());
+ if (attributes.hasAttribute(QLatin1String("traceEnd")))
+ setTraceEndTime(attributes.value(QLatin1String("traceEnd")).toString().toLongLong());
}
- if (elementName == "eventData") {
+ if (elementName == QLatin1String("eventData")) {
readingQmlEvents = true;
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("totalTime"))
- d->qmlMeasuredTime = attributes.value("totalTime").toString().toDouble();
+ if (attributes.hasAttribute(QLatin1String("totalTime")))
+ d->qmlMeasuredTime = attributes.value(QLatin1String("totalTime")).toString().toDouble();
break;
}
- if (elementName == "v8profile" && !readingQmlEvents) {
+ if (elementName == QLatin1String("v8profile") && !readingQmlEvents) {
d->v8DataModel->load(stream);
break;
}
- if (elementName == "trace") {
+ if (elementName == QLatin1String("trace")) {
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("traceStart"))
- setTraceStartTime(attributes.value("traceStart").toString().toLongLong());
- if (attributes.hasAttribute("traceEnd"))
- setTraceEndTime(attributes.value("traceEnd").toString().toLongLong());
+ if (attributes.hasAttribute(QLatin1String("traceStart")))
+ setTraceStartTime(attributes.value(QLatin1String("traceStart")).toString().toLongLong());
+ if (attributes.hasAttribute(QLatin1String("traceEnd")))
+ setTraceEndTime(attributes.value(QLatin1String("traceEnd")).toString().toLongLong());
}
- if (elementName == "range") {
+ if (elementName == QLatin1String("range")) {
QmlRangeEventStartInstance rangedEvent;
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("startTime"))
- rangedEvent.startTime = attributes.value("startTime").toString().toLongLong();
- if (attributes.hasAttribute("duration"))
- rangedEvent.duration = attributes.value("duration").toString().toLongLong();
- if (attributes.hasAttribute("framerate"))
- rangedEvent.frameRate = attributes.value("framerate").toString().toInt();
- if (attributes.hasAttribute("animationcount"))
- rangedEvent.animationCount = attributes.value("animationcount").toString().toInt();
+ if (attributes.hasAttribute(QLatin1String("startTime")))
+ rangedEvent.startTime = attributes.value(QLatin1String("startTime")).toString().toLongLong();
+ if (attributes.hasAttribute(QLatin1String("duration")))
+ rangedEvent.duration = attributes.value(QLatin1String("duration")).toString().toLongLong();
+ if (attributes.hasAttribute(QLatin1String("framerate")))
+ rangedEvent.frameRate = attributes.value(QLatin1String("framerate")).toString().toInt();
+ if (attributes.hasAttribute(QLatin1String("animationcount")))
+ rangedEvent.animationCount = attributes.value(QLatin1String("animationcount")).toString().toInt();
else
rangedEvent.animationCount = -1;
- if (attributes.hasAttribute("eventIndex")) {
- int ndx = attributes.value("eventIndex").toString().toInt();
+ if (attributes.hasAttribute(QLatin1String("eventIndex"))) {
+ int ndx = attributes.value(QLatin1String("eventIndex")).toString().toInt();
if (!descriptionBuffer.value(ndx))
descriptionBuffer[ndx] = new QmlRangeEventData;
rangedEvent.statsInfo = descriptionBuffer.value(ndx);
@@ -1524,10 +1519,10 @@ void QmlProfilerDataModel::load()
}
if (readingQmlEvents) {
- if (elementName == "event") {
+ if (elementName == QLatin1String("event")) {
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("index")) {
- int ndx = attributes.value("index").toString().toInt();
+ if (attributes.hasAttribute(QLatin1String("index"))) {
+ int ndx = attributes.value(QLatin1String("index")).toString().toInt();
if (!descriptionBuffer.value(ndx))
descriptionBuffer[ndx] = new QmlRangeEventData;
currentEvent = descriptionBuffer[ndx];
@@ -1548,30 +1543,29 @@ void QmlProfilerDataModel::load()
break;
QString readData = stream.text().toString();
- if (elementName == "displayname") {
+ if (elementName == QLatin1String("displayname")) {
currentEvent->displayName = readData;
break;
}
- if (elementName == "type") {
+ if (elementName == QLatin1String("type")) {
currentEvent->eventType = qmlEventTypeAsEnum(readData);
break;
}
- if (elementName == "filename") {
+ if (elementName == QLatin1String("filename")) {
currentEvent->location.filename = readData;
break;
}
- if (elementName == "line") {
+ if (elementName == QLatin1String("line")) {
currentEvent->location.line = readData.toInt();
break;
}
- if (elementName == "column") {
+ if (elementName == QLatin1String("column"))
currentEvent->location.column = readData.toInt();
- }
- if (elementName == "details") {
+ if (elementName == QLatin1String("details")) {
currentEvent->details = readData;
break;
}
- if (elementName == "bindingType") {
+ if (elementName == QLatin1String("bindingType")) {
currentEvent->bindingType = readData.toInt();
break;
}
@@ -1579,11 +1573,11 @@ void QmlProfilerDataModel::load()
break;
}
case QXmlStreamReader::EndElement : {
- if (elementName == "event") {
+ if (elementName == QLatin1String("event")) {
currentEvent = 0;
break;
}
- if (elementName == "eventData") {
+ if (elementName == QLatin1String("eventData")) {
readingQmlEvents = false;
break;
}
diff --git a/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp b/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp
index 164c6c2419..2385e42c1c 100644
--- a/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerdetailsrewriter.cpp
@@ -77,9 +77,8 @@ protected:
virtual bool preVisit(QmlJS::AST::Node *node)
{
- if (QmlJS::AST::cast<QmlJS::AST::UiQualifiedId *>(node)) {
+ if (QmlJS::AST::cast<QmlJS::AST::UiQualifiedId *>(node))
return false;
- }
return containsLocation(node->firstSourceLocation(), node->lastSourceLocation());
}
@@ -130,7 +129,7 @@ void QmlProfilerDetailsRewriter::requestDetailsForLocation(int type,
QFileInfo fileInfo(localFile);
if (!fileInfo.exists() || !fileInfo.isReadable())
return;
- if (QmlJSTools::languageOfFile(localFile) != QmlJS::Document::QmlLanguage)
+ if (!QmlJS::Document::isQmlLikeLanguage(QmlJSTools::languageOfFile(localFile)))
return;
PendingEvent ev = {location, localFile, type};
@@ -167,7 +166,7 @@ void QmlProfilerDetailsRewriter::rewriteDetailsForLocation(QTextStream &textDoc,
qint64 len = node->lastSourceLocation().end() - startPos;
textDoc.seek(startPos);
- QString details = textDoc.read(len).replace('\n'," ").simplified();
+ QString details = textDoc.read(len).replace(QLatin1Char('\n'), QLatin1Char(' ')).simplified();
emit rewriteDetailsString(type, location, details);
}
diff --git a/src/plugins/qmlprofiler/qmlprofilerengine.cpp b/src/plugins/qmlprofiler/qmlprofilerengine.cpp
index 1af282f4da..eb50233c55 100644
--- a/src/plugins/qmlprofiler/qmlprofilerengine.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerengine.cpp
@@ -39,7 +39,7 @@
#include <qmlprojectmanager/qmlprojectrunconfiguration.h>
#include <qmlprojectmanager/qmlprojectplugin.h>
#include <projectexplorer/localapplicationruncontrol.h>
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <qmldebug/qmloutputparser.h>
#include <remotelinux/remotelinuxrunconfiguration.h>
@@ -304,8 +304,8 @@ void QmlProfilerEngine::wrongSetupMessageBoxFinished(int button)
{
if (button == QMessageBox::Help) {
Core::HelpManager *helpManager = Core::HelpManager::instance();
- helpManager->handleHelpRequest("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"
- "#setting-up-qml-debugging");
+ helpManager->handleHelpRequest(QLatin1String("qthelp://com.nokia.qtcreator/doc/creator-debugging-qml.html"
+ "#setting-up-qml-debugging"));
}
}
@@ -341,16 +341,14 @@ void QmlProfilerEngine::processIsRunning(quint16 port)
void QmlProfilerEngine::registerProfilerStateManager( QmlProfilerStateManager *profilerState )
{
// disconnect old
- if (d->m_profilerState) {
+ if (d->m_profilerState)
disconnect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
- }
d->m_profilerState = profilerState;
// connect
- if (d->m_profilerState) {
+ if (d->m_profilerState)
connect(d->m_profilerState, SIGNAL(stateChanged()), this, SLOT(profilerStateChanged()));
- }
}
void QmlProfilerEngine::profilerStateChanged()
diff --git a/src/plugins/qmlprofiler/qmlprofilereventview.cpp b/src/plugins/qmlprofiler/qmlprofilereventview.cpp
index 224ae7f88f..d04a0203e0 100644
--- a/src/plugins/qmlprofiler/qmlprofilereventview.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilereventview.cpp
@@ -117,7 +117,7 @@ QmlProfilerEventsWidget::QmlProfilerEventsWidget(QWidget *parent,
QmlProfilerDataModel *profilerDataModel )
: QWidget(parent), d(new QmlProfilerEventsWidgetPrivate(this))
{
- setObjectName("QmlProfilerEventsView");
+ setObjectName(QLatin1String("QmlProfilerEventsView"));
d->m_profilerDataModel = profilerDataModel;
connect(d->m_profilerDataModel, SIGNAL(stateChanged()),
@@ -171,15 +171,14 @@ void QmlProfilerEventsWidget::profilerDataModelStateChanged()
{
if (d->m_profilerDataModel) {
QmlProfilerDataModel::State newState = d->m_profilerDataModel->currentState();
- if (newState == QmlProfilerDataModel::Empty) {
+ if (newState == QmlProfilerDataModel::Empty)
clear();
- }
}
}
void QmlProfilerEventsWidget::switchToV8View()
{
- setObjectName("QmlProfilerV8ProfileView");
+ setObjectName(QLatin1String("QmlProfilerV8ProfileView"));
d->m_eventTree->setViewType(QmlProfilerEventsMainView::V8ProfileView);
d->m_eventParents->setViewType(QmlProfilerEventsParentsAndChildrenView::V8ParentsView);
d->m_eventChildren->setViewType(QmlProfilerEventsParentsAndChildrenView::V8ChildrenView);
@@ -368,7 +367,7 @@ QmlProfilerEventsMainView::QmlProfilerEventsMainView(ViewTypes viewType,
QmlProfilerDataModel *dataModel)
: QTreeView(parent), d(new QmlProfilerEventsMainViewPrivate(this))
{
- setObjectName("QmlProfilerEventsTable");
+ setObjectName(QLatin1String("QmlProfilerEventsTable"));
header()->setResizeMode(QHeaderView::Interactive);
header()->setDefaultSectionSize(100);
header()->setMinimumSectionSize(50);
@@ -430,7 +429,7 @@ void QmlProfilerEventsMainView::setViewType(ViewTypes type)
d->m_viewType = type;
switch (type) {
case EventsView: {
- setObjectName("QmlProfilerEventsTable");
+ setObjectName(QLatin1String("QmlProfilerEventsTable"));
setFieldViewable(Name, true);
setFieldViewable(Type, true);
setFieldViewable(Percent, true);
@@ -446,7 +445,7 @@ void QmlProfilerEventsMainView::setViewType(ViewTypes type)
break;
}
case V8ProfileView: {
- setObjectName("QmlProfilerV8ProfileTable");
+ setObjectName(QLatin1String("QmlProfilerV8ProfileTable"));
setFieldViewable(Name, true);
setFieldViewable(Type, false);
setFieldViewable(Percent, true);
@@ -601,9 +600,8 @@ void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildModelFrom
continue;
QList<QStandardItem *> newRow;
- if (m_fieldShown[Name]) {
+ if (m_fieldShown[Name])
newRow << new EventsViewItem(binding->displayName);
- }
if (m_fieldShown[Type]) {
QString typeString = QmlProfilerEventsMainView::nameForType(binding->eventType);
@@ -695,9 +693,8 @@ void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildV8ModelFr
QV8EventData *v8event = list.at(index);
QList<QStandardItem *> newRow;
- if (m_fieldShown[Name]) {
+ if (m_fieldShown[Name])
newRow << new EventsViewItem(v8event->displayName);
- }
if (m_fieldShown[Percent]) {
newRow << new EventsViewItem(QString::number(v8event->totalPercent,'f',2)+QLatin1String(" %"));
@@ -730,7 +727,7 @@ void QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::buildV8ModelFr
item->setEditable(false);
// metadata
- newRow.at(0)->setData(QString("%1:%2").arg(v8event->filename, QString::number(v8event->line)), EventHashStrRole);
+ newRow.at(0)->setData(QString::fromLatin1("%1:%2").arg(v8event->filename, QString::number(v8event->line)), EventHashStrRole);
newRow.at(0)->setData(QVariant(v8event->filename), FilenameRole);
newRow.at(0)->setData(QVariant(v8event->line), LineRole);
newRow.at(0)->setData(QVariant(0),ColumnRole); // v8 events have no column info
@@ -813,9 +810,8 @@ void QmlProfilerEventsMainView::jumpToItem(const QModelIndex &index)
emit eventSelected(infoItem->data(EventIdRole).toInt());
// show in timelinerenderer
- if (d->m_viewType == EventsView) {
+ if (d->m_viewType == EventsView)
emit showEventInTimeline(infoItem->data(EventIdRole).toInt());
- }
d->m_preventSelectBounce = false;
}
@@ -880,7 +876,7 @@ QString QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::textForItem
// indentation
QStandardItem *itemParent = item->parent();
while (itemParent) {
- str += " ";
+ str += QLatin1String(" ");
itemParent = itemParent->parent();
}
}
@@ -890,9 +886,9 @@ QString QmlProfilerEventsMainView::QmlProfilerEventsMainViewPrivate::textForItem
for (int j = 0; j < colCount; ++j) {
QStandardItem *colItem = item->parent() ? item->parent()->child(item->row(),j) : m_model->item(item->row(),j);
str += colItem->data(Qt::DisplayRole).toString();
- if (j < colCount-1) str += '\t';
+ if (j < colCount-1) str += QLatin1Char('\t');
}
- str += '\n';
+ str += QLatin1Char('\n');
// recursively print children
if (recursive && item->child(0))
@@ -910,9 +906,9 @@ void QmlProfilerEventsMainView::copyTableToClipboard() const
for (int i = 0; i < columnCount; ++i) {
str += d->m_model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
if (i < columnCount - 1)
- str += '\t';
+ str += QLatin1Char('\t');
else
- str += '\n';
+ str += QLatin1Char('\n');
}
// data
int rowCount = d->m_model->rowCount();
diff --git a/src/plugins/qmlprofiler/qmlprofilerstatemanager.cpp b/src/plugins/qmlprofiler/qmlprofilerstatemanager.cpp
index 1597654946..953ed9852f 100644
--- a/src/plugins/qmlprofiler/qmlprofilerstatemanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerstatemanager.cpp
@@ -40,14 +40,14 @@ namespace Internal {
inline QString stringForState(int state) {
switch (state) {
- case QmlProfilerStateManager::Idle: return QString("Idle");
- case QmlProfilerStateManager::AppStarting: return QString("AppStarting");
- case QmlProfilerStateManager::AppRunning: return QString("AppRunning");
- case QmlProfilerStateManager::AppStopRequested: return QString("AppStopRequested");
- case QmlProfilerStateManager::AppReadyToStop: return QString("AppReadyToStop");
- case QmlProfilerStateManager::AppStopped: return QString("AppStopped");
- case QmlProfilerStateManager::AppDying: return QString("AppDying");
- case QmlProfilerStateManager::AppKilled: return QString("AppKilled");
+ case QmlProfilerStateManager::Idle: return QLatin1String("Idle");
+ case QmlProfilerStateManager::AppStarting: return QLatin1String("AppStarting");
+ case QmlProfilerStateManager::AppRunning: return QLatin1String("AppRunning");
+ case QmlProfilerStateManager::AppStopRequested: return QLatin1String("AppStopRequested");
+ case QmlProfilerStateManager::AppReadyToStop: return QLatin1String("AppReadyToStop");
+ case QmlProfilerStateManager::AppStopped: return QLatin1String("AppStopped");
+ case QmlProfilerStateManager::AppDying: return QLatin1String("AppDying");
+ case QmlProfilerStateManager::AppKilled: return QLatin1String("AppKilled");
default: break;
}
return QString();
diff --git a/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp b/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
index 25400b68a0..cf46cbeeb1 100644
--- a/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerstatewidget.cpp
@@ -66,7 +66,7 @@ QmlProfilerStateWidget::QmlProfilerStateWidget(QmlProfilerStateManager *stateMan
QmlProfilerDataModel *dataModel, QWidget *parent) :
QWidget(parent), d(new QmlProfilerStateWidgetPrivate(this))
{
- setObjectName("QML Profiler State Display");
+ setObjectName(QLatin1String("QML Profiler State Display"));
// UI elements
QVBoxLayout *layout = new QVBoxLayout(this);
diff --git a/src/plugins/qmlprofiler/qmlprofilertool.cpp b/src/plugins/qmlprofiler/qmlprofilertool.cpp
index 71f51c950a..450a2536d1 100644
--- a/src/plugins/qmlprofiler/qmlprofilertool.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertool.cpp
@@ -52,7 +52,7 @@
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/session.h>
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <remotelinux/remotelinuxrunconfiguration.h>
#include <remotelinux/linuxdevice.h>
@@ -123,7 +123,7 @@ public:
QmlProfilerTool::QmlProfilerTool(QObject *parent)
: IAnalyzerTool(parent), d(new QmlProfilerToolPrivate(this))
{
- setObjectName("QmlProfilerTool");
+ setObjectName(QLatin1String("QmlProfilerTool"));
d->m_profilerState = 0;
d->m_viewContainer = 0;
@@ -199,7 +199,7 @@ QmlProfilerTool::~QmlProfilerTool()
Core::Id QmlProfilerTool::id() const
{
- return "QmlProfiler";
+ return Core::Id("QmlProfiler");
}
RunMode QmlProfilerTool::runMode() const
@@ -250,9 +250,8 @@ IAnalyzerEngine *QmlProfilerTool::createEngine(const AnalyzerStartParameters &sp
}
// FIXME: Check that there's something sensible in sp.connParams
- if (isTcpConnection) {
+ if (isTcpConnection)
d->m_profilerConnections->setTcpConnection(sp.connParams.host, sp.connParams.port);
- }
d->m_runConfiguration = runConfiguration;
@@ -404,9 +403,8 @@ void QmlProfilerTool::populateFileFinder(QString projectDirectory, QString activ
sourceFiles << project->files(Project::ExcludeGeneratedFiles);
if (!projects.isEmpty()) {
- if (projectDirectory.isEmpty()) {
+ if (projectDirectory.isEmpty())
projectDirectory = projects.first()->projectDirectory();
- }
if (activeSysroot.isEmpty()) {
if (Target *target = projects.first()->activeTarget())
@@ -589,7 +587,8 @@ void QmlProfilerTool::showSaveOption()
void QmlProfilerTool::showSaveDialog()
{
- QString filename = QFileDialog::getSaveFileName(Core::ICore::mainWindow(), tr("Save QML Trace"), QString(), tr("QML traces (*%1)").arg(TraceFileExtension));
+ QString filename = QFileDialog::getSaveFileName(Core::ICore::mainWindow(), tr("Save QML Trace"), QString(),
+ tr("QML traces (*%1)").arg(QLatin1String(TraceFileExtension)));
if (!filename.isEmpty()) {
if (!filename.endsWith(QLatin1String(TraceFileExtension)))
filename += QLatin1String(TraceFileExtension);
@@ -605,7 +604,8 @@ void QmlProfilerTool::showLoadDialog()
if (AnalyzerManager::currentSelectedTool() != this)
AnalyzerManager::selectTool(this, StartRemote);
- QString filename = QFileDialog::getOpenFileName(Core::ICore::mainWindow(), tr("Load QML Trace"), QString(), tr("QML traces (*%1)").arg(TraceFileExtension));
+ QString filename = QFileDialog::getOpenFileName(Core::ICore::mainWindow(), tr("Load QML Trace"), QString(),
+ tr("QML traces (*%1)").arg(QLatin1String(TraceFileExtension)));
if (!filename.isEmpty()) {
// delayed load (prevent graphical artifacts due to long load time)
@@ -709,9 +709,8 @@ void QmlProfilerTool::clientRecordingChanged()
{
// if application is running, display server record changes
// if application is stopped, display client record changes
- if (d->m_profilerState->currentState() != QmlProfilerStateManager::AppRunning) {
+ if (d->m_profilerState->currentState() != QmlProfilerStateManager::AppRunning)
setRecording(d->m_profilerState->clientRecording());
- }
}
void QmlProfilerTool::serverRecordingChanged()
diff --git a/src/plugins/qmlprofiler/qmlprofilertraceview.cpp b/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
index 44e9bde444..5fbad1247a 100644
--- a/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilertraceview.cpp
@@ -132,7 +132,7 @@ public:
QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerTool *profilerTool, QmlProfilerViewManager *container, QmlProfilerDataModel *model, QmlProfilerStateManager *profilerState)
: QWidget(parent), d(new QmlProfilerTraceViewPrivate(this))
{
- setObjectName("QML Profiler");
+ setObjectName(QLatin1String("QML Profiler"));
d->m_zoomControl = new ZoomControl(this);
connect(d->m_zoomControl, SIGNAL(rangeChanged()), this, SLOT(updateRange()));
@@ -183,9 +183,9 @@ QmlProfilerTraceView::QmlProfilerTraceView(QWidget *parent, Analyzer::IAnalyzerT
d->m_profilerDataModel = model;
connect(d->m_profilerDataModel, SIGNAL(stateChanged()),
this, SLOT(profilerDataModelStateChanged()));
- d->m_mainView->rootContext()->setContextProperty("qmlProfilerDataModel",
+ d->m_mainView->rootContext()->setContextProperty(QLatin1String("qmlProfilerDataModel"),
d->m_profilerDataModel);
- d->m_overview->rootContext()->setContextProperty("qmlProfilerDataModel",
+ d->m_overview->rootContext()->setContextProperty(QLatin1String("qmlProfilerDataModel"),
d->m_profilerDataModel);
d->m_profilerState = profilerState;
@@ -210,25 +210,26 @@ QmlProfilerTraceView::~QmlProfilerTraceView()
// Initialize widgets
void QmlProfilerTraceView::reset()
{
- d->m_mainView->rootContext()->setContextProperty("zoomControl", d->m_zoomControl);
- d->m_timebar->rootContext()->setContextProperty("zoomControl", d->m_zoomControl);
- d->m_overview->rootContext()->setContextProperty("zoomControl", d->m_zoomControl);
+ d->m_mainView->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
+ d->m_timebar->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
+ d->m_overview->rootContext()->setContextProperty(QLatin1String("zoomControl"), d->m_zoomControl);
- d->m_timebar->setSource(QUrl("qrc:/qmlprofiler/TimeDisplay.qml"));
- d->m_overview->setSource(QUrl("qrc:/qmlprofiler/Overview.qml"));
+ d->m_timebar->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/TimeDisplay.qml")));
+ d->m_overview->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/Overview.qml")));
- d->m_mainView->setSource(QUrl("qrc:/qmlprofiler/MainView.qml"));
- d->m_mainView->rootObject()->setProperty("width", QVariant(width()));
- d->m_mainView->rootObject()->setProperty("candidateHeight", QVariant(height() - d->m_timebar->height() - d->m_overview->height()));
+ d->m_mainView->setSource(QUrl(QLatin1String("qrc:/qmlprofiler/MainView.qml")));
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ rootObject->setProperty("width", QVariant(width()));
+ rootObject->setProperty("candidateHeight", QVariant(height() - d->m_timebar->height() - d->m_overview->height()));
- connect(d->m_mainView->rootObject(), SIGNAL(updateCursorPosition()), this, SLOT(updateCursorPosition()));
- connect(d->m_mainView->rootObject(), SIGNAL(updateRangeButton()), this, SLOT(updateRangeButton()));
- connect(d->m_mainView->rootObject(), SIGNAL(updateLockButton()), this, SLOT(updateLockButton()));
- connect(this, SIGNAL(jumpToPrev()), d->m_mainView->rootObject(), SLOT(prevEvent()));
- connect(this, SIGNAL(jumpToNext()), d->m_mainView->rootObject(), SLOT(nextEvent()));
- connect(d->m_mainView->rootObject(), SIGNAL(selectedEventChanged(int)), this, SIGNAL(selectedEventChanged(int)));
- connect(d->m_mainView->rootObject(), SIGNAL(changeToolTip(QString)), this, SLOT(updateToolTip(QString)));
- connect(d->m_mainView->rootObject(), SIGNAL(updateVerticalScroll(int)), this, SLOT(updateVerticalScroll(int)));
+ connect(rootObject, SIGNAL(updateCursorPosition()), this, SLOT(updateCursorPosition()));
+ connect(rootObject, SIGNAL(updateRangeButton()), this, SLOT(updateRangeButton()));
+ connect(rootObject, SIGNAL(updateLockButton()), this, SLOT(updateLockButton()));
+ connect(this, SIGNAL(jumpToPrev()), rootObject, SLOT(prevEvent()));
+ connect(this, SIGNAL(jumpToNext()), rootObject, SLOT(nextEvent()));
+ connect(rootObject, SIGNAL(selectedEventChanged(int)), this, SIGNAL(selectedEventChanged(int)));
+ connect(rootObject, SIGNAL(changeToolTip(QString)), this, SLOT(updateToolTip(QString)));
+ connect(rootObject, SIGNAL(updateVerticalScroll(int)), this, SLOT(updateVerticalScroll(int)));
}
QWidget *QmlProfilerTraceView::createToolbar()
@@ -244,19 +245,19 @@ QWidget *QmlProfilerTraceView::createToolbar()
toolBarLayout->setSpacing(0);
QToolButton *buttonPrev= new QToolButton;
- buttonPrev->setIcon(QIcon(":/qmlprofiler/ico_prev.png"));
+ buttonPrev->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_prev.png")));
buttonPrev->setToolTip(tr("Jump to previous event"));
connect(buttonPrev, SIGNAL(clicked()), this, SIGNAL(jumpToPrev()));
connect(this, SIGNAL(enableToolbar(bool)), buttonPrev, SLOT(setEnabled(bool)));
QToolButton *buttonNext= new QToolButton;
- buttonNext->setIcon(QIcon(":/qmlprofiler/ico_next.png"));
+ buttonNext->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_next.png")));
buttonNext->setToolTip(tr("Jump to next event"));
connect(buttonNext, SIGNAL(clicked()), this, SIGNAL(jumpToNext()));
connect(this, SIGNAL(enableToolbar(bool)), buttonNext, SLOT(setEnabled(bool)));
QToolButton *buttonZoomControls = new QToolButton;
- buttonZoomControls->setIcon(QIcon(":/qmlprofiler/ico_zoom.png"));
+ buttonZoomControls->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_zoom.png")));
buttonZoomControls->setToolTip(tr("Show zoom slider"));
buttonZoomControls->setCheckable(true);
buttonZoomControls->setChecked(false);
@@ -264,7 +265,7 @@ QWidget *QmlProfilerTraceView::createToolbar()
connect(this, SIGNAL(enableToolbar(bool)), buttonZoomControls, SLOT(setEnabled(bool)));
d->m_buttonRange = new QToolButton;
- d->m_buttonRange->setIcon(QIcon(":/qmlprofiler/ico_rangeselection.png"));
+ d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselection.png")));
d->m_buttonRange->setToolTip(tr("Select range"));
d->m_buttonRange->setCheckable(true);
d->m_buttonRange->setChecked(false);
@@ -273,7 +274,7 @@ QWidget *QmlProfilerTraceView::createToolbar()
connect(this, SIGNAL(rangeModeChanged(bool)), d->m_buttonRange, SLOT(setChecked(bool)));
d->m_buttonLock = new QToolButton;
- d->m_buttonLock->setIcon(QIcon(":/qmlprofiler/ico_selectionmode.png"));
+ d->m_buttonLock->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_selectionmode.png")));
d->m_buttonLock->setToolTip(tr("View event information on mouseover"));
d->m_buttonLock->setCheckable(true);
d->m_buttonLock->setChecked(false);
@@ -313,7 +314,7 @@ QWidget *QmlProfilerTraceView::createZoomToolbar()
connect(this, SIGNAL(enableToolbar(bool)), zoomSlider, SLOT(setEnabled(bool)));
connect(zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setZoomLevel(int)));
connect(this, SIGNAL(zoomLevelChanged(int)), zoomSlider, SLOT(setValue(int)));
- zoomSlider->setStyleSheet("\
+ zoomSlider->setStyleSheet(QLatin1String("\
QSlider:horizontal {\
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #444444, stop: 1 #5a5a5a);\
border: 1px #313131;\
@@ -328,7 +329,7 @@ QWidget *QmlProfilerTraceView::createZoomToolbar()
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #5a5a5a, stop: 1 #444444);\
border: 1px #313131;\
}\
- ");
+ "));
toolBarLayout->addWidget(zoomSlider);
@@ -338,25 +339,25 @@ QWidget *QmlProfilerTraceView::createZoomToolbar()
/////////////////////////////////////////////////////////
bool QmlProfilerTraceView::hasValidSelection() const
{
- if (d->m_mainView->rootObject()) {
- return d->m_mainView->rootObject()->property("selectionRangeReady").toBool();
- }
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ return rootObject->property("selectionRangeReady").toBool();
return false;
}
qint64 QmlProfilerTraceView::selectionStart() const
{
- if (d->m_mainView->rootObject()) {
- return d->m_mainView->rootObject()->property("selectionRangeStart").toLongLong();
- }
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ return rootObject->property("selectionRangeStart").toLongLong();
return 0;
}
qint64 QmlProfilerTraceView::selectionEnd() const
{
- if (d->m_mainView->rootObject()) {
- return d->m_mainView->rootObject()->property("selectionRangeEnd").toLongLong();
- }
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ return rootObject->property("selectionRangeEnd").toLongLong();
return 0;
}
@@ -373,8 +374,9 @@ void QmlProfilerTraceView::clearDisplay()
void QmlProfilerTraceView::selectNextEventWithId(int eventId)
{
- if (d->m_mainView->rootObject())
- QMetaObject::invokeMethod(d->m_mainView->rootObject(), "selectNextWithId",
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ QMetaObject::invokeMethod(rootObject, "selectNextWithId",
Q_ARG(QVariant,QVariant(eventId)));
}
@@ -382,22 +384,24 @@ void QmlProfilerTraceView::selectNextEventWithId(int eventId)
// Goto source location
void QmlProfilerTraceView::updateCursorPosition()
{
- emit gotoSourceLocation(d->m_mainView->rootObject()->property("fileName").toString(),
- d->m_mainView->rootObject()->property("lineNumber").toInt(),
- d->m_mainView->rootObject()->property("columnNumber").toInt());
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ emit gotoSourceLocation(rootObject->property("fileName").toString(),
+ rootObject->property("lineNumber").toInt(),
+ rootObject->property("columnNumber").toInt());
}
/////////////////////////////////////////////////////////
// Toolbar buttons
void QmlProfilerTraceView::toggleRangeMode(bool active)
{
- bool rangeMode = d->m_mainView->rootObject()->property("selectionRangeMode").toBool();
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ bool rangeMode = rootObject->property("selectionRangeMode").toBool();
if (active != rangeMode) {
if (active)
- d->m_buttonRange->setIcon(QIcon(":/qmlprofiler/ico_rangeselected.png"));
+ d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselected.png")));
else
- d->m_buttonRange->setIcon(QIcon(":/qmlprofiler/ico_rangeselection.png"));
- d->m_mainView->rootObject()->setProperty("selectionRangeMode", QVariant(active));
+ d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselection.png")));
+ rootObject->setProperty("selectionRangeMode", QVariant(active));
}
}
@@ -405,18 +409,19 @@ void QmlProfilerTraceView::updateRangeButton()
{
bool rangeMode = d->m_mainView->rootObject()->property("selectionRangeMode").toBool();
if (rangeMode)
- d->m_buttonRange->setIcon(QIcon(":/qmlprofiler/ico_rangeselected.png"));
+ d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselected.png")));
else
- d->m_buttonRange->setIcon(QIcon(":/qmlprofiler/ico_rangeselection.png"));
+ d->m_buttonRange->setIcon(QIcon(QLatin1String(":/qmlprofiler/ico_rangeselection.png")));
emit rangeModeChanged(rangeMode);
}
void QmlProfilerTraceView::toggleLockMode(bool active)
{
- bool lockMode = !d->m_mainView->rootObject()->property("selectionLocked").toBool();
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ bool lockMode = !rootObject->property("selectionLocked").toBool();
if (active != lockMode) {
- d->m_mainView->rootObject()->setProperty("selectionLocked", QVariant(!active));
- d->m_mainView->rootObject()->setProperty("selectedItem", QVariant(-1));
+ rootObject->setProperty("selectionLocked", QVariant(!active));
+ rootObject->setProperty("selectedItem", QVariant(-1));
}
}
@@ -456,8 +461,9 @@ void QmlProfilerTraceView::updateRange()
void QmlProfilerTraceView::mouseWheelMoved(int mouseX, int mouseY, int wheelDelta)
{
Q_UNUSED(mouseY);
- if (d->m_mainView->rootObject()) {
- QMetaObject::invokeMethod(d->m_mainView->rootObject(), "wheelZoom",
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject) {
+ QMetaObject::invokeMethod(rootObject, "wheelZoom",
Q_ARG(QVariant, QVariant(mouseX)),
Q_ARG(QVariant, QVariant(wheelDelta)));
}
@@ -476,10 +482,11 @@ void QmlProfilerTraceView::updateVerticalScroll(int newPosition)
void QmlProfilerTraceView::resizeEvent(QResizeEvent *event)
{
QWidget::resizeEvent(event);
- if (d->m_mainView->rootObject()) {
- d->m_mainView->rootObject()->setProperty("width", QVariant(event->size().width()));
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject) {
+ rootObject->setProperty("width", QVariant(event->size().width()));
int newHeight = event->size().height() - d->m_timebar->height() - d->m_overview->height();
- d->m_mainView->rootObject()->setProperty("candidateHeight", QVariant(newHeight));
+ rootObject->setProperty("candidateHeight", QVariant(newHeight));
}
emit resized();
}
@@ -490,35 +497,28 @@ void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
{
QMenu menu;
QAction *viewAllAction = 0;
- QAction *getLocalStatsAction = 0;
- QAction *getGlobalStatsAction = 0;
QmlProfilerTool *profilerTool = qobject_cast<QmlProfilerTool *>(d->m_profilerTool);
- QPoint position = ev->globalPos();
- if (profilerTool) {
- QList <QAction *> commonActions = profilerTool->profilerContextMenuActions();
- foreach (QAction *act, commonActions) {
- menu.addAction(act);
- }
- }
+ if (profilerTool)
+ menu.addActions(profilerTool->profilerContextMenuActions());
menu.addSeparator();
- getLocalStatsAction = menu.addAction(tr("Limit Events Pane to Current Range"));
+
+ QAction *getLocalStatsAction = menu.addAction(tr("Limit Events Pane to Current Range"));
if (!d->m_viewContainer->hasValidSelection())
getLocalStatsAction->setEnabled(false);
- getGlobalStatsAction = menu.addAction(tr("Reset Events Pane"));
+
+ QAction *getGlobalStatsAction = menu.addAction(tr("Reset Events Pane"));
if (d->m_viewContainer->hasGlobalStats())
getGlobalStatsAction->setEnabled(false);
-
if (d->m_profilerDataModel->count() > 0) {
menu.addSeparator();
viewAllAction = menu.addAction(tr("Reset Zoom"));
}
-
- QAction *selectedAction = menu.exec(position);
+ QAction *selectedAction = menu.exec(ev->globalPos());
if (selectedAction) {
if (selectedAction == viewAllAction) {
@@ -543,14 +543,16 @@ void QmlProfilerTraceView::contextMenuEvent(QContextMenuEvent *ev)
// Tell QML the state of the profiler
void QmlProfilerTraceView::setRecording(bool recording)
{
- if (d->m_mainView->rootObject())
- d->m_mainView->rootObject()->setProperty("recordingEnabled", QVariant(recording));
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ rootObject->setProperty("recordingEnabled", QVariant(recording));
}
void QmlProfilerTraceView::setAppKilled()
{
- if (d->m_mainView->rootObject())
- d->m_mainView->rootObject()->setProperty("appKilled",QVariant(true));
+ QGraphicsObject *rootObject = d->m_mainView->rootObject();
+ if (rootObject)
+ rootObject->setProperty("appKilled",QVariant(true));
}
////////////////////////////////////////////////////////////////
// Profiler State
diff --git a/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp b/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
index c3293abb47..9b9fa32e12 100644
--- a/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
+++ b/src/plugins/qmlprofiler/qmlprofilerviewmanager.cpp
@@ -65,7 +65,7 @@ QmlProfilerViewManager::QmlProfilerViewManager(QObject *parent,
QmlProfilerStateManager *profilerState)
: QObject(parent), d(new QmlProfilerViewManagerPrivate(this))
{
- setObjectName("QML Profiler View Manager");
+ setObjectName(QLatin1String("QML Profiler View Manager"));
d->traceView = 0;
d->eventsView = 0;
d->v8profilerView = 0;
diff --git a/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp b/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp
index 44a87b3cac..434b6247c9 100644
--- a/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp
+++ b/src/plugins/qmlprofiler/qv8profilerdatamodel.cpp
@@ -193,9 +193,8 @@ void QV8ProfilerDataModel::addV8Event(int depth,
parentEvent = &d->v8RootEvent;
d->v8MeasuredTime += totalTime;
}
- if (depth > 0 && d->v8parents.contains(depth-1)) {
+ if (depth > 0 && d->v8parents.contains(depth-1))
parentEvent = d->v8parents.value(depth-1);
- }
if (parentEvent != 0) {
if (!eventData->parentHash.contains(parentEvent->eventHashStr)) {
@@ -298,24 +297,24 @@ void QV8ProfilerDataModel::QV8ProfilerDataModelPrivate::clearV8RootEvent()
void QV8ProfilerDataModel::save(QXmlStreamWriter &stream)
{
- stream.writeStartElement("v8profile"); // v8 profiler output
- stream.writeAttribute("totalTime", QString::number(d->v8MeasuredTime));
+ stream.writeStartElement(QLatin1String("v8profile")); // v8 profiler output
+ stream.writeAttribute(QLatin1String("totalTime"), QString::number(d->v8MeasuredTime));
foreach (QV8EventData *v8event, d->v8EventHash.values()) {
- stream.writeStartElement("event");
- stream.writeAttribute("index",
+ stream.writeStartElement(QLatin1String("event"));
+ stream.writeAttribute(QLatin1String("index"),
QString::number(
d->v8EventHash.keys().indexOf(
v8event->eventHashStr)));
- stream.writeTextElement("displayname", v8event->displayName);
- stream.writeTextElement("functionname", v8event->functionName);
+ stream.writeTextElement(QLatin1String("displayname"), v8event->displayName);
+ stream.writeTextElement(QLatin1String("functionname"), v8event->functionName);
if (!v8event->filename.isEmpty()) {
- stream.writeTextElement("filename", v8event->filename);
- stream.writeTextElement("line", QString::number(v8event->line));
+ stream.writeTextElement(QLatin1String("filename"), v8event->filename);
+ stream.writeTextElement(QLatin1String("line"), QString::number(v8event->line));
}
- stream.writeTextElement("totalTime", QString::number(v8event->totalTime));
- stream.writeTextElement("selfTime", QString::number(v8event->selfTime));
+ stream.writeTextElement(QLatin1String("totalTime"), QString::number(v8event->totalTime));
+ stream.writeTextElement(QLatin1String("selfTime"), QString::number(v8event->selfTime));
if (!v8event->childrenHash.isEmpty()) {
- stream.writeStartElement("childrenEvents");
+ stream.writeStartElement(QLatin1String("childrenEvents"));
QStringList childrenIndexes;
QStringList childrenTimes;
QStringList parentTimes;
@@ -325,9 +324,9 @@ void QV8ProfilerDataModel::save(QXmlStreamWriter &stream)
parentTimes << QString::number(v8child->totalTime);
}
- stream.writeAttribute("list", childrenIndexes.join(QString(", ")));
- stream.writeAttribute("childrenTimes", childrenTimes.join(QString(", ")));
- stream.writeAttribute("parentTimes", parentTimes.join(QString(", ")));
+ stream.writeAttribute(QLatin1String("list"), childrenIndexes.join(QLatin1String(", ")));
+ stream.writeAttribute(QLatin1String("childrenTimes"), childrenTimes.join(QLatin1String(", ")));
+ stream.writeAttribute(QLatin1String("parentTimes"), parentTimes.join(QLatin1String(", ")));
stream.writeEndElement();
}
stream.writeEndElement();
@@ -349,8 +348,8 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
// get the v8 time
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("totalTime"))
- d->v8MeasuredTime = attributes.value("totalTime").toString().toDouble();
+ if (attributes.hasAttribute(QLatin1String("totalTime")))
+ d->v8MeasuredTime = attributes.value(QLatin1String("totalTime")).toString().toDouble();
while (!stream.atEnd() && !stream.hasError()) {
QXmlStreamReader::TokenType token = stream.readNext();
@@ -358,10 +357,10 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
switch (token) {
case QXmlStreamReader::StartDocument : continue;
case QXmlStreamReader::StartElement : {
- if (elementName == "event") {
+ if (elementName == QLatin1String("event")) {
QXmlStreamAttributes attributes = stream.attributes();
- if (attributes.hasAttribute("index")) {
- int ndx = attributes.value("index").toString().toInt();
+ if (attributes.hasAttribute(QLatin1String("index"))) {
+ int ndx = attributes.value(QLatin1String("index")).toString().toInt();
if (!v8eventBuffer.value(ndx))
v8eventBuffer[ndx] = new QV8EventData;
v8event = v8eventBuffer[ndx];
@@ -374,20 +373,19 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
if (!v8event)
break;
- if (elementName == "childrenEvents") {
+ if (elementName == QLatin1String("childrenEvents")) {
QXmlStreamAttributes attributes = stream.attributes();
int eventIndex = v8eventBuffer.key(v8event);
- if (attributes.hasAttribute("list")) {
+ if (attributes.hasAttribute(QLatin1String("list"))) {
// store for later parsing (we haven't read all the events yet)
- childrenIndexes[eventIndex] = attributes.value("list").toString();
+ childrenIndexes[eventIndex] = attributes.value(QLatin1String("list")).toString();
}
- if (attributes.hasAttribute("childrenTimes")) {
+ if (attributes.hasAttribute(QLatin1String("childrenTimes"))) {
childrenTimes[eventIndex] =
- attributes.value("childrenTimes").toString();
- }
- if (attributes.hasAttribute("parentTimes")) {
- parentTimes[eventIndex] = attributes.value("parentTimes").toString();
+ attributes.value(QLatin1String("childrenTimes")).toString();
}
+ if (attributes.hasAttribute(QLatin1String("parentTimes")))
+ parentTimes[eventIndex] = attributes.value(QLatin1String("parentTimes")).toString();
}
stream.readNext();
@@ -395,40 +393,40 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
break;
QString readData = stream.text().toString();
- if (elementName == "displayname") {
+ if (elementName == QLatin1String("displayname")) {
v8event->displayName = readData;
break;
}
- if (elementName == "functionname") {
+ if (elementName == QLatin1String("functionname")) {
v8event->functionName = readData;
break;
}
- if (elementName == "filename") {
+ if (elementName == QLatin1String("filename")) {
v8event->filename = readData;
break;
}
- if (elementName == "line") {
+ if (elementName == QLatin1String("line")) {
v8event->line = readData.toInt();
break;
}
- if (elementName == "totalTime") {
+ if (elementName == QLatin1String("totalTime")) {
v8event->totalTime = readData.toDouble();
cumulatedV8Time += v8event->totalTime;
break;
}
- if (elementName == "selfTime") {
+ if (elementName == QLatin1String("selfTime")) {
v8event->selfTime = readData.toDouble();
break;
}
break;
}
case QXmlStreamReader::EndElement : {
- if (elementName == "v8profile") {
+ if (elementName == QLatin1String("v8profile")) {
// done reading the v8 profile data
break;
}
@@ -443,20 +441,18 @@ void QV8ProfilerDataModel::load(QXmlStreamReader &stream)
// find v8events' children and parents
foreach (int parentIndex, childrenIndexes.keys()) {
- QStringList childrenStrings = childrenIndexes.value(parentIndex).split(",");
- QStringList childrenTimesStrings = childrenTimes.value(parentIndex).split(", ");
- QStringList parentTimesStrings = parentTimes.value(parentIndex).split(", ");
+ QStringList childrenStrings = childrenIndexes.value(parentIndex).split(QLatin1String(","));
+ QStringList childrenTimesStrings = childrenTimes.value(parentIndex).split(QLatin1String(", "));
+ QStringList parentTimesStrings = parentTimes.value(parentIndex).split(QLatin1String(", "));
for (int ndx = 0; ndx < childrenStrings.count(); ndx++) {
int childIndex = childrenStrings[ndx].toInt();
if (v8eventBuffer.value(childIndex)) {
QV8EventSub *newChild = new QV8EventSub(v8eventBuffer[childIndex]);
QV8EventSub *newParent = new QV8EventSub(v8eventBuffer[parentIndex]);
- if (childrenTimesStrings.count() > ndx) {
+ if (childrenTimesStrings.count() > ndx)
newChild->totalTime = childrenTimesStrings[ndx].toDouble();
- }
- if (parentTimesStrings.count() > ndx) {
+ if (parentTimesStrings.count() > ndx)
newParent->totalTime = parentTimesStrings[ndx].toDouble();
- }
v8eventBuffer[parentIndex]->childrenHash.insert(
newChild->reference->displayName,
newChild);
diff --git a/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp b/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp
index 0a02e904d0..c1419b9ec6 100644
--- a/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp
+++ b/src/plugins/qmlprojectmanager/fileformat/filefilteritems.cpp
@@ -129,11 +129,10 @@ bool FileFilterBaseItem::recursive() const
} else if (m_recurse == DoNotRecurse) {
recursive = false;
} else { // RecurseDefault
- if (m_explicitFiles.isEmpty()) {
+ if (m_explicitFiles.isEmpty())
recursive = true;
- } else {
+ else
recursive = false;
- }
}
return recursive;
}
@@ -142,11 +141,10 @@ void FileFilterBaseItem::setRecursive(bool recurse)
{
bool oldRecursive = recursive();
- if (recurse) {
+ if (recurse)
m_recurse = Recurse;
- } else {
+ else
m_recurse = DoNotRecurse;
- }
if (recurse != oldRecursive)
updateFileList();
@@ -204,11 +202,10 @@ QString FileFilterBaseItem::absolutePath(const QString &path) const
QString FileFilterBaseItem::absoluteDir() const
{
QString absoluteDir;
- if (QFileInfo(m_rootDir).isAbsolute()) {
+ if (QFileInfo(m_rootDir).isAbsolute())
absoluteDir = m_rootDir;
- } else if (!m_defaultDir.isEmpty()) {
+ else if (!m_defaultDir.isEmpty())
absoluteDir = m_defaultDir + QLatin1Char('/') + m_rootDir;
- }
return QDir::cleanPath(absoluteDir);
}
@@ -264,15 +261,13 @@ void FileFilterBaseItem::updateFileListNow()
bool FileFilterBaseItem::fileMatches(const QString &fileName) const
{
foreach (const QString &suffix, m_fileSuffixes) {
- if (fileName.endsWith(suffix, Qt::CaseInsensitive)) {
+ if (fileName.endsWith(suffix, Qt::CaseInsensitive))
return true;
- }
}
foreach (QRegExp filter, m_regExpList) {
- if (filter.exactMatch(fileName)) {
+ if (filter.exactMatch(fileName))
return true;
- }
}
return false;
@@ -325,7 +320,7 @@ ImageFileFilterItem::ImageFileFilterItem(QObject *parent)
// supported image formats according to
QList<QByteArray> extensions = QImageReader::supportedImageFormats();
foreach (const QByteArray &extension, extensions) {
- filter.append(QString("*.%1;").arg(QString::fromAscii(extension)));
+ filter.append(QString::fromLatin1("*.%1;").arg(QString::fromLatin1(extension)));
}
setFilter(filter);
}
diff --git a/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp b/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp
index feed9694be..7b6eef9e2a 100644
--- a/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp
+++ b/src/plugins/qmlprojectmanager/fileformat/qmlprojectitem.cpp
@@ -56,9 +56,8 @@ QList<QmlFileFilterItem*> QmlProjectItemPrivate::qmlFileFilters() const
for (int i = 0; i < content.size(); ++i) {
QmlProjectContentItem *contentElement = content.at(i);
QmlFileFilterItem *qmlFileFilter = qobject_cast<QmlFileFilterItem*>(contentElement);
- if (qmlFileFilter) {
+ if (qmlFileFilter)
qmlFilters << qmlFileFilter;
- }
}
return qmlFilters;
}
diff --git a/src/plugins/qmlprojectmanager/qmlapp.cpp b/src/plugins/qmlprojectmanager/qmlapp.cpp
new file mode 100644
index 0000000000..143aaa12cd
--- /dev/null
+++ b/src/plugins/qmlprojectmanager/qmlapp.cpp
@@ -0,0 +1,439 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlapp.h"
+
+
+#include <coreplugin/basefilewizard.h>
+#include <coreplugin/icore.h>
+#include <utils/fileutils.h>
+#include <utils/qtcassert.h>
+
+#include <QDebug>
+#include <QDir>
+#include <QTextStream>
+
+namespace QmlProjectManager {
+namespace Internal {
+
+static QStringList binaryFiles()
+{
+ static QStringList result;
+ if (result.isEmpty())
+ result << QLatin1String("png") << QLatin1String("jpg") << QLatin1String("jpeg");
+ return result;
+}
+
+QString QmlApp::templateRootDirectory()
+{
+ return Core::ICore::instance()->resourcePath() + QLatin1String("/templates/qml/");
+}
+
+TemplateInfo::TemplateInfo()
+ : priority(5)
+{
+}
+
+QmlApp::QmlApp(QObject *parent)
+ : QObject(parent)
+{
+}
+
+QmlApp::~QmlApp()
+{
+}
+
+QString QmlApp::mainQmlFileName() const
+{
+ return projectName() + QLatin1String(".qml");
+}
+
+void QmlApp::setProjectNameAndBaseDirectory(const QString &projectName, const QString &projectBaseDirectory)
+{
+ m_projectBaseDirectory = projectBaseDirectory;
+ m_projectName = projectName.trimmed();
+}
+
+QString QmlApp::projectDirectory() const
+{
+ return QDir::cleanPath(m_projectBaseDirectory + QLatin1Char('/') + m_projectName);
+}
+
+QString QmlApp::projectName() const
+{
+ return m_projectName;
+}
+
+void QmlApp::setTemplateInfo(const TemplateInfo &templateInfo)
+{
+ m_templateInfo = templateInfo;
+}
+
+QString QmlApp::creatorFileName() const
+{
+ return m_creatorFileName;
+}
+
+const TemplateInfo &QmlApp::templateInfo() const
+{
+ return m_templateInfo;
+}
+
+QString QmlApp::templateDirectory() const
+{
+ const QDir dir(templateRootDirectory() + m_templateInfo.templateName);
+ return QDir::cleanPath(dir.absolutePath());
+}
+
+QStringList QmlApp::templateNames()
+{
+ QStringList templateNameList;
+ const QDir templateRoot(templateRootDirectory());
+
+ foreach (const QFileInfo &subDirectory,
+ templateRoot.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
+ templateNameList.append(subDirectory.fileName());
+
+ return templateNameList;
+}
+
+// Return locale language attribute "de_UTF8" -> "de", empty string for "C"
+static QString languageSetting()
+{
+#ifdef QT_CREATOR
+ QString name = Core::ICore::userInterfaceLanguage();
+ const int underScorePos = name.indexOf(QLatin1Char('_'));
+ if (underScorePos != -1)
+ name.truncate(underScorePos);
+ if (name.compare(QLatin1String("C"), Qt::CaseInsensitive) == 0)
+ name.clear();
+ return name;
+#else
+ return QLocale::system().name();
+#endif
+}
+
+static inline bool assignLanguageElementText(QXmlStreamReader &reader,
+ const QString &desiredLanguage,
+ QString *target)
+{
+ const QStringRef elementLanguage = reader.attributes().value(QLatin1String("xml:lang"));
+ if (elementLanguage.isEmpty()) {
+ // Try to find a translation for our Wizards
+ *target = QCoreApplication::translate("QmlProjectManager::Internal::QmlApplicationWizard",
+ reader.readElementText().toLatin1().constData());
+ return true;
+ }
+ if (elementLanguage == desiredLanguage) {
+ *target = reader.readElementText();
+ return true;
+ }
+ return false;
+}
+
+static bool parseTemplateXml(QXmlStreamReader &reader, TemplateInfo *info)
+{
+ const QString locale = languageSetting();
+
+ static const QLatin1String tag_template("template");
+ static const QLatin1String tag_displayName("displayname");
+ static const QLatin1String tag_description("description");
+ static const QLatin1String attribute_id("id");
+ static const QLatin1String attribute_featuresRequired("featuresRequired");
+ static const QLatin1String attribute_openEditor("openeditor");
+ static const QLatin1String attribute_priority("priority");
+
+ while (!reader.atEnd() && !reader.hasError()) {
+ reader.readNext();
+ if (reader.tokenType() != QXmlStreamReader::StartElement)
+ continue;
+
+ if (reader.name() == tag_template) {
+ info->openFile = reader.attributes().value(attribute_openEditor).toString();
+ if (reader.attributes().hasAttribute(attribute_priority))
+ info->priority = reader.attributes().value(attribute_priority).toString().toInt();
+
+ if (reader.attributes().hasAttribute(attribute_id))
+ info->wizardId = reader.attributes().value(attribute_id).toString();
+
+ if (reader.attributes().hasAttribute(attribute_featuresRequired))
+ info->featuresRequired = reader.attributes().value(attribute_featuresRequired).toString();
+
+ } else if (reader.name() == tag_displayName) {
+ if (!assignLanguageElementText(reader, locale, &info->displayName))
+ continue;
+ } else if (reader.name() == tag_description) {
+ if (!assignLanguageElementText(reader, locale, &info->description))
+ continue;
+ }
+ }
+ if (reader.hasError()) {
+ qWarning() << reader.errorString();
+ return false;
+ }
+
+ return true;
+}
+
+QList<TemplateInfo> QmlApp::templateInfos()
+{
+ QList<TemplateInfo> result;
+ foreach (const QString &templateName, templateNames()) {
+ const QString templatePath = templateRootDirectory() + templateName;
+ QFile xmlFile(templatePath + QLatin1String("/template.xml"));
+ if (!xmlFile.open(QIODevice::ReadOnly)) {
+ qWarning().nospace() << QString::fromLatin1("Cannot open %1").arg(QDir::toNativeSeparators(QFileInfo(xmlFile.fileName()).absoluteFilePath()));
+ continue;
+ }
+ TemplateInfo info;
+ info.templateName = templateName;
+ info.templatePath = templatePath;
+ QXmlStreamReader reader(&xmlFile);
+ if (parseTemplateXml(reader, &info))
+ result.append(info);
+ }
+ return result;
+}
+
+static QFileInfoList allFilesRecursive(const QString &path)
+{
+ const QDir currentDirectory(path);
+
+ QFileInfoList allFiles = currentDirectory.entryInfoList(QDir::Files);
+
+ foreach (const QFileInfo &subDirectory, currentDirectory.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot))
+ allFiles.append(allFilesRecursive(subDirectory.absoluteFilePath()));
+
+ return allFiles;
+}
+
+QByteArray QmlApp::readFile(const QString &filePath, bool &ok) const
+{
+ Utils::FileReader reader;
+
+ if (!reader.fetch(filePath)) {
+ ok = false;
+ return QByteArray();
+ }
+
+ ok = true;
+ return reader.data();
+}
+
+QString QmlApp::readAndAdaptTemplateFile(const QString &filePath, bool &ok) const
+{
+ const QByteArray originalTemplate = readFile(filePath, ok);
+ if (!ok)
+ return QString();
+
+ QTextStream tsIn(originalTemplate);
+ QByteArray adaptedTemplate;
+ QTextStream tsOut(&adaptedTemplate, QIODevice::WriteOnly | QIODevice::Text);
+ int lineNr = 1;
+ QString line;
+ do {
+ static const QString markerQtcReplace = QLatin1String("QTC_REPLACE");
+ static const QString markerWith = QLatin1String("WITH");
+
+ line = tsIn.readLine();
+ const int markerQtcReplaceIndex = line.indexOf(markerQtcReplace);
+ if (markerQtcReplaceIndex >= 0) {
+ QString replaceXWithYString = line.mid(markerQtcReplaceIndex + markerQtcReplace.length()).trimmed();
+ if (filePath.endsWith(QLatin1String(".json")))
+ replaceXWithYString.replace(QRegExp(QLatin1String("\",$")), QString());
+ else if (filePath.endsWith(QLatin1String(".html")))
+ replaceXWithYString.replace(QRegExp(QLatin1String(" -->$")), QString());
+ const QStringList replaceXWithY = replaceXWithYString.split(markerWith);
+ if (replaceXWithY.count() != 2) {
+ qWarning().nospace() << QString::fromLatin1("Error in %1:%2. Invalid %3 options.")
+ .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(markerQtcReplace);
+ ok = false;
+ return QString();
+ }
+ const QString replaceWhat = replaceXWithY.at(0).trimmed();
+ const QString replaceWith = replaceXWithY.at(1).trimmed();
+ if (!m_replacementVariables.contains(replaceWith)) {
+ qWarning().nospace() << QString::fromLatin1("Error in %1:%2. Unknown %3 option '%4'.")
+ .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(markerQtcReplace).arg(replaceWith);
+ ok = false;
+ return QString();
+ }
+ line = tsIn.readLine(); // Following line which is to be patched.
+ lineNr++;
+ if (line.indexOf(replaceWhat) < 0) {
+ qWarning().nospace() << QString::fromLatin1("Error in %1:%2. Replacement '%3' not found.")
+ .arg(QDir::toNativeSeparators(filePath)).arg(lineNr).arg(replaceWhat);
+ ok = false;
+ return QString();
+ }
+ line.replace(replaceWhat, m_replacementVariables.value(replaceWith));
+ }
+ if (!line.isNull())
+ tsOut << line << endl;
+ lineNr++;
+ } while (!line.isNull());
+
+ ok = true;
+ return QString::fromUtf8(adaptedTemplate);
+}
+
+bool QmlApp::addTemplate(const QString &sourceDirectory,
+ const QString &templateFileName,
+ const QString &tragetDirectory,
+ const QString &targetFileName,
+ Core::GeneratedFiles *files,
+ QString *errorMessage) const
+{
+ bool fileIsReadable;
+ Core::GeneratedFile file(tragetDirectory + QLatin1Char('/') + targetFileName);
+
+ const QString &data = readAndAdaptTemplateFile(sourceDirectory + QLatin1Char('/') + templateFileName, fileIsReadable);
+
+ if (!fileIsReadable) {
+ if (errorMessage)
+ *errorMessage = QCoreApplication::translate("QmlApplicationWizard", "Failed to read %1 template.").arg(templateFileName);
+ return false;
+ }
+
+ file.setContents(data);
+ files->append(file);
+
+ return true;
+}
+
+bool QmlApp::addBinaryFile(const QString &sourceDirectory,
+ const QString &templateFileName,
+ const QString &tragetDirectory,
+ const QString &targetFileName,
+ Core::GeneratedFiles *files,
+ QString *errorMessage) const
+{
+ bool fileIsReadable;
+
+ Core::GeneratedFile file(tragetDirectory + targetFileName);
+ file.setBinary(true);
+
+ const QByteArray &data = readFile(sourceDirectory + QLatin1Char('/') + templateFileName, fileIsReadable);
+
+ if (!fileIsReadable) {
+ if (errorMessage)
+ *errorMessage = QCoreApplication::translate("QmlApplicationWizard", "Failed to read file %1.").arg(templateFileName);
+ return false;
+ }
+
+ file.setBinaryContents(data);
+ files->append(file);
+
+ return true;
+}
+
+QString QmlApp::renameQmlFile(const QString &fileName) {
+ if (fileName == QLatin1String("main.qml"))
+ return mainQmlFileName();
+ return fileName;
+}
+
+Core::GeneratedFiles QmlApp::generateFiles(QString *errorMessage)
+{
+
+ Core::GeneratedFiles files;
+
+ QTC_ASSERT(errorMessage, return files);
+
+ errorMessage->clear();
+ setReplacementVariables();
+ const QFileInfoList templateFiles = allFilesRecursive(templateDirectory());
+
+ foreach (const QFileInfo &templateFile, templateFiles) {
+ const QString targetSubDirectory = templateFile.path().mid(templateDirectory().length());
+ const QString targetDirectory = projectDirectory() + targetSubDirectory + QLatin1Char('/');
+
+ QString targetFileName = templateFile.fileName();
+
+ if (templateFile.fileName() == QLatin1String("main.pro")) {
+ targetFileName = projectName() + QLatin1String(".pro");
+ m_creatorFileName = Core::BaseFileWizard::buildFileName(projectDirectory(),
+ projectName(),
+ QLatin1String("pro"));
+ } else if (templateFile.fileName() == QLatin1String("main.qmlproject")) {
+ targetFileName = projectName() + QLatin1String(".qmlproject");
+ m_creatorFileName = Core::BaseFileWizard::buildFileName(projectDirectory(),
+ projectName(),
+ QLatin1String("qmlproject"));
+ } else if (templateFile.fileName() == QLatin1String("main.qbp")) {
+ targetFileName = projectName() + QLatin1String(".qbp");
+ } else if (targetFileName == QLatin1String("template.xml")
+ || targetFileName == QLatin1String("template.png")) {
+ continue;
+ } else {
+ targetFileName = renameQmlFile(templateFile.fileName());
+ }
+
+ if (binaryFiles().contains(templateFile.suffix())) {
+ bool canAddBinaryFile = addBinaryFile(templateFile.absolutePath(),
+ templateFile.fileName(),
+ targetDirectory,
+ targetFileName,
+ &files,
+ errorMessage);
+ if (!canAddBinaryFile)
+ return Core::GeneratedFiles();
+ } else {
+ bool canAddTemplate = addTemplate(templateFile.absolutePath(),
+ templateFile.fileName(),
+ targetDirectory,
+ targetFileName,
+ &files,
+ errorMessage);
+ if (!canAddTemplate)
+ return Core::GeneratedFiles();
+
+ if (templateFile.fileName() == QLatin1String("main.pro")) {
+ files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute);
+ } else if (templateFile.fileName() == QLatin1String("main.qmlproject")) {
+ files.last().setAttributes(Core::GeneratedFile::OpenProjectAttribute);
+ } else if (templateFile.fileName() == m_templateInfo.openFile) {
+ files.last().setAttributes(Core::GeneratedFile::OpenEditorAttribute);
+ }
+ }
+ }
+
+ return files;
+}
+
+void QmlApp::setReplacementVariables()
+{
+ m_replacementVariables.clear();
+
+ m_replacementVariables.insert(QLatin1String("main"), mainQmlFileName());
+ m_replacementVariables.insert(QLatin1String("projectName"), projectName());
+}
+
+} // namespace Internal
+} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/qmlapp.h b/src/plugins/qmlprojectmanager/qmlapp.h
new file mode 100644
index 0000000000..4d40e337d1
--- /dev/null
+++ b/src/plugins/qmlprojectmanager/qmlapp.h
@@ -0,0 +1,118 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QMLAPP_H
+#define QMLAPP_H
+
+#include <QString>
+#include <QHash>
+#include <QObject>
+
+#include <coreplugin/generatedfile.h>
+
+namespace QmlProjectManager {
+namespace Internal {
+
+class TemplateInfo
+{
+public:
+ TemplateInfo();
+
+ QString templateName;
+ QString templatePath;
+ QString displayName;
+ QString description;
+ QString openFile;
+ QString wizardId;
+ QString featuresRequired;
+
+ int priority;
+};
+
+class QmlApp : public QObject
+{
+ Q_OBJECT
+public:
+
+ QmlApp(QObject *parent = 0);
+ ~QmlApp();
+
+ QString mainQmlFileName() const;
+ QString projectDirectory() const;
+ QString projectName() const;
+ const TemplateInfo &templateInfo() const;
+ QString templateDirectory() const;
+
+ static QString templateRootDirectory();
+ static QStringList templateNames();
+ static QList<TemplateInfo> templateInfos();
+
+ Core::GeneratedFiles generateFiles(QString *errorMessage);
+ QString renameQmlFile(const QString &fileName);
+
+ void setTemplateInfo(const TemplateInfo &templateInfo);
+
+ QString creatorFileName() const;
+
+public slots:
+ void setProjectNameAndBaseDirectory(const QString &projectName, const QString &projectBaseDirectory);
+
+protected:
+ QString readAndAdaptTemplateFile(const QString &filePath, bool &ok) const;
+ bool addTemplate(const QString &sourceDirectory,
+ const QString &sourceFileName,
+ const QString &targetDirectory,
+ const QString &targetFileName,
+ Core::GeneratedFiles *files,
+ QString *errorMessage) const;
+ bool addBinaryFile(const QString &sourceDirectory,
+ const QString &sourceFileName,
+ const QString &targetDirectory,
+ const QString &targetFileName,
+ Core::GeneratedFiles *files,
+ QString *errorMessage) const;
+ QByteArray readFile(const QString &filePath, bool &ok) const;
+
+private:
+ void setReplacementVariables();
+
+ QString m_runtime;
+
+ QString m_projectName;
+ QString m_projectBaseDirectory;
+ bool m_grantUserDataAccess;
+ QHash<QString, QString> m_replacementVariables;
+ TemplateInfo m_templateInfo;
+ QString m_creatorFileName;
+};
+
+} // namespace Internal
+} // namespace QmlProjectManager
+
+#endif // QMLAPP_H
diff --git a/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp b/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
new file mode 100644
index 0000000000..65334391fe
--- /dev/null
+++ b/src/plugins/qmlprojectmanager/qmlapplicationwizard.cpp
@@ -0,0 +1,175 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "qmlapplicationwizard.h"
+
+#include "qmlapp.h"
+
+#include <coreplugin/icore.h>
+#include <extensionsystem/iplugin.h>
+#include <extensionsystem/pluginmanager.h>
+#include <projectexplorer/customwizard/customwizard.h>
+#include <projectexplorer/kitmanager.h>
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/target.h>
+#include <qt4projectmanager/qt4project.h>
+#include <qt4projectmanager/qt4projectmanager.h>
+#include <qt4projectmanager/qt4projectmanagerconstants.h>
+#include <qtsupport/qtsupportconstants.h>
+#include <qtsupport/qtkitinformation.h>
+#include <utils/fileutils.h>
+
+#include "qmlprojectmanager.h"
+#include "qmlproject.h"
+
+#include <QCoreApplication>
+#include <QDirIterator>
+#include <QFileDialog>
+#include <QFileInfo>
+#include <QIcon>
+#include <QMessageBox>
+#include <QUrl>
+
+using namespace Core;
+using namespace ExtensionSystem;
+using namespace ProjectExplorer;
+using namespace Qt4ProjectManager;
+
+namespace QmlProjectManager {
+namespace Internal {
+
+QmlApplicationWizardDialog::QmlApplicationWizardDialog(QmlApp *qmlApp, QWidget *parent, const WizardDialogParameters &parameters)
+ : BaseProjectWizardDialog(parent, parameters),
+ m_qmlApp(qmlApp)
+{
+}
+
+QmlApp *QmlApplicationWizardDialog::qmlApp() const
+{
+ return m_qmlApp;
+}
+
+QmlApplicationWizard::QmlApplicationWizard(const BaseFileWizardParameters &parameters,
+ const TemplateInfo &templateInfo, QObject *parent)
+ : BaseFileWizard(parameters, parent),
+ m_qmlApp(new QmlApp(this))
+{
+ m_qmlApp->setTemplateInfo(templateInfo);
+}
+
+void QmlApplicationWizard::createInstances(ExtensionSystem::IPlugin *plugin)
+{
+ foreach (const TemplateInfo &templateInfo, QmlApp::templateInfos()) {
+ BaseFileWizardParameters parameters;
+ parameters.setDisplayName(templateInfo.displayName);
+ parameters.setDescription(templateInfo.description);
+ parameters.setDescriptionImage(templateInfo.templatePath + QLatin1String("/template.png"));
+ parameters.setCategory(
+ QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ parameters.setDisplayCategory(
+ QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
+ parameters.setKind(IWizard::ProjectWizard);
+ parameters.setId(templateInfo.wizardId);
+
+ QStringList stringList =
+ templateInfo.featuresRequired.split(QLatin1Char(','), QString::SkipEmptyParts);;
+ FeatureSet features;
+ foreach (const QString &string, stringList) {
+ Feature feature(Id::fromString(string.trimmed()));
+ features |= feature;
+ }
+
+ parameters.setRequiredFeatures(features);
+ parameters.setIcon(QIcon(QLatin1String(Qt4ProjectManager::Constants::ICON_QTQUICK_APP)));
+ QmlApplicationWizard *wizard = new QmlApplicationWizard(parameters, templateInfo);
+ plugin->addAutoReleasedObject(wizard);
+ }
+}
+
+BaseFileWizardParameters QmlApplicationWizard::parameters()
+{
+ BaseFileWizardParameters params(ProjectWizard);
+ params.setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
+ params.setId(QLatin1String("QA.QMLB Application"));
+ params.setIcon(QIcon(QLatin1String(Qt4ProjectManager::Constants::ICON_QTQUICK_APP)));
+ params.setDisplayCategory(
+ QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
+ params.setDisplayName(tr("Qt Quick Application"));
+ params.setDescription(tr("Creates a Qt Quick application project."));
+ return params;
+}
+
+QWizard *QmlApplicationWizard::createWizardDialog(QWidget *parent,
+ const WizardDialogParameters &wizardDialogParameters) const
+{
+ QmlApplicationWizardDialog *wizardDialog = new QmlApplicationWizardDialog(m_qmlApp,
+ parent, wizardDialogParameters);
+
+ connect(wizardDialog, SIGNAL(projectParametersChanged(QString,QString)), m_qmlApp,
+ SLOT(setProjectNameAndBaseDirectory(QString,QString)));
+
+ wizardDialog->setPath(wizardDialogParameters.defaultPath());
+
+ foreach (QWizardPage *page, wizardDialogParameters.extensionPages())
+ applyExtensionPageShortTitle(wizardDialog, wizardDialog->addPage(page));
+
+ return wizardDialog;
+}
+
+void QmlApplicationWizard::writeUserFile(const QString &fileName) const
+{
+ Manager *manager = ExtensionSystem::PluginManager::getObject<Manager>();
+
+ QmlProject *project = new QmlProject(manager, fileName);
+ QtSupport::QtVersionKitMatcher featureMatcher(requiredFeatures());
+ QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::instance()->kits();
+ foreach (ProjectExplorer::Kit *kit, kits)
+ if (featureMatcher.matches(kit)
+ && project->supportsKit(kit, 0)) // checks for desktop device
+ project->addTarget(project->createTarget(kit));
+
+ project->saveSettings();
+ delete project;
+}
+
+GeneratedFiles QmlApplicationWizard::generateFiles(const QWizard * /*wizard*/,
+ QString *errorMessage) const
+{
+ return m_qmlApp->generateFiles(errorMessage);
+}
+
+bool QmlApplicationWizard::postGenerateFiles(const QWizard * /*wizard*/, const GeneratedFiles &l,
+ QString *errorMessage)
+{
+ writeUserFile(m_qmlApp->creatorFileName());
+ return ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
+}
+
+} // namespace Internal
+} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.h b/src/plugins/qmlprojectmanager/qmlapplicationwizard.h
index 6a91c1c402..506429eca1 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.h
+++ b/src/plugins/qmlprojectmanager/qmlapplicationwizard.h
@@ -27,53 +27,62 @@
**
****************************************************************************/
-#ifndef QMLPROJECTAPPLICATIONWIZARD_H
-#define QMLPROJECTAPPLICATIONWIZARD_H
+#ifndef QMLAPPLICATIONWIZARD_H
+#define QMLAPPLICATIONWIZARD_H
#include <coreplugin/basefilewizard.h>
#include <projectexplorer/baseprojectwizarddialog.h>
+namespace ExtensionSystem {
+class IPlugin;
+} // namespace ExtensionSystem
+
namespace QmlProjectManager {
namespace Internal {
-class QmlProjectApplicationWizardDialog : public ProjectExplorer::BaseProjectWizardDialog
+class QmlApp;
+class TemplateInfo;
+
+class QmlApplicationWizardDialog : public ProjectExplorer::BaseProjectWizardDialog
{
Q_OBJECT
public:
- explicit QmlProjectApplicationWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &parameters);
+ QmlApplicationWizardDialog(QmlApp *qmlApp, QWidget *parent,
+ const Core::WizardDialogParameters &parameters);
+
+ QmlApp *qmlApp() const;
+
+private:
+ QmlApp *m_qmlApp;
};
-class QmlProjectApplicationWizard : public Core::BaseFileWizard
+
+class QmlApplicationWizard : public Core::BaseFileWizard
{
Q_OBJECT
-
+ Q_DISABLE_COPY(QmlApplicationWizard)
public:
- enum ProjectType {
- QtQuick2Project,
- QtQuick1Project
- };
+ QmlApplicationWizard(const Core::BaseFileWizardParameters &parameters,
+ const TemplateInfo &templateInfo, QObject *parent = 0);
- QmlProjectApplicationWizard(ProjectType projectType);
- virtual ~QmlProjectApplicationWizard();
- virtual Core::FeatureSet requiredFeatures() const;
+ static void createInstances(ExtensionSystem::IPlugin *plugin);
- static Core::BaseFileWizardParameters parameters(ProjectType projectType);
-protected:
- virtual QWizard *createWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &wizardDialogParameters) const;
+private: // functions
+ QWizard *createWizardDialog(QWidget *parent,
+ const Core::WizardDialogParameters &wizardDialogParameters) const;
+ Core::GeneratedFiles generateFiles(const QWizard *w, QString *errorMessage) const;
+ void writeUserFile(const QString &fileName) const;
+ bool postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &l, QString *errorMessage);
- virtual Core::GeneratedFiles generateFiles(const QWizard *w,
- QString *errorMessage) const;
+ static Core::BaseFileWizardParameters parameters();
- virtual bool postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &l, QString *errorMessage);
-
-private:
- const ProjectType m_projectType;
+private: //variables
+ mutable QString m_id;
+ QmlApp *m_qmlApp;
};
} // namespace Internal
} // namespace QmlProjectManager
-#endif // QMLPROJECTAPPLICATIONWIZARD_H
+#endif // QMLAPPLICATIONWIZARD_H
diff --git a/src/plugins/qmlprojectmanager/qmlproject.cpp b/src/plugins/qmlprojectmanager/qmlproject.cpp
index 56cbf2c4b2..fdaabe37d4 100644
--- a/src/plugins/qmlprojectmanager/qmlproject.cpp
+++ b/src/plugins/qmlprojectmanager/qmlproject.cpp
@@ -60,6 +60,7 @@ namespace QmlProjectManager {
QmlProject::QmlProject(Internal::Manager *manager, const QString &fileName)
: m_manager(manager),
m_fileName(fileName),
+ m_defaultImport(UnknownImport),
m_modelManager(QmlJS::ModelManagerInterface::instance())
{
setProjectContext(Core::Context(QmlProjectManager::Constants::PROJECTCONTEXT));
@@ -111,6 +112,18 @@ QDir QmlProject::projectDir() const
QString QmlProject::filesFileName() const
{ return m_fileName; }
+static QmlProject::QmlImport detectImport(const QString &qml) {
+ static QRegExp qtQuick1RegExp(QLatin1String("import\\s+QtQuick\\s+1"));
+ static QRegExp qtQuick2RegExp(QLatin1String("import\\s+QtQuick\\s+2"));
+
+ if (qml.contains(qtQuick1RegExp))
+ return QmlProject::QtQuick1Import;
+ else if (qml.contains(qtQuick2RegExp))
+ return QmlProject::QtQuick2Import;
+ else
+ return QmlProject::UnknownImport;
+}
+
void QmlProject::parseProject(RefreshOptions options)
{
Core::MessageManager *messageManager = Core::ICore::messageManager();
@@ -142,11 +155,14 @@ void QmlProject::parseProject(RefreshOptions options)
QString mainFilePath = m_projectItem.data()->mainFile();
if (!mainFilePath.isEmpty()) {
mainFilePath = projectDir().absoluteFilePath(mainFilePath);
- if (!QFileInfo(mainFilePath).isReadable()) {
+ Utils::FileReader reader;
+ QString errorMessage;
+ if (!reader.fetch(mainFilePath, &errorMessage)) {
messageManager->printToOutputPane(
tr("Warning while loading project file %1.").arg(m_fileName));
- messageManager->printToOutputPane(
- tr("File '%1' does not exist or is not readable.").arg(mainFilePath), true);
+ messageManager->printToOutputPane(errorMessage, true);
+ } else {
+ m_defaultImport = detectImport(QString::fromUtf8(reader.data()));
}
}
}
@@ -168,22 +184,33 @@ void QmlProject::refresh(RefreshOptions options)
if (options & Files)
m_rootNode->refresh();
- QmlJS::ModelManagerInterface::ProjectInfo pinfo(this);
- pinfo.sourceFiles = files();
- pinfo.importPaths = customImportPaths();
- QtSupport::BaseQtVersion *version = 0;
- if (activeTarget()) {
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(activeTarget()->kit());
- version = QtSupport::QtKitInformation::qtVersion(activeTarget()->kit());
- QtSupport::QmlDumpTool::pathAndEnvironment(this, version, tc, false, &pinfo.qmlDumpPath, &pinfo.qmlDumpEnvironment);
+ QmlJS::ModelManagerInterface::ProjectInfo projectInfo(this);
+ projectInfo.sourceFiles = files();
+ projectInfo.importPaths = customImportPaths();
+
+ QtSupport::BaseQtVersion *qtVersion = 0;
+ {
+ ProjectExplorer::Target *target = activeTarget();
+ ProjectExplorer::Kit *kit = target ? target->kit() : ProjectExplorer::KitManager::instance()->defaultKit();
+ ProjectExplorer::ToolChain *toolChain = ProjectExplorer::ToolChainKitInformation::toolChain(kit);
+ qtVersion = QtSupport::QtKitInformation::qtVersion(kit);
+ QtSupport::QmlDumpTool::pathAndEnvironment(this, qtVersion, toolChain, false,
+ &projectInfo.qmlDumpPath, &projectInfo.qmlDumpEnvironment);
}
- if (version) {
- pinfo.tryQmlDump = true;
- pinfo.qtImportsPath = version->qmakeProperty("QT_INSTALL_IMPORTS");
- pinfo.qtQmlPath = version->qmakeProperty("QT_INSTALL_QML");
- pinfo.qtVersionString = version->qtVersionString();
+
+ if (qtVersion) {
+ projectInfo.tryQmlDump = true;
+ projectInfo.qtImportsPath = qtVersion->qmakeProperty("QT_INSTALL_IMPORTS");
+ projectInfo.qtQmlPath = qtVersion->qmakeProperty("QT_INSTALL_QML");
+ projectInfo.qtVersionString = qtVersion->qtVersionString();
+
+ if (!projectInfo.qtQmlPath.isEmpty())
+ projectInfo.importPaths += projectInfo.qtQmlPath;
+ if (!projectInfo.qtImportsPath.isEmpty())
+ projectInfo.importPaths += projectInfo.qtImportsPath;
+
}
- m_modelManager->updateProjectInfo(pinfo);
+ m_modelManager->updateProjectInfo(projectInfo);
}
QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
@@ -201,11 +228,10 @@ QStringList QmlProject::convertToAbsoluteFiles(const QStringList &paths) const
QStringList QmlProject::files() const
{
QStringList files;
- if (m_projectItem) {
+ if (m_projectItem)
files = m_projectItem.data()->files();
- } else {
+ else
files = m_files;
- }
return files;
}
@@ -245,6 +271,11 @@ void QmlProject::refreshProjectFile()
refresh(QmlProject::ProjectFile | Files);
}
+QmlProject::QmlImport QmlProject::defaultImport() const
+{
+ return m_defaultImport;
+}
+
void QmlProject::refreshFiles(const QSet<QString> &/*added*/, const QSet<QString> &removed)
{
refresh(Files);
@@ -281,16 +312,26 @@ bool QmlProject::supportsKit(ProjectExplorer::Kit *k, QString *errorMessage) con
return false;
}
- // TODO: Limit supported versions?
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
- if (!version && errorMessage)
- *errorMessage = tr("No Qt version set in kit.");
- return version;
-}
+ if (!version) {
+ if (errorMessage)
+ *errorMessage = tr("No Qt version set in kit.");
+ return false;
+ }
-QList<ProjectExplorer::BuildConfigWidget*> QmlProject::subConfigWidgets()
-{
- return QList<ProjectExplorer::BuildConfigWidget*>();
+ if (version->qtVersion() < QtSupport::QtVersionNumber(4, 7, 0)) {
+ if (errorMessage)
+ *errorMessage = tr("Qt version is too old.");
+ return false;
+ }
+
+ if (version->qtVersion() < QtSupport::QtVersionNumber(5, 0, 0)
+ && defaultImport() == QtQuick2Import) {
+ if (errorMessage)
+ *errorMessage = tr("Qt version is too old.");
+ return false;
+ }
+ return true;
}
ProjectExplorer::ProjectNode *QmlProject::rootProjectNode() const
@@ -308,12 +349,13 @@ bool QmlProject::fromMap(const QVariantMap &map)
if (!Project::fromMap(map))
return false;
+ // refresh first - project information is used e.g. to decide the default RC's
+ refresh(Everything);
+
ProjectExplorer::Kit *defaultKit = ProjectExplorer::KitManager::instance()->defaultKit();
if (!activeTarget() && defaultKit)
addTarget(createTarget(defaultKit));
- refresh(Everything);
-
// addedTarget calls updateEnabled on the runconfigurations
// which needs to happen after refresh
foreach (ProjectExplorer::Target *t, targets())
diff --git a/src/plugins/qmlprojectmanager/qmlproject.h b/src/plugins/qmlprojectmanager/qmlproject.h
index 85b860c581..4969390cee 100644
--- a/src/plugins/qmlprojectmanager/qmlproject.h
+++ b/src/plugins/qmlprojectmanager/qmlproject.h
@@ -35,6 +35,7 @@
#include <projectexplorer/project.h>
#include <QDeclarativeEngine>
+#include <QPointer>
namespace ProjectExplorer { class RunConfiguration; }
namespace QmlJS { class ModelManagerInterface; }
@@ -67,8 +68,6 @@ public:
bool supportsKit(ProjectExplorer::Kit *k, QString *errorMessage) const;
- QList<ProjectExplorer::BuildConfigWidget*> subConfigWidgets();
-
ProjectExplorer::ProjectNode *rootProjectNode() const;
QStringList files(FilesMode fileMode) const;
@@ -93,6 +92,9 @@ public:
void refreshProjectFile();
+ enum QmlImport { UnknownImport, QtQuick1Import, QtQuick2Import };
+ QmlImport defaultImport() const;
+
private slots:
void refreshFiles(const QSet<QString> &added, const QSet<QString> &removed);
void addedTarget(ProjectExplorer::Target *target);
@@ -110,6 +112,7 @@ private:
QString m_fileName;
Internal::QmlProjectFile *m_file;
QString m_projectName;
+ QmlImport m_defaultImport;
QmlJS::ModelManagerInterface *m_modelManager;
// plain format
@@ -117,7 +120,7 @@ private:
// qml based, new format
QDeclarativeEngine m_engine;
- QWeakPointer<QmlProjectItem> m_projectItem;
+ QPointer<QmlProjectItem> m_projectItem;
Internal::QmlProjectNode *m_rootNode;
};
diff --git a/src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.cpp b/src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.cpp
deleted file mode 100644
index a6ffdd03fe..0000000000
--- a/src/plugins/qmlprojectmanager/qmlprojectapplicationwizard.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "qmlprojectapplicationwizard.h"
-
-#include "qmlprojectconstants.h"
-
-#include <app/app_version.h>
-#include <projectexplorer/customwizard/customwizard.h>
-#include <projectexplorer/projectexplorerconstants.h>
-#include <qtsupport/qtsupportconstants.h>
-
-#include <QIcon>
-
-#include <QPainter>
-#include <QPixmap>
-
-#include <QDir>
-#include <QTextStream>
-#include <QCoreApplication>
-
-namespace QmlProjectManager {
-namespace Internal {
-
-QmlProjectApplicationWizardDialog::QmlProjectApplicationWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &parameters) :
- ProjectExplorer::BaseProjectWizardDialog(parent, parameters)
-{
- setWindowTitle(tr("New Qt Quick UI Project"));
- setIntroDescription(tr("This wizard generates a Qt Quick UI project."));
-}
-
-QmlProjectApplicationWizard::QmlProjectApplicationWizard(ProjectType projectType)
- : Core::BaseFileWizard(parameters(projectType)), m_projectType(projectType)
-{ }
-
-QmlProjectApplicationWizard::~QmlProjectApplicationWizard()
-{ }
-
-Core::FeatureSet QmlProjectApplicationWizard::requiredFeatures() const
-{
- switch (m_projectType) {
- case QtQuick2Project:
- return Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_2)
- | Core::Feature(QtSupport::Constants::FEATURE_QMLPROJECT);
- case QtQuick1Project:
- default:
- return Core::Feature(QtSupport::Constants::FEATURE_QMLPROJECT)
- | Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1_1);
- }
-}
-
-Core::BaseFileWizardParameters QmlProjectApplicationWizard::parameters(ProjectType projectType)
-{
- Core::BaseFileWizardParameters parameters(ProjectWizard);
- parameters.setIcon(QIcon(QLatin1String(QtSupport::Constants::QML_WIZARD_ICON)));
- switch (projectType) {
- case QtQuick2Project:
- parameters.setDisplayName(tr("Qt Quick 2 UI"));
- parameters.setId(QLatin1String("QB.QML Application for Qt Quick 2.0"));
-
- parameters.setDescription(tr("Creates a Qt Quick UI 2 project with a single "
- "QML file that contains the main view.\n\n"
- "You can review Qt Quick UI 2 projects in the QML Scene and you need not build them. "
- "You do not need to have the development environment installed "
- "on your computer to create and run this type of projects.\n\nRequires <b>Qt 5.0</b> or newer."));
- break;
- case QtQuick1Project:
- default:
- parameters.setDisplayName(tr("Qt Quick 1 UI"));
- parameters.setId(QLatin1String("QB.QML Application for Qt Quick 1.1"));
-
- parameters.setDescription(tr("Creates a Qt Quick UI 1 project with a single "
- "QML file that contains the main view.\n\n"
- "You can review Qt Quick UI 1 projects in the QML Viewer and you need not build them. "
- "You do not need to have the development environment installed "
- "on your computer to create and run this type of projects.\n\nRequires <b>Qt 4.8</b> or newer."));
-
- }
-
- parameters.setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
- parameters.setDisplayCategory(QT_TRANSLATE_NOOP("ProjectExplorer", "Qt Application"));
- return parameters;
-}
-
-QWizard *QmlProjectApplicationWizard::createWizardDialog(QWidget *parent,
- const Core::WizardDialogParameters &wizardDialogParameters) const
-{
- QmlProjectApplicationWizardDialog *wizard = new QmlProjectApplicationWizardDialog(parent, wizardDialogParameters);
-
- wizard->setProjectName(QmlProjectApplicationWizardDialog::uniqueProjectName(wizardDialogParameters.defaultPath()));
-
- wizard->addExtensionPages(wizardDialogParameters.extensionPages());
-
- return wizard;
-}
-
-Core::GeneratedFiles QmlProjectApplicationWizard::generateFiles(const QWizard *w,
- QString *errorMessage) const
-{
- Q_UNUSED(errorMessage)
-
- const QmlProjectApplicationWizardDialog *wizard = qobject_cast<const QmlProjectApplicationWizardDialog *>(w);
- const QString projectName = wizard->projectName();
- const QString projectPath = wizard->path() + QLatin1Char('/') + projectName;
-
- const QString creatorFileName = Core::BaseFileWizard::buildFileName(projectPath,
- projectName,
- QLatin1String("qmlproject"));
-
- const QString mainFileName = Core::BaseFileWizard::buildFileName(projectPath,
- projectName,
- QLatin1String("qml"));
-
- QString contents;
- {
- QTextStream out(&contents);
-
- switch (m_projectType) {
- case QtQuick2Project:
- out << "import QtQuick 2.0" << endl;
- break;
- case QtQuick1Project:
- default:
- out << "import QtQuick 1.1" << endl;
- }
-
- out
- << endl
- << "Rectangle {" << endl
- << " width: 360" << endl
- << " height: 360" << endl
- << " Text {" << endl
- << " anchors.centerIn: parent" << endl
- << " text: \"Hello World\"" << endl
- << " }" << endl
- << " MouseArea {" << endl
- << " anchors.fill: parent" << endl
- << " onClicked: {" << endl
- << " Qt.quit();" << endl
- << " }" << endl
- << " }" << endl
- << "}" << endl;
- }
- Core::GeneratedFile generatedMainFile(mainFileName);
- generatedMainFile.setContents(contents);
- generatedMainFile.setAttributes(Core::GeneratedFile::OpenEditorAttribute);
-
- QString projectContents;
- {
- QTextStream out(&projectContents);
-
- out << "/* File generated by Qt Creator, version " << Core::Constants::IDE_VERSION_LONG << " */" << endl
- << endl
- << "import QmlProject 1.1" << endl
- << endl
- << "Project {" << endl
- << " mainFile: \"" << QDir(projectPath).relativeFilePath(mainFileName) << '"' << endl
- << endl
- << " /* Include .qml, .js, and image files from current directory and subdirectories */" << endl
- << " QmlFiles {" << endl
- << " directory: \".\"" << endl
- << " }" << endl
- << " JavaScriptFiles {" << endl
- << " directory: \".\"" << endl
- << " }" << endl
- << " ImageFiles {" << endl
- << " directory: \".\"" << endl
- << " }" << endl
- << " /* List of plugin directories passed to QML runtime */" << endl
- << " // importPaths: [ \"../exampleplugin\" ]" << endl
- << "}" << endl;
- }
- Core::GeneratedFile generatedCreatorFile(creatorFileName);
- generatedCreatorFile.setContents(projectContents);
- generatedCreatorFile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
-
- Core::GeneratedFiles files;
- files.append(generatedMainFile);
- files.append(generatedCreatorFile);
-
- return files;
-}
-
-bool QmlProjectApplicationWizard::postGenerateFiles(const QWizard *, const Core::GeneratedFiles &l, QString *errorMessage)
-{
- return ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
-
-}
-
-} // namespace Internal
-} // namespace QmlProjectManager
-
diff --git a/src/plugins/qmlprojectmanager/qmlprojectconstants.h b/src/plugins/qmlprojectmanager/qmlprojectconstants.h
index a081e934e1..387b6f28d6 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectconstants.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectconstants.h
@@ -30,12 +30,14 @@
#ifndef QMLPROJECTCONSTANTS_H
#define QMLPROJECTCONSTANTS_H
+#include <qmljstools/qmljstoolsconstants.h>
+
namespace QmlProjectManager {
namespace Constants {
const char *const PROJECTCONTEXT = "QmlProject.ProjectContext";
const char *const LANG_QML = "QML";
-const char *const QMLMIMETYPE = "application/x-qmlproject";
+const char *const QMLPROJECT_MIMETYPE = QmlJSTools::Constants::QMLPROJECT_MIMETYPE;
} // namespace Constants
} // namespace QmlProjectManager
diff --git a/src/plugins/qmlprojectmanager/qmlprojectfile.cpp b/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
index 9a044ae682..93ca0ccac8 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectfile.cpp
@@ -77,7 +77,7 @@ QString QmlProjectFile::suggestedFileName() const
QString QmlProjectFile::mimeType() const
{
- return Constants::QMLMIMETYPE;
+ return QLatin1String(Constants::QMLPROJECT_MIMETYPE);
}
bool QmlProjectFile::isModified() const
diff --git a/src/plugins/qmlprojectmanager/qmlprojectmanager.cpp b/src/plugins/qmlprojectmanager/qmlprojectmanager.cpp
index 8c39f17396..c3621bfb76 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectmanager.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectmanager.cpp
@@ -47,7 +47,7 @@ Manager::Manager()
}
QString Manager::mimeType() const
-{ return QLatin1String(Constants::QMLMIMETYPE); }
+{ return QLatin1String(Constants::QMLPROJECT_MIMETYPE); }
ProjectExplorer::Project *Manager::openProject(const QString &fileName, QString *errorString)
{
@@ -78,9 +78,8 @@ void Manager::unregisterProject(QmlProject *project)
void Manager::notifyChanged(const QString &fileName)
{
foreach (QmlProject *project, m_projects) {
- if (fileName == project->filesFileName()) {
+ if (fileName == project->filesFileName())
project->refresh(QmlProject::Files);
- }
}
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectmanager.pro b/src/plugins/qmlprojectmanager/qmlprojectmanager.pro
index ab1de261e8..c8eabe10c0 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectmanager.pro
+++ b/src/plugins/qmlprojectmanager/qmlprojectmanager.pro
@@ -17,10 +17,11 @@ HEADERS += qmlproject.h \
qmlprojectruncontrol.h \
qmlprojectrunconfiguration.h \
qmlprojectrunconfigurationfactory.h \
- qmlprojectapplicationwizard.h \
qmlprojectmanager_global.h \
qmlprojectmanagerconstants.h \
- qmlprojectrunconfigurationwidget.h
+ qmlprojectrunconfigurationwidget.h \
+ qmlapp.h \
+ qmlapplicationwizard.h
SOURCES += qmlproject.cpp \
qmlprojectplugin.cpp \
@@ -30,8 +31,9 @@ SOURCES += qmlproject.cpp \
qmlprojectruncontrol.cpp \
qmlprojectrunconfiguration.cpp \
qmlprojectrunconfigurationfactory.cpp \
- qmlprojectapplicationwizard.cpp \
- qmlprojectrunconfigurationwidget.cpp
+ qmlprojectrunconfigurationwidget.cpp \
+ qmlapp.cpp \
+ qmlapplicationwizard.cpp
RESOURCES += qmlproject.qrc
diff --git a/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs b/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs
index 5461694201..3900c9d108 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs
+++ b/src/plugins/qmlprojectmanager/qmlprojectmanager.qbs
@@ -5,6 +5,7 @@ import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "QmlProjectManager"
+ Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "declarative"] }
Depends { name: "Core" }
Depends { name: "ProjectExplorer" }
@@ -13,46 +14,42 @@ QtcPlugin {
Depends { name: "QmlJS" }
Depends { name: "Debugger" }
Depends { name: "QtSupport" }
-
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
+ Depends { name: "app_version_header" }
+ cpp.defines: base.concat("QMLPROJECTMANAGER_LIBRARY")
files: [
- "fileformat/qmlprojectitem.h",
- "fileformat/filefilteritems.h",
- "fileformat/qmlprojectfileformat.h",
+ "qmlapp.cpp",
+ "qmlapp.h",
+ "qmlapplicationwizard.cpp",
+ "qmlapplicationwizard.h",
+ "QmlProject.mimetypes.xml",
+ "qmlproject.cpp",
"qmlproject.h",
- "qmlprojectplugin.h",
- "qmlprojectmanager.h",
+ "qmlproject.qrc",
"qmlprojectconstants.h",
- "qmlprojectnodes.h",
+ "qmlprojectfile.cpp",
"qmlprojectfile.h",
- "qmlprojectruncontrol.h",
- "qmlprojectrunconfiguration.h",
- "qmlprojectrunconfigurationfactory.h",
- "qmlprojectapplicationwizard.h",
+ "qmlprojectmanager.cpp",
+ "qmlprojectmanager.h",
"qmlprojectmanager_global.h",
"qmlprojectmanagerconstants.h",
- "qmlprojectrunconfigurationwidget.h",
- "fileformat/qmlprojectitem.cpp",
- "fileformat/filefilteritems.cpp",
- "fileformat/qmlprojectfileformat.cpp",
- "qmlproject.cpp",
- "qmlprojectplugin.cpp",
- "qmlprojectmanager.cpp",
"qmlprojectnodes.cpp",
- "qmlprojectfile.cpp",
- "qmlprojectruncontrol.cpp",
+ "qmlprojectnodes.h",
+ "qmlprojectplugin.cpp",
+ "qmlprojectplugin.h",
"qmlprojectrunconfiguration.cpp",
+ "qmlprojectrunconfiguration.h",
"qmlprojectrunconfigurationfactory.cpp",
- "qmlprojectapplicationwizard.cpp",
+ "qmlprojectrunconfigurationfactory.h",
"qmlprojectrunconfigurationwidget.cpp",
- "qmlproject.qrc",
- "QmlProject.mimetypes.xml"
+ "qmlprojectrunconfigurationwidget.h",
+ "qmlprojectruncontrol.cpp",
+ "qmlprojectruncontrol.h",
+ "fileformat/filefilteritems.cpp",
+ "fileformat/filefilteritems.h",
+ "fileformat/qmlprojectfileformat.cpp",
+ "fileformat/qmlprojectfileformat.h",
+ "fileformat/qmlprojectitem.cpp",
+ "fileformat/qmlprojectitem.h",
]
}
-
diff --git a/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp b/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
index de01b50759..cb9e9d833b 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectnodes.cpp
@@ -103,7 +103,7 @@ void QmlProjectNode::refresh()
} else {
absoluteFilePath = m_project->projectDir().absoluteFilePath(fileInfo.filePath());
relativeDirectory = fileInfo.path();
- if (relativeDirectory == ".")
+ if (relativeDirectory == QLatin1String("."))
relativeDirectory.clear();
}
@@ -147,7 +147,7 @@ ProjectExplorer::FolderNode *QmlProjectNode::findOrCreateFolderByName(const QStr
else if (FolderNode *folder = m_folderByName.value(folderName))
return folder;
- FolderNode *folder = new FolderNode(baseDir + '/' + folderName);
+ FolderNode *folder = new FolderNode(baseDir + QLatin1Char('/') + folderName);
folder->setDisplayName(component);
m_folderByName.insert(folderName, folder);
diff --git a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp
index 192fdfdd67..8790b74054 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp
@@ -29,11 +29,11 @@
#include "qmlprojectplugin.h"
#include "qmlprojectmanager.h"
-#include "qmlprojectapplicationwizard.h"
#include "qmlprojectconstants.h"
#include "qmlproject.h"
#include "qmlprojectrunconfigurationfactory.h"
#include "qmlprojectruncontrol.h"
+#include "qmlapplicationwizard.h"
#include "fileformat/qmlprojectfileformat.h"
#include <extensionsystem/pluginmanager.h>
@@ -81,15 +81,14 @@ bool QmlProjectPlugin::initialize(const QStringList &, QString *errorMessage)
addAutoReleasedObject(new Internal::QmlProjectRunConfigurationFactory);
addAutoReleasedObject(new Internal::QmlProjectRunControlFactory);
- addAutoReleasedObject(new Internal::QmlProjectApplicationWizard(
- Internal::QmlProjectApplicationWizard::QtQuick1Project));
- addAutoReleasedObject(new Internal::QmlProjectApplicationWizard(
- Internal::QmlProjectApplicationWizard::QtQuick2Project));
+
+ Internal::QmlApplicationWizard::createInstances(this);
QmlProjectFileFormat::registerDeclarativeTypes();
Core::FileIconProvider *iconProvider = Core::FileIconProvider::instance();
- iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmlproject/images/qmlproject.png")), "qmlproject");
+ iconProvider->registerIconOverlayForSuffix(QIcon(QLatin1String(":/qmlproject/images/qmlproject.png")),
+ QLatin1String("qmlproject"));
return true;
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
index 114919da97..3216246ad8 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp
@@ -59,7 +59,7 @@ const char * const M_CURRENT_FILE = "CurrentFile";
QmlProjectRunConfiguration::QmlProjectRunConfiguration(ProjectExplorer::Target *parent,
Core::Id id) :
ProjectExplorer::RunConfiguration(parent, id),
- m_scriptFile(M_CURRENT_FILE),
+ m_scriptFile(QLatin1String(M_CURRENT_FILE)),
m_isEnabled(false)
{
ctor();
@@ -145,7 +145,7 @@ QString QmlProjectRunConfiguration::viewerArguments() const
// arguments from .qmlproject file
QmlProject *project = static_cast<QmlProject *>(target()->project());
foreach (const QString &importPath, project->customImportPaths()) {
- Utils::QtcProcess::addArg(&args, "-I");
+ Utils::QtcProcess::addArg(&args, QLatin1String("-I"));
Utils::QtcProcess::addArg(&args, importPath);
}
@@ -230,7 +230,7 @@ void QmlProjectRunConfiguration::setScriptSource(MainScriptSource source,
const QString &settingsPath)
{
if (source == FileInEditor) {
- m_scriptFile = M_CURRENT_FILE;
+ m_scriptFile = QLatin1String(M_CURRENT_FILE);
m_mainScriptFilename.clear();
} else if (source == FileInProjectFile) {
m_scriptFile.clear();
@@ -273,11 +273,11 @@ QVariantMap QmlProjectRunConfiguration::toMap() const
bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map)
{
m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString();
- m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString();
+ m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), QLatin1String(M_CURRENT_FILE)).toString();
m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(
map.value(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY)).toStringList());
- if (m_scriptFile == M_CURRENT_FILE)
+ if (m_scriptFile == QLatin1String(M_CURRENT_FILE))
setScriptSource(FileInEditor);
else if (m_scriptFile.isEmpty())
setScriptSource(FileInProjectFile);
@@ -338,8 +338,8 @@ void QmlProjectRunConfiguration::updateEnabled()
bool QmlProjectRunConfiguration::isValidVersion(QtSupport::BaseQtVersion *version)
{
if (version
- && (version->type() == QtSupport::Constants::DESKTOPQT
- || version->type() == QtSupport::Constants::SIMULATORQT)
+ && (version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)
+ || version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT))
&& !version->qmlviewerCommand().isEmpty()) {
return true;
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.h b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.h
index 1f5eaccd9d..b237341b76 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.h
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.h
@@ -34,7 +34,7 @@
#include <projectexplorer/runconfiguration.h>
-#include <QWeakPointer>
+#include <QPointer>
QT_FORWARD_DECLARE_CLASS(QStringListModel)
@@ -108,7 +108,7 @@ protected:
private:
void ctor();
static bool isValidVersion(QtSupport::BaseQtVersion *version);
-
+
static QString canonicalCapsPath(const QString &filePath);
Utils::Environment baseEnvironment() const;
@@ -124,7 +124,7 @@ private:
QString m_scriptFile;
QString m_qmlViewerArgs;
- QWeakPointer<Internal::QmlProjectRunConfigurationWidget> m_configurationWidget;
+ QPointer<Internal::QmlProjectRunConfigurationWidget> m_configurationWidget;
bool m_isEnabled;
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationfactory.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationfactory.cpp
index c54166a560..bc37e745f0 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationfactory.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationfactory.cpp
@@ -59,12 +59,26 @@ QList<Core::Id> QmlProjectRunConfigurationFactory::availableCreationIds(ProjectE
QtSupport::BaseQtVersion *version
= QtSupport::QtKitInformation::qtVersion(parent->kit());
- // put qmlscene first (so that it is the default) for Qt 5.0.0
+ // First id will be the default run configuration
QList<Core::Id> list;
- if (version && version->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
- list << Core::Id(Constants::QML_SCENE_RC_ID);
-
- list << Core::Id(Constants::QML_VIEWER_RC_ID);
+ if (version && version->qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0)) {
+ QmlProject *project = static_cast<QmlProject*>(parent->project());
+ switch (project->defaultImport()) {
+ case QmlProject::QtQuick1Import:
+ list << Core::Id(Constants::QML_VIEWER_RC_ID);
+ break;
+ case QmlProject::QtQuick2Import:
+ list << Core::Id(Constants::QML_SCENE_RC_ID);
+ break;
+ case QmlProject::UnknownImport:
+ default:
+ list << Core::Id(Constants::QML_SCENE_RC_ID);
+ list << Core::Id(Constants::QML_VIEWER_RC_ID);
+ break;
+ }
+ } else {
+ list << Core::Id(Constants::QML_VIEWER_RC_ID);
+ }
return list;
}
diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp
index 574c3c811b..b276812a7a 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfigurationwidget.cpp
@@ -138,7 +138,7 @@ void QmlProjectRunConfigurationWidget::updateFileComboBox()
m_fileListCombo->setEnabled(true);
m_fileListModel->clear();
- m_fileListModel->appendRow(new QStandardItem(CURRENT_FILE));
+ m_fileListModel->appendRow(new QStandardItem(QLatin1String(CURRENT_FILE)));
QModelIndex currentIndex;
QStringList sortedFiles = project->files(ProjectExplorer::Project::AllFiles);
@@ -168,11 +168,10 @@ void QmlProjectRunConfigurationWidget::updateFileComboBox()
currentIndex = item->index();
}
- if (currentIndex.isValid()) {
+ if (currentIndex.isValid())
m_fileListCombo->setCurrentIndex(currentIndex.row());
- } else {
+ else
m_fileListCombo->setCurrentIndex(0);
- }
}
void QmlProjectRunConfigurationWidget::setMainScript(int index)
diff --git a/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp b/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp
index 531edad752..7ae086727f 100644
--- a/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp
+++ b/src/plugins/qmlprojectmanager/qmlprojectruncontrol.cpp
@@ -59,11 +59,10 @@ QmlProjectRunControl::QmlProjectRunControl(QmlProjectRunConfiguration *runConfig
m_applicationLauncher.setEnvironment(runConfiguration->environment());
m_applicationLauncher.setWorkingDirectory(runConfiguration->workingDirectory());
- if (mode == NormalRunMode) {
+ if (mode == NormalRunMode)
m_executable = runConfiguration->viewerPath();
- } else {
+ else
m_executable = runConfiguration->observerPath();
- }
m_commandLineArguments = runConfiguration->viewerArguments();
m_mainQmlFile = runConfiguration->mainScript();
@@ -104,7 +103,7 @@ bool QmlProjectRunControl::isRunning() const
QIcon QmlProjectRunControl::icon() const
{
- return QIcon(ProjectExplorer::Constants::ICON_RUN_SMALL);
+ return QIcon(QLatin1String(ProjectExplorer::Constants::ICON_RUN_SMALL));
}
void QmlProjectRunControl::slotBringApplicationToForeground(qint64 pid)
@@ -200,9 +199,9 @@ RunControl *QmlProjectRunControlFactory::createDebugRunControl(QmlProjectRunConf
Debugger::DebuggerStartParameters params;
params.startMode = Debugger::StartInternal;
params.executable = runConfig->observerPath();
- params.qmlServerAddress = "127.0.0.1";
+ params.qmlServerAddress = QLatin1String("127.0.0.1");
params.qmlServerPort = runConfig->debuggerAspect()->qmlDebugServerPort();
- params.processArgs = QString("-qmljsdebugger=port:%1,block").arg(params.qmlServerPort);
+ params.processArgs = QString::fromLatin1("-qmljsdebugger=port:%1,block").arg(params.qmlServerPort);
params.processArgs += QLatin1Char(' ') + runConfig->viewerArguments();
params.workingDirectory = runConfig->workingDirectory();
params.environment = runConfig->environment();
@@ -217,13 +216,12 @@ RunControl *QmlProjectRunControlFactory::createDebugRunControl(QmlProjectRunConf
// Makes sure that all bindings go through the JavaScript engine, so that
// breakpoints are actually hit!
const QString optimizerKey = QLatin1String("QML_DISABLE_OPTIMIZER");
- if (!params.environment.hasKey(optimizerKey)) {
+ if (!params.environment.hasKey(optimizerKey))
params.environment.set(optimizerKey, QLatin1String("1"));
- }
if (params.executable.isEmpty()) {
QmlProjectPlugin::showQmlObserverToolWarning();
- *errorMessage = QString(""); // hack, we already showed a error message
+ errorMessage->clear(); // hack, we already showed a error message
return 0;
}
diff --git a/src/plugins/qnx/bardescriptordocument.cpp b/src/plugins/qnx/bardescriptordocument.cpp
new file mode 100644
index 0000000000..b2ad97d9bc
--- /dev/null
+++ b/src/plugins/qnx/bardescriptordocument.cpp
@@ -0,0 +1,260 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptordocument.h"
+
+#include "qnxconstants.h"
+#include "bardescriptoreditorwidget.h"
+#include "bardescriptordocumentnodehandlers.h"
+
+#include <coreplugin/editormanager/ieditor.h>
+#include <utils/qtcassert.h>
+
+#include <QtCore/QFile>
+#include <QtCore/QFileInfo>
+#include <QtCore/QDir>
+#include <QtCore/QTextCodec>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+BarDescriptorDocument::BarDescriptorDocument(BarDescriptorEditorWidget *editorWidget)
+ : Core::TextDocument(editorWidget)
+ , m_nodeHandlers(QList<BarDescriptorDocumentAbstractNodeHandler *>())
+ , m_editorWidget(editorWidget)
+{
+ // General
+ registerNodeHandler(new BarDescriptorDocumentIdNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentVersionNumberNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentBuildIdNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentAuthorNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentAuthorIdNodeHandler(m_editorWidget));
+
+ // Application
+ registerNodeHandler(new BarDescriptorDocumentApplicationNameNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentApplicationDescriptionNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentApplicationIconNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentSplashScreenNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentInitialWindowNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentArgNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentActionNodeHandler(m_editorWidget));
+ registerNodeHandler(new BarDescriptorDocumentEnvNodeHandler(m_editorWidget));
+
+ // Assets
+ registerNodeHandler(new BarDescriptorDocumentAssetNodeHandler(m_editorWidget));
+}
+
+BarDescriptorDocument::~BarDescriptorDocument()
+{
+ while (!m_nodeHandlers.isEmpty()) {
+ BarDescriptorDocumentAbstractNodeHandler *nodeHandler = m_nodeHandlers.takeFirst();
+ delete nodeHandler;
+ }
+}
+
+bool BarDescriptorDocument::open(QString *errorString, const QString &fileName) {
+ QString contents;
+ if (read(fileName, &contents, errorString) != Utils::TextFileFormat::ReadSuccess)
+ return false;
+
+ m_fileName = fileName;
+ m_editorWidget->editor()->setDisplayName(QFileInfo(fileName).fileName());
+
+ bool result = loadContent(contents);
+
+ if (!result)
+ *errorString = tr("%1 does not appear to be a valid application descriptor file").arg(QDir::toNativeSeparators(fileName));
+
+ return result;
+}
+
+bool BarDescriptorDocument::save(QString *errorString, const QString &fileName, bool autoSave)
+{
+ QTC_ASSERT(!autoSave, return false);
+ QTC_ASSERT(fileName.isEmpty(), return false);
+
+ bool result = write(m_fileName, xmlSource(), errorString);
+ if (!result)
+ return false;
+
+ m_editorWidget->setDirty(false);
+ emit changed();
+ return true;
+}
+
+QString BarDescriptorDocument::fileName() const
+{
+ return m_fileName;
+}
+
+QString BarDescriptorDocument::defaultPath() const
+{
+ QFileInfo fi(fileName());
+ return fi.absolutePath();
+}
+
+QString BarDescriptorDocument::suggestedFileName() const
+{
+ QFileInfo fi(fileName());
+ return fi.fileName();
+}
+
+QString BarDescriptorDocument::mimeType() const
+{
+ return QLatin1String(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE);
+}
+
+bool BarDescriptorDocument::shouldAutoSave() const
+{
+ return false;
+}
+
+bool BarDescriptorDocument::isModified() const
+{
+ return m_editorWidget->isDirty();
+}
+
+bool BarDescriptorDocument::isSaveAsAllowed() const
+{
+ return false;
+}
+
+Core::IDocument::ReloadBehavior BarDescriptorDocument::reloadBehavior(Core::IDocument::ChangeTrigger state, Core::IDocument::ChangeType type) const
+{
+ if (type == TypeRemoved || type == TypePermissions)
+ return BehaviorSilent;
+ if (type == TypeContents && state == TriggerInternal && !isModified())
+ return BehaviorSilent;
+ return BehaviorAsk;
+}
+
+bool BarDescriptorDocument::reload(QString *errorString, Core::IDocument::ReloadFlag flag, Core::IDocument::ChangeType type)
+{
+ Q_UNUSED(type);
+
+ if (flag == Core::IDocument::FlagIgnore)
+ return true;
+
+ return open(errorString, m_fileName);
+}
+
+void BarDescriptorDocument::rename(const QString &newName)
+{
+ const QString oldFilename = m_fileName;
+ m_fileName = newName;
+ m_editorWidget->editor()->setDisplayName(QFileInfo(m_fileName).fileName());
+ emit fileNameChanged(oldFilename, newName);
+ emit changed();
+}
+
+QString BarDescriptorDocument::xmlSource() const
+{
+ QDomDocument doc;
+ doc.appendChild(doc.createProcessingInstruction(QLatin1String("xml"), QLatin1String("version='1.0' encoding='") + QLatin1String(codec()->name()) + QLatin1String("' standalone='no'")));
+
+ // QNX
+ QDomElement rootElem = doc.createElement(QLatin1String("qnx"));
+ rootElem.setAttribute(QLatin1String("xmlns"), QLatin1String("http://www.qnx.com/schemas/application/1.0"));
+
+ QMap<int, BarDescriptorDocumentAbstractNodeHandler*> nodeHandlerMap;
+ foreach (BarDescriptorDocumentAbstractNodeHandler *nodeHandler, m_nodeHandlers)
+ nodeHandlerMap.insertMulti(nodeHandler->order(), nodeHandler);
+
+ QList<BarDescriptorDocumentAbstractNodeHandler*> nodeHandlers = nodeHandlerMap.values();
+ foreach (BarDescriptorDocumentAbstractNodeHandler *nodeHandler, nodeHandlers)
+ rootElem.appendChild(nodeHandler->toNode(doc));
+
+ doc.appendChild(rootElem);
+
+ return doc.toString(4);
+}
+
+bool BarDescriptorDocument::loadContent(const QString &xmlSource, QString *errorMessage, int *errorLine)
+{
+ QDomDocument doc;
+ bool result = doc.setContent(xmlSource, errorMessage, errorLine);
+ if (!result)
+ return false;
+
+ QDomElement docElem = doc.documentElement();
+ if (docElem.tagName() != QLatin1String("qnx"))
+ return false;
+
+ m_editorWidget->clear();
+
+ removeUnknownNodeHandlers();
+ foreach (BarDescriptorDocumentAbstractNodeHandler *nodeHandler, m_nodeHandlers)
+ nodeHandler->clear();
+
+ QDomNode node = docElem.firstChildElement();
+ while (!node.isNull()) {
+ BarDescriptorDocumentAbstractNodeHandler *nodeHandler = nodeHandlerForDomNode(node);
+ if (!nodeHandler) {
+ nodeHandler = new BarDescriptorDocumentUnknownNodeHandler(m_editorWidget);
+ registerNodeHandler(nodeHandler);
+ }
+
+ if (!nodeHandler->handle(node))
+ return false;
+
+ node = node.nextSibling();
+ }
+
+ m_editorWidget->setXmlSource(xmlSource);
+
+ return true;
+}
+
+void BarDescriptorDocument::registerNodeHandler(BarDescriptorDocumentAbstractNodeHandler *nodeHandler)
+{
+ m_nodeHandlers << nodeHandler;
+}
+
+BarDescriptorDocumentAbstractNodeHandler *BarDescriptorDocument::nodeHandlerForDomNode(const QDomNode &node)
+{
+ foreach (BarDescriptorDocumentAbstractNodeHandler *handler, m_nodeHandlers) {
+ if (handler->canHandle(node) && !dynamic_cast<BarDescriptorDocumentUnknownNodeHandler*>(handler))
+ return handler;
+ }
+
+ return 0;
+}
+
+void BarDescriptorDocument::removeUnknownNodeHandlers()
+{
+ for (int i = m_nodeHandlers.size() - 1; i >= 0; --i) {
+ BarDescriptorDocumentUnknownNodeHandler *nodeHandler = dynamic_cast<BarDescriptorDocumentUnknownNodeHandler*>(m_nodeHandlers[i]);
+ if (nodeHandler) {
+ m_nodeHandlers.removeAt(i);
+ delete nodeHandler;
+ }
+ }
+}
diff --git a/src/plugins/qnx/bardescriptordocument.h b/src/plugins/qnx/bardescriptordocument.h
new file mode 100644
index 0000000000..ca767458bd
--- /dev/null
+++ b/src/plugins/qnx/bardescriptordocument.h
@@ -0,0 +1,92 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QNX_INTERNAL_BARDESCRIPTORDOCUMENT_H
+#define QNX_INTERNAL_BARDESCRIPTORDOCUMENT_H
+
+#include <coreplugin/textdocument.h>
+
+#include <QDomNode>
+
+namespace Qnx {
+namespace Internal {
+
+struct BarDescriptorAsset {
+ QString source;
+ QString destination;
+ bool entry;
+};
+
+class BarDescriptorEditorWidget;
+class BarDescriptorDocumentAbstractNodeHandler;
+
+class BarDescriptorDocument : public Core::TextDocument
+{
+ Q_OBJECT
+public:
+ explicit BarDescriptorDocument(BarDescriptorEditorWidget *editorWidget);
+ ~BarDescriptorDocument();
+
+ bool open(QString *errorString, const QString &fileName);
+ bool save(QString *errorString, const QString &fileName = QString(), bool autoSave = false);
+ QString fileName() const;
+
+ QString defaultPath() const;
+ QString suggestedFileName() const;
+ QString mimeType() const;
+
+ bool shouldAutoSave() const;
+ bool isModified() const;
+ bool isSaveAsAllowed() const;
+
+ ReloadBehavior reloadBehavior(ChangeTrigger state, ChangeType type) const;
+ bool reload(QString *errorString, ReloadFlag flag, ChangeType type);
+ void rename(const QString &newName);
+
+ QString xmlSource() const;
+ bool loadContent(const QString &xmlSource, QString *errorMessage = 0, int *errorLine = 0);
+
+private:
+ void registerNodeHandler(BarDescriptorDocumentAbstractNodeHandler *nodeHandler);
+ BarDescriptorDocumentAbstractNodeHandler *nodeHandlerForDomNode(const QDomNode &node);
+ void removeUnknownNodeHandlers();
+
+ QList<BarDescriptorDocumentAbstractNodeHandler *> m_nodeHandlers;
+
+ QString m_fileName;
+
+ BarDescriptorEditorWidget *m_editorWidget;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // QNX_INTERNAL_BARDESCRIPTORDOCUMENT_H
diff --git a/src/plugins/qnx/bardescriptordocumentnodehandlers.cpp b/src/plugins/qnx/bardescriptordocumentnodehandlers.cpp
new file mode 100644
index 0000000000..a547fbf16d
--- /dev/null
+++ b/src/plugins/qnx/bardescriptordocumentnodehandlers.cpp
@@ -0,0 +1,671 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptordocumentnodehandlers.h"
+#include "bardescriptoreditorwidget.h"
+
+#include <utils/environment.h>
+#include <utils/qtcassert.h>
+
+#include <QDomNode>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+BarDescriptorDocumentAbstractNodeHandler::BarDescriptorDocumentAbstractNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : m_editorWidget(editorWidget)
+ , m_order(0xFFFF)
+{
+}
+
+BarDescriptorDocumentAbstractNodeHandler::~BarDescriptorDocumentAbstractNodeHandler()
+{
+}
+
+bool BarDescriptorDocumentAbstractNodeHandler::handle(const QDomNode &node)
+{
+ if (m_order == 0xFFFF)
+ m_order = node.lineNumber();
+
+ return fromNode(node);
+}
+
+void BarDescriptorDocumentAbstractNodeHandler::clear()
+{
+ m_order = 0xFFFF;
+}
+
+int BarDescriptorDocumentAbstractNodeHandler::order() const
+{
+ return m_order;
+}
+
+BarDescriptorEditorWidget *BarDescriptorDocumentAbstractNodeHandler::editorWidget() const
+{
+ return m_editorWidget;
+}
+
+bool BarDescriptorDocumentAbstractNodeHandler::canHandleSimpleTextElement(const QDomNode &node, const QString &tagName) const
+{
+ QDomElement element = node.toElement();
+ if (element.isNull())
+ return false;
+
+ if (element.tagName().toLower() != tagName.toLower())
+ return false;
+
+ QDomText textNode = element.firstChild().toText();
+ if (textNode.isNull())
+ return false;
+
+ return true;
+}
+
+QString BarDescriptorDocumentAbstractNodeHandler::loadSimpleTextElement(const QDomNode &node)
+{
+ QDomElement element = node.toElement();
+ QDomText textNode = element.firstChild().toText();
+ return textNode.data();
+}
+
+QDomElement BarDescriptorDocumentAbstractNodeHandler::createSimpleTextElement(QDomDocument &doc, const QString &tagName, const QString &textValue) const
+{
+ if (textValue.isEmpty())
+ return QDomElement();
+
+ QDomElement elem = doc.createElement(tagName);
+ elem.appendChild(doc.createTextNode(textValue));
+ return elem;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentIdNodeHandler::BarDescriptorDocumentIdNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentIdNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("id"));
+}
+
+bool BarDescriptorDocumentIdNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setPackageId(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentIdNodeHandler::toNode(QDomDocument &doc) const
+{
+ return createSimpleTextElement(doc, QLatin1String("id"), editorWidget()->packageId());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentVersionNumberNodeHandler::BarDescriptorDocumentVersionNumberNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentVersionNumberNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("versionNumber"));
+}
+
+bool BarDescriptorDocumentVersionNumberNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setPackageVersion(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentVersionNumberNodeHandler::toNode(QDomDocument &doc) const
+{
+ return createSimpleTextElement(doc, QLatin1String("versionNumber"), editorWidget()->packageVersion());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentBuildIdNodeHandler::BarDescriptorDocumentBuildIdNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentBuildIdNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("buildId"));
+}
+
+bool BarDescriptorDocumentBuildIdNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setPackageBuildId(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentBuildIdNodeHandler::toNode(QDomDocument &doc) const
+{
+ return createSimpleTextElement(doc, QLatin1String("buildId"), editorWidget()->packageBuildId());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentApplicationNameNodeHandler::BarDescriptorDocumentApplicationNameNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentApplicationNameNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("name"));
+}
+
+bool BarDescriptorDocumentApplicationNameNodeHandler::fromNode(const QDomNode &node)
+{
+ // TODO: Add support for localization
+
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setApplicationName(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentApplicationNameNodeHandler::toNode(QDomDocument &doc) const
+{
+ // TODO: Add support for localization
+
+ return createSimpleTextElement(doc, QLatin1String("name"), editorWidget()->applicationName());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentApplicationDescriptionNodeHandler::BarDescriptorDocumentApplicationDescriptionNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentApplicationDescriptionNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("description"));
+}
+
+bool BarDescriptorDocumentApplicationDescriptionNodeHandler::fromNode(const QDomNode &node)
+{
+ // TODO: Add support for localization
+
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setApplicationDescription(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentApplicationDescriptionNodeHandler::toNode(QDomDocument &doc) const
+{
+ return createSimpleTextElement(doc, QLatin1String("description"), editorWidget()->applicationDescription());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentApplicationIconNodeHandler::BarDescriptorDocumentApplicationIconNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentApplicationIconNodeHandler::canHandle(const QDomNode &node) const
+{
+ QDomElement element = node.toElement();
+ if (element.isNull())
+ return false;
+
+ if (element.tagName() != QLatin1String("icon"))
+ return false;
+
+ QDomElement imageElement = element.firstChild().toElement();
+ if (imageElement.isNull())
+ return false;
+
+ if (imageElement.tagName() != QLatin1String("image"))
+ return false;
+
+ QDomText imageTextNode = imageElement.firstChild().toText();
+ if (imageTextNode.isNull())
+ return false;
+
+ return true;
+}
+
+bool BarDescriptorDocumentApplicationIconNodeHandler::fromNode(const QDomNode &node)
+{
+ // TODO: Add support for localization
+
+ if (!canHandle(node))
+ return false;
+
+ QDomNode imageNode = node.firstChild();
+ QDomText imageTextNode = imageNode.firstChild().toText();
+ editorWidget()->setApplicationIcon(imageTextNode.data());
+ return true;
+}
+
+QDomNode BarDescriptorDocumentApplicationIconNodeHandler::toNode(QDomDocument &doc) const
+{
+ // TODO: Add support for localization
+ const QString iconFileName = editorWidget()->applicationIconFileName();
+ if (iconFileName.isEmpty())
+ return QDomElement();
+
+ QDomElement iconElement = doc.createElement(QLatin1String("icon"));
+ iconElement.appendChild(createSimpleTextElement(doc, QLatin1String("image"), iconFileName));
+ return iconElement;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentSplashScreenNodeHandler::BarDescriptorDocumentSplashScreenNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentSplashScreenNodeHandler::canHandle(const QDomNode &node) const
+{
+ QDomElement element = node.toElement();
+ if (element.isNull())
+ return false;
+
+ if (element.tagName().toLower() != QLatin1String("splashscreens"))
+ return false;
+
+ QDomElement imageElement = element.firstChild().toElement();
+ if (imageElement.isNull())
+ return false;
+
+ if (imageElement.tagName().toLower() != QLatin1String("image"))
+ return false;
+
+ QDomText imageTextNode = imageElement.firstChild().toText();
+ if (imageTextNode.isNull())
+ return false;
+
+ return true;
+}
+
+bool BarDescriptorDocumentSplashScreenNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ QDomElement imageNode = node.firstChildElement();
+ while (!imageNode.isNull()) {
+ if (imageNode.tagName().toLower() == QLatin1String("image")) {
+ QDomText imageTextNode = imageNode.firstChild().toText();
+ editorWidget()->appendSplashScreen(imageTextNode.data());
+ }
+ imageNode = imageNode.nextSiblingElement();
+ }
+ return true;
+}
+
+QDomNode BarDescriptorDocumentSplashScreenNodeHandler::toNode(QDomDocument &doc) const
+{
+ QStringList splashScreens = editorWidget()->splashScreens();
+ if (splashScreens.isEmpty())
+ return QDomElement();
+
+ QDomElement splashScreenElement = doc.createElement(QLatin1String("splashscreens"));
+ foreach (const QString &splashScreen, splashScreens)
+ splashScreenElement.appendChild(createSimpleTextElement(doc, QLatin1String("image"), splashScreen));
+
+ return splashScreenElement;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentAssetNodeHandler::BarDescriptorDocumentAssetNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentAssetNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("asset"));
+}
+
+bool BarDescriptorDocumentAssetNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ QDomElement element = node.toElement();
+
+ QString path = element.attribute(QLatin1String("path"));
+ QString entry = element.attribute(QLatin1String("entry"));
+ QDomText destNode = element.firstChild().toText();
+ QString dest = destNode.data();
+
+ BarDescriptorAsset asset;
+ asset.source = path;
+ asset.destination = dest;
+ asset.entry = entry == QLatin1String("true");
+
+ editorWidget()->addAsset(asset);
+ return true;
+}
+
+QDomNode BarDescriptorDocumentAssetNodeHandler::toNode(QDomDocument &doc) const
+{
+ QDomDocumentFragment fragment = doc.createDocumentFragment();
+
+ QList<BarDescriptorAsset> assets = editorWidget()->assets();
+ foreach (const BarDescriptorAsset &asset, assets) {
+ QDomElement assetElem = doc.createElement(QLatin1String("asset"));
+ assetElem.setAttribute(QLatin1String("path"), asset.source);
+ if (asset.entry) {
+ assetElem.setAttribute(QLatin1String("type"), QLatin1String("Qnx/Elf"));
+ assetElem.setAttribute(QLatin1String("entry"), QLatin1String("true"));
+ }
+ assetElem.appendChild(doc.createTextNode(asset.destination));
+ fragment.appendChild(assetElem);
+ }
+
+ return fragment;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentInitialWindowNodeHandler::BarDescriptorDocumentInitialWindowNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentInitialWindowNodeHandler::canHandle(const QDomNode &node) const
+{
+ QDomElement element = node.toElement();
+ if (element.isNull())
+ return false;
+
+ if (element.tagName() != QLatin1String("initialWindow"))
+ return false;
+
+ return true;
+}
+
+bool BarDescriptorDocumentInitialWindowNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ QDomElement child = node.firstChildElement();
+ while (!child.isNull()) {
+ if (child.tagName() == QLatin1String("aspectRatio")) {
+ editorWidget()->setOrientation(loadSimpleTextElement(child));
+ } else if (child.tagName() == QLatin1String("autoOrients")) {
+ if (loadSimpleTextElement(child) == QLatin1String("true"))
+ editorWidget()->setOrientation(QLatin1String("auto-orient"));
+ } else if (child.tagName() == QLatin1String("systemChrome")) {
+ editorWidget()->setChrome(loadSimpleTextElement(child));
+ } else if (child.tagName() == QLatin1String("transparent")) {
+ const QString transparent = loadSimpleTextElement(child);
+ editorWidget()->setTransparent(transparent == QLatin1String("true"));
+ }
+ child = child.nextSiblingElement();
+ }
+
+ return true;
+}
+
+QDomNode BarDescriptorDocumentInitialWindowNodeHandler::toNode(QDomDocument &doc) const
+{
+ QDomElement element = doc.createElement(QLatin1String("initialWindow"));
+
+ if (editorWidget()->orientation() == QLatin1String("auto-orient")) {
+ element.appendChild(createSimpleTextElement(doc, QLatin1String("autoOrients"), QLatin1String("true")));
+ } else if (!editorWidget()->orientation().isEmpty()) {
+ element.appendChild(createSimpleTextElement(doc, QLatin1String("aspectRatio"), editorWidget()->orientation()));
+ element.appendChild(createSimpleTextElement(doc, QLatin1String("autoOrients"), QLatin1String("false")));
+ }
+ element.appendChild(createSimpleTextElement(doc, QLatin1String("systemChrome"), editorWidget()->chrome()));
+ element.appendChild(createSimpleTextElement(doc, QLatin1String("transparent"), editorWidget()->transparent() ? QLatin1String("true") : QLatin1String("false")));
+
+ return element;
+}
+
+// ----------------------------------------------------------------------------
+
+
+BarDescriptorDocumentActionNodeHandler::BarDescriptorDocumentActionNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentActionNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("action"));
+}
+
+bool BarDescriptorDocumentActionNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ QString value = loadSimpleTextElement(node);
+ if (value != QLatin1String("run_native")) // This has no representation in the GUI, and is always added
+ editorWidget()->checkPermission(value);
+
+ return true;
+}
+
+QDomNode BarDescriptorDocumentActionNodeHandler::toNode(QDomDocument &doc) const
+{
+ QDomDocumentFragment frag = doc.createDocumentFragment();
+
+ QDomElement runNativeElement = doc.createElement(QLatin1String("action"));
+ runNativeElement.setAttribute(QLatin1String("system"), QLatin1String("true"));
+ runNativeElement.appendChild(doc.createTextNode(QLatin1String("run_native")));
+ frag.appendChild(runNativeElement);
+
+ QStringList checkedIdentifiers = editorWidget()->checkedPermissions();
+ foreach (const QString &identifier, checkedIdentifiers)
+ frag.appendChild(createSimpleTextElement(doc, QLatin1String("action"), identifier));
+
+ return frag;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentArgNodeHandler::BarDescriptorDocumentArgNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentArgNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("arg"));
+}
+
+bool BarDescriptorDocumentArgNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->appendApplicationArgument(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentArgNodeHandler::toNode(QDomDocument &doc) const
+{
+ QDomDocumentFragment frag = doc.createDocumentFragment();
+
+ QStringList arguments = editorWidget()->applicationArguments();
+ foreach (const QString &argument, arguments)
+ frag.appendChild(createSimpleTextElement(doc, QLatin1String("arg"), argument));
+
+ return frag;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentEnvNodeHandler::BarDescriptorDocumentEnvNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentEnvNodeHandler::canHandle(const QDomNode &node) const
+{
+ QDomElement element = node.toElement();
+ if (element.isNull())
+ return false;
+
+ if (element.tagName() != QLatin1String("env"))
+ return false;
+
+ if (!element.hasAttribute(QLatin1String("var")) || !element.hasAttribute(QLatin1String("value")))
+ return false;
+
+ return true;
+}
+
+bool BarDescriptorDocumentEnvNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ QDomElement element = node.toElement();
+
+ QString var = element.attribute(QLatin1String("var"));
+ QString value = element.attribute(QLatin1String("value"));
+
+ Utils::EnvironmentItem item(var, value);
+ editorWidget()->appendEnvironmentItem(item);
+ return true;
+}
+
+QDomNode BarDescriptorDocumentEnvNodeHandler::toNode(QDomDocument &doc) const
+{
+ QDomDocumentFragment frag = doc.createDocumentFragment();
+ QList<Utils::EnvironmentItem> environmentItems = editorWidget()->environment();
+
+ foreach (const Utils::EnvironmentItem &item, environmentItems) {
+ QDomElement element = doc.createElement(QLatin1String("env"));
+ element.setAttribute(QLatin1String("var"), item.name);
+ element.setAttribute(QLatin1String("value"), item.value);
+ frag.appendChild(element);
+ }
+
+ return frag;
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentAuthorNodeHandler::BarDescriptorDocumentAuthorNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentAuthorNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("author"))
+ || canHandleSimpleTextElement(node, QLatin1String("publisher"));
+}
+
+bool BarDescriptorDocumentAuthorNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setAuthor(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentAuthorNodeHandler::toNode(QDomDocument &doc) const
+{
+ return createSimpleTextElement(doc, QLatin1String("author"), editorWidget()->author());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentAuthorIdNodeHandler::BarDescriptorDocumentAuthorIdNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentAuthorIdNodeHandler::canHandle(const QDomNode &node) const
+{
+ return canHandleSimpleTextElement(node, QLatin1String("authorId"));
+}
+
+bool BarDescriptorDocumentAuthorIdNodeHandler::fromNode(const QDomNode &node)
+{
+ if (!canHandle(node))
+ return false;
+
+ editorWidget()->setAuthorId(loadSimpleTextElement(node));
+ return true;
+}
+
+QDomNode BarDescriptorDocumentAuthorIdNodeHandler::toNode(QDomDocument &doc) const
+{
+ return createSimpleTextElement(doc, QLatin1String("authorId"), editorWidget()->authorId());
+}
+
+// ----------------------------------------------------------------------------
+
+BarDescriptorDocumentUnknownNodeHandler::BarDescriptorDocumentUnknownNodeHandler(BarDescriptorEditorWidget *editorWidget)
+ : BarDescriptorDocumentAbstractNodeHandler(editorWidget)
+{
+}
+
+bool BarDescriptorDocumentUnknownNodeHandler::canHandle(const QDomNode &node) const
+{
+ Q_UNUSED(node);
+ return true;
+}
+
+bool BarDescriptorDocumentUnknownNodeHandler::fromNode(const QDomNode &node)
+{
+ m_node = node.cloneNode();
+ return true;
+}
+
+QDomNode BarDescriptorDocumentUnknownNodeHandler::toNode(QDomDocument &doc) const
+{
+ Q_UNUSED(doc);
+ return m_node;
+}
diff --git a/src/plugins/qnx/bardescriptordocumentnodehandlers.h b/src/plugins/qnx/bardescriptordocumentnodehandlers.h
new file mode 100644
index 0000000000..ad9db9bcf4
--- /dev/null
+++ b/src/plugins/qnx/bardescriptordocumentnodehandlers.h
@@ -0,0 +1,287 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QNX_INTERNAL_BARDESCRIPTORDOCUMENTNODEHANDLERS_H
+#define QNX_INTERNAL_BARDESCRIPTORDOCUMENTNODEHANDLERS_H
+
+#include <QDomNode>
+#include <QSharedPointer>
+
+namespace Qnx {
+namespace Internal {
+
+class BarDescriptorEditorWidget;
+
+class BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentAbstractNodeHandler(BarDescriptorEditorWidget *editorWidget);
+ virtual ~BarDescriptorDocumentAbstractNodeHandler();
+
+ virtual bool canHandle(const QDomNode &node) const = 0;
+ bool handle(const QDomNode &node);
+ virtual QDomNode toNode(QDomDocument &doc) const = 0;
+
+ void clear();
+ int order() const;
+
+protected:
+ BarDescriptorEditorWidget *editorWidget() const;
+
+ virtual bool fromNode(const QDomNode &node) = 0;
+
+ bool canHandleSimpleTextElement(const QDomNode &node, const QString &tagName) const;
+ QString loadSimpleTextElement(const QDomNode &node);
+ QDomElement createSimpleTextElement(QDomDocument &doc, const QString &tagName, const QString &textValue) const;
+
+private:
+ BarDescriptorEditorWidget *m_editorWidget;
+
+ int m_order;
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentIdNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentIdNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentVersionNumberNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentVersionNumberNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentBuildIdNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentBuildIdNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentApplicationNameNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentApplicationNameNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentApplicationDescriptionNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentApplicationDescriptionNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentApplicationIconNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentApplicationIconNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentSplashScreenNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentSplashScreenNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentAssetNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentAssetNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentInitialWindowNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentInitialWindowNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentActionNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentActionNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentArgNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentArgNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentEnvNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentEnvNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentAuthorNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentAuthorNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentAuthorIdNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentAuthorIdNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+};
+
+// ----------------------------------------------------------------------------
+
+class BarDescriptorDocumentUnknownNodeHandler : public BarDescriptorDocumentAbstractNodeHandler
+{
+public:
+ BarDescriptorDocumentUnknownNodeHandler(BarDescriptorEditorWidget *editorWidget);
+
+ bool canHandle(const QDomNode &node) const;
+ QDomNode toNode(QDomDocument &doc) const;
+
+protected:
+ bool fromNode(const QDomNode &node);
+
+private:
+ QDomNode m_node;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // QNX_INTERNAL_BARDESCRIPTORDOCUMENTNODEHANDLERS_H
diff --git a/src/plugins/qnx/bardescriptoreditor.cpp b/src/plugins/qnx/bardescriptoreditor.cpp
new file mode 100644
index 0000000000..030b862e62
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditor.cpp
@@ -0,0 +1,200 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptoreditor.h"
+
+#include "qnxconstants.h"
+#include "bardescriptoreditorwidget.h"
+#include "bardescriptordocument.h"
+
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/task.h>
+#include <projectexplorer/taskhub.h>
+#include <utils/qtcassert.h>
+
+#include <QAction>
+#include <QToolBar>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+BarDescriptorEditor::BarDescriptorEditor(BarDescriptorEditorWidget *editorWidget)
+ : Core::IEditor()
+ , m_taskHub(0)
+{
+ setWidget(editorWidget);
+
+ m_file = new BarDescriptorDocument(editorWidget);
+
+ m_toolBar = new QToolBar(editorWidget);
+
+ m_actionGroup = new QActionGroup(this);
+ connect(m_actionGroup, SIGNAL(triggered(QAction*)), this, SLOT(changeEditorPage(QAction*)));
+
+ QAction *generalAction = m_toolBar->addAction(tr("General"));
+ generalAction->setData(General);
+ generalAction->setCheckable(true);
+ m_actionGroup->addAction(generalAction);
+
+ QAction *applicationAction = m_toolBar->addAction(tr("Application"));
+ applicationAction->setData(Application);
+ applicationAction->setCheckable(true);
+ m_actionGroup->addAction(applicationAction);
+
+ QAction *assetsAction = m_toolBar->addAction(tr("Assets"));
+ assetsAction->setData(Assets);
+ assetsAction->setCheckable(true);
+ m_actionGroup->addAction(assetsAction);
+
+ QAction *sourceAction = m_toolBar->addAction(tr("XML Source"));
+ sourceAction->setData(Source);
+ sourceAction->setCheckable(true);
+ m_actionGroup->addAction(sourceAction);
+
+ generalAction->setChecked(true);
+}
+
+bool BarDescriptorEditor::createNew(const QString &contents)
+{
+ Q_UNUSED(contents);
+ return false;
+}
+
+bool BarDescriptorEditor::open(QString *errorString, const QString &fileName, const QString &realFileName)
+{
+ QTC_ASSERT(fileName == realFileName, return false);
+ return m_file->open(errorString, fileName);
+}
+
+Core::IDocument *BarDescriptorEditor::document()
+{
+ return m_file;
+}
+
+Core::Id BarDescriptorEditor::id() const
+{
+ return Constants::QNX_BAR_DESCRIPTOR_EDITOR_ID;
+}
+
+QString BarDescriptorEditor::displayName() const
+{
+ return m_displayName;
+}
+
+void BarDescriptorEditor::setDisplayName(const QString &title)
+{
+ if (title == m_displayName)
+ return;
+
+ m_displayName = title;
+ emit changed();
+}
+
+bool BarDescriptorEditor::duplicateSupported() const
+{
+ return false;
+}
+
+Core::IEditor *BarDescriptorEditor::duplicate(QWidget *parent)
+{
+ Q_UNUSED(parent);
+ return 0;
+}
+
+QByteArray BarDescriptorEditor::saveState() const
+{
+ return QByteArray(); // Not supported
+}
+
+bool BarDescriptorEditor::restoreState(const QByteArray &state)
+{
+ Q_UNUSED(state);
+ return false; // Not supported
+}
+
+bool BarDescriptorEditor::isTemporary() const
+{
+ return false;
+}
+
+QWidget *BarDescriptorEditor::toolBar()
+{
+ return m_toolBar;
+}
+
+void BarDescriptorEditor::changeEditorPage(QAction *action)
+{
+ setActivePage(static_cast<EditorPage>(action->data().toInt()));
+}
+
+ProjectExplorer::TaskHub *BarDescriptorEditor::taskHub()
+{
+ if (m_taskHub == 0) {
+ m_taskHub = ProjectExplorer::ProjectExplorerPlugin::instance()->taskHub();
+ m_taskHub->addCategory(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR, tr("Bar Descriptor"));
+ }
+
+ return m_taskHub;
+}
+
+void BarDescriptorEditor::setActivePage(BarDescriptorEditor::EditorPage page)
+{
+ BarDescriptorEditorWidget *editorWidget = qobject_cast<BarDescriptorEditorWidget *>(widget());
+ QTC_ASSERT(editorWidget, return);
+
+ int prevPage = editorWidget->currentIndex();
+
+ if (prevPage == page)
+ return;
+
+ if (page == Source) {
+ editorWidget->setXmlSource(m_file->xmlSource());
+ } else if (prevPage == Source) {
+ taskHub()->clearTasks(Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR);
+ QString errorMsg;
+ int errorLine;
+ if (!m_file->loadContent(editorWidget->xmlSource(), &errorMsg, &errorLine)) {
+ const ProjectExplorer::Task task(ProjectExplorer::Task::Error, errorMsg, Utils::FileName::fromString(m_file->fileName()),
+ errorLine, Constants::QNX_TASK_CATEGORY_BARDESCRIPTOR);
+ taskHub()->addTask(task);
+ taskHub()->requestPopup();
+
+ foreach (QAction *action, m_actionGroup->actions())
+ if (action->data().toInt() == Source)
+ action->setChecked(true);
+
+ return;
+ }
+ }
+
+ editorWidget->setCurrentIndex(page);
+}
diff --git a/src/plugins/qnx/bardescriptoreditor.h b/src/plugins/qnx/bardescriptoreditor.h
new file mode 100644
index 0000000000..5220aad966
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditor.h
@@ -0,0 +1,104 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QNX_INTERNAL_BARDESCRIPTOREDITOR_H
+#define QNX_INTERNAL_BARDESCRIPTOREDITOR_H
+
+#include <coreplugin/editormanager/ieditor.h>
+
+QT_BEGIN_NAMESPACE
+class QActionGroup;
+class QToolBar;
+QT_END_NAMESPACE
+
+namespace ProjectExplorer {
+ class TaskHub;
+}
+
+namespace Qnx {
+namespace Internal {
+
+class BarDescriptorDocument;
+
+class BarDescriptorEditorWidget;
+
+class BarDescriptorEditor : public Core::IEditor
+{
+ Q_OBJECT
+public:
+ explicit BarDescriptorEditor(BarDescriptorEditorWidget *editorWidget);
+
+ bool createNew(const QString &contents = QString());
+ bool open(QString *errorString, const QString &fileName, const QString &realFileName);
+ Core::IDocument *document();
+ Core::Id id() const;
+ QString displayName() const;
+ void setDisplayName(const QString &title);
+
+ bool duplicateSupported() const;
+ Core::IEditor *duplicate(QWidget *parent);
+
+ QByteArray saveState() const;
+ bool restoreState(const QByteArray &state);
+
+ bool isTemporary() const;
+
+ QWidget *toolBar();
+
+private slots:
+ void changeEditorPage(QAction *action);
+
+private:
+ enum EditorPage {
+ General = 0,
+ Application,
+ Assets,
+ Source
+ };
+
+ ProjectExplorer::TaskHub *taskHub();
+
+ void setActivePage(EditorPage page);
+
+ BarDescriptorDocument *m_file;
+
+ QString m_displayName;
+
+ QToolBar *m_toolBar;
+ QActionGroup *m_actionGroup;
+
+ ProjectExplorer::TaskHub *m_taskHub;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // QNX_INTERNAL_BARDESCRIPTOREDITOR_H
diff --git a/src/plugins/qnx/bardescriptoreditorfactory.cpp b/src/plugins/qnx/bardescriptoreditorfactory.cpp
new file mode 100644
index 0000000000..da3a933dce
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditorfactory.cpp
@@ -0,0 +1,74 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptoreditorfactory.h"
+
+#include "qnxconstants.h"
+#include "bardescriptoreditorwidget.h"
+
+#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/editormanager/ieditor.h>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+BarDescriptorEditorFactory::BarDescriptorEditorFactory(QObject *parent)
+ : Core::IEditorFactory(parent)
+ , m_mimeTypes(QStringList() << QLatin1String(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE))
+{
+}
+
+QStringList BarDescriptorEditorFactory::mimeTypes() const
+{
+ return m_mimeTypes;
+}
+
+Core::Id BarDescriptorEditorFactory::id() const
+{
+ return Constants::QNX_BAR_DESCRIPTOR_EDITOR_ID;
+}
+
+QString BarDescriptorEditorFactory::displayName() const
+{
+ return tr("Bar descriptor editor");
+}
+
+Core::IDocument *BarDescriptorEditorFactory::open(const QString &fileName)
+{
+ Core::IEditor *iface = Core::EditorManager::instance()->openEditor(fileName, id());
+ return iface ? iface->document() : 0;
+}
+
+Core::IEditor *BarDescriptorEditorFactory::createEditor(QWidget *parent)
+{
+ BarDescriptorEditorWidget *editorWidget = new BarDescriptorEditorWidget(parent);
+ return editorWidget->editor();
+}
diff --git a/src/plugins/qnx/bardescriptoreditorfactory.h b/src/plugins/qnx/bardescriptoreditorfactory.h
new file mode 100644
index 0000000000..1e49ac3247
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditorfactory.h
@@ -0,0 +1,62 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QNX_INTERNAL_BARDESCRIPTOREDITORFACTORY_H
+#define QNX_INTERNAL_BARDESCRIPTOREDITORFACTORY_H
+
+#include <coreplugin/editormanager/ieditorfactory.h>
+
+#include <QtCore/QStringList>
+
+namespace Qnx {
+namespace Internal {
+
+class BarDescriptorEditorFactory : public Core::IEditorFactory
+{
+ Q_OBJECT
+public:
+ explicit BarDescriptorEditorFactory(QObject *parent = 0);
+
+ QStringList mimeTypes() const;
+ Core::Id id() const;
+ QString displayName() const;
+ Core::IDocument *open(const QString &fileName);
+
+ Core::IEditor *createEditor(QWidget *parent);
+
+private:
+ QStringList m_mimeTypes;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // QNX_INTERNAL_BARDESCRIPTOREDITORFACTORY_H
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.cpp b/src/plugins/qnx/bardescriptoreditorwidget.cpp
new file mode 100644
index 0000000000..f2c2c9e93f
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditorwidget.cpp
@@ -0,0 +1,674 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptoreditorwidget.h"
+#include "ui_bardescriptoreditorwidget.h"
+
+#include "qnxconstants.h"
+#include "bardescriptoreditor.h"
+#include "bardescriptorpermissionsmodel.h"
+
+#include <qtsupport/qtversionmanager.h>
+#include <texteditor/plaintexteditor.h>
+#include <utils/qtcassert.h>
+
+#include <QFileDialog>
+#include <QItemSelection>
+#include <QStandardItemModel>
+#include <QStringListModel>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+namespace {
+void setTextBlocked(QLineEdit *lineEdit, const QString &value)
+{
+ bool blocked = lineEdit->blockSignals(true);
+ lineEdit->setText(value);
+ lineEdit->blockSignals(blocked);
+}
+
+void setComboBoxDataBlocked(QComboBox *comboBox, const QString &data)
+{
+ int index = comboBox->findData(data);
+ QTC_CHECK(index > -1);
+ bool blocked = comboBox->blockSignals(true);
+ comboBox->setCurrentIndex(index);
+ comboBox->blockSignals(blocked);
+}
+
+void setPathBlocked(Utils::PathChooser *pathChooser, const QString &path)
+{
+ bool blocked = pathChooser->blockSignals(true);
+ pathChooser->setPath(path);
+ pathChooser->blockSignals(blocked);
+}
+
+void setCheckBoxBlocked(QCheckBox *checkBox, bool check)
+{
+ bool blocked = checkBox->blockSignals(true);
+ checkBox->setChecked(check);
+ checkBox->blockSignals(blocked);
+}
+}
+
+BarDescriptorEditorWidget::BarDescriptorEditorWidget(QWidget *parent)
+ : QStackedWidget(parent)
+ , m_editor(0)
+ , m_dirty(false)
+ , m_ui(new Ui::BarDescriptorEditorWidget)
+{
+ m_ui->setupUi(this);
+
+ setCurrentIndex(0);
+
+ initGeneralPage();
+ initApplicationPage();
+ initAssetsPage();
+ initSourcePage();
+}
+
+BarDescriptorEditorWidget::~BarDescriptorEditorWidget()
+{
+ delete m_ui;
+}
+
+void BarDescriptorEditorWidget::initGeneralPage()
+{
+ QRegExp versionNumberRegExp(QLatin1String("(\\d{1,3}\\.)?(\\d{1,3}\\.)?(\\d{1,3})"));
+ QRegExpValidator *versionNumberValidator = new QRegExpValidator(versionNumberRegExp, this);
+ m_ui->packageVersion->setValidator(versionNumberValidator);
+
+ connect(m_ui->packageId, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+ connect(m_ui->packageVersion, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+ connect(m_ui->packageBuildId, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+
+ connect(m_ui->author, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+ connect(m_ui->authorId, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+}
+
+void BarDescriptorEditorWidget::clearGeneralPage()
+{
+ setTextBlocked(m_ui->packageId, QString());
+ setTextBlocked(m_ui->packageVersion, QString());
+ setTextBlocked(m_ui->packageBuildId, QString());
+
+ setTextBlocked(m_ui->author, QString());
+ setTextBlocked(m_ui->authorId, QString());
+}
+
+void BarDescriptorEditorWidget::initApplicationPage()
+{
+ // General
+ m_ui->orientation->addItem(tr("Default"), QLatin1String(""));
+ m_ui->orientation->addItem(tr("Auto-orient"), QLatin1String("auto-orient"));
+ m_ui->orientation->addItem(tr("Landscape"), QLatin1String("landscape"));
+ m_ui->orientation->addItem(tr("Portrait"), QLatin1String("portrait"));
+
+ m_ui->chrome->addItem(tr("Standard"), QLatin1String("standard"));
+ m_ui->chrome->addItem(tr("None"), QLatin1String("none"));
+
+ connect(m_ui->orientation, SIGNAL(currentIndexChanged(int)), this, SLOT(setDirty()));
+ connect(m_ui->chrome, SIGNAL(currentIndexChanged(int)), this, SLOT(setDirty()));
+ connect(m_ui->transparentMainWindow, SIGNAL(toggled(bool)), this, SLOT(setDirty()));
+ connect(m_ui->applicationArguments, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+
+ //Permissions
+ m_permissionsModel = new BarDescriptorPermissionsModel(this);
+ m_ui->permissionsView->setModel(m_permissionsModel);
+
+ connect(m_ui->selectAllPermissions, SIGNAL(clicked()), m_permissionsModel, SLOT(checkAll()));
+ connect(m_ui->deselectAllPermissions, SIGNAL(clicked()), m_permissionsModel, SLOT(uncheckAll()));
+ connect(m_permissionsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+
+ // Environment
+ m_ui->environmentWidget->setBaseEnvironmentText(tr("Device Environment"));
+
+ connect(m_ui->environmentWidget, SIGNAL(userChangesChanged()), this, SLOT(setDirty()));
+
+ // Entry-Point Text and Images
+ m_ui->iconFilePath->setExpectedKind(Utils::PathChooser::File);
+ m_ui->iconFilePath->setPromptDialogFilter(tr("Images (*.jpg *.png)"));
+
+ connect(m_ui->applicationName, SIGNAL(textChanged(QString)), this, SLOT(setDirty()));
+ connect(m_ui->applicationDescription, SIGNAL(textChanged()), this, SLOT(setDirty()));
+
+ connect(m_ui->iconFilePath, SIGNAL(changed(QString)), this, SLOT(setDirty()));
+ connect(m_ui->iconFilePath, SIGNAL(changed(QString)), this, SLOT(addImageAsAsset(QString)));
+ connect(m_ui->iconFilePath, SIGNAL(changed(QString)), this, SLOT(setApplicationIconPreview(QString)));
+ connect(m_ui->iconClearButton, SIGNAL(clicked()), m_ui->iconFilePath->lineEdit(), SLOT(clear()));
+
+ m_splashScreenModel = new QStringListModel(this);
+ m_ui->splashScreensView->setModel(m_splashScreenModel);
+ connect(m_ui->addSplashScreen, SIGNAL(clicked()), this, SLOT(browseForSplashScreen()));
+ connect(m_ui->removeSplashScreen, SIGNAL(clicked()), this, SLOT(removeSelectedSplashScreen()));
+ connect(m_splashScreenModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ connect(m_ui->splashScreensView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleSplashScreenSelectionChanged(QItemSelection, QItemSelection)));
+}
+
+void BarDescriptorEditorWidget::clearApplicationPage()
+{
+ // General
+ setComboBoxDataBlocked(m_ui->orientation, QLatin1String(""));
+ setComboBoxDataBlocked(m_ui->chrome, QLatin1String("none"));
+ setCheckBoxBlocked(m_ui->transparentMainWindow, false);
+ setTextBlocked(m_ui->applicationArguments, QString());
+
+ // Permissions
+ disconnect(m_permissionsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ m_permissionsModel->uncheckAll();
+ connect(m_permissionsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+
+ // Environment
+ disconnect(m_ui->environmentWidget, SIGNAL(userChangesChanged()), this, SLOT(setDirty()));
+ m_ui->environmentWidget->setUserChanges(QList<Utils::EnvironmentItem>());
+ connect(m_ui->environmentWidget, SIGNAL(userChangesChanged()), this, SLOT(setDirty()));
+
+ // Entry-Point Text and Images
+ setPathBlocked(m_ui->iconFilePath, QString());
+ setApplicationIconPreview(QString());
+
+ disconnect(m_splashScreenModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ m_splashScreenModel->setStringList(QStringList());
+ connect(m_splashScreenModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ setImagePreview(m_ui->splashScreenPreviewLabel, QString());
+
+}
+
+void BarDescriptorEditorWidget::initAssetsPage()
+{
+ QStringList headerLabels;
+ headerLabels << tr("Path") << tr("Destination") << tr("Entry-Point");
+ m_assetsModel = new QStandardItemModel(this);
+ m_assetsModel->setHorizontalHeaderLabels(headerLabels);
+ m_ui->assets->setModel(m_assetsModel);
+
+ connect(m_ui->addAsset, SIGNAL(clicked()), this, SLOT(addNewAsset()));
+ connect(m_ui->removeAsset, SIGNAL(clicked()), this, SLOT(removeSelectedAsset()));
+ connect(m_assetsModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(updateEntryCheckState(QStandardItem*)));
+ connect(m_assetsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+}
+
+void BarDescriptorEditorWidget::clearAssetsPage()
+{
+ disconnect(m_assetsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ m_assetsModel->removeRows(0, m_assetsModel->rowCount());
+ connect(m_assetsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+}
+
+void BarDescriptorEditorWidget::initSourcePage()
+{
+ m_ui->xmlSourceView->configure(QLatin1String(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE));
+ connect(m_ui->xmlSourceView, SIGNAL(textChanged()), this, SLOT(setDirty()));
+}
+
+void BarDescriptorEditorWidget::clearSourcePage()
+{
+ disconnect(m_ui->xmlSourceView, SIGNAL(textChanged()), this, SLOT(setDirty()));
+ m_ui->xmlSourceView->clear();
+ connect(m_ui->xmlSourceView, SIGNAL(textChanged()), this, SLOT(setDirty()));
+}
+
+Core::IEditor *BarDescriptorEditorWidget::editor() const
+{
+ if (!m_editor) {
+ m_editor = const_cast<BarDescriptorEditorWidget *>(this)->createEditor();
+ connect(this, SIGNAL(changed()), m_editor, SIGNAL(changed()));
+ }
+
+ return m_editor;
+}
+
+QString BarDescriptorEditorWidget::packageId() const
+{
+ return m_ui->packageId->text();
+}
+
+void BarDescriptorEditorWidget::setPackageId(const QString &packageId)
+{
+ setTextBlocked(m_ui->packageId, packageId);
+}
+
+QString BarDescriptorEditorWidget::packageVersion() const
+{
+ QString version = m_ui->packageVersion->text();
+ int pos = 0;
+ if (m_ui->packageVersion->validator()->validate(version, pos) == QValidator::Intermediate) {
+ if (version.endsWith(QLatin1Char('.')))
+ version = version.left(version.size() - 1);
+ }
+ return version;
+}
+
+void BarDescriptorEditorWidget::setPackageVersion(const QString &packageVersion)
+{
+ setTextBlocked(m_ui->packageVersion, packageVersion);
+}
+
+QString BarDescriptorEditorWidget::packageBuildId() const
+{
+ return m_ui->packageBuildId->text();
+}
+
+void BarDescriptorEditorWidget::setPackageBuildId(const QString &packageBuildId)
+{
+ setTextBlocked(m_ui->packageBuildId, packageBuildId);
+}
+
+QString BarDescriptorEditorWidget::author() const
+{
+ return m_ui->author->text();
+}
+
+void BarDescriptorEditorWidget::setAuthor(const QString &author)
+{
+ setTextBlocked(m_ui->author, author);
+}
+
+QString BarDescriptorEditorWidget::authorId() const
+{
+ return m_ui->authorId->text();
+}
+
+void BarDescriptorEditorWidget::setAuthorId(const QString &authorId)
+{
+ setTextBlocked(m_ui->authorId, authorId);
+}
+
+QString BarDescriptorEditorWidget::orientation() const
+{
+ return m_ui->orientation->itemData(m_ui->orientation->currentIndex()).toString();
+}
+
+void BarDescriptorEditorWidget::setOrientation(const QString &orientation)
+{
+ setComboBoxDataBlocked(m_ui->orientation, orientation);
+}
+
+QString BarDescriptorEditorWidget::chrome() const
+{
+ return m_ui->chrome->itemData(m_ui->chrome->currentIndex()).toString();
+}
+
+void BarDescriptorEditorWidget::setChrome(const QString &chrome)
+{
+ setComboBoxDataBlocked(m_ui->chrome, chrome);
+}
+
+bool BarDescriptorEditorWidget::transparent() const
+{
+ return m_ui->transparentMainWindow->isChecked();
+}
+
+void BarDescriptorEditorWidget::setTransparent(bool transparent)
+{
+ setCheckBoxBlocked(m_ui->transparentMainWindow, transparent);
+}
+
+void BarDescriptorEditorWidget::appendApplicationArgument(const QString &argument)
+{
+ QString completeArguments = m_ui->applicationArguments->text();
+ if (!completeArguments.isEmpty())
+ completeArguments.append(QLatin1Char(' '));
+ completeArguments.append(argument);
+
+ setTextBlocked(m_ui->applicationArguments, completeArguments);
+}
+
+QStringList BarDescriptorEditorWidget::applicationArguments() const
+{
+ // TODO: Should probably handle "argument with spaces within quotes"
+ return m_ui->applicationArguments->text().split(QLatin1Char(' '));
+}
+
+QStringList BarDescriptorEditorWidget::checkedPermissions() const
+{
+ return m_permissionsModel->checkedIdentifiers();
+}
+
+void BarDescriptorEditorWidget::checkPermission(const QString &identifier)
+{
+ disconnect(m_permissionsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ m_permissionsModel->checkPermission(identifier);
+ connect(m_permissionsModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+}
+
+QList<Utils::EnvironmentItem> BarDescriptorEditorWidget::environment() const
+{
+ return m_ui->environmentWidget->userChanges();
+}
+
+void BarDescriptorEditorWidget::appendEnvironmentItem(const Utils::EnvironmentItem &envItem)
+{
+ disconnect(m_ui->environmentWidget, SIGNAL(userChangesChanged()), this, SLOT(setDirty()));
+ QList<Utils::EnvironmentItem> items = m_ui->environmentWidget->userChanges();
+ items.append(envItem);
+ m_ui->environmentWidget->setUserChanges(items);
+ connect(m_ui->environmentWidget, SIGNAL(userChangesChanged()), this, SLOT(setDirty()));
+}
+
+QString BarDescriptorEditorWidget::applicationName() const
+{
+ return m_ui->applicationName->text();
+}
+
+void BarDescriptorEditorWidget::setApplicationName(const QString &applicationName)
+{
+ setTextBlocked(m_ui->applicationName, applicationName);
+}
+
+QString BarDescriptorEditorWidget::applicationDescription() const
+{
+ return m_ui->applicationDescription->toPlainText();
+}
+
+void BarDescriptorEditorWidget::setApplicationDescription(const QString &applicationDescription)
+{
+ bool blocked = m_ui->applicationDescription->blockSignals(true);
+ m_ui->applicationDescription->setPlainText(applicationDescription);
+ m_ui->applicationDescription->blockSignals(blocked);
+}
+
+QString BarDescriptorEditorWidget::applicationIconFileName() const
+{
+ return QFileInfo(m_ui->iconFilePath->path()).fileName();
+}
+
+void BarDescriptorEditorWidget::setApplicationIcon(const QString &iconPath)
+{
+ // During file loading, the assets might not have been read yet
+ QMetaObject::invokeMethod(this, "setApplicationIconDelayed", Qt::QueuedConnection, Q_ARG(QString, iconPath));
+}
+
+QStringList BarDescriptorEditorWidget::splashScreens() const
+{
+ QStringList result;
+
+ foreach (const QString &splashScreen, m_splashScreenModel->stringList())
+ result << QFileInfo(splashScreen).fileName();
+
+ return result;
+}
+
+void BarDescriptorEditorWidget::appendSplashScreen(const QString &splashScreenPath)
+{
+ // During file loading, the assets might not have been read yet
+ QMetaObject::invokeMethod(this, "appendSplashScreenDelayed", Qt::QueuedConnection, Q_ARG(QString, splashScreenPath));
+}
+
+void BarDescriptorEditorWidget::setApplicationIconDelayed(const QString &iconPath)
+{
+ const QString fullIconPath = localAssetPathFromDestination(iconPath);
+ setPathBlocked(m_ui->iconFilePath, fullIconPath);
+ setApplicationIconPreview(fullIconPath);
+}
+
+void BarDescriptorEditorWidget::setImagePreview(QLabel *previewLabel, const QString &path)
+{
+ if (path.isEmpty()) {
+ previewLabel->clear();
+ return;
+ }
+
+ QPixmap originalPixmap(path);
+ if (originalPixmap.isNull()) {
+ previewLabel->clear();
+ return;
+ }
+
+ QSize size = previewLabel->minimumSize();
+ QPixmap scaledPixmap = originalPixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ if (scaledPixmap.isNull()) {
+ previewLabel->clear();
+ return;
+ }
+
+ previewLabel->setPixmap(scaledPixmap);
+}
+
+void BarDescriptorEditorWidget::setApplicationIconPreview(const QString &path)
+{
+ setImagePreview(m_ui->iconPreviewLabel, path);
+}
+
+void BarDescriptorEditorWidget::appendSplashScreenDelayed(const QString &splashScreenPath)
+{
+ const QString fullSplashScreenPath = localAssetPathFromDestination(splashScreenPath);
+
+ disconnect(m_splashScreenModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+ int rowCount = m_splashScreenModel->rowCount();
+ m_splashScreenModel->insertRow(rowCount);
+ m_splashScreenModel->setData(m_splashScreenModel->index(rowCount), fullSplashScreenPath);
+ connect(m_splashScreenModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(setDirty()));
+}
+
+void BarDescriptorEditorWidget::browseForSplashScreen()
+{
+ const QString fileName = QFileDialog::getOpenFileName(this, tr("Select Splash Screen"), QString(), tr("Images (*.jpg *.png)"));
+ if (fileName.isEmpty())
+ return;
+
+ if (m_splashScreenModel->stringList().contains(fileName))
+ return;
+
+ int rowCount = m_splashScreenModel->rowCount();
+ m_splashScreenModel->insertRow(rowCount);
+ m_splashScreenModel->setData(m_splashScreenModel->index(rowCount), fileName);
+ addImageAsAsset(fileName);
+}
+
+void BarDescriptorEditorWidget::removeSelectedSplashScreen()
+{
+ QModelIndexList selectedIndexes = m_ui->splashScreensView->selectionModel()->selectedRows();
+ if (selectedIndexes.isEmpty())
+ return;
+
+ foreach (const QModelIndex &index, selectedIndexes) {
+ QString path = m_splashScreenModel->data(index, Qt::DisplayRole).toString();
+
+ QList<QStandardItem*> assetItems = m_assetsModel->findItems(path);
+ foreach (QStandardItem *assetItem, assetItems) {
+ QList<QStandardItem*> assetRow = m_assetsModel->takeRow(assetItem->row());
+ while (!assetRow.isEmpty())
+ delete assetRow.takeLast();
+ }
+
+ m_splashScreenModel->removeRow(index.row());
+ }
+}
+
+void BarDescriptorEditorWidget::handleSplashScreenSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+{
+ Q_UNUSED(deselected);
+
+ const bool emptySelection = selected.indexes().isEmpty();
+ m_ui->removeSplashScreen->setEnabled(!emptySelection);
+
+ if (!emptySelection) {
+ QString path = m_splashScreenModel->data(selected.indexes().at(0), Qt::DisplayRole).toString();
+ setImagePreview(m_ui->splashScreenPreviewLabel, path);
+ } else {
+ setImagePreview(m_ui->splashScreenPreviewLabel, QString());
+ }
+}
+
+void BarDescriptorEditorWidget::addAsset(const BarDescriptorAsset &asset)
+{
+ const QString path = asset.source;
+ const QString dest = asset.destination;
+ QTC_ASSERT(!path.isEmpty(), return);
+ QTC_ASSERT(!dest.isEmpty(), return);
+
+ if (hasAsset(asset))
+ return;
+
+ disconnect(m_assetsModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(updateEntryCheckState(QStandardItem*)));
+
+ QList<QStandardItem *> items;
+ items << new QStandardItem(path);
+ items << new QStandardItem(dest);
+
+ QStandardItem *entryItem = new QStandardItem();
+ entryItem->setCheckable(true);
+ entryItem->setCheckState(asset.entry ? Qt::Checked : Qt::Unchecked);
+ items << entryItem;
+ m_assetsModel->appendRow(items);
+
+ connect(m_assetsModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(updateEntryCheckState(QStandardItem*)));
+}
+
+bool BarDescriptorEditorWidget::hasAsset(const BarDescriptorAsset &asset)
+{
+ // TODO: Move this to a specific BarDescriptorAssetModel
+ for (int i = 0; i < m_assetsModel->rowCount(); ++i) {
+ QStandardItem *sourceItem = m_assetsModel->item(i, 0);
+ QStandardItem *destItem = m_assetsModel->item(i, 1);
+ if (sourceItem->text() == asset.source && destItem->text() == asset.destination)
+ return true;
+ }
+
+ return false;
+}
+
+QString BarDescriptorEditorWidget::localAssetPathFromDestination(const QString &destination)
+{
+ for (int i = 0; i < m_assetsModel->rowCount(); ++i) {
+ QStandardItem *destItem = m_assetsModel->item(i, 1);
+ if (destItem->text() == destination)
+ return m_assetsModel->item(i, 0)->text();
+ }
+
+ return QString();
+}
+
+QList<BarDescriptorAsset> BarDescriptorEditorWidget::assets() const
+{
+ QList<BarDescriptorAsset> result;
+
+ for (int i = 0; i < m_assetsModel->rowCount(); ++i) {
+ BarDescriptorAsset asset;
+ asset.source = m_assetsModel->item(i, 0)->text();
+ asset.destination = m_assetsModel->item(i, 1)->text();
+ asset.entry = m_assetsModel->item(i, 2)->checkState() == Qt::Checked;
+ result << asset;
+ }
+
+ return result;
+}
+
+QString BarDescriptorEditorWidget::xmlSource() const
+{
+ return m_ui->xmlSourceView->toPlainText();
+}
+
+void BarDescriptorEditorWidget::setXmlSource(const QString &xmlSource)
+{
+ disconnect(m_ui->xmlSourceView, SIGNAL(textChanged()), this, SLOT(setDirty()));
+ m_ui->xmlSourceView->setPlainText(xmlSource);
+ connect(m_ui->xmlSourceView, SIGNAL(textChanged()), this, SLOT(setDirty()));
+}
+
+bool BarDescriptorEditorWidget::isDirty() const
+{
+ return m_dirty;
+}
+
+void BarDescriptorEditorWidget::clear()
+{
+ clearGeneralPage();
+ clearApplicationPage();
+ clearAssetsPage();
+ clearSourcePage();
+}
+
+void BarDescriptorEditorWidget::setDirty(bool dirty)
+{
+ m_dirty = dirty;
+ emit changed();
+}
+
+BarDescriptorEditor *BarDescriptorEditorWidget::createEditor()
+{
+ return new BarDescriptorEditor(this);
+}
+
+void BarDescriptorEditorWidget::addNewAsset()
+{
+ const QString fileName = QFileDialog::getOpenFileName(this, tr("Select File to Add"));
+ if (fileName.isEmpty())
+ return;
+
+ QFileInfo fi(fileName);
+ BarDescriptorAsset asset;
+ asset.source = fileName;
+ asset.destination = fi.fileName();
+ asset.entry = false; // TODO
+ addAsset(asset);
+}
+
+void BarDescriptorEditorWidget::removeSelectedAsset()
+{
+ QModelIndexList selectedIndexes = m_ui->assets->selectionModel()->selectedRows();
+ if (selectedIndexes.isEmpty())
+ return;
+
+ foreach (const QModelIndex &index, selectedIndexes)
+ m_assetsModel->removeRow(index.row());
+}
+
+void BarDescriptorEditorWidget::updateEntryCheckState(QStandardItem *item)
+{
+ if (item->column() != 2 || item->checkState() == Qt::Unchecked)
+ return;
+
+ disconnect(m_assetsModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(updateEntryCheckState(QStandardItem*)));
+ for (int i = 0; i < m_assetsModel->rowCount(); ++i) {
+ QStandardItem *other = m_assetsModel->item(i, 2);
+ if (other == item)
+ continue;
+
+ // Only one asset can be the entry point
+ other->setCheckState(Qt::Unchecked);
+ }
+ connect(m_assetsModel, SIGNAL(itemChanged(QStandardItem*)), this, SLOT(updateEntryCheckState(QStandardItem*)));
+}
+
+void BarDescriptorEditorWidget::addImageAsAsset(const QString &path)
+{
+ if (path.isEmpty())
+ return;
+
+ BarDescriptorAsset asset;
+ asset.source = path;
+ asset.destination = QFileInfo(path).fileName();
+ asset.entry = false;
+ addAsset(asset);
+}
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.h b/src/plugins/qnx/bardescriptoreditorwidget.h
new file mode 100644
index 0000000000..b9fa8fcd7f
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditorwidget.h
@@ -0,0 +1,187 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QNX_INTERNAL_BARDESCRIPTOREDITORWIDGET_H
+#define QNX_INTERNAL_BARDESCRIPTOREDITORWIDGET_H
+
+#include "bardescriptordocument.h"
+
+#include <utils/environment.h>
+
+#include <QStackedWidget>
+
+QT_BEGIN_NAMESPACE
+class QItemSelection;
+class QLabel;
+class QLineEdit;
+class QStandardItemModel;
+class QStandardItem;
+class QStringListModel;
+QT_END_NAMESPACE
+
+namespace Core {
+class IEditor;
+}
+
+namespace Qnx {
+namespace Internal {
+
+namespace Ui {
+class BarDescriptorEditorWidget;
+}
+
+class BarDescriptorEditor;
+class BarDescriptorPermissionsModel;
+class BarDescriptorQtAssetsModel;
+class BarDescriptorQtAssetsProxyModel;
+
+class BarDescriptorEditorWidget : public QStackedWidget
+{
+ Q_OBJECT
+
+public:
+ explicit BarDescriptorEditorWidget(QWidget *parent = 0);
+ ~BarDescriptorEditorWidget();
+
+ Core::IEditor *editor() const;
+
+ // General
+ QString packageId() const;
+ void setPackageId(const QString &packageId);
+
+ QString packageVersion() const;
+ void setPackageVersion(const QString &packageVersion);
+
+ QString packageBuildId() const;
+ void setPackageBuildId(const QString &packageBuildId);
+
+ QString author() const;
+ void setAuthor(const QString &author);
+
+ QString authorId() const;
+ void setAuthorId(const QString &authorId);
+
+ // Application
+ QString orientation() const;
+ void setOrientation(const QString &orientation);
+
+ QString chrome() const;
+ void setChrome(const QString &chrome);
+
+ bool transparent() const;
+ void setTransparent(bool transparent);
+
+ void appendApplicationArgument(const QString &argument);
+ QStringList applicationArguments() const;
+
+ QStringList checkedPermissions() const;
+ void checkPermission(const QString &identifier);
+
+ QList<Utils::EnvironmentItem> environment() const;
+ void appendEnvironmentItem(const Utils::EnvironmentItem &envItem);
+
+ QString applicationName() const;
+ void setApplicationName(const QString &applicationName);
+
+ QString applicationDescription() const;
+ void setApplicationDescription(const QString &applicationDescription);
+
+ QString applicationIconFileName() const;
+ void setApplicationIcon(const QString &iconPath);
+
+ QStringList splashScreens() const;
+ void appendSplashScreen(const QString &splashScreenPath);
+
+ // Assets
+ void addAsset(const BarDescriptorAsset &asset);
+ QList<BarDescriptorAsset> assets() const;
+
+ QString xmlSource() const;
+ void setXmlSource(const QString &xmlSource);
+
+ bool isDirty() const;
+ void clear();
+
+public slots:
+ void setDirty(bool dirty = true);
+
+signals:
+ void changed();
+
+private slots:
+ void addNewAsset();
+ void removeSelectedAsset();
+ void updateEntryCheckState(QStandardItem *item);
+ void addImageAsAsset(const QString &path);
+
+ void setApplicationIconDelayed(const QString &iconPath);
+ void setApplicationIconPreview(const QString &path);
+
+ void appendSplashScreenDelayed(const QString &splashScreenPath);
+ void browseForSplashScreen();
+ void removeSelectedSplashScreen();
+ void handleSplashScreenSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
+
+private:
+ BarDescriptorEditor *createEditor();
+
+ void initGeneralPage();
+ void clearGeneralPage();
+ void initApplicationPage();
+ void clearApplicationPage();
+ void initAssetsPage();
+ void clearAssetsPage();
+ void initSourcePage();
+ void clearSourcePage();
+
+ bool hasAsset(const BarDescriptorAsset &asset);
+ QString localAssetPathFromDestination(const QString &path);
+
+ void setImagePreview(QLabel *previewLabel, const QString &path);
+
+ mutable Core::IEditor *m_editor;
+
+ bool m_dirty;
+
+ // Application
+ BarDescriptorPermissionsModel *m_permissionsModel;
+ QStringListModel *m_splashScreenModel;
+
+ // Assets
+ QStandardItemModel *m_assetsModel;
+
+ Ui::BarDescriptorEditorWidget *m_ui;
+};
+
+
+} // namespace Internal
+} // namespace Qnx
+#endif // QNX_INTERNAL_BARDESCRIPTOREDITORWIDGET_H
diff --git a/src/plugins/qnx/bardescriptoreditorwidget.ui b/src/plugins/qnx/bardescriptoreditorwidget.ui
new file mode 100644
index 0000000000..17c1c71bd7
--- /dev/null
+++ b/src/plugins/qnx/bardescriptoreditorwidget.ui
@@ -0,0 +1,540 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Qnx::Internal::BarDescriptorEditorWidget</class>
+ <widget class="QStackedWidget" name="Qnx::Internal::BarDescriptorEditorWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>1039</width>
+ <height>735</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>StackedWidget</string>
+ </property>
+ <property name="currentIndex">
+ <number>0</number>
+ </property>
+ <widget class="QWidget" name="generalPage">
+ <layout class="QVBoxLayout" name="verticalLayout_6">
+ <item>
+ <widget class="QScrollArea" name="scrollArea">
+ <property name="frameShape">
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="widgetResizable">
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="scrollAreaWidgetContents">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>1031</width>
+ <height>727</height>
+ </rect>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="groupBox_2">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Package Information</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Package ID:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="packageId">
+ <property name="maxLength">
+ <number>50</number>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>Package Version:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="packageVersion"/>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Package Build ID:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QLineEdit" name="packageBuildId"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="groupBox_6">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Author Information</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout_3">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Author:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QLineEdit" name="author"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_15">
+ <property name="text">
+ <string>Author ID:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="authorId"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="applicationPage">
+ <layout class="QVBoxLayout" name="verticalLayout_10">
+ <item>
+ <widget class="QScrollArea" name="scrollArea_2">
+ <property name="frameShape">
+ <enum>QFrame::NoFrame</enum>
+ </property>
+ <property name="widgetResizable">
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="scrollAreaWidgetContents_2">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>1014</width>
+ <height>810</height>
+ </rect>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_7">
+ <item>
+ <widget class="QGroupBox" name="groupBox">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Entry-Point Text and Images</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout_2">
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="applicationName"/>
+ </item>
+ <item row="3" column="1">
+ <widget class="QTextEdit" name="applicationDescription">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="1">
+ <layout class="QVBoxLayout" name="verticalLayout_8">
+ <item>
+ <widget class="QLabel" name="iconPreviewLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>90</width>
+ <height>90</height>
+ </size>
+ </property>
+ <property name="frameShape">
+ <enum>QFrame::Panel</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Sunken</enum>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_3">
+ <item>
+ <widget class="Utils::PathChooser" name="iconFilePath" native="true"/>
+ </item>
+ <item>
+ <widget class="QPushButton" name="iconClearButton">
+ <property name="text">
+ <string>Clear</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ <item row="6" column="0">
+ <widget class="QLabel" name="label_8">
+ <property name="text">
+ <string>Splash screens:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="7" column="0" colspan="2">
+ <layout class="QHBoxLayout" name="horizontalLayout_4">
+ <item>
+ <widget class="QListView" name="splashScreensView"/>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_9">
+ <item>
+ <widget class="QPushButton" name="addSplashScreen">
+ <property name="text">
+ <string>Add...</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeSplashScreen">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="text">
+ <string>Remove</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="splashScreenPreviewLabel">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>90</width>
+ <height>90</height>
+ </size>
+ </property>
+ <property name="frameShape">
+ <enum>QFrame::Panel</enum>
+ </property>
+ <property name="frameShadow">
+ <enum>QFrame::Sunken</enum>
+ </property>
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ <item row="5" column="0">
+ <widget class="QLabel" name="label_7">
+ <property name="text">
+ <string>Icon:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Description:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_6">
+ <property name="text">
+ <string>Name:</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="groupBox_3">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>General</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout_4">
+ <property name="fieldGrowthPolicy">
+ <enum>QFormLayout::ExpandingFieldsGrow</enum>
+ </property>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_12">
+ <property name="text">
+ <string>Orientation:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QComboBox" name="orientation"/>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_13">
+ <property name="text">
+ <string>Chrome:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QComboBox" name="chrome"/>
+ </item>
+ <item row="2" column="0" colspan="2">
+ <widget class="QCheckBox" name="transparentMainWindow">
+ <property name="text">
+ <string>Transparent main window</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <widget class="QLabel" name="label_14">
+ <property name="text">
+ <string>Application Arguments:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="1">
+ <widget class="QLineEdit" name="applicationArguments"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="groupBox_4">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Permissions</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <item>
+ <widget class="QTreeView" name="permissionsView">
+ <property name="rootIsDecorated">
+ <bool>false</bool>
+ </property>
+ <property name="itemsExpandable">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="selectAllPermissions">
+ <property name="text">
+ <string>Select All</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="deselectAllPermissions">
+ <property name="text">
+ <string>Deselect All</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QGroupBox" name="groupBox_5">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <property name="title">
+ <string>Environment</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_11">
+ <item>
+ <widget class="ProjectExplorer::EnvironmentWidget" name="environmentWidget" native="true"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="assetsPage">
+ <property name="maximumSize">
+ <size>
+ <width>900</width>
+ <height>16777215</height>
+ </size>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_5">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QTreeView" name="assets">
+ <property name="rootIsDecorated">
+ <bool>false</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QVBoxLayout" name="verticalLayout_4">
+ <item>
+ <widget class="QPushButton" name="addAsset">
+ <property name="text">
+ <string>Add...</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="removeAsset">
+ <property name="text">
+ <string>Remove</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="sourcePage">
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="TextEditor::PlainTextEditorWidget" name="xmlSourceView"/>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>TextEditor::PlainTextEditorWidget</class>
+ <extends>QPlainTextEdit</extends>
+ <header location="global">texteditor/plaintexteditor.h</header>
+ </customwidget>
+ <customwidget>
+ <class>Utils::PathChooser</class>
+ <extends>QWidget</extends>
+ <header location="global">utils/pathchooser.h</header>
+ <container>1</container>
+ </customwidget>
+ <customwidget>
+ <class>ProjectExplorer::EnvironmentWidget</class>
+ <extends>QWidget</extends>
+ <header location="global">projectexplorer/environmentwidget.h</header>
+ <container>1</container>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qnx/bardescriptormagicmatcher.cpp b/src/plugins/qnx/bardescriptormagicmatcher.cpp
new file mode 100644
index 0000000000..8e2af96d4a
--- /dev/null
+++ b/src/plugins/qnx/bardescriptormagicmatcher.cpp
@@ -0,0 +1,55 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptormagicmatcher.h"
+
+#include <QXmlStreamReader>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+BarDescriptorMagicMatcher::BarDescriptorMagicMatcher()
+{
+}
+
+bool BarDescriptorMagicMatcher::matches(const QByteArray &data) const
+{
+ QXmlStreamReader reader(data);
+ if (reader.readNextStartElement())
+ return reader.name() == QLatin1String("qnx");
+
+ return false;
+}
+
+int BarDescriptorMagicMatcher::priority() const
+{
+ return Core::MimeGlobPattern::MaxWeight;
+}
diff --git a/src/plugins/qt4projectmanager/profilekeywords.h b/src/plugins/qnx/bardescriptormagicmatcher.h
index 613397e7c8..661cd3bd08 100644
--- a/src/plugins/qt4projectmanager/profilekeywords.h
+++ b/src/plugins/qnx/bardescriptormagicmatcher.h
@@ -1,7 +1,9 @@
-/****************************************************************************
+/**************************************************************************
**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
@@ -27,27 +29,24 @@
**
****************************************************************************/
-#ifndef PROFILEKEYWORDS_H
-#define PROFILEKEYWORDS_H
-
-#include <QStringList>
+#ifndef QNX_INTERNAL_BARDESCRIPTORMAGICMATCHER_H
+#define QNX_INTERNAL_BARDESCRIPTORMAGICMATCHER_H
-namespace Qt4ProjectManager {
+#include <coreplugin/mimedatabase.h>
+namespace Qnx {
namespace Internal {
-class ProFileKeywords
+class BarDescriptorMagicMatcher : public Core::IMagicMatcher
{
public:
- static QStringList variables();
- static QStringList functions();
- static bool isVariable(const QString &word);
- static bool isFunction(const QString &word);
-private:
- ProFileKeywords();
+ BarDescriptorMagicMatcher();
+
+ bool matches(const QByteArray &data) const;
+ int priority() const;
};
} // namespace Internal
-} // namespace Qt4ProjectManager
+} // namespace Qnx
-#endif // PROFILEKEYWORDS_H
+#endif // QNX_INTERNAL_BARDESCRIPTORMAGICMATCHER_H
diff --git a/src/plugins/qnx/bardescriptorpermissionsmodel.cpp b/src/plugins/qnx/bardescriptorpermissionsmodel.cpp
new file mode 100644
index 0000000000..ccd700b545
--- /dev/null
+++ b/src/plugins/qnx/bardescriptorpermissionsmodel.cpp
@@ -0,0 +1,170 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "bardescriptorpermissionsmodel.h"
+
+#include <QStringList>
+
+using namespace Qnx;
+using namespace Qnx::Internal;
+
+BarDescriptorPermissionsModel::BarDescriptorPermissionsModel(QObject *parent) :
+ QAbstractTableModel(parent)
+{
+ initModel();
+}
+
+Qt::ItemFlags BarDescriptorPermissionsModel::flags(const QModelIndex &index) const
+{
+ Qt::ItemFlags flags = QAbstractTableModel::flags(index);
+ flags |= Qt::ItemIsUserCheckable;
+ return flags;
+}
+
+int BarDescriptorPermissionsModel::rowCount(const QModelIndex &parent) const
+{
+ Q_UNUSED(parent);
+ return m_permissions.size();
+}
+
+int BarDescriptorPermissionsModel::columnCount(const QModelIndex &parent) const
+{
+ Q_UNUSED(parent);
+ return 1;
+}
+
+QVariant BarDescriptorPermissionsModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid() || index.row() >= m_permissions.size() || index.column() >= 1)
+ return QVariant();
+
+ BarDescriptorPermission perm = m_permissions[index.row()];
+ switch (role) {
+ case Qt::DisplayRole:
+ case Qt::EditRole:
+ return perm.permission;
+ case Qt::CheckStateRole:
+ return perm.checked ? Qt::Checked : Qt::Unchecked;
+ case Qt::ToolTipRole:
+ return perm.description;
+ case IdentifierRole:
+ return perm.identifier;
+ }
+
+ return QVariant();
+}
+
+bool BarDescriptorPermissionsModel::setData(const QModelIndex &index, const QVariant &value, int role)
+{
+ if (!index.isValid() || index.row() >= m_permissions.size() || index.column() >= 1)
+ return false;
+
+ if (role == Qt::CheckStateRole) {
+ BarDescriptorPermission &perm = m_permissions[index.row()];
+ perm.checked = static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked;
+ emit dataChanged(index, index);
+
+ return true;
+ }
+
+ return false;
+}
+
+QVariant BarDescriptorPermissionsModel::headerData(int section, Qt::Orientation orientation, int role) const
+{
+ if (role != Qt::DisplayRole || orientation == Qt::Vertical)
+ return QVariant();
+
+ if (section == 0)
+ return tr("Permission");
+
+ return QVariant();
+}
+
+void BarDescriptorPermissionsModel::uncheckAll()
+{
+ setCheckStateAll(Qt::Unchecked);
+}
+
+void BarDescriptorPermissionsModel::checkAll()
+{
+ setCheckStateAll(Qt::Checked);
+}
+
+void BarDescriptorPermissionsModel::checkPermission(const QString &identifier)
+{
+ for (int i = 0; i < rowCount(); ++i) {
+ QModelIndex idx = index(i, 0);
+ if (data(idx, IdentifierRole).toString() == identifier)
+ setData(idx, Qt::Checked, Qt::CheckStateRole);
+ }
+}
+
+QStringList BarDescriptorPermissionsModel::checkedIdentifiers() const
+{
+ QStringList result;
+ foreach (const BarDescriptorPermission &perm, m_permissions) {
+ if (perm.checked)
+ result << perm.identifier;
+ }
+ return result;
+}
+
+void BarDescriptorPermissionsModel::initModel()
+{
+ beginResetModel();
+ m_permissions << BarDescriptorPermission(tr("Files"), QLatin1String("access_shared"),
+ tr("Read and write files that are shared between all applications run by the current user."));
+ m_permissions << BarDescriptorPermission(tr("Microphone"), QLatin1String("record_audio"),
+ tr("Access the audio stream from the microphone."));
+ m_permissions << BarDescriptorPermission(tr("GPS Location"), QLatin1String("read_geolocation"),
+ tr("Read the current location of the device."));
+ m_permissions << BarDescriptorPermission(tr("Camera"), QLatin1String("use_camera"),
+ tr("Capture images and video using the cameras."));
+ m_permissions << BarDescriptorPermission(tr("Internet"), QLatin1String("access_internet"),
+ tr("Use a Wi-Fi, wired, or other connection to a destination that is not local."));
+ m_permissions << BarDescriptorPermission(tr("Play Sounds"), QLatin1String("play_audio"),
+ tr("Play an audio stream."));
+ m_permissions << BarDescriptorPermission(tr("Post Notifications"), QLatin1String("post_notification"),
+ tr("Post a notification to the notifications area of the screen."));
+ m_permissions << BarDescriptorPermission(tr("Set Audio Volume"), QLatin1String("set_audio_volume"),
+ tr("Change the volume of an audio stream being played."));
+ m_permissions << BarDescriptorPermission(tr("Device Identifying Information"), QLatin1String("read_device_identifying_information"),
+ tr("Access unique device identifying information (e.g. PIN)."));
+ endResetModel();
+}
+
+
+void BarDescriptorPermissionsModel::setCheckStateAll(Qt::CheckState checkState)
+{
+ for (int i = 0; i < rowCount(); ++i)
+ setData(index(i, 0), checkState, Qt::CheckStateRole);
+}
diff --git a/src/plugins/qnx/bardescriptorpermissionsmodel.h b/src/plugins/qnx/bardescriptorpermissionsmodel.h
new file mode 100644
index 0000000000..1d1c60f3a9
--- /dev/null
+++ b/src/plugins/qnx/bardescriptorpermissionsmodel.h
@@ -0,0 +1,94 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2013 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef QNX_INTERNAL_BARDESCRIPTORPERMISSIONSMODEL_H
+#define QNX_INTERNAL_BARDESCRIPTORPERMISSIONSMODEL_H
+
+#include <QAbstractTableModel>
+
+namespace Qnx {
+namespace Internal {
+
+class BarDescriptorPermission {
+public:
+ BarDescriptorPermission(const QString &perm, const QString &ident, const QString &desc)
+ : checked(false)
+ , permission(perm)
+ , identifier(ident)
+ , description(desc)
+ {
+ }
+
+ bool checked;
+ QString permission;
+ QString identifier;
+ QString description;
+};
+
+class BarDescriptorPermissionsModel : public QAbstractTableModel
+{
+ Q_OBJECT
+public:
+ explicit BarDescriptorPermissionsModel(QObject *parent = 0);
+
+ Qt::ItemFlags flags(const QModelIndex &index) const;
+
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const;
+
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole);
+
+ QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
+
+ void checkPermission(const QString &identifier);
+ QStringList checkedIdentifiers() const;
+
+public slots:
+ void uncheckAll();
+ void checkAll();
+
+private:
+ enum DataRole {
+ IdentifierRole = Qt::UserRole
+ };
+
+ void setCheckStateAll(Qt::CheckState checkState);
+
+ void initModel();
+
+ QList<BarDescriptorPermission> m_permissions;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // QNX_INTERNAL_BARDESCRIPTORPERMISSIONSMODEL_H
diff --git a/src/plugins/qnx/blackberryapplicationrunner.cpp b/src/plugins/qnx/blackberryapplicationrunner.cpp
index 9fd9e00b1d..c44d84feb9 100644
--- a/src/plugins/qnx/blackberryapplicationrunner.cpp
+++ b/src/plugins/qnx/blackberryapplicationrunner.cpp
@@ -84,7 +84,7 @@ using namespace Qnx::Internal;
BlackBerryApplicationRunner::BlackBerryApplicationRunner(bool debugMode, BlackBerryRunConfiguration *runConfiguration, QObject *parent)
: QObject(parent)
, m_debugMode(debugMode)
- , m_slog2infoFound(true)
+ , m_slog2infoFound(false)
, m_pid(-1)
, m_appId(QString())
, m_running(false)
@@ -104,11 +104,11 @@ BlackBerryApplicationRunner::BlackBerryApplicationRunner(bool debugMode, BlackBe
m_environment = buildConfig->environment();
m_deployCmd = m_environment.searchInPath(QLatin1String(DEPLOY_CMD));
- m_deviceHost = runConfiguration->deployConfiguration()->deviceHost();
- m_password = runConfiguration->deployConfiguration()->password();
+ BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target->kit());
+ m_deviceHost = device->sshParameters().host;
+ m_password = device->sshParameters().password;
m_barPackage = runConfiguration->barPackage();
- BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target->kit());
m_sshParams = device->sshParameters();
// The BlackBerry device always uses key authentication
m_sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByKey;
@@ -147,7 +147,7 @@ void BlackBerryApplicationRunner::start()
void BlackBerryApplicationRunner::checkSlog2Info()
{
- if (m_testSlog2Process) {
+ if (m_slog2infoFound) {
readLaunchTime();
} else if (!m_testSlog2Process) {
m_testSlog2Process = new QSsh::SshRemoteProcessRunner(this);
@@ -233,11 +233,10 @@ void BlackBerryApplicationRunner::readStandardOutput()
QString line = QString::fromLocal8Bit(process->readLine());
emit output(line, Utils::StdOutFormat);
- if (line.startsWith(QLatin1String("result::"))) {
+ if (line.startsWith(QLatin1String("result::")))
m_pid = parsePid(line);
- } else if (line.startsWith(QLatin1String("Info: Launching"))) {
+ else if (line.startsWith(QLatin1String("Info: Launching")))
m_appId = parseAppId(line);
- }
}
}
@@ -256,11 +255,10 @@ void BlackBerryApplicationRunner::killTailProcess()
QSsh::SshRemoteProcessRunner *slayProcess = new QSsh::SshRemoteProcessRunner(this);
connect(slayProcess, SIGNAL(processClosed(int)), this, SIGNAL(finished()));
- if (m_slog2infoFound) {
+ if (m_slog2infoFound)
slayProcess->run("slay slog2info", m_sshParams);
- } else {
+ else
slayProcess->run("slay tail", m_sshParams);
- }
// Not supported by OpenSSH server
//m_tailProcess->sendSignalToProcess(Utils::SshRemoteProcess::KillSignal);
diff --git a/src/plugins/qnx/blackberryconfiguration.cpp b/src/plugins/qnx/blackberryconfiguration.cpp
new file mode 100644
index 0000000000..d51b671467
--- /dev/null
+++ b/src/plugins/qnx/blackberryconfiguration.cpp
@@ -0,0 +1,338 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "blackberryconfiguration.h"
+#include "blackberryqtversion.h"
+#include "qnxutils.h"
+
+#include <coreplugin/icore.h>
+
+#include <qtsupport/baseqtversion.h>
+#include <qtsupport/qtversionmanager.h>
+#include <qtsupport/qtkitinformation.h>
+
+#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/kitmanager.h>
+#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/gcctoolchain.h>
+#include <projectexplorer/toolchainmanager.h>
+
+#include <qt4projectmanager/qmakekitinformation.h>
+
+#include <debugger/debuggerkitinformation.h>
+
+#include <utils/persistentsettings.h>
+#include <utils/hostosinfo.h>
+
+#include <QFileInfo>
+#include <QDir>
+#include <QMessageBox>
+
+namespace Qnx {
+namespace Internal {
+
+namespace {
+const QLatin1String SettingsGroup("BlackBerryConfiguration");
+const QLatin1String NDKLocationKey("NDKLocation");
+}
+
+BlackBerryConfiguration::BlackBerryConfiguration(QObject *parent)
+ :QObject(parent)
+{
+ loadSetting();
+ connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveSetting()));
+}
+
+bool BlackBerryConfiguration::setConfig(const QString &ndkPath)
+{
+ if (ndkPath.isEmpty())
+ return false;
+
+ m_config.ndkPath = ndkPath;
+ m_config.qnxEnv = QnxUtils::parseEnvironmentFile(QnxUtils::envFilePath(ndkPath));
+
+ QString ndkTarget = m_config.qnxEnv.value(QLatin1String("QNX_TARGET"));
+ QString sep = QString::fromLatin1("%1qnx6").arg(QDir::separator());
+ m_config.targetName = ndkTarget.split(sep).first().split(QDir::separator()).last();
+
+ if (QDir(ndkTarget).exists())
+ m_config.sysRoot = Utils::FileName::fromString(ndkTarget);
+
+ QString qnxHost = m_config.qnxEnv.value(QLatin1String("QNX_HOST"));
+ Utils::FileName qmakePath = QnxUtils::executableWithExtension(Utils::FileName::fromString(qnxHost + QLatin1String("/usr/bin/qmake")));
+ Utils::FileName gccPath = QnxUtils::executableWithExtension(Utils::FileName::fromString(qnxHost + QLatin1String("/usr/bin/qcc")));
+ Utils::FileName deviceGdbPath = QnxUtils::executableWithExtension(Utils::FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntoarm-gdb")));
+ Utils::FileName simulatorGdbPath = QnxUtils::executableWithExtension(Utils::FileName::fromString(qnxHost + QLatin1String("/usr/bin/ntox86-gdb")));
+
+ if (!qmakePath.toFileInfo().exists() || !gccPath.toFileInfo().exists()
+ || !deviceGdbPath.toFileInfo().exists() || !simulatorGdbPath.toFileInfo().exists() ) {
+ QString errorMessage = tr("The following errors occurred while setting up BB10 Configuration:\n");
+ if (!qmakePath.toFileInfo().exists())
+ errorMessage += tr("- No Qt version found\n");
+
+ if (!gccPath.toFileInfo().exists())
+ errorMessage += tr("- No GCC compiler found\n");
+
+ if (!deviceGdbPath.toFileInfo().exists())
+ errorMessage += tr("- No Gdb debugger found for BB10 Device\n");
+
+ if (!simulatorGdbPath.toFileInfo().exists())
+ errorMessage += tr("- No Gdb debugger found for BB10 Simulator");
+
+ QMessageBox::warning(0, tr("Cannot Setup BB10 Configuration"),
+ errorMessage, QMessageBox::Ok);
+ return false;
+ }
+
+ m_config.qmakeBinaryFile = qmakePath;
+ m_config.gccCompiler = gccPath;
+ m_config.deviceDebuger = deviceGdbPath;
+ m_config.simulatorDebuger = simulatorGdbPath;
+
+ return true;
+}
+
+void BlackBerryConfiguration::setupConfiguration(const QString &ndkPath)
+{
+ if (ndkPath.isEmpty())
+ return;
+
+ if (setConfig(ndkPath)) {
+ QtSupport::BaseQtVersion *qtVersion = createQtVersion();
+ ProjectExplorer::GccToolChain *tc = createGccToolChain();
+ ProjectExplorer::Kit *deviceKit = createKit(ArmLeV7, qtVersion, tc);
+ ProjectExplorer::Kit *simulatorKit = createKit(X86, qtVersion, tc);
+ if (qtVersion && tc && deviceKit && simulatorKit) {
+ tc->setTargetAbi(qtVersion->qtAbis().first());
+ // register
+ QtSupport::QtVersionManager::instance()->addVersion(qtVersion);
+ ProjectExplorer::ToolChainManager::instance()->registerToolChain(tc);
+ ProjectExplorer::KitManager::instance()->registerKit(deviceKit);
+ ProjectExplorer::KitManager::instance()->registerKit(simulatorKit);
+
+ emit updated();
+ }
+ }
+}
+
+void BlackBerryConfiguration::cleanConfiguration()
+{
+ QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::instance()->qtVersionForQMakeBinary(m_config.qmakeBinaryFile);
+ if (version) {
+ foreach (ProjectExplorer::Kit *kit, ProjectExplorer::KitManager::instance()->kits()) {
+ if (version == QtSupport::QtKitInformation::qtVersion(kit))
+ ProjectExplorer::KitManager::instance()->deregisterKit(kit);
+ }
+
+ QtSupport::QtVersionManager::instance()->removeVersion(version);
+ }
+
+ foreach (ProjectExplorer::ToolChain* tc, ProjectExplorer::ToolChainManager::instance()->toolChains()) {
+ if (tc->compilerCommand() == m_config.gccCompiler)
+ ProjectExplorer::ToolChainManager::instance()->deregisterToolChain(tc);
+ }
+
+ BlackBerryConfig conf;
+ m_config = conf;
+ emit updated();
+
+ clearSetting();
+}
+
+QtSupport::BaseQtVersion *BlackBerryConfiguration::createQtVersion()
+{
+ if (m_config.qmakeBinaryFile.isEmpty())
+ return 0;
+
+ QString cpuDir = m_config.qnxEnv.value(QLatin1String("CPUVARDIR"));
+ QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::instance()->qtVersionForQMakeBinary(m_config.qmakeBinaryFile);
+ if (version) {
+ QMessageBox::warning(0, tr("Qt Version Already Known"),
+ tr("This Qt version was already registered"), QMessageBox::Ok);
+ return version;
+ }
+
+ version = new BlackBerryQtVersion(QnxUtils::cpudirToArch(cpuDir), m_config.qmakeBinaryFile, false, QString(), m_config.ndkPath);
+ if (!version) {
+ QMessageBox::warning(0, tr("Invalid Qt version"),
+ tr("Unable to add BlackBerry Qt version"), QMessageBox::Ok);
+ return 0;
+ }
+
+ version->setDisplayName(QString::fromLatin1("Qt BlackBerry 10 (%1)").arg(m_config.targetName));
+
+ return version;
+}
+
+ProjectExplorer::GccToolChain *BlackBerryConfiguration::createGccToolChain()
+{
+ if (m_config.qmakeBinaryFile.isEmpty() || m_config.gccCompiler.isEmpty())
+ return 0;
+
+ foreach (ProjectExplorer::ToolChain* tc, ProjectExplorer::ToolChainManager::instance()->toolChains()) {
+ if (tc->compilerCommand() == m_config.gccCompiler) {
+ QMessageBox::warning(0, tr("Compiler Already Known"),
+ tr("This Compiler was already registered"), QMessageBox::Ok);
+ return dynamic_cast<ProjectExplorer::GccToolChain*>(tc);
+ }
+ }
+
+ ProjectExplorer::GccToolChain* tc = new ProjectExplorer::GccToolChain(QLatin1String(ProjectExplorer::Constants::GCC_TOOLCHAIN_ID), false);
+ tc->setDisplayName(QString::fromLatin1("GCC BlackBerry 10 (%1)").arg(m_config.targetName));
+ tc->setCompilerCommand(m_config.gccCompiler);
+
+ return tc;
+}
+
+ProjectExplorer::Kit *BlackBerryConfiguration::createKit(QnxArchitecture arch, QtSupport::BaseQtVersion *qtVersion, ProjectExplorer::GccToolChain *tc)
+{
+ if (!qtVersion || !tc || m_config.targetName.isEmpty())
+ return 0;
+
+ // Check if an identical kit already exists
+ foreach (ProjectExplorer::Kit *kit, ProjectExplorer::KitManager::instance()->kits())
+ {
+ if (QtSupport::QtKitInformation::qtVersion(kit) == qtVersion && ProjectExplorer::ToolChainKitInformation::toolChain(kit) == tc
+ && ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(kit) == Constants::QNX_BB_OS_TYPE
+ && ProjectExplorer::SysRootKitInformation::sysRoot(kit) == m_config.sysRoot) {
+ if ((arch == X86 && Qt4ProjectManager::QmakeKitInformation::mkspec(kit).toString() == QString::fromLatin1("blackberry-x86-qcc")
+ && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_config.simulatorDebuger)
+ || (arch == ArmLeV7 && Debugger::DebuggerKitInformation::debuggerCommand(kit) == m_config.deviceDebuger)) {
+ QMessageBox::warning(0, tr("Kit Already Known"),
+ tr("This Kit was already registered"), QMessageBox::Ok);
+ return kit;
+ }
+ }
+ }
+
+ ProjectExplorer::Kit *kit = new ProjectExplorer::Kit;
+ QtSupport::QtKitInformation::setQtVersion(kit, qtVersion);
+ ProjectExplorer::ToolChainKitInformation::setToolChain(kit, tc);
+ if (arch == X86) {
+ Debugger::DebuggerKitInformation::setDebuggerCommand(kit, m_config.simulatorDebuger);
+ Qt4ProjectManager::QmakeKitInformation::setMkspec(kit, Utils::FileName::fromString(QString::fromLatin1("blackberry-x86-qcc")));
+ // TODO: Check if the name already exists(?)
+ kit->setDisplayName(tr("BlackBerry 10 (%1) - Simulator").arg(m_config.targetName));
+ } else {
+ Debugger::DebuggerKitInformation::setDebuggerCommand(kit, m_config.deviceDebuger);
+ kit->setDisplayName(tr("BlackBerry 10 (%1)").arg(m_config.targetName));
+ }
+
+ ProjectExplorer::DeviceTypeKitInformation::setDeviceTypeId(kit, Constants::QNX_BB_OS_TYPE);
+ ProjectExplorer::SysRootKitInformation::setSysRoot(kit, m_config.sysRoot);
+
+ return kit;
+}
+
+void BlackBerryConfiguration::loadSetting()
+{
+ QSettings *settings = Core::ICore::instance()->settings();
+ settings->beginGroup(SettingsGroup);
+ setConfig(settings->value(NDKLocationKey).toString());
+ settings->endGroup();
+}
+
+void BlackBerryConfiguration::saveSetting()
+{
+ if (m_config.ndkPath.isEmpty())
+ return;
+
+ QSettings *settings = Core::ICore::instance()->settings();
+ settings->beginGroup(SettingsGroup);
+ settings->setValue(NDKLocationKey, m_config.ndkPath);
+ settings->endGroup();
+}
+
+void BlackBerryConfiguration::clearSetting()
+{
+ QSettings *settings = Core::ICore::instance()->settings();
+ settings->beginGroup(SettingsGroup);
+ settings->remove(NDKLocationKey);
+ settings->endGroup();
+}
+
+BlackBerryConfiguration &BlackBerryConfiguration::instance()
+{
+ if (m_instance == 0)
+ m_instance = new BlackBerryConfiguration();
+ return *m_instance;
+}
+
+QString BlackBerryConfiguration::ndkPath() const
+{
+ return m_config.ndkPath;
+}
+
+QString BlackBerryConfiguration::targetName() const
+{
+ return m_config.targetName;
+}
+
+BlackBerryConfig BlackBerryConfiguration::config() const
+{
+ return m_config;
+}
+
+Utils::FileName BlackBerryConfiguration::qmakePath() const
+{
+ return m_config.qmakeBinaryFile;
+}
+
+Utils::FileName BlackBerryConfiguration::gccPath() const
+{
+ return m_config.gccCompiler;
+}
+
+Utils::FileName BlackBerryConfiguration::deviceGdbPath() const
+{
+ return m_config.deviceDebuger;
+}
+
+Utils::FileName BlackBerryConfiguration::simulatorGdbPath() const
+{
+ return m_config.simulatorDebuger;
+}
+
+Utils::FileName BlackBerryConfiguration::sysRoot() const
+{
+ return m_config.sysRoot;
+}
+
+// TODO: QnxUtils::parseEnvFile() and qnxEnv() to return Util::Enviroment instead(?)
+QMultiMap<QString, QString> BlackBerryConfiguration::qnxEnv() const
+{
+ return m_config.qnxEnv;
+}
+
+BlackBerryConfiguration* BlackBerryConfiguration::m_instance = 0;
+
+} // namespace Internal
+} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryconfiguration.h b/src/plugins/qnx/blackberryconfiguration.h
new file mode 100644
index 0000000000..e3935cfbf4
--- /dev/null
+++ b/src/plugins/qnx/blackberryconfiguration.h
@@ -0,0 +1,104 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef BLACKBERRYCONFIGURATIONS_H
+#define BLACKBERRYCONFIGURATIONS_H
+
+#include <qnxconstants.h>
+
+#include <utils/environment.h>
+#include <utils/fileutils.h>
+
+#include <qtsupport/baseqtversion.h>
+
+#include <projectexplorer/kit.h>
+#include <projectexplorer/gcctoolchain.h>
+
+#include <QSettings>
+#include <QObject>
+
+namespace Qnx {
+namespace Internal {
+
+class BlackBerryConfig
+{
+ QString ndkPath;
+ QString targetName;
+ Utils::FileName qmakeBinaryFile;
+ Utils::FileName gccCompiler;
+ Utils::FileName deviceDebuger;
+ Utils::FileName simulatorDebuger;
+ Utils::FileName sysRoot;
+ QMultiMap<QString, QString> qnxEnv;
+
+ friend class BlackBerryConfiguration;
+};
+
+class BlackBerryConfiguration: public QObject
+{
+ Q_OBJECT
+public:
+ static BlackBerryConfiguration &instance();
+ BlackBerryConfig config() const;
+ Utils::FileName qmakePath() const;
+ Utils::FileName gccPath() const;
+ Utils::FileName deviceGdbPath() const;
+ Utils::FileName simulatorGdbPath() const;
+ Utils::FileName sysRoot() const;
+ QMultiMap<QString, QString> qnxEnv() const;
+ void setupConfiguration(const QString &ndkPath);
+ QString ndkPath() const;
+ QString targetName() const;
+ void loadSetting();
+ void clearSetting();
+ void cleanConfiguration();
+
+public slots:
+ void saveSetting();
+
+private:
+ BlackBerryConfiguration(QObject *parent = 0);
+ static BlackBerryConfiguration *m_instance;
+ BlackBerryConfig m_config;
+
+ bool setConfig(const QString &ndkPath);
+ QtSupport::BaseQtVersion* createQtVersion();
+ ProjectExplorer::GccToolChain* createGccToolChain();
+ ProjectExplorer::Kit* createKit(QnxArchitecture arch, QtSupport::BaseQtVersion* qtVersion, ProjectExplorer::GccToolChain* tc);
+
+signals:
+ void updated();
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // BLACKBERRYCONFIGURATIONS_H
diff --git a/src/plugins/qnx/blackberryconnect.cpp b/src/plugins/qnx/blackberryconnect.cpp
index 37f0dcab86..0d4d6538c6 100644
--- a/src/plugins/qnx/blackberryconnect.cpp
+++ b/src/plugins/qnx/blackberryconnect.cpp
@@ -55,8 +55,12 @@ QMap<QString, int> BlackBerryConnect::m_usageCount = QMap<QString, int>();
BlackBerryConnect *BlackBerryConnect::instance(BlackBerryRunConfiguration *runConfig)
{
- BlackBerryDeployConfiguration *deployConfig = runConfig->deployConfiguration();
- QString deviceHost = deployConfig->deviceHost();
+
+ BlackBerryDeviceConfiguration::ConstPtr device
+ = BlackBerryDeviceConfiguration::device(runConfig->target()->kit());
+ QString deviceHost;
+ if (device)
+ deviceHost = device->sshParameters().host;
if (!m_instances.contains(deviceHost)) {
m_instances[deviceHost] = new BlackBerryConnect(runConfig);
m_usageCount[deviceHost] = 1;
@@ -97,11 +101,10 @@ BlackBerryConnect::BlackBerryConnect(BlackBerryRunConfiguration *runConfig)
m_connectCmd = env.searchInPath(QLatin1String(CONNECT_CMD));
m_qnxHost = env.value(QLatin1String("QNX_HOST"));
- BlackBerryDeployConfiguration *deployConfig = runConfig->deployConfiguration();
- m_deviceHost = deployConfig->deviceHost();
- m_password = deployConfig->password();
-
- BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target->kit());
+ BlackBerryDeviceConfiguration::ConstPtr device
+ = BlackBerryDeviceConfiguration::device(target->kit());
+ m_deviceHost = device->sshParameters().host;
+ m_password = device->sshParameters().password;
m_publicKeyFile = device->sshParameters().privateKeyFile + QLatin1String(".pub");
connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
diff --git a/src/plugins/qnx/blackberrydeployconfiguration.cpp b/src/plugins/qnx/blackberrydeployconfiguration.cpp
index 092b898ca0..a476c07d01 100644
--- a/src/plugins/qnx/blackberrydeployconfiguration.cpp
+++ b/src/plugins/qnx/blackberrydeployconfiguration.cpp
@@ -37,10 +37,15 @@
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/target.h>
+#include <projectexplorer/projectexplorer.h>
#include <qt4projectmanager/qt4nodes.h>
#include <qt4projectmanager/qt4project.h>
+#include <qt4projectmanager/qt4buildconfiguration.h>
+#include <coreplugin/icore.h>
#include <ssh/sshconnection.h>
+#include <QMessageBox>
+
using namespace Qnx;
using namespace Qnx::Internal;
@@ -60,6 +65,7 @@ BlackBerryDeployConfiguration::BlackBerryDeployConfiguration(ProjectExplorer::Ta
: ProjectExplorer::DeployConfiguration(parent, source)
{
ctor();
+ cloneSteps(source);
}
void BlackBerryDeployConfiguration::ctor()
@@ -72,42 +78,93 @@ void BlackBerryDeployConfiguration::ctor()
target()->project()->setNamedSettings(QLatin1String(DEPLOYMENT_INFO_SETTING), data);
}
+ connect(target()->project(), SIGNAL(proFilesEvaluated()), this, SLOT(setupBarDescriptor()), Qt::UniqueConnection);
+
setDefaultDisplayName(tr("Deploy to BlackBerry Device"));
}
-BlackBerryDeployConfiguration::~BlackBerryDeployConfiguration()
+void BlackBerryDeployConfiguration::setupBarDescriptor()
{
+ Qt4ProjectManager::Qt4BuildConfiguration *bc = qobject_cast<Qt4ProjectManager::Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
+ if (!bc || !target()->kit())
+ return;
+
+ Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target()->kit());
+ QString projectName = target()->project()->displayName();
+
+ if (deviceType == Constants::QNX_BB_OS_TYPE) {
+ const QLatin1String barDescriptorFileName("bar-descriptor.xml");
+ Utils::FileName barDescriptorPath = Utils::FileName::fromString(target()->project()->projectDirectory()).appendPath(barDescriptorFileName);
+ const QFile barDescriptorFile(barDescriptorPath.toString());
+ if (barDescriptorFile.exists())
+ return;
+
+ Utils::FileReader reader;
+ QString barDescriptorTemplate;
+ if (QDir(Utils::FileName::fromString(target()->project()->projectDirectory()).appendPath(QLatin1String("qml")).toString()).exists())
+ barDescriptorTemplate = Core::ICore::resourcePath()
+ + QLatin1String("/templates/wizards/bb-quickapp/") + barDescriptorFileName;
+ else
+ barDescriptorTemplate = Core::ICore::resourcePath()
+ + QLatin1String("/templates/wizards/bb-guiapp/") + barDescriptorFileName;
+
+
+ if (!reader.fetch(barDescriptorTemplate)) {
+ QMessageBox::warning(Core::ICore::mainWindow(),
+ tr("Error while setting up bar descriptor"),
+ tr("Reading bar descriptor template failed"),
+ QMessageBox::Ok);
+ return;
+ }
+
+ QString content = QString::fromUtf8(reader.data());
+ content.replace(QLatin1String("%ProjectName%"), projectName);
+ Utils::FileSaver writer(barDescriptorFile.fileName(), QIODevice::WriteOnly);
+ writer.write(content.toUtf8());
+ if (!writer.finalize()) {
+ QMessageBox::warning(Core::ICore::mainWindow(),
+ tr("Error while setting up bar descriptor"),
+ tr("Failure writing bar descriptor file."),
+ QMessageBox::Ok);
+ return;
+ }
+
+ // Add the Bar Descriptor to the existing project
+ if (target()->project()->rootProjectNode())
+ addBarDescriptorToProject(barDescriptorPath.toString());
+ }
}
-BlackBerryDeployInformation *BlackBerryDeployConfiguration::deploymentInfo() const
+void BlackBerryDeployConfiguration::addBarDescriptorToProject(const QString &barDesciptorPath)
{
- BlackBerryDeployInformation *info
- = qobject_cast<BlackBerryDeployInformation *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_INFO_SETTING)).value<QObject *>());
- return info;
+ if (barDesciptorPath.isEmpty())
+ return;
+
+ QMessageBox::StandardButton button =
+ QMessageBox::question(Core::ICore::mainWindow(),
+ tr("Add bar-descriptor.xml file to project"),
+ tr("Qt Creator has set up a bar descriptor file to enable "
+ "packaging.\nDo you want to add it to the project?"),
+ QMessageBox::Yes | QMessageBox::No);
+ if (button == QMessageBox::Yes)
+ ProjectExplorer::ProjectExplorerPlugin::instance()
+ ->addExistingFiles(target()->project()->rootProjectNode(), QStringList() << barDesciptorPath);
}
-QString BlackBerryDeployConfiguration::deviceHost() const
+BlackBerryDeployConfiguration::~BlackBerryDeployConfiguration()
{
- BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target()->kit());
- if (!device)
- return QString();
-
- return device->sshParameters().host;
}
-QString BlackBerryDeployConfiguration::password() const
+BlackBerryDeployInformation *BlackBerryDeployConfiguration::deploymentInfo() const
{
- BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target()->kit());
- return device->sshParameters().password;
+ BlackBerryDeployInformation *info
+ = qobject_cast<BlackBerryDeployInformation *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_INFO_SETTING)).value<QObject *>());
+ return info;
}
-QString BlackBerryDeployConfiguration::deviceName() const
+ProjectExplorer::NamedWidget *BlackBerryDeployConfiguration::createConfigWidget()
{
- BlackBerryDeviceConfiguration::ConstPtr device = BlackBerryDeviceConfiguration::device(target()->kit());
- if (!device)
- return QString();
-
- return device->displayName();
+ return new BlackBerryDeployConfigurationWidget(this);
}
QVariantMap BlackBerryDeployConfiguration::toMap() const
@@ -126,8 +183,3 @@ bool BlackBerryDeployConfiguration::fromMap(const QVariantMap &map)
deploymentInfo()->fromMap(deployInfoMap);
return true;
}
-
-ProjectExplorer::DeployConfigurationWidget *BlackBerryDeployConfiguration::configurationWidget() const
-{
- return new BlackBerryDeployConfigurationWidget;
-}
diff --git a/src/plugins/qnx/blackberrydeployconfiguration.h b/src/plugins/qnx/blackberrydeployconfiguration.h
index f0e034c993..fe20117080 100644
--- a/src/plugins/qnx/blackberrydeployconfiguration.h
+++ b/src/plugins/qnx/blackberrydeployconfiguration.h
@@ -54,14 +54,10 @@ public:
explicit BlackBerryDeployConfiguration(ProjectExplorer::Target *parent);
virtual ~BlackBerryDeployConfiguration();
- ProjectExplorer::DeployConfigurationWidget *configurationWidget() const;
+ ProjectExplorer::NamedWidget *createConfigWidget();
BlackBerryDeployInformation *deploymentInfo() const;
- QString deviceHost() const;
- QString password() const;
- QString deviceName() const;
-
QVariantMap toMap() const;
protected:
@@ -69,8 +65,12 @@ protected:
bool fromMap(const QVariantMap &map);
+private slots:
+ void setupBarDescriptor();
+
private:
void ctor();
+ void addBarDescriptorToProject(const QString& barDescriptorPath);
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrydeployconfigurationwidget.cpp b/src/plugins/qnx/blackberrydeployconfigurationwidget.cpp
index 073a407690..5f82687f44 100644
--- a/src/plugins/qnx/blackberrydeployconfigurationwidget.cpp
+++ b/src/plugins/qnx/blackberrydeployconfigurationwidget.cpp
@@ -43,22 +43,14 @@
using namespace Qnx;
using namespace Qnx::Internal;
-BlackBerryDeployConfigurationWidget::BlackBerryDeployConfigurationWidget(QWidget *parent)
- : ProjectExplorer::DeployConfigurationWidget(parent)
+BlackBerryDeployConfigurationWidget::BlackBerryDeployConfigurationWidget(BlackBerryDeployConfiguration *dc,
+ QWidget *parent)
+ : ProjectExplorer::NamedWidget(parent)
, m_ui(new Ui::BlackBerryDeployConfigurationWidget)
, m_deployConfiguration(0)
{
m_ui->setupUi(this);
-}
-
-BlackBerryDeployConfigurationWidget::~BlackBerryDeployConfigurationWidget()
-{
- delete m_ui;
-}
-
-void BlackBerryDeployConfigurationWidget::init(ProjectExplorer::DeployConfiguration *dc)
-{
- m_deployConfiguration = qobject_cast<BlackBerryDeployConfiguration *>(dc);
+ m_deployConfiguration = dc;
m_ui->deployPackagesView->setModel(m_deployConfiguration->deploymentInfo());
@@ -75,3 +67,8 @@ void BlackBerryDeployConfigurationWidget::init(ProjectExplorer::DeployConfigurat
m_ui->deployPackagesView->header()->resizeSections(QHeaderView::ResizeToContents);
}
+
+BlackBerryDeployConfigurationWidget::~BlackBerryDeployConfigurationWidget()
+{
+ delete m_ui;
+}
diff --git a/src/plugins/qnx/blackberrydeployconfigurationwidget.h b/src/plugins/qnx/blackberrydeployconfigurationwidget.h
index 7d49c77073..25c29c3f43 100644
--- a/src/plugins/qnx/blackberrydeployconfigurationwidget.h
+++ b/src/plugins/qnx/blackberrydeployconfigurationwidget.h
@@ -43,15 +43,13 @@ class BlackBerryDeployConfigurationWidget;
class BlackBerryDeployConfiguration;
-class BlackBerryDeployConfigurationWidget : public ProjectExplorer::DeployConfigurationWidget
+class BlackBerryDeployConfigurationWidget : public ProjectExplorer::NamedWidget
{
Q_OBJECT
public:
- explicit BlackBerryDeployConfigurationWidget(QWidget *parent = 0);
+ explicit BlackBerryDeployConfigurationWidget(BlackBerryDeployConfiguration *dc, QWidget *parent = 0);
~BlackBerryDeployConfigurationWidget();
- void init(ProjectExplorer::DeployConfiguration *dc);
-
private:
Ui::BlackBerryDeployConfigurationWidget *m_ui;
diff --git a/src/plugins/qnx/blackberrydeploystep.cpp b/src/plugins/qnx/blackberrydeploystep.cpp
index 77ead67e03..2086185fb3 100644
--- a/src/plugins/qnx/blackberrydeploystep.cpp
+++ b/src/plugins/qnx/blackberrydeploystep.cpp
@@ -41,6 +41,7 @@
#include <projectexplorer/target.h>
#include <qt4projectmanager/qt4buildconfiguration.h>
#include <utils/qtcassert.h>
+#include <ssh/sshconnection.h>
#include <QDir>
@@ -173,14 +174,20 @@ ProjectExplorer::BuildStepConfigWidget *BlackBerryDeployStep::createConfigWidget
QString BlackBerryDeployStep::deviceHost() const
{
- BlackBerryDeployConfiguration *dc = static_cast<BlackBerryDeployConfiguration *>(deployConfiguration());
- return dc->deviceHost();
+ BlackBerryDeviceConfiguration::ConstPtr device
+ = BlackBerryDeviceConfiguration::device(target()->kit());
+ if (device)
+ return device->sshParameters().host;
+ return QString();
}
QString BlackBerryDeployStep::password() const
{
- BlackBerryDeployConfiguration *dc = static_cast<BlackBerryDeployConfiguration *>(deployConfiguration());
- return dc->password();
+ BlackBerryDeviceConfiguration::ConstPtr device
+ = BlackBerryDeviceConfiguration::device(target()->kit());
+ if (device)
+ return device->sshParameters().password;
+ return QString();
}
void BlackBerryDeployStep::raiseError(const QString &errorMessage)
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp b/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp
index bdee9d7665..936bc9f446 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizard.cpp
@@ -66,7 +66,7 @@ BlackBerryDeviceConfigurationWizard::BlackBerryDeviceConfigurationWizard(QWidget
ProjectExplorer::IDevice::Ptr BlackBerryDeviceConfigurationWizard::device()
{
QSsh::SshConnectionParameters sshParams;
- sshParams.proxyType = QSsh::SshConnectionParameters::NoProxy;
+ sshParams.options = QSsh::SshIgnoreDefaultProxy;
sshParams.host = m_setupPage->hostName();
sshParams.password = m_setupPage->password();
sshParams.authenticationType = QSsh::SshConnectionParameters::AuthenticationByKey;
@@ -86,9 +86,8 @@ ProjectExplorer::IDevice::Ptr BlackBerryDeviceConfigurationWizard::device()
void BlackBerryDeviceConfigurationWizard::accept()
{
if (m_sshKeyPage->isGenerated()) {
- if (saveKeys()) {
+ if (saveKeys())
QWizard::accept();
- }
} else {
QWizard::accept();
}
@@ -131,9 +130,8 @@ bool BlackBerryDeviceConfigurationWizard::saveKeys()
pubKeyContent.append(atHost.toLocal8Bit());
pubSaver.write(pubKeyContent);
- if (!pubSaver.finalize(this)) {
+ if (!pubSaver.finalize(this))
return false;
- }
return true;
}
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp
index 2b4b206d0d..7d8e8d94af 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.cpp
@@ -45,6 +45,11 @@ using namespace Qnx::Internal;
namespace {
const char DEVICENAME_FIELD_ID[] = "DeviceName";
+
+QString defaultDeviceHostIp(IDevice::MachineType type)
+{
+ return type == IDevice::Hardware ? QLatin1String("169.254.0.1") : QString();
+}
}
BlackBerryDeviceConfigurationWizardSetupPage::BlackBerryDeviceConfigurationWizardSetupPage(QWidget *parent)
@@ -59,7 +64,7 @@ BlackBerryDeviceConfigurationWizardSetupPage::BlackBerryDeviceConfigurationWizar
connect(m_ui->deviceName, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
connect(m_ui->deviceHostIp, SIGNAL(textChanged(QString)), this, SIGNAL(completeChanged()));
- connect(m_ui->physicalDevice, SIGNAL(toggled(bool)), this, SIGNAL(completeChanged()));
+ connect(m_ui->physicalDevice, SIGNAL(toggled(bool)), this, SLOT(handleMachineTypeChanged()));
connect(m_ui->debugToken, SIGNAL(changed(QString)), this, SIGNAL(completeChanged()));
registerField(QLatin1String(DEVICENAME_FIELD_ID), m_ui->deviceName);
@@ -74,9 +79,9 @@ BlackBerryDeviceConfigurationWizardSetupPage::~BlackBerryDeviceConfigurationWiza
void BlackBerryDeviceConfigurationWizardSetupPage::initializePage()
{
m_ui->deviceName->setText(tr("BlackBerry Device"));
- m_ui->deviceHostIp->setText(QString());
m_ui->password->setText(QString());
m_ui->physicalDevice->setChecked(true);
+ m_ui->deviceHostIp->setText(defaultDeviceHostIp(machineType()));
}
bool BlackBerryDeviceConfigurationWizardSetupPage::isComplete() const
@@ -114,6 +119,12 @@ IDevice::MachineType BlackBerryDeviceConfigurationWizardSetupPage::machineType()
return m_ui->physicalDevice->isChecked() ? IDevice::Hardware : IDevice::Emulator;
}
+void BlackBerryDeviceConfigurationWizardSetupPage::handleMachineTypeChanged()
+{
+ if (m_ui->deviceHostIp->text().isEmpty())
+ m_ui->deviceHostIp->setText(defaultDeviceHostIp(machineType()));
+}
+
// ----------------------------------------------------------------------------
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h
index d12f8a77bb..8467bcece6 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardpages.h
@@ -63,6 +63,9 @@ public:
QString debugToken() const;
ProjectExplorer::IDevice::MachineType machineType() const;
+private slots:
+ void handleMachineTypeChanged();
+
private:
Ui::BlackBerryDeviceConfigurationWizardSetupPage *m_ui;
};
diff --git a/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui b/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui
index c08f32dd37..47ec51805f 100644
--- a/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui
+++ b/src/plugins/qnx/blackberrydeviceconfigurationwizardsetuppage.ui
@@ -7,13 +7,16 @@
<x>0</x>
<y>0</y>
<width>546</width>
- <height>148</height>
+ <height>170</height>
</rect>
</property>
<property name="windowTitle">
<string>WizardPage</string>
</property>
<layout class="QFormLayout" name="formLayout">
+ <property name="fieldGrowthPolicy">
+ <enum>QFormLayout::FieldsStayAtSizeHint</enum>
+ </property>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
@@ -24,14 +27,14 @@
<item row="0" column="1">
<widget class="QLineEdit" name="deviceName"/>
</item>
- <item row="1" column="0">
+ <item row="3" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>The device's host name or IP address:</string>
</property>
</widget>
</item>
- <item row="1" column="1">
+ <item row="3" column="1">
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLineEdit" name="deviceHostIp"/>
@@ -51,14 +54,14 @@
</item>
</layout>
</item>
- <item row="2" column="0">
+ <item row="4" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Device password:</string>
</property>
</widget>
</item>
- <item row="2" column="1">
+ <item row="4" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QLineEdit" name="password">
@@ -82,14 +85,24 @@
</item>
</layout>
</item>
- <item row="3" column="0">
+ <item row="6" column="0">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Debug token:</string>
+ </property>
+ </widget>
+ </item>
+ <item row="6" column="1">
+ <widget class="Utils::PathChooser" name="debugToken" native="true"/>
+ </item>
+ <item row="1" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Device type:</string>
</property>
</widget>
</item>
- <item row="3" column="1">
+ <item row="1" column="1">
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QRadioButton" name="physicalDevice">
@@ -107,16 +120,6 @@
</item>
</layout>
</item>
- <item row="4" column="0">
- <widget class="QLabel" name="label_5">
- <property name="text">
- <string>Debug token:</string>
- </property>
- </widget>
- </item>
- <item row="4" column="1">
- <widget class="Utils::PathChooser" name="debugToken" native="true"/>
- </item>
</layout>
</widget>
<customwidgets>
diff --git a/src/plugins/qnx/blackberryndksettingspage.cpp b/src/plugins/qnx/blackberryndksettingspage.cpp
new file mode 100644
index 0000000000..f5bb94b2dc
--- /dev/null
+++ b/src/plugins/qnx/blackberryndksettingspage.cpp
@@ -0,0 +1,69 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "blackberryndksettingspage.h"
+#include "blackberryndksettingswidget.h"
+#include "qnxconstants.h"
+
+#include <projectexplorer/projectexplorerconstants.h>
+
+#include <QCoreApplication>
+
+namespace Qnx {
+namespace Internal {
+
+BlackBerryNDKSettingsPage::BlackBerryNDKSettingsPage(QObject *parent) :
+ Core::IOptionsPage(parent)
+{
+ setId(Core::Id(Constants::QNX_BB_NDK_SETTINGS_ID));
+ setDisplayName(tr("NDK"));
+ setCategory(Constants::QNX_BB_CATEGORY);
+ setDisplayCategory(QCoreApplication::translate("BlackBerry",
+ Constants::QNX_BB_CATEGORY_TR));
+ setCategoryIcon(QLatin1String(Constants::QNX_BB_CATEGORY_ICON));
+}
+
+QWidget *BlackBerryNDKSettingsPage::createPage(QWidget *parent)
+{
+ m_widget = new BlackBerryNDKSettingsWidget(parent);
+ return m_widget;
+}
+
+void BlackBerryNDKSettingsPage::apply()
+{
+}
+
+void BlackBerryNDKSettingsPage::finish()
+{
+}
+
+} // namespace Internal
+} // namespace Qnx
diff --git a/src/plugins/qnx/blackberryndksettingspage.h b/src/plugins/qnx/blackberryndksettingspage.h
new file mode 100644
index 0000000000..af31f7ef04
--- /dev/null
+++ b/src/plugins/qnx/blackberryndksettingspage.h
@@ -0,0 +1,58 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef BLACKBERRYNDKSETTINGSPAGE_H
+#define BLACKBERRYNDKSETTINGSPAGE_H
+
+#include <coreplugin/dialogs/ioptionspage.h>
+
+namespace Qnx {
+namespace Internal {
+
+class BlackBerryNDKSettingsWidget;
+
+class BlackBerryNDKSettingsPage : public Core::IOptionsPage
+{
+ Q_OBJECT
+public:
+ explicit BlackBerryNDKSettingsPage(QObject *parent = 0);
+ QWidget *createPage(QWidget *parent);
+ void apply();
+ void finish();
+
+private:
+ BlackBerryNDKSettingsWidget *m_widget;
+};
+
+} // namespace Internal
+} // namespace Qnx
+
+#endif // BLACKBERRYNDKSETTINGSPAGE_H
diff --git a/src/plugins/qnx/blackberryndksettingswidget.cpp b/src/plugins/qnx/blackberryndksettingswidget.cpp
new file mode 100644
index 0000000000..5673559741
--- /dev/null
+++ b/src/plugins/qnx/blackberryndksettingswidget.cpp
@@ -0,0 +1,133 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "blackberryndksettingswidget.h"
+#include "ui_blackberryndksettingswidget.h"
+#include "qnxutils.h"
+
+#include <utils/pathchooser.h>
+
+#include <coreplugin/icore.h>
+
+#include <QMessageBox>
+
+namespace Qnx {
+namespace Internal {
+
+BlackBerryNDKSettingsWidget::BlackBerryNDKSettingsWidget(QWidget *parent) :
+ QWidget(parent),
+ m_ui(new Ui_BlackBerryNDKSettingsWidget)
+{
+ m_bbConfig = &BlackBerryConfiguration::instance();
+ m_ui->setupUi(this);
+ m_ui->sdkPath->setExpectedKind(Utils::PathChooser::ExistingDirectory);
+ m_ui->sdkPath->setPath(m_bbConfig->ndkPath());
+
+ initInfoTable();
+
+ connect(m_ui->sdkPath, SIGNAL(changed(QString)), this, SLOT(checkSdkPath()));
+ connect(m_ui->removeButton, SIGNAL(clicked()), this, SLOT(cleanConfiguration()));
+ connect(m_bbConfig, SIGNAL(updated()), this, SLOT(updateInfoTable()));
+}
+
+void BlackBerryNDKSettingsWidget::checkSdkPath()
+{
+ if (!m_ui->sdkPath->path().isEmpty() &&
+ QnxUtils::isValidNdkPath(m_ui->sdkPath->path()))
+ m_bbConfig->setupConfiguration(m_ui->sdkPath->path());
+}
+
+void BlackBerryNDKSettingsWidget::updateInfoTable()
+{
+ QMultiMap<QString, QString> env = m_bbConfig->qnxEnv();
+
+ if (env.isEmpty()) {
+ // clear
+ clearInfoTable();
+ return;
+ }
+
+ m_infoModel->clear();
+ m_infoModel->setHorizontalHeaderItem(0, new QStandardItem(QString(QLatin1String("Variable"))));
+ m_infoModel->setHorizontalHeaderItem(1, new QStandardItem(QString(QLatin1String("Value"))));
+
+ m_ui->ndkInfosTableView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents);
+ m_ui->ndkInfosTableView->horizontalHeader()->setStretchLastSection(true);
+
+ QMultiMap<QString, QString>::const_iterator it;
+ QMultiMap<QString, QString>::const_iterator end(env.constEnd());
+ for (it = env.constBegin(); it != end; ++it) {
+ const QString key = it.key();
+ const QString value = it.value();
+ QList <QStandardItem*> row;
+ row << new QStandardItem(key) << new QStandardItem(value);
+ m_infoModel->appendRow(row);
+ }
+
+ m_infoModel->appendRow( QList<QStandardItem*>() << new QStandardItem(QString(QLatin1String("QMAKE"))) << new QStandardItem(m_bbConfig->qmakePath().toString()));
+ m_infoModel->appendRow( QList<QStandardItem*>() << new QStandardItem(QString(QLatin1String("COMPILER"))) << new QStandardItem(m_bbConfig->gccPath().toString()));
+
+ m_ui->removeButton->setEnabled(true);
+}
+
+void BlackBerryNDKSettingsWidget::clearInfoTable()
+{
+ m_infoModel->clear();
+ m_ui->sdkPath->setPath(QString());
+ m_ui->removeButton->setEnabled(false);
+}
+
+void BlackBerryNDKSettingsWidget::cleanConfiguration()
+{
+ QMessageBox::StandardButton button =
+ QMessageBox::question(Core::ICore::mainWindow(),
+ tr("Clean BlackBerry 10 Configuration"),
+ tr("Are you sure you want to remove the current BlackBerry configuration?"),
+ QMessageBox::Yes | QMessageBox::No);
+
+ if (button == QMessageBox::Yes)
+ m_bbConfig->cleanConfiguration();
+}
+
+void BlackBerryNDKSettingsWidget::initInfoTable()
+{
+ m_infoModel = new QStandardItemModel(this);
+
+ m_ui->ndkInfosTableView->setModel(m_infoModel);
+ m_ui->ndkInfosTableView->verticalHeader()->hide();
+ m_ui->ndkInfosTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
+
+ updateInfoTable();
+}
+
+} // namespace Internal
+} // namespace Qnx
+
diff --git a/src/plugins/qnx/blackberryndksettingswidget.h b/src/plugins/qnx/blackberryndksettingswidget.h
new file mode 100644
index 0000000000..edf76bbce9
--- /dev/null
+++ b/src/plugins/qnx/blackberryndksettingswidget.h
@@ -0,0 +1,74 @@
+/**************************************************************************
+**
+** Copyright (C) 2011 - 2012 Research In Motion
+**
+** Contact: Research In Motion (blackberry-qt@qnx.com)
+** Contact: KDAB (info@kdab.com)
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef BLACKBERRYNDKSETTINGSWIDGET_H
+#define BLACKBERRYNDKSETTINGSWIDGET_H
+
+#include "blackberryconfiguration.h"
+
+#include <QWidget>
+#include <QStandardItemModel>
+
+
+namespace Qnx {
+namespace Internal {
+
+class Ui_BlackBerryNDKSettingsWidget;
+
+
+class BlackBerryNDKSettingsWidget : public QWidget
+{
+ Q_OBJECT
+public:
+ explicit BlackBerryNDKSettingsWidget(QWidget *parent = 0);
+
+signals:
+ void sdkPathChanged();
+
+public slots:
+ void checkSdkPath();
+ void updateInfoTable();
+ void clearInfoTable();
+ void cleanConfiguration();
+
+private:
+ void initInfoTable();
+ QString m_sdkPath;
+ Ui_BlackBerryNDKSettingsWidget *m_ui;
+ BlackBerryConfiguration *m_bbConfig;
+ QStandardItemModel *m_infoModel;
+
+};
+
+} // namespace Internal
+} // namespeace Qnx
+
+#endif // BLACKBERRYNDKSETTINGSWIDGET_H
diff --git a/src/plugins/qnx/blackberryndksettingswidget.ui b/src/plugins/qnx/blackberryndksettingswidget.ui
new file mode 100644
index 0000000000..a926e5822d
--- /dev/null
+++ b/src/plugins/qnx/blackberryndksettingswidget.ui
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>Qnx::Internal::BlackBerryNDKSettingsWidget</class>
+ <widget class="QWidget" name="Qnx::Internal::BlackBerryNDKSettingsWidget">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>794</width>
+ <height>473</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>BlackBerry NDK Path </string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="Utils::PathChooser" name="sdkPath" native="true"/>
+ </item>
+ </layout>
+ </item>
+ <item row="0" column="1">
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QPushButton" name="removeButton">
+ <property name="text">
+ <string>Remove</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item row="1" column="0">
+ <widget class="QTableView" name="ndkInfosTableView"/>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>Utils::PathChooser</class>
+ <extends>QWidget</extends>
+ <header location="global">utils/pathchooser.h</header>
+ <container>1</container>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/plugins/qnx/blackberryqtversion.cpp b/src/plugins/qnx/blackberryqtversion.cpp
index ddad6a2c2b..03d98241c8 100644
--- a/src/plugins/qnx/blackberryqtversion.cpp
+++ b/src/plugins/qnx/blackberryqtversion.cpp
@@ -31,9 +31,11 @@
#include "blackberryqtversion.h"
+#include "qnxutils.h"
#include "qnxconstants.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QTextStream>
@@ -41,110 +43,18 @@
using namespace Qnx;
using namespace Qnx::Internal;
-namespace {
-QMultiMap<QString, QString> parseEnvironmentFile(const QString &fileName)
-{
- QMultiMap<QString, QString> result;
-
- QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly))
- return result;
-
- QTextStream str(&file);
- QMap<QString, QString> fileContent;
- while (!str.atEnd()) {
- QString line = str.readLine();
- if (!line.contains(QLatin1Char('=')))
- continue;
-
- int equalIndex = line.indexOf(QLatin1Char('='));
- QString var = line.left(equalIndex);
- //Remove set in front
- if (var.startsWith(QLatin1String("set ")))
- var = var.right(var.size() - 4);
-
- QString value = line.mid(equalIndex + 1);
-
-#if defined Q_OS_WIN
- QRegExp systemVarRegExp(QLatin1String("IF NOT DEFINED ([\\w\\d]+)\\s+set ([\\w\\d]+)=([\\w\\d]+)"));
- if (line.contains(systemVarRegExp)) {
- var = systemVarRegExp.cap(2);
- Utils::Environment sysEnv = Utils::Environment::systemEnvironment();
- QString sysVar = systemVarRegExp.cap(1);
- if (sysEnv.hasKey(sysVar))
- value = sysEnv.value(sysVar);
- else
- value = systemVarRegExp.cap(3);
- }
-#elif defined Q_OS_UNIX
- QRegExp systemVarRegExp(QLatin1String("\\$\\{([\\w\\d]+):=([\\w\\d]+)\\}")); // to match e.g. "${QNX_HOST_VERSION:=10_0_9_52}"
- if (value.contains(systemVarRegExp)) {
- Utils::Environment sysEnv = Utils::Environment::systemEnvironment();
- QString sysVar = systemVarRegExp.cap(1);
- if (sysEnv.hasKey(sysVar))
- value = sysEnv.value(sysVar);
- else
- value = systemVarRegExp.cap(2);
- }
-#endif
-
- if (value.startsWith(QLatin1Char('"')))
- value = value.mid(1);
- if (value.endsWith(QLatin1Char('"')))
- value = value.left(value.size() - 1);
-
- fileContent[var] = value;
- }
- file.close();
-
- QMapIterator<QString, QString> it(fileContent);
- while (it.hasNext()) {
- it.next();
-#if defined Q_OS_WIN
- QStringList values = it.value().split(QLatin1Char(';'));
-#elif defined Q_OS_UNIX
- QStringList values = it.value().split(QLatin1Char(':'));
-#endif
- QString key = it.key();
- foreach (const QString &value, values) {
- const QString ownKeyAsWindowsVar = QLatin1Char('%') + key + QLatin1Char('%');
- const QString ownKeyAsUnixVar = QLatin1Char('$') + key;
- if (value != ownKeyAsUnixVar && value != ownKeyAsWindowsVar) { // to ignore e.g. PATH=$PATH
- QString val = value;
- if (val.contains(QLatin1Char('%')) || val.contains(QLatin1Char('$'))) {
- QMapIterator<QString, QString> replaceIt(fileContent);
- while (replaceIt.hasNext()) {
- replaceIt.next();
- const QString replaceKey = replaceIt.key();
- if (replaceKey == key)
- continue;
-
- const QString keyAsWindowsVar = QLatin1Char('%') + replaceKey + QLatin1Char('%');
- const QString keyAsUnixVar = QLatin1Char('$') + replaceKey;
- if (val.contains(keyAsWindowsVar))
- val.replace(keyAsWindowsVar, replaceIt.value());
- if (val.contains(keyAsUnixVar))
- val.replace(keyAsUnixVar, replaceIt.value());
- }
- }
- result.insert(key, val);
- }
- }
- }
-
- return result;
-}
-}
-
BlackBerryQtVersion::BlackBerryQtVersion()
: QnxAbstractQtVersion()
{
}
-BlackBerryQtVersion::BlackBerryQtVersion(QnxArchitecture arch, const Utils::FileName &path, bool isAutoDetected, const QString &autoDetectionSource)
+BlackBerryQtVersion::BlackBerryQtVersion(QnxArchitecture arch, const Utils::FileName &path, bool isAutoDetected, const QString &autoDetectionSource, const QString &sdkPath)
: QnxAbstractQtVersion(arch, path, isAutoDetected, autoDetectionSource)
{
-
+ if (QnxUtils::isValidNdkPath(sdkPath))
+ setSdkPath(sdkPath);
+ else
+ setDefaultSdkPath();
}
BlackBerryQtVersion::~BlackBerryQtVersion()
@@ -173,12 +83,20 @@ QMultiMap<QString, QString> BlackBerryQtVersion::environment() const
if (sdkPath().isEmpty())
return QMultiMap<QString, QString>();
-#if defined Q_OS_WIN
- const QString envFile = sdkPath() + QLatin1String("/bbndk-env.bat");
-#elif defined Q_OS_UNIX
- const QString envFile = sdkPath() + QLatin1String("/bbndk-env.sh");
-#endif
- return parseEnvironmentFile(envFile);
+ return QnxUtils::parseEnvironmentFile(QnxUtils::envFilePath(sdkPath()));
+}
+
+void BlackBerryQtVersion::setDefaultSdkPath()
+{
+ QHash<QString, QString> info = versionInfo();
+ QString qtHostPrefix;
+ if (info.contains(QLatin1String("QT_HOST_PREFIX")))
+ qtHostPrefix = info.value(QLatin1String("QT_HOST_PREFIX"));
+ else
+ return;
+
+ if (QnxUtils::isValidNdkPath(qtHostPrefix))
+ setSdkPath(qtHostPrefix);
}
Core::FeatureSet BlackBerryQtVersion::availableFeatures() const
diff --git a/src/plugins/qnx/blackberryqtversion.h b/src/plugins/qnx/blackberryqtversion.h
index d9af5f42bb..59160e1c35 100644
--- a/src/plugins/qnx/blackberryqtversion.h
+++ b/src/plugins/qnx/blackberryqtversion.h
@@ -44,8 +44,9 @@ class BlackBerryQtVersion : public QnxAbstractQtVersion
public:
BlackBerryQtVersion();
BlackBerryQtVersion(QnxArchitecture arch, const Utils::FileName &path,
- bool isAutoDetected = false,
- const QString &autoDetectionSource = QString());
+ bool isAutoDetected = false,
+ const QString &autoDetectionSource = QString(),
+ const QString &sdkPath = QString());
BlackBerryQtVersion *clone() const;
~BlackBerryQtVersion();
@@ -61,6 +62,7 @@ public:
private:
QMultiMap<QString, QString> environment() const;
+ void setDefaultSdkPath();
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberryrunconfiguration.cpp b/src/plugins/qnx/blackberryrunconfiguration.cpp
index 9d014026a7..b833cc7e32 100644
--- a/src/plugins/qnx/blackberryrunconfiguration.cpp
+++ b/src/plugins/qnx/blackberryrunconfiguration.cpp
@@ -87,7 +87,12 @@ QString BlackBerryRunConfiguration::proFilePath() const
QString BlackBerryRunConfiguration::deviceName() const
{
- return deployConfiguration()->deviceName();
+ BlackBerryDeviceConfiguration::ConstPtr device
+ = BlackBerryDeviceConfiguration::device(target()->kit());
+ if (!device)
+ return QString();
+
+ return device->displayName();
}
QString BlackBerryRunConfiguration::barPackage() const
@@ -98,9 +103,8 @@ QString BlackBerryRunConfiguration::barPackage() const
QList<BarPackageDeployInformation> packages = dc->deploymentInfo()->enabledPackages();
foreach (const BarPackageDeployInformation package, packages) {
- if (package.proFilePath == proFilePath()) {
+ if (package.proFilePath == proFilePath())
return package.packagePath;
- }
}
return QString();
}
diff --git a/src/plugins/qnx/blackberryruncontrolfactory.cpp b/src/plugins/qnx/blackberryruncontrolfactory.cpp
index 4a73104d1a..eb8cafd7ff 100644
--- a/src/plugins/qnx/blackberryruncontrolfactory.cpp
+++ b/src/plugins/qnx/blackberryruncontrolfactory.cpp
@@ -72,7 +72,7 @@ bool BlackBerryRunControlFactory::canRun(ProjectExplorer::RunConfiguration *runC
// not launch a second instance. Disable the Run button if the application is already
// running on the device.
if (m_activeRunControls.contains(rc->key())) {
- QWeakPointer<ProjectExplorer::RunControl> activeRunControl = m_activeRunControls[rc->key()];
+ QPointer<ProjectExplorer::RunControl> activeRunControl = m_activeRunControls[rc->key()];
if (activeRunControl && activeRunControl.data()->isRunning())
return false;
else
@@ -101,7 +101,7 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
if (mode == ProjectExplorer::NormalRunMode) {
BlackBerryRunControl *runControl = new BlackBerryRunControl(rc);
- m_activeRunControls[rc->key()] = QWeakPointer<ProjectExplorer::RunControl>(runControl);
+ m_activeRunControls[rc->key()] = runControl;
return runControl;
}
@@ -111,7 +111,7 @@ ProjectExplorer::RunControl *BlackBerryRunControlFactory::create(ProjectExplorer
return 0;
new BlackBerryDebugSupport(rc, runControl);
- m_activeRunControls[rc->key()] = QWeakPointer<ProjectExplorer::RunControl>(runControl);
+ m_activeRunControls[rc->key()] = runControl;
return runControl;
}
@@ -120,13 +120,6 @@ QString BlackBerryRunControlFactory::displayName() const
return tr("Run on BlackBerry Device");
}
-ProjectExplorer::RunConfigWidget *BlackBerryRunControlFactory::createConfigurationWidget(
- ProjectExplorer::RunConfiguration *runConfiguration)
-{
- Q_UNUSED(runConfiguration);
- return 0;
-}
-
Debugger::DebuggerStartParameters BlackBerryRunControlFactory::startParameters(
const BlackBerryRunConfiguration *runConfig)
{
@@ -158,9 +151,8 @@ Debugger::DebuggerStartParameters BlackBerryRunControlFactory::startParameters(
if (const ProjectExplorer::Project *project = runConfig->target()->project()) {
params.projectSourceDirectory = project->projectDirectory();
- if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration()) {
+ if (const ProjectExplorer::BuildConfiguration *buildConfig = runConfig->target()->activeBuildConfiguration())
params.projectBuildDirectory = buildConfig->buildDirectory();
- }
params.projectSourceFiles = project->files(ProjectExplorer::Project::ExcludeGeneratedFiles);
}
diff --git a/src/plugins/qnx/blackberryruncontrolfactory.h b/src/plugins/qnx/blackberryruncontrolfactory.h
index c83482cd37..c31191f207 100644
--- a/src/plugins/qnx/blackberryruncontrolfactory.h
+++ b/src/plugins/qnx/blackberryruncontrolfactory.h
@@ -60,13 +60,10 @@ public:
QString displayName() const;
- ProjectExplorer::RunConfigWidget *createConfigurationWidget(
- ProjectExplorer::RunConfiguration *runConfiguration);
-
private:
static Debugger::DebuggerStartParameters startParameters( const BlackBerryRunConfiguration *runConfig);
- mutable QMap<QString, QWeakPointer<ProjectExplorer::RunControl> > m_activeRunControls;
+ mutable QMap<QString, QPointer<ProjectExplorer::RunControl> > m_activeRunControls;
};
} // namespace Internal
diff --git a/src/plugins/qnx/blackberrywizardextension.cpp b/src/plugins/qnx/blackberrywizardextension.cpp
index de50157df7..16d9e46485 100644
--- a/src/plugins/qnx/blackberrywizardextension.cpp
+++ b/src/plugins/qnx/blackberrywizardextension.cpp
@@ -51,6 +51,7 @@ BlackBerryWizardExtension::BlackBerryWizardExtension()
QList<QWizardPage *> BlackBerryWizardExtension::extensionPages(const Core::IWizard *wizard)
{
QStringList validIds;
+ validIds << QLatin1String(Constants::QNX_BLACKBERRY_CASCADES_WIZARD_ID);
validIds << QLatin1String(Constants::QNX_BAR_DESCRIPTOR_WIZARD_ID);
validIds << QLatin1String(Constants::QNX_BLACKBERRY_QTQUICK_APP_WIZARD_ID);
validIds << QLatin1String(Constants::QNX_BLACKBERRY_GUI_APP_WIZARD_ID);
diff --git a/src/plugins/qnx/qnx.pro b/src/plugins/qnx/qnx.pro
index 5bc1501bab..01e82f444b 100644
--- a/src/plugins/qnx/qnx.pro
+++ b/src/plugins/qnx/qnx.pro
@@ -52,7 +52,17 @@ SOURCES += qnxplugin.cpp \
qnxdeviceconfiguration.cpp \
blackberrydeployinformation.cpp \
pathchooserdelegate.cpp \
- blackberryabstractdeploystep.cpp
+ blackberryabstractdeploystep.cpp \
+ blackberryndksettingswidget.cpp \
+ blackberryndksettingspage.cpp \
+ blackberryconfiguration.cpp \
+ bardescriptormagicmatcher.cpp \
+ bardescriptoreditorfactory.cpp \
+ bardescriptoreditor.cpp \
+ bardescriptoreditorwidget.cpp \
+ bardescriptordocument.cpp \
+ bardescriptordocumentnodehandlers.cpp \
+ bardescriptorpermissionsmodel.cpp
HEADERS += qnxplugin.h\
qnxconstants.h \
@@ -101,7 +111,17 @@ HEADERS += qnxplugin.h\
qnxdeviceconfiguration.h \
blackberrydeployinformation.h \
pathchooserdelegate.h \
- blackberryabstractdeploystep.h
+ blackberryabstractdeploystep.h \
+ blackberryndksettingswidget.h \
+ blackberryndksettingspage.h \
+ blackberryconfiguration.h \
+ bardescriptormagicmatcher.h \
+ bardescriptoreditorfactory.h \
+ bardescriptoreditor.h \
+ bardescriptoreditorwidget.h \
+ bardescriptordocument.h \
+ bardescriptordocumentnodehandlers.h \
+ bardescriptorpermissionsmodel.h
FORMS += \
blackberrydeviceconfigurationwizardsetuppage.ui \
@@ -110,7 +130,9 @@ FORMS += \
blackberrydeployconfigurationwidget.ui \
blackberrydeviceconfigurationwidget.ui \
qnxbaseqtconfigwidget.ui \
- bardescriptorfileimagewizardpage.ui
+ bardescriptorfileimagewizardpage.ui \
+ blackberryndksettingswidget.ui \
+ bardescriptoreditorwidget.ui
DEFINES += QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
diff --git a/src/plugins/qnx/qnx.qbs b/src/plugins/qnx/qnx.qbs
index a23e9c1146..967587700b 100644
--- a/src/plugins/qnx/qnx.qbs
+++ b/src/plugins/qnx/qnx.qbs
@@ -12,53 +12,63 @@ QtcPlugin {
Depends { name: "QtSupport" }
Depends { name: "Qt4ProjectManager" }
Depends { name: "RemoteLinux" }
+ Depends { name: "TextEditor" }
Depends { name: "Qt"; submodules: ["widgets", "xml", "network"] }
- cpp.defines: base.concat(["QT_NO_CAST_TO_ASCII", "QT_NO_CAST_FROM_ASCII"])
- cpp.includePaths: [
- "..",
- buildDirectory,
- "../../libs",
- "../../shared"
- ]
+ cpp.includePaths: base.concat("../../shared")
files: [
+ "bardescriptordocument.cpp",
+ "bardescriptordocument.h",
+ "bardescriptordocumentnodehandlers.cpp",
+ "bardescriptordocumentnodehandlers.h",
+ "bardescriptoreditor.cpp",
+ "bardescriptoreditor.h",
+ "bardescriptoreditorfactory.cpp",
+ "bardescriptoreditorfactory.h",
+ "bardescriptoreditorwidget.cpp",
+ "bardescriptoreditorwidget.h",
+ "bardescriptoreditorwidget.ui",
"bardescriptorfileimagewizardpage.cpp",
"bardescriptorfileimagewizardpage.h",
"bardescriptorfileimagewizardpage.ui",
+ "bardescriptormagicmatcher.cpp",
+ "bardescriptormagicmatcher.h",
+ "bardescriptorpermissionsmodel.cpp",
+ "bardescriptorpermissionsmodel.h",
"blackberryabstractdeploystep.cpp",
"blackberryabstractdeploystep.h",
"blackberryapplicationrunner.cpp",
"blackberryapplicationrunner.h",
"blackberryconnect.cpp",
"blackberryconnect.h",
+ "blackberrycreatepackagestep.cpp",
+ "blackberrycreatepackagestep.h",
"blackberrycreatepackagestepconfigwidget.cpp",
"blackberrycreatepackagestepconfigwidget.h",
- "blackberrycreatepackagestep.cpp",
"blackberrycreatepackagestepfactory.cpp",
"blackberrycreatepackagestepfactory.h",
- "blackberrycreatepackagestep.h",
"blackberrydebugsupport.cpp",
"blackberrydebugsupport.h",
"blackberrydeployconfiguration.cpp",
+ "blackberrydeployconfiguration.h",
"blackberrydeployconfigurationfactory.cpp",
"blackberrydeployconfigurationfactory.h",
- "blackberrydeployconfiguration.h",
"blackberrydeployconfigurationwidget.cpp",
"blackberrydeployconfigurationwidget.h",
"blackberrydeployconfigurationwidget.ui",
"blackberrydeployinformation.cpp",
"blackberrydeployinformation.h",
+ "blackberrydeploystep.cpp",
+ "blackberrydeploystep.h",
"blackberrydeploystepconfigwidget.cpp",
"blackberrydeploystepconfigwidget.h",
- "blackberrydeploystep.cpp",
"blackberrydeploystepfactory.cpp",
"blackberrydeploystepfactory.h",
- "blackberrydeploystep.h",
"blackberrydeviceconfiguration.cpp",
+ "blackberrydeviceconfiguration.h",
"blackberrydeviceconfigurationfactory.cpp",
"blackberrydeviceconfigurationfactory.h",
- "blackberrydeviceconfiguration.h",
"blackberrydeviceconfigurationwidget.cpp",
"blackberrydeviceconfigurationwidget.h",
"blackberrydeviceconfigurationwidget.ui",
@@ -69,26 +79,32 @@ QtcPlugin {
"blackberrydeviceconfigurationwizardsetuppage.ui",
"blackberrydeviceconfigurationwizardsshkeypage.ui",
"blackberryqtversion.cpp",
+ "blackberryqtversion.h",
"blackberryqtversionfactory.cpp",
"blackberryqtversionfactory.h",
- "blackberryqtversion.h",
"blackberryrunconfiguration.cpp",
+ "blackberryrunconfiguration.h",
"blackberryrunconfigurationfactory.cpp",
"blackberryrunconfigurationfactory.h",
- "blackberryrunconfiguration.h",
"blackberryrunconfigurationwidget.cpp",
"blackberryrunconfigurationwidget.h",
"blackberryrunconfigurationwidget.ui",
"blackberryruncontrol.cpp",
+ "blackberryruncontrol.h",
"blackberryruncontrolfactory.cpp",
"blackberryruncontrolfactory.h",
- "blackberryruncontrol.h",
+ "blackberryndksettingswidget.cpp",
+ "blackberryndksettingswidget.h",
+ "blackberryndksettingswidget.ui",
+ "blackberryndksettingspage.cpp",
+ "blackberryndksettingspage.h",
+ "blackberryconfiguration.cpp",
+ "blackberryconfiguration.h",
"blackberrywizardextension.cpp",
"blackberrywizardextension.h",
- "images/target.png",
- "images/target-small.png",
"pathchooserdelegate.cpp",
"pathchooserdelegate.h",
+ "qnx.qrc",
"qnxabstractqtversion.cpp",
"qnxabstractqtversion.h",
"qnxbaseqtconfigwidget.cpp",
@@ -98,35 +114,36 @@ QtcPlugin {
"qnxdebugsupport.cpp",
"qnxdebugsupport.h",
"qnxdeployconfiguration.cpp",
+ "qnxdeployconfiguration.h",
"qnxdeployconfigurationfactory.cpp",
"qnxdeployconfigurationfactory.h",
- "qnxdeployconfiguration.h",
"qnxdeploystepfactory.cpp",
"qnxdeploystepfactory.h",
"qnxdeviceconfiguration.cpp",
+ "qnxdeviceconfiguration.h",
"qnxdeviceconfigurationfactory.cpp",
"qnxdeviceconfigurationfactory.h",
- "qnxdeviceconfiguration.h",
"qnxdeviceconfigurationwizard.cpp",
"qnxdeviceconfigurationwizard.h",
"qnxdeviceconfigurationwizardpages.cpp",
"qnxdeviceconfigurationwizardpages.h",
"qnxplugin.cpp",
"qnxplugin.h",
- "qnx.qrc",
"qnxqtversion.cpp",
+ "qnxqtversion.h",
"qnxqtversionfactory.cpp",
"qnxqtversionfactory.h",
- "qnxqtversion.h",
"qnxrunconfiguration.cpp",
+ "qnxrunconfiguration.h",
"qnxrunconfigurationfactory.cpp",
"qnxrunconfigurationfactory.h",
- "qnxrunconfiguration.h",
"qnxruncontrol.cpp",
+ "qnxruncontrol.h",
"qnxruncontrolfactory.cpp",
"qnxruncontrolfactory.h",
- "qnxruncontrol.h",
"qnxutils.cpp",
- "qnxutils.h"
+ "qnxutils.h",
+ "images/target-small.png",
+ "images/target.png",
]
}
diff --git a/src/plugins/qnx/qnx_dependencies.pri b/src/plugins/qnx/qnx_dependencies.pri
index 9077f38f6f..7ad421acfa 100644
--- a/src/plugins/qnx/qnx_dependencies.pri
+++ b/src/plugins/qnx/qnx_dependencies.pri
@@ -1,3 +1,4 @@
include(../../plugins/coreplugin/coreplugin.pri)
include(../../plugins/qt4projectmanager/qt4projectmanager.pri)
include(../../plugins/remotelinux/remotelinux.pri)
+include(../../plugins/texteditor/texteditor.pri)
diff --git a/src/plugins/qnx/qnxabstractqtversion.cpp b/src/plugins/qnx/qnxabstractqtversion.cpp
index f74dd25f3f..f01305b958 100644
--- a/src/plugins/qnx/qnxabstractqtversion.cpp
+++ b/src/plugins/qnx/qnxabstractqtversion.cpp
@@ -30,10 +30,12 @@
****************************************************************************/
#include "qnxabstractqtversion.h"
-
#include "qnxbaseqtconfigwidget.h"
+#include "qnxutils.h"
+
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QDir>
@@ -50,7 +52,6 @@ QnxAbstractQtVersion::QnxAbstractQtVersion(QnxArchitecture arch, const Utils::Fi
: QtSupport::BaseQtVersion(path, isAutoDetected, autoDetectionSource)
, m_arch(arch)
{
- setDefaultSdkPath();
}
QnxArchitecture QnxAbstractQtVersion::architecture() const
@@ -68,7 +69,6 @@ QString QnxAbstractQtVersion::archString() const
case UnknownArch:
return QString();
}
-
return QString();
}
@@ -96,25 +96,24 @@ QList<ProjectExplorer::Abi> QnxAbstractQtVersion::detectQtAbis() const
void QnxAbstractQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const
{
QtSupport::BaseQtVersion::addToEnvironment(k, env);
+ updateEnvironment();
+ QnxUtils::prependQnxMapToEnvironment(m_envMap, env);
+ env.prependOrSetLibrarySearchPath(versionInfo().value(QLatin1String("QT_INSTALL_LIBS")));
+}
- if (!m_environmentUpToDate)
- updateEnvironment();
-
- QMultiMap<QString, QString>::const_iterator it;
- QMultiMap<QString, QString>::const_iterator end(m_envMap.constEnd());
- for (it = m_envMap.constBegin(); it != end; ++it) {
- const QString key = it.key();
- const QString value = it.value();
-
- if (key == QLatin1String("PATH"))
- env.prependOrSetPath(value);
- else if (key == QLatin1String("LD_LIBRARY_PATH"))
- env.prependOrSetLibrarySearchPath(value);
- else
- env.set(key, value);
+Utils::Environment QnxAbstractQtVersion::qmakeRunEnvironment() const
+{
+ if (!m_environmentUpToDate && !sdkPath().isEmpty())
+ {
+ // TODO: return Utils::Environment instead(?)
+ m_envMap = QnxUtils::parseEnvironmentFile(QnxUtils::envFilePath(sdkPath()));
+ m_environmentUpToDate = true;
}
- env.prependOrSetLibrarySearchPath(versionInfo().value(QLatin1String("QT_INSTALL_LIBS")));
+ Utils::Environment env = Utils::Environment::systemEnvironment();
+ QnxUtils::prependQnxMapToEnvironment(m_envMap, env);
+
+ return env;
}
QString QnxAbstractQtVersion::sdkPath() const
@@ -133,8 +132,10 @@ void QnxAbstractQtVersion::setSdkPath(const QString &sdkPath)
void QnxAbstractQtVersion::updateEnvironment() const
{
- m_envMap = environment();
- m_environmentUpToDate = true;
+ if (!m_environmentUpToDate) {
+ m_envMap = environment();
+ m_environmentUpToDate = true;
+ }
}
QString QnxAbstractQtVersion::qnxHost() const
@@ -170,23 +171,3 @@ QString QnxAbstractQtVersion::invalidReason() const
return QtSupport::BaseQtVersion::invalidReason();
}
-void QnxAbstractQtVersion::setDefaultSdkPath()
-{
- QHash<QString, QString> info = versionInfo();
- QString qtHostPrefix;
- if (info.contains(QLatin1String("QT_HOST_PREFIX")))
- qtHostPrefix = info.value(QLatin1String("QT_HOST_PREFIX"));
- else
- return;
-
- QString envFile;
-#if defined Q_OS_WIN
- envFile = qtHostPrefix + QLatin1String("/bbndk-env.bat");
-#elif defined Q_OS_UNIX
- envFile = qtHostPrefix + QLatin1String("/bbndk-env.sh");
-#endif
-
- if (QFileInfo(envFile).exists())
- setSdkPath(qtHostPrefix);
-
-}
diff --git a/src/plugins/qnx/qnxabstractqtversion.h b/src/plugins/qnx/qnxabstractqtversion.h
index a786eb768b..c00cbf2dea 100644
--- a/src/plugins/qnx/qnxabstractqtversion.h
+++ b/src/plugins/qnx/qnxabstractqtversion.h
@@ -63,6 +63,7 @@ public:
QList<ProjectExplorer::Abi> detectQtAbis() const;
void addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const;
+ Utils::Environment qmakeRunEnvironment() const;
QtSupport::QtConfigWidget *createConfigurationWidget() const;
@@ -70,17 +71,15 @@ public:
QString invalidReason() const;
virtual QString sdkDescription() const = 0;
- void setDefaultSdkPath();
protected:
QString sdkPath() const;
+ void setSdkPath(const QString &sdkPath);
private:
void updateEnvironment() const;
virtual QMultiMap<QString, QString> environment() const = 0;
- void setSdkPath(const QString &sdkPath);
-
QnxArchitecture m_arch;
QString m_sdkPath;
diff --git a/src/plugins/qnx/qnxconstants.h b/src/plugins/qnx/qnxconstants.h
index b2e808a472..bbf31e3d6e 100644
--- a/src/plugins/qnx/qnxconstants.h
+++ b/src/plugins/qnx/qnxconstants.h
@@ -32,6 +32,8 @@
#ifndef QNX_QNXCONSTANTS_H
#define QNX_QNXCONSTANTS_H
+#include <QtGlobal>
+
namespace Qnx {
enum QnxArchitecture {
@@ -75,6 +77,7 @@ const char QNX_QNX_OS_TYPE[] = "QnxOsType";
const char QNX_DEBUG_TOKEN_KEY[] = "debugToken";
+const char QNX_BLACKBERRY_CASCADES_WIZARD_ID[] = "Q.QnxBlackBerryCascadesApp";
const char QNX_BAR_DESCRIPTOR_WIZARD_ID[] = "Q.QnxBlackBerryBarDescriptor";
const char QNX_BLACKBERRY_QTQUICK_APP_WIZARD_ID[] = "Q.QnxBlackBerryQQApp";
const char QNX_BLACKBERRY_QTQUICK2_APP_WIZARD_ID[] = "Q.QnxBlackBerryQQ2App";
@@ -85,6 +88,16 @@ const char QNX_BB_PLATFORM_NAME[] = "BlackBerry";
const char QNX_DEBUG_EXECUTABLE[] = "pdebug";
+// BlackBerry settings constants
+const char QNX_BB_CATEGORY[] = "XF.BlackBerry";
+const char QNX_BB_CATEGORY_TR[] = QT_TRANSLATE_NOOP("BlackBerry", "BlackBerry");
+const char QNX_BB_CATEGORY_ICON[] = ":/qnx/images/target.png";
+const char QNX_BB_NDK_SETTINGS_ID[] = "ZZ.BlackBerry NDK Configuration";
+
+const char QNX_BAR_DESCRIPTOR_MIME_TYPE[] = "application/vnd.rim.qnx.bar_descriptor";
+const char QNX_BAR_DESCRIPTOR_EDITOR_ID[] = "Qnx.BarDescriptorEditor";
+
+const char QNX_TASK_CATEGORY_BARDESCRIPTOR[] = "Task.Category.BarDescriptor";
} // namespace Constants
} // namespace Qnx
diff --git a/src/plugins/qnx/qnxdeployconfiguration.cpp b/src/plugins/qnx/qnxdeployconfiguration.cpp
index 158a21c0ae..1e952588d2 100644
--- a/src/plugins/qnx/qnxdeployconfiguration.cpp
+++ b/src/plugins/qnx/qnxdeployconfiguration.cpp
@@ -42,4 +42,5 @@ QnxDeployConfiguration::QnxDeployConfiguration(ProjectExplorer::Target *target,
QnxDeployConfiguration::QnxDeployConfiguration(ProjectExplorer::Target *target, QnxDeployConfiguration *source)
: RemoteLinux::RemoteLinuxDeployConfiguration(target, source)
{
+ cloneSteps(source);
}
diff --git a/src/plugins/qnx/qnxdeviceconfigurationfactory.cpp b/src/plugins/qnx/qnxdeviceconfigurationfactory.cpp
index 371b04540f..d94b344b5d 100644
--- a/src/plugins/qnx/qnxdeviceconfigurationfactory.cpp
+++ b/src/plugins/qnx/qnxdeviceconfigurationfactory.cpp
@@ -67,9 +67,8 @@ ProjectExplorer::IDevice::Ptr QnxDeviceConfigurationFactory::create(Core::Id id)
{
Q_UNUSED(id);
QnxDeviceConfigurationWizard wizard;
- if (wizard.exec() != QDialog::Accepted) {
+ if (wizard.exec() != QDialog::Accepted)
return ProjectExplorer::IDevice::Ptr();
- }
return wizard.device();
}
diff --git a/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp b/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp
index 3b8167050a..cc8b9929b0 100644
--- a/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp
+++ b/src/plugins/qnx/qnxdeviceconfigurationwizard.cpp
@@ -61,17 +61,16 @@ QnxDeviceConfigurationWizard::QnxDeviceConfigurationWizard(QWidget *parent) :
IDevice::Ptr QnxDeviceConfigurationWizard::device()
{
QSsh::SshConnectionParameters sshParams;
- sshParams.proxyType = QSsh::SshConnectionParameters::NoProxy;
+ sshParams.options = QSsh::SshIgnoreDefaultProxy;
sshParams.host = m_setupPage->hostName();
sshParams.userName = m_setupPage->userName();
sshParams.port = 22;
sshParams.timeout = 10;
sshParams.authenticationType = m_setupPage->authenticationType();
- if (sshParams.authenticationType == QSsh::SshConnectionParameters::AuthenticationByPassword) {
+ if (sshParams.authenticationType == QSsh::SshConnectionParameters::AuthenticationByPassword)
sshParams.password = m_setupPage->password();
- } else {
+ else
sshParams.privateKeyFile = m_setupPage->privateKeyFilePath();
- }
QnxDeviceConfiguration::Ptr device = QnxDeviceConfiguration::create(m_setupPage->configurationName(),
Core::Id(Constants::QNX_QNX_OS_TYPE), IDevice::Hardware);
diff --git a/src/plugins/qnx/qnxplugin.cpp b/src/plugins/qnx/qnxplugin.cpp
index 40ae8ad263..06847aa59a 100644
--- a/src/plugins/qnx/qnxplugin.cpp
+++ b/src/plugins/qnx/qnxplugin.cpp
@@ -46,6 +46,12 @@
#include "qnxrunconfigurationfactory.h"
#include "qnxqtversionfactory.h"
#include "blackberrywizardextension.h"
+#include "blackberryndksettingspage.h"
+#include "bardescriptoreditorfactory.h"
+#include "bardescriptormagicmatcher.h"
+
+#include <coreplugin/icore.h>
+#include <coreplugin/mimedatabase.h>
#include <QtPlugin>
@@ -73,6 +79,7 @@ bool QNXPlugin::initialize(const QStringList &arguments, QString *errorString)
addAutoReleasedObject(new BlackBerryRunConfigurationFactory);
addAutoReleasedObject(new BlackBerryRunControlFactory);
addAutoReleasedObject(new BlackBerryWizardExtension);
+ addAutoReleasedObject(new BlackBerryNDKSettingsPage);
// Handles QNX
addAutoReleasedObject(new QnxQtVersionFactory);
@@ -82,6 +89,23 @@ bool QNXPlugin::initialize(const QStringList &arguments, QString *errorString)
addAutoReleasedObject(new QnxDeployConfigurationFactory);
addAutoReleasedObject(new QnxRunConfigurationFactory);
+ // bar-descriptor.xml editor
+ Core::MimeGlobPattern barDescriptorGlobPattern(QRegExp(QLatin1String("*.xml"), Qt::CaseInsensitive, QRegExp::Wildcard), Core::MimeGlobPattern::MinWeight + 1);
+ Core::MimeType barDescriptorMimeType;
+ barDescriptorMimeType.setType(QLatin1String(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE));
+ barDescriptorMimeType.setComment(tr("Bar descriptor file (BlackBerry)"));
+ barDescriptorMimeType.setGlobPatterns(QList<Core::MimeGlobPattern>() << barDescriptorGlobPattern);
+ barDescriptorMimeType.addMagicMatcher(QSharedPointer<Core::IMagicMatcher>(new BarDescriptorMagicMatcher));
+ barDescriptorMimeType.setSubClassesOf(QStringList() << QLatin1String("application/xml"));
+
+ Core::ICore *core = Core::ICore::instance();
+ Core::MimeDatabase *mdb = core->mimeDatabase();
+ if (!mdb->addMimeType(barDescriptorMimeType)) {
+ *errorString = tr("Could not add mime-type for bar-descriptor.xml editor");
+ return false;
+ }
+ addAutoReleasedObject(new BarDescriptorEditorFactory);
+
return true;
}
diff --git a/src/plugins/qnx/qnxqtversion.cpp b/src/plugins/qnx/qnxqtversion.cpp
index 20b725f005..e83a774bb2 100644
--- a/src/plugins/qnx/qnxqtversion.cpp
+++ b/src/plugins/qnx/qnxqtversion.cpp
@@ -33,6 +33,8 @@
#include "qnxconstants.h"
+#include <utils/hostosinfo.h>
+
using namespace Qnx;
using namespace Qnx::Internal;
@@ -44,6 +46,7 @@ QnxQtVersion::QnxQtVersion()
QnxQtVersion::QnxQtVersion(QnxArchitecture arch, const Utils::FileName &path, bool isAutoDetected, const QString &autoDetectionSource)
: QnxAbstractQtVersion(arch, path, isAutoDetected, autoDetectionSource)
{
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
}
QnxQtVersion *QnxQtVersion::clone() const
@@ -94,26 +97,26 @@ QMultiMap<QString, QString> QnxQtVersion::environment() const
QMultiMap<QString, QString> environment;
-#if defined Q_OS_WIN
- // TODO:
- //environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"));
- environment.insert(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath() + QLatin1String("/target/qnx6"));
- environment.insert(QLatin1String(Constants::QNX_HOST_KEY), sdkPath() + QLatin1String("/host/win32/x86"));
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ // TODO:
+ //environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"));
+ environment.insert(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath() + QLatin1String("/target/qnx6"));
+ environment.insert(QLatin1String(Constants::QNX_HOST_KEY), sdkPath() + QLatin1String("/host/win32/x86"));
- environment.insert(QLatin1String("PATH"), sdkPath() + QLatin1String("/host/win32/x86/usr/bin"));
+ environment.insert(QLatin1String("PATH"), sdkPath() + QLatin1String("/host/win32/x86/usr/bin"));
- // TODO:
- //environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin"));
-#elif defined Q_OS_UNIX
- environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"));
- environment.insert(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath() + QLatin1String("/target/qnx6"));
- environment.insert(QLatin1String(Constants::QNX_HOST_KEY), sdkPath() + QLatin1String("/host/linux/x86"));
+ // TODO:
+ //environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin"));
+ } else if (Utils::HostOsInfo::isAnyUnixHost()) {
+ environment.insert(QLatin1String("QNX_CONFIGURATION"), QLatin1String("/etc/qnx"));
+ environment.insert(QLatin1String(Constants::QNX_TARGET_KEY), sdkPath() + QLatin1String("/target/qnx6"));
+ environment.insert(QLatin1String(Constants::QNX_HOST_KEY), sdkPath() + QLatin1String("/host/linux/x86"));
- environment.insert(QLatin1String("PATH"), sdkPath() + QLatin1String("/host/linux/x86/usr/bin"));
- environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin"));
+ environment.insert(QLatin1String("PATH"), sdkPath() + QLatin1String("/host/linux/x86/usr/bin"));
+ environment.insert(QLatin1String("PATH"), QLatin1String("/etc/qnx/bin"));
- environment.insert(QLatin1String("LD_LIBRARY_PATH"), sdkPath() + QLatin1String("/host/linux/x86/usr/lib"));
-#endif
+ environment.insert(QLatin1String("LD_LIBRARY_PATH"), sdkPath() + QLatin1String("/host/linux/x86/usr/lib"));
+ }
environment.insert(QLatin1String("QNX_JAVAHOME"), sdkPath() + QLatin1String("/_jvm"));
environment.insert(QLatin1String("MAKEFLAGS"), QLatin1String("-I") + sdkPath() + QLatin1String("/target/qnx6/usr/include"));
diff --git a/src/plugins/qnx/qnxrunconfiguration.h b/src/plugins/qnx/qnxrunconfiguration.h
index b68c95b923..7d0f173985 100644
--- a/src/plugins/qnx/qnxrunconfiguration.h
+++ b/src/plugins/qnx/qnxrunconfiguration.h
@@ -41,7 +41,8 @@ class QnxRunConfiguration : public RemoteLinux::RemoteLinuxRunConfiguration
{
Q_OBJECT
public:
- QnxRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id, const QString &proFilePath);
+ QnxRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id,
+ const QString &projectFilePath);
QString environmentPreparationCommand() const;
diff --git a/src/plugins/qnx/qnxutils.cpp b/src/plugins/qnx/qnxutils.cpp
index 11c434623c..791a558444 100644
--- a/src/plugins/qnx/qnxutils.cpp
+++ b/src/plugins/qnx/qnxutils.cpp
@@ -30,9 +30,10 @@
****************************************************************************/
#include "qnxutils.h"
-
#include "qnxabstractqtversion.h"
+#include <utils/hostosinfo.h>
+
#include <QDir>
using namespace Qnx;
@@ -73,3 +74,142 @@ QStringList QnxUtils::searchPaths(QnxAbstractQtVersion *qtVersion)
return searchPaths;
}
+
+QMultiMap<QString, QString> QnxUtils::parseEnvironmentFile(const QString &fileName)
+{
+ QMultiMap<QString, QString> result;
+
+ QFile file(fileName);
+ if (!file.open(QIODevice::ReadOnly))
+ return result;
+
+ QTextStream str(&file);
+ QMap<QString, QString> fileContent;
+ while (!str.atEnd()) {
+ QString line = str.readLine();
+ if (!line.contains(QLatin1Char('=')))
+ continue;
+
+ int equalIndex = line.indexOf(QLatin1Char('='));
+ QString var = line.left(equalIndex);
+ //Remove set in front
+ if (var.startsWith(QLatin1String("set ")))
+ var = var.right(var.size() - 4);
+
+ QString value = line.mid(equalIndex + 1);
+
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ QRegExp systemVarRegExp(QLatin1String("IF NOT DEFINED ([\\w\\d]+)\\s+set ([\\w\\d]+)=([\\w\\d]+)"));
+ if (line.contains(systemVarRegExp)) {
+ var = systemVarRegExp.cap(2);
+ Utils::Environment sysEnv = Utils::Environment::systemEnvironment();
+ QString sysVar = systemVarRegExp.cap(1);
+ if (sysEnv.hasKey(sysVar))
+ value = sysEnv.value(sysVar);
+ else
+ value = systemVarRegExp.cap(3);
+ }
+ }
+ else if (Utils::HostOsInfo::isAnyUnixHost()) {
+ QRegExp systemVarRegExp(QLatin1String("\\$\\{([\\w\\d]+):=([\\w\\d]+)\\}")); // to match e.g. "${QNX_HOST_VERSION:=10_0_9_52}"
+ if (value.contains(systemVarRegExp)) {
+ Utils::Environment sysEnv = Utils::Environment::systemEnvironment();
+ QString sysVar = systemVarRegExp.cap(1);
+ if (sysEnv.hasKey(sysVar))
+ value = sysEnv.value(sysVar);
+ else
+ value = systemVarRegExp.cap(2);
+ }
+ }
+
+ if (value.startsWith(QLatin1Char('"')))
+ value = value.mid(1);
+ if (value.endsWith(QLatin1Char('"')))
+ value = value.left(value.size() - 1);
+
+ fileContent[var] = value;
+ }
+ file.close();
+
+ QMapIterator<QString, QString> it(fileContent);
+ while (it.hasNext()) {
+ it.next();
+ QStringList values;
+ if (Utils::HostOsInfo::isWindowsHost())
+ values = it.value().split(QLatin1Char(';'));
+ else if (Utils::HostOsInfo::isAnyUnixHost())
+ values = it.value().split(QLatin1Char(':'));
+
+ QString key = it.key();
+ foreach (const QString &value, values) {
+ const QString ownKeyAsWindowsVar = QLatin1Char('%') + key + QLatin1Char('%');
+ const QString ownKeyAsUnixVar = QLatin1Char('$') + key;
+ if (value != ownKeyAsUnixVar && value != ownKeyAsWindowsVar) { // to ignore e.g. PATH=$PATH
+ QString val = value;
+ if (val.contains(QLatin1Char('%')) || val.contains(QLatin1Char('$'))) {
+ QMapIterator<QString, QString> replaceIt(fileContent);
+ while (replaceIt.hasNext()) {
+ replaceIt.next();
+ const QString replaceKey = replaceIt.key();
+ if (replaceKey == key)
+ continue;
+
+ const QString keyAsWindowsVar = QLatin1Char('%') + replaceKey + QLatin1Char('%');
+ const QString keyAsUnixVar = QLatin1Char('$') + replaceKey;
+ if (val.contains(keyAsWindowsVar))
+ val.replace(keyAsWindowsVar, replaceIt.value());
+ if (val.contains(keyAsUnixVar))
+ val.replace(keyAsUnixVar, replaceIt.value());
+ }
+ }
+ result.insert(key, val);
+ }
+ }
+ }
+
+ if (!result.contains(QLatin1String("CPUVARDIR")))
+ result.insert(QLatin1String("CPUVARDIR"), QLatin1String("armle-v7"));
+
+ return result;
+}
+
+bool QnxUtils::isValidNdkPath(const QString &ndkPath)
+{
+ return (QFileInfo(envFilePath(ndkPath)).exists());
+}
+
+QString QnxUtils::envFilePath(const QString &ndkPath)
+{
+ QString envFile;
+ if (Utils::HostOsInfo::isWindowsHost())
+ envFile = ndkPath + QLatin1String("/bbndk-env.bat");
+ else if (Utils::HostOsInfo::isAnyUnixHost())
+ envFile = ndkPath + QLatin1String("/bbndk-env.sh");
+
+ return envFile;
+}
+
+void QnxUtils::prependQnxMapToEnvironment(const QMultiMap<QString, QString> &qnxMap, Utils::Environment &env)
+{
+ QMultiMap<QString, QString>::const_iterator it;
+ QMultiMap<QString, QString>::const_iterator end(qnxMap.constEnd());
+ for (it = qnxMap.constBegin(); it != end; ++it) {
+ const QString key = it.key();
+ const QString value = it.value();
+
+ if (key == QLatin1String("PATH"))
+ env.prependOrSetPath(value);
+ else if (key == QLatin1String("LD_LIBRARY_PATH"))
+ env.prependOrSetLibrarySearchPath(value);
+ else
+ env.set(key, value);
+ }
+}
+
+Utils::FileName QnxUtils::executableWithExtension(const Utils::FileName &fileName)
+{
+ Utils::FileName result = fileName;
+ if (Utils::HostOsInfo::isWindowsHost())
+ result.append(QLatin1String(".exe"));
+ return result;
+}
diff --git a/src/plugins/qnx/qnxutils.h b/src/plugins/qnx/qnxutils.h
index 6eb09a813b..5b8b179b6a 100644
--- a/src/plugins/qnx/qnxutils.h
+++ b/src/plugins/qnx/qnxutils.h
@@ -34,6 +34,11 @@
#include "qnxconstants.h"
+#include <utils/environment.h>
+#include <utils/qtcassert.h>
+#include <utils/fileutils.h>
+
+#include <QTextStream>
#include <QString>
namespace Qnx {
@@ -47,6 +52,11 @@ public:
static QString addQuotes(const QString &string);
static Qnx::QnxArchitecture cpudirToArch(const QString &cpuDir);
static QStringList searchPaths(QnxAbstractQtVersion *qtVersion);
+ static QMultiMap<QString, QString> parseEnvironmentFile(const QString &fileName);
+ static bool isValidNdkPath(const QString & ndkPath);
+ static QString envFilePath(const QString & ndkPath);
+ static void prependQnxMapToEnvironment(const QMultiMap<QString, QString> &qnxMap, Utils::Environment &env);
+ static Utils::FileName executableWithExtension(const Utils::FileName &fileName);
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/addlibrarywizard.cpp b/src/plugins/qt4projectmanager/addlibrarywizard.cpp
index b6c011549f..6e2c9c240f 100644
--- a/src/plugins/qt4projectmanager/addlibrarywizard.cpp
+++ b/src/plugins/qt4projectmanager/addlibrarywizard.cpp
@@ -31,6 +31,8 @@
#include "ui_librarydetailswidget.h"
#include "librarydetailscontroller.h"
+#include <utils/hostosinfo.h>
+
#include <QVBoxLayout>
#include <QRadioButton>
#include <QLabel>
@@ -175,10 +177,10 @@ LibraryTypePage::LibraryTypePage(AddLibraryWizard *parent)
packageLabel->setAttribute(Qt::WA_MacSmallSize, true);
layout->addWidget(packageLabel);
-#ifdef Q_OS_WIN
- m_packageRadio->setVisible(false);
- packageLabel->setVisible(false);
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ m_packageRadio->setVisible(false);
+ packageLabel->setVisible(false);
+ }
// select the default
m_internalRadio->setChecked(true);
diff --git a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetpluginwizardpage.cpp b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetpluginwizardpage.cpp
index 65eb14e849..140db480f4 100644
--- a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetpluginwizardpage.cpp
+++ b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetpluginwizardpage.cpp
@@ -123,11 +123,10 @@ void CustomWidgetPluginWizardPage::slotCheckCompleteness()
// A collection is complete only with class name
bool completeNow = false;
if (!pluginName().isEmpty()) {
- if (m_classCount > 1) {
+ if (m_classCount > 1)
completeNow = !collectionClassName().isEmpty();
- } else {
+ else
completeNow = true;
- }
}
if (completeNow != m_complete) {
m_complete = completeNow;
diff --git a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizarddialog.cpp b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizarddialog.cpp
index 39e0e51493..a7809f7bc3 100644
--- a/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/customwidgetwizard/customwidgetwizarddialog.cpp
@@ -53,7 +53,7 @@ public:
if (dev.isNull() || dev->id() != ProjectExplorer::Constants::DESKTOP_DEVICE_ID)
return false;
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
- return version && version->type() == QtSupport::Constants::DESKTOPQT;
+ return version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT);
}
};
@@ -79,7 +79,7 @@ CustomWidgetWizardDialog::CustomWidgetWizardDialog(const QString &templateName,
setIntroDescription(tr("This wizard generates a Qt Designer Custom Widget "
"or a Qt Designer Custom Widget Collection project."));
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
m_widgetPageId = addPage(m_widgetsPage);
m_pluginPageId = addPage(m_pluginPage);
diff --git a/src/plugins/qt4projectmanager/images/qml.ico b/src/plugins/qt4projectmanager/images/qml.ico
deleted file mode 100644
index 9b940c49d8..0000000000
--- a/src/plugins/qt4projectmanager/images/qml.ico
+++ /dev/null
Binary files differ
diff --git a/src/plugins/qt4projectmanager/images/qml.png b/src/plugins/qt4projectmanager/images/qml.png
new file mode 100644
index 0000000000..30cf0e7828
--- /dev/null
+++ b/src/plugins/qt4projectmanager/images/qml.png
Binary files differ
diff --git a/src/plugins/qt4projectmanager/librarydetailscontroller.cpp b/src/plugins/qt4projectmanager/librarydetailscontroller.cpp
index 287a47ebdd..ca6dfb5535 100644
--- a/src/plugins/qt4projectmanager/librarydetailscontroller.cpp
+++ b/src/plugins/qt4projectmanager/librarydetailscontroller.cpp
@@ -40,6 +40,7 @@
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/buildconfiguration.h>
+#include <utils/hostosinfo.h>
#include <QFileInfo>
#include <QDir>
@@ -66,27 +67,31 @@ LibraryDetailsController::LibraryDetailsController(
m_windowsGroupVisible(true),
m_libraryDetailsWidget(libraryDetails)
{
-#ifdef Q_OS_MAC
- m_creatorPlatform = CreatorMac;
-#endif
-#ifdef Q_OS_LINUX
- m_creatorPlatform = CreatorLinux;
-#endif
-#ifdef Q_OS_WIN
- m_creatorPlatform = CreatorWindows;
-#endif
-
-#ifndef Q_OS_LINUX
- // project for which we are going to insert the snippet
- const ProjectExplorer::Project *project =
- ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(proFile);
- // if its tool chain is maemo behave the same as we would be on linux
- ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(project->activeTarget()->kit());
- if (tc
- && (tc->targetAbi().osFlavor() == ProjectExplorer::Abi::HarmattanLinuxFlavor
- || tc->targetAbi().osFlavor() == ProjectExplorer::Abi::MaemoLinuxFlavor))
+ switch (Utils::HostOsInfo::hostOs()) {
+ case Utils::HostOsInfo::HostOsMac:
+ m_creatorPlatform = CreatorMac;
+ break;
+ case Utils::HostOsInfo::HostOsLinux:
m_creatorPlatform = CreatorLinux;
-#endif
+ break;
+ case Utils::HostOsInfo::HostOsWindows:
+ m_creatorPlatform = CreatorWindows;
+ break;
+ default:
+ break;
+ }
+
+ if (!Utils::HostOsInfo::isLinuxHost()) {
+ // project for which we are going to insert the snippet
+ const ProjectExplorer::Project *project =
+ ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projectForFile(proFile);
+ // if its tool chain is maemo behave the same as we would be on linux
+ ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(project->activeTarget()->kit());
+ if (tc
+ && (tc->targetAbi().osFlavor() == ProjectExplorer::Abi::HarmattanLinuxFlavor
+ || tc->targetAbi().osFlavor() == ProjectExplorer::Abi::MaemoLinuxFlavor))
+ m_creatorPlatform = CreatorLinux;
+ }
setPlatformsVisible(true);
setLinkageGroupVisible(true);
diff --git a/src/plugins/qt4projectmanager/makestep.cpp b/src/plugins/qt4projectmanager/makestep.cpp
index d76aaf990f..2c3ef4247d 100644
--- a/src/plugins/qt4projectmanager/makestep.cpp
+++ b/src/plugins/qt4projectmanager/makestep.cpp
@@ -38,6 +38,7 @@
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/buildsteplist.h>
+#include <projectexplorer/gnumakeparser.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/kitinformation.h>
@@ -200,12 +201,6 @@ bool MakeStep::init()
}
Utils::QtcProcess::addArgs(&args, m_userArgs);
-
- if (!isClean()) {
- if (!bc->defaultMakeTarget().isEmpty())
- Utils::QtcProcess::addArg(&args, bc->defaultMakeTarget());
- }
-
if (bc->fileNodeBuild() && subNode) {
QString objectsDir = subNode->objectsDirectory();
if (objectsDir.isEmpty()) {
@@ -247,21 +242,13 @@ bool MakeStep::init()
pp->setEnvironment(env);
pp->setArguments(args);
+ pp->resolveAll();
- IOutputParser *parser = 0;
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- if (version)
- parser = version->createOutputParser();
+ setOutputParser(new ProjectExplorer::GnuMakeParser());
+ IOutputParser *parser = target()->kit()->createOutputParser();
if (parser)
- parser->appendOutputParser(new QtSupport::QtParser);
- else
- parser = new QtSupport::QtParser;
- if (tc)
- parser->appendOutputParser(tc->outputParser());
-
- parser->setWorkingDirectory(workingDirectory);
-
- setOutputParser(parser);
+ appendOutputParser(parser);
+ outputParser()->setWorkingDirectory(pp->effectiveWorkingDirectory());
m_scriptTarget = (static_cast<Qt4Project *>(bc->target()->project())->rootQt4ProjectNode()->projectType() == ScriptTemplate);
@@ -429,10 +416,6 @@ void MakeStepConfigWidget::updateDetails()
param.setCommand(makeCmd);
QString args = m_makeStep->userArguments();
- if (!m_makeStep->isClean()) {
- if (!bc->defaultMakeTarget().isEmpty())
- Utils::QtcProcess::addArg(&args, bc->defaultMakeTarget());
- }
Utils::Environment env = bc->environment();
// Force output to english for the parsers. Do this here and not in the toolchain's
diff --git a/src/plugins/qt4projectmanager/profilecompletionassist.cpp b/src/plugins/qt4projectmanager/profilecompletionassist.cpp
index 5ce83077a5..84ea394bce 100644
--- a/src/plugins/qt4projectmanager/profilecompletionassist.cpp
+++ b/src/plugins/qt4projectmanager/profilecompletionassist.cpp
@@ -29,73 +29,236 @@
#include "profilecompletionassist.h"
#include "qt4projectmanagerconstants.h"
-#include "profilekeywords.h"
-#include <texteditor/codeassist/iassistinterface.h>
-#include <texteditor/codeassist/genericproposal.h>
-#include <texteditor/completionsettings.h>
-#include <texteditor/texteditorsettings.h>
-#include <texteditor/basetexteditor.h>
-
-#include <cplusplus/Icons.h>
-
-#include <QTextCursor>
+#include <texteditor/codeassist/keywordscompletionassist.h>
using namespace Qt4ProjectManager::Internal;
using namespace TextEditor;
-// -------------------------
-// ProFileAssistProposalItem
-// -------------------------
-ProFileAssistProposalItem::ProFileAssistProposalItem()
-{}
-ProFileAssistProposalItem::~ProFileAssistProposalItem()
-{}
-
-bool ProFileAssistProposalItem::prematurelyApplies(const QChar &c) const
-{
- // only '(' in case of a function
- if (c == QLatin1Char('(') && ProFileKeywords::isFunction(text()))
- return true;
- return false;
-}
-
-void ProFileAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *editor,
- int basePosition) const
-{
- const CompletionSettings &settings = TextEditorSettings::instance()->completionSettings();
-
- int replaceLength = editor->position() - basePosition;
- QString toInsert = text();
- int cursorOffset = 0;
- if (ProFileKeywords::isFunction(toInsert) && settings.m_autoInsertBrackets) {
- if (settings.m_spaceAfterFunctionName) {
- if (editor->textAt(editor->position(), 2) == QLatin1String(" (")) {
- cursorOffset = 2;
- } else if (editor->characterAt(editor->position()) == QLatin1Char('(')
- || editor->characterAt(editor->position()) == QLatin1Char(' ')) {
- replaceLength += 1;
- toInsert += QLatin1String(" (");
- } else {
- toInsert += QLatin1String(" ()");
- cursorOffset = -1;
- }
- } else {
- if (editor->characterAt(editor->position()) == QLatin1Char('(')) {
- cursorOffset = 1;
- } else {
- toInsert += QLatin1String("()");
- cursorOffset = -1;
- }
- }
- }
-
- editor->setCursorPosition(basePosition);
- editor->replace(replaceLength, toInsert);
- if (cursorOffset)
- editor->setCursorPosition(editor->position() + cursorOffset);
-}
+static const char *const variableKeywords[] = {
+ "BACKUP_REGISTRATION_FILE_MAEMO",
+ "CCFLAG",
+ "CONFIG",
+ "DEFINES",
+ "DEF_FILE",
+ "DEPENDPATH",
+ "DEPLOYMENT",
+ "DEPLOYMENT_PLUGIN",
+ "DESTDIR",
+ "DESTDIR_TARGET",
+ "DISTFILES",
+ "DLLDESTDIR",
+ "DISTFILES",
+ "DSP_TEMPLATE",
+ "FORMS",
+ "FORMS3",
+ "GUID",
+ "HEADERS",
+ "ICON",
+ "INCLUDEPATH",
+ "INSTALLS",
+ "LEXIMPLS",
+ "LEXOBJECTS",
+ "LEXSOURCES",
+ "LIBS",
+ "LITERAL_HASH",
+ "MAKEFILE",
+ "MAKEFILE_GENERATOR",
+ "MOBILITY",
+ "MOC_DIR",
+ "OBJECTIVE_HEADERS",
+ "OBJECTIVE_SOURCES",
+ "OBJECTS",
+ "OBJECTS_DIR",
+ "OBJMOC",
+ "OTHER_FILES",
+ "PKGCONFIG",
+ "POST_TARGETDEPS",
+ "PRE_TARGETDEPS",
+ "PRECOMPILED_HEADER",
+ "PWD",
+ "OUT_PWD",
+ "QMAKE",
+ "QMAKESPEC",
+ "QMAKE_APP_FLAG",
+ "QMAKE_APP_OR_DLL",
+ "QMAKE_AR_CMD",
+ "QMAKE_BUNDLE_DATA",
+ "QMAKE_BUNDLE_EXTENSION",
+ "QMAKE_CC",
+ "QMAKE_CFLAGS_DEBUG",
+ "QMAKE_CFLAGS_MT",
+ "QMAKE_CFLAGS_MT_DBG",
+ "QMAKE_CFLAGS_MT_DLL",
+ "QMAKE_CFLAGS_MT_DLLDBG",
+ "QMAKE_CFLAGS_RELEASE",
+ "QMAKE_CFLAGS_SHLIB",
+ "QMAKE_CFLAGS_THREAD",
+ "QMAKE_CFLAGS_WARN_OFF",
+ "QMAKE_CFLAGS_WARN_ON",
+ "QMAKE_CLEAN",
+ "QMAKE_CXX",
+ "QMAKE_CXXFLAGS",
+ "QMAKE_CXXFLAGS_DEBUG",
+ "QMAKE_CXXFLAGS_MT",
+ "QMAKE_CXXFLAGS_MT_DBG",
+ "QMAKE_CXXFLAGS_MT_DLL",
+ "QMAKE_CXXFLAGS_MT_DLLDBG",
+ "QMAKE_CXXFLAGS_RELEASE",
+ "QMAKE_CXXFLAGS_SHLIB",
+ "QMAKE_CXXFLAGS_THREAD",
+ "QMAKE_CXXFLAGS_WARN_OFF",
+ "QMAKE_CXXFLAGS_WARN_ON",
+ "QMAKE_DISTCLEAN",
+ "QMAKE_EXTENSION_SHLIB",
+ "QMAKE_EXT_MOC",
+ "QMAKE_EXT_UI",
+ "QMAKE_EXT_PRL",
+ "QMAKE_EXT_LEX",
+ "QMAKE_EXT_YACC",
+ "QMAKE_EXT_OBJ",
+ "QMAKE_EXT_CPP",
+ "QMAKE_EXT_H",
+ "QMAKE_EXTRA_COMPILERS",
+ "QMAKE_EXTRA_TARGETS",
+ "QMAKE_FAILED_REQUIREMENTS",
+ "QMAKE_FRAMEWORK_BUNDLE_NAME",
+ "QMAKE_FRAMEWORK_VERSION",
+ "QMAKE_INCDIR",
+ "QMAKE_INCDIR_EGL",
+ "QMAKE_INCDIR_OPENGL",
+ "QMAKE_INCDIR_OPENGL_ES1",
+ "QMAKE_INCDIR_OPENGL_ES2",
+ "QMAKE_INCDIR_OPENVG",
+ "QMAKE_INCDIR_QT",
+ "QMAKE_INCDIR_THREAD",
+ "QMAKE_INCDIR_X11",
+ "QMAKE_INFO_PLIST",
+ "QMAKE_LFLAGS",
+ "QMAKE_LFLAGS_CONSOLE",
+ "QMAKE_LFLAGS_CONSOLE_DLL",
+ "QMAKE_LFLAGS_DEBUG",
+ "QMAKE_LFLAGS_PLUGIN",
+ "QMAKE_LFLAGS_RPATH",
+ "QMAKE_LFLAGS_QT_DLL",
+ "QMAKE_LFLAGS_RELEASE",
+ "QMAKE_LFLAGS_SHAPP",
+ "QMAKE_LFLAGS_SHLIB",
+ "QMAKE_LFLAGS_SONAME",
+ "QMAKE_LFLAGS_THREAD",
+ "QMAKE_LFLAGS_WINDOWS",
+ "QMAKE_LFLAGS_WINDOWS_DLL",
+ "QMAKE_LIBDIR",
+ "QMAKE_LIBDIR_FLAGS",
+ "QMAKE_LIBDIR_EGL",
+ "QMAKE_LIBDIR_OPENGL",
+ "QMAKE_LIBDIR_OPENVG",
+ "QMAKE_LIBDIR_QT",
+ "QMAKE_LIBDIR_X11",
+ "QMAKE_LIBS",
+ "QMAKE_LIBS_CONSOLE",
+ "QMAKE_LIBS_EGL",
+ "QMAKE_LIBS_OPENGL",
+ "QMAKE_LIBS_OPENGL_QT",
+ "QMAKE_LIBS_OPENGL_ES1",
+ "QMAKE_LIBS_OPENGL_ES2",
+ "QMAKE_LIBS_OPENVG",
+ "QMAKE_LIBS_QT",
+ "QMAKE_LIBS_QT_DLL",
+ "QMAKE_LIBS_QT_OPENGL",
+ "QMAKE_LIBS_QT_THREAD",
+ "QMAKE_LIBS_RT",
+ "QMAKE_LIBS_RTMT",
+ "QMAKE_LIBS_THREAD",
+ "QMAKE_LIBS_WINDOWS",
+ "QMAKE_LIBS_X11",
+ "QMAKE_LIBS_X11SM",
+ "QMAKE_LIB_FLAG",
+ "QMAKE_LINK_SHLIB_CMD",
+ "QMAKE_LN_SHLIB",
+ "QMAKE_POST_LINK",
+ "QMAKE_PRE_LINK",
+ "QMAKE_PROJECT_NAME",
+ "QMAKE_MAC_SDK",
+ "QMAKE_MACOSX_DEPLOYMENT_TARGET",
+ "QMAKE_MAKEFILE",
+ "QMAKE_MOC_SRC",
+ "QMAKE_QMAKE",
+ "QMAKE_QT_DLL",
+ "QMAKE_RESOURCE_FLAGS",
+ "QMAKE_RPATH",
+ "QMAKE_RPATHDIR",
+ "QMAKE_RUN_CC",
+ "QMAKE_RUN_CC_IMP",
+ "QMAKE_RUN_CXX",
+ "QMAKE_RUN_CXX_IMP",
+ "QMAKE_TARGET",
+ "QMAKE_UIC",
+ "QT",
+ "QTPLUGIN",
+ "QT_VERSION",
+ "QT_MAJOR_VERSION",
+ "QT_MINOR_VERSION",
+ "QT_PATCH_VERSION",
+ "RCC_DIR",
+ "RC_FILE",
+ "REQUIRES",
+ "RESOURCES",
+ "RES_FILE",
+ "RSS_RULES",
+ "SIGNATURE_FILE",
+ "SOURCES",
+ "SRCMOC",
+ "STATECHARTS",
+ "SUBDIRS",
+ "TARGET",
+ "TEMPLATE",
+ "TRANSLATIONS",
+ "UICIMPLS",
+ "UICOBJECTS",
+ "UI_DIR",
+ "UI_HEADERS_DIR",
+ "UI_SOURCES_DIR",
+ "VER_MAJ",
+ "VER_MIN",
+ "VER_PAT",
+ "VERSION",
+ "VPATH",
+ "YACCIMPLS",
+ "YACCOBJECTS",
+ "YACCSOURCES",
+ "_PRO_FILE_",
+ "_PRO_FILE_PWD_",
+ 0
+};
+
+static const char *const functionKeywords[] = {
+ "basename",
+ "contains",
+ "count",
+ "dirname",
+ "error",
+ "eval",
+ "exists",
+ "find",
+ "for",
+ "include",
+ "infile",
+ "isEmpty",
+ "join",
+ "member",
+ "message",
+ "packagesExist",
+ "prompt",
+ "quote",
+ "replace",
+ "sprintf",
+ "system",
+ "unique",
+ "warning",
+ 0
+};
// -------------------------------
// ProFileCompletionAssistProvider
@@ -103,127 +266,41 @@ void ProFileAssistProposalItem::applyContextualContent(TextEditor::BaseTextEdito
ProFileCompletionAssistProvider::ProFileCompletionAssistProvider()
{}
-ProFileCompletionAssistProvider::~ProFileCompletionAssistProvider()
-{}
-
-bool ProFileCompletionAssistProvider::supportsEditor(const Core::Id &editorId) const
-{
- return editorId == Qt4ProjectManager::Constants::PROFILE_EDITOR_ID;
-}
-
-bool ProFileCompletionAssistProvider::isAsynchronous() const
-{
- return false;
-}
-
-int ProFileCompletionAssistProvider::activationCharSequenceLength() const
+void ProFileCompletionAssistProvider::init()
{
- return 0;
+ for (uint i = 0; i < sizeof variableKeywords / sizeof variableKeywords[0] - 1; i++)
+ m_variables.append(QLatin1String(variableKeywords[i]));
+ for (uint i = 0; i < sizeof functionKeywords / sizeof functionKeywords[0] - 1; i++)
+ m_functions.append(QLatin1String(functionKeywords[i]));
}
-bool ProFileCompletionAssistProvider::isActivationCharSequence(const QString &sequence) const
+ProFileCompletionAssistProvider::~ProFileCompletionAssistProvider()
{
- Q_UNUSED(sequence);
- return false;
}
-bool ProFileCompletionAssistProvider::isContinuationChar(const QChar &c) const
+bool ProFileCompletionAssistProvider::supportsEditor(const Core::Id &editorId) const
{
- return c.isLetterOrNumber() || c == QLatin1Char('_');
+ return editorId == Qt4ProjectManager::Constants::PROFILE_EDITOR_ID;
}
IAssistProcessor *ProFileCompletionAssistProvider::createProcessor() const
{
- return new ProFileCompletionAssistProcessor;
-}
-
-// --------------------------------
-// ProFileCompletionAssistProcessor
-// --------------------------------
-ProFileCompletionAssistProcessor::ProFileCompletionAssistProcessor()
- : m_startPosition(-1)
- , m_variableIcon(CPlusPlus::Icons().iconForType(CPlusPlus::Icons::VarPublicIconType))
- , m_functionIcon(CPlusPlus::Icons().iconForType(CPlusPlus::Icons::FuncPublicIconType))
-{}
-
-ProFileCompletionAssistProcessor::~ProFileCompletionAssistProcessor()
-{}
-
-IAssistProposal *ProFileCompletionAssistProcessor::perform(const IAssistInterface *interface)
-{
- m_interface.reset(interface);
-
- if (isInComment())
- return 0;
-
- if (interface->reason() == IdleEditor && !acceptsIdleEditor())
- return 0;
-
- if (m_startPosition == -1)
- m_startPosition = findStartOfName();
-
- QList<TextEditor::BasicProposalItem *> items;
- QStringList keywords = ProFileKeywords::variables() + ProFileKeywords::functions();
- for (int i = 0; i < keywords.count(); i++) {
- BasicProposalItem *item = new ProFileAssistProposalItem;
- item->setText(keywords[i]);
- item->setIcon(ProFileKeywords::isFunction(item->text()) ? m_functionIcon : m_variableIcon);
- items.append(item);
- }
-
- return new GenericProposal(m_startPosition, new ProFileAssistProposalModel(items));
+ if (m_variables.isEmpty())
+ const_cast<ProFileCompletionAssistProvider *>(this)->init();
+ TextEditor::Keywords keywords = TextEditor::Keywords(m_variables, m_functions, QMap<QString, QStringList>());
+ return new KeywordsCompletionAssistProcessor(keywords);
}
-bool ProFileCompletionAssistProcessor::acceptsIdleEditor()
+QStringList ProFileCompletionAssistProvider::variables() const
{
- const int pos = m_interface->position();
- QChar characterUnderCursor = m_interface->characterAt(pos);
- if (!characterUnderCursor.isLetterOrNumber()) {
- m_startPosition = findStartOfName();
- if (pos - m_startPosition >= 3 && !isInComment())
- return true;
- }
- return false;
+ if (m_variables.isEmpty())
+ const_cast<ProFileCompletionAssistProvider *>(this)->init();
+ return m_variables;
}
-int ProFileCompletionAssistProcessor::findStartOfName(int pos) const
-{
- if (pos == -1)
- pos = m_interface->position();
- QChar chr;
-
- // Skip to the start of a name
- do {
- chr = m_interface->characterAt(--pos);
- } while (chr.isLetterOrNumber() || chr == QLatin1Char('_'));
-
- return pos + 1;
-}
-
-bool ProFileCompletionAssistProcessor::isInComment() const
-{
- QTextCursor tc(m_interface->textDocument());
- tc.setPosition(m_interface->position());
- tc.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
- const QString &lineBeginning = tc.selectedText();
- if (lineBeginning.contains(QLatin1Char('#')))
- return true;
- return false;
-}
-
-// --------------------------
-// ProFileAssistProposalModel
-// --------------------------
-ProFileAssistProposalModel::ProFileAssistProposalModel(
- const QList<BasicProposalItem *> &items)
- : BasicProposalItemListModel(items)
-{}
-
-ProFileAssistProposalModel::~ProFileAssistProposalModel()
-{}
-
-bool ProFileAssistProposalModel::isSortable(const QString &prefix) const
+QStringList ProFileCompletionAssistProvider::functions() const
{
- Q_UNUSED(prefix)
- return false;
+ if (m_functions.isEmpty())
+ const_cast<ProFileCompletionAssistProvider *>(this)->init();
+ return m_functions;
}
diff --git a/src/plugins/qt4projectmanager/profilecompletionassist.h b/src/plugins/qt4projectmanager/profilecompletionassist.h
index cac1a6b74b..4c25f9c51f 100644
--- a/src/plugins/qt4projectmanager/profilecompletionassist.h
+++ b/src/plugins/qt4projectmanager/profilecompletionassist.h
@@ -30,71 +30,28 @@
#ifndef PROFILECOMPLETIONASSIST_H
#define PROFILECOMPLETIONASSIST_H
-#include <texteditor/codeassist/basicproposalitem.h>
-#include <texteditor/codeassist/basicproposalitemlistmodel.h>
#include <texteditor/codeassist/completionassistprovider.h>
-#include <texteditor/codeassist/iassistprocessor.h>
-#include <QIcon>
+#include <QStringList>
namespace Qt4ProjectManager {
namespace Internal {
-class ProFileAssistProposalItem : public TextEditor::BasicProposalItem
-{
-public:
- ProFileAssistProposalItem();
- virtual ~ProFileAssistProposalItem();
-
- virtual bool prematurelyApplies(const QChar &c) const;
- virtual void applyContextualContent(TextEditor::BaseTextEditor *editor,
- int basePosition) const;
-};
-
-
class ProFileCompletionAssistProvider : public TextEditor::CompletionAssistProvider
{
+ Q_OBJECT
public:
ProFileCompletionAssistProvider();
+ void init();
virtual ~ProFileCompletionAssistProvider();
virtual bool supportsEditor(const Core::Id &editorId) const;
virtual TextEditor::IAssistProcessor *createProcessor() const;
-
- virtual bool isAsynchronous() const;
- virtual int activationCharSequenceLength() const;
- virtual bool isActivationCharSequence(const QString &sequence) const;
- virtual bool isContinuationChar(const QChar &c) const;
-};
-
-
-class ProFileCompletionAssistProcessor : public TextEditor::IAssistProcessor
-{
-public:
- ProFileCompletionAssistProcessor();
- virtual ~ProFileCompletionAssistProcessor();
-
- virtual TextEditor::IAssistProposal *perform(const TextEditor::IAssistInterface *interface);
-
+ QStringList variables() const;
+ QStringList functions() const;
private:
- bool acceptsIdleEditor();
- int findStartOfName(int pos = -1) const;
- bool isInComment() const;
-
- int m_startPosition;
- QScopedPointer<const TextEditor::IAssistInterface> m_interface;
- const QIcon m_variableIcon;
- const QIcon m_functionIcon;
-};
-
-
-class ProFileAssistProposalModel : public TextEditor::BasicProposalItemListModel
-{
-public:
- ProFileAssistProposalModel(const QList<TextEditor::BasicProposalItem *> &items);
- virtual ~ProFileAssistProposalModel();
-
- virtual bool isSortable(const QString &prefix) const;
+ QStringList m_variables;
+ QStringList m_functions;
};
} // Internal
diff --git a/src/plugins/qt4projectmanager/profileeditor.cpp b/src/plugins/qt4projectmanager/profileeditor.cpp
index f19eaa21d3..8916e39e4d 100644
--- a/src/plugins/qt4projectmanager/profileeditor.cpp
+++ b/src/plugins/qt4projectmanager/profileeditor.cpp
@@ -34,10 +34,10 @@
#include "qt4projectmanagerconstants.h"
#include "profileeditorfactory.h"
-#include <coreplugin/icore.h>
+#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/icore.h>
#include <coreplugin/id.h>
-#include <coreplugin/actionmanager/actioncontainer.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditoractionhandler.h>
#include <texteditor/texteditorconstants.h>
@@ -45,21 +45,20 @@
#include <QFileInfo>
#include <QDir>
-#include <QMenu>
+#include <QSharedPointer>
-using namespace Qt4ProjectManager;
-using namespace Qt4ProjectManager::Internal;
+namespace Qt4ProjectManager {
+namespace Internal {
//
-// ProFileEditorEditable
+// ProFileEditor
//
ProFileEditor::ProFileEditor(ProFileEditorWidget *editor)
: BaseTextEditor(editor)
{
- setContext(Core::Context(Qt4ProjectManager::Constants::C_PROFILEEDITOR,
+ setContext(Core::Context(Constants::C_PROFILEEDITOR,
TextEditor::Constants::C_TEXTEDITOR));
-// m_contexts << uidm->uniqueIdentifier(Qt4ProjectManager::Constants::PROJECT_KIND);
}
Core::IEditor *ProFileEditor::duplicate(QWidget *parent)
@@ -73,18 +72,18 @@ Core::IEditor *ProFileEditor::duplicate(QWidget *parent)
Core::Id ProFileEditor::id() const
{
- return Qt4ProjectManager::Constants::PROFILE_EDITOR_ID;
+ return Core::Id(Constants::PROFILE_EDITOR_ID);
}
//
-// ProFileEditorEditor
+// ProFileEditorWidget
//
ProFileEditorWidget::ProFileEditorWidget(QWidget *parent, ProFileEditorFactory *factory, TextEditor::TextEditorActionHandler *ah)
: BaseTextEditorWidget(parent), m_factory(factory), m_ah(ah)
{
- ProFileDocument *doc = new ProFileDocument();
- doc->setMimeType(QLatin1String(Qt4ProjectManager::Constants::PROFILE_MIMETYPE));
+ QSharedPointer<ProFileDocument> doc(new ProFileDocument());
+ doc->setMimeType(QLatin1String(Constants::PROFILE_MIMETYPE));
setBaseTextDocument(doc);
ah->setupActions(this);
@@ -101,14 +100,12 @@ void ProFileEditorWidget::unCommentSelection()
static bool isValidFileNameChar(const QChar &c)
{
- if (c.isLetterOrNumber()
+ return c.isLetterOrNumber()
|| c == QLatin1Char('.')
|| c == QLatin1Char('_')
|| c == QLatin1Char('-')
|| c == QLatin1Char('/')
- || c == QLatin1Char('\\'))
- return true;
- return false;
+ || c == QLatin1Char('\\');
}
ProFileEditorWidget::Link ProFileEditorWidget::findLinkAt(const QTextCursor &cursor,
@@ -213,8 +210,7 @@ void ProFileEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
<< TextEditor::C_VISUAL_WHITESPACE;
}
- const QVector<QTextCharFormat> formats = fs.toTextCharFormats(categories);
- highlighter->setFormats(formats.constBegin(), formats.constEnd());
+ highlighter->setFormats(fs.toTextCharFormats(categories));
highlighter->rehighlight();
}
@@ -238,3 +234,6 @@ QString ProFileDocument::suggestedFileName() const
QFileInfo fi(fileName());
return fi.fileName();
}
+
+} // namespace Internal
+} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/profileeditor.h b/src/plugins/qt4projectmanager/profileeditor.h
index 8fd92fcdb8..b64a1cbd8e 100644
--- a/src/plugins/qt4projectmanager/profileeditor.h
+++ b/src/plugins/qt4projectmanager/profileeditor.h
@@ -40,15 +40,9 @@ class TextEditorActionHandler;
}
namespace Qt4ProjectManager {
-
-class Qt4Manager;
-class Qt4Project;
-
namespace Internal {
class ProFileEditorFactory;
-class ProFileHighlighter;
-
class ProFileEditorWidget;
class ProFileEditor : public TextEditor::BaseTextEditor
@@ -78,6 +72,7 @@ public:
TextEditor::TextEditorActionHandler *actionHandler() const { return m_ah; }
void unCommentSelection();
+
protected:
virtual Link findLinkAt(const QTextCursor &, bool resolveTarget = true);
TextEditor::BaseTextEditor *createEditor();
@@ -100,6 +95,10 @@ public:
ProFileDocument();
QString defaultPath() const;
QString suggestedFileName() const;
+
+ // qmake project files doesn't support UTF8-BOM
+ // If the BOM would be added qmake would fail and QtCreator couldn't parse the project file
+ bool supportsUtf8Bom() { return false; }
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/profileeditorfactory.cpp b/src/plugins/qt4projectmanager/profileeditorfactory.cpp
index ffa7b96bab..dbe3de98e9 100644
--- a/src/plugins/qt4projectmanager/profileeditorfactory.cpp
+++ b/src/plugins/qt4projectmanager/profileeditorfactory.cpp
@@ -68,7 +68,7 @@ ProFileEditorFactory::~ProFileEditorFactory()
Core::Id ProFileEditorFactory::id() const
{
- return Qt4ProjectManager::Constants::PROFILE_EDITOR_ID;
+ return Core::Id(Qt4ProjectManager::Constants::PROFILE_EDITOR_ID);
}
QString ProFileEditorFactory::displayName() const
diff --git a/src/plugins/qt4projectmanager/profilehighlighter.cpp b/src/plugins/qt4projectmanager/profilehighlighter.cpp
index 26fb152727..0a0ccc4938 100644
--- a/src/plugins/qt4projectmanager/profilehighlighter.cpp
+++ b/src/plugins/qt4projectmanager/profilehighlighter.cpp
@@ -28,7 +28,9 @@
****************************************************************************/
#include "profilehighlighter.h"
-#include "profilekeywords.h"
+#include "profilecompletionassist.h"
+
+#include <extensionsystem/pluginmanager.h>
#include <QRegExp>
#include <QColor>
@@ -41,6 +43,9 @@ using namespace Qt4ProjectManager::Internal;
ProFileHighlighter::ProFileHighlighter(QTextDocument *document) :
TextEditor::SyntaxHighlighter(document)
{
+ ProFileCompletionAssistProvider *pcap
+ = ExtensionSystem::PluginManager::instance()->getObject<ProFileCompletionAssistProvider>();
+ m_keywords = TextEditor::Keywords(pcap->variables(), pcap->functions(), QMap<QString, QStringList>());
}
void ProFileHighlighter::highlightBlock(const QString &text)
@@ -61,12 +66,12 @@ void ProFileHighlighter::highlightBlock(const QString &text)
if (c.isLetter() || c == QLatin1Char('_') || c == QLatin1Char('.') || c.isDigit()) {
buf += c;
setFormat(i - buf.length()+1, buf.length(), emptyFormat);
- if (!buf.isEmpty() && ProFileKeywords::isFunction(buf))
+ if (!buf.isEmpty() && m_keywords.isFunction(buf))
setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileFunctionFormat]);
- else if (!buf.isEmpty() && ProFileKeywords::isVariable(buf))
+ else if (!buf.isEmpty() && m_keywords.isVariable(buf))
setFormat(i - buf.length()+1, buf.length(), m_formats[ProfileVariableFormat]);
} else if (c == QLatin1Char('(')) {
- if (!buf.isEmpty() && ProFileKeywords::isFunction(buf))
+ if (!buf.isEmpty() && m_keywords.isFunction(buf))
setFormat(i - buf.length(), buf.length(), m_formats[ProfileFunctionFormat]);
buf.clear();
} else if (c == QLatin1Char('#')) {
@@ -74,7 +79,7 @@ void ProFileHighlighter::highlightBlock(const QString &text)
setFormat(i, 1, m_formats[ProfileCommentFormat]);
buf.clear();
} else {
- if (!buf.isEmpty() && ProFileKeywords::isVariable(buf))
+ if (!buf.isEmpty() && m_keywords.isVariable(buf))
setFormat(i - buf.length(), buf.length(), m_formats[ProfileVariableFormat]);
buf.clear();
}
diff --git a/src/plugins/qt4projectmanager/profilehighlighter.h b/src/plugins/qt4projectmanager/profilehighlighter.h
index 986bc09bbb..e5f8e30012 100644
--- a/src/plugins/qt4projectmanager/profilehighlighter.h
+++ b/src/plugins/qt4projectmanager/profilehighlighter.h
@@ -31,9 +31,11 @@
#define PROFILEHIGHLIGHTER_H
#include <texteditor/syntaxhighlighter.h>
+#include <texteditor/codeassist/keywordscompletionassist.h>
#include <QtAlgorithms>
#include <QSyntaxHighlighter>
#include <QTextCharFormat>
+#include <QVector>
namespace Qt4ProjectManager {
namespace Internal {
@@ -51,16 +53,17 @@ public:
};
ProFileHighlighter(QTextDocument *document = 0);
- virtual void highlightBlock(const QString &text);
+ void highlightBlock(const QString &text);
// Set formats from a sequence of type QTextCharFormat
- template <class InputIterator>
- void setFormats(InputIterator begin, InputIterator end) {
- qCopy(begin, end, m_formats);
- }
+ void setFormats(const QVector<QTextCharFormat> &formats)
+ {
+ qCopy(formats.begin(), formats.end(), m_formats);
+ }
private:
QTextCharFormat m_formats[NumProfileFormats];
+ TextEditor::Keywords m_keywords;
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/profilehoverhandler.cpp b/src/plugins/qt4projectmanager/profilehoverhandler.cpp
index 8812b270f4..16b3ed8568 100644
--- a/src/plugins/qt4projectmanager/profilehoverhandler.cpp
+++ b/src/plugins/qt4projectmanager/profilehoverhandler.cpp
@@ -29,7 +29,7 @@
#include "profilehoverhandler.h"
#include "profileeditor.h"
-#include "profilekeywords.h"
+#include "profilecompletionassist.h"
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/editormanager/editormanager.h>
@@ -38,7 +38,6 @@
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
#include <texteditor/helpitem.h>
-#include <texteditor/tooltip/tooltip.h>
#include <utils/htmldocextractor.h>
#include <QTextCursor>
@@ -53,6 +52,9 @@ ProFileHoverHandler::ProFileHoverHandler(QObject *parent)
: BaseHoverHandler(parent),
m_manualKind(UnknownManual)
{
+ ProFileCompletionAssistProvider *pcap
+ = ExtensionSystem::PluginManager::instance()->getObject<ProFileCompletionAssistProvider>();
+ m_keywords = TextEditor::Keywords(pcap->variables(), pcap->functions(), QMap<QString, QStringList>());
}
ProFileHoverHandler::~ProFileHoverHandler()
@@ -111,9 +113,9 @@ void ProFileHoverHandler::identifyQMakeKeyword(const QString &text, int pos)
if (checkBuffer) {
if (!buf.isEmpty()) {
if ((i >= pos) && (i - buf.size() <= pos)) {
- if (ProFileKeywords::isFunction(buf))
+ if (m_keywords.isFunction(buf))
identifyDocFragment(FunctionManual, buf);
- else if (ProFileKeywords::isVariable(buf))
+ else if (m_keywords.isVariable(buf))
identifyDocFragment(VariableManual, buf);
break;
}
diff --git a/src/plugins/qt4projectmanager/profilehoverhandler.h b/src/plugins/qt4projectmanager/profilehoverhandler.h
index afa557f3a6..a42b1b61fa 100644
--- a/src/plugins/qt4projectmanager/profilehoverhandler.h
+++ b/src/plugins/qt4projectmanager/profilehoverhandler.h
@@ -31,6 +31,7 @@
#define PROFILEHOVERHANDLER_H
#include <texteditor/basehoverhandler.h>
+#include <texteditor/codeassist/keywordscompletionassist.h>
#include <QObject>
@@ -76,6 +77,7 @@ private:
QString m_docFragment;
ManualKind m_manualKind;
+ TextEditor::Keywords m_keywords;
};
} // namespace Internal
diff --git a/src/plugins/qt4projectmanager/profilekeywords.cpp b/src/plugins/qt4projectmanager/profilekeywords.cpp
deleted file mode 100644
index 10e4748a2d..0000000000
--- a/src/plugins/qt4projectmanager/profilekeywords.cpp
+++ /dev/null
@@ -1,332 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "profilekeywords.h"
-
-using namespace Qt4ProjectManager::Internal;
-
-static const char *const variableKeywords[] = {
- "BACKUP_REGISTRATION_FILE_MAEMO",
- "CCFLAG",
- "CONFIG",
- "DEFINES",
- "DEF_FILE",
- "DEPENDPATH",
- "DEPLOYMENT",
- "DEPLOYMENT_PLUGIN",
- "DESTDIR",
- "DESTDIR_TARGET",
- "DISTFILES",
- "DLLDESTDIR",
- "DISTFILES",
- "DSP_TEMPLATE",
- "FORMS",
- "FORMS3",
- "GUID",
- "HEADERS",
- "ICON",
- "INCLUDEPATH",
- "INSTALLS",
- "LEXIMPLS",
- "LEXOBJECTS",
- "LEXSOURCES",
- "LIBS",
- "LITERAL_HASH",
- "MAKEFILE",
- "MAKEFILE_GENERATOR",
- "MOBILITY",
- "MOC_DIR",
- "OBJECTIVE_HEADERS",
- "OBJECTIVE_SOURCES",
- "OBJECTS",
- "OBJECTS_DIR",
- "OBJMOC",
- "OTHER_FILES",
- "PKGCONFIG",
- "POST_TARGETDEPS",
- "PRE_TARGETDEPS",
- "PRECOMPILED_HEADER",
- "PWD",
- "OUT_PWD",
- "QMAKE",
- "QMAKESPEC",
- "QMAKE_APP_FLAG",
- "QMAKE_APP_OR_DLL",
- "QMAKE_AR_CMD",
- "QMAKE_BUNDLE_DATA",
- "QMAKE_BUNDLE_EXTENSION",
- "QMAKE_CC",
- "QMAKE_CFLAGS_DEBUG",
- "QMAKE_CFLAGS_MT",
- "QMAKE_CFLAGS_MT_DBG",
- "QMAKE_CFLAGS_MT_DLL",
- "QMAKE_CFLAGS_MT_DLLDBG",
- "QMAKE_CFLAGS_RELEASE",
- "QMAKE_CFLAGS_SHLIB",
- "QMAKE_CFLAGS_THREAD",
- "QMAKE_CFLAGS_WARN_OFF",
- "QMAKE_CFLAGS_WARN_ON",
- "QMAKE_CLEAN",
- "QMAKE_CXX",
- "QMAKE_CXXFLAGS",
- "QMAKE_CXXFLAGS_DEBUG",
- "QMAKE_CXXFLAGS_MT",
- "QMAKE_CXXFLAGS_MT_DBG",
- "QMAKE_CXXFLAGS_MT_DLL",
- "QMAKE_CXXFLAGS_MT_DLLDBG",
- "QMAKE_CXXFLAGS_RELEASE",
- "QMAKE_CXXFLAGS_SHLIB",
- "QMAKE_CXXFLAGS_THREAD",
- "QMAKE_CXXFLAGS_WARN_OFF",
- "QMAKE_CXXFLAGS_WARN_ON",
- "QMAKE_DISTCLEAN",
- "QMAKE_EXTENSION_SHLIB",
- "QMAKE_EXT_MOC",
- "QMAKE_EXT_UI",
- "QMAKE_EXT_PRL",
- "QMAKE_EXT_LEX",
- "QMAKE_EXT_YACC",
- "QMAKE_EXT_OBJ",
- "QMAKE_EXT_CPP",
- "QMAKE_EXT_H",
- "QMAKE_EXTRA_COMPILERS",
- "QMAKE_EXTRA_TARGETS",
- "QMAKE_FAILED_REQUIREMENTS",
- "QMAKE_FILETAGS",
- "QMAKE_FRAMEWORK_BUNDLE_NAME",
- "QMAKE_FRAMEWORK_VERSION",
- "QMAKE_INCDIR",
- "QMAKE_INCDIR_EGL",
- "QMAKE_INCDIR_OPENGL",
- "QMAKE_INCDIR_OPENGL_ES1",
- "QMAKE_INCDIR_OPENGL_ES2",
- "QMAKE_INCDIR_OPENVG",
- "QMAKE_INCDIR_QT",
- "QMAKE_INCDIR_THREAD",
- "QMAKE_INCDIR_X11",
- "QMAKE_INFO_PLIST",
- "QMAKE_LFLAGS",
- "QMAKE_LFLAGS_CONSOLE",
- "QMAKE_LFLAGS_CONSOLE_DLL",
- "QMAKE_LFLAGS_DEBUG",
- "QMAKE_LFLAGS_PLUGIN",
- "QMAKE_LFLAGS_RPATH",
- "QMAKE_LFLAGS_QT_DLL",
- "QMAKE_LFLAGS_RELEASE",
- "QMAKE_LFLAGS_SHAPP",
- "QMAKE_LFLAGS_SHLIB",
- "QMAKE_LFLAGS_SONAME",
- "QMAKE_LFLAGS_THREAD",
- "QMAKE_LFLAGS_WINDOWS",
- "QMAKE_LFLAGS_WINDOWS_DLL",
- "QMAKE_LIBDIR",
- "QMAKE_LIBDIR_FLAGS",
- "QMAKE_LIBDIR_EGL",
- "QMAKE_LIBDIR_OPENGL",
- "QMAKE_LIBDIR_OPENVG",
- "QMAKE_LIBDIR_QT",
- "QMAKE_LIBDIR_X11",
- "QMAKE_LIBS",
- "QMAKE_LIBS_CONSOLE",
- "QMAKE_LIBS_EGL",
- "QMAKE_LIBS_OPENGL",
- "QMAKE_LIBS_OPENGL_QT",
- "QMAKE_LIBS_OPENGL_ES1",
- "QMAKE_LIBS_OPENGL_ES2",
- "QMAKE_LIBS_OPENVG",
- "QMAKE_LIBS_QT",
- "QMAKE_LIBS_QT_DLL",
- "QMAKE_LIBS_QT_OPENGL",
- "QMAKE_LIBS_QT_THREAD",
- "QMAKE_LIBS_RT",
- "QMAKE_LIBS_RTMT",
- "QMAKE_LIBS_THREAD",
- "QMAKE_LIBS_WINDOWS",
- "QMAKE_LIBS_X11",
- "QMAKE_LIBS_X11SM",
- "QMAKE_LIB_FLAG",
- "QMAKE_LINK_SHLIB_CMD",
- "QMAKE_LN_SHLIB",
- "QMAKE_POST_LINK",
- "QMAKE_PRE_LINK",
- "QMAKE_PROJECT_NAME",
- "QMAKE_MAC_SDK",
- "QMAKE_MACOSX_DEPLOYMENT_TARGET",
- "QMAKE_MAKEFILE",
- "QMAKE_MOC_SRC",
- "QMAKE_QMAKE",
- "QMAKE_QT_DLL",
- "QMAKE_RESOURCE_FLAGS",
- "QMAKE_RPATH",
- "QMAKE_RPATHDIR",
- "QMAKE_RUN_CC",
- "QMAKE_RUN_CC_IMP",
- "QMAKE_RUN_CXX",
- "QMAKE_RUN_CXX_IMP",
- "QMAKE_TARGET",
- "QMAKE_UIC",
- "QT",
- "QTPLUGIN",
- "QT_VERSION",
- "QT_MAJOR_VERSION",
- "QT_MINOR_VERSION",
- "QT_PATCH_VERSION",
- "RCC_DIR",
- "RC_FILE",
- "REQUIRES",
- "RESOURCES",
- "RES_FILE",
- "RSS_RULES",
- "SIGNATURE_FILE",
- "SOURCES",
- "SRCMOC",
- "STATECHARTS",
- "SUBDIRS",
- "TEMPLATE",
- "TRANSLATIONS",
- "UICIMPLS",
- "UICOBJECTS",
- "UI_DIR",
- "UI_HEADERS_DIR",
- "UI_SOURCES_DIR",
- "VER_MAJ",
- "VER_MIN",
- "VER_PAT",
- "VERSION",
- "VPATH",
- "YACCIMPLS",
- "YACCOBJECTS",
- "YACCSOURCES",
- "_PRO_FILE_",
- "_PRO_FILE_PWD_",
- 0
-};
-
-static const char *const functionKeywords[] = {
- "basename",
- "contains",
- "count",
- "dirname",
- "error",
- "eval",
- "exists",
- "find",
- "for",
- "include",
- "infile",
- "isEmpty",
- "join",
- "member",
- "message",
- "packagesExist",
- "prompt",
- "quote",
- "replace",
- "sprintf",
- "system",
- "unique",
- "warning",
- 0
-};
-
-class ProFileKeywordsImplementation
-{
-public:
- static ProFileKeywordsImplementation *instance();
- QStringList variables();
- QStringList functions();
- bool isVariable(const QString &word);
- bool isFunction(const QString &word);
-private:
- ProFileKeywordsImplementation();
- static ProFileKeywordsImplementation *m_instance;
- QStringList m_variables;
- QStringList m_functions;
-};
-
-ProFileKeywordsImplementation *ProFileKeywordsImplementation::m_instance = 0;
-
-ProFileKeywordsImplementation *ProFileKeywordsImplementation::instance()
-{
- if (!m_instance)
- m_instance = new ProFileKeywordsImplementation();
- return m_instance;
-}
-
-QStringList ProFileKeywordsImplementation::variables()
-{
- return m_variables;
-}
-
-QStringList ProFileKeywordsImplementation::functions()
-{
- return m_functions;
-}
-
-bool ProFileKeywordsImplementation::isVariable(const QString &word)
-{
- return m_variables.contains(word);
-}
-
-bool ProFileKeywordsImplementation::isFunction(const QString &word)
-{
- return m_functions.contains(word);
-}
-
-ProFileKeywordsImplementation::ProFileKeywordsImplementation()
-{
- for (uint i = 0; i < sizeof variableKeywords / sizeof variableKeywords[0] - 1; i++)
- m_variables.append(QLatin1String(variableKeywords[i]));
- for (uint i = 0; i < sizeof functionKeywords / sizeof functionKeywords[0] - 1; i++)
- m_functions.append(QLatin1String(functionKeywords[i]));
-}
-
-ProFileKeywords::ProFileKeywords()
-{
-}
-
-QStringList ProFileKeywords::variables()
-{
- return ProFileKeywordsImplementation::instance()->variables();
-}
-
-QStringList ProFileKeywords::functions()
-{
- return ProFileKeywordsImplementation::instance()->functions();
-}
-
-bool ProFileKeywords::isVariable(const QString &word)
-{
- return ProFileKeywordsImplementation::instance()->isVariable(word);
-}
-
-bool ProFileKeywords::isFunction(const QString &word)
-{
- return ProFileKeywordsImplementation::instance()->isFunction(word);
-}
diff --git a/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp b/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp
index 4c73a68e12..b6aacd77a0 100644
--- a/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp
+++ b/src/plugins/qt4projectmanager/qmakekitconfigwidget.cpp
@@ -35,35 +35,36 @@
#include <coreplugin/icore.h>
#include <projectexplorer/projectexplorerconstants.h>
-#include <QHBoxLayout>
#include <QLineEdit>
namespace Qt4ProjectManager {
namespace Internal {
-QmakeKitConfigWidget::QmakeKitConfigWidget(ProjectExplorer::Kit *k, QWidget *parent) :
- ProjectExplorer::KitConfigWidget(parent),
- m_kit(k),
+QmakeKitConfigWidget::QmakeKitConfigWidget(ProjectExplorer::Kit *k) :
+ ProjectExplorer::KitConfigWidget(k),
m_lineEdit(new QLineEdit),
m_ignoreChange(false)
{
- setToolTip(tr("The mkspec to use when building the project with qmake.<br>"
- "This setting is ignored when using other build systems."));
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
-
- m_lineEdit->setContentsMargins(0, 0, 0, 0);
- layout->addWidget(m_lineEdit);
-
refresh(); // set up everything according to kit
connect(m_lineEdit, SIGNAL(textEdited(QString)), this, SLOT(mkspecWasChanged(QString)));
}
+QWidget *QmakeKitConfigWidget::mainWidget() const
+{
+ return m_lineEdit;
+}
+
QString QmakeKitConfigWidget::displayName() const
{
return tr("Qt mkspec:");
}
+QString QmakeKitConfigWidget::toolTip() const
+{
+ return tr("The mkspec to use when building the project with qmake.<br>"
+ "This setting is ignored when using other build systems.");
+}
+
void QmakeKitConfigWidget::makeReadOnly()
{
m_lineEdit->setEnabled(false);
diff --git a/src/plugins/qt4projectmanager/qmakekitconfigwidget.h b/src/plugins/qt4projectmanager/qmakekitconfigwidget.h
index 0b69c6c4ad..02e63bc015 100644
--- a/src/plugins/qt4projectmanager/qmakekitconfigwidget.h
+++ b/src/plugins/qt4projectmanager/qmakekitconfigwidget.h
@@ -32,13 +32,11 @@
#include <projectexplorer/kitconfigwidget.h>
-QT_FORWARD_DECLARE_CLASS(QLineEdit)
-
-namespace ProjectExplorer { class Kit; }
+QT_BEGIN_NAMESPACE
+class QLineEdit;
+QT_END_NAMESPACE
namespace Qt4ProjectManager {
-class BaseQtVersion;
-
namespace Internal {
class QmakeKitConfigWidget : public ProjectExplorer::KitConfigWidget
@@ -46,12 +44,13 @@ class QmakeKitConfigWidget : public ProjectExplorer::KitConfigWidget
Q_OBJECT
public:
- explicit QmakeKitConfigWidget(ProjectExplorer::Kit *k, QWidget *parent = 0);
+ explicit QmakeKitConfigWidget(ProjectExplorer::Kit *k);
+ QWidget *mainWidget() const;
QString displayName() const;
+ QString toolTip() const;
void makeReadOnly();
-
void refresh();
private slots:
@@ -60,7 +59,6 @@ private slots:
private:
int findQtVersion(const int id) const;
- ProjectExplorer::Kit *m_kit;
QLineEdit *m_lineEdit;
bool m_ignoreChange;
};
diff --git a/src/plugins/qt4projectmanager/qmakeparser.cpp b/src/plugins/qt4projectmanager/qmakeparser.cpp
index 8e59653479..e0f544be77 100644
--- a/src/plugins/qt4projectmanager/qmakeparser.cpp
+++ b/src/plugins/qt4projectmanager/qmakeparser.cpp
@@ -137,7 +137,7 @@ void Qt4ProjectManagerPlugin::testQmakeOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Error,
QLatin1String("Parse Error ('sth odd')"),
- Utils::FileName::fromUserInput("e:\\project.pro"),
+ Utils::FileName::fromUserInput(QLatin1String("e:\\project.pro")),
14,
categoryBuildSystem))
<< QString();
@@ -160,7 +160,7 @@ void Qt4ProjectManagerPlugin::testQmakeOutputParsers_data()
<< (QList<ProjectExplorer::Task>()
<< Task(Task::Warning,
QLatin1String("Unescaped backslashes are deprecated."),
- Utils::FileName::fromUserInput("e:\\NokiaQtSDK\\Simulator\\Qt\\msvc2008\\lib\\qtmaind.prl"), 1,
+ Utils::FileName::fromUserInput(QLatin1String("e:\\NokiaQtSDK\\Simulator\\Qt\\msvc2008\\lib\\qtmaind.prl")), 1,
categoryBuildSystem))
<< QString();
}
diff --git a/src/plugins/qt4projectmanager/qmakestep.cpp b/src/plugins/qt4projectmanager/qmakestep.cpp
index b02da30adf..dad8ff3385 100644
--- a/src/plugins/qt4projectmanager/qmakestep.cpp
+++ b/src/plugins/qt4projectmanager/qmakestep.cpp
@@ -53,6 +53,7 @@
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/debugginghelperbuildtask.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
@@ -65,14 +66,15 @@
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using namespace ProjectExplorer;
+using namespace Utils;
namespace {
-const char * const QMAKE_BS_ID("QtProjectManager.QMakeBuildStep");
+const char QMAKE_BS_ID[] = "QtProjectManager.QMakeBuildStep";
-const char * const QMAKE_ARGUMENTS_KEY("QtProjectManager.QMakeBuildStep.QMakeArguments");
-const char * const QMAKE_FORCED_KEY("QtProjectManager.QMakeBuildStep.QMakeForced");
-const char * const QMAKE_QMLDEBUGLIBAUTO_KEY("QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibraryAuto");
-const char * const QMAKE_QMLDEBUGLIB_KEY("QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary");
+const char QMAKE_ARGUMENTS_KEY[] = "QtProjectManager.QMakeBuildStep.QMakeArguments";
+const char QMAKE_FORCED_KEY[] = "QtProjectManager.QMakeBuildStep.QMakeForced";
+const char QMAKE_QMLDEBUGLIBAUTO_KEY[] = "QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibraryAuto";
+const char QMAKE_QMLDEBUGLIB_KEY[] = "QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary";
}
QMakeStep::QMakeStep(BuildStepList *bsl) :
@@ -136,7 +138,7 @@ QString QMakeStep::allArguments(bool shorted)
arguments << QLatin1String("-r");
bool userProvidedMkspec = false;
- for (Utils::QtcProcess::ConstArgIterator ait(m_userArgs); ait.next(); ) {
+ for (QtcProcess::ConstArgIterator ait(m_userArgs); ait.next(); ) {
if (ait.value() == QLatin1String("-spec")) {
if (ait.next()) {
userProvidedMkspec = true;
@@ -144,7 +146,7 @@ QString QMakeStep::allArguments(bool shorted)
}
}
}
- Utils::FileName specArg = mkspec();
+ FileName specArg = mkspec();
if (!userProvidedMkspec && !specArg.isEmpty())
arguments << QLatin1String("-spec") << specArg.toUserOutput();
@@ -153,12 +155,12 @@ QString QMakeStep::allArguments(bool shorted)
arguments << deducedArguments();
- QString args = Utils::QtcProcess::joinArgs(arguments);
+ QString args = QtcProcess::joinArgs(arguments);
// User arguments
- Utils::QtcProcess::addArgs(&args, m_userArgs);
+ QtcProcess::addArgs(&args, m_userArgs);
// moreArgumentsAfter
foreach (const QString &arg, deducedArgumentsAfter())
- Utils::QtcProcess::addArg(&args, arg);
+ QtcProcess::addArg(&args, arg);
return args;
}
@@ -174,11 +176,11 @@ QStringList QMakeStep::deducedArguments()
ProjectExplorer::Abi targetAbi;
if (tc)
targetAbi = tc->targetAbi();
-#if defined(Q_OS_WIN) || defined(Q_OS_MAC)
- if ((targetAbi.osFlavor() == ProjectExplorer::Abi::HarmattanLinuxFlavor
- || targetAbi.osFlavor() == ProjectExplorer::Abi::MaemoLinuxFlavor))
+ if ((HostOsInfo::isWindowsHost() || HostOsInfo::isMacHost())
+ && (targetAbi.osFlavor() == ProjectExplorer::Abi::HarmattanLinuxFlavor
+ || targetAbi.osFlavor() == ProjectExplorer::Abi::MaemoLinuxFlavor)) {
arguments << QLatin1String("-unix");
-#endif
+ }
// explicitly add architecture to CONFIG
if ((targetAbi.os() == ProjectExplorer::Abi::MacOS)
@@ -204,9 +206,8 @@ QStringList QMakeStep::deducedArguments()
// TODO: For Qt5, we can pass both arguments as there can be Qt Quick 1/2 projects.
// Currently there is no support for debugging multiple engines.
arguments << QLatin1String(Constants::QMAKEVAR_QUICK1_DEBUG);
- if (version->qtVersion().majorVersion >= 5) {
+ if (version->qtVersion().majorVersion >= 5)
arguments << QLatin1String(Constants::QMAKEVAR_QUICK2_DEBUG);
- }
} else {
const QString qmlDebuggingHelperLibrary = version->qmlDebuggingHelperLibrary(true);
if (!qmlDebuggingHelperLibrary.isEmpty()) {
@@ -259,7 +260,7 @@ bool QMakeStep::init()
else
workingDirectory = qt4bc->buildDirectory();
- Utils::FileName program = qtVersion->qmakeCommand();
+ FileName program = qtVersion->qmakeCommand();
QString makefile = workingDirectory;
@@ -287,6 +288,7 @@ bool QMakeStep::init()
pp->setCommand(program.toString());
pp->setArguments(args);
pp->setEnvironment(qt4bc->environment());
+ pp->resolveAll();
setOutputParser(new QMakeParser);
@@ -446,7 +448,7 @@ void QMakeStep::setLinkQmlDebuggingLibrary(bool enable)
QStringList QMakeStep::parserArguments()
{
QStringList result;
- for (Utils::QtcProcess::ConstArgIterator ait(allArguments()); ait.next(); )
+ for (QtcProcess::ConstArgIterator ait(allArguments()); ait.next(); )
if (ait.isSimple())
result << ait.value();
return result;
@@ -457,13 +459,13 @@ QString QMakeStep::userArguments()
return m_userArgs;
}
-Utils::FileName QMakeStep::mkspec()
+FileName QMakeStep::mkspec()
{
QString additionalArguments = m_userArgs;
- for (Utils::QtcProcess::ArgIterator ait(&additionalArguments); ait.next(); ) {
+ for (QtcProcess::ArgIterator ait(&additionalArguments); ait.next(); ) {
if (ait.value() == QLatin1String("-spec")) {
if (ait.next())
- return Utils::FileName::fromUserInput(ait.value());
+ return FileName::fromUserInput(ait.value());
}
}
@@ -487,11 +489,10 @@ bool QMakeStep::fromMap(const QVariantMap &map)
if (map.value(QLatin1String(QMAKE_QMLDEBUGLIBAUTO_KEY), false).toBool()) {
m_linkQmlDebuggingLibrary = DebugLink;
} else {
- if (map.value(QLatin1String(QMAKE_QMLDEBUGLIB_KEY), false).toBool()) {
+ if (map.value(QLatin1String(QMAKE_QMLDEBUGLIB_KEY), false).toBool())
m_linkQmlDebuggingLibrary = DoLink;
- } else {
+ else
m_linkQmlDebuggingLibrary = DoNotLink;
- }
}
return BuildStep::fromMap(map);
diff --git a/src/plugins/qt4projectmanager/qt-desktop/desktopqtversion.cpp b/src/plugins/qt4projectmanager/qt-desktop/desktopqtversion.cpp
index 88036deca7..20d670eb2d 100644
--- a/src/plugins/qt4projectmanager/qt-desktop/desktopqtversion.cpp
+++ b/src/plugins/qt4projectmanager/qt-desktop/desktopqtversion.cpp
@@ -28,7 +28,7 @@
****************************************************************************/
#include "desktopqtversion.h"
-#include "qt4projectmanagerconstants.h"
+#include "../qt4projectmanagerconstants.h"
#include <qtsupport/qtsupportconstants.h>
#include <proparser/profileevaluator.h>
@@ -49,7 +49,7 @@ DesktopQtVersion::DesktopQtVersion()
DesktopQtVersion::DesktopQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource)
: BaseQtVersion(path, isAutodetected, autodetectionSource)
{
-
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
}
DesktopQtVersion::~DesktopQtVersion()
diff --git a/src/plugins/qt4projectmanager/qt-desktop/desktopqtversionfactory.cpp b/src/plugins/qt4projectmanager/qt-desktop/desktopqtversionfactory.cpp
index a4863b7d13..b31c909e52 100644
--- a/src/plugins/qt4projectmanager/qt-desktop/desktopqtversionfactory.cpp
+++ b/src/plugins/qt4projectmanager/qt-desktop/desktopqtversionfactory.cpp
@@ -27,8 +27,8 @@
**
****************************************************************************/
#include "desktopqtversionfactory.h"
-#include "qt4projectmanagerconstants.h"
#include "desktopqtversion.h"
+#include "../qt4projectmanagerconstants.h"
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/qtsupportconstants.h>
diff --git a/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.cpp b/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.cpp
index f4e789cf71..c2dbf17f45 100644
--- a/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.cpp
+++ b/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.cpp
@@ -29,12 +29,12 @@
#include "qt4runconfiguration.h"
-#include "makestep.h"
-#include "qt4nodes.h"
-#include "qt4project.h"
-#include "qt4buildconfiguration.h"
-#include "qt4projectmanagerconstants.h"
-#include "qmakestep.h"
+#include "../makestep.h"
+#include "../qt4nodes.h"
+#include "../qt4project.h"
+#include "../qt4buildconfiguration.h"
+#include "../qt4projectmanagerconstants.h"
+#include "../qmakestep.h"
#include <coreplugin/coreconstants.h>
#include <coreplugin/icore.h>
@@ -58,6 +58,7 @@
#include <qtsupport/baseqtversion.h>
#include <qtsupport/profilereader.h>
#include <qtsupport/qtkitinformation.h>
+#include <utils/hostosinfo.h>
#include <QFormLayout>
#include <QInputDialog>
@@ -150,7 +151,7 @@ QString Qt4RunConfiguration::disabledReason() const
return QString();
}
-void Qt4RunConfiguration::kitUpdated(Qt4ProjectManager::Qt4ProFileNode *pro, bool success, bool parseInProgress)
+void Qt4RunConfiguration::proFileUpdated(Qt4ProjectManager::Qt4ProFileNode *pro, bool success, bool parseInProgress)
{
if (m_proFilePath != pro->path()) {
if (!parseInProgress) {
@@ -179,12 +180,12 @@ void Qt4RunConfiguration::ctor()
setDefaultDisplayName(defaultDisplayName());
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- m_forcedGuiMode = (version && version->type() == QtSupport::Constants::SIMULATORQT);
+ m_forcedGuiMode = (version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT));
connect(target(), SIGNAL(environmentChanged()),
this, SIGNAL(baseEnvironmentChanged()));
- connect(target()->project(), SIGNAL(kitUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)),
- this, SLOT(kitUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)));
+ connect(target()->project(), SIGNAL(proFileUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)),
+ this, SLOT(proFileUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)));
connect(target(), SIGNAL(kitChanged()),
this, SLOT(kitChanged()));
}
@@ -192,7 +193,7 @@ void Qt4RunConfiguration::ctor()
void Qt4RunConfiguration::kitChanged()
{
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- m_forcedGuiMode = (version && version->type() == QtSupport::Constants::SIMULATORQT);
+ m_forcedGuiMode = (version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT));
emit runModeChanged(runMode()); // Always emit
}
@@ -261,13 +262,13 @@ Qt4RunConfigurationWidget::Qt4RunConfigurationWidget(Qt4RunConfiguration *qt4Run
toplayout->addRow(QString(), m_useTerminalCheck);
m_useTerminalCheck->setVisible(!m_qt4RunConfiguration->forcedGuiMode());
-#ifdef Q_OS_MAC
- m_usingDyldImageSuffix = new QCheckBox(tr("Use debug version of frameworks (DYLD_IMAGE_SUFFIX=_debug)"), this);
- m_usingDyldImageSuffix->setChecked(m_qt4RunConfiguration->isUsingDyldImageSuffix());
- toplayout->addRow(QString(), m_usingDyldImageSuffix);
- connect(m_usingDyldImageSuffix, SIGNAL(toggled(bool)),
- this, SLOT(usingDyldImageSuffixToggled(bool)));
-#endif
+ if (Utils::HostOsInfo::isMacHost()) {
+ m_usingDyldImageSuffix = new QCheckBox(tr("Use debug version of frameworks (DYLD_IMAGE_SUFFIX=_debug)"), this);
+ m_usingDyldImageSuffix->setChecked(m_qt4RunConfiguration->isUsingDyldImageSuffix());
+ toplayout->addRow(QString(), m_usingDyldImageSuffix);
+ connect(m_usingDyldImageSuffix, SIGNAL(toggled(bool)),
+ this, SLOT(usingDyldImageSuffixToggled(bool)));
+ }
QLabel *environmentLabel = new QLabel(this);
environmentLabel->setText(tr("Run Environment"));
@@ -596,9 +597,8 @@ Utils::Environment Qt4RunConfiguration::baseEnvironment() const
&& target()->activeBuildConfiguration()) {
env = target()->activeBuildConfiguration()->environment();
}
- if (m_isUsingDyldImageSuffix) {
+ if (m_isUsingDyldImageSuffix)
env.set(QLatin1String("DYLD_IMAGE_SUFFIX"), QLatin1String("_debug"));
- }
// The user could be linking to a library found via a -L/some/dir switch
// to find those libraries while actually running we explicitly prepend those
diff --git a/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h b/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h
index 5f8c9ca4b0..8fa80838ca 100644
--- a/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h
+++ b/src/plugins/qt4projectmanager/qt-desktop/qt4runconfiguration.h
@@ -32,7 +32,7 @@
#include "qmakerunconfigurationfactory.h"
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <utils/environment.h>
@@ -113,7 +113,7 @@ signals:
private slots:
void kitChanged();
- void kitUpdated(Qt4ProjectManager::Qt4ProFileNode *pro, bool success, bool parseInProgress);
+ void proFileUpdated(Qt4ProjectManager::Qt4ProFileNode *pro, bool success, bool parseInProgress);
protected:
Qt4RunConfiguration(ProjectExplorer::Target *parent, Qt4RunConfiguration *source);
diff --git a/src/plugins/qt4projectmanager/qt-desktop/simulatorqtversion.cpp b/src/plugins/qt4projectmanager/qt-desktop/simulatorqtversion.cpp
index 132e637a12..843f954856 100644
--- a/src/plugins/qt4projectmanager/qt-desktop/simulatorqtversion.cpp
+++ b/src/plugins/qt4projectmanager/qt-desktop/simulatorqtversion.cpp
@@ -49,7 +49,7 @@ SimulatorQtVersion::SimulatorQtVersion()
SimulatorQtVersion::SimulatorQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource)
: QtSupport::BaseQtVersion(path, isAutodetected, autodetectionSource)
{
-
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
}
SimulatorQtVersion::~SimulatorQtVersion()
@@ -100,6 +100,6 @@ Core::FeatureSet SimulatorQtVersion::availableFeatures() const
bool SimulatorQtVersion::supportsPlatform(const QString &platformName) const
{
- return (platformName == QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM
- || platformName.isEmpty());
+ return (platformName.isEmpty()
+ || platformName == QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM));
}
diff --git a/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp b/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp
index 8c721797d6..8a5c35343d 100644
--- a/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp
+++ b/src/plugins/qt4projectmanager/qt4buildconfiguration.cpp
@@ -43,29 +43,31 @@
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
+#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/kitinformation.h>
#include <qtsupport/qtsupportconstants.h>
#include <qtsupport/qtversionfactory.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
+#include <qt4projectmanager/qmakekitinformation.h>
#include <QDebug>
#include <QInputDialog>
-using namespace Qt4ProjectManager;
-using namespace Qt4ProjectManager::Internal;
-using namespace ProjectExplorer;
+namespace Qt4ProjectManager {
-namespace {
-const char * const QT4_BC_ID("Qt4ProjectManager.Qt4BuildConfiguration");
+using namespace Internal;
+using namespace ProjectExplorer;
+using namespace QtSupport;
+using namespace Utils;
-const char * const USE_SHADOW_BUILD_KEY("Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild");
-const char * const BUILD_DIRECTORY_KEY("Qt4ProjectManager.Qt4BuildConfiguration.BuildDirectory");
-const char * const BUILD_CONFIGURATION_KEY("Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration");
+const char QT4_BC_ID[] = "Qt4ProjectManager.Qt4BuildConfiguration";
+const char USE_SHADOW_BUILD_KEY[] = "Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild";
+const char BUILD_DIRECTORY_KEY[] = "Qt4ProjectManager.Qt4BuildConfiguration.BuildDirectory";
+const char BUILD_CONFIGURATION_KEY[] = "Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration";
enum { debug = 0 };
-}
Qt4BuildConfiguration::Qt4BuildConfiguration(Target *target) :
BuildConfiguration(target, Core::Id(QT4_BC_ID)),
@@ -121,12 +123,18 @@ bool Qt4BuildConfiguration::fromMap(const QVariantMap &map)
return false;
m_shadowBuild = map.value(QLatin1String(USE_SHADOW_BUILD_KEY), true).toBool();
- m_qmakeBuildConfiguration = QtSupport::BaseQtVersion::QmakeBuildConfigs(map.value(QLatin1String(BUILD_CONFIGURATION_KEY)).toInt());
+ m_qmakeBuildConfiguration = BaseQtVersion::QmakeBuildConfigs(map.value(QLatin1String(BUILD_CONFIGURATION_KEY)).toInt());
m_buildDirectory = map.value(QLatin1String(BUILD_DIRECTORY_KEY), defaultShadowBuildDirectory()).toString();
m_lastEmmitedBuildDirectory = buildDirectory();
m_qtVersionSupportsShadowBuilds = supportsShadowBuilds();
+ m_lastKitState = LastKitState(target()->kit());
+
+ connect(ProjectExplorer::ToolChainManager::instance(), SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain *)),
+ this, SLOT(toolChainUpdated(ProjectExplorer::ToolChain *)));
+ connect(QtSupport::QtVersionManager::instance(), SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
+ this, SLOT(qtVersionsChanged(QList<int>,QList<int>,QList<int>)));
return true;
}
@@ -142,9 +150,27 @@ void Qt4BuildConfiguration::ctor()
void Qt4BuildConfiguration::kitChanged()
{
- emitProFileEvaluateNeeded();
- emit environmentChanged();
- emitBuildDirectoryChanged();
+ LastKitState newState = LastKitState(target()->kit());
+ if (newState != m_lastKitState) {
+ // This only checks if the ids have changed!
+ // For that reason the Qt4BuildConfiguration is also connected
+ // to the toolchain and qtversion managers
+ emitProFileEvaluateNeeded();
+ emitBuildDirectoryChanged();
+ m_lastKitState = newState;
+ }
+}
+
+void Qt4BuildConfiguration::toolChainUpdated(ProjectExplorer::ToolChain *tc)
+{
+ if (ToolChainKitInformation::toolChain(target()->kit()) == tc)
+ emitProFileEvaluateNeeded();
+}
+
+void Qt4BuildConfiguration::qtVersionsChanged(const QList<int> &,const QList<int> &, const QList<int> &changed)
+{
+ if (changed.contains(QtKitInformation::qtVersionId(target()->kit())))
+ emitProFileEvaluateNeeded();
}
void Qt4BuildConfiguration::emitBuildDirectoryChanged()
@@ -158,15 +184,9 @@ void Qt4BuildConfiguration::emitBuildDirectoryChanged()
}
}
-Utils::Environment Qt4BuildConfiguration::baseEnvironment() const
-{
- Utils::Environment env = BuildConfiguration::baseEnvironment();
- return env;
-}
-
-BuildConfigWidget *Qt4BuildConfiguration::createConfigWidget()
+NamedWidget *Qt4BuildConfiguration::createConfigWidget()
{
- return new Qt4ProjectConfigWidget(target());
+ return new Qt4ProjectConfigWidget(this);
}
QString Qt4BuildConfiguration::defaultShadowBuildDirectory() const
@@ -191,7 +211,7 @@ QString Qt4BuildConfiguration::rawBuildDirectory() const
return workingDirectory;
}
-/// returns the build directory
+/// Returns the build directory.
QString Qt4BuildConfiguration::buildDirectory() const
{
QString path = QDir::cleanPath(environment().expandVariables(rawBuildDirectory()));
@@ -200,14 +220,14 @@ QString Qt4BuildConfiguration::buildDirectory() const
bool Qt4BuildConfiguration::supportsShadowBuilds()
{
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
+ BaseQtVersion *version = QtKitInformation::qtVersion(target()->kit());
return !version || version->supportsShadowBuilds();
}
/// If only a sub tree should be build this function returns which sub node
/// should be build
/// \see Qt4BuildConfiguration::setSubNodeBuild
-Qt4ProjectManager::Qt4ProFileNode *Qt4BuildConfiguration::subNodeBuild() const
+Qt4ProFileNode *Qt4BuildConfiguration::subNodeBuild() const
{
return m_subNodeBuild;
}
@@ -218,7 +238,7 @@ Qt4ProjectManager::Qt4ProFileNode *Qt4BuildConfiguration::subNodeBuild() const
/// calling BuildManager::buildProject( BuildConfiguration * )
/// and reset immediately afterwards
/// That is m_subNodesBuild is set only temporarly
-void Qt4BuildConfiguration::setSubNodeBuild(Qt4ProjectManager::Qt4ProFileNode *node)
+void Qt4BuildConfiguration::setSubNodeBuild(Qt4ProFileNode *node)
{
m_subNodeBuild = node;
}
@@ -253,7 +273,7 @@ QString Qt4BuildConfiguration::shadowBuildDirectory() const
void Qt4BuildConfiguration::setShadowBuildAndDirectory(bool shadowBuild, const QString &buildDirectory)
{
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
+ BaseQtVersion *version = QtKitInformation::qtVersion(target()->kit());
QString directoryToSet = buildDirectory;
bool toSet = (shadowBuild && version && version->isValid() && version->supportsShadowBuilds());
if (m_shadowBuild == toSet && m_buildDirectory == directoryToSet)
@@ -262,32 +282,21 @@ void Qt4BuildConfiguration::setShadowBuildAndDirectory(bool shadowBuild, const Q
m_shadowBuild = toSet;
m_buildDirectory = directoryToSet;
- emit environmentChanged();
emitBuildDirectoryChanged();
emitProFileEvaluateNeeded();
}
-QString Qt4BuildConfiguration::defaultMakeTarget() const
-{
- ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(target()->kit());
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- if (!tc || !version)
- return QString();
-
- return tc->defaultMakeTarget();
-}
-
QString Qt4BuildConfiguration::makefile() const
{
return static_cast<Qt4Project *>(target()->project())->rootQt4ProjectNode()->makefile();
}
-QtSupport::BaseQtVersion::QmakeBuildConfigs Qt4BuildConfiguration::qmakeBuildConfiguration() const
+BaseQtVersion::QmakeBuildConfigs Qt4BuildConfiguration::qmakeBuildConfiguration() const
{
return m_qmakeBuildConfiguration;
}
-void Qt4BuildConfiguration::setQMakeBuildConfiguration(QtSupport::BaseQtVersion::QmakeBuildConfigs config)
+void Qt4BuildConfiguration::setQMakeBuildConfiguration(BaseQtVersion::QmakeBuildConfigs config)
{
if (m_qmakeBuildConfiguration == config)
return;
@@ -314,17 +323,18 @@ void Qt4BuildConfiguration::emitQMakeBuildConfigurationChanged()
QStringList Qt4BuildConfiguration::configCommandLineArguments() const
{
QStringList result;
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
- QtSupport::BaseQtVersion::QmakeBuildConfigs defaultBuildConfiguration = version ? version->defaultBuildConfig() : (QtSupport::BaseQtVersion::DebugBuild | QtSupport::BaseQtVersion::BuildAll);
- QtSupport::BaseQtVersion::QmakeBuildConfigs userBuildConfiguration = m_qmakeBuildConfiguration;
- if ((defaultBuildConfiguration & QtSupport::BaseQtVersion::BuildAll) && !(userBuildConfiguration & QtSupport::BaseQtVersion::BuildAll))
+ BaseQtVersion *version = QtKitInformation::qtVersion(target()->kit());
+ BaseQtVersion::QmakeBuildConfigs defaultBuildConfiguration =
+ version ? version->defaultBuildConfig() : (BaseQtVersion::DebugBuild | BaseQtVersion::BuildAll);
+ BaseQtVersion::QmakeBuildConfigs userBuildConfiguration = m_qmakeBuildConfiguration;
+ if ((defaultBuildConfiguration & BaseQtVersion::BuildAll) && !(userBuildConfiguration & BaseQtVersion::BuildAll))
result << QLatin1String("CONFIG-=debug_and_release");
- if (!(defaultBuildConfiguration & QtSupport::BaseQtVersion::BuildAll) && (userBuildConfiguration & QtSupport::BaseQtVersion::BuildAll))
+ if (!(defaultBuildConfiguration & BaseQtVersion::BuildAll) && (userBuildConfiguration & BaseQtVersion::BuildAll))
result << QLatin1String("CONFIG+=debug_and_release");
- if ((defaultBuildConfiguration & QtSupport::BaseQtVersion::DebugBuild) && !(userBuildConfiguration & QtSupport::BaseQtVersion::DebugBuild))
+ if ((defaultBuildConfiguration & BaseQtVersion::DebugBuild) && !(userBuildConfiguration & BaseQtVersion::DebugBuild))
result << QLatin1String("CONFIG+=release");
- if (!(defaultBuildConfiguration & QtSupport::BaseQtVersion::DebugBuild) && (userBuildConfiguration & QtSupport::BaseQtVersion::DebugBuild))
+ if (!(defaultBuildConfiguration & BaseQtVersion::DebugBuild) && (userBuildConfiguration & BaseQtVersion::DebugBuild))
result << QLatin1String("CONFIG+=debug");
return result;
}
@@ -351,19 +361,19 @@ MakeStep *Qt4BuildConfiguration::makeStep() const
return 0;
}
-// returns true if both are equal
+// Returns true if both are equal.
Qt4BuildConfiguration::MakefileState Qt4BuildConfiguration::compareToImportFrom(const QString &makefile)
{
QMakeStep *qs = qmakeStep();
if (QFileInfo(makefile).exists() && qs) {
- Utils::FileName qmakePath = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target()->kit());
+ FileName qmakePath = QtVersionManager::findQMakeBinaryFromMakefile(makefile);
+ BaseQtVersion *version = QtKitInformation::qtVersion(target()->kit());
if (!version)
return MakefileForWrongProject;
if (version->qmakeCommand() == qmakePath) {
// same qtversion
- QPair<QtSupport::BaseQtVersion::QmakeBuildConfigs, QString> result =
- QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());
+ QPair<BaseQtVersion::QmakeBuildConfigs, QString> result =
+ QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());
if (qmakeBuildConfiguration() == result.first) {
// The qmake Build Configuration are the same,
// now compare arguments lists
@@ -376,17 +386,17 @@ Qt4BuildConfiguration::MakefileState Qt4BuildConfiguration::compareToImportFrom(
// are not interested in), splitting them up into individual strings:
extractSpecFromArguments(&userArgs, workingDirectory, version, &actualArgs);
actualArgs = qs->deducedArguments() + actualArgs + qs->deducedArgumentsAfter();
- Utils::FileName actualSpec = qs->mkspec();
+ FileName actualSpec = qs->mkspec();
QString qmakeArgs = result.second;
QStringList parsedArgs;
- Utils::FileName parsedSpec = extractSpecFromArguments(&qmakeArgs, workingDirectory, version, &parsedArgs);
+ FileName parsedSpec = extractSpecFromArguments(&qmakeArgs, workingDirectory, version, &parsedArgs);
if (debug) {
- qDebug()<<"Actual args:"<<actualArgs;
- qDebug()<<"Parsed args:"<<parsedArgs;
- qDebug()<<"Actual spec:"<<actualSpec.toString();
- qDebug()<<"Parsed spec:"<<parsedSpec.toString();
+ qDebug() << "Actual args:" << actualArgs;
+ qDebug() << "Parsed args:" << parsedArgs;
+ qDebug() << "Actual spec:" << actualSpec.toString();
+ qDebug() << "Parsed spec:" << parsedSpec.toString();
}
// Comparing the sorted list is obviously wrong
@@ -410,20 +420,22 @@ Qt4BuildConfiguration::MakefileState Qt4BuildConfiguration::compareToImportFrom(
if (actualSpec == parsedSpec)
return MakefileMatches;
// Actual spec is the default one
-// qDebug()<<"AS vs VS"<<actualSpec<<version->mkspec();
- if ((actualSpec == version->mkspec() || actualSpec == Utils::FileName::fromString(QLatin1String("default")))
- && (parsedSpec == version->mkspec() || parsedSpec == Utils::FileName::fromString(QLatin1String("default")) || parsedSpec.isEmpty()))
+// qDebug() << "AS vs VS" << actualSpec << version->mkspec();
+ if ((actualSpec == version->mkspec() || actualSpec == FileName::fromString(QLatin1String("default")))
+ && (parsedSpec == version->mkspec() || parsedSpec == FileName::fromString(QLatin1String("default")) || parsedSpec.isEmpty()))
return MakefileMatches;
}
return MakefileIncompatible;
} else {
if (debug)
- qDebug()<<"different qmake buildconfigurations buildconfiguration:"<<qmakeBuildConfiguration()<<" Makefile:"<<result.first;
+ qDebug() << "different qmake buildconfigurations buildconfiguration:"
+ << qmakeBuildConfiguration() << " Makefile:" << result.first;
return MakefileIncompatible;
}
} else {
if (debug)
- qDebug() << "different Qt versions, buildconfiguration:" << version->qmakeCommand().toString() << " Makefile:"<< qmakePath.toString();
+ qDebug() << "different Qt versions, buildconfiguration:" << version->qmakeCommand().toString()
+ << " Makefile:"<< qmakePath.toString();
return MakefileForWrongProject;
}
}
@@ -433,7 +445,7 @@ Qt4BuildConfiguration::MakefileState Qt4BuildConfiguration::compareToImportFrom(
bool Qt4BuildConfiguration::removeQMLInspectorFromArguments(QString *args)
{
bool removedArgument = false;
- for (Utils::QtcProcess::ArgIterator ait(args); ait.next(); ) {
+ for (QtcProcess::ArgIterator ait(args); ait.next(); ) {
const QString arg = ait.value();
if (arg.contains(QLatin1String(Constants::QMAKEVAR_QMLJSDEBUGGER_PATH))
|| arg.contains(QLatin1String(Constants::QMAKEVAR_QUICK1_DEBUG))
@@ -445,21 +457,21 @@ bool Qt4BuildConfiguration::removeQMLInspectorFromArguments(QString *args)
return removedArgument;
}
-Utils::FileName Qt4BuildConfiguration::extractSpecFromArguments(QString *args,
- const QString &directory, const QtSupport::BaseQtVersion *version,
- QStringList *outArgs)
+FileName Qt4BuildConfiguration::extractSpecFromArguments(QString *args,
+ const QString &directory, const BaseQtVersion *version,
+ QStringList *outArgs)
{
- Utils::FileName parsedSpec;
+ FileName parsedSpec;
bool ignoreNext = false;
bool nextIsSpec = false;
- for (Utils::QtcProcess::ArgIterator ait(args); ait.next(); ) {
+ for (QtcProcess::ArgIterator ait(args); ait.next(); ) {
if (ignoreNext) {
ignoreNext = false;
ait.deleteArg();
} else if (nextIsSpec) {
nextIsSpec = false;
- parsedSpec = Utils::FileName::fromUserInput(ait.value());
+ parsedSpec = FileName::fromUserInput(ait.value());
ait.deleteArg();
} else if (ait.value() == QLatin1String("-spec") || ait.value() == QLatin1String("-platform")) {
nextIsSpec = true;
@@ -479,9 +491,9 @@ Utils::FileName Qt4BuildConfiguration::extractSpecFromArguments(QString *args,
}
if (parsedSpec.isEmpty())
- return Utils::FileName();
+ return FileName();
- Utils::FileName baseMkspecDir = Utils::FileName::fromUserInput(
+ FileName baseMkspecDir = FileName::fromUserInput(
version->qmakeProperty("QT_HOST_DATA") + QLatin1String("/mkspecs"));
baseMkspecDir = Utils::FileName::fromString(baseMkspecDir.toFileInfo().canonicalFilePath());
@@ -491,37 +503,29 @@ Utils::FileName Qt4BuildConfiguration::extractSpecFromArguments(QString *args,
// if it is the former we need to get the canonical form
// for the other one we don't need to do anything
if (parsedSpec.toFileInfo().isRelative()) {
- if (QFileInfo(directory + QLatin1Char('/') + parsedSpec.toString()).exists()) {
- parsedSpec = Utils::FileName::fromUserInput(directory + QLatin1Char('/') + parsedSpec.toString());
- } else {
- parsedSpec = Utils::FileName::fromUserInput(baseMkspecDir.toString() + QLatin1Char('/') + parsedSpec.toString());
- }
+ if (QFileInfo(directory + QLatin1Char('/') + parsedSpec.toString()).exists())
+ parsedSpec = FileName::fromUserInput(directory + QLatin1Char('/') + parsedSpec.toString());
+ else
+ parsedSpec = FileName::fromUserInput(baseMkspecDir.toString() + QLatin1Char('/') + parsedSpec.toString());
}
QFileInfo f2 = parsedSpec.toFileInfo();
while (f2.isSymLink()) {
- parsedSpec = Utils::FileName::fromString(f2.symLinkTarget());
+ parsedSpec = FileName::fromString(f2.symLinkTarget());
f2.setFile(parsedSpec.toString());
}
if (parsedSpec.isChildOf(baseMkspecDir)) {
parsedSpec = parsedSpec.relativeChildPath(baseMkspecDir);
} else {
- Utils::FileName sourceMkSpecPath = Utils::FileName::fromString(version->sourcePath().toString()
- + QLatin1String("/mkspecs"));
- if (parsedSpec.isChildOf(sourceMkSpecPath)) {
+ FileName sourceMkSpecPath = FileName::fromString(version->sourcePath().toString()
+ + QLatin1String("/mkspecs"));
+ if (parsedSpec.isChildOf(sourceMkSpecPath))
parsedSpec = parsedSpec.relativeChildPath(sourceMkSpecPath);
- }
}
return parsedSpec;
}
-ProjectExplorer::IOutputParser *Qt4BuildConfiguration::createOutputParser() const
-{
- ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit());
- return tc ? tc->outputParser() : 0;
-}
-
bool Qt4BuildConfiguration::isEnabled() const
{
return m_isEnabled;
@@ -547,11 +551,11 @@ void Qt4BuildConfiguration::setEnabled(bool enabled)
*/
Qt4BuildConfigurationFactory::Qt4BuildConfigurationFactory(QObject *parent) :
- ProjectExplorer::IBuildConfigurationFactory(parent)
+ IBuildConfigurationFactory(parent)
{
update();
- QtSupport::QtVersionManager *vm = QtSupport::QtVersionManager::instance();
+ QtVersionManager *vm = QtVersionManager::instance();
connect(vm, SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)),
this, SLOT(update()));
}
@@ -593,17 +597,17 @@ bool Qt4BuildConfigurationFactory::canCreate(const Target *parent, const Core::I
return id == QT4_BC_ID;
}
-BuildConfiguration *Qt4BuildConfigurationFactory::create(ProjectExplorer::Target *parent, const Core::Id id, const QString &name)
+BuildConfiguration *Qt4BuildConfigurationFactory::create(Target *parent, const Core::Id id, const QString &name)
{
if (!canCreate(parent, id))
return 0;
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(parent->kit());
+ BaseQtVersion *version = QtKitInformation::qtVersion(parent->kit());
Q_ASSERT(version);
bool ok = true;
QString buildConfigurationName = name;
- if (buildConfigurationName.isEmpty())
+ if (buildConfigurationName.isNull())
buildConfigurationName = QInputDialog::getText(0,
tr("New Configuration"),
tr("New configuration name:"),
@@ -614,28 +618,28 @@ BuildConfiguration *Qt4BuildConfigurationFactory::create(ProjectExplorer::Target
return 0;
//: Debug build configuration. We recommend not translating it.
- QString defaultFirstName = tr("%1 Debug").arg(version->displayName());
+ QString defaultFirstName = tr("%1 Debug").arg(version->displayName()).trimmed();
QString customFirstName;
if (buildConfigurationName != version->displayName())
- customFirstName = tr("%1 Debug").arg(buildConfigurationName);
+ customFirstName = tr("%1 Debug").arg(buildConfigurationName).trimmed();
//: Release build configuration. We recommend not translating it.
- QString defaultSecondName = tr("%1 Release").arg(version->displayName());
+ QString defaultSecondName = tr("%1 Release").arg(version->displayName()).trimmed();
QString customSecondName;
if (buildConfigurationName != version->displayName())
- customSecondName = tr("%1 Release").arg(buildConfigurationName);
+ customSecondName = tr("%1 Release").arg(buildConfigurationName).trimmed();
BuildConfiguration *bc
= Qt4BuildConfiguration::setup(parent, defaultFirstName, customFirstName,
version->defaultBuildConfig(), QString(), QString(), false);
parent->addBuildConfiguration(
Qt4BuildConfiguration::setup(parent, defaultSecondName, customSecondName,
- (version->defaultBuildConfig() ^ QtSupport::BaseQtVersion::DebugBuild),
+ (version->defaultBuildConfig() ^ BaseQtVersion::DebugBuild),
QString(), QString(), false));
return bc;
}
-bool Qt4BuildConfigurationFactory::canClone(const Target *parent, ProjectExplorer::BuildConfiguration *source) const
+bool Qt4BuildConfigurationFactory::canClone(const Target *parent, BuildConfiguration *source) const
{
return canHandle(parent) && qobject_cast<Qt4BuildConfiguration *>(source);
}
@@ -666,20 +670,20 @@ BuildConfiguration *Qt4BuildConfigurationFactory::restore(Target *parent, const
return 0;
}
-QList<BuildConfigurationInfo> Qt4BuildConfigurationFactory::availableBuildConfigurations(const ProjectExplorer::Kit *k,
+QList<BuildConfigurationInfo> Qt4BuildConfigurationFactory::availableBuildConfigurations(const Kit *k,
const QString &proFilePath)
{
QList<BuildConfigurationInfo> infoList;
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
+ BaseQtVersion *version = QtKitInformation::qtVersion(k);
if (!version || !version->isValid())
return infoList;
- QtSupport::BaseQtVersion::QmakeBuildConfigs config = version->defaultBuildConfig() | QtSupport::BaseQtVersion::DebugBuild;
+ BaseQtVersion::QmakeBuildConfigs config = version->defaultBuildConfig() | QtSupport::BaseQtVersion::DebugBuild;
BuildConfigurationInfo info = BuildConfigurationInfo(config, QString(), QString(), false);
info.directory = Qt4Project::shadowBuildDirectory(proFilePath, k, buildConfigurationDisplayName(info));
infoList.append(info);
- info.buildConfig = config ^ QtSupport::BaseQtVersion::DebugBuild;
+ info.buildConfig = config ^ BaseQtVersion::DebugBuild;
info.directory = Qt4Project::shadowBuildDirectory(proFilePath, k, buildConfigurationDisplayName(info));
infoList.append(info);
return infoList;
@@ -688,7 +692,7 @@ QList<BuildConfigurationInfo> Qt4BuildConfigurationFactory::availableBuildConfig
// Return name of a build configuration.
QString Qt4BuildConfigurationFactory::buildConfigurationDisplayName(const BuildConfigurationInfo &info)
{
- return (info.buildConfig & QtSupport::BaseQtVersion::DebugBuild) ?
+ return (info.buildConfig & BaseQtVersion::DebugBuild) ?
//: Name of a debug build configuration to created by a project wizard. We recommend not translating it.
tr("Debug") :
//: Name of a release build configuration to be created by a project wizard. We recommend not translating it.
@@ -697,7 +701,7 @@ QString Qt4BuildConfigurationFactory::buildConfigurationDisplayName(const BuildC
BuildConfiguration::BuildType Qt4BuildConfiguration::buildType() const
{
- if (qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild)
+ if (qmakeBuildConfiguration() & BaseQtVersion::DebugBuild)
return Debug;
else
return Release;
@@ -705,21 +709,19 @@ BuildConfiguration::BuildType Qt4BuildConfiguration::buildType() const
Qt4BuildConfiguration *Qt4BuildConfiguration::setup(Target *t, QString defaultDisplayName,
QString displayName,
- QtSupport::BaseQtVersion::QmakeBuildConfigs qmakeBuildConfiguration,
+ BaseQtVersion::QmakeBuildConfigs qmakeBuildConfiguration,
QString additionalArguments, QString directory,
bool importing)
{
- bool debug = qmakeBuildConfiguration & QtSupport::BaseQtVersion::DebugBuild;
+ bool debug = qmakeBuildConfiguration & BaseQtVersion::DebugBuild;
- // Add the buildconfiguration
+ // Add the build configuration.
Qt4BuildConfiguration *bc = new Qt4BuildConfiguration(t);
bc->setDefaultDisplayName(defaultDisplayName);
bc->setDisplayName(displayName);
- ProjectExplorer::BuildStepList *buildSteps =
- bc->stepList(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_BUILD));
- ProjectExplorer::BuildStepList *cleanSteps =
- bc->stepList(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
+ BuildStepList *buildSteps = bc->stepList(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_BUILD));
+ BuildStepList *cleanSteps = bc->stepList(Core::Id(ProjectExplorer::Constants::BUILDSTEPS_CLEAN));
Q_ASSERT(buildSteps);
Q_ASSERT(cleanSteps);
@@ -729,7 +731,7 @@ Qt4BuildConfiguration *Qt4BuildConfiguration::setup(Target *t, QString defaultDi
MakeStep *makeStep = new MakeStep(buildSteps);
buildSteps->insertStep(1, makeStep);
- MakeStep* cleanStep = new MakeStep(cleanSteps);
+ MakeStep *cleanStep = new MakeStep(cleanSteps);
cleanStep->setClean(true);
cleanStep->setUserArguments(QLatin1String("clean"));
cleanSteps->insertStep(0, cleanStep);
@@ -741,8 +743,8 @@ Qt4BuildConfiguration *Qt4BuildConfiguration::setup(Target *t, QString defaultDi
if (importing)
qmakeStep->setLinkQmlDebuggingLibrary(enableQmlDebugger);
- // set some options for qmake and make
- if (qmakeBuildConfiguration & QtSupport::BaseQtVersion::BuildAll) // debug_and_release => explicit targets
+ // Set some options for qmake and make.
+ if (qmakeBuildConfiguration & BaseQtVersion::BuildAll) // debug_and_release => explicit targets
makeStep->setUserArguments(debug ? QLatin1String("debug") : QLatin1String("release"));
bc->setQMakeBuildConfiguration(qmakeBuildConfiguration);
@@ -752,3 +754,34 @@ Qt4BuildConfiguration *Qt4BuildConfiguration::setup(Target *t, QString defaultDi
return bc;
}
+
+Qt4BuildConfiguration::LastKitState::LastKitState()
+{
+
+}
+
+Qt4BuildConfiguration::LastKitState::LastKitState(Kit *k)
+ : m_qtVersion(QtKitInformation::qtVersionId(k)),
+ m_sysroot(SysRootKitInformation::sysRoot(k).toString()),
+ m_mkspec(QmakeKitInformation::mkspec(k).toString())
+{
+ ToolChain *tc = ToolChainKitInformation::toolChain(k);
+ m_toolchain = tc ? tc->id() : QString();
+}
+
+bool Qt4BuildConfiguration::LastKitState::operator ==(const LastKitState &other)
+{
+ return m_qtVersion == other.m_qtVersion
+ && m_toolchain == other.m_toolchain
+ && m_sysroot == other.m_sysroot
+ && m_mkspec == other.m_mkspec;
+}
+
+bool Qt4BuildConfiguration::LastKitState::operator !=(const LastKitState &other)
+{
+ return !operator ==(other);
+}
+
+
+
+} // namespace Qt4ProjectManager
diff --git a/src/plugins/qt4projectmanager/qt4buildconfiguration.h b/src/plugins/qt4projectmanager/qt4buildconfiguration.h
index a00959c7d9..902b5a0072 100644
--- a/src/plugins/qt4projectmanager/qt4buildconfiguration.h
+++ b/src/plugins/qt4projectmanager/qt4buildconfiguration.h
@@ -55,9 +55,7 @@ public:
explicit Qt4BuildConfiguration(ProjectExplorer::Target *target);
~Qt4BuildConfiguration();
- Utils::Environment baseEnvironment() const;
-
- ProjectExplorer::BuildConfigWidget *createConfigWidget();
+ ProjectExplorer::NamedWidget *createConfigWidget();
QString buildDirectory() const;
bool shadowBuild() const;
QString shadowBuildDirectory() const;
@@ -88,7 +86,6 @@ public:
QMakeStep *qmakeStep() const;
MakeStep *makeStep() const;
- QString defaultMakeTarget() const;
QString makefile() const;
enum MakefileState { MakefileMatches, MakefileForWrongProject, MakefileIncompatible, MakefileMissing };
@@ -100,8 +97,6 @@ public:
QVariantMap toMap() const;
- ProjectExplorer::IOutputParser *createOutputParser() const;
-
virtual bool isEnabled() const;
virtual QString disabledReason() const;
/// \internal For Qt4Project, since that manages the parsing information
@@ -129,6 +124,8 @@ signals:
private slots:
void kitChanged();
+ void toolChainUpdated(ProjectExplorer::ToolChain *tc);
+ void qtVersionsChanged(const QList<int> &, const QList<int> &, const QList<int> &changed);
void emitBuildDirectoryChanged();
protected:
@@ -141,6 +138,21 @@ private:
QString rawBuildDirectory() const;
QString defaultShadowBuildDirectory() const;
+ class LastKitState
+ {
+ public:
+ LastKitState();
+ explicit LastKitState(ProjectExplorer::Kit *k);
+ bool operator ==(const LastKitState &other);
+ bool operator !=(const LastKitState &other);
+ private:
+ int m_qtVersion;
+ QString m_toolchain;
+ QString m_sysroot;
+ QString m_mkspec;
+ };
+ LastKitState m_lastKitState;
+
bool m_shadowBuild;
bool m_isEnabled;
QString m_buildDirectory;
diff --git a/src/plugins/qt4projectmanager/qt4nodes.cpp b/src/plugins/qt4projectmanager/qt4nodes.cpp
index b80c5e343c..011cc56763 100644
--- a/src/plugins/qt4projectmanager/qt4nodes.cpp
+++ b/src/plugins/qt4projectmanager/qt4nodes.cpp
@@ -57,6 +57,7 @@
#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtsupportconstants.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <utils/fileutils.h>
@@ -100,7 +101,7 @@ static const FileTypeDataStorage fileTypeDataStorage[] = {
":/qt4projectmanager/images/qt_qrc.png" },
{ ProjectExplorer::QMLType,
QT_TRANSLATE_NOOP("Qt4ProjectManager::Qt4PriFileNode", "QML"),
- ":/qt4projectmanager/images/qml.ico" },
+ ":/qt4projectmanager/images/qml.png" },
{ ProjectExplorer::UnknownFileType,
QT_TRANSLATE_NOOP("Qt4ProjectManager::Qt4PriFileNode", "Other files"),
":/qt4projectmanager/images/unknown.png" }
@@ -337,10 +338,8 @@ struct InternalNode
fileWithoutPrefix = file;
}
QStringList parts = fileWithoutPrefix.toString().split(separator, QString::SkipEmptyParts);
-#ifndef Q_OS_WIN
- if (!isRelative && parts.count() > 0)
+ if (!Utils::HostOsInfo::isWindowsHost() && !isRelative && parts.count() > 0)
parts[0].prepend(separator);
-#endif
QStringListIterator it(parts);
InternalNode *currentNode = this;
QString path = (isRelative ? (projectDirFileName.toString() + QLatin1Char('/')) : QString());
@@ -542,29 +541,26 @@ struct InternalNode
};
}
-QStringList Qt4PriFileNode::baseVPaths(QtSupport::ProFileReader *reader, const QString &projectDir) const
+QStringList Qt4PriFileNode::baseVPaths(QtSupport::ProFileReader *reader, const QString &projectDir, const QString &buildDir) const
{
QStringList result;
if (!reader)
return result;
result += reader->absolutePathValues(QLatin1String("VPATH"), projectDir);
result << projectDir; // QMAKE_ABSOLUTE_SOURCE_PATH
- result += reader->absolutePathValues(QLatin1String("DEPENDPATH"), projectDir);
+ result << buildDir;
result.removeDuplicates();
return result;
}
QStringList Qt4PriFileNode::fullVPaths(const QStringList &baseVPaths, QtSupport::ProFileReader *reader,
- FileType type, const QString &qmakeVariable, const QString &projectDir) const
+ const QString &qmakeVariable, const QString &projectDir) const
{
QStringList vPaths;
if (!reader)
return vPaths;
- if (type == ProjectExplorer::SourceType)
- vPaths = reader->absolutePathValues(QLatin1String("VPATH_") + qmakeVariable, projectDir);
+ vPaths = reader->absolutePathValues(QLatin1String("VPATH_") + qmakeVariable, projectDir);
vPaths += baseVPaths;
- if (type == ProjectExplorer::HeaderType)
- vPaths += reader->absolutePathValues(QLatin1String("INCLUDEPATH"), projectDir);
vPaths.removeDuplicates();
return vPaths;
}
@@ -653,10 +649,10 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
QStringList baseVPathsExact;
if (includeFileExact)
- baseVPathsExact = baseVPaths(readerExact, projectDir);
+ baseVPathsExact = baseVPaths(readerExact, projectDir, m_qt4ProFileNode->buildDir());
QStringList baseVPathsCumulative;
if (includeFileCumlative)
- baseVPathsCumulative = baseVPaths(readerCumulative, projectDir);
+ baseVPathsCumulative = baseVPaths(readerCumulative, projectDir, m_qt4ProFileNode->buildDir());
const QVector<Qt4NodeStaticData::FileTypeData> &fileTypes = qt4NodeStaticData()->fileTypeData;
@@ -668,13 +664,13 @@ void Qt4PriFileNode::update(ProFile *includeFileExact, QtSupport::ProFileReader
QSet<Utils::FileName> newFilePaths;
foreach (const QString &qmakeVariable, qmakeVariables) {
if (includeFileExact) {
- QStringList vPathsExact = fullVPaths(baseVPathsExact, readerExact, type, qmakeVariable, projectDir);
+ QStringList vPathsExact = fullVPaths(baseVPathsExact, readerExact, qmakeVariable, projectDir);
QStringList tmp = readerExact->absoluteFileValues(qmakeVariable, projectDir, vPathsExact, includeFileExact);
foreach (const QString &t, tmp)
newFilePaths += Utils::FileName::fromString(t);
}
if (includeFileCumlative) {
- QStringList vPathsCumulative = fullVPaths(baseVPathsCumulative, readerCumulative, type, qmakeVariable, projectDir);
+ QStringList vPathsCumulative = fullVPaths(baseVPathsCumulative, readerCumulative, qmakeVariable, projectDir);
QStringList tmp = readerCumulative->absoluteFileValues(qmakeVariable, projectDir, vPathsCumulative, includeFileCumlative);
foreach (const QString &t, tmp)
newFilePaths += Utils::FileName::fromString(t);
@@ -860,11 +856,10 @@ QList<ProjectNode::ProjectAction> Qt4PriFileNode::supportedActions(Node *node) c
// work on a subset of the file types according to project type.
actions << AddNewFile;
- if (m_recursiveEnumerateFiles.contains(Utils::FileName::fromString(node->path()))) {
+ if (m_recursiveEnumerateFiles.contains(Utils::FileName::fromString(node->path())))
actions << EraseFile;
- } else {
+ else
actions << RemoveFile;
- }
bool addExistingFiles = true;
if (node->nodeType() == ProjectExplorer::VirtualFolderNodeType) {
@@ -1311,7 +1306,7 @@ QSet<Utils::FileName> Qt4PriFileNode::filterFilesRecursiveEnumerata(ProjectExplo
QSet<Utils::FileName> result;
if (fileType != ProjectExplorer::QMLType && fileType != ProjectExplorer::UnknownFileType)
return result;
- if(fileType == ProjectExplorer::QMLType) {
+ if (fileType == ProjectExplorer::QMLType) {
foreach (const Utils::FileName &file, files)
if (file.endsWith(QLatin1String(".qml")))
result << file;
@@ -1391,28 +1386,19 @@ TargetInformation Qt4ProFileNode::targetInformation(const QString &fileName) con
QString Qt4ProFileNode::makefile() const
{
- if (m_varValues[Makefile].isEmpty())
- return QString();
- return m_varValues[Makefile].first();
+ return singleVariableValue(Makefile);
}
QString Qt4ProFileNode::objectExtension() const
{
- if (m_varValues[ObjectExt].isEmpty()) {
-#ifdef Q_OS_WIN
- return QLatin1String(".obj");
-#else
- return QLatin1String(".o");
-#endif
- }
+ if (m_varValues[ObjectExt].isEmpty())
+ return Utils::HostOsInfo::isWindowsHost() ? QLatin1String(".obj") : QLatin1String(".o");
return m_varValues[ObjectExt].first();
}
QString Qt4ProFileNode::objectsDirectory() const
{
- if (m_varValues[ObjectsDir].isEmpty())
- return QString();
- return m_varValues[ObjectsDir].first();
+ return singleVariableValue(ObjectsDir);
}
QByteArray Qt4ProFileNode::cxxDefines() const
@@ -1494,10 +1480,9 @@ bool Qt4ProFileNode::isParent(Qt4ProFileNode *node)
void Qt4ProFileNode::buildStateChanged(ProjectExplorer::Project *project)
{
- if (project == m_project && !ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager()->isBuilding(m_project)) {
- QStringList filesToUpdate = updateUiFiles();
- updateCodeModelSupportFromBuild(filesToUpdate);
- }
+ if (project == m_project
+ && !ProjectExplorer::ProjectExplorerPlugin::instance()->buildManager()->isBuilding(m_project))
+ updateCodeModelSupportFromBuild();
}
bool Qt4ProFileNode::hasBuildTargets() const
@@ -1532,16 +1517,20 @@ QString Qt4ProFileNode::singleVariableValue(const Qt4Variable var) const
return values.isEmpty() ? QString() : values.first();
}
+QStringList Qt4ProFileNode::uiFiles() const
+{
+ return m_uiHeaderFiles;
+}
+
void Qt4ProFileNode::emitProFileUpdatedRecursive()
{
foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
if (Internal::Qt4NodesWatcher *qt4Watcher = qobject_cast<Internal::Qt4NodesWatcher*>(watcher))
- emit qt4Watcher->kitUpdated(this, m_validParse, m_parseInProgress);
+ emit qt4Watcher->proFileUpdated(this, m_validParse, m_parseInProgress);
foreach (ProjectNode *subNode, subProjectNodes()) {
- if (Qt4ProFileNode *node = qobject_cast<Qt4ProFileNode *>(subNode)) {
+ if (Qt4ProFileNode *node = qobject_cast<Qt4ProFileNode *>(subNode))
node->emitProFileUpdatedRecursive();
- }
}
}
@@ -1549,9 +1538,8 @@ void Qt4ProFileNode::setParseInProgressRecursive(bool b)
{
setParseInProgress(b);
foreach (ProjectNode *subNode, subProjectNodes()) {
- if (Qt4ProFileNode *node = qobject_cast<Qt4ProFileNode *>(subNode)) {
+ if (Qt4ProFileNode *node = qobject_cast<Qt4ProFileNode *>(subNode))
node->setParseInProgressRecursive(b);
- }
}
}
@@ -1562,16 +1550,15 @@ void Qt4ProFileNode::setParseInProgress(bool b)
m_parseInProgress = b;
foreach (ProjectExplorer::NodesWatcher *watcher, watchers())
if (Internal::Qt4NodesWatcher *qt4Watcher = qobject_cast<Internal::Qt4NodesWatcher*>(watcher))
- emit qt4Watcher->kitUpdated(this, m_validParse, m_parseInProgress);
+ emit qt4Watcher->proFileUpdated(this, m_validParse, m_parseInProgress);
}
void Qt4ProFileNode::setValidParseRecursive(bool b)
{
setValidParse(b);
foreach (ProjectNode *subNode, subProjectNodes()) {
- if (Qt4ProFileNode *node = qobject_cast<Qt4ProFileNode *>(subNode)) {
+ if (Qt4ProFileNode *node = qobject_cast<Qt4ProFileNode *>(subNode))
node->setValidParseRecursive(b);
- }
}
}
@@ -1803,7 +1790,7 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
// Remove case
toRemove << *existingIt;
++existingIt;
- } else if(! newExactAtEnd
+ } else if (! newExactAtEnd
&& (existingAtEnd || *newExactIt < (*existingIt)->path())
&& (newCumlativeAtEnd || *newExactIt < *newCumlativeIt)) {
// Mark node from exact for adding
@@ -1830,7 +1817,7 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
++newCumlativeIt;
} else if (newCumlativeAtEnd) {
++newExactIt;
- } else if(*newExactIt < *newCumlativeIt) {
+ } else if (*newExactIt < *newCumlativeIt) {
++newExactIt;
} else if (*newCumlativeIt < *newExactIt) {
++newCumlativeIt;
@@ -1919,23 +1906,20 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
m_subProjectsNotToDeploy = subProjectsNotToDeploy;
setupInstallsList(m_readerExact);
- setupProjectVersion(m_readerExact);
+ QString buildDirectory = buildDir();
// update other variables
QHash<Qt4Variable, QStringList> newVarValues;
newVarValues[DefinesVar] = m_readerExact->values(QLatin1String("DEFINES"));
newVarValues[IncludePathVar] = includePaths(m_readerExact);
- newVarValues[CppFlagsVar] = m_readerExact->values("QMAKE_CXXFLAGS");
+ newVarValues[CppFlagsVar] = m_readerExact->values(QLatin1String("QMAKE_CXXFLAGS"));
newVarValues[CppHeaderVar] = fileListForVar(m_readerExact, m_readerCumulative,
- QLatin1String("HEADERS"), m_projectDir,
- ProjectExplorer::HeaderType);
+ QLatin1String("HEADERS"), m_projectDir, buildDirectory);
newVarValues[CppSourceVar] = fileListForVar(m_readerExact, m_readerCumulative,
- QLatin1String("SOURCES"), m_projectDir,
- ProjectExplorer::SourceType);
+ QLatin1String("SOURCES"), m_projectDir, buildDirectory);
newVarValues[ObjCSourceVar] = fileListForVar(m_readerExact, m_readerCumulative,
- QLatin1String("OBJECTIVE_SOURCES"), m_projectDir,
- ProjectExplorer::SourceType);
+ QLatin1String("OBJECTIVE_SOURCES"), m_projectDir, buildDirectory);
newVarValues[UiDirVar] = QStringList() << uiDirPath(m_readerExact);
newVarValues[MocDirVar] = QStringList() << mocDirPath(m_readerExact);
newVarValues[PkgConfigVar] = m_readerExact->values(QLatin1String("PKGCONFIG"));
@@ -1955,8 +1939,8 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
newVarValues[VersionVar] = m_readerExact->values(QLatin1String("VERSION"));
newVarValues[TargetVersionExtVar]
= m_readerExact->values(QLatin1String("TARGET_VERSION_EXT"));
- newVarValues[StaticLibExtensionVar] = m_readerExact->values("QMAKE_EXTENSION_STATICLIB");
- newVarValues[ShLibExtensionVar] = m_readerExact->values("QMAKE_EXTENSION_SHLIB");
+ newVarValues[StaticLibExtensionVar] = m_readerExact->values(QLatin1String("QMAKE_EXTENSION_STATICLIB"));
+ newVarValues[ShLibExtensionVar] = m_readerExact->values(QLatin1String("QMAKE_EXTENSION_SHLIB"));
m_isDeployable = false;
if (m_projectType == ApplicationTemplate) {
@@ -1983,7 +1967,6 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
setParseInProgress(false);
createUiCodeModelSupport();
- updateUiFiles();
m_project->destroyProFileReader(m_readerExact);
m_project->destroyProFileReader(m_readerCumulative);
@@ -1993,10 +1976,10 @@ void Qt4ProFileNode::applyEvaluate(EvalResult evalResult, bool async)
}
QStringList Qt4ProFileNode::fileListForVar(QtSupport::ProFileReader *readerExact, QtSupport::ProFileReader *readerCumulative,
- const QString &varName, const QString &projectDir, FileType type) const
+ const QString &varName, const QString &projectDir, const QString &buildDir) const
{
- QStringList baseVPathsExact = baseVPaths(readerExact, projectDir);
- QStringList vPathsExact = fullVPaths(baseVPathsExact, readerExact, type, varName, projectDir);
+ QStringList baseVPathsExact = baseVPaths(readerExact, projectDir, buildDir);
+ QStringList vPathsExact = fullVPaths(baseVPathsExact, readerExact, varName, projectDir);
QStringList result;
result = readerExact->absoluteFileValues(varName,
@@ -2004,8 +1987,8 @@ QStringList Qt4ProFileNode::fileListForVar(QtSupport::ProFileReader *readerExact
vPathsExact,
0);
if (readerCumulative) {
- QStringList baseVPathsCumulative = baseVPaths(readerCumulative, projectDir);
- QStringList vPathsCumulative = fullVPaths(baseVPathsCumulative, readerCumulative, type, varName, projectDir);
+ QStringList baseVPathsCumulative = baseVPaths(readerCumulative, projectDir, buildDir);
+ QStringList vPathsCumulative = fullVPaths(baseVPathsCumulative, readerCumulative, varName, projectDir);
result += readerCumulative->absoluteFileValues(varName,
projectDir,
vPathsCumulative,
@@ -2015,114 +1998,6 @@ QStringList Qt4ProFileNode::fileListForVar(QtSupport::ProFileReader *readerExact
return result;
}
-// This function is triggered after a build, and updates the state ui files
-// It does so by storing a modification time for each ui file we know about.
-QStringList Qt4ProFileNode::updateUiFiles()
-{
-// qDebug()<<"Qt4ProFileNode::updateUiFiles()";
- // Only those two project types can have ui files for us
- if (m_projectType != ApplicationTemplate
- && m_projectType != LibraryTemplate)
- return QStringList();
-
- // Find all ui files
- FindUiFileNodesVisitor uiFilesVisitor;
- this->accept(&uiFilesVisitor);
- const QList<ProjectExplorer::FileNode*> uiFiles = uiFilesVisitor.uiFileNodes;
-
- // Find the UiDir, there can only ever be one
- QString uiDir = buildDir();
- QStringList tmp = m_varValues[UiDirVar];
- if (tmp.size() != 0)
- uiDir = tmp.first();
-
- // Collect all existing generated files
- QList<ProjectExplorer::FileNode*> existingFileNodes;
- foreach (ProjectExplorer::FileNode *file, fileNodes()) {
- if (file->isGenerated())
- existingFileNodes << file;
- }
-
- // Convert uiFile to uiHeaderFilePath, find all headers that correspond
- // and try to find them in uiDir
- QStringList newFilePaths;
- foreach (ProjectExplorer::FileNode *uiFile, uiFiles) {
- const QString uiHeaderFilePath
- = QString::fromLatin1("%1/ui_%2.h").arg(uiDir, QFileInfo(uiFile->path()).completeBaseName());
- if (QFileInfo(uiHeaderFilePath).exists())
- newFilePaths << uiHeaderFilePath;
- }
-
- // Create a diff between those lists
- QList<ProjectExplorer::FileNode*> toRemove;
- QList<ProjectExplorer::FileNode*> toAdd;
- // The list of files for which we call updateSourceFile
- QStringList toUpdate;
-
- qSort(newFilePaths);
- qSort(existingFileNodes.begin(), existingFileNodes.end(), sortNodesByPath);
-
- QList<ProjectExplorer::FileNode*>::const_iterator existingNodeIter = existingFileNodes.constBegin();
- QList<QString>::const_iterator newPathIter = newFilePaths.constBegin();
- while (existingNodeIter != existingFileNodes.constEnd()
- && newPathIter != newFilePaths.constEnd()) {
- if ((*existingNodeIter)->path() < *newPathIter) {
- toRemove << *existingNodeIter;
- ++existingNodeIter;
- } else if ((*existingNodeIter)->path() > *newPathIter) {
- toAdd << new ProjectExplorer::FileNode(*newPathIter, ProjectExplorer::HeaderType, true);
- ++newPathIter;
- } else { // *existingNodeIter->path() == *newPathIter
- QString fileName = (*existingNodeIter)->path();
- QMap<QString, QDateTime>::const_iterator it = m_uitimestamps.find(fileName);
- QDateTime lastModified = QFileInfo(fileName).lastModified();
- if (it == m_uitimestamps.constEnd() || it.value() < lastModified) {
- toUpdate << fileName;
- m_uitimestamps[fileName] = lastModified;
- }
- ++existingNodeIter;
- ++newPathIter;
- }
- }
- while (existingNodeIter != existingFileNodes.constEnd()) {
- toRemove << *existingNodeIter;
- ++existingNodeIter;
- }
- while (newPathIter != newFilePaths.constEnd()) {
- toAdd << new ProjectExplorer::FileNode(*newPathIter, ProjectExplorer::HeaderType, true);
- ++newPathIter;
- }
-
- // Update project tree
- if (!toRemove.isEmpty()) {
- foreach (ProjectExplorer::FileNode *file, toRemove)
- m_uitimestamps.remove(file->path());
- removeFileNodes(toRemove, this);
- }
-
- CPlusPlus::CppModelManagerInterface *modelManager =
- CPlusPlus::CppModelManagerInterface::instance();
-
- if (!toAdd.isEmpty()) {
- foreach (ProjectExplorer::FileNode *file, toAdd) {
- m_uitimestamps.insert(file->path(), QFileInfo(file->path()).lastModified());
- toUpdate << file->path();
-
- // Also adding files depending on that
- // We only need to do that for files that were newly created
- QString fileName = QFileInfo(file->path()).fileName();
- foreach (CPlusPlus::Document::Ptr doc, modelManager->snapshot()) {
- if (doc->includedFiles().contains(fileName)) {
- if (!toUpdate.contains(doc->fileName()))
- toUpdate << doc->fileName();
- }
- }
- }
- addFileNodes(toAdd, this);
- }
- return toUpdate;
-}
-
QString Qt4ProFileNode::uiDirPath(QtSupport::ProFileReader *reader) const
{
QString path = reader->value(QLatin1String("UI_DIR"));
@@ -2163,9 +2038,8 @@ QStringList Qt4ProFileNode::libDirectories(QtSupport::ProFileReader *reader) con
{
QStringList result;
foreach (const QString &str, reader->values(QLatin1String("LIBS"))) {
- if (str.startsWith(QLatin1String("-L"))) {
+ if (str.startsWith(QLatin1String("-L")))
result.append(str.mid(2));
- }
}
return result;
}
@@ -2199,11 +2073,10 @@ QStringList Qt4ProFileNode::subDirsPaths(QtSupport::ProFileReader *reader, QStri
realDir = info.filePath();
QString realFile;
- if (info.isDir()) {
+ if (info.isDir())
realFile = QString::fromLatin1("%1/%2.pro").arg(realDir, info.fileName());
- } else {
+ else
realFile = realDir;
- }
if (QFile::exists(realFile)) {
realFile = QDir::cleanPath(realFile);
@@ -2229,65 +2102,89 @@ TargetInformation Qt4ProFileNode::targetInformation(QtSupport::ProFileReader *re
if (!reader)
return result;
+ QtSupport::ProFileReader *readerBP = 0;
+ QStringList builds = reader->values(QLatin1String("BUILDS"));
+ QString buildTarget;
+ if (!builds.isEmpty()) {
+ QString build = builds.first();
+ buildTarget = reader->value(build + QLatin1String(".target"));
+
+ QHash<QString, QStringList> basevars;
+ QStringList basecfgs = reader->values(build + QLatin1String(".CONFIG"));
+ basecfgs += build;
+ basecfgs += QLatin1String("build_pass");
+ basevars[QLatin1String("BUILD_PASS")] = QStringList(build);
+ QStringList buildname = reader->values(build + QLatin1String(".name"));
+ basevars[QLatin1String("BUILD_NAME")] = (buildname.isEmpty() ? QStringList(build) : buildname);
+
+ readerBP = m_project->createProFileReader(this);
+ readerBP->setExtraVars(basevars);
+ readerBP->setExtraConfigs(basecfgs);
+
+ EvalResult evalResult = EvalOk;
+ if (ProFile *pro = readerBP->parsedProFile(m_projectFilePath)) {
+ if (!readerBP->accept(pro, QMakeEvaluator::LoadAll))
+ evalResult = EvalPartial;
+ pro->deref();
+ } else {
+ evalResult = EvalFail;
+ }
+
+ if (evalResult != EvalOk)
+ return result;
+
+ reader = readerBP;
+ }
+
+ // BUILD DIR
result.buildDir = buildDir();
const QString baseDir = result.buildDir;
// qDebug() << "base build dir is:"<<baseDir;
- // Working Directory
- const QString destDir = QLatin1String("DESTDIR");
- if (reader->contains(destDir)) {
- //qDebug() << "reader contains destdir:" << reader->value("DESTDIR");
- result.workingDir = reader->value(destDir);
- if (QDir::isRelativePath(result.workingDir)) {
- result.workingDir = baseDir + QLatin1Char('/') + result.workingDir;
- //qDebug() << "was relative and expanded to" << result.workingDir;
- }
+ QString destDir;
+ if (reader->contains(QLatin1String("DESTDIR"))) {
+ destDir = reader->value(QLatin1String("DESTDIR"));
+ bool workingDirIsBaseDir = false;
+ if (destDir == buildTarget) // special case for "debug" or "release"
+ workingDirIsBaseDir = true;
+
+ if (QDir::isRelativePath(destDir))
+ destDir = baseDir + QLatin1Char('/') + destDir;
+
+ if (workingDirIsBaseDir)
+ result.workingDir = baseDir;
+ else
+ result.workingDir = destDir;
} else {
- //qDebug() << "reader didn't contain DESTDIR, setting to " << baseDir;
+ destDir = baseDir;
result.workingDir = baseDir;
}
+ // Target
result.target = reader->value(QLatin1String("TARGET"));
if (result.target.isEmpty())
result.target = QFileInfo(m_projectFilePath).baseName();
-#if defined (Q_OS_MAC)
- if (reader->values(QLatin1String("CONFIG")).contains(QLatin1String("app_bundle"))) {
- result.workingDir += QLatin1Char('/')
- + result.target
- + QLatin1String(".app/Contents/MacOS");
+ if (Utils::HostOsInfo::isMacHost()
+ && reader->values(QLatin1String("CONFIG")).contains(QLatin1String("app_bundle"))) {
+ const QString infix = QLatin1Char('/') + result.target
+ + QLatin1String(".app/Contents/MacOS");
+ result.workingDir += infix;
+ destDir += infix;
}
-#endif
result.workingDir = QDir::cleanPath(result.workingDir);
- QString wd = result.workingDir;
- if ( (!reader->contains(destDir) || reader->value(destDir) == QLatin1String("."))) {
- const QStringList configValues = reader->values(QLatin1String("CONFIG"));
- if (configValues.contains(QLatin1String("debug_and_release"))
- && configValues.contains(QLatin1String("debug_and_release_target"))) {
- // If we don't have a destdir and debug and release is set
- // then the executable is in a debug/release folder
- //qDebug() << "reader has debug_and_release_target";
-
- // Hmm can we find out whether it's debug or release in a saner way?
- // Theoretically it's in CONFIG
- QString qmakeBuildConfig = QLatin1String("release");
- ProjectExplorer::Target *target = m_project->activeTarget();
- Qt4BuildConfiguration *bc = target ? qobject_cast<Qt4BuildConfiguration *>(target->activeBuildConfiguration()) : 0;
- if (!target || !bc || bc->qmakeBuildConfiguration() & QtSupport::BaseQtVersion::DebugBuild)
- qmakeBuildConfig = QLatin1String("debug");
- wd += QLatin1Char('/') + qmakeBuildConfig;
- }
- }
-
- result.executable = QDir::cleanPath(wd + QLatin1Char('/') + result.target);
+ /// should this really be in this method?
+ result.executable = QDir::cleanPath(destDir + QLatin1Char('/') + result.target);
//qDebug() << "##### updateTarget sets:" << result.workingDir << result.executable;
-#if defined (Q_OS_WIN)
- result.executable += QLatin1String(".exe");
-#endif
+ Utils::HostOsInfo::appendExecutableSuffix(result.executable);
result.valid = true;
+
+ if (readerBP)
+ m_project->destroyProFileReader(readerBP);
+
return result;
}
@@ -2344,59 +2241,6 @@ void Qt4ProFileNode::setupInstallsList(const QtSupport::ProFileReader *reader)
}
}
-void Qt4ProFileNode::setupProjectVersion(const QtSupport::ProFileReader *reader)
-{
- m_projectVersion.major = m_projectVersion.minor = m_projectVersion.patch = -1;
- bool ok;
- int val = reader->value(QLatin1String("VER_MAJ")).toInt(&ok);
- if (ok)
- m_projectVersion.major = val;
- val = reader->value(QLatin1String("VER_MIN")).toInt(&ok);
- if (ok)
- m_projectVersion.minor = val;
- val = reader->value(QLatin1String("VER_PAT")).toInt(&ok);
- if (ok)
- m_projectVersion.patch = val;
- if (m_projectVersion.major != -1 && m_projectVersion.minor != -1
- && m_projectVersion.patch != -1) {
- return;
- }
-
- const QString &version = reader->value(QLatin1String("VERSION"));
- const QChar dot(QLatin1Char('.'));
- int dotIndex = version.indexOf(dot);
- if (m_projectVersion.major == -1) {
- val = version.left(dotIndex).toInt(&ok);
- if (ok)
- m_projectVersion.major = val;
- }
- if (dotIndex != -1) {
- int numberStartIndex = dotIndex + 1;
- dotIndex = version.indexOf(dot, numberStartIndex);
- if (m_projectVersion.minor == -1) {
- val = version.mid(numberStartIndex, dotIndex - numberStartIndex).toInt(&ok);
- if (ok)
- m_projectVersion.minor = val;
- }
- }
- if (dotIndex != -1) {
- int numberStartIndex = dotIndex + 1;
- dotIndex = version.indexOf(dot, numberStartIndex);
- if (m_projectVersion.patch == -1) {
- val = version.mid(numberStartIndex, dotIndex - numberStartIndex).toInt(&ok);
- if (ok)
- m_projectVersion.patch= val;
- }
- }
-
- if (m_projectVersion.major == -1)
- m_projectVersion.major = 1;
- if (m_projectVersion.minor == -1)
- m_projectVersion.minor = 0;
- if (m_projectVersion.patch == -1)
- m_projectVersion.patch = 0;
-}
-
InstallsList Qt4ProFileNode::installsList() const
{
return m_installsList;
@@ -2418,16 +2262,12 @@ QString Qt4ProFileNode::buildDir(Qt4BuildConfiguration *bc) const
return QDir(bc->buildDirectory()).absoluteFilePath(relativeDir);
}
-void Qt4ProFileNode::updateCodeModelSupportFromBuild(const QStringList &files)
+void Qt4ProFileNode::updateCodeModelSupportFromBuild()
{
- foreach (const QString &file, files) {
- QMap<QString, Internal::Qt4UiCodeModelSupport *>::const_iterator it, end;
- end = m_uiCodeModelSupport.constEnd();
- for (it = m_uiCodeModelSupport.constBegin(); it != end; ++it) {
- if (it.value()->fileName() == file)
- it.value()->updateFromBuild();
- }
- }
+ QMap<QString, Internal::Qt4UiCodeModelSupport *>::const_iterator it, end;
+ end = m_uiCodeModelSupport.constEnd();
+ for (it = m_uiCodeModelSupport.constBegin(); it != end; ++it)
+ it.value()->updateFromBuild();
}
void Qt4ProFileNode::updateCodeModelSupportFromEditor(const QString &uiFileName,
@@ -2470,6 +2310,8 @@ void Qt4ProFileNode::createUiCodeModelSupport()
oldCodeModelSupport = m_uiCodeModelSupport;
m_uiCodeModelSupport.clear();
+ m_uiHeaderFiles.clear();
+
// Only those two project types can have ui files for us
if (m_projectType == ApplicationTemplate || m_projectType == LibraryTemplate) {
// Find all ui files
@@ -2481,6 +2323,7 @@ void Qt4ProFileNode::createUiCodeModelSupport()
const QString uiDir = uiDirectory();
foreach (const ProjectExplorer::FileNode *uiFile, uiFiles) {
const QString uiHeaderFilePath = uiHeaderFile(uiDir, uiFile->path());
+ m_uiHeaderFiles << uiHeaderFilePath;
// qDebug()<<"code model support for "<<uiFile->path()<<" "<<uiHeaderFilePath;
QMap<QString, Internal::Qt4UiCodeModelSupport *>::iterator it = oldCodeModelSupport.find(uiFile->path());
if (it != oldCodeModelSupport.end()) {
diff --git a/src/plugins/qt4projectmanager/qt4nodes.h b/src/plugins/qt4projectmanager/qt4nodes.h
index e5c228e15c..67d8b96246 100644
--- a/src/plugins/qt4projectmanager/qt4nodes.h
+++ b/src/plugins/qt4projectmanager/qt4nodes.h
@@ -191,9 +191,8 @@ private:
bool priFileWritable(const QString &path);
bool saveModifiedEditors();
QStringList formResources(const QString &formFile) const;
- QStringList baseVPaths(QtSupport::ProFileReader *reader, const QString &projectDir) const;
- QStringList fullVPaths(const QStringList &baseVPaths, QtSupport::ProFileReader *reader,
- FileType type, const QString &qmakeVariable, const QString &projectDir) const;
+ QStringList baseVPaths(QtSupport::ProFileReader *reader, const QString &projectDir, const QString &buildDir) const;
+ QStringList fullVPaths(const QStringList &baseVPaths, QtSupport::ProFileReader *reader, const QString &qmakeVariable, const QString &projectDir) const;
void watchFolders(const QSet<QString> &folders);
Qt4Project *m_project;
@@ -257,7 +256,7 @@ signals:
const QHash<Qt4Variable, QStringList> &oldValues,
const QHash<Qt4Variable, QStringList> &newValues);
- void kitUpdated(Qt4ProjectManager::Qt4ProFileNode *projectNode, bool success, bool parseInProgress);
+ void proFileUpdated(Qt4ProjectManager::Qt4ProFileNode *projectNode, bool success, bool parseInProgress);
private:
// let them emit signals
@@ -367,7 +366,7 @@ public:
return !m_subProjectsNotToDeploy.contains(filePath);
}
- void updateCodeModelSupportFromBuild(const QStringList &files);
+ void updateCodeModelSupportFromBuild();
void updateCodeModelSupportFromEditor(const QString &uiFileName, const QString &contents);
QString sourceDir() const;
@@ -375,13 +374,13 @@ public:
QString uiDirectory() const;
static QString uiHeaderFile(const QString &uiDir, const QString &formFile);
+ QStringList uiFiles() const;
const Qt4ProFileNode *findProFileFor(const QString &string) const;
TargetInformation targetInformation(const QString &fileName) const;
TargetInformation targetInformation() const;
InstallsList installsList() const;
- ProjectVersion projectVersion() const { return m_projectVersion; }
QString makefile() const;
QString objectExtension() const;
@@ -422,10 +421,9 @@ private:
typedef QHash<Qt4Variable, QStringList> Qt4VariablesHash;
void createUiCodeModelSupport();
- QStringList updateUiFiles();
QStringList fileListForVar(QtSupport::ProFileReader *readerExact, QtSupport::ProFileReader *readerCumulative,
- const QString &varName, const QString &projectDir, FileType type) const;
+ const QString &varName, const QString &projectDir, const QString &buildDir) const;
QString uiDirPath(QtSupport::ProFileReader *reader) const;
QString mocDirPath(QtSupport::ProFileReader *reader) const;
QStringList includePaths(QtSupport::ProFileReader *reader) const;
@@ -434,7 +432,6 @@ private:
TargetInformation targetInformation(QtSupport::ProFileReader *reader) const;
void setupInstallsList(const QtSupport::ProFileReader *reader);
- void setupProjectVersion(const QtSupport::ProFileReader *reader);
Qt4ProjectType m_projectType;
Qt4VariablesHash m_varValues;
@@ -445,12 +442,13 @@ private:
QString m_resolvedMkspecPath;
QStringList m_subProjectsNotToDeploy;
InstallsList m_installsList;
- ProjectVersion m_projectVersion;
friend class Qt4NodeHierarchy;
bool m_validParse;
bool m_parseInProgress;
+ QStringList m_uiHeaderFiles;
+
// Async stuff
QFutureWatcher<EvalResult> m_parseFutureWatcher;
QtSupport::ProFileReader *m_readerExact;
diff --git a/src/plugins/qt4projectmanager/qt4project.cpp b/src/plugins/qt4projectmanager/qt4project.cpp
index 66c539896a..1945f54ebc 100644
--- a/src/plugins/qt4projectmanager/qt4project.cpp
+++ b/src/plugins/qt4projectmanager/qt4project.cpp
@@ -46,6 +46,8 @@
#include <coreplugin/messagemanager.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/progressmanager/progressmanager.h>
+#include <coreplugin/documentmanager.h>
+#include <coreplugin/variablemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <cpptools/ModelManagerInterface.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
@@ -54,10 +56,10 @@
#include <projectexplorer/toolchain.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/target.h>
-#include <projectexplorer/buildenvironmentwidget.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/projectmacroexpander.h>
#include <utils/qtcassert.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <qtsupport/qmldumptool.h>
@@ -67,6 +69,7 @@
#include <qtsupport/qtsupportconstants.h>
#include <qtsupport/qtversionmanager.h>
#include <utils/QtConcurrentTools>
+#include <utils/stringutils.h>
#include <QDebug>
#include <QDir>
@@ -97,24 +100,6 @@ Qt4BuildConfiguration *enableActiveQt4BuildConfiguration(ProjectExplorer::Target
return bc;
}
-QString sanitize(const QString &input)
-{
- QString result;
- result.reserve(input.size());
- foreach (const QChar &qc, input) {
- const char c = qc.toLatin1();
- if ((c >= 'a' && c <='z')
- || (c >= 'A' && c <= 'Z')
- || (c >= '0' && c <= '9')
- || c == '-'
- || c == '_')
- result.append(qc);
- else
- result.append(QLatin1Char('_'));
- }
- return result;
-}
-
} // namespace
namespace Qt4ProjectManager {
@@ -359,7 +344,6 @@ Qt4Project::Qt4Project(Qt4Manager *manager, const QString& fileName) :
m_pendingEvaluateFuturesCount(0),
m_asyncUpdateState(NoState),
m_cancelEvaluate(false),
- m_codeModelCanceled(false),
m_centralizedFolderWatcher(0),
m_activeTarget(0)
{
@@ -397,6 +381,32 @@ void Qt4Project::updateFileList()
}
}
+bool Qt4Project::setupTarget(ProjectExplorer::Target *t)
+{
+ QList<BuildConfigurationInfo> infoList
+ = Qt4BuildConfigurationFactory::availableBuildConfigurations(t->kit(), m_fileInfo->fileName());
+ setupTarget(t, infoList);
+ return true;
+}
+
+void Qt4Project::setupTarget(ProjectExplorer::Target *t, const QList<BuildConfigurationInfo> &infoList)
+{
+ // Build Configurations:
+ foreach (const BuildConfigurationInfo &info, infoList) {
+ QString name = info.buildConfig & QtSupport::BaseQtVersion::DebugBuild
+ ? tr("Debug") : tr("Release");
+ Qt4BuildConfiguration *bc
+ = Qt4BuildConfiguration::setup(t, name, name,
+ info.buildConfig, info.additionalArguments,
+ info.directory, info.importing);
+ t->addBuildConfiguration(bc);
+ }
+
+ // Deploy Configurations:
+ t->updateDefaultDeployConfigurations();
+ // Do not create Run Configurations: Those will be generated later anyway.
+}
+
bool Qt4Project::fromMap(const QVariantMap &map)
{
if (!Project::fromMap(map))
@@ -423,8 +433,8 @@ bool Qt4Project::fromMap(const QVariantMap &map)
updateCodeModels();
// We have the profile nodes now, so we know the runconfigs!
- connect(m_nodesWatcher, SIGNAL(kitUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)),
- this, SIGNAL(kitUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)));
+ connect(m_nodesWatcher, SIGNAL(proFileUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)),
+ this, SIGNAL(proFileUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)));
// Now we emit update once :)
m_rootProjectNode->emitProFileUpdatedRecursive();
@@ -454,9 +464,9 @@ bool Qt4Project::equalFileList(const QStringList &a, const QStringList &b)
QStringList::const_iterator bend = b.constEnd();
while (ait != aend && bit != bend) {
- if (*ait == QLatin1String("<configuration>"))
+ if (*ait == CPlusPlus::CppModelManagerInterface::configurationFileName())
++ait;
- else if (*bit == QLatin1String("<configuration>"))
+ else if (*bit == CPlusPlus::CppModelManagerInterface::configurationFileName())
++bit;
else if (*ait == *bit)
++ait, ++bit;
@@ -514,11 +524,17 @@ void Qt4Project::updateCppCodeModel()
QStringList allFiles;
foreach (Qt4ProFileNode *pro, proFiles) {
ProjectPart::Ptr part(new ProjectPart);
- part->qtVersion = qtVersionForPart;
+
+ if (pro->variableValue(ConfigVar).contains(QLatin1String("qt")))
+ part->qtVersion = qtVersionForPart;
+ else
+ part->qtVersion = ProjectPart::NoQt;
+
+ const QStringList cxxflags = pro->variableValue(CppFlagsVar);
// part->defines
if (tc)
- part->defines = tc->predefinedMacros(pro->variableValue(CppFlagsVar));
+ part->defines = tc->predefinedMacros(cxxflags);
part->defines += pro->cxxDefines();
// part->includePaths
@@ -526,10 +542,9 @@ void Qt4Project::updateCppCodeModel()
QList<HeaderPath> headers;
if (tc)
- headers = tc->systemHeaderPaths(SysRootKitInformation::sysRoot(k)); // todo pass cxxflags?
- if (qtVersion) {
+ headers = tc->systemHeaderPaths(cxxflags, SysRootKitInformation::sysRoot(k));
+ if (qtVersion)
headers.append(qtVersion->systemHeaderPathes(k));
- }
foreach (const HeaderPath &headerPath, headers) {
if (headerPath.kind() == HeaderPath::FrameworkHeaderPath)
@@ -550,26 +565,21 @@ void Qt4Project::updateCppCodeModel()
part->precompiledHeaders.append(pro->variableValue(PrecompiledHeaderVar));
// part->language
- part->language = CPlusPlus::CppModelManagerInterface::CXX;
- // part->flags
if (tc)
- part->cxx11Enabled = tc->compilerFlags(pro->variableValue(CppFlagsVar)) == ToolChain::STD_CXX11;
+ part->language = tc->compilerFlags(cxxflags) == ToolChain::STD_CXX11 ? ProjectPart::CXX11 : ProjectPart::CXX;
+ else
+ part->language = CPlusPlus::CppModelManagerInterface::ProjectPart::CXX11;
part->sourceFiles = pro->variableValue(CppSourceVar);
- part->sourceFiles += pro->variableValue(CppHeaderVar);
- part->sourceFiles.prepend(QLatin1String("<configuration>"));
+ part->headerFiles += pro->variableValue(CppHeaderVar);
+ part->headerFiles += pro->uiFiles();
+ part->sourceFiles.prepend(CPlusPlus::CppModelManagerInterface::configurationFileName());
+ part->objcSourceFiles = pro->variableValue(ObjCSourceVar);
pinfo.appendProjectPart(part);
+ allFiles += part->headerFiles;
allFiles += part->sourceFiles;
-
- part = ProjectPart::Ptr(new ProjectPart);
- // todo objc code?
- part->language = CPlusPlus::CppModelManagerInterface::OBJC;
- part->sourceFiles = pro->variableValue(ObjCSourceVar);
- if (!part->sourceFiles.isEmpty())
- pinfo.appendProjectPart(part);
-
- allFiles += part->sourceFiles;
+ allFiles += part->objcSourceFiles;
}
modelmanager->updateProjectInfo(pinfo);
@@ -715,7 +725,6 @@ void Qt4Project::scheduleAsyncUpdate(Qt4ProFileNode *node)
// Cancel running code model update
m_codeModelFuture.cancel();
- m_codeModelCanceled = true;
} else if (m_asyncUpdateState == AsyncUpdateInProgress) {
// A update is in progress
// And this slot only gets called if a file changed on disc
@@ -764,7 +773,6 @@ void Qt4Project::scheduleAsyncUpdate()
// Cancel running code model update
m_codeModelFuture.cancel();
- m_codeModelCanceled = true;
}
@@ -792,6 +800,7 @@ void Qt4Project::decrementPendingEvaluateFutures()
// We are done!
if (debug)
qDebug()<<" reporting finished";
+
m_asyncUpdateFutureInterface->reportFinished();
delete m_asyncUpdateFutureInterface;
m_asyncUpdateFutureInterface = 0;
@@ -846,7 +855,7 @@ void Qt4Project::asyncUpdate()
} else {
if (debug)
qDebug()<<" partial update,"<<m_partialEvaluate.size()<<"nodes to update";
- foreach(Qt4ProFileNode *node, m_partialEvaluate)
+ foreach (Qt4ProFileNode *node, m_partialEvaluate)
node->asyncUpdate();
}
@@ -903,10 +912,10 @@ QStringList Qt4Project::files(FilesMode fileMode) const
// Find the folder that contains a file a certain type (recurse down)
static FolderNode *folderOf(FolderNode *in, FileType fileType, const QString &fileName)
{
- foreach(FileNode *fn, in->fileNodes())
+ foreach (FileNode *fn, in->fileNodes())
if (fn->fileType() == fileType && fn->path() == fileName)
return in;
- foreach(FolderNode *folder, in->subFolderNodes())
+ foreach (FolderNode *folder, in->subFolderNodes())
if (FolderNode *pn = folderOf(folder, fileType, fileName))
return pn;
return 0;
@@ -937,10 +946,10 @@ void Qt4Project::proFileParseError(const QString &errorMessage)
Core::ICore::messageManager()->printToOutputPanePopup(errorMessage);
}
-QtSupport::ProFileReader *Qt4Project::createProFileReader(Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc)
+QtSupport::ProFileReader *Qt4Project::createProFileReader(const Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc)
{
if (!m_qmakeGlobals) {
- m_qmakeGlobals = new QMakeGlobals;
+ m_qmakeGlobals = new ProFileGlobals;
m_qmakeGlobalsRefCnt = 0;
Kit *k;
@@ -952,12 +961,10 @@ QtSupport::ProFileReader *Qt4Project::createProFileReader(Qt4ProFileNode *qt4Pro
if (bc) {
k = bc->target()->kit();
env = bc->environment();
- if (bc->qmakeStep()) {
+ if (bc->qmakeStep())
qmakeArgs = bc->qmakeStep()->parserArguments();
- m_qmakeGlobals->qmakespec = m_qmakeGlobals->xqmakespec = bc->qmakeStep()->mkspec().toString();
- } else {
+ else
qmakeArgs = bc->configCommandLineArguments();
- }
} else {
k = KitManager::instance()->defaultKit();
}
@@ -977,7 +984,7 @@ QtSupport::ProFileReader *Qt4Project::createProFileReader(Qt4ProFileNode *qt4Pro
for (; eit != eend; ++eit)
m_qmakeGlobals->environment.insert(env.key(eit), env.value(eit));
- m_qmakeGlobals->setCommandLineArguments(qmakeArgs);
+ m_qmakeGlobals->setCommandLineArguments(m_rootProjectNode->buildDir(), qmakeArgs);
QtSupport::ProFileCacheManager::instance()->incRefCount();
}
@@ -990,7 +997,7 @@ QtSupport::ProFileReader *Qt4Project::createProFileReader(Qt4ProFileNode *qt4Pro
return reader;
}
-QMakeGlobals *Qt4Project::qmakeGlobals()
+ProFileGlobals *Qt4Project::qmakeGlobals()
{
return m_qmakeGlobals;
}
@@ -1036,13 +1043,6 @@ bool Qt4Project::parseInProgress(const QString &proFilePath) const
return node && node->parseInProgress();
}
-QList<BuildConfigWidget*> Qt4Project::subConfigWidgets()
-{
- QList<BuildConfigWidget*> subWidgets;
- subWidgets << new BuildEnvironmentWidget;
- return subWidgets;
-}
-
void Qt4Project::collectAllfProFiles(QList<Qt4ProFileNode *> &list, Qt4ProFileNode *node)
{
list.append(node);
@@ -1152,7 +1152,7 @@ void Qt4Project::notifyChanged(const QString &name)
if (files(Qt4Project::ExcludeGeneratedFiles).contains(name)) {
QList<Qt4ProFileNode *> list;
findProFile(name, rootQt4ProjectNode(), list);
- foreach(Qt4ProFileNode *node, list) {
+ foreach (Qt4ProFileNode *node, list) {
QtSupport::ProFileCacheManager::instance()->discardFile(name);
node->update();
}
@@ -1248,9 +1248,8 @@ void CentralizedFolderWatcher::unwatchFolders(const QList<QString> &folders, Qt4
if (!folder.endsWith(slash))
folder.append(slash);
m_map.remove(folder, node);
- if (!m_map.contains(folder)) {
+ if (!m_map.contains(folder))
m_watcher.removePath(folder);
- }
// Figure out which recursive directories we can remove
// this might not scale. I'm pretty sure it doesn't
@@ -1295,7 +1294,7 @@ void CentralizedFolderWatcher::folderChanged(const QString &folder)
void CentralizedFolderWatcher::onTimer()
{
- foreach(const QString &folder, m_changedFolders)
+ foreach (const QString &folder, m_changedFolders)
delayedFolderChanged(folder);
m_changedFolders.clear();
}
@@ -1396,19 +1395,21 @@ QString Qt4Project::disabledReasonForRunConfiguration(const QString &proFilePath
.arg(QFileInfo(proFilePath).fileName());
}
-QString Qt4Project::shadowBuildDirectory(const QString &profilePath, const Kit *k, const QString &suffix)
+QString Qt4Project::shadowBuildDirectory(const QString &proFilePath, const Kit *k, const QString &suffix)
{
- if (profilePath.isEmpty())
+ if (proFilePath.isEmpty())
return QString();
- QFileInfo info(profilePath);
+ QFileInfo info(proFilePath);
QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(k);
if (version && !version->supportsShadowBuilds())
return info.absolutePath();
- QString base = QDir::cleanPath(projectDirectory(profilePath) + QLatin1String("/../")
- + info.baseName() + QLatin1String("-build-"));
- return base + buildNameFor(k) + QLatin1String("-") + sanitize(suffix);
+ const QString projectName = QFileInfo(proFilePath).completeBaseName();
+ ProjectExplorer::ProjectExpander expander(proFilePath, projectName, k, suffix);
+ QDir projectDir = QDir(projectDirectory(proFilePath));
+ QString buildPath = Utils::expandMacros(Core::DocumentManager::buildDirectory(), &expander);
+ return QDir::cleanPath(projectDir.absoluteFilePath(buildPath));
}
QString Qt4Project::buildNameFor(const Kit *k)
@@ -1425,22 +1426,7 @@ Target *Qt4Project::createTarget(Kit *k, const QList<BuildConfigurationInfo> &in
return 0;
Target *t = new Target(this, k);
-
- // Build Configurations:
- foreach (const BuildConfigurationInfo &info, infoList) {
- QString name = info.buildConfig & QtSupport::BaseQtVersion::DebugBuild
- ? tr("Debug") : tr("Release");
- Qt4BuildConfiguration *bc
- = Qt4BuildConfiguration::setup(t, name, name,
- info.buildConfig, info.additionalArguments,
- info.directory, info.importing);
- t->addBuildConfiguration(bc);
- }
-
- // Deploy Configurations:
- t->updateDefaultDeployConfigurations();
- // Do not create Run Configurations: Those will be generated later anyway.
-
+ setupTarget(t, infoList);
return t;
}
@@ -1530,7 +1516,7 @@ void Qt4Project::collectLibraryData(const Qt4ProFileNode *node, DeploymentData &
break;
}
case ProjectExplorer::Abi::MacOS:
- if (config.contains("lib_bundle")) {
+ if (config.contains(QLatin1String("lib_bundle"))) {
ti.workingDir.append(QLatin1Char('/')).append(ti.target)
.append(QLatin1String(".framework"));
} else {
diff --git a/src/plugins/qt4projectmanager/qt4project.h b/src/plugins/qt4projectmanager/qt4project.h
index 307e20b4f9..2621885ae0 100644
--- a/src/plugins/qt4projectmanager/qt4project.h
+++ b/src/plugins/qt4projectmanager/qt4project.h
@@ -42,7 +42,7 @@
#include <QFuture>
QT_BEGIN_NAMESPACE
-class QMakeGlobals;
+class ProFileGlobals;
QT_END_NAMESPACE
namespace ProjectExplorer { class DeploymentData; }
@@ -92,8 +92,6 @@ public:
virtual QStringList files(FilesMode fileMode) const;
virtual QString generatedUiHeader(const QString &formFile) const;
- QList<ProjectExplorer::BuildConfigWidget*> subConfigWidgets();
-
QList<Qt4ProFileNode *> allProFiles() const;
QList<Qt4ProFileNode *> applicationProFiles() const;
bool hasApplicationProFile(const QString &path) const;
@@ -102,9 +100,9 @@ public:
void notifyChanged(const QString &name);
/// \internal
- QtSupport::ProFileReader *createProFileReader(Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc = 0);
+ QtSupport::ProFileReader *createProFileReader(const Qt4ProFileNode *qt4ProFileNode, Qt4BuildConfiguration *bc = 0);
/// \internal
- QMakeGlobals *qmakeGlobals();
+ ProFileGlobals *qmakeGlobals();
/// \internal
void destroyProFileReader(QtSupport::ProFileReader *reader);
@@ -144,7 +142,7 @@ public:
void emitBuildDirectoryInitialized();
signals:
- void kitUpdated(Qt4ProjectManager::Qt4ProFileNode *node, bool, bool);
+ void proFileUpdated(Qt4ProjectManager::Qt4ProFileNode *node, bool, bool);
void buildDirectoryInitialized();
void proFilesEvaluated();
@@ -155,6 +153,8 @@ public slots:
protected:
bool fromMap(const QVariantMap &map);
+ bool setupTarget(ProjectExplorer::Target *t);
+ void setupTarget(ProjectExplorer::Target *t, const QList<BuildConfigurationInfo> &infoList);
private slots:
void asyncUpdate();
@@ -195,7 +195,7 @@ private:
Internal::Qt4ProjectFiles *m_projectFiles;
// cached data during project rescan
- QMakeGlobals *m_qmakeGlobals;
+ ProFileGlobals *m_qmakeGlobals;
int m_qmakeGlobalsRefCnt;
QTimer m_asyncUpdateTimer;
@@ -204,7 +204,6 @@ private:
enum AsyncUpdateState { NoState, Base, AsyncFullUpdatePending, AsyncPartialUpdatePending, AsyncUpdateInProgress, ShuttingDown };
AsyncUpdateState m_asyncUpdateState;
bool m_cancelEvaluate;
- bool m_codeModelCanceled;
QList<Qt4ProFileNode *> m_partialEvaluate;
QFuture<void> m_codeModelFuture;
diff --git a/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp b/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp
index 37cd6e55b1..74d0607129 100644
--- a/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp
+++ b/src/plugins/qt4projectmanager/qt4projectconfigwidget.cpp
@@ -35,6 +35,7 @@
#include "qt4projectmanagerconstants.h"
#include "qt4projectmanager.h"
#include "qt4buildconfiguration.h"
+#include "qt4nodes.h"
#include "ui_qt4projectconfigwidget.h"
#include <coreplugin/icore.h>
@@ -54,21 +55,16 @@
#include <utils/qtcprocess.h>
#include <extensionsystem/pluginmanager.h>
-#include <QFileDialog>
#include <QPushButton>
#include <utils/detailswidget.h>
-namespace {
-bool debug = false;
-}
-
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
using namespace ProjectExplorer;
-Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(ProjectExplorer::Target *target)
- : BuildConfigWidget(),
- m_buildConfiguration(0),
+Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(Qt4BuildConfiguration *bc)
+ : NamedWidget(),
+ m_buildConfiguration(bc),
m_ignoreChange(false)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
@@ -95,11 +91,25 @@ Qt4ProjectConfigWidget::Qt4ProjectConfigWidget(ProjectExplorer::Target *target)
connect(m_ui->shadowBuildDirEdit, SIGNAL(changed(QString)),
this, SLOT(shadowBuildEdited()));
- Qt4Project *project = static_cast<Qt4Project *>(target->project());
+ Qt4Project *project = static_cast<Qt4Project *>(bc->target()->project());
connect(project, SIGNAL(environmentChanged()), this, SLOT(environmentChanged()));
connect(project, SIGNAL(buildDirectoryInitialized()), this, SLOT(updateProblemLabel()));
+ connect(project, SIGNAL(proFilesEvaluated()), this, SLOT(updateProblemLabel()));
+
+ connect(bc->target(), SIGNAL(kitChanged()), this, SLOT(updateProblemLabel()));
+
+ m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());
+
+ connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
+ this, SLOT(buildDirectoryChanged()));
+ connect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
+ this, SLOT(updateProblemLabel()));
- connect(target, SIGNAL(kitChanged()), this, SLOT(updateProblemLabel()));
+ m_ui->shadowBuildDirEdit->setBaseDirectory(m_buildConfiguration->target()->project()->projectDirectory());
+
+ buildDirectoryChanged();
+
+ setDisplayName(tr("General"));
}
Qt4ProjectConfigWidget::~Qt4ProjectConfigWidget()
@@ -126,37 +136,6 @@ void Qt4ProjectConfigWidget::environmentChanged()
m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());
}
-QString Qt4ProjectConfigWidget::displayName() const
-{
- return tr("General");
-}
-
-void Qt4ProjectConfigWidget::init(ProjectExplorer::BuildConfiguration *bc)
-{
- QTC_ASSERT(bc, return);
-
- if (debug)
- qDebug() << "Qt4ProjectConfigWidget::init() for" << bc->displayName();
-
- if (m_buildConfiguration) {
- disconnect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
- this, SLOT(buildDirectoryChanged()));
- disconnect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
- this, SLOT(updateProblemLabel()));
- }
- m_buildConfiguration = static_cast<Qt4BuildConfiguration *>(bc);
- m_ui->shadowBuildDirEdit->setEnvironment(m_buildConfiguration->environment());
-
- connect(m_buildConfiguration, SIGNAL(buildDirectoryChanged()),
- this, SLOT(buildDirectoryChanged()));
- connect(m_buildConfiguration, SIGNAL(qmakeBuildConfigurationChanged()),
- this, SLOT(updateProblemLabel()));
-
- m_ui->shadowBuildDirEdit->setBaseDirectory(m_buildConfiguration->target()->project()->projectDirectory());
-
- buildDirectoryChanged();
-}
-
void Qt4ProjectConfigWidget::buildDirectoryChanged()
{
if (m_ignoreChange)
@@ -209,7 +188,7 @@ void Qt4ProjectConfigWidget::shadowBuildEdited()
void Qt4ProjectConfigWidget::updateProblemLabel()
{
-
+ m_ui->shadowBuildDirEdit->triggerChanged();
ProjectExplorer::Kit *k = m_buildConfiguration->target()->kit();
const QString proFileName = m_buildConfiguration->target()->project()->document()->fileName();
@@ -220,6 +199,12 @@ void Qt4ProjectConfigWidget::updateProblemLabel()
return;
}
+ Qt4Project *p = static_cast<Qt4Project *>(m_buildConfiguration->target()->project());
+ if (p->rootQt4ProjectNode()->parseInProgress() || !p->rootQt4ProjectNode()->validParse()) {
+ setProblemLabel(QString());
+ return;
+ }
+
bool targetMismatch = false;
bool incompatibleBuild = false;
bool allGood = false;
diff --git a/src/plugins/qt4projectmanager/qt4projectconfigwidget.h b/src/plugins/qt4projectmanager/qt4projectconfigwidget.h
index a86a87485c..01dcdf38b8 100644
--- a/src/plugins/qt4projectmanager/qt4projectconfigwidget.h
+++ b/src/plugins/qt4projectmanager/qt4projectconfigwidget.h
@@ -30,7 +30,7 @@
#ifndef QT4PROJECTCONFIGWIDGET_H
#define QT4PROJECTCONFIGWIDGET_H
-#include <projectexplorer/buildstep.h>
+#include <projectexplorer/namedwidget.h>
QT_BEGIN_NAMESPACE
class QAbstractButton;
@@ -49,16 +49,13 @@ namespace Ui {
class Qt4ProjectConfigWidget;
}
-class Qt4ProjectConfigWidget : public ProjectExplorer::BuildConfigWidget
+class Qt4ProjectConfigWidget : public ProjectExplorer::NamedWidget
{
Q_OBJECT
public:
- Qt4ProjectConfigWidget(ProjectExplorer::Target *target);
+ Qt4ProjectConfigWidget(Qt4BuildConfiguration *bc);
~Qt4ProjectConfigWidget();
- QString displayName() const;
- void init(ProjectExplorer::BuildConfiguration *bc);
-
private slots:
// User changes in our widgets
void shadowBuildClicked(bool checked);
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.cpp b/src/plugins/qt4projectmanager/qt4projectmanager.cpp
index 4b7607032b..b1c742f37e 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.cpp
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.cpp
@@ -45,7 +45,6 @@
#include <coreplugin/id.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/editormanager/ieditor.h>
-#include <coreplugin/variablemanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/buildmanager.h>
#include <projectexplorer/session.h>
@@ -62,7 +61,6 @@
#include <QDir>
#include <QFileInfo>
#include <QVariant>
-#include <QFileDialog>
#include <QMessageBox>
using namespace Qt4ProjectManager;
@@ -76,9 +74,6 @@ using ProjectExplorer::FormType;
using ProjectExplorer::ResourceType;
using ProjectExplorer::UnknownFileType;
-static const char kHostBins[] = "CurrentProject:QT_HOST_BINS";
-static const char kInstallBins[] = "CurrentProject:QT_INSTALL_BINS";
-
// Known file types of a Qt 4 project
static const char *qt4FileTypes[] = {
"CppHeaderFiles",
@@ -138,15 +133,6 @@ void Qt4Manager::init()
connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
this, SLOT(editorChanged(Core::IEditor*)));
-
- Core::VariableManager *vm = Core::VariableManager::instance();
- vm->registerVariable(kHostBins,
- tr("Full path to the host bin directory of the current project's Qt version."));
- vm->registerVariable(kInstallBins,
- tr("Full path to the target bin directory of the current project's Qt version."
- " You probably want %1 instead.").arg(QString::fromLatin1(kHostBins)));
- connect(vm, SIGNAL(variableUpdateRequested(QByteArray)),
- this, SLOT(updateVariable(QByteArray)));
}
void Qt4Manager::editorChanged(Core::IEditor *editor)
@@ -188,27 +174,6 @@ void Qt4Manager::editorAboutToClose(Core::IEditor *editor)
}
}
-void Qt4Manager::updateVariable(const QByteArray &variable)
-{
- if (variable == kHostBins || variable == kInstallBins) {
- Qt4Project *qt4pro = qobject_cast<Qt4Project *>(ProjectExplorer::ProjectExplorerPlugin::currentProject());
- if (!qt4pro) {
- Core::VariableManager::instance()->remove(variable);
- return;
- }
- QString value;
- const QtSupport::BaseQtVersion *qtv = 0;
- if (ProjectExplorer::Target *t = qt4pro->activeTarget())
- qtv = QtSupport::QtKitInformation::qtVersion(t->kit());
- else
- qtv = QtSupport::QtKitInformation::qtVersion(ProjectExplorer::KitManager::instance()->defaultKit());
-
- if (qtv)
- value = qtv->qmakeProperty(variable == kHostBins ? "QT_HOST_BINS" : "QT_INSTALL_BINS");
- Core::VariableManager::instance()->insert(variable, value);
- }
-}
-
void Qt4Manager::uiEditorContentsChanged()
{
// cast sender, get filename
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.h b/src/plugins/qt4projectmanager/qt4projectmanager.h
index e745022e70..7e431f3e14 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.h
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.h
@@ -106,7 +106,6 @@ private slots:
void editorAboutToClose(Core::IEditor *editor);
void uiEditorContentsChanged();
void editorChanged(Core::IEditor*);
- void updateVariable(const QByteArray &variable);
private:
QList<Qt4Project *> m_projects;
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.pro b/src/plugins/qt4projectmanager/qt4projectmanager.pro
index ae1b4ff64d..0f648d3852 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.pro
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.pro
@@ -1,10 +1,13 @@
TEMPLATE = lib
TARGET = Qt4ProjectManager
-DEFINES += QT_CREATOR QT4PROJECTMANAGER_LIBRARY
QT += network
include(../../qtcreatorplugin.pri)
include(qt4projectmanager_dependencies.pri)
+DEFINES += \
+ QT_CREATOR \
+ QT4PROJECTMANAGER_LIBRARY
+
HEADERS += \
qmakekitinformation.h \
qmakekitconfigwidget.h \
@@ -63,7 +66,6 @@ HEADERS += \
librarydetailscontroller.h \
findqt4profiles.h \
qt4projectmanager_global.h \
- profilekeywords.h \
qt4targetsetupwidget.h \
buildconfigurationinfo.h \
winceqtversionfactory.h \
@@ -127,7 +129,6 @@ SOURCES += \
addlibrarywizard.cpp \
librarydetailscontroller.cpp \
findqt4profiles.cpp \
- profilekeywords.cpp \
qt4targetsetupwidget.cpp \
winceqtversionfactory.cpp \
winceqtversion.cpp \
@@ -152,5 +153,4 @@ RESOURCES += qt4projectmanager.qrc \
include(qt-desktop/qt-desktop.pri)
include(customwidgetwizard/customwidgetwizard.pri)
-DEFINES += QT_NO_CAST_TO_ASCII
OTHER_FILES += Qt4ProjectManager.mimetypes.xml
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.qbs b/src/plugins/qt4projectmanager/qt4projectmanager.qbs
index b70d5f4d1e..57502c1d0e 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.qbs
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.qbs
@@ -16,35 +16,30 @@ QtcPlugin {
Depends { name: "TextEditor" }
Depends { name: "cpp" }
- cpp.defines: {
- return base.concat([
- "PROPARSER_AS_LIBRARY",
- "PROPARSER_THREAD_SAFE",
- "PROEVALUATOR_THREAD_SAFE",
- "PROEVALUATOR_CUMULATIVE"
- ])
- }
- cpp.includePaths: [
- ".",
- "..",
- buildDirectory,
+ cpp.defines: base.concat([
+ "PROPARSER_AS_LIBRARY",
+ "PROPARSER_THREAD_SAFE",
+ "PROEVALUATOR_THREAD_SAFE",
+ "PROEVALUATOR_CUMULATIVE"
+ ])
+ cpp.includePaths: base.concat([
"customwidgetwizard",
- "../../libs",
"../../shared",
- ]
+ ])
files: [
"Qt4ProjectManager.mimetypes.xml",
- "librarydetailswidget.ui",
- "qt4projectmanager.qrc",
"addlibrarywizard.cpp",
"addlibrarywizard.h",
+ "buildconfigurationinfo.h",
"externaleditors.cpp",
"externaleditors.h",
"findqt4profiles.cpp",
"findqt4profiles.h",
"librarydetailscontroller.cpp",
"librarydetailscontroller.h",
+ "librarydetailswidget.ui",
+ "makestep.cpp",
"makestep.h",
"makestep.ui",
"profilecompletionassist.cpp",
@@ -57,14 +52,14 @@ QtcPlugin {
"profilehighlighter.h",
"profilehoverhandler.cpp",
"profilehoverhandler.h",
- "profilekeywords.cpp",
- "profilekeywords.h",
"qmakeparser.cpp",
"qmakeparser.h",
"qmakekitconfigwidget.cpp",
"qmakekitconfigwidget.h",
"qmakekitinformation.cpp",
"qmakekitinformation.h",
+ "qmakeparser.cpp",
+ "qmakeparser.h",
"qmakerunconfigurationfactory.cpp",
"qmakerunconfigurationfactory.h",
"qmakestep.cpp",
@@ -72,12 +67,16 @@ QtcPlugin {
"qmakestep.ui",
"qt4buildconfiguration.cpp",
"qt4buildconfiguration.h",
+ "qt4nodes.cpp",
"qt4nodes.h",
"qt4project.cpp",
"qt4project.h",
"qt4projectconfigwidget.cpp",
"qt4projectconfigwidget.h",
"qt4projectconfigwidget.ui",
+ "qt4projectmanager.cpp",
+ "qt4projectmanager.h",
+ "qt4projectmanager.qrc",
"qt4projectmanager_global.h",
"qt4projectmanagerconstants.h",
"qt4projectmanagerplugin.cpp",
@@ -94,22 +93,17 @@ QtcPlugin {
"winceqtversion.h",
"winceqtversionfactory.cpp",
"winceqtversionfactory.h",
- "buildconfigurationinfo.h",
- "makestep.cpp",
- "qt4nodes.cpp",
- "qt4projectmanager.cpp",
- "qt4projectmanager.h",
- "customwidgetwizard/classdefinition.ui",
- "customwidgetwizard/customwidgetpluginwizardpage.ui",
- "customwidgetwizard/customwidgetwidgetswizardpage.ui",
"customwidgetwizard/classdefinition.cpp",
"customwidgetwizard/classdefinition.h",
+ "customwidgetwizard/classdefinition.ui",
"customwidgetwizard/classlist.cpp",
"customwidgetwizard/classlist.h",
"customwidgetwizard/customwidgetpluginwizardpage.cpp",
"customwidgetwizard/customwidgetpluginwizardpage.h",
+ "customwidgetwizard/customwidgetpluginwizardpage.ui",
"customwidgetwizard/customwidgetwidgetswizardpage.cpp",
"customwidgetwizard/customwidgetwidgetswizardpage.h",
+ "customwidgetwizard/customwidgetwidgetswizardpage.ui",
"customwidgetwizard/customwidgetwizard.cpp",
"customwidgetwizard/customwidgetwizard.h",
"customwidgetwizard/customwidgetwizarddialog.cpp",
@@ -136,8 +130,6 @@ QtcPlugin {
"qt-desktop/simulatorqtversion.h",
"qt-desktop/simulatorqtversionfactory.cpp",
"qt-desktop/simulatorqtversionfactory.h",
- "wizards/testwizardpage.ui",
- "wizards/wizards.qrc",
"wizards/abstractmobileapp.cpp",
"wizards/abstractmobileapp.h",
"wizards/abstractmobileappwizard.cpp",
@@ -163,6 +155,9 @@ QtcPlugin {
"wizards/html5appwizardpages.cpp",
"wizards/html5appwizardpages.h",
"wizards/html5appwizardsourcespage.ui",
+ "wizards/importwidget.cpp",
+ "wizards/importwidget.h",
+ "wizards/libraryparameters.cpp",
"wizards/libraryparameters.h",
"wizards/librarywizard.cpp",
"wizards/librarywizard.h",
@@ -201,19 +196,18 @@ QtcPlugin {
"wizards/subdirsprojectwizarddialog.h",
"wizards/targetsetuppage.cpp",
"wizards/targetsetuppage.h",
- "wizards/importwidget.cpp",
- "wizards/importwidget.h",
"wizards/testwizard.cpp",
"wizards/testwizard.h",
"wizards/testwizarddialog.cpp",
"wizards/testwizarddialog.h",
"wizards/testwizardpage.cpp",
"wizards/testwizardpage.h",
- "wizards/libraryparameters.cpp",
+ "wizards/testwizardpage.ui",
+ "wizards/wizards.qrc",
"wizards/images/console.png",
"wizards/images/gui.png",
"wizards/images/html5app.png",
"wizards/images/lib.png",
- "wizards/images/qtquickapp.png"
+ "wizards/images/qtquickapp.png",
]
}
diff --git a/src/plugins/qt4projectmanager/qt4projectmanager.qrc b/src/plugins/qt4projectmanager/qt4projectmanager.qrc
index 2fa83ca94b..130651d467 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanager.qrc
+++ b/src/plugins/qt4projectmanager/qt4projectmanager.qrc
@@ -9,6 +9,6 @@
<file>images/qt_qrc.png</file>
<file>images/sources.png</file>
<file>images/unknown.png</file>
- <file>images/qml.ico</file>
+ <file>images/qml.png</file>
</qresource>
</RCC>
diff --git a/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp b/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp
index 8e5140b86b..530c888dfd 100644
--- a/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp
+++ b/src/plugins/qt4projectmanager/qt4projectmanagerplugin.cpp
@@ -77,6 +77,7 @@
#include <texteditor/texteditoractionhandler.h>
#include <texteditor/texteditorconstants.h>
#include <texteditor/texteditorsettings.h>
+#include <utils/hostosinfo.h>
#include <utils/parameteraction.h>
#ifdef WITH_TESTS
@@ -152,11 +153,10 @@ bool Qt4ProjectManagerPlugin::initialize(const QStringList &arguments, QString *
addAutoReleasedObject(new Qt4BuildConfigurationFactory);
addAutoReleasedObject(new Qt4RunConfigurationFactory);
-#ifdef Q_OS_MAC
- addAutoReleasedObject(new MacDesignerExternalEditor);
-#else
- addAutoReleasedObject(new DesignerExternalEditor);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ addAutoReleasedObject(new MacDesignerExternalEditor);
+ else
+ addAutoReleasedObject(new DesignerExternalEditor);
addAutoReleasedObject(new LinguistExternalEditor);
addAutoReleasedObject(new DesktopQtVersionFactory);
diff --git a/src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp b/src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp
index 91e5a0e48f..7b62ecd53f 100644
--- a/src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp
+++ b/src/plugins/qt4projectmanager/qt4targetsetupwidget.cpp
@@ -41,6 +41,7 @@
#include <utils/detailsbutton.h>
#include <utils/detailswidget.h>
+#include <utils/hostosinfo.h>
#include <utils/pathchooser.h>
#include <QCheckBox>
@@ -92,9 +93,8 @@ Qt4TargetSetupWidget::Qt4TargetSetupWidget(ProjectExplorer::Kit *k,
QWidget *w = new QWidget;
m_newBuildsLayout = new QGridLayout;
m_newBuildsLayout->setMargin(0);
-#ifdef Q_OS_MAC
- m_newBuildsLayout->setSpacing(0);
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ m_newBuildsLayout->setSpacing(0);
w->setLayout(m_newBuildsLayout);
layout->addWidget(w);
@@ -228,8 +228,8 @@ void Qt4TargetSetupWidget::manageKit()
return;
page->showKit(m_kit);
- Core::ICore::showOptionsDialog(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::KITS_SETTINGS_PAGE_ID));
+ Core::ICore::showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ ProjectExplorer::Constants::KITS_SETTINGS_PAGE_ID);
}
void Qt4TargetSetupWidget::setProFilePath(const QString &proFilePath)
diff --git a/src/plugins/qt4projectmanager/qtmodulesinfo.cpp b/src/plugins/qt4projectmanager/qtmodulesinfo.cpp
index a2731f565e..0722849702 100644
--- a/src/plugins/qt4projectmanager/qtmodulesinfo.cpp
+++ b/src/plugins/qt4projectmanager/qtmodulesinfo.cpp
@@ -134,14 +134,14 @@ QStringList QtModulesInfo::modules()
{
QStringList result;
foreach (const item *i, staticQtModuleInfo()->items)
- result.push_back(i->config);
+ result.push_back(QLatin1String(i->config));
return result;
}
static inline const item *itemForModule(const QString &module)
{
foreach (const item *i, staticQtModuleInfo()->items)
- if (i->config == module)
+ if (QLatin1String(i->config) == module)
return i;
return 0;
}
diff --git a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp b/src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp
index 25c32a7dd8..3368760033 100644
--- a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp
+++ b/src/plugins/qt4projectmanager/unconfiguredprojectpanel.cpp
@@ -44,10 +44,12 @@
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/session.h>
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
+#include <QDialogButtonBox>
using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;
@@ -59,7 +61,7 @@ UnconfiguredProjectPanel::UnconfiguredProjectPanel()
QString Qt4ProjectManager::Internal::UnconfiguredProjectPanel::id() const
{
- return Constants::UNCONFIGURED_PANEL_PAGE_ID;
+ return QLatin1String(Constants::UNCONFIGURED_PANEL_PAGE_ID);
}
QString Qt4ProjectManager::Internal::UnconfiguredProjectPanel::displayName() const
@@ -83,7 +85,7 @@ ProjectExplorer::PropertiesPanel *Qt4ProjectManager::Internal::UnconfiguredProje
{
ProjectExplorer::PropertiesPanel *panel = new ProjectExplorer::PropertiesPanel;
panel->setDisplayName(displayName());
- panel->setIcon(QIcon(":/projectexplorer/images/unconfigured.png"));
+ panel->setIcon(QIcon(QLatin1String(":/projectexplorer/images/unconfigured.png")));
TargetSetupPageWrapper *w = new TargetSetupPageWrapper(project);
panel->setWidget(w);
@@ -117,9 +119,18 @@ TargetSetupPageWrapper::TargetSetupPageWrapper(ProjectExplorer::Project *project
layout->addLayout(hbox);
layout->setMargin(0);
hbox->addStretch();
+
+ QDialogButtonBox *box = new QDialogButtonBox(this);
+
m_configureButton = new QPushButton(this);
m_configureButton->setText(tr("Configure Project"));
- hbox->addWidget(m_configureButton);
+ box->addButton(m_configureButton, QDialogButtonBox::AcceptRole);
+
+ m_cancelButton = new QPushButton(this);
+ m_cancelButton->setText(tr("Cancel"));
+ box->addButton(m_cancelButton, QDialogButtonBox::RejectRole);
+
+ hbox->addWidget(box);
layout->addStretch(10);
@@ -127,6 +138,8 @@ TargetSetupPageWrapper::TargetSetupPageWrapper(ProjectExplorer::Project *project
connect(m_configureButton, SIGNAL(clicked()),
this, SLOT(done()));
+ connect(m_cancelButton, SIGNAL(clicked()),
+ this, SLOT(cancel()));
connect(m_targetSetupPage, SIGNAL(completeChanged()),
this, SLOT(completeChanged()));
connect(ProjectExplorer::KitManager::instance(), SIGNAL(defaultkitChanged()),
@@ -181,9 +194,15 @@ void TargetSetupPageWrapper::keyPressEvent(QKeyEvent *event)
void TargetSetupPageWrapper::keyReleaseEvent(QKeyEvent *event)
{
- if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
+ if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter)
event->accept();
- }
+}
+
+void TargetSetupPageWrapper::cancel()
+{
+ ProjectExplorer::ProjectExplorerPlugin::instance()->unloadProject(m_project);
+ if (ProjectExplorer::ProjectExplorerPlugin::instance()->session()->projects().isEmpty())
+ Core::ICore::instance()->modeManager()->activateMode(Core::Constants::MODE_WELCOME);
}
void TargetSetupPageWrapper::done()
diff --git a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.h b/src/plugins/qt4projectmanager/unconfiguredprojectpanel.h
index 611a15b86c..e71e7d2ef1 100644
--- a/src/plugins/qt4projectmanager/unconfiguredprojectpanel.h
+++ b/src/plugins/qt4projectmanager/unconfiguredprojectpanel.h
@@ -66,6 +66,7 @@ protected:
void keyPressEvent(QKeyEvent *event);
private slots:
void done();
+ void cancel();
void kitUpdated(ProjectExplorer::Kit *k);
void updateNoteText();
void completeChanged();
@@ -74,6 +75,7 @@ private:
Qt4Project *m_project;
TargetSetupPage *m_targetSetupPage;
QPushButton *m_configureButton;
+ QPushButton *m_cancelButton;
};
}
diff --git a/src/plugins/qt4projectmanager/winceqtversion.cpp b/src/plugins/qt4projectmanager/winceqtversion.cpp
index 4debd158a6..b75b94857b 100644
--- a/src/plugins/qt4projectmanager/winceqtversion.cpp
+++ b/src/plugins/qt4projectmanager/winceqtversion.cpp
@@ -50,6 +50,7 @@ WinCeQtVersion::WinCeQtVersion(const Utils::FileName &path, const QString &archT
m_archType = ProjectExplorer::Abi::X86Architecture;
else if (0 == archType.compare(QLatin1String("mipsii"), Qt::CaseInsensitive))
m_archType = ProjectExplorer::Abi::MipsArchitecture;
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
}
WinCeQtVersion::~WinCeQtVersion()
diff --git a/src/plugins/qt4projectmanager/wizards/abstractmobileapp.cpp b/src/plugins/qt4projectmanager/wizards/abstractmobileapp.cpp
index 63a8577460..343f026993 100644
--- a/src/plugins/qt4projectmanager/wizards/abstractmobileapp.cpp
+++ b/src/plugins/qt4projectmanager/wizards/abstractmobileapp.cpp
@@ -279,8 +279,8 @@ QByteArray AbstractMobileApp::generateProFile(QString *errorMessage) const
out << line << endl;
};
- proFileContent.replace("../shared/" + DeploymentPriFileName.toAscii(),
- DeploymentPriFileName.toAscii());
+ proFileContent.replace("../shared/" + DeploymentPriFileName.toLatin1(),
+ DeploymentPriFileName.toLatin1());
return proFileContent;
}
@@ -437,7 +437,7 @@ QByteArray AbstractMobileApp::generateFile(int fileType,
const QString versionLine =
comment + sep + FileChecksum + sep + checkSumString
+ sep + FileStubVersion + sep + versionString + QLatin1Char('\x0A');
- return versionLine.toAscii() + data;
+ return versionLine.toLatin1() + data;
}
int AbstractMobileApp::makeStubVersion(int minor)
diff --git a/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp b/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp
index b52e2eb78f..fce7d4abbe 100644
--- a/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/abstractmobileappwizard.cpp
@@ -63,9 +63,10 @@ AbstractMobileAppWizardDialog::AbstractMobileAppWizardDialog(QWidget *parent,
, m_genericItem(0)
, m_maemoItem(0)
, m_harmattanItem(0)
- , m_kitIds(parameters.extraValues().value(ProjectExplorer::Constants::PROJECT_KIT_IDS).value<QList<Core::Id> >())
+ , m_kitIds(parameters.extraValues().value(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ .value<QList<Core::Id> >())
{
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS)) {
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS))) {
m_targetsPage = new TargetSetupPage;
m_targetsPage->setPreferredKitMatcher(new QtSupport::QtPlatformKitMatcher(selectedPlatform()));
m_targetsPage->setRequiredKitMatcher(new QtSupport::QtVersionKitMatcher(requiredFeatures(),
@@ -87,11 +88,11 @@ void AbstractMobileAppWizardDialog::addMobilePages()
}
const bool shouldAddGenericPage = m_targetsPage
- || isQtPlatformSelected(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM);
+ || isQtPlatformSelected(QLatin1String(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM));
const bool shouldAddMaemoPage = m_targetsPage
- || isQtPlatformSelected(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM);
+ || isQtPlatformSelected(QLatin1String(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM));
const bool shouldAddHarmattanPage = m_targetsPage
- || isQtPlatformSelected(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM);
+ || isQtPlatformSelected(QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM));
if (shouldAddGenericPage) {
m_genericOptionsPageId = addPageWithTitle(m_genericOptionsPage,
@@ -131,21 +132,21 @@ int AbstractMobileAppWizardDialog::nextId() const
{
if (m_targetsPage) {
if (currentPage() == m_targetsPage) {
- if (isQtPlatformSelected(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM))
+ if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM)))
return m_genericOptionsPageId;
- else if (isQtPlatformSelected(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM))
+ else if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM)))
return m_harmattanOptionsPageId;
else
return idOfNextGenericPage();
} else if (currentPage() == m_genericOptionsPage) {
- if (isQtPlatformSelected(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM))
+ if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM)))
return m_maemoOptionsPageId;
- else if (isQtPlatformSelected(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM))
+ else if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM)))
return m_harmattanOptionsPageId;
else
return idOfNextGenericPage();
} else if (currentPage() == m_maemoOptionsPage) {
- if (isQtPlatformSelected(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM))
+ if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM)))
return m_harmattanOptionsPageId;
else
return idOfNextGenericPage();
@@ -168,9 +169,9 @@ void AbstractMobileAppWizardDialog::initializePage(int id)
|| id == m_maemoOptionsPageId) {
QList<Utils::WizardProgressItem *> order;
order << m_genericItem;
- if (isQtPlatformSelected(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM))
+ if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MAEMO_FREMANTLE_PLATFORM)))
order << m_maemoItem;
- if (isQtPlatformSelected(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM))
+ if (isQtPlatformSelected(QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM)))
order << m_harmattanItem;
order << itemOfNextGenericPage();
@@ -253,7 +254,7 @@ Core::GeneratedFiles AbstractMobileAppWizard::generateFiles(const QWizard *wizar
app()->setOrientation(wdlg->m_genericOptionsPage->orientation());
app()->setPngIcon64(wdlg->m_maemoOptionsPage->pngIcon());
app()->setPngIcon80(wdlg->m_harmattanOptionsPage->pngIcon());
- if (wdlg->isQtPlatformSelected(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM))
+ if (wdlg->isQtPlatformSelected(QLatin1String(QtSupport::Constants::MEEGO_HARMATTAN_PLATFORM)))
app()->setSupportsMeegoBooster(wdlg->m_harmattanOptionsPage->supportsBooster());
prepareGenerateFiles(wizard, errorMessage);
return app()->generateFiles(errorMessage);
diff --git a/src/plugins/qt4projectmanager/wizards/consoleappwizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/consoleappwizarddialog.cpp
index 573f134360..41bfe92efc 100644
--- a/src/plugins/qt4projectmanager/wizards/consoleappwizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/consoleappwizarddialog.cpp
@@ -53,7 +53,7 @@ ConsoleAppWizardDialog::ConsoleAppWizardDialog(const QString &templateName,
"provide a GUI."));
addModulesPage();
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
addExtensionPages(parameters.extensionPages());
diff --git a/src/plugins/qt4projectmanager/wizards/emptyprojectwizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/emptyprojectwizarddialog.cpp
index 7cf219371e..0201d89b2a 100644
--- a/src/plugins/qt4projectmanager/wizards/emptyprojectwizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/emptyprojectwizarddialog.cpp
@@ -45,7 +45,7 @@ EmptyProjectWizardDialog::EmptyProjectWizardDialog(const QString &templateName,
setIntroDescription(tr("This wizard generates an empty Qt project. "
"Add files to it later on by using the other wizards."));
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
addExtensionPages(parameters.extensionPages());
diff --git a/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp b/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp
index 382862d914..28091fe2b0 100644
--- a/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/guiappwizard.cpp
@@ -149,7 +149,7 @@ static inline bool generateFormClass(const GuiAppParameters &params,
}
}
if (headerContents.isEmpty() || sourceContents.isEmpty()) {
- *errorMessage = QString::fromAscii("Failed to obtain Designer plugin code generation service.");
+ *errorMessage = QString::fromLatin1("Failed to obtain Designer plugin code generation service.");
return false;
}
diff --git a/src/plugins/qt4projectmanager/wizards/guiappwizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/guiappwizarddialog.cpp
index c1d408565c..79d5b28b1b 100644
--- a/src/plugins/qt4projectmanager/wizards/guiappwizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/guiappwizarddialog.cpp
@@ -64,7 +64,7 @@ GuiAppWizardDialog::GuiAppWizardDialog(const QString &templateName,
"and includes an empty widget."));
addModulesPage();
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage(isMobile);
m_filesPage->setFormInputCheckable(true);
diff --git a/src/plugins/qt4projectmanager/wizards/libraryparameters.cpp b/src/plugins/qt4projectmanager/wizards/libraryparameters.cpp
index 0da9197243..762a356b2a 100644
--- a/src/plugins/qt4projectmanager/wizards/libraryparameters.cpp
+++ b/src/plugins/qt4projectmanager/wizards/libraryparameters.cpp
@@ -111,15 +111,13 @@ void LibraryParameters::generateCode(QtProjectParameters:: Type t,
// Is this a QObject (plugin)
const bool inheritsQObject = t == QtProjectParameters::Qt4Plugin;
- if (inheritsQObject) {
+ if (inheritsQObject)
headerStr << namespaceIndent << indent << "Q_OBJECT\n";
- }
headerStr << namespaceIndent << "public:\n";
- if (inheritsQObject) {
+ if (inheritsQObject)
headerStr << namespaceIndent << indent << unqualifiedClassName << "(QObject *parent = 0);\n";
- } else {
+ else
headerStr << namespaceIndent << indent << unqualifiedClassName << "();\n";
- }
headerStr << namespaceIndent << "};\n\n";
Utils::writeClosingNameSpaces(namespaceList, indent, headerStr);
headerStr << "#endif // "<< guard << '\n';
diff --git a/src/plugins/qt4projectmanager/wizards/librarywizard.cpp b/src/plugins/qt4projectmanager/wizards/librarywizard.cpp
index f70c04d826..a94333f56a 100644
--- a/src/plugins/qt4projectmanager/wizards/librarywizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/librarywizard.cpp
@@ -99,7 +99,7 @@ Core::GeneratedFiles LibraryWizard::generateFiles(const QWizard *w,
// Create files: global header for shared libs
QString globalHeaderFileName;
if (projectParams.type == QtProjectParameters::SharedLibrary) {
- const QString globalHeaderName = buildFileName(projectPath, projectParams.fileName + QLatin1String(sharedHeaderPostfixC), headerSuffix());
+ const QString globalHeaderName = buildFileName(projectPath, projectParams.fileName.toLower() + QLatin1String(sharedHeaderPostfixC), headerSuffix());
Core::GeneratedFile globalHeader(globalHeaderName);
globalHeaderFileName = QFileInfo(globalHeader.path()).fileName();
globalHeader.setContents(CppTools::AbstractEditorSupport::licenseTemplate(globalHeaderFileName)
diff --git a/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp
index acf49d2b70..46b93787aa 100644
--- a/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/librarywizarddialog.cpp
@@ -152,7 +152,7 @@ LibraryWizardDialog::LibraryWizardDialog(const QString &templateName,
// Use the intro page instead, set up initially
setIntroDescription(tr("This wizard generates a C++ library project."));
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS)) {
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS))) {
m_targetPageId = addTargetSetupPage();
m_mobilePageId = addPage(m_mobilePage);
}
@@ -168,12 +168,10 @@ LibraryWizardDialog::LibraryWizardDialog(const QString &templateName,
Utils::WizardProgressItem *introItem = wizardProgress()->item(startId());
Utils::WizardProgressItem *targetItem = 0;
Utils::WizardProgressItem *mobileItem = 0;
- if (m_targetPageId != -1) {
+ if (m_targetPageId != -1)
targetItem = wizardProgress()->item(m_targetPageId);
- }
- if (m_mobilePageId != -1) {
+ if (m_mobilePageId != -1)
mobileItem = wizardProgress()->item(m_mobilePageId);
- }
Utils::WizardProgressItem *modulesItem = wizardProgress()->item(m_modulesPageId);
Utils::WizardProgressItem *filesItem = wizardProgress()->item(m_filesPageId);
filesItem->setTitle(tr("Details"));
@@ -357,9 +355,8 @@ LibraryParameters LibraryWizardDialog::libraryParameters() const
rc.sourceFileName = m_filesPage->sourceFileName();
rc.headerFileName = m_filesPage->headerFileName();
if (!rc.baseClassName.isEmpty())
- if (const PluginBaseClasses *plb = findPluginBaseClass(rc.baseClassName)) {
+ if (const PluginBaseClasses *plb = findPluginBaseClass(rc.baseClassName))
rc.baseClassModule = QLatin1String(plb->module);
- }
return rc;
}
diff --git a/src/plugins/qt4projectmanager/wizards/mobileappwizardpages.cpp b/src/plugins/qt4projectmanager/wizards/mobileappwizardpages.cpp
index f4299203fb..2ec27aba2c 100644
--- a/src/plugins/qt4projectmanager/wizards/mobileappwizardpages.cpp
+++ b/src/plugins/qt4projectmanager/wizards/mobileappwizardpages.cpp
@@ -153,7 +153,7 @@ public:
saver.setAutoRemove(false);
if (!saver.hasError())
saver.setResult(m_pixmap.save(
- saver.file(), QFileInfo(m_iconPath).suffix().toAscii().constData()));
+ saver.file(), QFileInfo(m_iconPath).suffix().toLatin1().constData()));
if (!saver.finalize()) {
QMessageBox::critical(QApplication::activeWindow(),
tr("File Error"),
diff --git a/src/plugins/qt4projectmanager/wizards/qtquickapp.cpp b/src/plugins/qt4projectmanager/wizards/qtquickapp.cpp
index dbff8834d2..97db161444 100644
--- a/src/plugins/qt4projectmanager/wizards/qtquickapp.cpp
+++ b/src/plugins/qt4projectmanager/wizards/qtquickapp.cpp
@@ -42,53 +42,6 @@
namespace Qt4ProjectManager {
namespace Internal {
-const QString qmldir(QLatin1String("qmldir"));
-const QString qmldir_plugin(QLatin1String("plugin"));
-
-QmlModule::QmlModule(const QString &uri, const QFileInfo &rootDir, const QFileInfo &qmldir,
- bool isExternal, QtQuickApp *qtQuickApp)
- : uri(uri)
- , rootDir(rootDir)
- , qmldir(qmldir)
- , isExternal(isExternal)
- , qtQuickApp(qtQuickApp)
-{}
-
-QString QmlModule::path(Path path) const
-{
- switch (path) {
- case Root: {
- return rootDir.canonicalFilePath();
- }
- case ContentDir: {
- const QDir proFile(qtQuickApp->path(QtQuickApp::AppProPath));
- return proFile.relativeFilePath(qmldir.canonicalPath());
- }
- case ContentBase: {
- const QString localRoot = rootDir.canonicalFilePath() + QLatin1Char('/');
- QDir contentDir = qmldir.dir();
- contentDir.cdUp();
- const QString localContentDir = contentDir.canonicalPath();
- return localContentDir.right(localContentDir.length() - localRoot.length());
- }
- case DeployedContentBase: {
- const QString modulesDir = qtQuickApp->path(QtQuickApp::ModulesDir);
- return modulesDir + QLatin1Char('/') + this->path(ContentBase);
- }
- default: qFatal("QmlModule::path() needs more work");
- }
- return QString();
-}
-
-QmlCppPlugin::QmlCppPlugin(const QString &name, const QFileInfo &path,
- const QmlModule *module, const QFileInfo &proFile)
- : name(name)
- , path(path)
- , module(module)
- , proFile(proFile)
-{
-}
-
QtQuickApp::QtQuickApp()
: AbstractMobileApp()
, m_mainQmlMode(ModeGenerate)
@@ -97,11 +50,6 @@ QtQuickApp::QtQuickApp()
m_canSupportMeegoBooster = true;
}
-QtQuickApp::~QtQuickApp()
-{
- clearModulesAndPlugins();
-}
-
void QtQuickApp::setComponentSet(ComponentSet componentSet)
{
m_componentSet = componentSet;
@@ -124,47 +72,6 @@ QtQuickApp::Mode QtQuickApp::mainQmlMode() const
return m_mainQmlMode;
}
-bool QtQuickApp::setExternalModules(const QStringList &uris,
- const QStringList &importPaths)
-{
- clearModulesAndPlugins();
- m_importPaths.clear();
- foreach (const QFileInfo &importPath, importPaths) {
- if (!importPath.exists()) {
- m_error = QCoreApplication::translate(
- "Qt4ProjectManager::Internal::QtQuickApp",
- "The QML import path '%1' cannot be found.")
- .arg(QDir::toNativeSeparators(importPath.filePath()));
- return false;
- } else {
- m_importPaths.append(importPath.canonicalFilePath());
- }
- }
- foreach (const QString &uri, uris) {
- QString uriPath = uri;
- uriPath.replace(QLatin1Char('.'), QLatin1Char('/'));
- const int modulesCount = m_modules.count();
- foreach (const QFileInfo &importPath, m_importPaths) {
- const QFileInfo qmlDirFile(
- importPath.absoluteFilePath() + QLatin1Char('/')
- + uriPath + QLatin1Char('/') + qmldir);
- if (qmlDirFile.exists()) {
- if (!addExternalModule(uri, importPath, qmlDirFile))
- return false;
- break;
- }
- }
- if (modulesCount == m_modules.count()) { // no module was added
- m_error = QCoreApplication::translate(
- "Qt4ProjectManager::Internal::QtQuickApp",
- "The QML module '%1' cannot be found.").arg(uri);
- return false;
- }
- }
- m_error.clear();
- return true;
-}
-
QString QtQuickApp::pathExtended(int fileType) const
{
const bool importQmlFile = m_mainQmlMode == ModeImport;
@@ -199,7 +106,6 @@ QString QtQuickApp::pathExtended(int fileType) const
case QmlDir: return pathBase + qmlSubDir;
case QmlDirProFileRelative: return importQmlFile ? appProFilePath.relativeFilePath(m_mainQmlFile.canonicalPath())
: QString(qmlSubDir).remove(qmlSubDir.length() - 1, 1);
- case ModulesDir: return QLatin1String("modules");
default: qFatal("QtQuickApp::pathExtended() needs more work");
}
return QString();
@@ -220,14 +126,9 @@ bool QtQuickApp::adaptCurrentMainCppTemplateLine(QString &line) const
{
const QLatin1Char quote('"');
- if (line.contains(QLatin1String("// MAINQML"))) {
+ if (line.contains(QLatin1String("// MAINQML")))
insertParameter(line, quote + path(MainQmlDeployed) + quote);
- } else if (line.contains(QLatin1String("// ADDIMPORTPATH"))) {
- if (m_modules.isEmpty())
- return false;
- else
- insertParameter(line, quote + path(ModulesDir) + quote);
- }
+
return true;
}
@@ -240,17 +141,7 @@ void QtQuickApp::handleCurrentProFileTemplateLine(const QString &line,
QString nextLine = proFileTemplate.readLine(); // eats 'QML_IMPORT_PATH ='
if (!nextLine.startsWith(QLatin1String("QML_IMPORT_PATH =")))
return;
-
- proFile << nextLine;
-
- const QLatin1String separator(" \\\n ");
- const QDir proPath(path(AppProPath));
- foreach (const QString &importPath, m_importPaths) {
- const QString relativePath = proPath.relativeFilePath(importPath);
- proFile << separator << relativePath;
- }
-
- proFile << endl;
+ proFile << nextLine << endl;
} else if (line.contains(QLatin1String("# HARMATTAN_BOOSTABLE"))) {
QString nextLine = proFileTemplate.readLine(); // eats '# CONFIG += qdeclarative-boostable'
if (supportsMeegoBooster())
@@ -259,83 +150,6 @@ void QtQuickApp::handleCurrentProFileTemplateLine(const QString &line,
}
}
-void QtQuickApp::clearModulesAndPlugins()
-{
- qDeleteAll(m_modules);
- m_modules.clear();
- qDeleteAll(m_cppPlugins);
- m_cppPlugins.clear();
-}
-
-bool QtQuickApp::addCppPlugin(const QString &qmldirLine, QmlModule *module)
-{
- const QStringList qmldirLineElements =
- qmldirLine.split(QLatin1Char(' '), QString::SkipEmptyParts);
- if (qmldirLineElements.count() < 2) {
- m_error = QCoreApplication::translate(
- "Qt4ProjectManager::Internal::QtQuickApp",
- "Invalid '%1' entry in '%2' of module '%3'.")
- .arg(qmldir_plugin).arg(qmldir).arg(module->uri);
- return false;
- }
- const QString name = qmldirLineElements.at(1);
- const QFileInfo path(module->qmldir.dir(), qmldirLineElements.value(2, QString()));
-
- // TODO: Add more magic to find a good .pro file..
- const QString proFileName = name + QLatin1String(".pro");
- const QFileInfo proFile_guess1(module->qmldir.dir(), proFileName);
- const QFileInfo proFile_guess2(QString(module->qmldir.dir().absolutePath() + QLatin1String("/../")),
- proFileName);
- const QFileInfo proFile_guess3(module->qmldir.dir(),
- QFileInfo(module->qmldir.path()).fileName() + QLatin1String(".pro"));
- const QFileInfo proFile_guess4(proFile_guess3.absolutePath() + QLatin1String("/../")
- + proFile_guess3.fileName());
-
- QFileInfo foundProFile;
- if (proFile_guess1.exists()) {
- foundProFile = proFile_guess1.canonicalFilePath();
- } else if (proFile_guess2.exists()) {
- foundProFile = proFile_guess2.canonicalFilePath();
- } else if (proFile_guess3.exists()) {
- foundProFile = proFile_guess3.canonicalFilePath();
- } else if (proFile_guess4.exists()) {
- foundProFile = proFile_guess4.canonicalFilePath();
- } else {
- m_error = QCoreApplication::translate(
- "Qt4ProjectManager::Internal::QtQuickApp",
- "No .pro file for plugin '%1' can be found.").arg(name);
- return false;
- }
- QmlCppPlugin *plugin =
- new QmlCppPlugin(name, path, module, foundProFile);
- m_cppPlugins.append(plugin);
- module->cppPlugins.insert(name, plugin);
- return true;
-}
-
-bool QtQuickApp::addCppPlugins(QmlModule *module)
-{
- QFile qmlDirFile(module->qmldir.absoluteFilePath());
- if (qmlDirFile.open(QIODevice::ReadOnly)) {
- QTextStream in(&qmlDirFile);
- QString line;
- while (!(line = in.readLine()).isNull()) {
- line = line.trimmed();
- if (line.startsWith(qmldir_plugin) && !addCppPlugin(line, module))
- return false;
- };
- }
- return true;
-}
-
-bool QtQuickApp::addExternalModule(const QString &name, const QFileInfo &dir,
- const QFileInfo &contentDir)
-{
- QmlModule *module = new QmlModule(name, dir, contentDir, true, this);
- m_modules.append(module);
- return addCppPlugins(module);
-}
-
#ifndef CREATORLESSTEST
Core::GeneratedFiles QtQuickApp::generateFiles(QString *errorMessage) const
{
@@ -360,11 +174,6 @@ bool QtQuickApp::useExistingMainQml() const
return !m_mainQmlFile.filePath().isEmpty();
}
-const QList<QmlModule*> QtQuickApp::modules() const
-{
- return m_modules;
-}
-
QString QtQuickApp::appViewerBaseName() const
{
return QLatin1String(m_componentSet == QtQuick20Components ?
@@ -418,7 +227,7 @@ QByteArray QtQuickApp::generateFileExtended(int fileType,
int QtQuickApp::stubVersionMinor() const
{
- return m_componentSet == QtQuick20Components ? 1 : 22;
+ return m_componentSet == QtQuick20Components ? 2 : 22;
}
QList<AbstractGeneratedFileInfo> QtQuickApp::updateableFiles(const QString &mainProFile) const
@@ -454,9 +263,6 @@ QList<DeploymentFolder> QtQuickApp::deploymentFolders() const
{
QList<DeploymentFolder> result;
result.append(DeploymentFolder(path(QmlDirProFileRelative), QLatin1String("qml")));
- foreach (const QmlModule *module, m_modules)
- if (module->isExternal)
- result.append(DeploymentFolder(module->path(QmlModule::ContentDir), module->path(QmlModule::DeployedContentBase)));
return result;
}
diff --git a/src/plugins/qt4projectmanager/wizards/qtquickapp.h b/src/plugins/qt4projectmanager/wizards/qtquickapp.h
index e7268ef23c..772b9bb252 100644
--- a/src/plugins/qt4projectmanager/wizards/qtquickapp.h
+++ b/src/plugins/qt4projectmanager/wizards/qtquickapp.h
@@ -38,42 +38,6 @@
namespace Qt4ProjectManager {
namespace Internal {
-class QtQuickApp;
-struct QmlCppPlugin;
-
-struct QmlModule
-{
- enum Path {
- // Example: Module "com.foo.bar" in "c:/modules/".
- // "qmldir" file is in "c:/modules/com/foo/bar/".
- // Application .pro file is "c:/app/app.pro".
- Root, // "c:/modules/" (absolute)
- ContentDir, // "../modules/com/foo/bar" (relative form .pro file)
- ContentBase, // "com/foo/"
- DeployedContentBase // "<qmlmodules>/com/foo" (on deploy target)
- };
-
- QmlModule(const QString &name, const QFileInfo &rootDir, const QFileInfo &qmldir,
- bool isExternal, QtQuickApp *qtQuickApp);
- QString path(Path path) const;
- const QString uri; // "com.foo.bar"
- const QFileInfo rootDir; // Location of "com/"
- const QFileInfo qmldir; // 'qmldir' file.
- const bool isExternal; // Either external or inside a source paths
- const QtQuickApp *qtQuickApp;
- QHash<QString, QmlCppPlugin *> cppPlugins; // Just as info. No ownership.
-};
-
-struct QmlCppPlugin
-{
- QmlCppPlugin(const QString &name, const QFileInfo &path,
- const QmlModule *module, const QFileInfo &proFile);
- const QString name; // Original name
- const QFileInfo path; // Plugin path where qmldir points to
- const QmlModule *module;
- const QFileInfo proFile; // .pro file for the plugin
-};
-
struct QtQuickAppGeneratedFileInfo : public AbstractGeneratedFileInfo
{
enum ExtendedFileType {
@@ -102,7 +66,6 @@ public:
AppViewerHOrigin,
QmlDir,
QmlDirProFileRelative,
- ModulesDir,
MainPageQml,
MainPageQmlOrigin
};
@@ -119,14 +82,12 @@ public:
};
QtQuickApp();
- virtual ~QtQuickApp();
void setComponentSet(ComponentSet componentSet);
ComponentSet componentSet() const;
void setMainQml(Mode mode, const QString &file = QString());
Mode mainQmlMode() const;
- bool setExternalModules(const QStringList &uris, const QStringList &importPaths);
#ifndef CREATORLESSTEST
virtual Core::GeneratedFiles generateFiles(QString *errorMessage) const;
@@ -134,7 +95,6 @@ public:
bool generateFiles(QString *errorMessage) const;
#endif // CREATORLESSTEST
bool useExistingMainQml() const;
- const QList<QmlModule*> modules() const;
static const int StubVersion;
@@ -157,18 +117,10 @@ private:
QList<AbstractGeneratedFileInfo> updateableFiles(const QString &mainProFile) const;
QList<DeploymentFolder> deploymentFolders() const;
- bool addExternalModule(const QString &uri, const QFileInfo &dir,
- const QFileInfo &contentDir);
- bool addCppPlugins(QmlModule *module);
- bool addCppPlugin(const QString &qmldirLine, QmlModule *module);
- void clearModulesAndPlugins();
QString componentSetDir(ComponentSet componentSet) const;
QFileInfo m_mainQmlFile;
Mode m_mainQmlMode;
- QStringList m_importPaths;
- QList<QmlModule *> m_modules;
- QList<QmlCppPlugin *> m_cppPlugins;
ComponentSet m_componentSet;
};
diff --git a/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp b/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp
index bfbe9c163d..332590506c 100644
--- a/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/qtquickappwizard.cpp
@@ -93,9 +93,8 @@ QtQuickAppWizardDialog::QtQuickAppWizardDialog(QWidget *parent,
bool QtQuickAppWizardDialog::validateCurrentPage()
{
- if (currentPage() == m_componentOptionsPage) {
+ if (currentPage() == m_componentOptionsPage)
setIgnoreGenericOptionsPage(false);
- }
return AbstractMobileAppWizardDialog::validateCurrentPage();
}
@@ -167,7 +166,7 @@ void QtQuickAppWizard::createInstances(ExtensionSystem::IPlugin *plugin)
"platform.\n\nRequires <b>Qt 4.7.4</b> or newer, and the "
"component set installed for your Qt version."));
parameter.setRequiredFeatures(basicFeatures | Core::Feature(QtSupport::Constants::FEATURE_QTQUICK_COMPONENTS_MEEGO)
- | QtSupport::Constants::FEATURE_QT_QUICK_1_1);
+ | Core::Feature(QtSupport::Constants::FEATURE_QT_QUICK_1_1));
list << parameter;
parameter = base;
@@ -195,7 +194,7 @@ Core::BaseFileWizardParameters QtQuickAppWizard::baseParameters()
parameters.setIcon(QIcon(QLatin1String(Qt4ProjectManager::Constants::ICON_QTQUICK_APP)));
parameters.setId(QLatin1String("D.QMLA Application"));
parameters.setCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY));
- parameters.setDisplayCategory(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY);
+ parameters.setDisplayCategory(QLatin1String(ProjectExplorer::Constants::QT_APPLICATION_WIZARD_CATEGORY_DISPLAY));
return parameters;
}
diff --git a/src/plugins/qt4projectmanager/wizards/qtwizard.cpp b/src/plugins/qt4projectmanager/wizards/qtwizard.cpp
index d9aca1c8cb..90d7067843 100644
--- a/src/plugins/qt4projectmanager/wizards/qtwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/qtwizard.cpp
@@ -168,7 +168,7 @@ CustomQt4ProjectWizard::CustomQt4ProjectWizard(const Core::BaseFileWizardParamet
{
BaseQt4ProjectWizardDialog *wizard = new BaseQt4ProjectWizardDialog(false, parent, wizardDialogParameters);
- if (!wizardDialogParameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!wizardDialogParameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
wizard->addTargetSetupPage(false, targetPageId);
initProjectWizardDialog(wizard, wizardDialogParameters.defaultPath(),
@@ -192,7 +192,8 @@ BaseQt4ProjectWizardDialog::BaseQt4ProjectWizardDialog(bool showModulesPage, QWi
ProjectExplorer::BaseProjectWizardDialog(parent, parameters),
m_modulesPage(0),
m_targetSetupPage(0),
- m_profileIds(parameters.extraValues().value(ProjectExplorer::Constants::PROJECT_KIT_IDS).value<QList<Core::Id> >())
+ m_profileIds(parameters.extraValues().value(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ .value<QList<Core::Id> >())
{
init(showModulesPage);
}
@@ -204,7 +205,8 @@ BaseQt4ProjectWizardDialog::BaseQt4ProjectWizardDialog(bool showModulesPage,
ProjectExplorer::BaseProjectWizardDialog(introPage, introId, parent, parameters),
m_modulesPage(0),
m_targetSetupPage(0),
- m_profileIds(parameters.extraValues().value(ProjectExplorer::Constants::PROJECT_KIT_IDS).value<QList<Core::Id> >())
+ m_profileIds(parameters.extraValues().value(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ .value<QList<Core::Id> >())
{
init(showModulesPage);
}
diff --git a/src/plugins/qt4projectmanager/wizards/subdirsprojectwizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/subdirsprojectwizarddialog.cpp
index 81e3bd96c9..188e4cc8b0 100644
--- a/src/plugins/qt4projectmanager/wizards/subdirsprojectwizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/subdirsprojectwizarddialog.cpp
@@ -46,7 +46,7 @@ SubdirsProjectWizardDialog::SubdirsProjectWizardDialog(const QString &templateNa
setIntroDescription(tr("This wizard generates a Qt subdirs project. "
"Add subprojects to it later on by using the other wizards."));
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
addExtensionPages(parameters.extensionPages());
diff --git a/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp b/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
index 14649e1abf..b41a9e1409 100644
--- a/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
+++ b/src/plugins/qt4projectmanager/wizards/targetsetuppage.cpp
@@ -80,6 +80,9 @@ public:
void setupUi(QWidget *q)
{
QWidget *setupTargetPage = new QWidget(q);
+ descriptionLabel = new QLabel(setupTargetPage);
+ descriptionLabel->setWordWrap(true);
+ descriptionLabel->setVisible(false);
headerLabel = new QLabel(setupTargetPage);
headerLabel->setWordWrap(true);
@@ -89,9 +92,6 @@ public:
noValidKitLabel->setWordWrap(true);
noValidKitLabel->setText(TargetSetupPage::tr("<span style=\" font-weight:600;\">No valid kits found.</span>"));
- descriptionLabel = new QLabel(setupTargetPage);
- descriptionLabel->setWordWrap(true);
- descriptionLabel->setVisible(false);
optionHintLabel = new QLabel(setupTargetPage);
optionHintLabel->setWordWrap(true);
@@ -625,8 +625,8 @@ void TargetSetupPage::updateVisibility()
void TargetSetupPage::openOptions()
{
- Core::ICore::instance()->showOptionsDialog(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY),
- QLatin1String(ProjectExplorer::Constants::KITS_SETTINGS_PAGE_ID),
+ Core::ICore::instance()->showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ ProjectExplorer::Constants::KITS_SETTINGS_PAGE_ID,
this);
}
diff --git a/src/plugins/qt4projectmanager/wizards/testwizard.cpp b/src/plugins/qt4projectmanager/wizards/testwizard.cpp
index fe7a596156..4d2758dff8 100644
--- a/src/plugins/qt4projectmanager/wizards/testwizard.cpp
+++ b/src/plugins/qt4projectmanager/wizards/testwizard.cpp
@@ -120,9 +120,8 @@ static QString generateTestCode(const TestWizardParameters &testParams,
}
// Test slot with data or dummy
writeVoidMemberBody(str, testParams.className, testParams.testSlot, false);
- if (testParams.useDataSet) {
+ if (testParams.useDataSet)
str << indent << "QFETCH(" << testDataTypeC << ", data);\n";
- }
switch (testParams.type) {
case TestWizardParameters::Test:
str << indent << "QVERIFY2(true, \"Failure\");\n";
diff --git a/src/plugins/qt4projectmanager/wizards/testwizarddialog.cpp b/src/plugins/qt4projectmanager/wizards/testwizarddialog.cpp
index 5c802ead36..fa90d9e5d8 100644
--- a/src/plugins/qt4projectmanager/wizards/testwizarddialog.cpp
+++ b/src/plugins/qt4projectmanager/wizards/testwizarddialog.cpp
@@ -61,7 +61,7 @@ TestWizardDialog::TestWizardDialog(const QString &templateName,
setWindowIcon(icon);
setWindowTitle(templateName);
setSelectedModules(QLatin1String("core testlib"), true);
- if (!parameters.extraValues().contains(ProjectExplorer::Constants::PROJECT_KIT_IDS))
+ if (!parameters.extraValues().contains(QLatin1String(ProjectExplorer::Constants::PROJECT_KIT_IDS)))
addTargetSetupPage();
m_modulesPageId = addModulesPage();
m_testPageId = addPage(m_testPage);
diff --git a/src/plugins/qtsupport/baseqtversion.cpp b/src/plugins/qtsupport/baseqtversion.cpp
index b52ccef155..988c5d9777 100644
--- a/src/plugins/qtsupport/baseqtversion.cpp
+++ b/src/plugins/qtsupport/baseqtversion.cpp
@@ -47,6 +47,8 @@
#include <utils/persistentsettings.h>
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
+#include <utils/qtcassert.h>
#include <utils/synchronousprocess.h>
#include <QDir>
@@ -57,6 +59,7 @@
using namespace QtSupport;
using namespace QtSupport::Internal;
+using namespace Utils;
static const char QTVERSIONID[] = "Id";
static const char QTVERSIONNAME[] = "Name";
@@ -163,7 +166,7 @@ int BaseQtVersion::getUniqueId()
return QtVersionManager::instance()->getUniqueId();
}
-BaseQtVersion::BaseQtVersion(const Utils::FileName &qmakeCommand, bool isAutodetected, const QString &autodetectionSource)
+BaseQtVersion::BaseQtVersion(const FileName &qmakeCommand, bool isAutodetected, const QString &autodetectionSource)
: m_id(getUniqueId()),
m_isAutodetected(isAutodetected),
m_autodetectionSource(autodetectionSource),
@@ -183,7 +186,6 @@ BaseQtVersion::BaseQtVersion(const Utils::FileName &qmakeCommand, bool isAutodet
m_qmakeIsExecutable(true)
{
ctor(qmakeCommand);
- setDisplayName(defaultDisplayName(qtVersionString(), qmakeCommand, false));
}
BaseQtVersion::BaseQtVersion()
@@ -203,10 +205,10 @@ BaseQtVersion::BaseQtVersion()
m_hasDocumentation(false),
m_qmakeIsExecutable(true)
{
- ctor(Utils::FileName());
+ ctor(FileName());
}
-void BaseQtVersion::ctor(const Utils::FileName &qmakePath)
+void BaseQtVersion::ctor(const FileName &qmakePath)
{
m_qmakeCommand = qmakePath;
m_designerCommand.clear();
@@ -224,7 +226,7 @@ BaseQtVersion::~BaseQtVersion()
{
}
-QString BaseQtVersion::defaultDisplayName(const QString &versionString, const Utils::FileName &qmakePath,
+QString BaseQtVersion::defaultDisplayName(const QString &versionString, const FileName &qmakePath,
bool fromPath)
{
QString location;
@@ -266,12 +268,10 @@ Core::FeatureSet BaseQtVersion::availableFeatures() const
features |= Core::FeatureSet(QtSupport::Constants::FEATURE_QT_QUICK);
features |= Core::FeatureSet(QtSupport::Constants::FEATURE_QT_QUICK_1);
}
- if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 1)) {
+ if (qtVersion() >= QtSupport::QtVersionNumber(4, 7, 1))
features |= Core::FeatureSet(QtSupport::Constants::FEATURE_QT_QUICK_1_1);
- }
- if (qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0)) {
+ if (qtVersion() >= QtSupport::QtVersionNumber(5, 0, 0))
features |= Core::FeatureSet(QtSupport::Constants::FEATURE_QT_QUICK_2);
- }
return features;
}
@@ -317,12 +317,47 @@ QList<ProjectExplorer::Task> BaseQtVersion::validateKit(const ProjectExplorer::K
version->displayName(),
qtAbiString);
result << ProjectExplorer::Task(ProjectExplorer::Task::Error,
- message, Utils::FileName(), -1,
+ message, FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM));
} // Abi mismatch
return result;
}
+FileName BaseQtVersion::headerPath() const
+{
+ return Utils::FileName::fromUserInput(qmakeProperty("QT_INSTALL_HEADERS"));
+}
+
+FileName BaseQtVersion::libraryPath() const
+{
+ return Utils::FileName::fromUserInput(qmakeProperty("QT_INSTALL_LIBS"));
+}
+
+FileName BaseQtVersion::binPath() const
+{
+ return Utils::FileName::fromUserInput(qmakeProperty("QT_HOST_BINS"));
+}
+
+Utils::FileName QtSupport::BaseQtVersion::mkspecsPath() const
+{
+ Utils::FileName result = Utils::FileName::fromUserInput(qmakeProperty("QT_HOST_DATA"));
+ if (result.isEmpty())
+ result = Utils::FileName::fromUserInput(qmakeProperty("QMAKE_MKSPECS"));
+ else
+ result.appendPath(QLatin1String("mkspecs"));
+ return result;
+}
+
+QString QtSupport::BaseQtVersion::qtNamespace() const
+{
+ return qmakeProperty("QT_NAMESPACE");
+}
+
+QString QtSupport::BaseQtVersion::qtLibInfix() const
+{
+ return qmakeProperty("QT_LIBINFIX");
+}
+
void BaseQtVersion::setId(int id)
{
m_id = id;
@@ -340,7 +375,7 @@ void BaseQtVersion::fromMap(const QVariantMap &map)
QString string = map.value(QLatin1String(QTVERSIONQMAKEPATH)).toString();
if (string.startsWith(QLatin1Char('~')))
string.remove(0, 1).prepend(QDir::homePath());
- ctor(Utils::FileName::fromString(string));
+ ctor(FileName::fromString(string));
}
QVariantMap BaseQtVersion::toMap() const
@@ -399,9 +434,9 @@ QStringList BaseQtVersion::warningReason() const
return ret;
}
-ProjectExplorer::ToolChain *BaseQtVersion::preferredToolChain(const Utils::FileName &ms) const
+ProjectExplorer::ToolChain *BaseQtVersion::preferredToolChain(const FileName &ms) const
{
- const Utils::FileName spec = ms.isEmpty() ? mkspec() : ms;
+ const FileName spec = ms.isEmpty() ? mkspec() : ms;
QList<ProjectExplorer::ToolChain *> tcList = ProjectExplorer::ToolChainManager::instance()->toolChains();
ProjectExplorer::ToolChain *possibleTc = 0;
foreach (ProjectExplorer::ToolChain *tc, tcList) {
@@ -415,7 +450,7 @@ ProjectExplorer::ToolChain *BaseQtVersion::preferredToolChain(const Utils::FileN
return possibleTc;
}
-Utils::FileName BaseQtVersion::qmakeCommand() const
+FileName BaseQtVersion::qmakeCommand() const
{
return m_qmakeCommand;
}
@@ -570,10 +605,10 @@ void BaseQtVersion::updateSourcePath() const
}
}
}
- m_sourcePath = Utils::FileName::fromUserInput(sourcePath);
+ m_sourcePath = FileName::fromUserInput(sourcePath);
}
-Utils::FileName BaseQtVersion::sourcePath() const
+FileName BaseQtVersion::sourcePath() const
{
updateSourcePath();
return m_sourcePath;
@@ -652,46 +687,43 @@ QString BaseQtVersion::findQtBinary(Binaries binary) const
QStringList possibleCommands;
switch (binary) {
case QmlScene: {
-#if defined(Q_OS_WIN)
- possibleCommands << QLatin1String("qmlscene.exe");
-#else
- possibleCommands << QLatin1String("qmlscene");
-#endif
+ if (HostOsInfo::isWindowsHost())
+ possibleCommands << QLatin1String("qmlscene.exe");
+ else
+ possibleCommands << QLatin1String("qmlscene");
}
case QmlViewer: {
-#if defined(Q_OS_WIN)
- possibleCommands << QLatin1String("qmlviewer.exe");
-#elif defined(Q_OS_MAC)
- possibleCommands << QLatin1String("QMLViewer.app/Contents/MacOS/QMLViewer");
-#else
- possibleCommands << QLatin1String("qmlviewer");
-#endif
+ if (HostOsInfo::isWindowsHost())
+ possibleCommands << QLatin1String("qmlviewer.exe");
+ else if (HostOsInfo::isMacHost())
+ possibleCommands << QLatin1String("QMLViewer.app/Contents/MacOS/QMLViewer");
+ else
+ possibleCommands << QLatin1String("qmlviewer");
}
break;
case Designer:
-#if defined(Q_OS_WIN)
- possibleCommands << QLatin1String("designer.exe");
-#elif defined(Q_OS_MAC)
- possibleCommands << QLatin1String("Designer.app/Contents/MacOS/Designer");
-#else
- possibleCommands << QLatin1String("designer");
-#endif
+ if (HostOsInfo::isWindowsHost())
+ possibleCommands << QLatin1String("designer.exe");
+ else if (HostOsInfo::isMacHost())
+ possibleCommands << QLatin1String("Designer.app/Contents/MacOS/Designer");
+ else
+ possibleCommands << QLatin1String("designer");
break;
case Linguist:
-#if defined(Q_OS_WIN)
- possibleCommands << QLatin1String("linguist.exe");
-#elif defined(Q_OS_MAC)
- possibleCommands << QLatin1String("Linguist.app/Contents/MacOS/Linguist");
-#else
- possibleCommands << QLatin1String("linguist");
-#endif
+ if (HostOsInfo::isWindowsHost())
+ possibleCommands << QLatin1String("linguist.exe");
+ else if (HostOsInfo::isMacHost())
+ possibleCommands << QLatin1String("Linguist.app/Contents/MacOS/Linguist");
+ else
+ possibleCommands << QLatin1String("linguist");
break;
case Uic:
-#ifdef Q_OS_WIN
- possibleCommands << QLatin1String("uic.exe");
-#else
- possibleCommands << QLatin1String("uic-qt4") << QLatin1String("uic4") << QLatin1String("uic");
-#endif
+ if (HostOsInfo::isWindowsHost()) {
+ possibleCommands << QLatin1String("uic.exe");
+ } else {
+ possibleCommands << QLatin1String("uic-qt4") << QLatin1String("uic4")
+ << QLatin1String("uic");
+ }
break;
default:
Q_ASSERT(false);
@@ -726,13 +758,13 @@ void BaseQtVersion::updateMkspec() const
if (m_mkspecFullPath.isEmpty())
return;
- Utils::FileName baseMkspecDir = mkspecDirectoryFromVersionInfo(versionInfo());
+ FileName baseMkspecDir = mkspecDirectoryFromVersionInfo(versionInfo());
if (m_mkspec.isChildOf(baseMkspecDir)) {
m_mkspec = m_mkspec.relativeChildPath(baseMkspecDir);
// qDebug() << "Setting mkspec to"<<mkspec;
} else {
- Utils::FileName sourceMkSpecPath = sourcePath().appendPath(QLatin1String("mkspecs"));
+ FileName sourceMkSpecPath = sourcePath().appendPath(QLatin1String("mkspecs"));
if (m_mkspec.isChildOf(sourceMkSpecPath)) {
m_mkspec = m_mkspec.relativeChildPath(sourceMkSpecPath);
} else {
@@ -750,7 +782,7 @@ void BaseQtVersion::ensureMkSpecParsed() const
if (mkspecPath().isEmpty())
return;
- QMakeGlobals option;
+ ProFileGlobals option;
option.setProperties(versionInfo());
ProMessageHandler msgHandler(true);
ProFileCacheManager::instance()->incRefCount();
@@ -783,22 +815,22 @@ void BaseQtVersion::parseMkSpec(ProFileEvaluator *evaluator) const
m_mkspecValues.insert(declarativeBins, evaluator->value(declarativeBins));
}
-Utils::FileName BaseQtVersion::mkspec() const
+FileName BaseQtVersion::mkspec() const
{
updateMkspec();
return m_mkspec;
}
-Utils::FileName BaseQtVersion::mkspecFor(ProjectExplorer::ToolChain *tc) const
+FileName BaseQtVersion::mkspecFor(ProjectExplorer::ToolChain *tc) const
{
Utils::FileName versionSpec = mkspec();
if (!tc)
return versionSpec;
- const QList<Utils::FileName> tcSpecList = tc->suggestedMkspecList();
+ const QList<FileName> tcSpecList = tc->suggestedMkspecList();
if (tcSpecList.contains(versionSpec))
return versionSpec;
- foreach (const Utils::FileName &tcSpec, tcSpecList) {
+ foreach (const FileName &tcSpec, tcSpecList) {
if (hasMkspec(tcSpec))
return tcSpec;
}
@@ -806,13 +838,13 @@ Utils::FileName BaseQtVersion::mkspecFor(ProjectExplorer::ToolChain *tc) const
return versionSpec;
}
-Utils::FileName BaseQtVersion::mkspecPath() const
+FileName BaseQtVersion::mkspecPath() const
{
updateMkspec();
return m_mkspecFullPath;
}
-bool BaseQtVersion::hasMkspec(const Utils::FileName &spec) const
+bool BaseQtVersion::hasMkspec(const FileName &spec) const
{
updateVersionInfo();
QFileInfo fi;
@@ -867,8 +899,11 @@ void BaseQtVersion::updateVersionInfo() const
m_hasQmlDebuggingLibrary = false;
m_hasQmlObserver = false;
- if (!queryQMakeVariables(qmakeCommand(), &m_versionInfo, &m_qmakeIsExecutable))
+ if (!queryQMakeVariables(qmakeCommand(), qmakeRunEnvironment(), &m_versionInfo)) {
+ m_qmakeIsExecutable = false;
return;
+ }
+ m_qmakeIsExecutable = true;
const QString qtInstallData = qmakeProperty("QT_INSTALL_DATA");
const QString qtInstallBins = qmakeProperty("QT_INSTALL_BINS");
@@ -966,12 +1001,11 @@ QString BaseQtVersion::demosPath() const
QString BaseQtVersion::frameworkInstallPath() const
{
-#ifdef Q_OS_MAC
- updateVersionInfo();
- return m_versionInfo.value(QLatin1String("QT_INSTALL_LIBS"));
-#else
+ if (HostOsInfo::isMacHost()) {
+ updateVersionInfo();
+ return m_versionInfo.value(QLatin1String("QT_INSTALL_LIBS"));
+ }
return QString();
-#endif
}
bool BaseQtVersion::hasExamples() const
@@ -994,13 +1028,23 @@ QList<ProjectExplorer::HeaderPath> BaseQtVersion::systemHeaderPathes(const Proje
return result;
}
-void BaseQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const
+void BaseQtVersion::addToEnvironment(const ProjectExplorer::Kit *k, Environment &env) const
{
Q_UNUSED(k);
env.set(QLatin1String("QTDIR"), QDir::toNativeSeparators(qmakeProperty("QT_HOST_DATA")));
env.prependOrSetPath(qmakeProperty("QT_HOST_BINS"));
}
+// Some Qt versions may require environment settings for qmake to work
+//
+// One such example is Blackberry which for some reason decided to always use the same
+// qmake and use environment variables embedded in their mkspecs to make that point to
+// the different Qt installations.
+Utils::Environment BaseQtVersion::qmakeRunEnvironment() const
+{
+ return Utils::Environment::systemEnvironment();
+}
+
bool BaseQtVersion::hasGdbDebuggingHelper() const
{
updateVersionInfo();
@@ -1038,10 +1082,10 @@ bool BaseQtVersion::hasQmlObserver() const
return m_hasQmlObserver;
}
-Utils::Environment BaseQtVersion::qmlToolsEnvironment() const
+Environment BaseQtVersion::qmlToolsEnvironment() const
{
// FIXME: This seems broken!
- Utils::Environment environment = Utils::Environment::systemEnvironment();
+ Environment environment = Environment::systemEnvironment();
#if 0 // FIXME: Fix this!
addToEnvironment(environment);
#endif
@@ -1127,7 +1171,7 @@ QList<ProjectExplorer::Task> BaseQtVersion::reportIssuesImpl(const QString &proF
if (!isValid()) {
//: %1: Reason for being invalid
const QString msg = QCoreApplication::translate("Qt4ProjectManager::QtVersion", "The Qt version is invalid: %1").arg(invalidReason());
- results.append(ProjectExplorer::Task(ProjectExplorer::Task::Error, msg, Utils::FileName(), -1,
+ results.append(ProjectExplorer::Task(ProjectExplorer::Task::Error, msg, FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
}
@@ -1137,7 +1181,7 @@ QList<ProjectExplorer::Task> BaseQtVersion::reportIssuesImpl(const QString &proF
//: %1: Path to qmake executable
const QString msg = QCoreApplication::translate("Qt4ProjectManager::QtVersion",
"The qmake command \"%1\" was not found or is not executable.").arg(qmakeCommand().toUserOutput());
- results.append(ProjectExplorer::Task(ProjectExplorer::Task::Error, msg, Utils::FileName(), -1,
+ results.append(ProjectExplorer::Task(ProjectExplorer::Task::Error, msg, FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
}
@@ -1148,13 +1192,13 @@ QList<ProjectExplorer::Task> BaseQtVersion::reportIssuesImpl(const QString &proF
if ((tmpBuildDir.startsWith(sourcePath)) && (tmpBuildDir != sourcePath)) {
const QString msg = QCoreApplication::translate("Qt4ProjectManager::QtVersion",
"Qmake does not support build directories below the source directory.");
- results.append(ProjectExplorer::Task(ProjectExplorer::Task::Warning, msg, Utils::FileName(), -1,
+ results.append(ProjectExplorer::Task(ProjectExplorer::Task::Warning, msg, FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
} else if (tmpBuildDir.count(slash) != sourcePath.count(slash) && qtVersion() < QtVersionNumber(4,8, 0)) {
const QString msg = QCoreApplication::translate("Qt4ProjectManager::QtVersion",
"The build directory needs to be at the same level as the source directory.");
- results.append(ProjectExplorer::Task(ProjectExplorer::Task::Warning, msg, Utils::FileName(), -1,
+ results.append(ProjectExplorer::Task(ProjectExplorer::Task::Warning, msg, FileName(), -1,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)));
}
@@ -1169,25 +1213,16 @@ BaseQtVersion::reportIssues(const QString &proFile, const QString &buildDir) con
return results;
}
-ProjectExplorer::IOutputParser *BaseQtVersion::createOutputParser() const
-{
- return new ProjectExplorer::GnuMakeParser;
-}
-
QtConfigWidget *BaseQtVersion::createConfigurationWidget() const
{
return 0;
}
-bool BaseQtVersion::queryQMakeVariables(const Utils::FileName &binary, QHash<QString, QString> *versionInfo)
+static QByteArray runQmakeQuery(const FileName &binary, const Environment &env,
+ QString *error)
{
- bool qmakeIsExecutable;
- return BaseQtVersion::queryQMakeVariables(binary, versionInfo, &qmakeIsExecutable);
-}
+ QTC_ASSERT(error, return QByteArray());
-static QByteArray runQmakeQuery(const Utils::FileName &binary, const Utils::Environment &env,
- bool *isExecutable)
-{
const int timeOutMS = 30000; // Might be slow on some machines.
QProcess process;
@@ -1195,38 +1230,40 @@ static QByteArray runQmakeQuery(const Utils::FileName &binary, const Utils::Envi
process.start(binary.toString(), QStringList(QLatin1String("-query")), QIODevice::ReadOnly);
if (!process.waitForStarted()) {
- qWarning("Cannot start '%s': %s", qPrintable(binary.toUserOutput()), qPrintable(process.errorString()));
- *isExecutable = false;
+ *error = QCoreApplication::translate("QtVersion", "Cannot start '%1': %2").arg(binary.toUserOutput()).arg(process.errorString());
return QByteArray();
}
if (!process.waitForFinished(timeOutMS)) {
- Utils::SynchronousProcess::stopProcess(process);
- *isExecutable = true;
- qWarning("Timeout running '%s' (%dms).", qPrintable(binary.toUserOutput()), timeOutMS);
+ SynchronousProcess::stopProcess(process);
+ *error = QCoreApplication::translate("QtVersion", "Timeout running '%1' (%2ms).").arg(binary.toUserOutput()).arg(timeOutMS);
return QByteArray();
}
if (process.exitStatus() != QProcess::NormalExit) {
- qWarning("'%s' crashed.", qPrintable(binary.toUserOutput()));
- *isExecutable = false;
+ *error = QCoreApplication::translate("QtVersion", "'%1' crashed.").arg(binary.toUserOutput());
return QByteArray();
}
- *isExecutable = true;
+ error->clear();
return process.readAllStandardOutput();
}
-bool BaseQtVersion::queryQMakeVariables(const Utils::FileName &binary, QHash<QString, QString> *versionInfo,
- bool *qmakeIsExecutable)
+bool BaseQtVersion::queryQMakeVariables(const FileName &binary, const Environment &env,
+ QHash<QString, QString> *versionInfo, QString *error)
{
+ QString tmp;
+ if (!error)
+ error = &tmp;
+
const QFileInfo qmake = binary.toFileInfo();
- *qmakeIsExecutable = qmake.exists() && qmake.isExecutable() && !qmake.isDir();
- if (!*qmakeIsExecutable)
+ if (!qmake.exists() || !qmake.isExecutable() || qmake.isDir()) {
+ *error = QCoreApplication::translate("QtVersion", "qmake '%1' is not a executable").arg(binary.toUserOutput());
return false;
+ }
QByteArray output;
- output = runQmakeQuery(binary, Utils::Environment::systemEnvironment(), qmakeIsExecutable);
+ output = runQmakeQuery(binary, env, error);
- if (output.isNull() && !*qmakeIsExecutable) {
+ if (output.isNull() && !error->isEmpty()) {
// Note: Don't rerun if we were able to execute the binary before.
// Try running qmake with all kinds of tool chains set up in the environment.
@@ -1237,10 +1274,10 @@ bool BaseQtVersion::queryQMakeVariables(const Utils::FileName &binary, QHash<QSt
foreach (ProjectExplorer::ToolChain *tc, tcList) {
if (!abiList.contains(tc->targetAbi()))
continue;
- Utils::Environment env = Utils::Environment::systemEnvironment();
- tc->addToEnvironment(env);
- output = runQmakeQuery(binary, env, qmakeIsExecutable);
- if (*qmakeIsExecutable)
+ Environment realEnv = env;
+ tc->addToEnvironment(realEnv);
+ output = runQmakeQuery(binary, realEnv, error);
+ if (error->isEmpty())
break;
}
}
@@ -1278,19 +1315,19 @@ bool BaseQtVersion::queryQMakeVariables(const Utils::FileName &binary, QHash<QSt
return true;
}
-Utils::FileName BaseQtVersion::mkspecDirectoryFromVersionInfo(const QHash<QString, QString> &versionInfo)
+FileName BaseQtVersion::mkspecDirectoryFromVersionInfo(const QHash<QString, QString> &versionInfo)
{
QString dataDir = qmakeProperty(versionInfo, "QT_HOST_DATA");
if (dataDir.isEmpty())
- return Utils::FileName();
- return Utils::FileName::fromUserInput(dataDir + QLatin1String("/mkspecs"));
+ return FileName();
+ return FileName::fromUserInput(dataDir + QLatin1String("/mkspecs"));
}
-Utils::FileName BaseQtVersion::mkspecFromVersionInfo(const QHash<QString, QString> &versionInfo)
+FileName BaseQtVersion::mkspecFromVersionInfo(const QHash<QString, QString> &versionInfo)
{
- Utils::FileName baseMkspecDir = mkspecDirectoryFromVersionInfo(versionInfo);
+ FileName baseMkspecDir = mkspecDirectoryFromVersionInfo(versionInfo);
if (baseMkspecDir.isEmpty())
- return Utils::FileName();
+ return FileName();
bool qt5 = false;
QString theSpec = qmakeProperty(versionInfo, "QMAKE_XSPEC");
@@ -1299,67 +1336,66 @@ Utils::FileName BaseQtVersion::mkspecFromVersionInfo(const QHash<QString, QStrin
else
qt5 = true;
- Utils::FileName mkspecFullPath = baseMkspecDir;
+ FileName mkspecFullPath = baseMkspecDir;
mkspecFullPath.appendPath(theSpec);
// qDebug() << "default mkspec is located at" << mkspecFullPath;
-#ifdef Q_OS_WIN
- if (!qt5) {
- QFile f2(mkspecFullPath.toString() + QLatin1String("/qmake.conf"));
- if (f2.exists() && f2.open(QIODevice::ReadOnly)) {
- while (!f2.atEnd()) {
- QByteArray line = f2.readLine();
- if (line.startsWith("QMAKESPEC_ORIGINAL")) {
- const QList<QByteArray> &temp = line.split('=');
- if (temp.size() == 2) {
- QString possibleFullPath = QString::fromLocal8Bit(temp.at(1).trimmed().constData());
- // We sometimes get a mix of different slash styles here...
- possibleFullPath = possibleFullPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
- if (QFileInfo(possibleFullPath).exists()) // Only if the path exists
- mkspecFullPath = Utils::FileName::fromUserInput(possibleFullPath);
+ if (HostOsInfo::isWindowsHost()) {
+ if (!qt5) {
+ QFile f2(mkspecFullPath.toString() + QLatin1String("/qmake.conf"));
+ if (f2.exists() && f2.open(QIODevice::ReadOnly)) {
+ while (!f2.atEnd()) {
+ QByteArray line = f2.readLine();
+ if (line.startsWith("QMAKESPEC_ORIGINAL")) {
+ const QList<QByteArray> &temp = line.split('=');
+ if (temp.size() == 2) {
+ QString possibleFullPath = QString::fromLocal8Bit(temp.at(1).trimmed().constData());
+ // We sometimes get a mix of different slash styles here...
+ possibleFullPath = possibleFullPath.replace(QLatin1Char('\\'), QLatin1Char('/'));
+ if (QFileInfo(possibleFullPath).exists()) // Only if the path exists
+ mkspecFullPath = FileName::fromUserInput(possibleFullPath);
+ }
+ break;
}
- break;
}
+ f2.close();
}
- f2.close();
}
- }
-#else
-# ifdef Q_OS_MAC
- QFile f2(mkspecFullPath.toString() + QLatin1String("/qmake.conf"));
- if (f2.exists() && f2.open(QIODevice::ReadOnly)) {
- while (!f2.atEnd()) {
- QByteArray line = f2.readLine();
- if (line.startsWith("MAKEFILE_GENERATOR")) {
- const QList<QByteArray> &temp = line.split('=');
- if (temp.size() == 2) {
- const QByteArray &value = temp.at(1);
- if (value.contains("XCODE")) {
- // we don't want to generate xcode projects...
-// qDebug() << "default mkspec is xcode, falling back to g++";
- return baseMkspecDir.appendPath(QLatin1String("macx-g++"));
+ } else {
+ if (HostOsInfo::isMacHost()) {
+ QFile f2(mkspecFullPath.toString() + QLatin1String("/qmake.conf"));
+ if (f2.exists() && f2.open(QIODevice::ReadOnly)) {
+ while (!f2.atEnd()) {
+ QByteArray line = f2.readLine();
+ if (line.startsWith("MAKEFILE_GENERATOR")) {
+ const QList<QByteArray> &temp = line.split('=');
+ if (temp.size() == 2) {
+ const QByteArray &value = temp.at(1);
+ if (value.contains("XCODE")) {
+ // we don't want to generate xcode projects...
+ // qDebug() << "default mkspec is xcode, falling back to g++";
+ return baseMkspecDir.appendPath(QLatin1String("macx-g++"));
+ }
+ }
+ break;
}
}
- break;
+ f2.close();
}
}
- f2.close();
- }
-# endif
- if (!qt5) {
- //resolve mkspec link
- QString rspec = mkspecFullPath.toFileInfo().readLink();
- if (!rspec.isEmpty())
- mkspecFullPath = Utils::FileName::fromUserInput(
- QDir(baseMkspecDir.toString()).absoluteFilePath(rspec));
+ if (!qt5) {
+ //resolve mkspec link
+ QString rspec = mkspecFullPath.toFileInfo().readLink();
+ if (!rspec.isEmpty())
+ mkspecFullPath = FileName::fromUserInput(
+ QDir(baseMkspecDir.toString()).absoluteFilePath(rspec));
+ }
}
-#endif
-
return mkspecFullPath;
}
-Utils::FileName BaseQtVersion::qtCorePath(const QHash<QString,QString> &versionInfo, const QString &versionString)
+FileName BaseQtVersion::qtCorePath(const QHash<QString,QString> &versionInfo, const QString &versionString)
{
QStringList dirs;
dirs << qmakeProperty(versionInfo, "QT_INSTALL_LIBS")
@@ -1377,7 +1413,7 @@ Utils::FileName BaseQtVersion::qtCorePath(const QHash<QString,QString> &versionI
&& file.startsWith(QLatin1String("QtCore"))
&& file.endsWith(QLatin1String(".framework"))) {
// handle Framework
- Utils::FileName lib(info);
+ FileName lib(info);
lib.appendPath(file.left(file.lastIndexOf(QLatin1Char('.'))));
return lib;
}
@@ -1393,18 +1429,18 @@ Utils::FileName BaseQtVersion::qtCorePath(const QHash<QString,QString> &versionI
|| file.endsWith(QString::fromLatin1(".so.") + versionString)
|| file.endsWith(QLatin1String(".so"))
|| file.endsWith(QLatin1Char('.') + versionString + QLatin1String(".dylib")))
- return Utils::FileName(info);
+ return FileName(info);
}
}
}
}
// Return path to first static library found:
if (!staticLibs.isEmpty())
- return Utils::FileName(staticLibs.at(0));
- return Utils::FileName();
+ return FileName(staticLibs.at(0));
+ return FileName();
}
-QList<ProjectExplorer::Abi> BaseQtVersion::qtAbisFromLibrary(const Utils::FileName &coreLibrary)
+QList<ProjectExplorer::Abi> BaseQtVersion::qtAbisFromLibrary(const FileName &coreLibrary)
{
return ProjectExplorer::Abi::abisOfBinary(coreLibrary);
}
diff --git a/src/plugins/qtsupport/baseqtversion.h b/src/plugins/qtsupport/baseqtversion.h
index dc9eb03891..f9f9cf76cd 100644
--- a/src/plugins/qtsupport/baseqtversion.h
+++ b/src/plugins/qtsupport/baseqtversion.h
@@ -131,6 +131,7 @@ public:
static QString qmakeProperty(const QHash<QString,QString> &versionInfo, const QByteArray &name);
QString qmakeProperty(const QByteArray &name) const;
virtual void addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const;
+ virtual Utils::Environment qmakeRunEnvironment() const;
virtual Utils::FileName sourcePath() const;
// used by QtUiCodeModelSupport
@@ -185,14 +186,11 @@ public:
/// warnings and finally info items.
QList<ProjectExplorer::Task> reportIssues(const QString &proFile, const QString &buildDir) const;
- virtual ProjectExplorer::IOutputParser *createOutputParser() const;
-
- static bool queryQMakeVariables(const Utils::FileName &binary, QHash<QString, QString> *versionInfo);
- static bool queryQMakeVariables(const Utils::FileName &binary, QHash<QString, QString> *versionInfo, bool *qmakeIsExecutable);
+ static bool queryQMakeVariables(const Utils::FileName &binary, const Utils::Environment &env,
+ QHash<QString, QString> *versionInfo, QString *error = 0);
static Utils::FileName mkspecDirectoryFromVersionInfo(const QHash<QString, QString> &versionInfo);
static Utils::FileName mkspecFromVersionInfo(const QHash<QString, QString> &versionInfo);
-
virtual bool supportsBinaryDebuggingHelper() const;
virtual QString gdbDebuggingHelperLibrary() const;
virtual QString qmlDebuggingHelperLibrary(bool debugVersion) const;
@@ -221,6 +219,14 @@ public:
virtual QList<ProjectExplorer::Task> validateKit(const ProjectExplorer::Kit *k);
+ Utils::FileName headerPath() const;
+ Utils::FileName libraryPath() const;
+ Utils::FileName binPath() const;
+ Utils::FileName mkspecsPath() const;
+
+ QString qtNamespace() const;
+ QString qtLibInfix() const;
+
protected:
BaseQtVersion();
BaseQtVersion(const Utils::FileName &path, bool isAutodetected = false, const QString &autodetectionSource = QString());
diff --git a/src/plugins/qtsupport/customexecutablerunconfiguration.cpp b/src/plugins/qtsupport/customexecutablerunconfiguration.cpp
index 84c5f100dd..0104e3849f 100644
--- a/src/plugins/qtsupport/customexecutablerunconfiguration.cpp
+++ b/src/plugins/qtsupport/customexecutablerunconfiguration.cpp
@@ -54,29 +54,22 @@ using namespace QtSupport;
using namespace QtSupport::Internal;
namespace {
-const char * const CUSTOM_EXECUTABLE_ID("ProjectExplorer.CustomExecutableRunConfiguration");
+const char CUSTOM_EXECUTABLE_ID[] = "ProjectExplorer.CustomExecutableRunConfiguration";
-const char * const EXECUTABLE_KEY("ProjectExplorer.CustomExecutableRunConfiguration.Executable");
-const char * const ARGUMENTS_KEY("ProjectExplorer.CustomExecutableRunConfiguration.Arguments");
-const char * const WORKING_DIRECTORY_KEY("ProjectExplorer.CustomExecutableRunConfiguration.WorkingDirectory");
-const char * const USE_TERMINAL_KEY("ProjectExplorer.CustomExecutableRunConfiguration.UseTerminal");
-const char * const USER_ENVIRONMENT_CHANGES_KEY("ProjectExplorer.CustomExecutableRunConfiguration.UserEnvironmentChanges");
-const char * const BASE_ENVIRONMENT_BASE_KEY("ProjectExplorer.CustomExecutableRunConfiguration.BaseEnvironmentBase");
+const char EXECUTABLE_KEY[] = "ProjectExplorer.CustomExecutableRunConfiguration.Executable";
+const char ARGUMENTS_KEY[] = "ProjectExplorer.CustomExecutableRunConfiguration.Arguments";
+const char WORKING_DIRECTORY_KEY[] = "ProjectExplorer.CustomExecutableRunConfiguration.WorkingDirectory";
+const char USE_TERMINAL_KEY[] = "ProjectExplorer.CustomExecutableRunConfiguration.UseTerminal";
+const char USER_ENVIRONMENT_CHANGES_KEY[] = "ProjectExplorer.CustomExecutableRunConfiguration.UserEnvironmentChanges";
+const char BASE_ENVIRONMENT_BASE_KEY[] = "ProjectExplorer.CustomExecutableRunConfiguration.BaseEnvironmentBase";
}
void CustomExecutableRunConfiguration::ctor()
{
setDefaultDisplayName(defaultDisplayName());
- connect(target(), SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
- this, SLOT(activeBuildConfigurationChanged()));
-
- m_lastActiveBuildConfiguration = activeBuildConfiguration();
-
- if (m_lastActiveBuildConfiguration) {
- connect(m_lastActiveBuildConfiguration, SIGNAL(environmentChanged()),
- this, SIGNAL(baseEnvironmentChanged()));
- }
+ connect(target(), SIGNAL(environmentChanged()),
+ this, SIGNAL(baseEnvironmentChanged()));
}
CustomExecutableRunConfiguration::CustomExecutableRunConfiguration(ProjectExplorer::Target *parent) :
@@ -106,19 +99,6 @@ CustomExecutableRunConfiguration::~CustomExecutableRunConfiguration()
{
}
-void CustomExecutableRunConfiguration::activeBuildConfigurationChanged()
-{
- if (m_lastActiveBuildConfiguration) {
- disconnect(m_lastActiveBuildConfiguration, SIGNAL(environmentChanged()),
- this, SIGNAL(baseEnvironmentChanged()));
- }
- m_lastActiveBuildConfiguration = activeBuildConfiguration();
- if (m_lastActiveBuildConfiguration) {
- connect(m_lastActiveBuildConfiguration, SIGNAL(environmentChanged()),
- this, SIGNAL(baseEnvironmentChanged()));
- }
-}
-
// Dialog embedding the CustomExecutableConfigurationWidget
// prompting the user to complete the configuration.
class CustomExecutableDialog : public QDialog
@@ -280,6 +260,8 @@ Utils::Environment CustomExecutableRunConfiguration::baseEnvironment() const
} else if (m_baseEnvironmentBase == CustomExecutableRunConfiguration::BuildEnvironmentBase) {
if (activeBuildConfiguration())
env = activeBuildConfiguration()->environment();
+ else
+ env = Utils::Environment::systemEnvironment(); // fall back
}
return env;
}
diff --git a/src/plugins/qtsupport/customexecutablerunconfiguration.h b/src/plugins/qtsupport/customexecutablerunconfiguration.h
index d277cdf796..bf2f35cce2 100644
--- a/src/plugins/qtsupport/customexecutablerunconfiguration.h
+++ b/src/plugins/qtsupport/customexecutablerunconfiguration.h
@@ -32,7 +32,7 @@
#include "qtsupport_global.h"
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <utils/environment.h>
@@ -87,9 +87,6 @@ signals:
void baseEnvironmentChanged();
void userEnvironmentChangesChanged(const QList<Utils::EnvironmentItem> &diff);
-private slots:
- void activeBuildConfigurationChanged();
-
protected:
CustomExecutableRunConfiguration(ProjectExplorer::Target *parent,
CustomExecutableRunConfiguration *source);
@@ -127,7 +124,6 @@ private:
QString m_userName;
QList<Utils::EnvironmentItem> m_userEnvironmentChanges;
BaseEnvironmentBase m_baseEnvironmentBase;
- ProjectExplorer::BuildConfiguration *m_lastActiveBuildConfiguration;
};
class CustomExecutableRunConfigurationFactory : public ProjectExplorer::IRunConfigurationFactory
diff --git a/src/plugins/qtsupport/debugginghelper.cpp b/src/plugins/qtsupport/debugginghelper.cpp
index c48ca69e71..4085b3e9f1 100644
--- a/src/plugins/qtsupport/debugginghelper.cpp
+++ b/src/plugins/qtsupport/debugginghelper.cpp
@@ -99,7 +99,7 @@ QString DebuggingHelperLibrary::copy(const QString &qtInstallData,
const QStringList directories = DebuggingHelperLibrary::debuggingHelperLibraryDirectories(qtInstallData);
// Try to find a writeable directory.
- foreach(const QString &directory, directories)
+ foreach (const QString &directory, directories)
if (copyFiles(sourcePath(), sourceFileNames(), directory, errorMessage)) {
errorMessage->clear();
return directory;
diff --git a/src/plugins/qtsupport/debugginghelperbuildtask.cpp b/src/plugins/qtsupport/debugginghelperbuildtask.cpp
index b7042fa16c..3442dd1d46 100644
--- a/src/plugins/qtsupport/debugginghelperbuildtask.cpp
+++ b/src/plugins/qtsupport/debugginghelperbuildtask.cpp
@@ -224,9 +224,8 @@ bool DebuggingHelperBuildTask::buildDebuggingHelper(QFutureInterface<void> &futu
}
log(output, error);
- if (!success) {
+ if (!success)
return false;
- }
}
future.setProgressValue(4);
@@ -247,9 +246,8 @@ bool DebuggingHelperBuildTask::buildDebuggingHelper(QFutureInterface<void> &futu
success = false;
}
log(output, error);
- if (!success) {
+ if (!success)
return false;
- }
}
future.setProgressValue(5);
return true;
diff --git a/src/plugins/qtsupport/exampleslistmodel.cpp b/src/plugins/qtsupport/exampleslistmodel.cpp
index 9f9e392ea2..2c0f7a3468 100644
--- a/src/plugins/qtsupport/exampleslistmodel.cpp
+++ b/src/plugins/qtsupport/exampleslistmodel.cpp
@@ -29,28 +29,23 @@
#include "exampleslistmodel.h"
-#include <QFile>
+#include <QDebug>
#include <QDir>
+#include <QFile>
#include <QUrl>
#include <QXmlStreamReader>
-#include <QDebug>
-
-#include <coreplugin/icore.h>
#include <coreplugin/helpmanager.h>
+#include <coreplugin/icore.h>
+#include <projectexplorer/kitmanager.h>
+#include <qtsupport/qtkitinformation.h>
#include <qtsupport/qtversionmanager.h>
+#include <utils/environment.h>
#include <utils/qtcassert.h>
-#include <utils/environment.h>
-#include <projectexplorer/kitmanager.h>
-#include <qtsupport/qtkitinformation.h>
#include <algorithm>
-using QtSupport::QtVersionManager;
-using QtSupport::BaseQtVersion;
-
namespace QtSupport {
-
namespace Internal {
ExamplesListModel::ExamplesListModel(QObject *parent) :
@@ -85,7 +80,7 @@ ExamplesListModel::ExamplesListModel(QObject *parent) :
SLOT(handleQtVersionsChanged()));
}
-static inline QString fixStringForTags(const QString &string)
+static QString fixStringForTags(const QString &string)
{
QString returnString = string;
returnString.remove(QLatin1String("<i>"));
@@ -95,7 +90,7 @@ static inline QString fixStringForTags(const QString &string)
return returnString;
}
-static inline QStringList trimStringList(const QStringList &stringlist)
+static QStringList trimStringList(const QStringList &stringlist)
{
QStringList returnList;
foreach (const QString &string, stringlist)
@@ -112,7 +107,7 @@ static QString relativeOrInstallPath(const QString &path, const QString &manifes
const QString installResolvedPath = installPath + slash + path;
if (QFile::exists(relativeResolvedPath))
return relativeResolvedPath;
- else if (QFile::exists(installResolvedPath))
+ if (QFile::exists(installResolvedPath))
return installResolvedPath;
// doesn't exist, just return relative
return relativeResolvedPath;
@@ -151,11 +146,9 @@ static bool isValidExampleOrDemo(ExampleItem &item)
return ok || debugExamples();
}
-QList<ExampleItem> ExamplesListModel::parseExamples(QXmlStreamReader *reader,
- const QString &projectsOffset,
- const QString &examplesInstallPath)
+void ExamplesListModel::parseExamples(QXmlStreamReader *reader,
+ const QString &projectsOffset, const QString &examplesInstallPath)
{
- QList<ExampleItem> examples;
ExampleItem item;
const QChar slash = QLatin1Char('/');
while (!reader->atEnd()) {
@@ -175,7 +168,7 @@ QList<ExampleItem> ExamplesListModel::parseExamples(QXmlStreamReader *reader,
item.filesToOpen.append(relativeOrInstallPath(reader->readElementText(QXmlStreamReader::ErrorOnUnexpectedElement),
projectsOffset, examplesInstallPath));
} else if (reader->name() == QLatin1String("description")) {
- item.description = fixStringForTags(reader->readElementText(QXmlStreamReader::ErrorOnUnexpectedElement));
+ item.description = fixStringForTags(reader->readElementText(QXmlStreamReader::ErrorOnUnexpectedElement));
} else if (reader->name() == QLatin1String("dependency")) {
item.dependencies.append(projectsOffset + slash + reader->readElementText(QXmlStreamReader::ErrorOnUnexpectedElement));
} else if (reader->name() == QLatin1String("tags")) {
@@ -188,23 +181,20 @@ QList<ExampleItem> ExamplesListModel::parseExamples(QXmlStreamReader *reader,
case QXmlStreamReader::EndElement:
if (reader->name() == QLatin1String("example")) {
if (isValidExampleOrDemo(item))
- examples.append(item);
+ m_exampleItems.append(item);
} else if (reader->name() == QLatin1String("examples")) {
- return examples;
+ return;
}
break;
default: // nothing
break;
}
}
- return examples;
}
-QList<ExampleItem> ExamplesListModel::parseDemos(QXmlStreamReader *reader,
- const QString &projectsOffset,
- const QString &demosInstallPath)
+void ExamplesListModel::parseDemos(QXmlStreamReader *reader,
+ const QString &projectsOffset, const QString &demosInstallPath)
{
- QList<ExampleItem> demos;
ExampleItem item;
const QChar slash = QLatin1Char('/');
while (!reader->atEnd()) {
@@ -234,21 +224,19 @@ QList<ExampleItem> ExamplesListModel::parseDemos(QXmlStreamReader *reader,
case QXmlStreamReader::EndElement:
if (reader->name() == QLatin1String("demo")) {
if (isValidExampleOrDemo(item))
- demos.append(item);
+ m_exampleItems.append(item);
} else if (reader->name() == QLatin1String("demos")) {
- return demos;
+ return;
}
break;
default: // nothing
break;
}
}
- return demos;
}
-QList<ExampleItem> ExamplesListModel::parseTutorials(QXmlStreamReader* reader, const QString& projectsOffset)
+void ExamplesListModel::parseTutorials(QXmlStreamReader *reader, const QString &projectsOffset)
{
- QList<ExampleItem> tutorials;
ExampleItem item;
const QChar slash = QLatin1Char('/');
while (!reader->atEnd()) {
@@ -285,16 +273,14 @@ QList<ExampleItem> ExamplesListModel::parseTutorials(QXmlStreamReader* reader, c
break;
case QXmlStreamReader::EndElement:
if (reader->name() == QLatin1String("tutorial"))
- tutorials.append(item);
+ m_exampleItems.append(item);
else if (reader->name() == QLatin1String("tutorials"))
- return tutorials;
+ return;
break;
default: // nothing
break;
}
}
-
- return tutorials;
}
void ExamplesListModel::handleQtVersionsChanged()
@@ -305,15 +291,20 @@ void ExamplesListModel::handleQtVersionsChanged()
void ExamplesListModel::updateExamples()
{
- clear();
QString examplesInstallPath;
QString demosInstallPath;
QString examplesFallback;
QString demosFallback;
QString sourceFallback;
- foreach (const QString &exampleSource,
- exampleSources(&examplesInstallPath, &demosInstallPath,
- &examplesFallback, &demosFallback, &sourceFallback)) {
+
+ QStringList sources = exampleSources(&examplesInstallPath, &demosInstallPath,
+ &examplesFallback, &demosFallback, &sourceFallback);
+
+ beginResetModel();
+ m_tags.clear();
+ m_exampleItems.clear();
+
+ foreach (const QString &exampleSource, sources) {
QFile exampleFile(exampleSource);
if (!exampleFile.open(QIODevice::ReadOnly)) {
if (debugExamples())
@@ -345,11 +336,11 @@ void ExamplesListModel::updateExamples()
switch (reader.readNext()) {
case QXmlStreamReader::StartElement:
if (reader.name() == QLatin1String("examples"))
- addItems(parseExamples(&reader, examplesDir.path(), examplesInstallPath));
+ parseExamples(&reader, examplesDir.path(), examplesInstallPath);
else if (reader.name() == QLatin1String("demos"))
- addItems(parseDemos(&reader, demosDir.path(), demosInstallPath));
+ parseDemos(&reader, demosDir.path(), demosInstallPath);
else if (reader.name() == QLatin1String("tutorials"))
- addItems(parseTutorials(&reader, examplesDir.path()));
+ parseTutorials(&reader, examplesDir.path());
break;
default: // nothing
break;
@@ -358,6 +349,7 @@ void ExamplesListModel::updateExamples()
if (reader.hasError() && debugExamples())
qWarning() << QString::fromLatin1("ERROR: Could not parse file as XML document ('%1')").arg(exampleSource);
}
+ endResetModel();
m_tags.sort();
m_tags.erase(std::unique(m_tags.begin(), m_tags.end()), m_tags.end());
@@ -476,40 +468,21 @@ QStringList ExamplesListModel::exampleSources(QString *examplesInstallPath, QStr
return sources;
}
-void ExamplesListModel::clear()
-{
- if (exampleItems.count() > 0) {
- beginRemoveRows(QModelIndex(), 0, exampleItems.size()-1);
- exampleItems.clear();
- endRemoveRows();
- }
- m_tags.clear();
-}
-
-void ExamplesListModel::addItems(const QList<ExampleItem> &newItems)
-{
- if (newItems.isEmpty())
- return;
- beginInsertRows(QModelIndex(), exampleItems.size(), exampleItems.size() - 1 + newItems.size());
- exampleItems.append(newItems);
- endInsertRows();
-}
-
int ExamplesListModel::rowCount(const QModelIndex &) const
{
ensureInitialized();
- return exampleItems.size();
+ return m_exampleItems.size();
}
QVariant ExamplesListModel::data(const QModelIndex &index, int role) const
{
ensureInitialized();
- if (!index.isValid() || index.row()+1 > exampleItems.count()) {
+ if (!index.isValid() || index.row()+1 > m_exampleItems.count()) {
qDebug() << Q_FUNC_INFO << "invalid index requested";
return QVariant();
}
- ExampleItem item = exampleItems.at(index.row());
+ ExampleItem item = m_exampleItems.at(index.row());
switch (role)
{
case Qt::DisplayRole: // for search only
@@ -548,7 +521,6 @@ QVariant ExamplesListModel::data(const QModelIndex &index, int role) const
qDebug() << Q_FUNC_INFO << "role type not supported";
return QVariant();
}
-
}
QStringList ExamplesListModel::tags() const
@@ -590,12 +562,11 @@ void ExamplesListModelFilter::updateFilter()
}
}
-bool containsSubString(const QStringList& list, const QString& substr, Qt::CaseSensitivity cs)
+bool containsSubString(const QStringList &list, const QString &substr, Qt::CaseSensitivity cs)
{
- foreach (const QString &elem, list) {
+ foreach (const QString &elem, list)
if (elem.contains(substr, cs))
return true;
- }
return false;
}
@@ -617,10 +588,9 @@ bool ExamplesListModelFilter::filterAcceptsRow(int sourceRow, const QModelIndex
const QStringList tags = sourceModel()->index(sourceRow, 0, sourceParent).data(Tags).toStringList();
if (!m_filterTags.isEmpty()) {
- foreach(const QString &tag, m_filterTags) {
+ foreach (const QString &tag, m_filterTags)
if (!tags.contains(tag, Qt::CaseInsensitive))
return false;
- }
return true;
}
@@ -628,8 +598,7 @@ bool ExamplesListModelFilter::filterAcceptsRow(int sourceRow, const QModelIndex
const QString description = sourceModel()->index(sourceRow, 0, sourceParent).data(Description).toString();
const QString name = sourceModel()->index(sourceRow, 0, sourceParent).data(Name).toString();
-
- foreach(const QString &subString, m_searchString) {
+ foreach (const QString &subString, m_searchString) {
bool wordMatch = false;
wordMatch |= (bool)name.contains(subString, Qt::CaseInsensitive);
if (wordMatch)
@@ -643,11 +612,7 @@ bool ExamplesListModelFilter::filterAcceptsRow(int sourceRow, const QModelIndex
}
}
- bool ok = QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
- if (!ok)
- return false;
-
- return true;
+ return QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent);
}
int ExamplesListModelFilter::rowCount(const QModelIndex &parent) const
@@ -685,7 +650,8 @@ void ExamplesListModelFilter::timerEvent(QTimerEvent *timerEvent)
}
}
-struct SearchStringLexer {
+struct SearchStringLexer
+{
QString code;
const QChar *codePtr;
QChar yychar;
diff --git a/src/plugins/qtsupport/exampleslistmodel.h b/src/plugins/qtsupport/exampleslistmodel.h
index 1dcf164c21..0611212082 100644
--- a/src/plugins/qtsupport/exampleslistmodel.h
+++ b/src/plugins/qtsupport/exampleslistmodel.h
@@ -31,20 +31,27 @@
#define EXAMPLESLISTMODEL_H
#include <QAbstractListModel>
+#include <QSortFilterProxyModel>
#include <QStringList>
#include <QXmlStreamReader>
-#include <QSortFilterProxyModel>
namespace QtSupport {
namespace Internal {
-enum ExampleRoles { Name=Qt::UserRole, ProjectPath, Description, ImageUrl,
- DocUrl, FilesToOpen, Tags, Difficulty, HasSourceCode,
- Type, Dependencies, IsVideo, VideoUrl, VideoLength, Platforms };
+enum ExampleRoles
+{
+ Name = Qt::UserRole, ProjectPath, Description, ImageUrl,
+ DocUrl, FilesToOpen, Tags, Difficulty, HasSourceCode,
+ Type, Dependencies, IsVideo, VideoUrl, VideoLength, Platforms
+};
-enum InstructionalType { Example=0, Demo, Tutorial };
+enum InstructionalType
+{
+ Example = 0, Demo, Tutorial
+};
-struct ExampleItem {
+struct ExampleItem
+{
ExampleItem(): difficulty(0), isVideo(false) {}
InstructionalType type;
QString name;
@@ -63,24 +70,21 @@ struct ExampleItem {
QStringList platforms;
};
-class ExamplesListModel : public QAbstractListModel {
+class ExamplesListModel : public QAbstractListModel
+{
Q_OBJECT
+
public:
explicit ExamplesListModel(QObject *parent);
- virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
- virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QStringList tags() const;
-
-
void ensureInitialized() const;
- void beginReset()
- { beginResetModel(); }
-
- void endReset()
- { endResetModel(); }
+ void beginReset() { beginResetModel(); }
+ void endReset() { endResetModel(); }
signals:
void tagsUpdated();
@@ -91,25 +95,26 @@ public slots:
void helpInitialized();
private:
- void addItems(const QList<ExampleItem> &items);
- QList<ExampleItem> parseExamples(QXmlStreamReader *reader, const QString &projectsOffset,
+ void parseExamples(QXmlStreamReader *reader, const QString &projectsOffset,
const QString &examplesInstallPath);
- QList<ExampleItem> parseDemos(QXmlStreamReader *reader, const QString &projectsOffset,
+ void parseDemos(QXmlStreamReader *reader, const QString &projectsOffset,
const QString &demosInstallPath);
- QList<ExampleItem> parseTutorials(QXmlStreamReader *reader, const QString &projectsOffset);
- void clear();
+ void parseTutorials(QXmlStreamReader *reader, const QString &projectsOffset);
QStringList exampleSources(QString *examplesInstallPath, QString *demosInstallPath,
QString *examplesFallback, QString *demosFallback,
QString *sourceFallback);
- QList<ExampleItem> exampleItems;
+
+ QList<ExampleItem> m_exampleItems;
QStringList m_tags;
bool m_updateOnQtVersionsChanged;
bool m_initialized;
bool m_helpInitialized;
};
-class ExamplesListModelFilter : public QSortFilterProxyModel {
+class ExamplesListModelFilter : public QSortFilterProxyModel
+{
Q_OBJECT
+
public:
Q_PROPERTY(bool showTutorialsOnly READ showTutorialsOnly WRITE setShowTutorialsOnly NOTIFY showTutorialsOnlyChanged)
Q_PROPERTY(QStringList filterTags READ filterTags WRITE setFilterTags NOTIFY filterTagsChanged)
@@ -119,15 +124,15 @@ public:
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
- bool showTutorialsOnly() {return m_showTutorialsOnly;}
+ bool showTutorialsOnly() { return m_showTutorialsOnly; }
QStringList filterTags() const { return m_filterTags; }
QStringList searchStrings() const { return m_searchString; }
- virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
- virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
public slots:
- void setFilterTags(const QStringList& arg)
+ void setFilterTags(const QStringList &arg)
{
if (m_filterTags != arg) {
m_filterTags = arg;
@@ -136,7 +141,7 @@ public slots:
}
void updateFilter();
- void setSearchStrings(const QStringList& arg)
+ void setSearchStrings(const QStringList &arg)
{
if (m_searchString != arg) {
m_searchString = arg;
@@ -145,20 +150,16 @@ public slots:
}
}
- void parseSearchString(const QString& arg);
+ void parseSearchString(const QString &arg);
void setShowTutorialsOnly(bool showTutorialsOnly);
signals:
void showTutorialsOnlyChanged();
-
- void filterTagsChanged(const QStringList& arg);
-
- void searchStrings(const QStringList& arg);
-
-protected:
- void timerEvent(QTimerEvent *event);
+ void filterTagsChanged(const QStringList &arg);
+ void searchStrings(const QStringList &arg);
private:
+ void timerEvent(QTimerEvent *event);
void delayedUpdateFilter();
bool m_showTutorialsOnly;
diff --git a/src/plugins/qtsupport/gettingstartedwelcomepage.cpp b/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
index 9cd065bf73..24ead38f09 100644
--- a/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
+++ b/src/plugins/qtsupport/gettingstartedwelcomepage.cpp
@@ -55,7 +55,7 @@
#include <QMutex>
#include <QThread>
#include <QMutexLocker>
-#include <QWeakPointer>
+#include <QPointer>
#include <QWaitCondition>
#include <QDir>
#include <QBuffer>
@@ -75,20 +75,23 @@
#include <QDeclarativeContext>
#include <QDesktopServices>
+using namespace Utils;
+
namespace QtSupport {
namespace Internal {
const char C_FALLBACK_ROOT[] = "ProjectsFallbackRoot";
-QWeakPointer<ExamplesListModel> &examplesModelStatic()
+QPointer<ExamplesListModel> &examplesModelStatic()
{
- static QWeakPointer<ExamplesListModel> s_examplesModel;
+ static QPointer<ExamplesListModel> s_examplesModel;
return s_examplesModel;
}
class Fetcher : public QObject
{
Q_OBJECT
+
public:
Fetcher() : QObject(), m_shutdown(false)
{
@@ -179,7 +182,7 @@ public:
Q_UNUSED(size)
QMutexLocker lock(&m_mutex);
- QUrl url = QUrl::fromEncoded(id.toAscii());
+ QUrl url = QUrl::fromEncoded(id.toLatin1());
if (!m_fetcher.asynchronousFetchData(url))
return QImage();
@@ -351,9 +354,9 @@ QString ExamplesWelcomePage::copyToAlternativeLocation(const QFileInfo& proFileI
.arg(nativeProjectDir));
lay->addWidget(descrLbl, 0, 0, 1, 2);
QLabel *txt = new QLabel(tr("&Location:"));
- Utils::PathChooser *chooser = new Utils::PathChooser;
+ PathChooser *chooser = new PathChooser;
txt->setBuddy(chooser);
- chooser->setExpectedKind(Utils::PathChooser::ExistingDirectory);
+ chooser->setExpectedKind(PathChooser::ExistingDirectory);
QSettings *settings = Core::ICore::settings();
chooser->setPath(settings->value(QString::fromLatin1(C_FALLBACK_ROOT),
Core::DocumentManager::projectsDirectory()).toString());
@@ -382,15 +385,18 @@ QString ExamplesWelcomePage::copyToAlternativeLocation(const QFileInfo& proFileI
} else {
QString error;
QString targetDir = destBaseDir + QLatin1Char('/') + exampleDirName;
- if (Utils::FileUtils::copyRecursively(projectDir, targetDir, &error)) {
+ if (FileUtils::copyRecursively(FileName::fromString(projectDir),
+ FileName::fromString(targetDir), &error)) {
// set vars to new location
const QStringList::Iterator end = filesToOpen.end();
for (QStringList::Iterator it = filesToOpen.begin(); it != end; ++it)
it->replace(projectDir, targetDir);
foreach (const QString &dependency, dependencies) {
- QString dirName = QDir(dependency).dirName();
- if (!Utils::FileUtils::copyRecursively(dependency, targetDir + QDir::separator()+ dirName, &error)) {
+ FileName targetFile = FileName::fromString(targetDir);
+ targetFile.appendPath(QDir(dependency).dirName());
+ if (!FileUtils::copyRecursively(FileName::fromString(dependency), targetFile,
+ &error)) {
QMessageBox::warning(Core::ICore::mainWindow(), tr("Cannot Copy Project"), error);
// do not fail, just warn;
}
diff --git a/src/plugins/qtsupport/gettingstartedwelcomepage.h b/src/plugins/qtsupport/gettingstartedwelcomepage.h
index 8adddcef9a..4149816b38 100644
--- a/src/plugins/qtsupport/gettingstartedwelcomepage.h
+++ b/src/plugins/qtsupport/gettingstartedwelcomepage.h
@@ -65,6 +65,7 @@ private:
class ExamplesWelcomePage : public Utils::IWelcomePage
{
Q_OBJECT
+
public:
ExamplesWelcomePage();
diff --git a/src/plugins/qtsupport/profilereader.cpp b/src/plugins/qtsupport/profilereader.cpp
index cc4878cef0..7b242f4a30 100644
--- a/src/plugins/qtsupport/profilereader.cpp
+++ b/src/plugins/qtsupport/profilereader.cpp
@@ -39,8 +39,10 @@ using namespace QtSupport;
static QString format(const QString &fileName, int lineNo, const QString &msg)
{
- if (lineNo)
+ if (lineNo > 0)
return QString::fromLatin1("%1(%2): %3").arg(fileName, QString::number(lineNo), msg);
+ else if (lineNo)
+ return QString::fromLatin1("%1: %3").arg(fileName, msg);
else
return msg;
}
@@ -65,7 +67,7 @@ void ProMessageHandler::fileMessage(const QString &)
}
-ProFileReader::ProFileReader(QMakeGlobals *option)
+ProFileReader::ProFileReader(ProFileGlobals *option)
: QMakeParser(ProFileCacheManager::instance()->cache(), this)
, ProFileEvaluator(option, this, this)
, m_ignoreLevel(0)
diff --git a/src/plugins/qtsupport/profilereader.h b/src/plugins/qtsupport/profilereader.h
index 73e76711e9..8e01262786 100644
--- a/src/plugins/qtsupport/profilereader.h
+++ b/src/plugins/qtsupport/profilereader.h
@@ -70,7 +70,7 @@ class QTSUPPORT_EXPORT ProFileReader : public ProMessageHandler, public QMakePar
Q_OBJECT
public:
- ProFileReader(QMakeGlobals *option);
+ ProFileReader(ProFileGlobals *option);
~ProFileReader();
QList<ProFile*> includeFiles() const;
diff --git a/src/plugins/qtsupport/qmldebugginglibrary.cpp b/src/plugins/qtsupport/qmldebugginglibrary.cpp
index a28520e54e..ea19d76c24 100644
--- a/src/plugins/qtsupport/qmldebugginglibrary.cpp
+++ b/src/plugins/qtsupport/qmldebugginglibrary.cpp
@@ -100,11 +100,10 @@ QString QmlDebuggingLibrary::copy(const QString &qtInstallData, QString *errorMe
// Try to find a writeable directory.
foreach (const QString &directory, directories) {
- if (!mkpath(directory, errorMessage)) {
+ if (!mkpath(directory, errorMessage))
continue;
- } else {
+ else
errorMessage->clear();
- }
if (copyFiles(sourcePath(), sourceFileNames(),
directory, errorMessage))
@@ -124,9 +123,8 @@ QStringList QmlDebuggingLibrary::recursiveFileList(const QDir &dir, const QStrin
QStringList files;
QString _prefix = prefix;
- if (!_prefix.isEmpty() && !_prefix.endsWith(QLatin1Char('/'))) {
+ if (!_prefix.isEmpty() && !_prefix.endsWith(QLatin1Char('/')))
_prefix = _prefix + QLatin1Char('/');
- }
foreach (const QString &fileName, dir.entryList(QDir::Files)) {
files << _prefix + fileName;
}
diff --git a/src/plugins/qtsupport/qmldumptool.cpp b/src/plugins/qtsupport/qmldumptool.cpp
index 845c8982d2..9921878e73 100644
--- a/src/plugins/qtsupport/qmldumptool.cpp
+++ b/src/plugins/qtsupport/qmldumptool.cpp
@@ -41,6 +41,7 @@
#include <projectexplorer/runconfiguration.h>
#include <utils/runextensions.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDesktopServices>
#include <QCoreApplication>
@@ -120,9 +121,8 @@ private slots:
}
}
- if (m_failed) {
+ if (m_failed)
qWarning("%s", qPrintable(errorMessage));
- }
// update qmldump path for all the project
QmlJS::ModelManagerInterface *modelManager = QmlJS::ModelManagerInterface::instance();
@@ -244,9 +244,8 @@ static QStringList sourceFileNames()
files << QLatin1String("main.cpp") << QLatin1String("qmldump.pro")
<< QLatin1String("qmlstreamwriter.cpp") << QLatin1String("qmlstreamwriter.h")
<< QLatin1String("LICENSE.LGPL") << QLatin1String("LGPL_EXCEPTION.TXT");
-#ifdef Q_OS_MAC
- files << QLatin1String("Info.plist");
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ files << QLatin1String("Info.plist");
return files;
}
@@ -275,7 +274,7 @@ QStringList QmlDumpTool::locationsByInstallData(const QString &qtInstallData, bo
QStringList result;
QFileInfo fileInfo;
const QStringList binFilenames = validBinaryFilenames(debugDump);
- foreach(const QString &directory, installDirectories(qtInstallData)) {
+ foreach (const QString &directory, installDirectories(qtInstallData)) {
if (getHelperFileInfoFor(binFilenames, directory, &fileInfo))
result << fileInfo.filePath();
}
@@ -294,10 +293,9 @@ QString QmlDumpTool::copy(const QString &qtInstallData, QString *errorMessage)
const QStringList directories = QmlDumpTool::installDirectories(qtInstallData);
// Try to find a writeable directory.
- foreach(const QString &directory, directories) {
- if (copyFiles(sourcePath(), sourceFileNames(), directory, errorMessage)) {
+ foreach (const QString &directory, directories) {
+ if (copyFiles(sourcePath(), sourceFileNames(), directory, errorMessage))
return directory;
- }
}
*errorMessage = QCoreApplication::translate("ProjectExplorer::QmlDumpTool",
"qmldump could not be built in any of the directories:\n- %1\n\nReason: %2")
diff --git a/src/plugins/qtsupport/qtkitconfigwidget.cpp b/src/plugins/qtsupport/qtkitconfigwidget.cpp
index 0575e70371..7d4167edc4 100644
--- a/src/plugins/qtsupport/qtkitconfigwidget.cpp
+++ b/src/plugins/qtsupport/qtkitconfigwidget.cpp
@@ -45,34 +45,21 @@
namespace QtSupport {
namespace Internal {
-QtKitConfigWidget::QtKitConfigWidget(ProjectExplorer::Kit *k, QWidget *parent) :
- ProjectExplorer::KitConfigWidget(parent),
- m_kit(k),
- m_combo(new QComboBox),
- m_manageButton(new QPushButton(this))
+QtKitConfigWidget::QtKitConfigWidget(ProjectExplorer::Kit *k) :
+ KitConfigWidget(k)
{
- setToolTip(tr("The Qt library to use for all projects using this kit.<br>"
- "A Qt version is required for qmake-based projects and optional when using other build systems."));
- QHBoxLayout *layout = new QHBoxLayout(this);
- layout->setMargin(0);
-
- m_combo->setContentsMargins(0, 0, 0, 0);
- m_combo->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
- layout->addWidget(m_combo);
-
- m_manageButton->setContentsMargins(0, 0, 0, 0);
- m_manageButton->setText(tr("Manage..."));
+ m_combo = new QComboBox;
+ m_combo->addItem(tr("None"), -1);
QtVersionManager *mgr = QtVersionManager::instance();
-
- // initially populate combobox:
- m_combo->addItem(tr("None"), -1);
QList<BaseQtVersion *> versions = mgr->validVersions();
QList<int> versionIds;
foreach (BaseQtVersion *v, versions)
versionIds.append(v->uniqueId());
versionsChanged(versionIds, QList<int>(), QList<int>());
+ m_manageButton = new QPushButton(tr("Manage..."));
+
refresh();
connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(currentWasChanged(int)));
@@ -87,6 +74,13 @@ QString QtKitConfigWidget::displayName() const
return tr("Qt version:");
}
+QString QtKitConfigWidget::toolTip() const
+{
+ return tr("The Qt library to use for all projects using this kit.<br>"
+ "A Qt version is required for qmake-based projects "
+ "and optional when using other build systems.");
+}
+
void QtKitConfigWidget::makeReadOnly()
{
m_combo->setEnabled(false);
@@ -97,6 +91,11 @@ void QtKitConfigWidget::refresh()
m_combo->setCurrentIndex(findQtVersion(QtKitInformation::qtVersionId(m_kit)));
}
+QWidget *QtKitConfigWidget::mainWidget() const
+{
+ return m_combo;
+}
+
QWidget *QtKitConfigWidget::buttonWidget() const
{
return m_manageButton;
@@ -129,8 +128,8 @@ void QtKitConfigWidget::versionsChanged(const QList<int> &added, const QList<int
void QtKitConfigWidget::manageQtVersions()
{
- Core::ICore::showOptionsDialog(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY),
- QLatin1String(QtSupport::Constants::QTVERSION_SETTINGS_PAGE_ID));
+ Core::ICore::showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY,
+ Constants::QTVERSION_SETTINGS_PAGE_ID);
}
void QtKitConfigWidget::currentWasChanged(int idx)
diff --git a/src/plugins/qtsupport/qtkitconfigwidget.h b/src/plugins/qtsupport/qtkitconfigwidget.h
index b28f5fb945..4e5b3476d1 100644
--- a/src/plugins/qtsupport/qtkitconfigwidget.h
+++ b/src/plugins/qtsupport/qtkitconfigwidget.h
@@ -32,14 +32,12 @@
#include <projectexplorer/kitconfigwidget.h>
-QT_FORWARD_DECLARE_CLASS(QComboBox)
-QT_FORWARD_DECLARE_CLASS(QPushButton)
-
-namespace ProjectExplorer { class Kit; }
+QT_BEGIN_NAMESPACE
+class QComboBox;
+class QPushButton;
+QT_END_NAMESPACE
namespace QtSupport {
-class BaseQtVersion;
-
namespace Internal {
class QtKitConfigWidget : public ProjectExplorer::KitConfigWidget
@@ -47,14 +45,16 @@ class QtKitConfigWidget : public ProjectExplorer::KitConfigWidget
Q_OBJECT
public:
- explicit QtKitConfigWidget(ProjectExplorer::Kit *k, QWidget *parent = 0);
+ explicit QtKitConfigWidget(ProjectExplorer::Kit *k);
QString displayName() const;
void makeReadOnly();
void refresh();
+ QWidget *mainWidget() const;
QWidget *buttonWidget() const;
+ QString toolTip() const;
private slots:
void versionsChanged(const QList<int> &added, const QList<int> &removed, const QList<int> &changed);
@@ -64,7 +64,6 @@ private slots:
private:
int findQtVersion(const int id) const;
- ProjectExplorer::Kit *m_kit;
QComboBox *m_combo;
QPushButton *m_manageButton;
};
diff --git a/src/plugins/qtsupport/qtkitinformation.cpp b/src/plugins/qtsupport/qtkitinformation.cpp
index ab6641c6e1..a4643a838f 100644
--- a/src/plugins/qtsupport/qtkitinformation.cpp
+++ b/src/plugins/qtsupport/qtkitinformation.cpp
@@ -32,6 +32,7 @@
#include "qtkitconfigwidget.h"
#include "qtsupportconstants.h"
#include "qtversionmanager.h"
+#include "qtparser.h"
#include <utils/environment.h>
@@ -126,6 +127,13 @@ void QtKitInformation::addToEnvironment(const ProjectExplorer::Kit *k, Utils::En
version->addToEnvironment(k, env);
}
+ProjectExplorer::IOutputParser *QtKitInformation::createOutputParser(const ProjectExplorer::Kit *k) const
+{
+ if (qtVersion(k))
+ return new QtParser;
+ return 0;
+}
+
int QtKitInformation::qtVersionId(const ProjectExplorer::Kit *k)
{
if (!k)
diff --git a/src/plugins/qtsupport/qtkitinformation.h b/src/plugins/qtsupport/qtkitinformation.h
index 3b364d0302..5efca50a59 100644
--- a/src/plugins/qtsupport/qtkitinformation.h
+++ b/src/plugins/qtsupport/qtkitinformation.h
@@ -32,10 +32,10 @@
#include "qtsupport_global.h"
-#include <projectexplorer/kitinformation.h>
-
#include "baseqtversion.h"
+#include <projectexplorer/kitinformation.h>
+
namespace QtSupport {
class QTSUPPORT_EXPORT QtKitInformation : public ProjectExplorer::KitInformation
@@ -61,11 +61,13 @@ public:
ItemList toUserOutput(ProjectExplorer::Kit *k) const;
void addToEnvironment(const ProjectExplorer::Kit *k, Utils::Environment &env) const;
+ ProjectExplorer::IOutputParser *createOutputParser(const ProjectExplorer::Kit *k) const;
static int qtVersionId(const ProjectExplorer::Kit *k);
static void setQtVersionId(ProjectExplorer::Kit *k, const int id);
static BaseQtVersion *qtVersion(const ProjectExplorer::Kit *k);
static void setQtVersion(ProjectExplorer::Kit *k, const BaseQtVersion *v);
+
private slots:
void qtVersionsChanged(const QList<int> &addedIds,
const QList<int> &removedIds,
@@ -87,8 +89,8 @@ class QTSUPPORT_EXPORT QtVersionKitMatcher : public ProjectExplorer::KitMatcher
{
public:
explicit QtVersionKitMatcher(const Core::FeatureSet &required = Core::FeatureSet(),
- const QtVersionNumber &min = QtVersionNumber(0, 0, 0),
- const QtVersionNumber &max = QtVersionNumber(INT_MAX, INT_MAX, INT_MAX)) :
+ const QtVersionNumber &min = QtVersionNumber(0, 0, 0),
+ const QtVersionNumber &max = QtVersionNumber(INT_MAX, INT_MAX, INT_MAX)) :
m_min(min), m_max(max), m_features(required)
{ }
diff --git a/src/plugins/qtsupport/qtoptionspage.cpp b/src/plugins/qtsupport/qtoptionspage.cpp
index f0baf28164..948359f1fa 100644
--- a/src/plugins/qtsupport/qtoptionspage.cpp
+++ b/src/plugins/qtsupport/qtoptionspage.cpp
@@ -48,6 +48,7 @@
#include <projectexplorer/toolchainmanager.h>
#include <projectexplorer/toolchain.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <utils/hostosinfo.h>
#include <utils/runextensions.h>
#include <QDir>
@@ -61,6 +62,7 @@ enum ModelRoles { VersionIdRole = Qt::UserRole, ToolChainIdRole, BuildLogRole, B
using namespace QtSupport;
using namespace QtSupport::Internal;
+using namespace Utils;
///
// QtOptionsPage
@@ -69,9 +71,9 @@ using namespace QtSupport::Internal;
QtOptionsPage::QtOptionsPage()
: m_widget(0)
{
- setId(QLatin1String(Constants::QTVERSION_SETTINGS_PAGE_ID));
+ setId(Constants::QTVERSION_SETTINGS_PAGE_ID);
setDisplayName(QCoreApplication::translate("Qt4ProjectManager", Constants::QTVERSION_SETTINGS_PAGE_NAME));
- setCategory(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY));
+ setCategory(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("ProjectExplorer",
ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY_ICON));
@@ -129,14 +131,14 @@ QtOptionsPageWidget::QtOptionsPageWidget(QWidget *parent)
connect(m_infoBrowser, SIGNAL(anchorClicked(QUrl)), this, SLOT(infoAnchorClicked(QUrl)));
m_ui->infoWidget->setWidget(m_infoBrowser);
connect(m_ui->infoWidget, SIGNAL(expanded(bool)),
- this, SLOT(handleInfoWidgetExpanded(bool)));
+ this, SLOT(setInfoWidgetVisibility()));
m_ui->versionInfoWidget->setWidget(versionInfoWidget);
m_ui->versionInfoWidget->setState(Utils::DetailsWidget::NoSummary);
m_ui->debuggingHelperWidget->setWidget(debuggingHelperDetailsWidget);
connect(m_ui->debuggingHelperWidget, SIGNAL(expanded(bool)),
- this, SLOT(handleDebuggingHelperExpanded(bool)));
+ this, SLOT(setInfoWidgetVisibility()));
// setup parent items for auto-detected and manual versions
m_ui->qtdirList->header()->setResizeMode(QHeaderView::ResizeToContents);
@@ -334,16 +336,12 @@ void QtOptionsPageWidget::qtVersionsDumpUpdated(const Utils::FileName &qmakeComm
}
}
-void QtOptionsPageWidget::handleInfoWidgetExpanded(bool expanded)
+void QtOptionsPageWidget::setInfoWidgetVisibility()
{
- m_ui->versionInfoWidget->setVisible(!expanded);
- m_ui->debuggingHelperWidget->setVisible(!expanded);
-}
-
-void QtOptionsPageWidget::handleDebuggingHelperExpanded(bool expanded)
-{
- m_ui->versionInfoWidget->setVisible(!expanded);
- m_ui->infoWidget->setVisible(!expanded);
+ m_ui->versionInfoWidget->setVisible((m_ui->infoWidget->state() == DetailsWidget::Collapsed)
+ && (m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed));
+ m_ui->infoWidget->setVisible(m_ui->debuggingHelperWidget->state() == DetailsWidget::Collapsed);
+ m_ui->debuggingHelperWidget->setVisible(m_ui->infoWidget->state() == DetailsWidget::Collapsed);
}
void QtOptionsPageWidget::infoAnchorClicked(const QUrl &url)
@@ -616,16 +614,14 @@ static QString filterForQmakeFileDialog()
for (int i = 0; i < commands.size(); ++i) {
if (i)
filter += QLatin1Char(' ');
-#ifdef Q_OS_MAC
- // work around QTBUG-7739 that prohibits filters that don't start with *
- filter += QLatin1Char('*');
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ // work around QTBUG-7739 that prohibits filters that don't start with *
+ filter += QLatin1Char('*');
filter += commands.at(i);
-#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)
- // kde bug, we need at least one wildcard character
- // see QTCREATORBUG-7771
- filter += QLatin1Char('*');
-#endif
+ if (Utils::HostOsInfo::isAnyUnixHost() && !Utils::HostOsInfo::isMacHost())
+ // kde bug, we need at least one wildcard character
+ // see QTCREATORBUG-7771
+ filter += QLatin1Char('*');
}
filter += QLatin1Char(')');
return filter;
@@ -635,23 +631,30 @@ void QtOptionsPageWidget::addQtDir()
{
Utils::FileName qtVersion = Utils::FileName::fromString(
QFileDialog::getOpenFileName(this,
- tr("Select a qmake executable"),
+ tr("Select a qmake Executable"),
QString(),
filterForQmakeFileDialog(),
0,
QFileDialog::DontResolveSymlinks));
if (qtVersion.isNull())
return;
- BaseQtVersion *version = QtVersionManager::instance()->qtVersionForQMakeBinary(qtVersion);
+ BaseQtVersion *version = 0;
+ foreach (BaseQtVersion *v, m_versions) {
+ if (v->qmakeCommand() == qtVersion) {
+ version = v;
+ break;
+ }
+ }
if (version) {
// Already exist
- QMessageBox::warning(this, tr("Qt known"),
+ QMessageBox::warning(this, tr("Qt Version Already Known"),
tr("This Qt version was already registered as \"%1\".")
.arg(version->displayName()));
return;
}
- version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion);
+ QString error;
+ version = QtVersionFactory::createQtVersionFromQMakePath(qtVersion, false, QString(), &error);
if (version) {
m_versions.append(version);
@@ -664,6 +667,10 @@ void QtOptionsPageWidget::addQtDir()
m_ui->qtdirList->setCurrentItem(item); // should update the rest of the ui
m_versionUi->nameEdit->setFocus();
m_versionUi->nameEdit->selectAll();
+ } else {
+ QMessageBox::warning(this, tr("Qmake not Executable"),
+ tr("The qmake executable %1 could not be added: %2").arg(qtVersion.toUserOutput()).arg(error));
+ return;
}
updateCleanUpButton();
}
@@ -703,7 +710,7 @@ void QtOptionsPageWidget::editPath()
if (current->type() != version->type()) {
// not the same type, error out
QMessageBox::critical(this, tr("Incompatible Qt Versions"),
- tr("The Qt version selected must be for the same device type."),
+ tr("The Qt version selected must match the device type."),
QMessageBox::Ok);
delete version;
return;
@@ -790,11 +797,10 @@ void QtOptionsPageWidget::updateDebuggingHelperUi()
gdbHelperText = QDir::toNativeSeparators(version->gdbDebuggingHelperLibrary());
gdbHelperTextFlags = Qt::TextSelectableByMouse;
} else {
- if (canBuildGdbHelper) {
+ if (canBuildGdbHelper)
gdbHelperText = tr("<i>Not yet built.</i>");
- } else {
+ else
gdbHelperText = tr("<i>Not needed.</i>");
- }
}
m_debuggingHelperUi->gdbHelperStatus->setText(gdbHelperText);
m_debuggingHelperUi->gdbHelperStatus->setTextInteractionFlags(gdbHelperTextFlags);
@@ -909,8 +915,7 @@ void QtOptionsPageWidget::updateDebuggingHelperUi()
m_debuggingHelperUi->rebuildButton->setEnabled(canBuild && !isBuilding);
m_debuggingHelperUi->toolChainComboBox->setEnabled(canBuild && !isBuilding);
-
- m_ui->debuggingHelperWidget->setVisible(true);
+ setInfoWidgetVisibility();
}
}
@@ -958,12 +963,12 @@ void QtOptionsPageWidget::updateDescriptionLabel()
if (version) {
m_infoBrowser->setHtml(version->toHtml(true));
- m_ui->versionInfoWidget->setVisible(true);
- m_ui->infoWidget->setVisible(true);
+ setInfoWidgetVisibility();
} else {
m_infoBrowser->setHtml(QString());
m_ui->versionInfoWidget->setVisible(false);
m_ui->infoWidget->setVisible(false);
+ m_ui->debuggingHelperWidget->setVisible(false);
}
}
@@ -986,9 +991,8 @@ QTreeWidgetItem *QtOptionsPageWidget::treeItemForIndex(int index) const
QTreeWidgetItem *toplevelItem = m_ui->qtdirList->topLevelItem(i);
for (int j = 0; j < toplevelItem->childCount(); ++j) {
QTreeWidgetItem *item = toplevelItem->child(j);
- if (item->data(0, VersionIdRole).toInt() == uniqueId) {
+ if (item->data(0, VersionIdRole).toInt() == uniqueId)
return item;
- }
}
}
return 0;
diff --git a/src/plugins/qtsupport/qtoptionspage.h b/src/plugins/qtsupport/qtoptionspage.h
index f1bf7744c9..2e68d391f7 100644
--- a/src/plugins/qtsupport/qtoptionspage.h
+++ b/src/plugins/qtsupport/qtoptionspage.h
@@ -118,8 +118,7 @@ private slots:
void selectedToolChainChanged(int index);
void qtVersionsDumpUpdated(const Utils::FileName &qmakeCommand);
- void handleInfoWidgetExpanded(bool expanded);
- void handleDebuggingHelperExpanded(bool expanded);
+ void setInfoWidgetVisibility();
void infoAnchorClicked(const QUrl &);
private:
diff --git a/src/plugins/qtsupport/qtoutputformatter.cpp b/src/plugins/qtsupport/qtoutputformatter.cpp
index fb61ef0f1b..bd590ab88c 100644
--- a/src/plugins/qtsupport/qtoutputformatter.cpp
+++ b/src/plugins/qtsupport/qtoutputformatter.cpp
@@ -43,8 +43,7 @@ using namespace QtSupport;
QtOutputFormatter::QtOutputFormatter(ProjectExplorer::Project *project)
: OutputFormatter()
- , m_qmlError(QLatin1String("^(?:\\[Qt Message\\] )?" // '[Qt Message] ' prefix (optional, on Symbian)
- "(file:///.+" // file url
+ , m_qmlError(QLatin1String("^(file:///.+" // file url
":\\d+" // colon, line
"(?::\\d+)?)" // colon, column (optional)
":")) // colon
@@ -54,7 +53,7 @@ QtOutputFormatter::QtOutputFormatter(ProjectExplorer::Project *project)
, m_qtTestFail(QLatin1String("^ Loc: \\[(.*)\\]"))
, m_project(project)
{
- if(project) {
+ if (project) {
m_projectFinder.setProjectFiles(project->files(Project::ExcludeGeneratedFiles));
m_projectFinder.setProjectDirectory(project->projectDirectory());
diff --git a/src/plugins/qtsupport/qtoutputformatter.h b/src/plugins/qtsupport/qtoutputformatter.h
index 0ec98e7b81..e53d141f0c 100644
--- a/src/plugins/qtsupport/qtoutputformatter.h
+++ b/src/plugins/qtsupport/qtoutputformatter.h
@@ -36,7 +36,7 @@
#include <utils/fileinprojectfinder.h>
#include <QRegExp>
-#include <QWeakPointer>
+#include <QPointer>
QT_FORWARD_DECLARE_CLASS(QTextCursor)
@@ -80,7 +80,7 @@ private:
mutable QRegExp m_qtAssert;
mutable QRegExp m_qtAssertX;
mutable QRegExp m_qtTestFail;
- QWeakPointer<ProjectExplorer::Project> m_project;
+ QPointer<ProjectExplorer::Project> m_project;
QString m_lastLine;
Utils::FileInProjectFinder m_projectFinder;
};
diff --git a/src/plugins/qtsupport/qtparser.cpp b/src/plugins/qtsupport/qtparser.cpp
index b76e5d6431..5acf924945 100644
--- a/src/plugins/qtsupport/qtparser.cpp
+++ b/src/plugins/qtsupport/qtparser.cpp
@@ -41,7 +41,7 @@ using ProjectExplorer::Task;
#define FILE_PATTERN "^(([A-Za-z]:)?[^:]+\\.[^:]+)"
QtParser::QtParser() :
- m_mocRegExp(QLatin1String(FILE_PATTERN"[:\\(](\\d+)\\)?:\\s(Warning|Error):\\s(.+)$"))
+ m_mocRegExp(QLatin1String(FILE_PATTERN"[:\\(](\\d+)\\)?:\\s([Ww]arning|[Ee]rror):\\s(.+)$"))
{
setObjectName(QLatin1String("QtParser"));
m_mocRegExp.setMinimal(true);
@@ -60,7 +60,7 @@ void QtParser::stdError(const QString &line)
Utils::FileName::fromUserInput(m_mocRegExp.cap(1)) /* filename */,
lineno,
Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE));
- if (m_mocRegExp.cap(4) == QLatin1String("Warning"))
+ if (m_mocRegExp.cap(4).compare(QLatin1String("Warning"), Qt::CaseInsensitive) == 0)
task.type = Task::Warning;
emit addTask(task);
return;
@@ -116,6 +116,15 @@ void QtSupportPlugin::testQtOutputParser_data()
"../../scriptbug/main.cpp:22: instantiated from here\n")
<< QList<ProjectExplorer::Task>()
<< QString();
+ QTest::newRow("qdoc warning")
+ << QString::fromLatin1("/home/user/dev/qt5/qtscript/src/script/api/qscriptengine.cpp:295: warning: Can't create link to 'Object Trees & Ownership'")
+ << OutputParserTester::STDERR
+ << QString() << QString()
+ << (QList<ProjectExplorer::Task>() << Task(Task::Warning,
+ QLatin1String("Can't create link to 'Object Trees & Ownership'"),
+ Utils::FileName::fromUserInput(QLatin1String("/home/user/dev/qt5/qtscript/src/script/api/qscriptengine.cpp")), 295,
+ Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_COMPILE)))
+ << QString();
QTest::newRow("moc warning")
<< QString::fromLatin1("..\\untitled\\errorfile.h:0: Warning: No relevant classes found. No output generated.")
<< OutputParserTester::STDERR
diff --git a/src/plugins/qtsupport/qtsupport.pri b/src/plugins/qtsupport/qtsupport.pri
index a419733faf..e4de26c4ca 100644
--- a/src/plugins/qtsupport/qtsupport.pri
+++ b/src/plugins/qtsupport/qtsupport.pri
@@ -5,3 +5,4 @@ DEFINES *= QMAKE_AS_LIBRARY
DEFINES *= PROPARSER_THREAD_SAFE
DEFINES *= PROEVALUATOR_THREAD_SAFE
DEFINES *= PROEVALUATOR_CUMULATIVE
+DEFINES *= PROEVALUATOR_SETENV
diff --git a/src/plugins/qtsupport/qtsupport.pro b/src/plugins/qtsupport/qtsupport.pro
index c1a2ad0be6..8a5799316b 100644
--- a/src/plugins/qtsupport/qtsupport.pro
+++ b/src/plugins/qtsupport/qtsupport.pro
@@ -7,7 +7,7 @@ include(../../qtcreatorplugin.pri)
include(qtsupport_dependencies.pri)
DEFINES += \
QMAKE_AS_LIBRARY QMAKE_LIBRARY \
- PROPARSER_THREAD_SAFE PROEVALUATOR_THREAD_SAFE PROEVALUATOR_CUMULATIVE
+ PROPARSER_THREAD_SAFE PROEVALUATOR_THREAD_SAFE PROEVALUATOR_CUMULATIVE PROEVALUATOR_SETENV
include(../../shared/proparser/proparser.pri)
HEADERS += \
@@ -61,6 +61,3 @@ FORMS += \
qtversioninfo.ui \
debugginghelper.ui \
qtversionmanager.ui \
-
-
-DEFINES += QT_NO_CAST_FROM_ASCII
diff --git a/src/plugins/qtsupport/qtsupport.qbs b/src/plugins/qtsupport/qtsupport.qbs
index e8aed6c497..cc30200f0f 100644
--- a/src/plugins/qtsupport/qtsupport.qbs
+++ b/src/plugins/qtsupport/qtsupport.qbs
@@ -12,101 +12,102 @@ QtcPlugin {
Depends { name: "QmlJS" }
Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
+ cpp.includePaths: base.concat([
"../../shared",
- "../../shared/proparser",
- "..",
- "../../libs",
- buildDirectory
- ]
- cpp.defines: {
- return base.concat([
- "QT_NO_CAST_FROM_ASCII",
- "QT_NO_CAST_TO_ASCII",
- "QMAKE_AS_LIBRARY",
- "QMAKE_LIBRARY",
- "PROPARSER_THREAD_SAFE",
- "PROEVALUATOR_THREAD_SAFE",
- "PROEVALUATOR_CUMULATIVE",
- "QMAKE_BUILTIN_PRFS"
- ])
+ "../../shared/proparser"
+ ])
+
+ cpp.defines: base.concat([
+ "QMAKE_AS_LIBRARY",
+ "QMAKE_LIBRARY",
+ "PROPARSER_THREAD_SAFE",
+ "PROEVALUATOR_THREAD_SAFE",
+ "PROEVALUATOR_CUMULATIVE",
+ "QMAKE_BUILTIN_PRFS",
+ "PROEVALUATOR_SETENV"
+ ])
+
+ Group {
+ prefix: "../../shared/proparser/"
+ files: [
+ "ioutils.cpp",
+ "ioutils.h",
+ "profileevaluator.cpp",
+ "profileevaluator.h",
+ "proitems.cpp",
+ "proitems.h",
+ "proparser.qrc",
+ "prowriter.cpp",
+ "prowriter.h",
+ "qmake_global.h",
+ "qmakebuiltins.cpp",
+ "qmakeevaluator.cpp",
+ "qmakeevaluator.h",
+ "qmakeevaluator_p.h",
+ "qmakeglobals.cpp",
+ "qmakeglobals.h",
+ "qmakeparser.cpp",
+ "qmakeparser.h",
+ ]
}
files: [
- "../../shared/proparser/qmakebuiltins.cpp",
- "../../shared/proparser/qmakeevaluator.cpp",
- "../../shared/proparser/qmakeevaluator.h",
- "../../shared/proparser/qmakeevaluator_p.h",
- "../../shared/proparser/qmakeglobals.cpp",
- "../../shared/proparser/qmakeglobals.h",
- "../../shared/proparser/qmakeparser.cpp",
- "../../shared/proparser/qmakeparser.h",
- "../../shared/proparser/qmake_global.h",
- "../../shared/proparser/profileevaluator.cpp",
- "../../shared/proparser/profileevaluator.h",
- "../../shared/proparser/proitems.cpp",
- "../../shared/proparser/proitems.h",
- "../../shared/proparser/prowriter.cpp",
- "../../shared/proparser/prowriter.h",
- "../../shared/proparser/proparser.qrc",
- "../../shared/proparser/ioutils.h",
- "../../shared/proparser/ioutils.cpp",
- "qtversioninfo.ui",
- "qtversionmanager.ui",
+ "baseqtversion.cpp",
"baseqtversion.h",
+ "customexecutableconfigurationwidget.cpp",
+ "customexecutableconfigurationwidget.h",
+ "customexecutablerunconfiguration.cpp",
+ "customexecutablerunconfiguration.h",
"debugginghelper.cpp",
"debugginghelper.h",
"debugginghelper.ui",
+ "debugginghelperbuildtask.cpp",
"debugginghelperbuildtask.h",
+ "exampleslistmodel.cpp",
"exampleslistmodel.h",
+ "gettingstartedwelcomepage.cpp",
"gettingstartedwelcomepage.h",
"profilereader.cpp",
"profilereader.h",
+ "qmldebugginglibrary.cpp",
"qmldebugginglibrary.h",
+ "qmldumptool.cpp",
"qmldumptool.h",
+ "qmlobservertool.cpp",
"qmlobservertool.h",
- "qtoptionspage.h",
- "qtoutputformatter.cpp",
- "qtoutputformatter.h",
- "qtparser.h",
"qtkitconfigwidget.cpp",
"qtkitconfigwidget.h",
"qtkitinformation.cpp",
"qtkitinformation.h",
+ "qtoptionspage.cpp",
+ "qtoptionspage.h",
+ "qtoutputformatter.cpp",
+ "qtoutputformatter.h",
+ "qtparser.cpp",
+ "qtparser.h",
"qtsupport_global.h",
"qtsupportconstants.h",
"qtsupportplugin.cpp",
"qtsupportplugin.h",
+ "qtversionfactory.cpp",
"qtversionfactory.h",
+ "qtversioninfo.ui",
+ "qtversionmanager.cpp",
"qtversionmanager.h",
+ "qtversionmanager.ui",
"screenshotcropper.cpp",
"screenshotcropper.h",
"showbuildlog.ui",
- "baseqtversion.cpp",
- "customexecutableconfigurationwidget.cpp",
- "customexecutableconfigurationwidget.h",
- "customexecutablerunconfiguration.cpp",
- "customexecutablerunconfiguration.h",
- "debugginghelperbuildtask.cpp",
- "exampleslistmodel.cpp",
- "gettingstartedwelcomepage.cpp",
- "qmldebugginglibrary.cpp",
- "qmldumptool.cpp",
- "qmlobservertool.cpp",
- "qtoptionspage.cpp",
- "qtparser.cpp",
- "qtversionfactory.cpp",
- "qtversionmanager.cpp"
]
ProductModule {
Depends { name: "cpp" }
- cpp.includePaths: [ "../../shared" ]
+ cpp.includePaths: "../../shared"
cpp.defines: [
"QMAKE_AS_LIBRARY",
"PROEVALUATOR_THREAD_SAFE",
- "QMAKE_BUILTIN_PRFS"
+ "QMAKE_BUILTIN_PRFS",
+ "PROEVALUATOR_SETENV"
]
}
}
diff --git a/src/plugins/qtsupport/qtsupportplugin.cpp b/src/plugins/qtsupport/qtsupportplugin.cpp
index 780af44f3c..cedb477348 100644
--- a/src/plugins/qtsupport/qtsupportplugin.cpp
+++ b/src/plugins/qtsupport/qtsupportplugin.cpp
@@ -38,12 +38,19 @@
#include "gettingstartedwelcomepage.h"
+#include <coreplugin/variablemanager.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/kitmanager.h>
+#include <projectexplorer/project.h>
+#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/target.h>
#include <QtPlugin>
#include <QMenu>
+static const char kHostBins[] = "CurrentProject:QT_HOST_BINS";
+static const char kInstallBins[] = "CurrentProject:QT_INSTALL_BINS";
+
using namespace QtSupport;
using namespace QtSupport::Internal;
@@ -81,6 +88,15 @@ bool QtSupportPlugin::initialize(const QStringList &arguments, QString *errorMes
void QtSupportPlugin::extensionsInitialized()
{
+ Core::VariableManager *vm = Core::VariableManager::instance();
+ vm->registerVariable(kHostBins,
+ tr("Full path to the host bin directory of the current project's Qt version."));
+ vm->registerVariable(kInstallBins,
+ tr("Full path to the target bin directory of the current project's Qt version."
+ " You probably want %1 instead.").arg(QString::fromLatin1(kHostBins)));
+ connect(vm, SIGNAL(variableUpdateRequested(QByteArray)),
+ this, SLOT(updateVariable(QByteArray)));
+
QtVersionManager::instance()->extensionsInitialized();
ProjectExplorer::KitManager::instance()->registerKitInformation(new QtKitInformation);
}
@@ -90,4 +106,25 @@ bool QtSupportPlugin::delayedInitialize()
return QtVersionManager::instance()->delayedInitialize();
}
+void QtSupportPlugin::updateVariable(const QByteArray &variable)
+{
+ if (variable != kHostBins && variable != kInstallBins)
+ return;
+
+ ProjectExplorer::Project *project = ProjectExplorer::ProjectExplorerPlugin::currentProject();
+ if (!project || !project->activeTarget()) {
+ Core::VariableManager::instance()->remove(variable);
+ return;
+ }
+
+ const BaseQtVersion *qtVersion = QtKitInformation::qtVersion(project->activeTarget()->kit());
+ if (!qtVersion) {
+ Core::VariableManager::instance()->remove(variable);
+ return;
+ }
+
+ QString value = qtVersion->qmakeProperty(variable == kHostBins ? "QT_HOST_BINS" : "QT_INSTALL_BINS");
+ Core::VariableManager::instance()->insert(variable, value);
+}
+
Q_EXPORT_PLUGIN(QtSupportPlugin)
diff --git a/src/plugins/qtsupport/qtsupportplugin.h b/src/plugins/qtsupport/qtsupportplugin.h
index 58c008458d..29ffe16ee2 100644
--- a/src/plugins/qtsupport/qtsupportplugin.h
+++ b/src/plugins/qtsupport/qtsupportplugin.h
@@ -49,6 +49,8 @@ public:
bool delayedInitialize();
private slots:
+ void updateVariable(const QByteArray &variable);
+
#ifdef WITH_TESTS
void testQtOutputParser_data();
void testQtOutputParser();
diff --git a/src/plugins/qtsupport/qtversionfactory.cpp b/src/plugins/qtsupport/qtversionfactory.cpp
index 5300868fd0..eb34c054c8 100644
--- a/src/plugins/qtsupport/qtversionfactory.cpp
+++ b/src/plugins/qtsupport/qtversionfactory.cpp
@@ -33,6 +33,8 @@
#include "baseqtversion.h"
#include <extensionsystem/pluginmanager.h>
+#include <utils/environment.h>
+
#include <QSettings>
using namespace QtSupport;
@@ -54,15 +56,15 @@ bool sortByPriority(QtVersionFactory *a, QtVersionFactory *b)
return a->priority() > b->priority();
}
-BaseQtVersion *QtVersionFactory::createQtVersionFromQMakePath(const Utils::FileName &qmakePath, bool isAutoDetected, const QString &autoDetectionSource)
+BaseQtVersion *QtVersionFactory::createQtVersionFromQMakePath(const Utils::FileName &qmakePath, bool isAutoDetected, const QString &autoDetectionSource, QString *error)
{
QHash<QString, QString> versionInfo;
- bool success = BaseQtVersion::queryQMakeVariables(qmakePath, &versionInfo);
- if (!success)
+ Utils::Environment env = Utils::Environment::systemEnvironment();
+ if (!BaseQtVersion::queryQMakeVariables(qmakePath, env, &versionInfo, error))
return 0;
Utils::FileName mkspec = BaseQtVersion::mkspecFromVersionInfo(versionInfo);
- QMakeGlobals globals;
+ ProFileGlobals globals;
globals.setProperties(versionInfo);
ProMessageHandler msgHandler(true);
ProFileCacheManager::instance()->incRefCount();
@@ -81,5 +83,7 @@ BaseQtVersion *QtVersionFactory::createQtVersionFromQMakePath(const Utils::FileN
}
}
ProFileCacheManager::instance()->decRefCount();
+ if (error)
+ *error = tr("No factory found for qmake: '%1'").arg(qmakePath.toUserOutput());
return 0;
}
diff --git a/src/plugins/qtsupport/qtversionfactory.h b/src/plugins/qtsupport/qtversionfactory.h
index 459fbb0f70..bf4329d7f7 100644
--- a/src/plugins/qtsupport/qtversionfactory.h
+++ b/src/plugins/qtsupport/qtversionfactory.h
@@ -62,7 +62,7 @@ public:
virtual int priority() const = 0;
virtual BaseQtVersion *create(const Utils::FileName &qmakePath, ProFileEvaluator *evaluator, bool isAutoDetected = false, const QString &autoDetectionSource = QString()) = 0;
- static BaseQtVersion *createQtVersionFromQMakePath(const Utils::FileName &qmakePath, bool isAutoDetected = false, const QString &autoDetectionSource = QString());
+ static BaseQtVersion *createQtVersionFromQMakePath(const Utils::FileName &qmakePath, bool isAutoDetected = false, const QString &autoDetectionSource = QString(), QString *error = 0);
};
} // namespace QtSupport
diff --git a/src/plugins/qtsupport/qtversionmanager.cpp b/src/plugins/qtsupport/qtversionmanager.cpp
index 442aaa9e18..6c83b053f4 100644
--- a/src/plugins/qtsupport/qtversionmanager.cpp
+++ b/src/plugins/qtsupport/qtversionmanager.cpp
@@ -475,20 +475,6 @@ bool QtVersionManager::isValidId(int id) const
return m_versions.contains(id);
}
-QString QtVersionManager::popPendingMwcUpdate()
-{
- if (m_pendingMwcUpdates.isEmpty())
- return QString();
- return m_pendingMwcUpdates.takeFirst();
-}
-
-QString QtVersionManager::popPendingGcceUpdate()
-{
- if (m_pendingGcceUpdates.isEmpty())
- return QString();
- return m_pendingGcceUpdates.takeFirst();
-}
-
Core::FeatureSet QtVersionManager::availableFeatures(const QString &platformName) const
{
Core::FeatureSet features;
@@ -650,7 +636,7 @@ BaseQtVersion *QtVersionManager::qtVersionForQMakeBinary(const Utils::FileName &
void dumpQMakeAssignments(const QList<QMakeAssignment> &list)
{
- foreach(const QMakeAssignment &qa, list) {
+ foreach (const QMakeAssignment &qa, list) {
qDebug()<<qa.variable<<qa.op<<qa.value;
}
}
@@ -706,11 +692,11 @@ QPair<BaseQtVersion::QmakeBuildConfigs, QString> QtVersionManager::scanMakeFile(
if (debug)
dumpQMakeAssignments(assignments);
- foreach(const QMakeAssignment &qa, assignments)
+ foreach (const QMakeAssignment &qa, assignments)
Utils::QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
if (!afterAssignments.isEmpty()) {
Utils::QtcProcess::addArg(&result2, QLatin1String("-after"));
- foreach(const QMakeAssignment &qa, afterAssignments)
+ foreach (const QMakeAssignment &qa, afterAssignments)
Utils::QtcProcess::addArg(&result2, qa.variable + qa.op + qa.value);
}
}
@@ -805,11 +791,11 @@ BaseQtVersion::QmakeBuildConfigs QtVersionManager::qmakeBuildConfigFromCmdArgs(Q
BaseQtVersion::QmakeBuildConfigs result = defaultBuildConfig;
QList<QMakeAssignment> oldAssignments = *assignments;
assignments->clear();
- foreach(const QMakeAssignment &qa, oldAssignments) {
+ foreach (const QMakeAssignment &qa, oldAssignments) {
if (qa.variable == QLatin1String("CONFIG")) {
QStringList values = qa.value.split(QLatin1Char(' '));
QStringList newValues;
- foreach(const QString &value, values) {
+ foreach (const QString &value, values) {
if (value == QLatin1String("debug")) {
if (qa.op == QLatin1String("+="))
result = result | BaseQtVersion::DebugBuild;
diff --git a/src/plugins/qtsupport/qtversionmanager.h b/src/plugins/qtsupport/qtversionmanager.h
index 5f184128b4..6df5262597 100644
--- a/src/plugins/qtsupport/qtversionmanager.h
+++ b/src/plugins/qtsupport/qtversionmanager.h
@@ -91,10 +91,6 @@ public:
static Utils::FileName findQMakeBinaryFromMakefile(const QString &directory);
bool isValidId(int id) const;
- // Compatibility with pre-2.2:
- QString popPendingMwcUpdate();
- QString popPendingGcceUpdate();
-
Core::FeatureSet availableFeatures(const QString &platformName) const;
QStringList availablePlatforms() const;
QString displayNameForPlatform(const QString &string) const;
@@ -122,7 +118,6 @@ private:
static BaseQtVersion::QmakeBuildConfigs qmakeBuildConfigFromCmdArgs(QList<QMakeAssignment> *assignments,
BaseQtVersion::QmakeBuildConfigs defaultBuildConfig);
bool restoreQtVersions();
- bool legacyRestore();
void findSystemQt();
void saveQtVersions();
void updateDocumentation();
@@ -140,10 +135,6 @@ private:
// managed by QtProjectManagerPlugin
static QtVersionManager *m_self;
- // Compatibility with pre-2.2:
- QStringList m_pendingMwcUpdates;
- QStringList m_pendingGcceUpdates;
-
Utils::FileSystemWatcher *m_configFileWatcher;
QTimer *m_fileWatcherTimer;
Utils::PersistentSettingsWriter *m_writer;
diff --git a/src/plugins/remotelinux/RemoteLinux.pluginspec.in b/src/plugins/remotelinux/RemoteLinux.pluginspec.in
index 3bbe22ef6f..6f9bdfe208 100644
--- a/src/plugins/remotelinux/RemoteLinux.pluginspec.in
+++ b/src/plugins/remotelinux/RemoteLinux.pluginspec.in
@@ -17,6 +17,6 @@ Alternatively, this plugin may be used under the terms of the GNU Lesser General
<dependency name=\"Core\" version=\"$$QTCREATOR_VERSION\"/>
<dependency name=\"Debugger\" version=\"$$QTCREATOR_VERSION\"/>
<dependency name=\"ProjectExplorer\" version=\"$$QTCREATOR_VERSION\"/>
- <dependency name=\"Qt4ProjectManager\" version=\"$$QTCREATOR_VERSION\"/>
+ <dependency name=\"QtSupport\" version=\"$$QTCREATOR_VERSION\"/>
</dependencyList>
</plugin>
diff --git a/src/plugins/remotelinux/abstractpackagingstep.cpp b/src/plugins/remotelinux/abstractpackagingstep.cpp
index ca7427c0b8..3b705859b1 100644
--- a/src/plugins/remotelinux/abstractpackagingstep.cpp
+++ b/src/plugins/remotelinux/abstractpackagingstep.cpp
@@ -28,12 +28,12 @@
****************************************************************************/
#include "abstractpackagingstep.h"
-#include "deployablefile.h"
-#include "deploymentinfo.h"
#include "remotelinuxdeployconfiguration.h"
#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/task.h>
#include <utils/fileutils.h>
@@ -54,6 +54,7 @@ public:
BuildConfiguration *currentBuildConfiguration;
QString cachedPackageFilePath;
QString cachedPackageDirectory;
+ bool deploymentDataModified;
};
} // namespace Internal
@@ -77,8 +78,10 @@ void AbstractPackagingStep::ctor()
SLOT(handleBuildConfigurationChanged()));
handleBuildConfigurationChanged();
- connect(this, SIGNAL(unmodifyDeploymentInfo()),
- this, SLOT(setDeploymentInfoUnmodified()));
+ connect(target(), SIGNAL(deploymentDataChanged()), SLOT(setDeploymentDataModified()));
+ setDeploymentDataModified();
+
+ connect(this, SIGNAL(unmodifyDeploymentData()), this, SLOT(setDeploymentDataUnmodified()));
}
AbstractPackagingStep::~AbstractPackagingStep()
@@ -121,23 +124,18 @@ QString AbstractPackagingStep::packageDirectory() const
? d->currentBuildConfiguration->buildDirectory() : QString();
}
-RemoteLinuxDeployConfiguration *AbstractPackagingStep::deployConfiguration() const
-{
- return qobject_cast<RemoteLinuxDeployConfiguration *>(parent()->parent());
-}
-
bool AbstractPackagingStep::isPackagingNeeded() const
{
- const DeploymentInfo * const deploymentInfo = deployConfiguration()->deploymentInfo();
QFileInfo packageInfo(packageFilePath());
- if (!packageInfo.exists() || deploymentInfo->isModified())
+ if (!packageInfo.exists() || d->deploymentDataModified)
return true;
- const int deployableCount = deploymentInfo->deployableCount();
- for (int i = 0; i < deployableCount; ++i) {
- if (Utils::FileUtils::isFileNewerThan(deploymentInfo->deployableAt(i).localFilePath,
- packageInfo.lastModified()))
+ const DeploymentData &dd = target()->deploymentData();
+ for (int i = 0; i < dd.fileCount(); ++i) {
+ if (Utils::FileUtils::isFileNewerThan(dd.fileAt(i).localFilePath(),
+ packageInfo.lastModified())) {
return true;
+ }
}
return false;
@@ -158,13 +156,18 @@ void AbstractPackagingStep::setPackagingStarted()
void AbstractPackagingStep::setPackagingFinished(bool success)
{
if (success)
- emit unmodifyDeploymentInfo();
+ emit unmodifyDeploymentData();
}
// called in gui thread
-void AbstractPackagingStep::setDeploymentInfoUnmodified()
+void AbstractPackagingStep::setDeploymentDataUnmodified()
+{
+ d->deploymentDataModified = false;
+}
+
+void AbstractPackagingStep::setDeploymentDataModified()
{
- deployConfiguration()->deploymentInfo()->setUnmodified();
+ d->deploymentDataModified = true;
}
void AbstractPackagingStep::raiseError(const QString &errorMessage)
diff --git a/src/plugins/remotelinux/abstractpackagingstep.h b/src/plugins/remotelinux/abstractpackagingstep.h
index ad22dc8f23..6c62793587 100644
--- a/src/plugins/remotelinux/abstractpackagingstep.h
+++ b/src/plugins/remotelinux/abstractpackagingstep.h
@@ -35,11 +35,8 @@
namespace RemoteLinux {
class RemoteLinuxDeployConfiguration;
-class DeploymentInfo;
-namespace Internal {
-class AbstractPackagingStepPrivate;
-}
+namespace Internal { class AbstractPackagingStepPrivate; }
class REMOTELINUX_EXPORT AbstractPackagingStep : public ProjectExplorer::BuildStep
{
@@ -56,14 +53,13 @@ public:
signals:
void packageFilePathChanged();
- void unmodifyDeploymentInfo();
+ void unmodifyDeploymentData();
protected:
void setPackagingStarted();
void setPackagingFinished(bool success);
void raiseError(const QString &errorMessage);
- RemoteLinuxDeployConfiguration *deployConfiguration() const;
QString cachedPackageDirectory() const;
QString packageDirectory() const;
@@ -71,7 +67,8 @@ protected:
private slots:
void handleBuildConfigurationChanged();
- void setDeploymentInfoUnmodified();
+ void setDeploymentDataUnmodified();
+ void setDeploymentDataModified();
private:
virtual QString packageFileName() const = 0;
diff --git a/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp b/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
index ad4f77c51b..0cd603b625 100644
--- a/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxdeployservice.cpp
@@ -29,9 +29,7 @@
#include "abstractremotelinuxdeployservice.h"
-#include "deployablefile.h"
-
-#include <projectexplorer/buildconfiguration.h>
+#include <projectexplorer/deployablefile.h>
#include <projectexplorer/target.h>
#include <qtsupport/qtkitinformation.h>
#include <utils/qtcassert.h>
@@ -86,7 +84,7 @@ public:
: kit(0), connection(0), state(Inactive), stopRequested(false) {}
IDevice::ConstPtr deviceConfiguration;
- QPointer<BuildConfiguration> buildConfiguration;
+ QPointer<Target> target;
Kit *kit;
SshConnection *connection;
State state;
@@ -108,9 +106,9 @@ AbstractRemoteLinuxDeployService::~AbstractRemoteLinuxDeployService()
delete d;
}
-const BuildConfiguration *AbstractRemoteLinuxDeployService::buildConfiguration() const
+const Target *AbstractRemoteLinuxDeployService::target() const
{
- return d->buildConfiguration;
+ return d->target;
}
const Kit *AbstractRemoteLinuxDeployService::profile() const
@@ -130,15 +128,11 @@ SshConnection *AbstractRemoteLinuxDeployService::connection() const
void AbstractRemoteLinuxDeployService::saveDeploymentTimeStamp(const DeployableFile &deployableFile)
{
- if (!d->buildConfiguration)
+ if (!d->target)
return;
- const QtSupport::BaseQtVersion *const qtVersion
- = QtSupport::QtKitInformation::qtVersion(d->kit);
QString systemRoot;
if (SysRootKitInformation::hasSysRoot(d->kit))
systemRoot = SysRootKitInformation::sysRoot(d->kit).toString();
- if (!qtVersion || !qtVersion->isValid())
- return;
d->lastDeployed.insert(DeployParameters(deployableFile,
deviceConfiguration()->sshParameters().host,
systemRoot),
@@ -147,11 +141,7 @@ void AbstractRemoteLinuxDeployService::saveDeploymentTimeStamp(const DeployableF
bool AbstractRemoteLinuxDeployService::hasChangedSinceLastDeployment(const DeployableFile &deployableFile) const
{
- if (!d->buildConfiguration)
- return true;
- const QtSupport::BaseQtVersion *const qtVersion
- = QtSupport::QtKitInformation::qtVersion(d->kit);
- if (!qtVersion || !qtVersion->isValid())
+ if (!target())
return true;
QString systemRoot;
if (SysRootKitInformation::hasSysRoot(d->kit))
@@ -159,14 +149,14 @@ bool AbstractRemoteLinuxDeployService::hasChangedSinceLastDeployment(const Deplo
const QDateTime &lastDeployed = d->lastDeployed.value(DeployParameters(deployableFile,
deviceConfiguration()->sshParameters().host, systemRoot));
return !lastDeployed.isValid()
- || QFileInfo(deployableFile.localFilePath).lastModified() > lastDeployed;
+ || deployableFile.localFilePath().toFileInfo().lastModified() > lastDeployed;
}
-void AbstractRemoteLinuxDeployService::setBuildConfiguration(BuildConfiguration *bc)
+void AbstractRemoteLinuxDeployService::setTarget(Target *target)
{
- d->buildConfiguration = bc;
- if (bc && bc->target())
- d->kit = bc->target()->kit();
+ d->target = target;
+ if (target)
+ d->kit = target->kit();
else
d->kit = 0;
d->deviceConfiguration = DeviceKitInformation::device(d->kit);
@@ -235,8 +225,8 @@ QVariantMap AbstractRemoteLinuxDeployService::exportDeployTimes() const
QVariantList timeList;
typedef QHash<DeployParameters, QDateTime>::ConstIterator DepIt;
for (DepIt it = d->lastDeployed.begin(); it != d->lastDeployed.end(); ++it) {
- fileList << it.key().file.localFilePath;
- remotePathList << it.key().file.remoteDir;
+ fileList << it.key().file.localFilePath().toString();
+ remotePathList << it.key().file.remoteDirectory();
hostList << it.key().host;
sysrootList << it.key().sysroot;
timeList << it.value();
diff --git a/src/plugins/remotelinux/abstractremotelinuxdeployservice.h b/src/plugins/remotelinux/abstractremotelinuxdeployservice.h
index c34ba15546..0606700b72 100644
--- a/src/plugins/remotelinux/abstractremotelinuxdeployservice.h
+++ b/src/plugins/remotelinux/abstractremotelinuxdeployservice.h
@@ -40,17 +40,13 @@
namespace QSsh { class SshConnection; }
namespace ProjectExplorer {
-class BuildConfiguration;
+class DeployableFile;
class Kit;
+class Target;
}
namespace RemoteLinux {
-class DeployableFile;
-class DeploymentInfo;
-
-namespace Internal {
-class AbstractRemoteLinuxDeployServicePrivate;
-}
+namespace Internal { class AbstractRemoteLinuxDeployServicePrivate; }
class REMOTELINUX_EXPORT AbstractRemoteLinuxDeployService : public QObject
{
@@ -60,7 +56,7 @@ public:
explicit AbstractRemoteLinuxDeployService(QObject *parent = 0);
~AbstractRemoteLinuxDeployService();
- void setBuildConfiguration(ProjectExplorer::BuildConfiguration *bc);
+ void setTarget(ProjectExplorer::Target *bc);
void start();
void stop();
@@ -77,13 +73,13 @@ signals:
void stdErrData(const QString &data);
protected:
- const ProjectExplorer::BuildConfiguration *buildConfiguration() const;
+ const ProjectExplorer::Target *target() const;
const ProjectExplorer::Kit *profile() const;
ProjectExplorer::IDevice::ConstPtr deviceConfiguration() const;
QSsh::SshConnection *connection() const;
- void saveDeploymentTimeStamp(const DeployableFile &deployableFile);
- bool hasChangedSinceLastDeployment(const DeployableFile &deployableFile) const;
+ void saveDeploymentTimeStamp(const ProjectExplorer::DeployableFile &deployableFile);
+ bool hasChangedSinceLastDeployment(const ProjectExplorer::DeployableFile &deployableFile) const;
void handleDeviceSetupDone(bool success);
void handleDeploymentDone();
diff --git a/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp b/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp
index 066f911753..17f9964d2d 100644
--- a/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp
+++ b/src/plugins/remotelinux/abstractremotelinuxdeploystep.cpp
@@ -83,7 +83,7 @@ QVariantMap AbstractRemoteLinuxDeployStep::toMap() const
bool AbstractRemoteLinuxDeployStep::init()
{
QString error;
- deployService()->setBuildConfiguration(target()->activeBuildConfiguration());
+ deployService()->setTarget(target());
const bool canDeploy = initInternal(&error);
if (!canDeploy)
emit addOutput(tr("Cannot deploy: %1").arg(error), ErrorMessageOutput);
diff --git a/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp b/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp
index ffdd9556f3..ba10fbae02 100644
--- a/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp
+++ b/src/plugins/remotelinux/abstractuploadandinstallpackageservice.cpp
@@ -29,16 +29,18 @@
#include "abstractuploadandinstallpackageservice.h"
-#include "deployablefile.h"
#include "packageuploader.h"
#include "remotelinuxpackageinstaller.h"
+#include <projectexplorer/deployablefile.h>
#include <utils/qtcassert.h>
#include <ssh/sshconnection.h>
#include <QFileInfo>
#include <QString>
+using namespace ProjectExplorer;
+
namespace RemoteLinux {
namespace Internal {
namespace {
diff --git a/src/plugins/remotelinux/deployablefilesperprofile.cpp b/src/plugins/remotelinux/deployablefilesperprofile.cpp
deleted file mode 100644
index 9db1eccad5..0000000000
--- a/src/plugins/remotelinux/deployablefilesperprofile.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-#include "deployablefilesperprofile.h"
-
-#include "deployablefile.h"
-
-#include <utils/qtcassert.h>
-
-#include <QFileInfo>
-#include <QDir>
-#include <QBrush>
-
-using namespace Qt4ProjectManager;
-
-namespace RemoteLinux {
-namespace Internal {
-class DeployableFilesPerProFilePrivate
-{
-public:
- DeployableFilesPerProFilePrivate(const Qt4ProFileNode *proFileNode)
- : projectType(proFileNode->projectType()),
- proFilePath(proFileNode->path()),
- projectName(proFileNode->displayName()),
- targetInfo(proFileNode->targetInformation()),
- installsList(proFileNode->installsList()),
- projectVersion(proFileNode->projectVersion()),
- config(proFileNode->variableValue(ConfigVar)),
- modified(true)
- {
- }
-
- const Qt4ProjectType projectType;
- const QString proFilePath;
- const QString projectName;
- const Qt4ProjectManager::TargetInformation targetInfo;
- const Qt4ProjectManager::InstallsList installsList;
- const Qt4ProjectManager::ProjectVersion projectVersion;
- const QStringList config;
- QList<DeployableFile> deployables;
- bool modified;
-};
-
-} // namespace Internal
-
-using namespace Internal;
-
-DeployableFilesPerProFile::DeployableFilesPerProFile(const Qt4ProFileNode *proFileNode,
- const QString &installPrefix, QObject *parent)
- : QAbstractTableModel(parent), d(new DeployableFilesPerProFilePrivate(proFileNode))
-{
- if (hasTargetPath()) {
- if (d->projectType == ApplicationTemplate) {
- d->deployables.prepend(DeployableFile(localExecutableFilePath(),
- d->installsList.targetPath, DeployableFile::TypeExecutable));
- } else if (d->projectType == LibraryTemplate) {
- foreach (const QString &filePath, localLibraryFilePaths()) {
- d->deployables.prepend(DeployableFile(filePath,
- d->installsList.targetPath));
- }
- }
- }
-
- foreach (const InstallsItem &elem, d->installsList.items) {
- foreach (const QString &file, elem.files)
- d->deployables << DeployableFile(file, elem.path);
- }
-
- if (!installPrefix.isEmpty()) {
- for (int i = 0; i < d->deployables.count(); ++i)
- d->deployables[i].remoteDir.prepend(installPrefix + QLatin1Char('/'));
- }
-}
-
-DeployableFilesPerProFile::~DeployableFilesPerProFile()
-{
- delete d;
-}
-
-DeployableFile DeployableFilesPerProFile::deployableAt(int row) const
-{
- Q_ASSERT(row >= 0 && row < rowCount());
- return d->deployables.at(row);
-}
-
-int DeployableFilesPerProFile::rowCount(const QModelIndex &parent) const
-{
- return parent.isValid() ? 0 : d->deployables.count();
-}
-
-int DeployableFilesPerProFile::columnCount(const QModelIndex &parent) const
-{
- return parent.isValid() ? 0 : 2;
-}
-
-QVariant DeployableFilesPerProFile::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid() || index.row() >= rowCount())
- return QVariant();
-
- const DeployableFile &d = deployableAt(index.row());
- if (index.column() == 0 && role == Qt::DisplayRole)
- return QDir::toNativeSeparators(d.localFilePath);
- if (role == Qt::DisplayRole)
- return QDir::cleanPath(d.remoteDir);
- return QVariant();
-}
-
-QVariant DeployableFilesPerProFile::headerData(int section,
- Qt::Orientation orientation, int role) const
-{
- if (orientation == Qt::Vertical || role != Qt::DisplayRole)
- return QVariant();
- return section == 0 ? tr("Local File Path") : tr("Remote Directory");
-}
-
-QString DeployableFilesPerProFile::localExecutableFilePath() const
-{
- if (!d->targetInfo.valid || d->projectType != ApplicationTemplate)
- return QString();
- return QDir::cleanPath(d->targetInfo.workingDir + '/' + d->targetInfo.target);
-}
-
-QStringList DeployableFilesPerProFile::localLibraryFilePaths() const
-{
- QStringList list;
-
- if (!d->targetInfo.valid || d->projectType != LibraryTemplate)
- return list;
- QString basePath = d->targetInfo.workingDir + QLatin1String("/lib");
- const bool isStatic = d->config.contains(QLatin1String("static"))
- || d->config.contains(QLatin1String("staticlib"));
- basePath += d->targetInfo.target + QLatin1String(isStatic ? ".a" : ".so");
- basePath = QDir::cleanPath(basePath);
- if (!isStatic && !d->config.contains(QLatin1String("plugin"))) {
- const QChar dot(QLatin1Char('.'));
- const QString filePathMajor = basePath + dot
- + QString::number(d->projectVersion.major);
- const QString filePathMinor = filePathMajor + dot
- + QString::number(d->projectVersion.minor);
- const QString filePathPatch = filePathMinor + dot
- + QString::number(d->projectVersion.patch);
- list << filePathPatch << filePathMinor << filePathMajor;
- }
- return list << basePath;
-}
-
-QString DeployableFilesPerProFile::remoteExecutableFilePath() const
-{
- return hasTargetPath() && d->projectType == ApplicationTemplate
- ? deployableAt(0).remoteDir + QLatin1Char('/')
- + QFileInfo(localExecutableFilePath()).fileName()
- : QString();
-}
-
-QString DeployableFilesPerProFile::projectDir() const
-{
- return QFileInfo(d->proFilePath).dir().path();
-}
-
-bool DeployableFilesPerProFile::hasTargetPath() const
-{
- return !d->installsList.targetPath.isEmpty();
-}
-
-bool DeployableFilesPerProFile::isModified() const { return d->modified; }
-void DeployableFilesPerProFile::setUnModified() { d->modified = false; }
-QString DeployableFilesPerProFile::projectName() const { return d->projectName; }
-QString DeployableFilesPerProFile::proFilePath() const { return d->proFilePath; }
-Qt4ProjectType DeployableFilesPerProFile::projectType() const { return d->projectType; }
-QString DeployableFilesPerProFile::applicationName() const { return d->targetInfo.target; }
-
-} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/deployablefilesperprofile.h b/src/plugins/remotelinux/deployablefilesperprofile.h
deleted file mode 100644
index 8a424e4037..0000000000
--- a/src/plugins/remotelinux/deployablefilesperprofile.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#ifndef DEPLOYABLEFILESPERPROFILE_H
-#define DEPLOYABLEFILESPERPROFILE_H
-
-#include "remotelinux_export.h"
-
-#include <qt4projectmanager/qt4nodes.h>
-
-#include <QAbstractTableModel>
-#include <QList>
-#include <QString>
-
-namespace RemoteLinux {
-class DeployableFile;
-
-namespace Internal {
-class DeployableFilesPerProFilePrivate;
-}
-
-class REMOTELINUX_EXPORT DeployableFilesPerProFile : public QAbstractTableModel
-{
- Q_OBJECT
-public:
- DeployableFilesPerProFile(const Qt4ProjectManager::Qt4ProFileNode *proFileNode,
- const QString &installPrefix, QObject *parent);
- ~DeployableFilesPerProFile();
-
- virtual int rowCount(const QModelIndex &parent = QModelIndex()) const;
-
- DeployableFile deployableAt(int row) const;
- bool isModified() const;
- void setUnModified();
- QString localExecutableFilePath() const;
- QString remoteExecutableFilePath() const;
- QString projectName() const;
- QString projectDir() const;
- QString proFilePath() const;
- Qt4ProjectManager::Qt4ProjectType projectType() const;
- bool isApplicationProject() const { return projectType() == Qt4ProjectManager::ApplicationTemplate; }
- QString applicationName() const;
- bool hasTargetPath() const;
-
-private:
- virtual int columnCount(const QModelIndex &parent = QModelIndex()) const;
- virtual QVariant data(const QModelIndex &index,
- int role = Qt::DisplayRole) const;
- virtual QVariant headerData(int section, Qt::Orientation orientation,
- int role = Qt::DisplayRole) const;
-
- QStringList localLibraryFilePaths() const;
-
- Internal::DeployableFilesPerProFilePrivate * const d;
-};
-
-} // namespace RemoteLinux
-
-#endif // DEPLOYABLEFILESPERPROFILE_H
diff --git a/src/plugins/remotelinux/deploymentinfo.cpp b/src/plugins/remotelinux/deploymentinfo.cpp
deleted file mode 100644
index e70d851212..0000000000
--- a/src/plugins/remotelinux/deploymentinfo.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "deploymentinfo.h"
-
-#include "deployablefile.h"
-#include "deployablefilesperprofile.h"
-#include "remotelinuxdeployconfiguration.h"
-
-#include <projectexplorer/buildstep.h>
-#include <projectexplorer/target.h>
-#include <qt4projectmanager/qt4project.h>
-#include <qtsupport/qtkitinformation.h>
-
-#include <QList>
-#include <QTimer>
-
-using namespace Qt4ProjectManager;
-
-namespace RemoteLinux {
-namespace Internal {
-class DeploymentInfoPrivate
-{
-public:
- DeploymentInfoPrivate(const Qt4ProjectManager::Qt4Project *p) : project(p) {}
-
- QList<DeployableFilesPerProFile *> listModels;
- const Qt4ProjectManager::Qt4Project *const project;
- QString installPrefix;
-};
-} // namespace Internal
-
-using namespace Internal;
-
-DeploymentInfo::DeploymentInfo(Qt4ProjectManager::Qt4Project *project, const QString &installPrefix)
- : QAbstractListModel(project), d(new DeploymentInfoPrivate(project))
-{
- connect(project, SIGNAL(proFilesEvaluated()), SLOT(createModels()));
- setInstallPrefix(installPrefix);
-}
-
-DeploymentInfo::~DeploymentInfo()
-{
- delete d;
-}
-
-void DeploymentInfo::createModels()
-{
- ProjectExplorer::Target *target = d->project->activeTarget();
- if (!target
- || !target->activeDeployConfiguration()
- || !qobject_cast<RemoteLinuxDeployConfiguration *>(target->activeDeployConfiguration()))
- return;
-
- QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(target->kit());
- if (!version || !version->isValid()) {
- beginResetModel();
- qDeleteAll(d->listModels);
- d->listModels.clear();
- endResetModel();
- return;
- }
- const Qt4ProFileNode *const rootNode = d->project->rootQt4ProjectNode();
- if (!rootNode || rootNode->parseInProgress()) // Can be null right after project creation by wizard.
- return;
- disconnect(d->project, SIGNAL(proFilesEvaluated()), this, SLOT(createModels()));
- beginResetModel();
- qDeleteAll(d->listModels);
- d->listModels.clear();
- createModels(rootNode);
- endResetModel();
- connect (d->project, SIGNAL(proFilesEvaluated()), SLOT(createModels()));
-}
-
-void DeploymentInfo::createModels(const Qt4ProFileNode *proFileNode)
-{
- switch (proFileNode->projectType()) {
- case ApplicationTemplate:
- case LibraryTemplate:
- case AuxTemplate:
- d->listModels << new DeployableFilesPerProFile(proFileNode, d->installPrefix, this);
- break;
- case SubDirsTemplate: {
- const QList<Qt4PriFileNode *> &subProjects = proFileNode->subProjectNodesExact();
- foreach (const ProjectExplorer::ProjectNode * const subProject, subProjects) {
- const Qt4ProFileNode * const qt4SubProject
- = qobject_cast<const Qt4ProFileNode *>(subProject);
- if (!qt4SubProject)
- continue;
- if (qt4SubProject->path().endsWith(QLatin1String(".pri")))
- continue;
- if (!proFileNode->isSubProjectDeployable(subProject->path()))
- continue;
- createModels(qt4SubProject);
- }
- }
- default:
- break;
- }
-}
-
-void DeploymentInfo::setUnmodified()
-{
- foreach (DeployableFilesPerProFile * const model, d->listModels)
- model->setUnModified();
-}
-
-bool DeploymentInfo::isModified() const
-{
- foreach (const DeployableFilesPerProFile * const model, d->listModels) {
- if (model->isModified())
- return true;
- }
- return false;
-}
-
-void DeploymentInfo::setInstallPrefix(const QString &installPrefix)
-{
- d->installPrefix = installPrefix;
- createModels();
-}
-
-int DeploymentInfo::deployableCount() const
-{
- int count = 0;
- foreach (const DeployableFilesPerProFile * const model, d->listModels)
- count += model->rowCount();
- return count;
-}
-
-DeployableFile DeploymentInfo::deployableAt(int i) const
-{
- foreach (const DeployableFilesPerProFile * const model, d->listModels) {
- Q_ASSERT(i >= 0);
- if (i < model->rowCount())
- return model->deployableAt(i);
- i -= model->rowCount();
- }
-
- Q_ASSERT(!"Invalid deployable number");
- return DeployableFile(QString(), QString());
-}
-
-QString DeploymentInfo::remoteExecutableFilePath(const QString &localExecutableFilePath) const
-{
- foreach (const DeployableFilesPerProFile * const model, d->listModels) {
- if (model->localExecutableFilePath() == localExecutableFilePath)
- return model->remoteExecutableFilePath();
- }
- return QString();
-}
-
-int DeploymentInfo::rowCount(const QModelIndex &parent) const
-{
- return parent.isValid() ? 0 : modelCount();
-}
-
-QVariant DeploymentInfo::data(const QModelIndex &index, int role) const
-{
- if (!index.isValid() || index.row() < 0 || index.row() >= modelCount()
- || index.column() != 0)
- return QVariant();
- const DeployableFilesPerProFile * const model = d->listModels.at(index.row());
- if (role == Qt::ForegroundRole && model->projectType() != AuxTemplate
- && !model->hasTargetPath()) {
- QBrush brush;
- brush.setColor(Qt::red);
- return brush;
- }
- if (role == Qt::DisplayRole)
- return QFileInfo(model->proFilePath()).fileName();
- return QVariant();
-}
-
-int DeploymentInfo::modelCount() const { return d->listModels.count(); }
-DeployableFilesPerProFile *DeploymentInfo::modelAt(int i) const { return d->listModels.at(i); }
-
-} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/deploymentsettingsassistant.cpp b/src/plugins/remotelinux/deploymentsettingsassistant.cpp
deleted file mode 100644
index 6055ed5b5e..0000000000
--- a/src/plugins/remotelinux/deploymentsettingsassistant.cpp
+++ /dev/null
@@ -1,175 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-#include "deploymentsettingsassistant.h"
-
-#include "deploymentinfo.h"
-#include "deployablefile.h"
-#include "deployablefilesperprofile.h"
-#include "profilesupdatedialog.h"
-#include "remotelinuxdeployconfiguration.h"
-
-#include <coreplugin/documentmanager.h>
-#include <coreplugin/icore.h>
-#include <projectexplorer/project.h>
-#include <projectexplorer/target.h>
-#include <qt4projectmanager/qt4nodes.h>
-#include <utils/fileutils.h>
-#include <utils/qtcassert.h>
-
-#include <QDir>
-#include <QHash>
-#include <QString>
-
-using namespace Qt4ProjectManager;
-
-namespace RemoteLinux {
-namespace Internal {
-namespace {
-
-enum ProFileUpdateSetting { UpdateProFile, DontUpdateProFile };
-typedef QHash<QString, ProFileUpdateSetting> UpdateSettingsMap;
-
-} // anonymous namespace
-
-class DeploymentSettingsAssistantInternal
-{
-public:
- DeploymentSettingsAssistantInternal(DeploymentInfo *deploymentInfo)
- : deploymentInfo(deploymentInfo)
- {
- }
-
- DeploymentInfo * const deploymentInfo;
- UpdateSettingsMap updateSettings;
-};
-
-} // namespace Internal
-
-using namespace Internal;
-
-DeploymentSettingsAssistant::DeploymentSettingsAssistant(DeploymentInfo *deploymentInfo,
- ProjectExplorer::Project *parent)
- : QObject(parent),
- d(new DeploymentSettingsAssistantInternal(deploymentInfo))
-{
- connect(d->deploymentInfo, SIGNAL(modelReset()), SLOT(handleDeploymentInfoUpdated()));
-}
-
-DeploymentSettingsAssistant::~DeploymentSettingsAssistant()
-{
- delete d;
-}
-
-bool DeploymentSettingsAssistant::addDeployableToProFile(const QString &qmakeScope,
- const DeployableFilesPerProFile *proFileInfo, const QString &variableName,
- const DeployableFile &deployable)
-{
- const QString filesLine = variableName + QLatin1String(".files = ")
- + QDir(proFileInfo->projectDir()).relativeFilePath(deployable.localFilePath);
- const QString pathLine = variableName + QLatin1String(".path = ") + deployable.remoteDir;
- const QString installsLine = QLatin1String("INSTALLS += ") + variableName;
- return addLinesToProFile(qmakeScope, proFileInfo,
- QStringList() << filesLine << pathLine << installsLine);
-}
-
-bool DeploymentSettingsAssistant::addLinesToProFile(const QString &qmakeScope,
- const DeployableFilesPerProFile *proFileInfo,
- const QStringList &lines)
-{
- Core::FileChangeBlocker update(proFileInfo->proFilePath());
-
- const QString separator = QLatin1String("\n ");
- const QString proFileString = QLatin1Char('\n') + qmakeScope + QLatin1String(" {")
- + separator + lines.join(separator) + QLatin1String("\n}\n");
- Utils::FileSaver saver(proFileInfo->proFilePath(), QIODevice::Append);
- saver.write(proFileString.toLocal8Bit());
- return saver.finalize(Core::ICore::mainWindow());
-}
-
-void DeploymentSettingsAssistant::handleDeploymentInfoUpdated()
-{
- ProjectExplorer::Project *project = static_cast<ProjectExplorer::Project *>(parent());
- QStringList scopes;
- QStringList pathes;
- foreach (ProjectExplorer::Target *target, project->targets()) {
- foreach (ProjectExplorer::DeployConfiguration *dc, target->deployConfigurations()) {
- RemoteLinuxDeployConfiguration *rldc = qobject_cast<RemoteLinuxDeployConfiguration *>(dc);
- if (!rldc)
- continue;
- const QString scope = rldc->qmakeScope();
- if (!scopes.contains(scope)) {
- scopes.append(scope);
- pathes.append(rldc->installPrefix());
- }
- }
- }
- if (scopes.isEmpty())
- return;
-
- QList<DeployableFilesPerProFile *> proFilesToAskAbout;
- QList<DeployableFilesPerProFile *> proFilesToUpdate;
- for (int i = 0; i < d->deploymentInfo->modelCount(); ++i) {
- DeployableFilesPerProFile * const proFileInfo = d->deploymentInfo->modelAt(i);
- if (proFileInfo->projectType() != AuxTemplate && !proFileInfo->hasTargetPath()) {
- const UpdateSettingsMap::ConstIterator it
- = d->updateSettings.find(proFileInfo->proFilePath());
- if (it == d->updateSettings.constEnd())
- proFilesToAskAbout << proFileInfo;
- else if (it.value() == UpdateProFile)
- proFilesToUpdate << proFileInfo;
- }
- }
-
- if (!proFilesToAskAbout.isEmpty()) {
- ProFilesUpdateDialog dialog(proFilesToAskAbout);
- dialog.exec();
- const QList<ProFilesUpdateDialog::UpdateSetting> &settings = dialog.getUpdateSettings();
- foreach (const ProFilesUpdateDialog::UpdateSetting &setting, settings) {
- const ProFileUpdateSetting updateSetting = setting.second
- ? UpdateProFile : DontUpdateProFile;
- d->updateSettings.insert(setting.first->proFilePath(), updateSetting);
- if (updateSetting == UpdateProFile)
- proFilesToUpdate << setting.first;
- }
- }
-
- foreach (const DeployableFilesPerProFile * const proFileInfo, proFilesToUpdate) {
- const QString remoteDirSuffix = QLatin1String(proFileInfo->projectType() == LibraryTemplate
- ? "/lib" : "/bin");
- for (int i = 0; i < scopes.count(); ++i) {
- const QString remoteDir = QLatin1String("target.path = ") + pathes.at(i)
- + QLatin1Char('/') + proFileInfo->projectName() + remoteDirSuffix;
- const QStringList deployInfo = QStringList() << remoteDir
- << QLatin1String("INSTALLS += target");
- addLinesToProFile(scopes.at(i), proFileInfo, deployInfo);
- }
- }
-}
-
-} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/embeddedlinuxqtversion.cpp b/src/plugins/remotelinux/embeddedlinuxqtversion.cpp
index 75f5b8d4b1..c9b2ff5fe3 100644
--- a/src/plugins/remotelinux/embeddedlinuxqtversion.cpp
+++ b/src/plugins/remotelinux/embeddedlinuxqtversion.cpp
@@ -44,7 +44,9 @@ EmbeddedLinuxQtVersion::EmbeddedLinuxQtVersion()
EmbeddedLinuxQtVersion::EmbeddedLinuxQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource)
: BaseQtVersion(path, isAutodetected, autodetectionSource)
-{ }
+{
+ setDisplayName(defaultDisplayName(qtVersionString(), path, false));
+}
EmbeddedLinuxQtVersion::~EmbeddedLinuxQtVersion()
{ }
@@ -56,7 +58,7 @@ EmbeddedLinuxQtVersion *EmbeddedLinuxQtVersion::clone() const
QString EmbeddedLinuxQtVersion::type() const
{
- return RemoteLinux::Constants::EMBEDDED_LINUX_QT;
+ return QLatin1String(RemoteLinux::Constants::EMBEDDED_LINUX_QT);
}
QList<ProjectExplorer::Abi> EmbeddedLinuxQtVersion::detectQtAbis() const
diff --git a/src/plugins/remotelinux/genericdirectuploadservice.cpp b/src/plugins/remotelinux/genericdirectuploadservice.cpp
index 810d39b09c..a10a5deadb 100644
--- a/src/plugins/remotelinux/genericdirectuploadservice.cpp
+++ b/src/plugins/remotelinux/genericdirectuploadservice.cpp
@@ -28,8 +28,7 @@
****************************************************************************/
#include "genericdirectuploadservice.h"
-#include "deployablefile.h"
-
+#include <projectexplorer/deployablefile.h>
#include <utils/qtcassert.h>
#include <ssh/sftpchannel.h>
#include <ssh/sshconnection.h>
@@ -40,6 +39,7 @@
#include <QList>
#include <QString>
+using namespace ProjectExplorer;
using namespace QSsh;
namespace RemoteLinux {
@@ -163,8 +163,9 @@ void GenericDirectUploadService::handleUploadFinished(QSsh::SftpJobId jobId, con
const DeployableFile df = d->filesToUpload.takeFirst();
if (!errorMsg.isEmpty()) {
QString errorString = tr("Upload of file '%1' failed. The server said: '%2'.")
- .arg(QDir::toNativeSeparators(df.localFilePath), errorMsg);
- if (errorMsg == QLatin1String("Failure") && df.remoteDir.contains(QLatin1String("/bin"))) {
+ .arg(df.localFilePath().toUserOutput(), errorMsg);
+ if (errorMsg == QLatin1String("Failure")
+ && df.remoteDirectory().contains(QLatin1String("/bin"))) {
errorString += QLatin1Char(' ') + tr("If '%1' is currently running "
"on the remote host, you might need to stop it first.").arg(df.remoteFilePath());
}
@@ -200,7 +201,7 @@ void GenericDirectUploadService::handleLnFinished(int exitStatus)
}
const DeployableFile df = d->filesToUpload.takeFirst();
- const QString nativePath = QDir::toNativeSeparators(df.localFilePath);
+ const QString nativePath = df.localFilePath().toUserOutput();
if (exitStatus != SshRemoteProcess::NormalExit || d->lnProc->exitCode() != 0) {
emit errorMessage(tr("Failed to upload file '%1'.").arg(nativePath));
setFinished();
@@ -241,8 +242,8 @@ void GenericDirectUploadService::handleMkdirFinished(int exitStatus)
}
const DeployableFile &df = d->filesToUpload.first();
- QFileInfo fi(df.localFilePath);
- const QString nativePath = QDir::toNativeSeparators(df.localFilePath);
+ QFileInfo fi = df.localFilePath().toFileInfo();
+ const QString nativePath = df.localFilePath().toUserOutput();
if (exitStatus != SshRemoteProcess::NormalExit || d->mkdirProc->exitCode() != 0) {
emit errorMessage(tr("Failed to upload file '%1'.").arg(nativePath));
setFinished();
@@ -252,7 +253,7 @@ void GenericDirectUploadService::handleMkdirFinished(int exitStatus)
d->filesToUpload.removeFirst();
uploadNextFile();
} else {
- const QString remoteFilePath = df.remoteDir + QLatin1Char('/') + fi.fileName();
+ const QString remoteFilePath = df.remoteDirectory() + QLatin1Char('/') + fi.fileName();
if (fi.isSymLink()) {
const QString target = fi.dir().relativeFilePath(fi.symLinkTarget()); // see QTBUG-5817.
const QString command = QLatin1String("ln -sf ") + target + QLatin1Char(' ')
@@ -265,8 +266,8 @@ void GenericDirectUploadService::handleMkdirFinished(int exitStatus)
connect(d->lnProc.data(), SIGNAL(readyReadStandardError()), SLOT(handleStdErrData()));
d->lnProc->start();
} else {
- const SftpJobId job = d->uploader->uploadFile(df.localFilePath, remoteFilePath,
- SftpOverwriteExisting);
+ const SftpJobId job = d->uploader->uploadFile(df.localFilePath().toString(),
+ remoteFilePath, SftpOverwriteExisting);
if (job == SftpInvalidJob) {
emit errorMessage(tr("Failed to upload file '%1': "
"Could not open for reading.").arg(nativePath));
@@ -301,16 +302,16 @@ void GenericDirectUploadService::stopDeployment()
void GenericDirectUploadService::checkDeploymentNeeded(const DeployableFile &deployable) const
{
- QFileInfo fileInfo(deployable.localFilePath);
+ QFileInfo fileInfo = deployable.localFilePath().toFileInfo();
if (fileInfo.isDir()) {
- const QStringList files = QDir(deployable.localFilePath)
+ const QStringList files = QDir(deployable.localFilePath().toString())
.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
if (files.isEmpty() && (!d->incremental || hasChangedSinceLastDeployment(deployable)))
d->filesToUpload << deployable;
foreach (const QString &fileName, files) {
- const QString localFilePath = deployable.localFilePath
+ const QString localFilePath = deployable.localFilePath().toString()
+ QLatin1Char('/') + fileName;
- const QString remoteDir = deployable.remoteDir + QLatin1Char('/')
+ const QString remoteDir = deployable.remoteDirectory() + QLatin1Char('/')
+ fileInfo.fileName();
checkDeploymentNeeded(DeployableFile(localFilePath, remoteDir));
}
@@ -343,16 +344,16 @@ void GenericDirectUploadService::uploadNextFile()
}
const DeployableFile &df = d->filesToUpload.first();
- QString dirToCreate = df.remoteDir;
+ QString dirToCreate = df.remoteDirectory();
if (dirToCreate.isEmpty()) {
emit warningMessage(tr("Warning: No remote path set for local file '%1'. Skipping upload.")
- .arg(QDir::toNativeSeparators(df.localFilePath)));
+ .arg(df.localFilePath().toUserOutput()));
d->filesToUpload.takeFirst();
uploadNextFile();
return;
}
- QFileInfo fi(df.localFilePath);
+ QFileInfo fi = df.localFilePath().toFileInfo();
if (fi.isDir())
dirToCreate += QLatin1Char('/') + fi.fileName();
const QString command = QLatin1String("mkdir -p ") + dirToCreate;
@@ -361,7 +362,7 @@ void GenericDirectUploadService::uploadNextFile()
connect(d->mkdirProc.data(), SIGNAL(readyReadStandardOutput()), SLOT(handleStdOutData()));
connect(d->mkdirProc.data(), SIGNAL(readyReadStandardError()), SLOT(handleStdErrData()));
emit progressMessage(tr("Uploading file '%1'...")
- .arg(QDir::toNativeSeparators(df.localFilePath)));
+ .arg(df.localFilePath().toUserOutput()));
d->mkdirProc->start();
}
diff --git a/src/plugins/remotelinux/genericdirectuploadservice.h b/src/plugins/remotelinux/genericdirectuploadservice.h
index d2c666596c..047b42db6e 100644
--- a/src/plugins/remotelinux/genericdirectuploadservice.h
+++ b/src/plugins/remotelinux/genericdirectuploadservice.h
@@ -38,8 +38,9 @@
QT_FORWARD_DECLARE_CLASS(QString)
+namespace ProjectExplorer { class DeployableFile; }
+
namespace RemoteLinux {
-class DeployableFile;
namespace Internal { class GenericDirectUploadServicePrivate; }
class REMOTELINUX_EXPORT GenericDirectUploadService : public AbstractRemoteLinuxDeployService
@@ -49,7 +50,7 @@ public:
GenericDirectUploadService(QObject *parent = 0);
~GenericDirectUploadService();
- void setDeployableFiles(const QList<DeployableFile> &deployableFiles);
+ void setDeployableFiles(const QList<ProjectExplorer::DeployableFile> &deployableFiles);
void setIncrementalDeployment(bool incremental);
protected:
@@ -72,7 +73,7 @@ private slots:
void handleStdErrData();
private:
- void checkDeploymentNeeded(const DeployableFile &file) const;
+ void checkDeploymentNeeded(const ProjectExplorer::DeployableFile &file) const;
void setFinished();
void uploadNextFile();
diff --git a/src/plugins/remotelinux/genericdirectuploadstep.cpp b/src/plugins/remotelinux/genericdirectuploadstep.cpp
index 8aedba9682..dae40b9dd9 100644
--- a/src/plugins/remotelinux/genericdirectuploadstep.cpp
+++ b/src/plugins/remotelinux/genericdirectuploadstep.cpp
@@ -28,11 +28,12 @@
****************************************************************************/
#include "genericdirectuploadstep.h"
-#include "deployablefile.h"
-#include "deploymentinfo.h"
#include "genericdirectuploadservice.h"
#include "remotelinuxdeployconfiguration.h"
+#include <projectexplorer/deploymentdata.h>
+#include <projectexplorer/target.h>
+
#include <QCheckBox>
#include <QVBoxLayout>
#include <QList>
@@ -108,12 +109,7 @@ BuildStepConfigWidget *GenericDirectUploadStep::createConfigWidget()
bool GenericDirectUploadStep::initInternal(QString *error)
{
- QList<DeployableFile> deployableFiles;
- const DeploymentInfo * const deploymentInfo = deployConfiguration()->deploymentInfo();
- const int deployableCount = deploymentInfo->deployableCount();
- for (int i = 0; i < deployableCount; ++i)
- deployableFiles << deploymentInfo->deployableAt(i);
- deployService()->setDeployableFiles(deployableFiles);
+ deployService()->setDeployableFiles(target()->deploymentData().allFiles());
deployService()->setIncrementalDeployment(incrementalDeployment());
return deployService()->isDeploymentPossible(error);
}
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
index 7816570190..a23caac9a6 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwidget.cpp
@@ -173,7 +173,7 @@ void GenericLinuxDeviceConfigurationWidget::initGui()
m_ui->machineTypeValueLabel->setText(tr("Physical Device"));
else
m_ui->machineTypeValueLabel->setText(tr("Emulator"));
- m_ui->portsWarningLabel->setPixmap(QPixmap(":/projectexplorer/images/compile_error.png"));
+ m_ui->portsWarningLabel->setPixmap(QPixmap(QLatin1String(":/projectexplorer/images/compile_error.png")));
m_ui->portsWarningLabel->setToolTip(QLatin1String("<font color=\"red\">")
+ tr("You will need at least one port.") + QLatin1String("</font>"));
m_ui->keyFileLineEdit->setExpectedKind(PathChooser::File);
diff --git a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
index c6634aa795..add6ab5909 100644
--- a/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
+++ b/src/plugins/remotelinux/genericlinuxdeviceconfigurationwizard.cpp
@@ -77,6 +77,7 @@ GenericLinuxDeviceConfigurationWizard::~GenericLinuxDeviceConfigurationWizard()
IDevice::Ptr GenericLinuxDeviceConfigurationWizard::device()
{
QSsh::SshConnectionParameters sshParams;
+ sshParams.options &= ~SshConnectionOptions(SshEnableStrictConformanceChecks); // For older SSH servers.
sshParams.host = d->setupPage.hostName();
sshParams.userName = d->setupPage.userName();
sshParams.port = 22;
diff --git a/src/plugins/remotelinux/linuxdevice.cpp b/src/plugins/remotelinux/linuxdevice.cpp
index 73aed66384..9a537b22f2 100644
--- a/src/plugins/remotelinux/linuxdevice.cpp
+++ b/src/plugins/remotelinux/linuxdevice.cpp
@@ -71,7 +71,7 @@ private:
"cat $dir/stat;"
"readlink $dir/exe;"
"printf '%1''%2';"
- "done").arg(Delimiter0).arg(Delimiter1);
+ "done").arg(QLatin1String(Delimiter0)).arg(QLatin1String(Delimiter1));
}
QList<DeviceProcess> buildProcessList(const QString &listProcessesReply) const
diff --git a/src/plugins/remotelinux/profilesupdatedialog.cpp b/src/plugins/remotelinux/profilesupdatedialog.cpp
deleted file mode 100644
index d5b01a48b6..0000000000
--- a/src/plugins/remotelinux/profilesupdatedialog.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-#include "profilesupdatedialog.h"
-#include "ui_profilesupdatedialog.h"
-
-#include "deployablefilesperprofile.h"
-
-#include <qt4projectmanager/qt4nodes.h>
-
-#include <QDir>
-#include <QTableWidgetItem>
-
-namespace RemoteLinux {
-namespace Internal {
-
-ProFilesUpdateDialog::ProFilesUpdateDialog(const QList<DeployableFilesPerProFile *> &models,
- QWidget *parent)
- : QDialog(parent),
- m_models(models),
- ui(new Ui::ProFilesUpdateDialog)
-{
- ui->setupUi(this);
- ui->tableWidget->setRowCount(models.count());
- ui->tableWidget->setHorizontalHeaderItem(0,
- new QTableWidgetItem(tr("Updateable Project Files")));
- for (int row = 0; row < models.count(); ++row) {
- QTableWidgetItem *const item
- = new QTableWidgetItem(QDir::toNativeSeparators(models.at(row)->proFilePath()));
- item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
- item->setCheckState(Qt::Unchecked);
- ui->tableWidget->setItem(row, 0, item);
- }
- ui->tableWidget->horizontalHeader()->setResizeMode(QHeaderView::ResizeToContents);
- ui->tableWidget->resizeRowsToContents();
- connect(ui->checkAllButton, SIGNAL(clicked()), this, SLOT(checkAll()));
- connect(ui->uncheckAllButton, SIGNAL(clicked()), this, SLOT(uncheckAll()));
-}
-
-ProFilesUpdateDialog::~ProFilesUpdateDialog()
-{
- delete ui;
-}
-
-void ProFilesUpdateDialog::checkAll()
-{
- setCheckStateForAll(Qt::Checked);
-}
-
-void ProFilesUpdateDialog::uncheckAll()
-{
- setCheckStateForAll(Qt::Unchecked);
-}
-
-void ProFilesUpdateDialog::setCheckStateForAll(Qt::CheckState checkState)
-{
- for (int row = 0; row < ui->tableWidget->rowCount(); ++row) {
- ui->tableWidget->item(row, 0)->setCheckState(checkState);
- }
-}
-
-QList<ProFilesUpdateDialog::UpdateSetting> ProFilesUpdateDialog::getUpdateSettings() const
-{
- QList<UpdateSetting> settings;
- for (int row = 0; row < m_models.count(); ++row) {
- const bool doUpdate = result() != Rejected
- && ui->tableWidget->item(row, 0)->checkState() == Qt::Checked;
- settings << UpdateSetting(m_models.at(row), doUpdate);
- }
- return settings;
-}
-
-} // namespace RemoteLinux
-} // namespace Internal
diff --git a/src/plugins/remotelinux/profilesupdatedialog.ui b/src/plugins/remotelinux/profilesupdatedialog.ui
deleted file mode 100644
index 7885a3f418..0000000000
--- a/src/plugins/remotelinux/profilesupdatedialog.ui
+++ /dev/null
@@ -1,139 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>RemoteLinux::Internal::ProFilesUpdateDialog</class>
- <widget class="QDialog" name="RemoteLinux::Internal::ProFilesUpdateDialog">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>659</width>
- <height>494</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>Maemo Deployment Issue</string>
- </property>
- <layout class="QVBoxLayout" name="verticalLayout">
- <item>
- <widget class="QLabel" name="infoLabel">
- <property name="text">
- <string>The project files listed below do not contain deployment information, which means the respective targets cannot be deployed to and/or run on a device. Qt Creator will add the missing information to these files if you check the respective rows below.</string>
- </property>
- <property name="wordWrap">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QPushButton" name="checkAllButton">
- <property name="text">
- <string>&amp;Check all</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QPushButton" name="uncheckAllButton">
- <property name="text">
- <string>&amp;Uncheck All</string>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- <item>
- <widget class="Line" name="line_2">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QTableWidget" name="tableWidget">
- <property name="showGrid">
- <bool>false</bool>
- </property>
- <property name="columnCount">
- <number>1</number>
- </property>
- <attribute name="horizontalHeaderDefaultSectionSize">
- <number>200</number>
- </attribute>
- <attribute name="horizontalHeaderStretchLastSection">
- <bool>true</bool>
- </attribute>
- <attribute name="verticalHeaderVisible">
- <bool>false</bool>
- </attribute>
- <column/>
- </widget>
- </item>
- <item>
- <widget class="Line" name="line">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QDialogButtonBox" name="buttonBox">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="standardButtons">
- <set>QDialogButtonBox::Ok</set>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <resources/>
- <connections>
- <connection>
- <sender>buttonBox</sender>
- <signal>accepted()</signal>
- <receiver>RemoteLinux::Internal::ProFilesUpdateDialog</receiver>
- <slot>accept()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>248</x>
- <y>254</y>
- </hint>
- <hint type="destinationlabel">
- <x>157</x>
- <y>274</y>
- </hint>
- </hints>
- </connection>
- <connection>
- <sender>buttonBox</sender>
- <signal>rejected()</signal>
- <receiver>RemoteLinux::Internal::ProFilesUpdateDialog</receiver>
- <slot>reject()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>316</x>
- <y>260</y>
- </hint>
- <hint type="destinationlabel">
- <x>286</x>
- <y>274</y>
- </hint>
- </hints>
- </connection>
- </connections>
-</ui>
diff --git a/src/plugins/remotelinux/publickeydeploymentdialog.cpp b/src/plugins/remotelinux/publickeydeploymentdialog.cpp
index 011f25a27a..2443e6e31d 100644
--- a/src/plugins/remotelinux/publickeydeploymentdialog.cpp
+++ b/src/plugins/remotelinux/publickeydeploymentdialog.cpp
@@ -109,7 +109,7 @@ void PublicKeyDeploymentDialog::handleDeploymentFinished(const QString &errorMsg
buttonText = errorMsg;
textColor = "red";
}
- setLabelText(QString::fromLatin1("<font color=\"%1\">%2</font>").arg(textColor, buttonText));
+ setLabelText(QString::fromLatin1("<font color=\"%1\">%2</font>").arg(QLatin1String(textColor), buttonText));
setCancelButtonText(tr("Close"));
}
diff --git a/src/plugins/remotelinux/remotelinux.pro b/src/plugins/remotelinux/remotelinux.pro
index 6059ce60ab..61a57481c6 100644
--- a/src/plugins/remotelinux/remotelinux.pro
+++ b/src/plugins/remotelinux/remotelinux.pro
@@ -21,9 +21,6 @@ HEADERS += \
remotelinuxruncontrolfactory.h \
remotelinuxdebugsupport.h \
genericlinuxdeviceconfigurationwizardpages.h \
- deployablefile.h \
- deployablefilesperprofile.h \
- deploymentinfo.h \
abstractremotelinuxdeploystep.h \
genericdirectuploadstep.h \
uploadandinstalltarpackagestep.h \
@@ -44,14 +41,13 @@ HEADERS += \
sshkeydeployer.h \
typespecificdeviceconfigurationlistmodel.h \
remotelinuxutils.h \
- deploymentsettingsassistant.h \
remotelinuxdeployconfigurationwidget.h \
- profilesupdatedialog.h \
remotelinuxcustomcommanddeployservice.h \
remotelinuxcustomcommanddeploymentstep.h \
genericlinuxdeviceconfigurationwidget.h \
remotelinuxcheckforfreediskspaceservice.h \
- remotelinuxcheckforfreediskspacestep.h
+ remotelinuxcheckforfreediskspacestep.h \
+ remotelinuxdeploymentdatamodel.h
SOURCES += \
embeddedlinuxqtversion.cpp \
@@ -68,8 +64,6 @@ SOURCES += \
remotelinuxruncontrolfactory.cpp \
remotelinuxdebugsupport.cpp \
genericlinuxdeviceconfigurationwizardpages.cpp \
- deployablefilesperprofile.cpp \
- deploymentinfo.cpp \
abstractremotelinuxdeploystep.cpp \
genericdirectuploadstep.cpp \
uploadandinstalltarpackagestep.cpp \
@@ -89,24 +83,21 @@ SOURCES += \
sshkeydeployer.cpp \
typespecificdeviceconfigurationlistmodel.cpp \
remotelinuxutils.cpp \
- deploymentsettingsassistant.cpp \
remotelinuxdeployconfigurationwidget.cpp \
- profilesupdatedialog.cpp \
remotelinuxcustomcommanddeployservice.cpp \
remotelinuxcustomcommanddeploymentstep.cpp \
genericlinuxdeviceconfigurationwidget.cpp \
remotelinuxcheckforfreediskspaceservice.cpp \
- remotelinuxcheckforfreediskspacestep.cpp
+ remotelinuxcheckforfreediskspacestep.cpp \
+ remotelinuxdeploymentdatamodel.cpp
FORMS += \
genericlinuxdeviceconfigurationwizardsetuppage.ui \
linuxdevicetestdialog.ui \
remotelinuxdeployconfigurationwidget.ui \
- profilesupdatedialog.ui \
genericlinuxdeviceconfigurationwidget.ui \
remotelinuxcheckforfreediskspacestepwidget.ui
RESOURCES += remotelinux.qrc
-DEFINES += QT_NO_CAST_TO_ASCII
DEFINES += REMOTELINUX_LIBRARY
diff --git a/src/plugins/remotelinux/remotelinux.qbs b/src/plugins/remotelinux/remotelinux.qbs
index 221172e322..79beba4559 100644
--- a/src/plugins/remotelinux/remotelinux.qbs
+++ b/src/plugins/remotelinux/remotelinux.qbs
@@ -5,65 +5,64 @@ import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "RemoteLinux"
+ Depends { name: "cpp" }
Depends { name: "Qt.widgets" }
Depends { name: "Core" }
Depends { name: "Debugger" }
Depends { name: "ProjectExplorer" }
- Depends { name: "Qt4ProjectManager" }
Depends { name: "QtSupport" }
Depends { name: "QtcSsh" }
-
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
+ cpp.defines: base.concat("REMOTELINUX_LIBRARY")
files: [
"abstractpackagingstep.cpp",
"abstractpackagingstep.h",
"abstractremotelinuxdeployservice.cpp",
"abstractremotelinuxdeployservice.h",
+ "abstractremotelinuxdeploystep.cpp",
"abstractremotelinuxdeploystep.h",
"abstractuploadandinstallpackageservice.cpp",
"abstractuploadandinstallpackageservice.h",
- "deployablefile.h",
- "deployablefilesperprofile.cpp",
- "deployablefilesperprofile.h",
- "deploymentinfo.cpp",
- "deploymentinfo.h",
- "deploymentsettingsassistant.cpp",
- "deploymentsettingsassistant.h",
"embeddedlinuxqtversion.cpp",
"embeddedlinuxqtversion.h",
"embeddedlinuxqtversionfactory.cpp",
"embeddedlinuxqtversionfactory.h",
"genericdirectuploadservice.cpp",
+ "genericdirectuploadservice.h",
+ "genericdirectuploadstep.cpp",
"genericdirectuploadstep.h",
"genericlinuxdeviceconfigurationfactory.cpp",
"genericlinuxdeviceconfigurationfactory.h",
+ "genericlinuxdeviceconfigurationwidget.cpp",
+ "genericlinuxdeviceconfigurationwidget.h",
+ "genericlinuxdeviceconfigurationwidget.ui",
"genericlinuxdeviceconfigurationwizard.cpp",
"genericlinuxdeviceconfigurationwizard.h",
"genericlinuxdeviceconfigurationwizardpages.cpp",
"genericlinuxdeviceconfigurationwizardpages.h",
"genericlinuxdeviceconfigurationwizardsetuppage.ui",
- "genericlinuxdeviceconfigurationwidget.cpp",
- "genericlinuxdeviceconfigurationwidget.h",
- "genericlinuxdeviceconfigurationwidget.ui",
"genericremotelinuxdeploystepfactory.cpp",
"genericremotelinuxdeploystepfactory.h",
"linuxdevice.cpp",
"linuxdevice.h",
"linuxdevicetestdialog.cpp",
"linuxdevicetestdialog.h",
+ "linuxdevicetestdialog.ui",
"linuxdevicetester.cpp",
"linuxdevicetester.h",
+ "packageuploader.cpp",
+ "packageuploader.h",
"publickeydeploymentdialog.cpp",
"publickeydeploymentdialog.h",
"remotelinux.qrc",
"remotelinux_constants.h",
"remotelinux_export.h",
+ "remotelinuxcheckforfreediskspaceservice.cpp",
+ "remotelinuxcheckforfreediskspaceservice.h",
+ "remotelinuxcheckforfreediskspacestep.cpp",
+ "remotelinuxcheckforfreediskspacestep.h",
+ "remotelinuxcheckforfreediskspacestepwidget.ui",
+ "remotelinuxcustomcommanddeploymentstep.cpp",
"remotelinuxcustomcommanddeploymentstep.h",
"remotelinuxcustomcommanddeployservice.cpp",
"remotelinuxcustomcommanddeployservice.h",
@@ -75,7 +74,13 @@ QtcPlugin {
"remotelinuxdeployconfigurationfactory.h",
"remotelinuxdeployconfigurationwidget.cpp",
"remotelinuxdeployconfigurationwidget.h",
+ "remotelinuxdeployconfigurationwidget.ui",
+ "remotelinuxdeploymentdatamodel.cpp",
+ "remotelinuxdeploymentdatamodel.h",
+ "remotelinuxenvironmentreader.cpp",
+ "remotelinuxenvironmentreader.h",
"remotelinuxpackageinstaller.cpp",
+ "remotelinuxpackageinstaller.h",
"remotelinuxplugin.cpp",
"remotelinuxplugin.h",
"remotelinuxrunconfiguration.cpp",
@@ -84,40 +89,21 @@ QtcPlugin {
"remotelinuxrunconfigurationfactory.h",
"remotelinuxrunconfigurationwidget.cpp",
"remotelinuxrunconfigurationwidget.h",
+ "remotelinuxruncontrol.cpp",
"remotelinuxruncontrol.h",
+ "remotelinuxruncontrolfactory.cpp",
+ "remotelinuxruncontrolfactory.h",
"remotelinuxutils.cpp",
"remotelinuxutils.h",
- "tarpackagecreationstep.h",
- "uploadandinstalltarpackagestep.h",
- "genericdirectuploadservice.h",
- "linuxdevicetestdialog.ui",
- "packageuploader.cpp",
- "packageuploader.h",
- "profilesupdatedialog.cpp",
- "profilesupdatedialog.h",
- "profilesupdatedialog.ui",
- "remotelinuxdeployconfigurationwidget.ui",
- "remotelinuxenvironmentreader.cpp",
- "remotelinuxenvironmentreader.h",
- "remotelinuxpackageinstaller.h",
"sshkeydeployer.cpp",
"sshkeydeployer.h",
+ "tarpackagecreationstep.cpp",
+ "tarpackagecreationstep.h",
"typespecificdeviceconfigurationlistmodel.cpp",
"typespecificdeviceconfigurationlistmodel.h",
- "abstractremotelinuxdeploystep.cpp",
- "genericdirectuploadstep.cpp",
- "remotelinuxcustomcommanddeploymentstep.cpp",
- "remotelinuxruncontrol.cpp",
- "remotelinuxruncontrolfactory.cpp",
- "remotelinuxruncontrolfactory.h",
- "tarpackagecreationstep.cpp",
"uploadandinstalltarpackagestep.cpp",
- "remotelinuxcheckforfreediskspaceservice.h",
- "remotelinuxcheckforfreediskspaceservice.cpp",
- "remotelinuxcheckforfreediskspacestep.h",
- "remotelinuxcheckforfreediskspacestep.cpp",
- "remotelinuxcheckforfreediskspacestepwidget.ui",
- "images/embeddedtarget.png"
+ "uploadandinstalltarpackagestep.h",
+ "images/embeddedtarget.png",
]
ProductModule {
diff --git a/src/plugins/remotelinux/remotelinux_dependencies.pri b/src/plugins/remotelinux/remotelinux_dependencies.pri
index c2940f9362..697ec645a1 100644
--- a/src/plugins/remotelinux/remotelinux_dependencies.pri
+++ b/src/plugins/remotelinux/remotelinux_dependencies.pri
@@ -1,4 +1,4 @@
include(../../plugins/coreplugin/coreplugin.pri)
include(../../plugins/debugger/debugger.pri)
include(../../plugins/projectexplorer/projectexplorer.pri)
-include(../../plugins/qt4projectmanager/qt4projectmanager.pri)
+include(../../plugins/qtsupport/qtsupport.pri)
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp b/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp
index fe20fa1a61..15de35bf53 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp
+++ b/src/plugins/remotelinux/remotelinuxdeployconfiguration.cpp
@@ -28,21 +28,12 @@
****************************************************************************/
#include "remotelinuxdeployconfiguration.h"
-#include "deploymentinfo.h"
#include "remotelinuxdeployconfigurationwidget.h"
-#include "typespecificdeviceconfigurationlistmodel.h"
-#include <projectexplorer/devicesupport/devicemanager.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
-#include <qt4projectmanager/qt4project.h>
using namespace ProjectExplorer;
-using namespace Qt4ProjectManager;
-
-namespace {
-const char DEPLOYMENT_INFO_SETTING[] = "RemoteLinux.DeploymentInfo";
-} // namespace
namespace RemoteLinux {
@@ -53,15 +44,6 @@ RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(ProjectExplorer::
: DeployConfiguration(target, id)
{
setDefaultDisplayName(defaultDisplayName);
-
- // Make sure we have deploymentInfo, but create it only once:
- DeploymentInfo *info
- = qobject_cast<DeploymentInfo *>(target->project()->namedSettings(QLatin1String(DEPLOYMENT_INFO_SETTING)).value<QObject *>());
- if (!info) {
- info = new DeploymentInfo(static_cast<Qt4ProjectManager::Qt4Project *>(target->project()));
- QVariant data = QVariant::fromValue(static_cast<QObject *>(info));
- target->project()->setNamedSettings(QLatin1String(DEPLOYMENT_INFO_SETTING), data);
- }
}
RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(ProjectExplorer::Target *target,
@@ -69,26 +51,9 @@ RemoteLinuxDeployConfiguration::RemoteLinuxDeployConfiguration(ProjectExplorer::
: DeployConfiguration(target, source)
{ }
-DeploymentInfo *RemoteLinuxDeployConfiguration::deploymentInfo() const
-{
- DeploymentInfo *info
- = qobject_cast<DeploymentInfo *>(target()->project()->namedSettings(QLatin1String(DEPLOYMENT_INFO_SETTING)).value<QObject *>());
- return info;
-}
-
-QString RemoteLinuxDeployConfiguration::qmakeScope() const
-{
- return QLatin1String("unix");
-}
-
-QString RemoteLinuxDeployConfiguration::installPrefix() const
-{
- return QString();
-}
-
-DeployConfigurationWidget *RemoteLinuxDeployConfiguration::configurationWidget() const
+NamedWidget *RemoteLinuxDeployConfiguration::createConfigWidget()
{
- return new RemoteLinuxDeployConfigurationWidget;
+ return new RemoteLinuxDeployConfigurationWidget(this);
}
} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfiguration.h b/src/plugins/remotelinux/remotelinuxdeployconfiguration.h
index 2c3ba8928f..fad2b76f9b 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfiguration.h
+++ b/src/plugins/remotelinux/remotelinuxdeployconfiguration.h
@@ -38,9 +38,6 @@
#include <projectexplorer/devicesupport/idevice.h>
namespace RemoteLinux {
-class AbstractEmbeddedLinuxTarget;
-class DeploymentInfo;
-
namespace Internal { class RemoteLinuxDeployConfigurationFactory; }
class REMOTELINUX_EXPORT RemoteLinuxDeployConfiguration
@@ -54,9 +51,7 @@ public:
RemoteLinuxDeployConfiguration(ProjectExplorer::Target *target,
RemoteLinuxDeployConfiguration *source);
- ProjectExplorer::DeployConfigurationWidget *configurationWidget() const;
-
- DeploymentInfo *deploymentInfo() const;
+ ProjectExplorer::NamedWidget *createConfigWidget();
template<class T> T *earlierBuildStep(const ProjectExplorer::BuildStep *laterBuildStep) const
{
@@ -70,12 +65,6 @@ public:
return 0;
}
- virtual QString qmakeScope() const;
- virtual QString installPrefix() const;
-
-signals:
- void packagingChanged();
-
private:
friend class Internal::RemoteLinuxDeployConfigurationFactory;
};
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
index 94f76d6410..e7772aeae0 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationfactory.cpp
@@ -36,8 +36,8 @@
#include <projectexplorer/abi.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
-#include <qt4projectmanager/qt4project.h>
#include <QCoreApplication>
@@ -58,8 +58,6 @@ RemoteLinuxDeployConfigurationFactory::RemoteLinuxDeployConfigurationFactory(QOb
QList<Core::Id> RemoteLinuxDeployConfigurationFactory::availableCreationIds(Target *parent) const
{
QList<Core::Id> ids;
- if (!qobject_cast<Qt4ProjectManager::Qt4Project *>(parent->project()))
- return ids;
if (!parent->project()->supportsKit(parent->kit()))
return ids;
ProjectExplorer::ToolChain *tc
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.cpp b/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.cpp
index 9159ff0648..53ade0d925 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.cpp
@@ -29,147 +29,55 @@
#include "remotelinuxdeployconfigurationwidget.h"
#include "ui_remotelinuxdeployconfigurationwidget.h"
-#include "deployablefilesperprofile.h"
-#include "deploymentinfo.h"
#include "remotelinuxdeployconfiguration.h"
-#include "typespecificdeviceconfigurationlistmodel.h"
+#include "remotelinuxdeploymentdatamodel.h"
-#include <coreplugin/editormanager/editormanager.h>
-#include <coreplugin/icore.h>
-#include <coreplugin/id.h>
-#include <projectexplorer/devicesupport/devicemanager.h>
-#include <projectexplorer/projectexplorerconstants.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <utils/qtcassert.h>
-#include <QTreeView>
-
using namespace ProjectExplorer;
namespace RemoteLinux {
namespace Internal {
-namespace {
-class MyTreeView : public QTreeView
-{
- Q_OBJECT
-public:
- MyTreeView(QWidget *parent = 0) : QTreeView(parent) {}
-
-signals:
- void doubleClicked();
-
-private:
- void mouseDoubleClickEvent(QMouseEvent *event)
- {
- emit doubleClicked();
- QTreeView::mouseDoubleClickEvent(event);
- }
-};
-
-} // anonymous namespace
class RemoteLinuxDeployConfigurationWidgetPrivate
{
public:
Ui::RemoteLinuxDeployConfigurationWidget ui;
- MyTreeView treeView;
RemoteLinuxDeployConfiguration *deployConfiguration;
+ RemoteLinuxDeploymentDataModel deploymentDataModel;
};
} // namespace Internal
using namespace Internal;
-RemoteLinuxDeployConfigurationWidget::RemoteLinuxDeployConfigurationWidget(QWidget *parent) :
- DeployConfigurationWidget(parent), d(new RemoteLinuxDeployConfigurationWidgetPrivate)
+RemoteLinuxDeployConfigurationWidget::RemoteLinuxDeployConfigurationWidget(RemoteLinuxDeployConfiguration *dc,
+ QWidget *parent) :
+ NamedWidget(parent), d(new RemoteLinuxDeployConfigurationWidgetPrivate)
{
d->ui.setupUi(this);
- d->treeView.setTextElideMode(Qt::ElideMiddle);
- d->treeView.setWordWrap(false);
- d->treeView.setUniformRowHeights(true);
- layout()->addWidget(&d->treeView);
-}
-
-RemoteLinuxDeployConfigurationWidget::~RemoteLinuxDeployConfigurationWidget()
-{
- delete d;
-}
-
-void RemoteLinuxDeployConfigurationWidget::init(DeployConfiguration *dc)
-{
- d->deployConfiguration = qobject_cast<RemoteLinuxDeployConfiguration *>(dc);
- Q_ASSERT(d->deployConfiguration);
-
- connect(&d->treeView, SIGNAL(doubleClicked()), SLOT(openProjectFile()));
-
- d->ui.projectsComboBox->setModel(d->deployConfiguration->deploymentInfo());
- connect(d->deployConfiguration->deploymentInfo(), SIGNAL(modelAboutToBeReset()),
- SLOT(handleModelListToBeReset()));
+ d->ui.deploymentDataView->setTextElideMode(Qt::ElideMiddle);
+ d->ui.deploymentDataView->setWordWrap(false);
+ d->ui.deploymentDataView->setUniformRowHeights(true);
+ d->ui.deploymentDataView->setModel(&d->deploymentDataModel);
- // Queued connection because of race condition with combo box's reaction
- // to modelReset().
- connect(d->deployConfiguration->deploymentInfo(), SIGNAL(modelReset()),
- SLOT(handleModelListReset()), Qt::QueuedConnection);
+ d->deployConfiguration = dc;
- connect(d->ui.projectsComboBox, SIGNAL(currentIndexChanged(int)), SLOT(setModel(int)));
- handleModelListReset();
+ connect(dc->target(), SIGNAL(deploymentDataChanged()), SLOT(updateDeploymentDataModel()));
+ updateDeploymentDataModel();
}
-RemoteLinuxDeployConfiguration *RemoteLinuxDeployConfigurationWidget::deployConfiguration() const
-{
- return d->deployConfiguration;
-}
-
-DeployableFilesPerProFile *RemoteLinuxDeployConfigurationWidget::currentModel() const
-{
- const int modelRow = d->ui.projectsComboBox->currentIndex();
- if (modelRow == -1)
- return 0;
- return d->deployConfiguration->deploymentInfo()->modelAt(modelRow);
-}
-
-void RemoteLinuxDeployConfigurationWidget::handleModelListToBeReset()
-{
- d->treeView.setModel(0);
-}
-
-void RemoteLinuxDeployConfigurationWidget::handleModelListReset()
-{
- QTC_ASSERT(d->deployConfiguration->deploymentInfo()->modelCount()
- == d->ui.projectsComboBox->count(), return);
-
- if (d->deployConfiguration->deploymentInfo()->modelCount() > 0) {
- d->treeView.setToolTip(tr("Double-click to edit the project file"));
- if (d->ui.projectsComboBox->currentIndex() == -1)
- d->ui.projectsComboBox->setCurrentIndex(0);
- else
- setModel(d->ui.projectsComboBox->currentIndex());
- } else {
- d->treeView.setToolTip(QString());
- }
-}
-
-void RemoteLinuxDeployConfigurationWidget::setModel(int row)
+RemoteLinuxDeployConfigurationWidget::~RemoteLinuxDeployConfigurationWidget()
{
- DeployableFilesPerProFile * const proFileInfo = row == -1
- ? 0 : d->deployConfiguration->deploymentInfo()->modelAt(row);
- d->treeView.setModel(proFileInfo);
- if (proFileInfo)
- d->treeView.resizeColumnToContents(0);
- emit currentModelChanged(proFileInfo);
+ delete d;
}
-void RemoteLinuxDeployConfigurationWidget::openProjectFile()
+void RemoteLinuxDeployConfigurationWidget::updateDeploymentDataModel()
{
- const int row = d->ui.projectsComboBox->currentIndex();
- if (row == -1)
- return;
- const DeployableFilesPerProFile * const proFileInfo =
- d->deployConfiguration->deploymentInfo()->modelAt(row);
- Core::EditorManager::openEditor(proFileInfo->proFilePath(), Core::Id(),
- Core::EditorManager::ModeSwitch);
+ d->deploymentDataModel.setDeploymentData(d->deployConfiguration->target()->deploymentData());
+ d->ui.deploymentDataView->resizeColumnToContents(0);
}
} // namespace RemoteLinux
-
-#include "remotelinuxdeployconfigurationwidget.moc"
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.h b/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.h
index e972008077..f155414530 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.h
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.h
@@ -34,7 +34,6 @@
#include <projectexplorer/deployconfiguration.h>
namespace RemoteLinux {
-class DeployableFilesPerProFile;
class RemoteLinuxDeployConfiguration;
namespace Internal {
@@ -42,27 +41,17 @@ class RemoteLinuxDeployConfigurationWidgetPrivate;
} // namespace Internal
class REMOTELINUX_EXPORT RemoteLinuxDeployConfigurationWidget
- : public ProjectExplorer::DeployConfigurationWidget
+ : public ProjectExplorer::NamedWidget
{
Q_OBJECT
public:
- explicit RemoteLinuxDeployConfigurationWidget(QWidget *parent = 0);
+ explicit RemoteLinuxDeployConfigurationWidget(RemoteLinux::RemoteLinuxDeployConfiguration *dc,
+ QWidget *parent = 0);
~RemoteLinuxDeployConfigurationWidget();
- void init(ProjectExplorer::DeployConfiguration *dc);
-
- RemoteLinuxDeployConfiguration *deployConfiguration() const;
- DeployableFilesPerProFile *currentModel() const;
-
-signals:
- void currentModelChanged(const RemoteLinux::DeployableFilesPerProFile *proFileInfo);
-
private slots:
- void handleModelListToBeReset();
- void handleModelListReset();
- void setModel(int row);
- void openProjectFile();
+ void updateDeploymentDataModel();
private:
Internal::RemoteLinuxDeployConfigurationWidgetPrivate * const d;
diff --git a/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.ui b/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.ui
index 2bfa1bd8a6..fb765741e9 100644
--- a/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.ui
+++ b/src/plugins/remotelinux/remotelinuxdeployconfigurationwidget.ui
@@ -15,45 +15,14 @@
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
- <layout class="QFormLayout" name="formLayout">
- <property name="fieldGrowthPolicy">
- <enum>QFormLayout::AllNonFixedFieldsGrow</enum>
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>Files to deploy:</string>
</property>
- <item row="0" column="0">
- <widget class="QLabel" name="installLabel">
- <property name="toolTip">
- <string>These show the INSTALLS settings from the project file(s).</string>
- </property>
- <property name="text">
- <string>Files to install for subproject:</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QComboBox" name="projectsComboBox">
- <property name="sizeAdjustPolicy">
- <enum>QComboBox::AdjustToContents</enum>
- </property>
- </widget>
- </item>
- <item>
- <spacer name="horizontalSpacer_2">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- </layout>
- </item>
- </layout>
+ </widget>
+ </item>
+ <item>
+ <widget class="QTreeView" name="deploymentDataView"/>
</item>
</layout>
</widget>
diff --git a/src/plugins/remotelinux/deploymentinfo.h b/src/plugins/remotelinux/remotelinuxdeploymentdatamodel.cpp
index 25de56c879..a2022fb9c8 100644
--- a/src/plugins/remotelinux/deploymentinfo.h
+++ b/src/plugins/remotelinux/remotelinuxdeploymentdatamodel.cpp
@@ -1,4 +1,4 @@
-/****************************************************************************
+/**************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
@@ -27,55 +27,55 @@
**
****************************************************************************/
-#ifndef DEPLOYMENTINFO_H
-#define DEPLOYMENTINFO_H
+#include "remotelinuxdeploymentdatamodel.h"
-#include "remotelinux_export.h"
+#include <QDir>
-#include <QAbstractListModel>
-
-namespace ProjectExplorer { class Target; }
-namespace Qt4ProjectManager {
-class Qt4ProFileNode;
-class Qt4Project;
-} // namespace Qt4ProjectManager
+using namespace ProjectExplorer;
namespace RemoteLinux {
-class DeployableFile;
-class DeployableFilesPerProFile;
-namespace Internal {
-class DeploymentInfoPrivate;
+RemoteLinuxDeploymentDataModel::RemoteLinuxDeploymentDataModel(QObject *parent)
+ : QAbstractTableModel(parent)
+{
}
-class REMOTELINUX_EXPORT DeploymentInfo : public QAbstractListModel
+void RemoteLinuxDeploymentDataModel::setDeploymentData(const DeploymentData &deploymentData)
{
- Q_OBJECT
-public:
- DeploymentInfo(Qt4ProjectManager::Qt4Project *project, const QString &installPrefix = QString());
- ~DeploymentInfo();
+ beginResetModel();
+ m_deploymentData = deploymentData;
+ endResetModel();
+}
- void setUnmodified();
- bool isModified() const;
- void setInstallPrefix(const QString &installPrefix);
- int deployableCount() const;
- DeployableFile deployableAt(int i) const;
- QString remoteExecutableFilePath(const QString &localExecutableFilePath) const;
- int modelCount() const;
- DeployableFilesPerProFile *modelAt(int i) const;
+int RemoteLinuxDeploymentDataModel::rowCount(const QModelIndex &parent) const
+{
+ return parent.isValid() ? 0 : m_deploymentData.fileCount();
+}
-private slots:
- void createModels();
+int RemoteLinuxDeploymentDataModel::columnCount(const QModelIndex &parent) const
+{
+ return parent.isValid() ? 0 : 2;
+}
-private:
- virtual int rowCount(const QModelIndex &parent) const;
- virtual QVariant data(const QModelIndex &index, int role) const;
+QVariant RemoteLinuxDeploymentDataModel::headerData(int section, Qt::Orientation orientation,
+ int role) const
+{
+ if (orientation == Qt::Vertical || role != Qt::DisplayRole)
+ return QVariant();
+ return section == 0 ? tr("Local File Path") : tr("Remote Directory");
+}
- void createModels(const Qt4ProjectManager::Qt4ProFileNode *proFileNode);
+QVariant RemoteLinuxDeploymentDataModel::data(const QModelIndex &index, int role) const
+{
+ if (!index.isValid() || index.row() >= rowCount() || index.column() >= columnCount())
+ return QVariant();
- Internal::DeploymentInfoPrivate * const d;
-};
+ const DeployableFile &d = m_deploymentData.fileAt(index.row());
+ if (index.column() == 0 && role == Qt::DisplayRole)
+ return d.localFilePath().toUserOutput();
+ if (role == Qt::DisplayRole)
+ return d.remoteDirectory();
+ return QVariant();
+}
} // namespace RemoteLinux
-
-#endif // DEPLOYMENTINFO_H
diff --git a/src/plugins/remotelinux/profilesupdatedialog.h b/src/plugins/remotelinux/remotelinuxdeploymentdatamodel.h
index f89fe75e98..266d6f5fc3 100644
--- a/src/plugins/remotelinux/profilesupdatedialog.h
+++ b/src/plugins/remotelinux/remotelinuxdeploymentdatamodel.h
@@ -26,43 +26,32 @@
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
+#ifndef REMOTELINUXDEPLOYMENTDATAMODEL_H
+#define REMOTELINUXDEPLOYMENTDATAMODEL_H
-#ifndef PROFILESUPDATEDIALOG_H
-#define PROFILESUPDATEDIALOG_H
+#include <projectexplorer/deploymentdata.h>
-#include <QList>
-#include <QPair>
-#include <QString>
-#include <QDialog>
+#include <QAbstractTableModel>
namespace RemoteLinux {
-class DeployableFilesPerProFile;
-namespace Internal {
-namespace Ui { class ProFilesUpdateDialog; }
-
-class ProFilesUpdateDialog : public QDialog
+class RemoteLinuxDeploymentDataModel : public QAbstractTableModel
{
Q_OBJECT
-
public:
- typedef QPair<DeployableFilesPerProFile *, bool> UpdateSetting;
+ explicit RemoteLinuxDeploymentDataModel(QObject *parent = 0);
- explicit ProFilesUpdateDialog(const QList<DeployableFilesPerProFile *> &models,
- QWidget *parent = 0);
- ~ProFilesUpdateDialog();
- QList<UpdateSetting> getUpdateSettings() const;
+ void setDeploymentData(const ProjectExplorer::DeploymentData &deploymentData);
private:
- Q_SLOT void checkAll();
- Q_SLOT void uncheckAll();
- void setCheckStateForAll(Qt::CheckState checkState);
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ int columnCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
- const QList<DeployableFilesPerProFile *> m_models;
- Ui::ProFilesUpdateDialog *ui;
+ ProjectExplorer::DeploymentData m_deploymentData;
};
} // namespace RemoteLinux
-} // namespace Internal
-#endif // PROFILESUPDATEDIALOG_H
+#endif // REMOTELINUXDEPLOYMENTDATAMODEL_H
diff --git a/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp b/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
index 112bf3df59..0aae9177c5 100644
--- a/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
+++ b/src/plugins/remotelinux/remotelinuxenvironmentreader.cpp
@@ -111,7 +111,7 @@ void RemoteLinuxEnvironmentReader::remoteProcessFinished(int exitCode)
} else {
QString errorMsg = tr("Error running remote process: %1")
.arg(m_remoteProcessRunner->processErrorString());
- QString remoteStderr = m_remoteProcessRunner->readAllStandardError();
+ QString remoteStderr = QString::fromUtf8(m_remoteProcessRunner->readAllStandardError());
if (!remoteStderr.isEmpty())
errorMsg += tr("\nRemote stderr was: '%1'").arg(remoteStderr);
emit error(errorMsg);
diff --git a/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp b/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp
index 92a4fe9ea4..4ea4ac8dba 100644
--- a/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp
+++ b/src/plugins/remotelinux/remotelinuxpackageinstaller.cpp
@@ -104,13 +104,12 @@ void AbstractRemoteLinuxPackageInstaller::handleInstallationFinished(int exitSta
if (!d->isRunning)
return;
- if (exitStatus != SshRemoteProcess::NormalExit || d->installer->processExitCode() != 0) {
+ if (exitStatus != SshRemoteProcess::NormalExit || d->installer->processExitCode() != 0)
emit finished(tr("Installing package failed."));
- } else if (!errorString().isEmpty()) {
+ else if (!errorString().isEmpty())
emit finished(errorString());
- } else {
+ else
emit finished();
- }
setFinished();
}
diff --git a/src/plugins/remotelinux/remotelinuxplugin.cpp b/src/plugins/remotelinux/remotelinuxplugin.cpp
index f6118366ff..310aaa7284 100644
--- a/src/plugins/remotelinux/remotelinuxplugin.cpp
+++ b/src/plugins/remotelinux/remotelinuxplugin.cpp
@@ -30,10 +30,8 @@
#include "remotelinuxplugin.h"
#include "embeddedlinuxqtversionfactory.h"
-#include "deployablefile.h"
#include "genericlinuxdeviceconfigurationfactory.h"
#include "genericremotelinuxdeploystepfactory.h"
-#include "qt4projectmanager/qt4projectmanagerconstants.h"
#include "remotelinuxdeployconfigurationfactory.h"
#include "remotelinuxrunconfigurationfactory.h"
#include "remotelinuxruncontrolfactory.h"
@@ -71,8 +69,6 @@ bool RemoteLinuxPlugin::initialize(const QStringList &arguments,
addAutoReleasedObject(new EmbeddedLinuxQtVersionFactory);
- qRegisterMetaType<RemoteLinux::DeployableFile>("RemoteLinux::DeployableFile");
-
return true;
}
diff --git a/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp b/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
index 0e27e8f9a3..52a829d6f3 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfiguration.cpp
@@ -29,23 +29,21 @@
#include "remotelinuxrunconfiguration.h"
-#include "deploymentinfo.h"
#include "remotelinuxdeployconfiguration.h"
#include "remotelinuxrunconfigurationwidget.h"
-#include <projectexplorer/projectexplorer.h>
+#include <projectexplorer/buildtargetinfo.h>
+#include <projectexplorer/deploymentdata.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/session.h>
#include <projectexplorer/target.h>
#include <projectexplorer/toolchain.h>
#include <qtsupport/qtoutputformatter.h>
-#include <qt4projectmanager/qt4nodes.h>
-#include <qt4projectmanager/qt4project.h>
#include <utils/portlist.h>
#include <utils/qtcassert.h>
using namespace ProjectExplorer;
-using namespace Qt4ProjectManager;
using namespace QSsh;
using namespace Utils;
@@ -65,38 +63,32 @@ const char WorkingDirectoryKey[] = "RemoteLinux.RunConfig.WorkingDirectory";
class RemoteLinuxRunConfigurationPrivate {
public:
- RemoteLinuxRunConfigurationPrivate(const QString &proFilePath, const ProjectExplorer::Target *target)
- : proFilePath(proFilePath),
+ RemoteLinuxRunConfigurationPrivate(const QString &projectFilePath)
+ : projectFilePath(projectFilePath),
baseEnvironmentType(RemoteLinuxRunConfiguration::RemoteBaseEnvironment),
- validParse(false),
- parseInProgress(true),
useAlternateRemoteExecutable(false)
{
- validParse = static_cast<Qt4Project *>(target->project())->validParse(proFilePath);
- parseInProgress = static_cast<Qt4Project *>(target->project())->parseInProgress(proFilePath);
}
RemoteLinuxRunConfigurationPrivate(const RemoteLinuxRunConfigurationPrivate *other)
- : proFilePath(other->proFilePath), gdbPath(other->gdbPath), arguments(other->arguments),
+ : projectFilePath(other->projectFilePath),
+ gdbPath(other->gdbPath),
+ arguments(other->arguments),
baseEnvironmentType(other->baseEnvironmentType),
remoteEnvironment(other->remoteEnvironment),
userEnvironmentChanges(other->userEnvironmentChanges),
- validParse(other->validParse),
- parseInProgress(other->parseInProgress),
useAlternateRemoteExecutable(other->useAlternateRemoteExecutable),
alternateRemoteExecutable(other->alternateRemoteExecutable),
workingDirectory(other->workingDirectory)
{
}
- QString proFilePath;
+ QString projectFilePath;
QString gdbPath;
QString arguments;
RemoteLinuxRunConfiguration::BaseEnvironmentType baseEnvironmentType;
Environment remoteEnvironment;
QList<EnvironmentItem> userEnvironmentChanges;
- bool validParse;
- bool parseInProgress;
QString disabledReason;
bool useAlternateRemoteExecutable;
QString alternateRemoteExecutable;
@@ -110,7 +102,7 @@ using namespace Internal;
RemoteLinuxRunConfiguration::RemoteLinuxRunConfiguration(Target *parent, const Core::Id id,
const QString &proFilePath)
: RunConfiguration(parent, id),
- d(new RemoteLinuxRunConfigurationPrivate(proFilePath, parent))
+ d(new RemoteLinuxRunConfigurationPrivate(proFilePath))
{
init();
}
@@ -133,34 +125,14 @@ void RemoteLinuxRunConfiguration::init()
setDefaultDisplayName(defaultDisplayName());
debuggerAspect()->suppressQmlDebuggingSpinbox();
- connect(target(),
- SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)),
- this, SLOT(handleDeployConfigChanged()));
- handleDeployConfigChanged();
-
- Project *pro = target()->project();
- connect(pro, SIGNAL(kitUpdated(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)),
- this, SLOT(proFileUpdate(Qt4ProjectManager::Qt4ProFileNode*,bool,bool)));
+ connect(target(), SIGNAL(deploymentDataChanged()), SLOT(handleBuildSystemDataUpdated()));
+ connect(target(), SIGNAL(applicationTargetsChanged()), SLOT(handleBuildSystemDataUpdated()));
connect(target(), SIGNAL(kitChanged()),
- this, SLOT(handleDeployablesUpdated())); // Handles device changes, etc.
+ this, SLOT(handleBuildSystemDataUpdated())); // Handles device changes, etc.
}
bool RemoteLinuxRunConfiguration::isEnabled() const
{
- if (d->parseInProgress) {
- d->disabledReason = tr("The .pro file '%1' is being parsed.")
- .arg(QFileInfo(d->proFilePath).fileName());
- return false;
- }
- if (!d->validParse) {
- Qt4Project *project = static_cast<Qt4Project *>(target()->project());
- d->disabledReason = project->disabledReasonForRunConfiguration(d->proFilePath);
- return false;
- }
- if (!activeBuildConfiguration()) {
- d->disabledReason = tr("No active build configuration.");
- return false;
- }
if (remoteExecutableFilePath().isEmpty()) {
d->disabledReason = tr("Don't know what to run.");
return false;
@@ -184,26 +156,12 @@ OutputFormatter *RemoteLinuxRunConfiguration::createOutputFormatter() const
return new QtSupport::QtOutputFormatter(target()->project());
}
-void RemoteLinuxRunConfiguration::proFileUpdate(Qt4ProjectManager::Qt4ProFileNode *pro, bool success, bool parseInProgress)
-{
- if (d->proFilePath == pro->path()) {
- bool enabled = isEnabled();
- QString reason = disabledReason();
- d->validParse = success;
- d->parseInProgress = parseInProgress;
- if (enabled != isEnabled() || reason != disabledReason())
- updateEnabledState();
- if (!parseInProgress)
- emit targetInformationChanged();
- }
-}
-
QVariantMap RemoteLinuxRunConfiguration::toMap() const
{
QVariantMap map(RunConfiguration::toMap());
map.insert(QLatin1String(ArgumentsKey), d->arguments);
const QDir dir = QDir(target()->project()->projectDirectory());
- map.insert(QLatin1String(ProFileKey), dir.relativeFilePath(d->proFilePath));
+ map.insert(QLatin1String(ProFileKey), dir.relativeFilePath(d->projectFilePath));
map.insert(QLatin1String(BaseEnvironmentBaseKey), d->baseEnvironmentType);
map.insert(QLatin1String(UserEnvironmentChangesKey),
EnvironmentItem::toStringList(d->userEnvironmentChanges));
@@ -220,7 +178,8 @@ bool RemoteLinuxRunConfiguration::fromMap(const QVariantMap &map)
d->arguments = map.value(QLatin1String(ArgumentsKey)).toString();
const QDir dir = QDir(target()->project()->projectDirectory());
- d->proFilePath = QDir::cleanPath(dir.filePath(map.value(QLatin1String(ProFileKey)).toString()));
+ d->projectFilePath
+ = QDir::cleanPath(dir.filePath(map.value(QLatin1String(ProFileKey)).toString()));
d->userEnvironmentChanges =
EnvironmentItem::fromStringList(map.value(QLatin1String(UserEnvironmentChangesKey))
.toStringList());
@@ -230,10 +189,6 @@ bool RemoteLinuxRunConfiguration::fromMap(const QVariantMap &map)
d->alternateRemoteExecutable = map.value(QLatin1String(AlternateExeKey)).toString();
d->workingDirectory = map.value(QLatin1String(WorkingDirectoryKey)).toString();
- Qt4Project *project = static_cast<Qt4Project *>(target()->project());
- d->validParse = project->validParse(d->proFilePath);
- d->parseInProgress = project->parseInProgress(d->proFilePath);
-
setDefaultDisplayName(defaultDisplayName());
return true;
@@ -241,18 +196,13 @@ bool RemoteLinuxRunConfiguration::fromMap(const QVariantMap &map)
QString RemoteLinuxRunConfiguration::defaultDisplayName()
{
- if (!d->proFilePath.isEmpty())
+ if (!d->projectFilePath.isEmpty())
//: %1 is the name of a project which is being run on remote Linux
- return tr("%1 (on Remote Device)").arg(QFileInfo(d->proFilePath).completeBaseName());
+ return tr("%1 (on Remote Device)").arg(QFileInfo(d->projectFilePath).completeBaseName());
//: Remote Linux run configuration default display name
return tr("Run on Remote Device");
}
-RemoteLinuxDeployConfiguration *RemoteLinuxRunConfiguration::deployConfig() const
-{
- return qobject_cast<RemoteLinuxDeployConfiguration *>(target()->activeDeployConfiguration());
-}
-
QString RemoteLinuxRunConfiguration::arguments() const
{
return d->arguments;
@@ -280,19 +230,14 @@ QString RemoteLinuxRunConfiguration::commandPrefix() const
QString RemoteLinuxRunConfiguration::localExecutableFilePath() const
{
- TargetInformation ti = static_cast<Qt4Project *>(target()->project())->rootQt4ProjectNode()
- ->targetInformation(d->proFilePath);
- if (!ti.valid)
- return QString();
-
- return QDir::cleanPath(ti.workingDir + QLatin1Char('/') + ti.target);
+ return target()->applicationTargets()
+ .targetForProject(Utils::FileName::fromString(d->projectFilePath)).toString();
}
QString RemoteLinuxRunConfiguration::defaultRemoteExecutableFilePath() const
{
- return deployConfig()
- ? deployConfig()->deploymentInfo()->remoteExecutableFilePath(localExecutableFilePath())
- : QString();
+ return target()->deploymentData().deployableForLocalFile(localExecutableFilePath())
+ .remoteFilePath();
}
QString RemoteLinuxRunConfiguration::remoteExecutableFilePath() const
@@ -347,17 +292,10 @@ int RemoteLinuxRunConfiguration::portsUsedByDebuggers() const
return ports;
}
-void RemoteLinuxRunConfiguration::handleDeployConfigChanged()
-{
- RemoteLinuxDeployConfiguration * const activeDeployConf = deployConfig();
- if (activeDeployConf)
- connect(activeDeployConf->deploymentInfo(), SIGNAL(modelReset()),
- SLOT(handleDeployablesUpdated()), Qt::UniqueConnection);
-}
-
-void RemoteLinuxRunConfiguration::handleDeployablesUpdated()
+void RemoteLinuxRunConfiguration::handleBuildSystemDataUpdated()
{
emit deploySpecsChanged();
+ emit targetInformationChanged();
updateEnabledState();
}
@@ -432,9 +370,9 @@ void RemoteLinuxRunConfiguration::setRemoteEnvironment(const Environment &enviro
}
}
-QString RemoteLinuxRunConfiguration::proFilePath() const
+QString RemoteLinuxRunConfiguration::projectFilePath() const
{
- return d->proFilePath;
+ return d->projectFilePath;
}
void RemoteLinuxRunConfiguration::setDisabledReason(const QString &reason) const
diff --git a/src/plugins/remotelinux/remotelinuxrunconfiguration.h b/src/plugins/remotelinux/remotelinuxrunconfiguration.h
index aa56432e18..245d5468c5 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfiguration.h
+++ b/src/plugins/remotelinux/remotelinuxrunconfiguration.h
@@ -35,10 +35,6 @@
#include <projectexplorer/runconfiguration.h>
#include <utils/environment.h>
-namespace Qt4ProjectManager {
-class Qt4ProFileNode;
-} // namespace Qt4ProjectManager
-
namespace Utils { class PortList; }
namespace RemoteLinux {
@@ -66,7 +62,7 @@ public:
enum DebuggingType { DebugCppOnly, DebugQmlOnly, DebugCppAndQml };
RemoteLinuxRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id,
- const QString &proFilePath);
+ const QString &projectFilePath);
~RemoteLinuxRunConfiguration();
bool isEnabled() const;
@@ -74,8 +70,6 @@ public:
QWidget *createConfigurationWidget();
Utils::OutputFormatter *createOutputFormatter() const;
- RemoteLinuxDeployConfiguration *deployConfig() const;
-
virtual QString environmentPreparationCommand() const;
virtual QString commandPrefix() const;
@@ -102,7 +96,7 @@ public:
int portsUsedByDebuggers() const;
- QString proFilePath() const;
+ QString projectFilePath() const;
static const QString IdPrefix;
@@ -125,9 +119,7 @@ protected slots:
void updateEnabledState() { emit enabledChanged(); }
private slots:
- void proFileUpdate(Qt4ProjectManager::Qt4ProFileNode *pro, bool success, bool parseInProgress);
- void handleDeployConfigChanged();
- void handleDeployablesUpdated();
+ void handleBuildSystemDataUpdated();
private:
void init();
diff --git a/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.cpp b/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.cpp
index 6799a84da4..dedce8627b 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.cpp
@@ -29,14 +29,12 @@
#include "remotelinuxrunconfigurationfactory.h"
#include "remotelinux_constants.h"
-#include "remotelinuxdeployconfigurationfactory.h"
#include "remotelinuxrunconfiguration.h"
+#include <projectexplorer/buildtargetinfo.h>
#include <projectexplorer/kitinformation.h>
+#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
-#include <qt4projectmanager/qt4project.h>
-#include <qt4projectmanager/qt4nodes.h>
-#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
@@ -44,7 +42,6 @@
#include <QStringList>
using namespace ProjectExplorer;
-using namespace Qt4ProjectManager;
namespace RemoteLinux {
namespace Internal {
@@ -61,8 +58,10 @@ QString pathFromId(Core::Id id)
} // namespace
RemoteLinuxRunConfigurationFactory::RemoteLinuxRunConfigurationFactory(QObject *parent)
- : Qt4ProjectManager::QmakeRunConfigurationFactory(parent)
-{ setObjectName(QLatin1String("RemoteLinuxRunConfigurationFactory")); }
+ : IRunConfigurationFactory(parent)
+{
+ setObjectName(QLatin1String("RemoteLinuxRunConfigurationFactory"));
+}
RemoteLinuxRunConfigurationFactory::~RemoteLinuxRunConfigurationFactory()
{
@@ -72,14 +71,14 @@ bool RemoteLinuxRunConfigurationFactory::canCreate(Target *parent, const Core::I
{
if (!canHandle(parent))
return false;
- return static_cast<Qt4Project *>(parent->project())->hasApplicationProFile(pathFromId(id));
+ return !parent->applicationTargets().targetForProject(pathFromId(id)).isEmpty();
}
bool RemoteLinuxRunConfigurationFactory::canRestore(Target *parent, const QVariantMap &map) const
{
if (!canHandle(parent))
return false;
- return ProjectExplorer::idFromMap(map).toString().startsWith(RemoteLinuxRunConfiguration::IdPrefix);
+ return idFromMap(map).toString().startsWith(RemoteLinuxRunConfiguration::IdPrefix);
}
bool RemoteLinuxRunConfigurationFactory::canClone(Target *parent, RunConfiguration *source) const
@@ -95,10 +94,8 @@ QList<Core::Id> RemoteLinuxRunConfigurationFactory::availableCreationIds(Target
if (!canHandle(parent))
return result;
- QStringList proFiles = static_cast<Qt4Project *>(parent->project())
- ->applicationProFilePathes(RemoteLinuxRunConfiguration::IdPrefix);
- foreach (const QString &pf, proFiles)
- result << Core::Id(pf);
+ foreach (const BuildTargetInfo &bti, parent->applicationTargets().list)
+ result << (Core::Id(RemoteLinuxRunConfiguration::IdPrefix + bti.projectFilePath.toString()));
return result;
}
@@ -118,8 +115,8 @@ RunConfiguration *RemoteLinuxRunConfigurationFactory::restore(Target *parent,
const QVariantMap &map)
{
QTC_ASSERT(canRestore(parent, map), return 0);
- RemoteLinuxRunConfiguration *rc
- = new RemoteLinuxRunConfiguration(parent, Core::Id(RemoteLinuxRunConfiguration::IdPrefix), QString());
+ RemoteLinuxRunConfiguration *rc = new RemoteLinuxRunConfiguration(parent,
+ Core::Id(RemoteLinuxRunConfiguration::IdPrefix), QString());
if (rc->fromMap(map))
return rc;
@@ -135,26 +132,13 @@ RunConfiguration *RemoteLinuxRunConfigurationFactory::clone(Target *parent,
return new RemoteLinuxRunConfiguration(parent, old);
}
-bool RemoteLinuxRunConfigurationFactory::canHandle(Target *t) const
+bool RemoteLinuxRunConfigurationFactory::canHandle(const Target *target) const
{
- if (!t->project()->supportsKit(t->kit()))
+ if (!target->project()->supportsKit(target->kit()))
return false;
- if (!qobject_cast<Qt4Project *>(t->project()))
- return false;
-
- Core::Id deviceType = ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(t->kit());
+ const Core::Id deviceType = DeviceTypeKitInformation::deviceTypeId(target->kit());
return deviceType == RemoteLinux::Constants::GenericLinuxOsType;
}
-QList<RunConfiguration *> RemoteLinuxRunConfigurationFactory::runConfigurationsForNode(Target *t, ProjectExplorer::Node *n)
-{
- QList<ProjectExplorer::RunConfiguration *> result;
- foreach (ProjectExplorer::RunConfiguration *rc, t->runConfigurations())
- if (RemoteLinuxRunConfiguration *qt4c = qobject_cast<RemoteLinuxRunConfiguration *>(rc))
- if (qt4c->proFilePath() == n->path())
- result << rc;
- return result;
-}
-
} // namespace Internal
} // namespace RemoteLinux
diff --git a/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.h b/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.h
index 78449d2fb8..a4d951574f 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.h
+++ b/src/plugins/remotelinux/remotelinuxrunconfigurationfactory.h
@@ -30,14 +30,11 @@
#define REMOTELINUXRUNCONFIGURATIONFACTORY_H
#include <projectexplorer/runconfiguration.h>
-#include <qt4projectmanager/qmakerunconfigurationfactory.h>
-
-namespace ProjectExplorer { class Node; }
namespace RemoteLinux {
namespace Internal {
-class RemoteLinuxRunConfigurationFactory : public Qt4ProjectManager::QmakeRunConfigurationFactory
+class RemoteLinuxRunConfigurationFactory : public ProjectExplorer::IRunConfigurationFactory
{
Q_OBJECT
@@ -59,9 +56,8 @@ public:
ProjectExplorer::RunConfiguration *clone(ProjectExplorer::Target *parent,
ProjectExplorer::RunConfiguration *source);
- bool canHandle(ProjectExplorer::Target *t) const;
- QList<ProjectExplorer::RunConfiguration *> runConfigurationsForNode(ProjectExplorer::Target *t,
- ProjectExplorer::Node *n);
+private:
+ bool canHandle(const ProjectExplorer::Target *target) const;
};
} // namespace Internal
diff --git a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
index cd1d89a940..3aa1a12ca9 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
+++ b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.cpp
@@ -229,13 +229,23 @@ void RemoteLinuxRunConfigurationWidget::argumentsEdited(const QString &text)
void RemoteLinuxRunConfigurationWidget::updateTargetInformation()
{
- d->localExecutableLabel
- .setText(QDir::toNativeSeparators(d->runConfiguration->localExecutableFilePath()));
+ setLabelText(d->localExecutableLabel,
+ QDir::toNativeSeparators(d->runConfiguration->localExecutableFilePath()),
+ tr("Unknown"));
}
void RemoteLinuxRunConfigurationWidget::handleDeploySpecsChanged()
{
- d->remoteExecutableLabel.setText(d->runConfiguration->defaultRemoteExecutableFilePath());
+ setLabelText(d->remoteExecutableLabel, d->runConfiguration->defaultRemoteExecutableFilePath(),
+ tr("Remote path not set"));
+}
+
+void RemoteLinuxRunConfigurationWidget::setLabelText(QLabel &label, const QString &regularText,
+ const QString &errorText)
+{
+ const QString errorMessage = QLatin1String("<font color=\"red\">") + errorText
+ + QLatin1String("</font>");
+ label.setText(regularText.isEmpty() ? errorMessage : regularText);
}
void RemoteLinuxRunConfigurationWidget::handleUseAlternateCommandChanged()
diff --git a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.h b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.h
index 932508527d..704430573c 100644
--- a/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.h
+++ b/src/plugins/remotelinux/remotelinuxrunconfigurationwidget.h
@@ -34,6 +34,7 @@
#include <QWidget>
QT_BEGIN_NAMESPACE
+class QLabel;
class QVBoxLayout;
QT_END_NAMESPACE
@@ -79,6 +80,7 @@ private slots:
private:
void addGenericWidgets(QVBoxLayout *mainLayout);
void addEnvironmentWidgets(QVBoxLayout *mainLayout);
+ void setLabelText(QLabel &label, const QString &regularText, const QString &errorText);
Internal::RemoteLinuxRunConfigurationWidgetPrivate * const d;
};
diff --git a/src/plugins/remotelinux/remotelinuxruncontrol.cpp b/src/plugins/remotelinux/remotelinuxruncontrol.cpp
index 4eb0f3d356..8d3aa71627 100644
--- a/src/plugins/remotelinux/remotelinuxruncontrol.cpp
+++ b/src/plugins/remotelinux/remotelinuxruncontrol.cpp
@@ -127,7 +127,7 @@ bool RemoteLinuxRunControl::isRunning() const
QIcon RemoteLinuxRunControl::icon() const
{
- return QIcon(ProjectExplorer::Constants::ICON_RUN_SMALL);
+ return QIcon(QLatin1String(ProjectExplorer::Constants::ICON_RUN_SMALL));
}
void RemoteLinuxRunControl::setApplicationRunnerPreRunAction(DeviceApplicationHelperAction *action)
diff --git a/src/plugins/remotelinux/tarpackagecreationstep.cpp b/src/plugins/remotelinux/tarpackagecreationstep.cpp
index 6ea2b18d1b..431db74d75 100644
--- a/src/plugins/remotelinux/tarpackagecreationstep.cpp
+++ b/src/plugins/remotelinux/tarpackagecreationstep.cpp
@@ -28,10 +28,9 @@
****************************************************************************/
#include "tarpackagecreationstep.h"
-#include "deployablefile.h"
-#include "deploymentinfo.h"
#include "remotelinuxdeployconfiguration.h"
+#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
@@ -40,6 +39,8 @@
#include <QFile>
#include <QFileInfo>
+#include <cstring>
+
using namespace ProjectExplorer;
namespace RemoteLinux {
@@ -56,7 +57,7 @@ public:
QString summaryText() const
{
- TarPackageCreationStep * const step = qobject_cast<TarPackageCreationStep *>(this->step());
+ TarPackageCreationStep * const step = static_cast<TarPackageCreationStep *>(this->step());
if (step->packageFilePath().isEmpty()) {
return QLatin1String("<font color=\"red\">")
+ tr("Tarball creation not possible.") + QLatin1String("</font>");
@@ -112,13 +113,8 @@ bool TarPackageCreationStep::init()
if (!AbstractPackagingStep::init())
return false;
m_packagingNeeded = isPackagingNeeded();
- if (!m_packagingNeeded)
- return true;
-
- const DeploymentInfo * const deploymentInfo = deployConfiguration()->deploymentInfo();
- for (int i = 0; i < deploymentInfo->deployableCount(); ++i)
- m_files.append(deploymentInfo->deployableAt(i));
-
+ if (m_packagingNeeded)
+ m_files = target()->deploymentData().allFiles();
return true;
}
@@ -152,13 +148,13 @@ bool TarPackageCreationStep::doPackage(QFutureInterface<bool> &fi)
}
foreach (const DeployableFile &d, m_files) {
- if (d.remoteDir.isEmpty()) {
+ if (d.remoteDirectory().isEmpty()) {
emit addOutput(tr("No remote path specified for file '%1', skipping.")
- .arg(QDir::toNativeSeparators(d.localFilePath)), ErrorMessageOutput);
+ .arg(d.localFilePath().toUserOutput()), ErrorMessageOutput);
continue;
}
- QFileInfo fileInfo(d.localFilePath);
- if (!appendFile(tarFile, fileInfo, d.remoteDir + QLatin1Char('/')
+ QFileInfo fileInfo = d.localFilePath().toFileInfo();
+ if (!appendFile(tarFile, fileInfo, d.remoteDirectory() + QLatin1Char('/')
+ fileInfo.fileName(), fi)) {
return false;
}
@@ -230,20 +226,20 @@ bool TarPackageCreationStep::writeHeader(QFile &tarFile, const QFileInfo &fileIn
const QString &remoteFilePath)
{
TarFileHeader header;
- qMemSet(&header, '\0', sizeof header);
+ std::memset(&header, '\0', sizeof header);
const QByteArray &filePath = remoteFilePath.toUtf8();
const int maxFilePathLength = sizeof header.fileNamePrefix + sizeof header.fileName;
if (filePath.count() > maxFilePathLength) {
raiseError(tr("Cannot add file '%1' to tar-archive: path too long.")
- .arg(QDir::toNativeSeparators(filePath)));
+ .arg(QDir::toNativeSeparators(remoteFilePath)));
return false;
}
const int fileNameBytesToWrite = qMin<int>(filePath.length(), sizeof header.fileName);
const int fileNameOffset = filePath.length() - fileNameBytesToWrite;
- qMemCopy(&header.fileName, filePath.data() + fileNameOffset, fileNameBytesToWrite);
+ std::memcpy(&header.fileName, filePath.data() + fileNameOffset, fileNameBytesToWrite);
if (fileNameOffset > 0)
- qMemCopy(&header.fileNamePrefix, filePath.data(), fileNameOffset);
+ std::memcpy(&header.fileNamePrefix, filePath.data(), fileNameOffset);
int permissions = (0400 * fileInfo.permission(QFile::ReadOwner))
| (0200 * fileInfo.permission(QFile::WriteOwner))
| (0100 * fileInfo.permission(QFile::ExeOwner))
@@ -253,36 +249,36 @@ bool TarPackageCreationStep::writeHeader(QFile &tarFile, const QFileInfo &fileIn
| (04 * fileInfo.permission(QFile::ReadOther))
| (02 * fileInfo.permission(QFile::WriteOther))
| (01 * fileInfo.permission(QFile::ExeOther));
- const QByteArray permissionString = QString("%1").arg(permissions,
- sizeof header.fileMode - 1, 8, QLatin1Char('0')).toAscii();
- qMemCopy(&header.fileMode, permissionString.data(), permissionString.length());
- const QByteArray uidString = QString("%1").arg(fileInfo.ownerId(),
- sizeof header.uid - 1, 8, QLatin1Char('0')).toAscii();
- qMemCopy(&header.uid, uidString.data(), uidString.length());
- const QByteArray gidString = QString("%1").arg(fileInfo.groupId(),
- sizeof header.gid - 1, 8, QLatin1Char('0')).toAscii();
- qMemCopy(&header.gid, gidString.data(), gidString.length());
- const QByteArray sizeString = QString("%1").arg(fileInfo.size(),
- sizeof header.length - 1, 8, QLatin1Char('0')).toAscii();
- qMemCopy(&header.length, sizeString.data(), sizeString.length());
- const QByteArray mtimeString = QString("%1").arg(fileInfo.lastModified().toTime_t(),
- sizeof header.mtime - 1, 8, QLatin1Char('0')).toAscii();
- qMemCopy(&header.mtime, mtimeString.data(), mtimeString.length());
+ const QByteArray permissionString = QString::fromLatin1("%1").arg(permissions,
+ sizeof header.fileMode - 1, 8, QLatin1Char('0')).toLatin1();
+ std::memcpy(&header.fileMode, permissionString.data(), permissionString.length());
+ const QByteArray uidString = QString::fromLatin1("%1").arg(fileInfo.ownerId(),
+ sizeof header.uid - 1, 8, QLatin1Char('0')).toLatin1();
+ std::memcpy(&header.uid, uidString.data(), uidString.length());
+ const QByteArray gidString = QString::fromLatin1("%1").arg(fileInfo.groupId(),
+ sizeof header.gid - 1, 8, QLatin1Char('0')).toLatin1();
+ std::memcpy(&header.gid, gidString.data(), gidString.length());
+ const QByteArray sizeString = QString::fromLatin1("%1").arg(fileInfo.size(),
+ sizeof header.length - 1, 8, QLatin1Char('0')).toLatin1();
+ std::memcpy(&header.length, sizeString.data(), sizeString.length());
+ const QByteArray mtimeString = QString::fromLatin1("%1").arg(fileInfo.lastModified().toTime_t(),
+ sizeof header.mtime - 1, 8, QLatin1Char('0')).toLatin1();
+ std::memcpy(&header.mtime, mtimeString.data(), mtimeString.length());
if (fileInfo.isDir())
header.typeflag = '5';
- qMemCopy(&header.magic, "ustar", sizeof "ustar");
- qMemCopy(&header.version, "00", 2);
+ std::memcpy(&header.magic, "ustar", sizeof "ustar");
+ std::memcpy(&header.version, "00", 2);
const QByteArray &owner = fileInfo.owner().toUtf8();
- qMemCopy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
+ std::memcpy(&header.uname, owner.data(), qMin<int>(owner.length(), sizeof header.uname - 1));
const QByteArray &group = fileInfo.group().toUtf8();
- qMemCopy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
- qMemSet(&header.chksum, ' ', sizeof header.chksum);
+ std::memcpy(&header.gname, group.data(), qMin<int>(group.length(), sizeof header.gname - 1));
+ std::memset(&header.chksum, ' ', sizeof header.chksum);
quint64 checksum = 0;
for (size_t i = 0; i < sizeof header; ++i)
checksum += reinterpret_cast<char *>(&header)[i];
- const QByteArray checksumString = QString("%1").arg(checksum,
- sizeof header.chksum - 1, 8, QLatin1Char('0')).toAscii();
- qMemCopy(&header.chksum, checksumString.data(), checksumString.length());
+ const QByteArray checksumString = QString::fromLatin1("%1").arg(checksum,
+ sizeof header.chksum - 1, 8, QLatin1Char('0')).toLatin1();
+ std::memcpy(&header.chksum, checksumString.data(), checksumString.length());
header.chksum[sizeof header.chksum-1] = 0;
if (!tarFile.write(reinterpret_cast<char *>(&header), sizeof header)) {
raiseError(tr("Error writing tar file '%1': %2")
diff --git a/src/plugins/remotelinux/tarpackagecreationstep.h b/src/plugins/remotelinux/tarpackagecreationstep.h
index b3f3d9c23f..45a98f5ce8 100644
--- a/src/plugins/remotelinux/tarpackagecreationstep.h
+++ b/src/plugins/remotelinux/tarpackagecreationstep.h
@@ -31,7 +31,8 @@
#include "abstractpackagingstep.h"
#include "remotelinux_export.h"
-#include "deployablefile.h"
+
+#include <projectexplorer/deployablefile.h>
QT_BEGIN_NAMESPACE
class QFile;
@@ -65,7 +66,7 @@ private:
const QString &remoteFilePath);
bool m_packagingNeeded;
- QList<DeployableFile> m_files;
+ QList<ProjectExplorer::DeployableFile> m_files;
};
} // namespace RemoteLinux
diff --git a/src/plugins/resourceeditor/qrceditor/qrceditor.cpp b/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
index 0e9316516d..f15a62b957 100644
--- a/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
+++ b/src/plugins/resourceeditor/qrceditor/qrceditor.cpp
@@ -287,9 +287,8 @@ void QrcEditor::resolveLocationIssues(QStringList &files)
}
// All paths fine -> no interaction needed
- if (i == count) {
+ if (i == count)
return;
- }
// Interact with user from now on
ResolveLocationContext context;
@@ -298,9 +297,8 @@ void QrcEditor::resolveLocationIssues(QStringList &files)
// Path fine -> skip file
QString const &file = *it;
QString const relativePath = dir.relativeFilePath(file);
- if (!relativePath.startsWith(dotdotSlash)) {
+ if (!relativePath.startsWith(dotdotSlash))
continue;
- }
// Path troublesome and aborted -> remove file
bool ok = false;
if (!abort) {
diff --git a/src/plugins/resourceeditor/qrceditor/resourcefile.cpp b/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
index 811ec49ac9..d117eea083 100644
--- a/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
+++ b/src/plugins/resourceeditor/qrceditor/resourcefile.cpp
@@ -650,11 +650,10 @@ int ResourceModel::rowCount(const QModelIndex &parent) const
Q_ASSERT(prefix);
bool const isFileNode = (prefix != node);
- if (isFileNode) {
+ if (isFileNode)
return 0;
- } else {
+ else
return prefix->file_list.count();
- }
} else {
return m_resource_file.prefixCount();
}
@@ -698,7 +697,7 @@ bool ResourceModel::iconFileExtension(const QString &path)
const QList<QByteArray> _ext_list = QImageReader::supportedImageFormats();
foreach (const QByteArray &ext, _ext_list) {
QString dotExt = QString(QLatin1Char('.'));
- dotExt += QString::fromAscii(ext);
+ dotExt += QString::fromLatin1(ext);
ext_list.append(dotExt);
}
}
@@ -948,15 +947,13 @@ void ResourceModel::addFiles(int prefixIndex, const QStringList &fileNames, int
firstFile = -1;
lastFile = -1;
- if (!prefix_model_idx.isValid()) {
+ if (!prefix_model_idx.isValid())
return;
- }
QStringList unique_list = existingFilesSubtracted(prefixIndex, fileNames);
- if (unique_list.isEmpty()) {
+ if (unique_list.isEmpty())
return;
- }
const int cnt = m_resource_file.fileCount(prefixIndex);
beginInsertRows(prefix_model_idx, cnt, cnt + unique_list.count() - 1); // ### FIXME
@@ -1091,10 +1088,11 @@ QModelIndex ResourceModel::deleteItem(const QModelIndex &idx)
bool ResourceModel::reload()
{
+ beginResetModel();
const bool result = m_resource_file.load();
if (result)
setDirty(false);
- reset();
+ endResetModel();
return result;
}
diff --git a/src/plugins/resourceeditor/qrceditor/resourceview.cpp b/src/plugins/resourceeditor/qrceditor/resourceview.cpp
index 9c12488636..ae902b3b7a 100644
--- a/src/plugins/resourceeditor/qrceditor/resourceview.cpp
+++ b/src/plugins/resourceeditor/qrceditor/resourceview.cpp
@@ -314,9 +314,8 @@ void ResourceView::addFiles(int prefixIndex, const QStringList &fileNames, int c
// Expand prefix node
const QModelIndex prefixModelIndex = m_qrcModel->index(prefixIndex, 0, QModelIndex());
- if (prefixModelIndex.isValid()) {
+ if (prefixModelIndex.isValid())
this->setExpanded(prefixModelIndex, true);
- }
}
void ResourceView::removeFiles(int prefixIndex, int firstFileIndex, int lastFileIndex)
diff --git a/src/plugins/resourceeditor/resourceeditor.pro b/src/plugins/resourceeditor/resourceeditor.pro
index bfdb9a528a..5db47efcf8 100644
--- a/src/plugins/resourceeditor/resourceeditor.pro
+++ b/src/plugins/resourceeditor/resourceeditor.pro
@@ -1,8 +1,6 @@
TEMPLATE = lib
TARGET = ResourceEditor
-DEFINES += QT_NO_CAST_FROM_ASCII
-
include(../../qtcreatorplugin.pri)
include(../../libs/utils/utils.pri)
include(../../plugins/coreplugin/coreplugin.pri)
diff --git a/src/plugins/resourceeditor/resourceeditor.qbs b/src/plugins/resourceeditor/resourceeditor.qbs
index 68dc1df8bc..889bd951f2 100644
--- a/src/plugins/resourceeditor/resourceeditor.qbs
+++ b/src/plugins/resourceeditor/resourceeditor.qbs
@@ -10,14 +10,7 @@ QtcPlugin {
Depends { name: "cpp" }
Depends { name: "Qt"; submodules: ["widgets", "xml"] }
- cpp.includePaths: [
- "..",
- "../..",
- "../../libs",
- buildDirectory,
- "qrceditor",
- "../../tools/utils"
- ]
+ cpp.includePaths: base.concat("qrceditor")
files: [
"ResourceEditor.mimetypes.xml",
@@ -31,15 +24,14 @@ QtcPlugin {
"resourceeditorw.h",
"resourcewizard.cpp",
"resourcewizard.h",
- "qrceditor/resourcefile.cpp",
- "qrceditor/resourceview.cpp",
"qrceditor/qrceditor.cpp",
- "qrceditor/undocommands.cpp",
+ "qrceditor/qrceditor.h",
+ "qrceditor/qrceditor.ui",
+ "qrceditor/resourcefile.cpp",
"qrceditor/resourcefile_p.h",
+ "qrceditor/resourceview.cpp",
"qrceditor/resourceview.h",
- "qrceditor/qrceditor.h",
+ "qrceditor/undocommands.cpp",
"qrceditor/undocommands_p.h",
- "qrceditor/qrceditor.ui"
]
}
-
diff --git a/src/plugins/resourceeditor/resourceeditorfactory.cpp b/src/plugins/resourceeditor/resourceeditorfactory.cpp
index 353d6e6a39..748b4e9973 100644
--- a/src/plugins/resourceeditor/resourceeditorfactory.cpp
+++ b/src/plugins/resourceeditor/resourceeditorfactory.cpp
@@ -54,7 +54,7 @@ ResourceEditorFactory::ResourceEditorFactory(ResourceEditorPlugin *plugin) :
Core::Id ResourceEditorFactory::id() const
{
- return RESOURCEEDITOR_ID;
+ return Core::Id(RESOURCEEDITOR_ID);
}
QString ResourceEditorFactory::displayName() const
diff --git a/src/plugins/resourceeditor/resourceeditorw.h b/src/plugins/resourceeditor/resourceeditorw.h
index acb57ae6be..539cbd174f 100644
--- a/src/plugins/resourceeditor/resourceeditorw.h
+++ b/src/plugins/resourceeditor/resourceeditorw.h
@@ -46,7 +46,7 @@ class ResourceEditorW;
class QrcEditor;
class ResourceEditorDocument
- : public virtual Core::IDocument
+ : public Core::IDocument
{
Q_OBJECT
diff --git a/src/plugins/subversion/annotationhighlighter.h b/src/plugins/subversion/annotationhighlighter.h
index def786bd28..683e820215 100644
--- a/src/plugins/subversion/annotationhighlighter.h
+++ b/src/plugins/subversion/annotationhighlighter.h
@@ -44,7 +44,7 @@ public:
QTextDocument *document = 0);
private:
- virtual QString changeNumber(const QString &block) const;
+ QString changeNumber(const QString &block) const;
const QChar m_blank;
};
diff --git a/src/plugins/subversion/checkoutwizard.h b/src/plugins/subversion/checkoutwizard.h
index 481c9458a9..7bd41dac09 100644
--- a/src/plugins/subversion/checkoutwizard.h
+++ b/src/plugins/subversion/checkoutwizard.h
@@ -42,15 +42,15 @@ public:
explicit CheckoutWizard(QObject *parent = 0);
// IWizard
- virtual QIcon icon() const;
- virtual QString description() const;
- virtual QString displayName() const;
+ QIcon icon() const;
+ QString description() const;
+ QString displayName() const;
protected:
// BaseCheckoutWizard
- virtual QList<QWizardPage*> createParameterPages(const QString &path);
- virtual QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPage,
- QString *checkoutPath);
+ QList<QWizardPage*> createParameterPages(const QString &path);
+ QSharedPointer<VcsBase::AbstractCheckoutJob> createJob(const QList<QWizardPage*> &parameterPage,
+ QString *checkoutPath);
};
} // namespace Internal
diff --git a/src/plugins/subversion/checkoutwizardpage.h b/src/plugins/subversion/checkoutwizardpage.h
index 594f9117b6..f656463d5c 100644
--- a/src/plugins/subversion/checkoutwizardpage.h
+++ b/src/plugins/subversion/checkoutwizardpage.h
@@ -41,7 +41,7 @@ public:
CheckoutWizardPage(QWidget *parent = 0);
protected:
- virtual QString directoryFromRepository(const QString &r) const;
+ QString directoryFromRepository(const QString &r) const;
};
} // namespace Internal
diff --git a/src/plugins/subversion/settingspage.cpp b/src/plugins/subversion/settingspage.cpp
index 3d6e9e743f..f209cd4010 100644
--- a/src/plugins/subversion/settingspage.cpp
+++ b/src/plugins/subversion/settingspage.cpp
@@ -103,7 +103,7 @@ QString SettingsPageWidget::searchKeywords() const
SettingsPage::SettingsPage() :
m_widget(0)
{
- setId(QLatin1String(VcsBase::Constants::VCS_ID_SUBVERSION));
+ setId(VcsBase::Constants::VCS_ID_SUBVERSION);
setDisplayName(tr("Subversion"));
}
diff --git a/src/plugins/subversion/subversion.pro b/src/plugins/subversion/subversion.pro
index dbb1765c39..b7be53fe6d 100644
--- a/src/plugins/subversion/subversion.pro
+++ b/src/plugins/subversion/subversion.pro
@@ -8,8 +8,6 @@ include(../../plugins/coreplugin/coreplugin.pri)
include(../../plugins/vcsbase/vcsbase.pri)
include(../../libs/utils/utils.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
-
HEADERS += annotationhighlighter.h \
subversionplugin.h \
subversioncontrol.h \
diff --git a/src/plugins/subversion/subversion.qbs b/src/plugins/subversion/subversion.qbs
index bed2a9aea3..ed5571e47c 100644
--- a/src/plugins/subversion/subversion.qbs
+++ b/src/plugins/subversion/subversion.qbs
@@ -12,35 +12,28 @@ QtcPlugin {
Depends { name: "VcsBase" }
Depends { name: "Locator" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
+ "annotationhighlighter.cpp",
"annotationhighlighter.h",
- "subversionplugin.h",
- "subversioncontrol.h",
- "settingspage.h",
- "subversioneditor.h",
- "subversionsubmiteditor.h",
- "subversionsettings.h",
+ "checkoutwizard.cpp",
"checkoutwizard.h",
+ "checkoutwizardpage.cpp",
"checkoutwizardpage.h",
+ "settingspage.cpp",
+ "settingspage.h",
+ "settingspage.ui",
+ "subversion.qrc",
"subversionconstants.h",
- "annotationhighlighter.cpp",
- "subversionplugin.cpp",
"subversioncontrol.cpp",
- "settingspage.cpp",
+ "subversioncontrol.h",
"subversioneditor.cpp",
- "subversionsubmiteditor.cpp",
+ "subversioneditor.h",
+ "subversionplugin.cpp",
+ "subversionplugin.h",
"subversionsettings.cpp",
- "checkoutwizard.cpp",
- "checkoutwizardpage.cpp",
- "settingspage.ui",
- "subversion.qrc"
+ "subversionsettings.h",
+ "subversionsubmiteditor.cpp",
+ "subversionsubmiteditor.h",
]
}
diff --git a/src/plugins/subversion/subversioncontrol.cpp b/src/plugins/subversion/subversioncontrol.cpp
index a83df6c559..64763227b4 100644
--- a/src/plugins/subversion/subversioncontrol.cpp
+++ b/src/plugins/subversion/subversioncontrol.cpp
@@ -50,7 +50,7 @@ QString SubversionControl::displayName() const
Core::Id SubversionControl::id() const
{
- return VcsBase::Constants::VCS_ID_SUBVERSION;
+ return Core::Id(VcsBase::Constants::VCS_ID_SUBVERSION);
}
bool SubversionControl::isConfigured() const
diff --git a/src/plugins/subversion/subversioneditor.cpp b/src/plugins/subversion/subversioneditor.cpp
index ed719a19c0..569268686e 100644
--- a/src/plugins/subversion/subversioneditor.cpp
+++ b/src/plugins/subversion/subversioneditor.cpp
@@ -52,6 +52,17 @@ SubversionEditor::SubversionEditor(const VcsBase::VcsBaseEditorParameters *type,
{
QTC_ASSERT(m_changeNumberPattern.isValid(), return);
QTC_ASSERT(m_revisionNumberPattern.isValid(), return);
+ /* Diff pattern:
+ \code
+ Index: main.cpp
+ ===================================================================
+ --- main.cpp<tab>(revision 2)
+ +++ main.cpp<tab>(working copy)
+ @@ -6,6 +6,5 @@
+ \endcode
+ */
+ setDiffFilePattern(QRegExp(QLatin1String("^[-+]{3} ([^\\t]+)|^Index: .*|^=+$")));
+ setLogEntryPattern(QRegExp(QLatin1String("^(r\\d+) \\|")));
setAnnotateRevisionTextFormat(tr("Annotate revision \"%1\""));
}
@@ -98,49 +109,12 @@ QString SubversionEditor::changeUnderCursor(const QTextCursor &c) const
return QString();
}
-/* code:
- Index: main.cpp
-===================================================================
---- main.cpp (revision 2)
-+++ main.cpp (working copy)
-@@ -6,6 +6,5 @@
-\endcode
-*/
-
-VcsBase::DiffHighlighter *SubversionEditor::createDiffHighlighter() const
-{
- const QRegExp filePattern(QLatin1String("^[-+][-+][-+] .*|^Index: .*|^==*$"));
- QTC_CHECK(filePattern.isValid());
- return new VcsBase::DiffHighlighter(filePattern);
-}
-
VcsBase::BaseAnnotationHighlighter *SubversionEditor::createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const
{
return new SubversionAnnotationHighlighter(changes, bg);
}
-QString SubversionEditor::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
-{
- // "+++ /depot/.../mainwindow.cpp<tab>(revision 3)"
- // Go back chunks
- const QString diffIndicator = QLatin1String("+++ ");
- for (QTextBlock block = inBlock; block.isValid() ; block = block.previous()) {
- QString diffFileName = block.text();
- if (diffFileName.startsWith(diffIndicator)) {
- diffFileName.remove(0, diffIndicator.size());
- const int tabIndex = diffFileName.lastIndexOf(QLatin1Char('\t'));
- if (tabIndex != -1)
- diffFileName.truncate(tabIndex);
- const QString rc = findDiffFile(diffFileName);
- if (Subversion::Constants::debug)
- qDebug() << Q_FUNC_INFO << diffFileName << rc << source();
- return rc;
- }
- }
- return QString();
-}
-
QStringList SubversionEditor::annotationPreviousVersions(const QString &v) const
{
bool ok;
diff --git a/src/plugins/subversion/subversioneditor.h b/src/plugins/subversion/subversioneditor.h
index 1a6b33d4ee..ee883255a5 100644
--- a/src/plugins/subversion/subversioneditor.h
+++ b/src/plugins/subversion/subversioneditor.h
@@ -46,12 +46,10 @@ public:
QWidget *parent);
private:
- virtual QSet<QString> annotationChanges() const;
- virtual QString changeUnderCursor(const QTextCursor &) const;
- virtual VcsBase::DiffHighlighter *createDiffHighlighter() const;
- virtual VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
- virtual QString fileNameFromDiffSpecification(const QTextBlock &diffFileName) const;
- virtual QStringList annotationPreviousVersions(const QString &) const;
+ QSet<QString> annotationChanges() const;
+ QString changeUnderCursor(const QTextCursor &) const;
+ VcsBase::BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes, const QColor &bg) const;
+ QStringList annotationPreviousVersions(const QString &) const;
mutable QRegExp m_changeNumberPattern;
mutable QRegExp m_revisionNumberPattern;
diff --git a/src/plugins/subversion/subversionplugin.cpp b/src/plugins/subversion/subversionplugin.cpp
index 0198f96e22..8a45167af7 100644
--- a/src/plugins/subversion/subversionplugin.cpp
+++ b/src/plugins/subversion/subversionplugin.cpp
@@ -45,6 +45,7 @@
#include <utils/synchronousprocess.h>
#include <utils/parameteraction.h>
#include <utils/fileutils.h>
+#include <utils/hostosinfo.h>
#include <coreplugin/icore.h>
#include <coreplugin/coreconstants.h>
@@ -76,6 +77,10 @@
#include <QInputDialog>
#include <limits.h>
+#ifdef WITH_TESTS
+#include <QTest>
+#endif
+
namespace Subversion {
namespace Internal {
@@ -141,7 +146,7 @@ static inline const VcsBase::VcsBaseEditorParameters *findType(int ie)
static inline QString debugCodec(const QTextCodec *c)
{
- return c ? QString::fromAscii(c->name()) : QString::fromAscii("Null codec");
+ return c ? QString::fromLatin1(c->name()) : QString::fromLatin1("Null codec");
}
// Parse "svn status" output for added/modified/deleted files
@@ -171,10 +176,9 @@ StatusList parseStatusOutput(const QString &output)
static inline QStringList svnDirectories()
{
QStringList rc(QLatin1String(".svn"));
-#ifdef Q_OS_WIN
- // Option on Windows systems to avoid hassle with some IDEs
- rc.push_back(QLatin1String("_svn"));
-#endif
+ if (Utils::HostOsInfo::isWindowsHost())
+ // Option on Windows systems to avoid hassle with some IDEs
+ rc.push_back(QLatin1String("_svn"));
return rc;
}
@@ -236,7 +240,8 @@ static const VcsBase::VcsBaseSubmitEditorParameters submitParameters = {
Subversion::Constants::SUBVERSION_SUBMIT_MIMETYPE,
Subversion::Constants::SUBVERSIONCOMMITEDITOR_ID,
Subversion::Constants::SUBVERSIONCOMMITEDITOR_DISPLAY_NAME,
- Subversion::Constants::SUBVERSIONCOMMITEDITOR
+ Subversion::Constants::SUBVERSIONCOMMITEDITOR,
+ VcsBase::VcsBaseSubmitEditorParameters::DiffFiles
};
bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *errorMessage)
@@ -268,9 +273,8 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e
addAutoReleasedObject(new CheckoutWizard);
- const QString description = QLatin1String("Subversion");
const QString prefix = QLatin1String("svn");
- m_commandLocator = new Locator::CommandLocator(description, prefix, prefix);
+ m_commandLocator = new Locator::CommandLocator("Subversion", prefix, prefix);
addAutoReleasedObject(m_commandLocator);
//register actions
@@ -681,11 +685,10 @@ void SubversionPlugin::revertAll()
const SubversionResponse revertResponse =
runSvn(state.topLevel(), args, m_settings.timeOutMS(),
SshPasswordPrompt|ShowStdOutInLogWindow);
- if (revertResponse.error) {
+ if (revertResponse.error)
QMessageBox::warning(0, title, tr("Revert failed: %1").arg(revertResponse.message), QMessageBox::Ok);
- } else {
+ else
subVersionControl()->emitRepositoryChanged(state.topLevel());
- }
}
void SubversionPlugin::revertCurrentFile()
@@ -718,9 +721,8 @@ void SubversionPlugin::revertCurrentFile()
runSvn(state.currentFileTopLevel(), args, m_settings.timeOutMS(),
SshPasswordPrompt|ShowStdOutInLogWindow);
- if (!revertResponse.error) {
+ if (!revertResponse.error)
subVersionControl()->emitFilesChanged(QStringList(state.currentFile()));
- }
}
void SubversionPlugin::diffProject()
@@ -883,7 +885,7 @@ void SubversionPlugin::filelog(const QString &workingDir,
QStringList args(QLatin1String("log"));
if (m_settings.logCount > 0)
args << QLatin1String("-l") << QString::number(m_settings.logCount);
- foreach(const QString &file, files)
+ foreach (const QString &file, files)
args.append(QDir::toNativeSeparators(file));
// subversion stores log in UTF-8 and returns it back in user system locale.
@@ -1145,7 +1147,7 @@ Core::IEditor *SubversionPlugin::showOutputInEditor(const QString &title, const
{
const VcsBase::VcsBaseEditorParameters *params = findType(editorType);
QTC_ASSERT(params, return 0);
- const Core::Id id = params->id;
+ const Core::Id id = Core::Id(QByteArray(params->id));
if (Subversion::Constants::debug)
qDebug() << "SubversionPlugin::showOutputInEditor" << title << id.name()
<< "Size= " << output.size() << " Type=" << editorType << debugCodec(codec);
@@ -1190,11 +1192,9 @@ SubversionPlugin *SubversionPlugin::instance()
bool SubversionPlugin::vcsAdd(const QString &workingDir, const QString &rawFileName)
{
-#ifdef Q_OS_MAC // See below.
- return vcsAdd14(workingDir, rawFileName);
-#else
+ if (Utils::HostOsInfo::isMacHost()) // See below.
+ return vcsAdd14(workingDir, rawFileName);
return vcsAdd15(workingDir, rawFileName);
-#endif
}
// Post 1.4 add: Use "--parents" to add directories
@@ -1307,20 +1307,20 @@ QString SubversionPlugin::vcsGetRepositoryURL(const QString &directory)
bool repo = false;
bool root = false;
- while(!xml.atEnd() && !xml.hasError()) {
- switch(xml.readNext()) {
+ while (!xml.atEnd() && !xml.hasError()) {
+ switch (xml.readNext()) {
case QXmlStreamReader::StartDocument:
break;
case QXmlStreamReader::StartElement:
- if(xml.name() == QLatin1String("repository"))
+ if (xml.name() == QLatin1String("repository"))
repo = true;
- else if(repo && xml.name() == QLatin1String("root"))
+ else if (repo && xml.name() == QLatin1String("root"))
root = true;
break;
case QXmlStreamReader::EndElement:
- if(xml.name() == QLatin1String("repository"))
+ if (xml.name() == QLatin1String("repository"))
repo = false;
- else if(repo && xml.name() == QLatin1String("root"))
+ else if (repo && xml.name() == QLatin1String("root"))
root = false;
break;
case QXmlStreamReader::Characters:
@@ -1393,6 +1393,64 @@ SubversionControl *SubversionPlugin::subVersionControl() const
return static_cast<SubversionControl *>(versionControl());
}
+#ifdef WITH_TESTS
+void SubversionPlugin::testDiffFileResolving_data()
+{
+ QTest::addColumn<QByteArray>("header");
+ QTest::addColumn<QByteArray>("fileName");
+
+ QTest::newRow("New") << QByteArray(
+ "Index: src/plugins/subversion/subversioneditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/subversion/subversioneditor.cpp\t(revision 0)\n"
+ "+++ src/plugins/subversion/subversioneditor.cpp\t(revision 0)\n"
+ "@@ -0,0 +125 @@\n\n")
+ << QByteArray("src/plugins/subversion/subversioneditor.cpp");
+ QTest::newRow("Deleted") << QByteArray(
+ "Index: src/plugins/subversion/subversioneditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/subversion/subversioneditor.cpp\t(revision 42)\n"
+ "+++ src/plugins/subversion/subversioneditor.cpp\t(working copy)\n"
+ "@@ -1,125 +0,0 @@\n\n")
+ << QByteArray("src/plugins/subversion/subversioneditor.cpp");
+ QTest::newRow("Normal") << QByteArray(
+ "Index: src/plugins/subversion/subversioneditor.cpp\n"
+ "===================================================================\n"
+ "--- src/plugins/subversion/subversioneditor.cpp\t(revision 42)\n"
+ "+++ src/plugins/subversion/subversioneditor.cpp\t(working copy)\n"
+ "@@ -120,7 +120,7 @@\n\n")
+ << QByteArray("src/plugins/subversion/subversioneditor.cpp");
+}
+
+void SubversionPlugin::testDiffFileResolving()
+{
+ SubversionEditor editor(editorParameters + 3, 0);
+ editor.testDiffFileResolving();
+}
+
+void SubversionPlugin::testLogResolving()
+{
+ QByteArray data(
+ "------------------------------------------------------------------------\n"
+ "r1439551 | philip | 2013-01-28 20:19:55 +0200 (Mon, 28 Jan 2013) | 4 lines\n"
+ "\n"
+ "* subversion/tests/cmdline/update_tests.py\n"
+ " (update_moved_dir_file_move): Resolve conflict, adjust expectations,\n"
+ " remove XFail.\n"
+ "\n"
+ "------------------------------------------------------------------------\n"
+ "r1439540 | philip | 2013-01-28 20:06:36 +0200 (Mon, 28 Jan 2013) | 4 lines\n"
+ "\n"
+ "* subversion/tests/cmdline/update_tests.py\n"
+ " (update_moved_dir_edited_leaf_del): Do non-recursive resolution, adjust\n"
+ " expectations, remove XFail.\n"
+ "\n"
+ );
+ SubversionEditor editor(editorParameters + 1, 0);
+ editor.testLogResolving(data, "r1439551", "r1439540");
+}
+#endif
+
} // Internal
} // Subversion
diff --git a/src/plugins/subversion/subversionplugin.h b/src/plugins/subversion/subversionplugin.h
index 6dfe5e44d7..b10c489b6e 100644
--- a/src/plugins/subversion/subversionplugin.h
+++ b/src/plugins/subversion/subversionplugin.h
@@ -98,8 +98,8 @@ public:
bool vcsDelete(const QString &workingDir, const QString &fileName);
bool vcsMove(const QString &workingDir, const QString &from, const QString &to);
bool managesDirectory(const QString &directory, QString *topLevel = 0) const;
- virtual bool vcsCheckout(const QString &directory, const QByteArray &url);
- virtual QString vcsGetRepositoryURL(const QString &directory);
+ bool vcsCheckout(const QString &directory, const QByteArray &url);
+ QString vcsGetRepositoryURL(const QString &directory);
static SubversionPlugin *instance();
@@ -136,10 +136,15 @@ private slots:
void diffRepository();
void statusRepository();
void updateRepository();
+#ifdef WITH_TESTS
+ void testDiffFileResolving_data();
+ void testDiffFileResolving();
+ void testLogResolving();
+#endif
protected:
- virtual void updateActions(VcsBase::VcsBasePlugin::ActionState);
- virtual bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
+ void updateActions(VcsBase::VcsBasePlugin::ActionState);
+ bool submitEditorAboutToClose(VcsBase::VcsBaseSubmitEditor *submitEditor);
private:
inline bool isCommitEditorOpen() const;
diff --git a/src/plugins/subversion/subversionsettings.cpp b/src/plugins/subversion/subversionsettings.cpp
index 1af26dc321..dc963e7c41 100644
--- a/src/plugins/subversion/subversionsettings.cpp
+++ b/src/plugins/subversion/subversionsettings.cpp
@@ -30,6 +30,7 @@
#include "subversionsettings.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <QSettings>
@@ -48,12 +49,7 @@ enum { defaultTimeOutS = 30, defaultLogCount = 1000 };
static QString defaultCommand()
{
- QString rc;
- rc = QLatin1String("svn");
-#if defined(Q_OS_WIN32)
- rc.append(QLatin1String(".exe"));
-#endif
- return rc;
+ return QLatin1String("svn" QTC_HOST_EXE_SUFFIX);
}
using namespace Subversion::Internal;
diff --git a/src/plugins/subversion/subversionsubmiteditor.cpp b/src/plugins/subversion/subversionsubmiteditor.cpp
index 11e30f457c..14c2961021 100644
--- a/src/plugins/subversion/subversionsubmiteditor.cpp
+++ b/src/plugins/subversion/subversionsubmiteditor.cpp
@@ -30,14 +30,14 @@
#include "subversionsubmiteditor.h"
-#include <utils/submiteditorwidget.h>
+#include <vcsbase/submiteditorwidget.h>
#include <vcsbase/submitfilemodel.h>
using namespace Subversion::Internal;
SubversionSubmitEditor::SubversionSubmitEditor(const VcsBase::VcsBaseSubmitEditorParameters *parameters,
QWidget *parentWidget) :
- VcsBase::VcsBaseSubmitEditor(parameters, new Utils::SubmitEditorWidget(parentWidget))
+ VcsBase::VcsBaseSubmitEditor(parameters, new VcsBase::SubmitEditorWidget(parentWidget))
{
setDisplayName(tr("Subversion Submit"));
setDescriptionMandatory(false);
@@ -50,7 +50,7 @@ void SubversionSubmitEditor::setStatusList(const QList<StatusFilePair> &statusOu
const ConstIterator cend = statusOutput.constEnd();
for (ConstIterator it = statusOutput.constBegin(); it != cend; ++it)
- model->addFile(it->second, it->first, true);
+ model->addFile(it->second, it->first);
// Hack to allow completion in "description" field : completion needs a root repository, the
// checkScriptWorkingDirectory property is fine (at this point it was set by SubversionPlugin)
setFileModel(model, this->checkScriptWorkingDirectory());
diff --git a/src/plugins/tasklist/taskfilefactory.cpp b/src/plugins/tasklist/taskfilefactory.cpp
index 466c22ef0c..7fc761f040 100644
--- a/src/plugins/tasklist/taskfilefactory.cpp
+++ b/src/plugins/tasklist/taskfilefactory.cpp
@@ -59,7 +59,7 @@ QStringList TaskFileFactory::mimeTypes() const
Core::Id TaskFileFactory::id() const
{
- return "ProjectExplorer.TaskFileFactory";
+ return Core::Id("ProjectExplorer.TaskFileFactory");
}
QString TaskFileFactory::displayName() const
diff --git a/src/plugins/tasklist/tasklist.qbs b/src/plugins/tasklist/tasklist.qbs
index 8dc99abeae..4b3b8a7b45 100644
--- a/src/plugins/tasklist/tasklist.qbs
+++ b/src/plugins/tasklist/tasklist.qbs
@@ -12,26 +12,18 @@ QtcPlugin {
Depends { name: "Locator" }
Depends { name: "TextEditor" }
- Depends { name: "cpp" }
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
- "tasklistplugin.h",
- "tasklist_export.h",
- "tasklistconstants.h",
- "stopmonitoringhandler.h",
- "taskfile.h",
- "taskfilefactory.h",
- "tasklistplugin.cpp",
+ "TaskList.mimetypes.xml",
"stopmonitoringhandler.cpp",
+ "stopmonitoringhandler.h",
"taskfile.cpp",
+ "taskfile.h",
"taskfilefactory.cpp",
+ "taskfilefactory.h",
"tasklist.qrc",
- "TaskList.mimetypes.xml"
+ "tasklist_export.h",
+ "tasklistconstants.h",
+ "tasklistplugin.cpp",
+ "tasklistplugin.h",
]
}
-
diff --git a/src/plugins/tasklist/tasklistplugin.cpp b/src/plugins/tasklist/tasklistplugin.cpp
index f84c33452b..18ed2c3068 100644
--- a/src/plugins/tasklist/tasklistplugin.cpp
+++ b/src/plugins/tasklist/tasklistplugin.cpp
@@ -112,7 +112,7 @@ public:
file = QDir::fromNativeSeparators(file);
QFileInfo fi(file);
if (fi.isRelative() && context) {
- QString fullPath = context->projectDirectory() + '/' + file;
+ QString fullPath = context->projectDirectory() + QLatin1Char('/') + file;
fi.setFile(fullPath);
file = fi.absoluteFilePath();
}
@@ -130,29 +130,29 @@ public:
{
QStringList result;
QString line = QString::fromUtf8(raw.constData());
- if (line.startsWith(QChar('#')))
+ if (line.startsWith(QLatin1Char('#')))
return result;
- return line.split(QChar('\t'));
+ return line.split(QLatin1Char('\t'));
}
QString unescape(const QString &input) const
{
QString result;
for (int i = 0; i < input.count(); ++i) {
- if (input.at(i) == QChar('\\')) {
+ if (input.at(i) == QLatin1Char('\\')) {
if (i == input.count() - 1)
continue;
- if (input.at(i + 1) == QChar('n')) {
- result.append(QChar('\n'));
+ if (input.at(i + 1) == QLatin1Char('n')) {
+ result.append(QLatin1Char('\n'));
++i;
continue;
- } else if (input.at(i + 1) == QChar('t')) {
- result.append(QChar('\t'));
+ } else if (input.at(i + 1) == QLatin1Char('t')) {
+ result.append(QLatin1Char('\t'));
++i;
continue;
- } else if (input.at(i + 1) == QChar('\\')) {
- result.append(QChar('\\'));
+ } else if (input.at(i + 1) == QLatin1Char('\\')) {
+ result.append(QLatin1Char('\\'));
++i;
continue;
}
diff --git a/src/plugins/texteditor/basefilefind.cpp b/src/plugins/texteditor/basefilefind.cpp
index a8cbcfe6ea..0fcc66d960 100644
--- a/src/plugins/texteditor/basefilefind.cpp
+++ b/src/plugins/texteditor/basefilefind.cpp
@@ -104,9 +104,8 @@ QStringList BaseFileFind::fileNameFilters() const
const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
foreach (const QString &part, parts) {
const QString filter = part.trimmed();
- if (!filter.isEmpty()) {
+ if (!filter.isEmpty())
filters << filter;
- }
}
}
return filters;
@@ -131,8 +130,8 @@ void BaseFileFind::runNewSearch(const QString &txt, Find::FindFlags findFlags,
search->setUserData(qVariantFromValue(parameters));
connect(search, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
if (searchMode == SearchResultWindow::SearchAndReplace) {
- connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
- this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
+ connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>,bool)),
+ this, SLOT(doReplace(QString,QList<Find::SearchResultItem>,bool)));
}
connect(search, SIGNAL(visibilityChanged(bool)), this, SLOT(hideHighlightAll(bool)));
connect(search, SIGNAL(cancelled()), this, SLOT(cancel()));
@@ -183,9 +182,10 @@ void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
}
void BaseFileFind::doReplace(const QString &text,
- const QList<Find::SearchResultItem> &items)
+ const QList<Find::SearchResultItem> &items,
+ bool preserveCase)
{
- QStringList files = replaceAll(text, items);
+ QStringList files = replaceAll(text, items, preserveCase);
if (!files.isEmpty()) {
Core::DocumentManager::notifyFilesChangedInternally(files);
Find::SearchResultWindow::instance()->hide();
@@ -279,11 +279,10 @@ void BaseFileFind::updateComboEntries(QComboBox *combo, bool onTop)
{
int index = combo->findText(combo->currentText());
if (index < 0) {
- if (onTop) {
+ if (onTop)
combo->insertItem(0, combo->currentText());
- } else {
+ else
combo->addItem(combo->currentText());
- }
combo->setCurrentIndex(combo->findText(combo->currentText()));
}
}
@@ -331,7 +330,8 @@ void BaseFileFind::searchAgain()
}
QStringList BaseFileFind::replaceAll(const QString &text,
- const QList<Find::SearchResultItem> &items)
+ const QList<Find::SearchResultItem> &items,
+ bool preserveCase)
{
if (items.isEmpty())
return QStringList();
@@ -358,10 +358,15 @@ QStringList BaseFileFind::replaceAll(const QString &text,
processed.insert(p);
QString replacement;
- if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty())
+ if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
- else
+ } else if (preserveCase) {
+ const QString originalText = (item.textMarkLength == 0) ? item.text
+ : item.text.mid(item.textMarkPos, item.textMarkLength);
+ replacement = Utils::matchCaseReplacement(originalText, text);
+ } else {
replacement = text;
+ }
const int start = file->position(item.lineNumber, item.textMarkPos + 1);
const int end = file->position(item.lineNumber,
diff --git a/src/plugins/texteditor/basefilefind.h b/src/plugins/texteditor/basefilefind.h
index 631d62efa1..5780eb3094 100644
--- a/src/plugins/texteditor/basefilefind.h
+++ b/src/plugins/texteditor/basefilefind.h
@@ -71,7 +71,8 @@ public:
/* returns the list of unique files that were passed in items */
static QStringList replaceAll(const QString &txt,
- const QList<Find::SearchResultItem> &items);
+ const QList<Find::SearchResultItem> &items,
+ bool preserveCase = false);
protected:
virtual Utils::FileIterator *files(const QStringList &nameFilters,
@@ -95,7 +96,8 @@ private slots:
void setPaused(bool paused);
void openEditor(const Find::SearchResultItem &item);
void doReplace(const QString &txt,
- const QList<Find::SearchResultItem> &items);
+ const QList<Find::SearchResultItem> &items,
+ bool preserveCase);
void hideHighlightAll(bool visible);
void searchAgain();
diff --git a/src/plugins/texteditor/basehoverhandler.cpp b/src/plugins/texteditor/basehoverhandler.cpp
index 999c0297bb..b583e7cd55 100644
--- a/src/plugins/texteditor/basehoverhandler.cpp
+++ b/src/plugins/texteditor/basehoverhandler.cpp
@@ -31,14 +31,14 @@
#include "itexteditor.h"
#include "basetexteditor.h"
#include "displaysettings.h"
-#include "tooltip.h"
-#include "tipcontents.h"
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/id.h>
#include <debugger/debuggerconstants.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <QPoint>
@@ -89,7 +89,7 @@ void BaseHoverHandler::updateContextHelpId(TextEditor::ITextEditor *editor, int
// If the tooltip is visible and there is a help match, this match is used to update
// the help id. Otherwise, let the identification process happen.
- if (!ToolTip::instance()->isVisible() || !lastHelpItemIdentified().isValid())
+ if (!Utils::ToolTip::instance()->isVisible() || !lastHelpItemIdentified().isValid())
process(editor, pos);
if (lastHelpItemIdentified().isValid())
@@ -162,9 +162,9 @@ void BaseHoverHandler::decorateToolTip()
void BaseHoverHandler::operateTooltip(ITextEditor *editor, const QPoint &point)
{
if (m_toolTip.isEmpty())
- ToolTip::instance()->hide();
+ Utils::ToolTip::instance()->hide();
else
- ToolTip::instance()->show(point, TextContent(m_toolTip), editor->widget());
+ Utils::ToolTip::instance()->show(point, Utils::TextContent(m_toolTip), editor->widget());
}
BaseTextEditorWidget *BaseHoverHandler::baseTextEditor(ITextEditor *editor)
diff --git a/src/plugins/texteditor/basetextdocument.cpp b/src/plugins/texteditor/basetextdocument.cpp
index 019227e0b0..5a8603271d 100644
--- a/src/plugins/texteditor/basetextdocument.cpp
+++ b/src/plugins/texteditor/basetextdocument.cpp
@@ -38,15 +38,16 @@
#include "syntaxhighlighter.h"
#include "texteditorconstants.h"
-#include <QStringList>
-#include <QFile>
+#include <QApplication>
#include <QDir>
+#include <QFile>
#include <QFileInfo>
-#include <QTextStream>
-#include <QTextCodec>
#include <QFutureInterface>
+#include <QScrollBar>
+#include <QStringList>
#include <QSyntaxHighlighter>
-#include <QApplication>
+#include <QTextCodec>
+#include <QTextStream>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/icore.h>
@@ -196,6 +197,12 @@ ITextMarkable *BaseTextDocument::documentMarker() const
return documentLayout->markableInterface();
}
+/*!
+ * \brief Saves the document to the specified file.
+ * \param errorString output parameter, contains error reason.
+ * \param autoSave signalise that this function was called by the automatic save routine.
+ * If autosave is true, the cursor will be restored and some signals suppressed.
+ */
bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool autoSave)
{
QTextCursor cursor(d->m_document);
@@ -204,9 +211,12 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
BaseTextEditorWidget *editorWidget = 0;
int savedPosition = 0;
int savedAnchor = 0;
+ int savedVScrollBarValue = 0;
+ int savedHScrollBarValue = 0;
int undos = d->m_document->availableUndoSteps();
- // When saving the current editor, make sure to maintain the cursor position for undo
+ // When saving the current editor, make sure to maintain the cursor and scroll bar
+ // positions for undo
Core::IEditor *currentEditor = Core::EditorManager::currentEditor();
if (BaseTextEditor *editable = qobject_cast<BaseTextEditor*>(currentEditor)) {
if (editable->document() == this) {
@@ -214,6 +224,8 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
QTextCursor cur = editorWidget->textCursor();
savedPosition = cur.position();
savedAnchor = cur.anchor();
+ savedVScrollBarValue = editorWidget->verticalScrollBar()->value();
+ savedHScrollBarValue = editorWidget->horizontalScrollBar()->value();
cursor.setPosition(cur.position());
}
}
@@ -231,8 +243,9 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
if (!fileName.isEmpty())
fName = fileName;
+ // check if UTF8-BOM has to be added or removed
Utils::TextFileFormat saveFormat = format();
- if (saveFormat.codec->name() == "UTF-8") {
+ if (saveFormat.codec->name() == "UTF-8" && supportsUtf8Bom()) {
switch (d->m_extraEncodingSettings.m_utf8BomSetting) {
case TextEditor::ExtraEncodingSettings::AlwaysAdd:
saveFormat.hasUtf8Bom = true;
@@ -243,16 +256,19 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
saveFormat.hasUtf8Bom = false;
break;
}
- } // "UTF-8"
+ }
const bool ok = write(fName, saveFormat, d->m_document->toPlainText(), errorString);
+ // restore text cursor and scroll bar positions
if (autoSave && undos < d->m_document->availableUndoSteps()) {
d->m_document->undo();
if (editorWidget) {
QTextCursor cur = editorWidget->textCursor();
cur.setPosition(savedAnchor);
cur.setPosition(savedPosition, QTextCursor::KeepAnchor);
+ editorWidget->verticalScrollBar()->setValue(savedVScrollBarValue);
+ editorWidget->horizontalScrollBar()->setValue(savedHScrollBarValue);
editorWidget->setTextCursor(cur);
}
}
@@ -263,6 +279,7 @@ bool BaseTextDocument::save(QString *errorString, const QString &fileName, bool
if (autoSave)
return true;
+ // inform about the new filename
const QFileInfo fi(fName);
const QString oldFileName = d->m_fileName;
d->m_fileName = QDir::cleanPath(fi.absoluteFilePath());
diff --git a/src/plugins/texteditor/basetextdocumentlayout.cpp b/src/plugins/texteditor/basetextdocumentlayout.cpp
index 60f5c409d6..263c78eb1a 100644
--- a/src/plugins/texteditor/basetextdocumentlayout.cpp
+++ b/src/plugins/texteditor/basetextdocumentlayout.cpp
@@ -29,6 +29,7 @@
#include "basetextdocumentlayout.h"
#include <utils/qtcassert.h>
+#include <QDebug>
using namespace TextEditor;
@@ -52,8 +53,6 @@ public:
void removeMarkFromMarksCache(TextEditor::ITextMark *mark);
private:
- double recalculateMaxMarkWidthFactor() const;
-
TextMarks m_marksCache; // not owned
QTextDocument *document;
};
@@ -86,24 +85,23 @@ bool DocumentMarker::addMark(TextEditor::ITextMark *mark)
mark->updateLineNumber(blockNumber + 1);
QTC_CHECK(mark->lineNumber() == blockNumber + 1); // Checks that the base class is called
mark->updateBlock(block);
- documentLayout->hasMarks = true;
- documentLayout->maxMarkWidthFactor = qMax(mark->widthFactor(),
- documentLayout->maxMarkWidthFactor);
- documentLayout->requestUpdate();
mark->setMarkableInterface(this);
+ if (!mark->isVisible())
+ return true;
+ // Update document layout
+ double newMaxWidthFactor = qMax(mark->widthFactor(), documentLayout->maxMarkWidthFactor);
+ bool fullUpdate = newMaxWidthFactor > documentLayout->maxMarkWidthFactor || !documentLayout->hasMarks;
+ documentLayout->hasMarks = true;
+ documentLayout->maxMarkWidthFactor = newMaxWidthFactor;
+ if (fullUpdate)
+ documentLayout->requestUpdate();
+ else
+ documentLayout->requestExtraAreaUpdate();
return true;
}
return false;
}
-double DocumentMarker::recalculateMaxMarkWidthFactor() const
-{
- double maxWidthFactor = 1.0;
- foreach (const ITextMark *mark, marks())
- maxWidthFactor = qMax(mark->widthFactor(), maxWidthFactor);
- return maxWidthFactor;
-}
-
TextEditor::TextMarks DocumentMarker::marksAt(int line) const
{
QTC_ASSERT(line >= 1, return TextMarks());
@@ -122,31 +120,50 @@ void DocumentMarker::removeMarkFromMarksCache(TextEditor::ITextMark *mark)
BaseTextDocumentLayout *documentLayout =
qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
QTC_ASSERT(documentLayout, return);
- bool needUpdate = m_marksCache.removeOne(mark);
+ m_marksCache.removeAll(mark);
+
if (m_marksCache.isEmpty()) {
documentLayout->hasMarks = false;
- needUpdate = true;
+ documentLayout->maxMarkWidthFactor = 1.0;
+ documentLayout->requestUpdate();
+ return;
}
- if (needUpdate) {
- documentLayout->maxMarkWidthFactor = recalculateMaxMarkWidthFactor();
- updateMark(0);
+ if (!mark->isVisible())
+ return;
+
+ if (documentLayout->maxMarkWidthFactor == 1.0
+ || mark->widthFactor() == 1.0
+ || mark->widthFactor() < documentLayout->maxMarkWidthFactor) {
+ // No change in width possible
+ documentLayout->requestExtraAreaUpdate();
+ } else {
+ double maxWidthFactor = 1.0;
+ foreach (const ITextMark *mark, marks()) {
+ if (!mark->isVisible())
+ continue;
+ maxWidthFactor = qMax(mark->widthFactor(), maxWidthFactor);
+ if (maxWidthFactor == documentLayout->maxMarkWidthFactor)
+ break; // Still a mark with the maxMarkWidthFactor
+ }
+
+ if (maxWidthFactor != documentLayout->maxMarkWidthFactor) {
+ documentLayout->maxMarkWidthFactor = maxWidthFactor;
+ documentLayout->requestUpdate();
+ } else {
+ documentLayout->requestExtraAreaUpdate();
+ }
}
}
void DocumentMarker::removeMark(TextEditor::ITextMark *mark)
{
- BaseTextDocumentLayout *documentLayout =
- qobject_cast<BaseTextDocumentLayout*>(document->documentLayout());
- QTC_ASSERT(documentLayout, return);
-
- QTextBlock block = document->begin();
- while (block.isValid()) {
- if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
- data->removeMark(mark);
- }
- block = block.next();
+ QTextBlock block = document->findBlockByNumber(mark->lineNumber() - 1);
+ if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
+ if (!data->removeMark(mark))
+ qDebug() << "Could not find mark" << mark << "on line" << mark->lineNumber();
}
+
removeMarkFromMarksCache(mark);
mark->setMarkableInterface(0);
}
@@ -169,9 +186,7 @@ CodeFormatterData::~CodeFormatterData()
TextBlockUserData::~TextBlockUserData()
{
- TextMarks marks = m_marks;
- m_marks.clear();
- foreach (ITextMark *mrk, marks) {
+ foreach (ITextMark *mrk, m_marks) {
TextEditor::Internal::DocumentMarker *documentMarker
= static_cast<TextEditor::Internal::DocumentMarker *>(mrk->markableInterface());
documentMarker->removeMarkFromMarksCache(mrk);
@@ -375,15 +390,13 @@ bool TextBlockUserData::findPreviousBlockOpenParenthesis(QTextCursor *cursor, bo
for (int i = parenList.count()-1; i >= 0; --i) {
Parenthesis paren = parenList.at(i);
if (paren.chr != QLatin1Char('{') && paren.chr != QLatin1Char('}')
- && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-')
- && paren.chr != QLatin1Char('[') && paren.chr != QLatin1Char(']'))
+ && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-'))
continue;
if (block == cursor->block()) {
if (position - block.position() <= paren.pos + (paren.type == Parenthesis::Closed ? 1 : 0))
continue;
- if (checkStartPosition && paren.type == Parenthesis::Opened && paren.pos== cursor->position()) {
+ if (checkStartPosition && paren.type == Parenthesis::Opened && paren.pos== cursor->position())
return true;
- }
}
if (paren.type == Parenthesis::Closed) {
++ignore;
@@ -439,8 +452,7 @@ bool TextBlockUserData::findNextBlockClosingParenthesis(QTextCursor *cursor)
for (int i = 0; i < parenList.count(); ++i) {
Parenthesis paren = parenList.at(i);
if (paren.chr != QLatin1Char('{') && paren.chr != QLatin1Char('}')
- && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-')
- && paren.chr != QLatin1Char('[') && paren.chr != QLatin1Char(']'))
+ && paren.chr != QLatin1Char('+') && paren.chr != QLatin1Char('-'))
continue;
if (block == cursor->block() &&
(position - block.position() > paren.pos - (paren.type == Parenthesis::Opened ? 1 : 0)))
@@ -674,6 +686,11 @@ void BaseTextDocumentLayout::setFolded(const QTextBlock &block, bool folded)
}
}
+void BaseTextDocumentLayout::requestExtraAreaUpdate()
+{
+ emit updateExtraArea();
+}
+
ITextMarkable *BaseTextDocumentLayout::markableInterface()
{
return m_documentMarker;
@@ -747,6 +764,7 @@ void BaseTextDocumentLayout::documentReloaded(TextMarks marks)
= static_cast<TextEditor::Internal::DocumentMarker *>(m_documentMarker);
documentMarker->removeMarkFromMarksCache(mark);
mark->removedFromEditor();
+ mark->setMarkableInterface(0);
}
}
requestUpdate();
diff --git a/src/plugins/texteditor/basetextdocumentlayout.h b/src/plugins/texteditor/basetextdocumentlayout.h
index 07edcfc1d0..6fc22276d0 100644
--- a/src/plugins/texteditor/basetextdocumentlayout.h
+++ b/src/plugins/texteditor/basetextdocumentlayout.h
@@ -202,6 +202,7 @@ public:
return data;
}
+ void requestExtraAreaUpdate();
void emitDocumentSizeChanged() { emit documentSizeChanged(documentSize()); }
ITextMarkable *markableInterface();
@@ -221,6 +222,9 @@ public:
void documentReloaded(TextMarks marks);
void updateMarksLineNumber();
void updateMarksBlock(const QTextBlock &block);
+
+signals:
+ void updateExtraArea();
};
} // namespace TextEditor
diff --git a/src/plugins/texteditor/basetexteditor.cpp b/src/plugins/texteditor/basetexteditor.cpp
index 04448d36ce..ce107f880c 100644
--- a/src/plugins/texteditor/basetexteditor.cpp
+++ b/src/plugins/texteditor/basetexteditor.cpp
@@ -41,8 +41,6 @@
#include "texteditorconstants.h"
#include "texteditorplugin.h"
#include "syntaxhighlighter.h"
-#include "tooltip.h"
-#include "tipcontents.h"
#include "indenter.h"
#include "autocompleter.h"
#include "snippet.h"
@@ -67,8 +65,11 @@
#include <extensionsystem/pluginmanager.h>
#include <find/basetextfind.h>
#include <utils/linecolumnlabel.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <utils/stylehelper.h>
+#include <utils/tooltip/tooltip.h>
+#include <utils/tooltip/tipcontents.h>
#include <QCoreApplication>
#include <QTextCodec>
@@ -116,6 +117,7 @@
using namespace TextEditor;
using namespace TextEditor::Internal;
+using namespace Utils;
namespace TextEditor {
namespace Internal {
@@ -179,10 +181,20 @@ Core::IEditor *BaseTextEditorWidget::openEditorAt(const QString &fileName, int l
return editor;
}
-static void convertToPlainText(QString &txt)
+QString BaseTextEditorWidget::plainTextFromSelection() const
{
- QChar *uc = txt.data();
- QChar *e = uc + txt.size();
+ QTextCursor cursor = textCursor();
+
+ // Copy the selected text as plain text
+ QString text = cursor.selectedText();
+ return convertToPlainText(text);
+}
+
+QString BaseTextEditorWidget::convertToPlainText(const QString &txt)
+{
+ QString ret = txt;
+ QChar *uc = ret.data();
+ QChar *e = uc + ret.size();
for (; uc != e; ++uc) {
switch (uc->unicode()) {
@@ -199,6 +211,7 @@ static void convertToPlainText(QString &txt)
;
}
}
+ return ret;
}
static const char kTextBlockMimeType[] = "application/vnd.nokia.qtcreator.blocktext";
@@ -252,7 +265,7 @@ BaseTextEditorWidget::BaseTextEditorWidget(QWidget *parent)
// parentheses matcher
d->m_formatRange = true;
d->m_matchFormat.setForeground(Qt::red);
- d->m_rangeFormat.setBackground(QColor(0xb4, 0xee, 0xb4));
+ d->m_matchFormat.setBackground(QColor(0xb4, 0xee, 0xb4));
d->m_mismatchFormat.setBackground(Qt::magenta);
d->m_parenthesesMatchingTimer = new QTimer(this);
d->m_parenthesesMatchingTimer->setSingleShot(true);
@@ -299,9 +312,8 @@ void BaseTextEditorWidget::print(QPrinter *printer)
printer->setFullPage(true);
QPrintDialog *dlg = new QPrintDialog(printer, this);
dlg->setWindowTitle(tr("Print Document"));
- if (dlg->exec() == QDialog::Accepted) {
+ if (dlg->exec() == QDialog::Accepted)
d->print(printer);
- }
printer->setFullPage(oldFullPage);
delete dlg;
}
@@ -524,7 +536,7 @@ BaseTextEditor *BaseTextEditorWidget::editor() const
void BaseTextEditorWidget::selectEncoding()
{
- BaseTextDocument *doc = d->m_document;
+ BaseTextDocument *doc = d->m_document.data();
CodecSelector codecSelector(this, doc);
switch (codecSelector.exec()) {
@@ -566,14 +578,13 @@ void BaseTextEditorWidget::updateCannotDecodeInfo()
{
setReadOnly(d->m_document->hasDecodingError());
if (d->m_document->hasDecodingError()) {
- Core::InfoBarEntry info(
- QLatin1String(Constants::SELECT_ENCODING),
+ Core::InfoBarEntry info(Core::Id(Constants::SELECT_ENCODING),
tr("<b>Error:</b> Could not decode \"%1\" with \"%2\"-encoding. Editing not possible.")
.arg(displayName()).arg(QString::fromLatin1(d->m_document->codec()->name())));
info.setCustomButtonInfo(tr("Select Encoding"), this, SLOT(selectEncoding()));
d->m_document->infoBar()->addInfo(info);
} else {
- d->m_document->infoBar()->removeInfo(QLatin1String(Constants::SELECT_ENCODING));
+ d->m_document->infoBar()->removeInfo(Core::Id(Constants::SELECT_ENCODING));
}
}
@@ -655,7 +666,7 @@ void BaseTextEditorWidget::setChangeSet(const Utils::ChangeSet &changeSet)
Core::IDocument *BaseTextEditorWidget::editorDocument() const
{
- return d->m_document;
+ return d->m_document.data();
}
void BaseTextEditorWidget::editorContentsChange(int position, int charsRemoved, int charsAdded)
@@ -1014,9 +1025,11 @@ void BaseTextEditorWidget::insertLineAbove()
{
QTextCursor cursor = textCursor();
cursor.beginEditBlock();
- cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor);
- cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::MoveAnchor);
+ // If the cursor is at the beginning of the document,
+ // it should still insert a line above the current line.
+ cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::MoveAnchor);
cursor.insertBlock();
+ cursor.movePosition(QTextCursor::PreviousBlock, QTextCursor::MoveAnchor);
indent(document(), cursor, QChar::Null);
cursor.endEditBlock();
setTextCursor(cursor);
@@ -1066,7 +1079,35 @@ void BaseTextEditorWidget::unindent()
void BaseTextEditorWidget::openLinkUnderCursor()
{
- openLink(findLinkAt(textCursor()));
+ Core::EditorManager* editorManager = Core::EditorManager::instance();
+ Link symbolLink = findLinkAt(textCursor());
+
+ if (!openLinksInNextSplit() || !editorManager->hasSplitter()) {
+ openLink(symbolLink);
+ return;
+ }
+
+ Core::IEditor *editor = Core::EditorManager::currentEditor();
+
+ if (forceOpenLinksInNextSplit()) {
+ editorManager->gotoOtherSplit();
+ } else {
+ bool isVisible = false;
+ foreach (Core::IEditor *visEditor, editorManager->visibleEditors()) {
+ if (visEditor->document() &&
+ (symbolLink.fileName == visEditor->document()->fileName()) &&
+ (visEditor != editor)) {
+ isVisible = true;
+ editorManager->activateEditor(visEditor);
+ break;
+ }
+ }
+
+ if (!isVisible)
+ editorManager->gotoOtherSplit();
+ }
+ openLink(symbolLink);
+ editorManager->activateEditor(editor);
}
void BaseTextEditorWidget::moveLineUpDown(bool up)
@@ -1136,8 +1177,10 @@ void BaseTextEditorWidget::moveLineUpDown(bool up)
int end = move.position();
if (hasSelection) {
+ move.setPosition(end);
+ move.setPosition(start, QTextCursor::KeepAnchor);
+ } else {
move.setPosition(start);
- move.setPosition(end, QTextCursor::KeepAnchor);
}
//update positions of affectedMarkers
@@ -1408,12 +1451,10 @@ bool BaseTextEditorWidget::cursorMoveKeyEvent(QKeyEvent *e)
QTextCursor::MoveMode mode = QTextCursor::MoveAnchor;
QTextCursor::MoveOperation op = QTextCursor::NoMove;
- if (e == QKeySequence::MoveToNextChar) {
+ if (e == QKeySequence::MoveToNextChar)
op = QTextCursor::Right;
- }
- else if (e == QKeySequence::MoveToPreviousChar) {
+ else if (e == QKeySequence::MoveToPreviousChar)
op = QTextCursor::Left;
- }
else if (e == QKeySequence::SelectNextChar) {
op = QTextCursor::Right;
mode = QTextCursor::KeepAnchor;
@@ -1521,13 +1562,12 @@ bool BaseTextEditorWidget::cursorMoveKeyEvent(QKeyEvent *e)
bool visualNavigation = cursor.visualNavigation();
cursor.setVisualNavigation(true);
- if (camelCaseNavigationEnabled() && op == QTextCursor::WordRight) {
+ if (camelCaseNavigationEnabled() && op == QTextCursor::WordRight)
camelCaseRight(cursor, mode);
- } else if (camelCaseNavigationEnabled() && op == QTextCursor::WordLeft) {
+ else if (camelCaseNavigationEnabled() && op == QTextCursor::WordLeft)
camelCaseLeft(cursor, mode);
- } else if (!cursor.movePosition(op, mode) && mode == QTextCursor::MoveAnchor) {
+ else if (!cursor.movePosition(op, mode) && mode == QTextCursor::MoveAnchor)
cursor.clearSelection();
- }
cursor.setVisualNavigation(visualNavigation);
setTextCursor(cursor);
@@ -1761,7 +1801,8 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
// fall through
case Qt::Key_Right:
case Qt::Key_Left:
-#ifndef Q_OS_MAC
+ if (HostOsInfo::isMacHost())
+ break;
if ((e->modifiers()
& (Qt::AltModifier | Qt::ShiftModifier)) == (Qt::AltModifier | Qt::ShiftModifier)) {
int diff_row = 0;
@@ -1785,7 +1826,6 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
viewport()->update();
}
}
-#endif
break;
case Qt::Key_PageUp:
case Qt::Key_PageDown:
@@ -1829,13 +1869,8 @@ void BaseTextEditorWidget::keyPressEvent(QKeyEvent *e)
}
}
- if (e->key() == Qt::Key_H && e->modifiers() ==
-#ifdef Q_OS_DARWIN
- Qt::MetaModifier
-#else
- Qt::ControlModifier
-#endif
- ) {
+ if (e->key() == Qt::Key_H
+ && e->modifiers() == Qt::KeyboardModifiers(HostOsInfo::controlModifier())) {
universalHelper();
e->accept();
return;
@@ -1970,11 +2005,10 @@ void BaseTextEditorWidget::insertCodeSnippet(const QTextCursor &cursor_arg, cons
int cursorPosition = cursor.position();
cursor.insertText(textToInsert);
- if (textToInsert.isEmpty()) {
+ if (textToInsert.isEmpty())
positions.insert(cursorPosition, 0);
- } else {
+ else
positions.insert(cursorPosition, textToInsert.length());
- }
++pos;
}
@@ -2143,15 +2177,15 @@ void BaseTextEditorWidget::setDisplayName(const QString &title)
emit changed();
}
-BaseTextDocument *BaseTextEditorWidget::baseTextDocument() const
+QSharedPointer<BaseTextDocument> BaseTextEditorWidget::baseTextDocument() const
{
return d->m_document;
}
-void BaseTextEditorWidget::setBaseTextDocument(BaseTextDocument *doc)
+void BaseTextEditorWidget::setBaseTextDocument(const QSharedPointer<BaseTextDocument> &doc)
{
- if (doc) {
+ if (!doc.isNull()) {
d->setupDocumentSignals(doc);
d->m_document = doc;
}
@@ -2233,7 +2267,7 @@ bool BaseTextEditorWidget::restoreState(const QByteArray &state)
stream >> collapsedBlocks;
QTextDocument *doc = document();
bool layoutChanged = false;
- foreach(int blockNumber, collapsedBlocks) {
+ foreach (int blockNumber, collapsedBlocks) {
QTextBlock block = doc->findBlockByNumber(qMax(0, blockNumber));
if (block.isValid()) {
BaseTextDocumentLayout::doFoldOrUnfold(block, false);
@@ -2302,6 +2336,26 @@ bool BaseTextEditorWidget::lineNumbersVisible() const
return d->m_lineNumbersVisible;
}
+void BaseTextEditorWidget::setOpenLinksInNextSplit(bool b)
+{
+ d->m_displaySettings.m_openLinksInNextSplit = b;
+}
+
+bool BaseTextEditorWidget::openLinksInNextSplit() const
+{
+ return d->m_displaySettings.m_openLinksInNextSplit;
+}
+
+void BaseTextEditorWidget::setForceOpenLinksInNextSplit(bool b)
+{
+ d->m_displaySettings.m_forceOpenLinksInNextSplit = b;
+}
+
+bool BaseTextEditorWidget::forceOpenLinksInNextSplit() const
+{
+ return d->m_displaySettings.m_forceOpenLinksInNextSplit;
+}
+
void BaseTextEditorWidget::setMarksVisible(bool b)
{
d->m_marksVisible = b;
@@ -2500,6 +2554,7 @@ BaseTextEditorWidgetPrivate::BaseTextEditorWidgetPrivate()
m_codeAssistant(new CodeAssistant),
m_assistRelevantContentAdded(false),
m_cursorBlockNumber(-1),
+ m_markDragging(false),
m_autoCompleter(new AutoCompleter),
m_indenter(new Indenter),
m_clipboardAssistProvider(new Internal::ClipboardAssistProvider)
@@ -2510,12 +2565,12 @@ BaseTextEditorWidgetPrivate::~BaseTextEditorWidgetPrivate()
{
}
-void BaseTextEditorWidgetPrivate::setupDocumentSignals(BaseTextDocument *document)
+void BaseTextEditorWidgetPrivate::setupDocumentSignals(const QSharedPointer<BaseTextDocument> &document)
{
- BaseTextDocument *oldDocument = q->baseTextDocument();
- if (oldDocument) {
+ QSharedPointer<BaseTextDocument> oldDocument = q->baseTextDocument();
+ if (!oldDocument.isNull()) {
q->disconnect(oldDocument->document(), 0, q, 0);
- q->disconnect(oldDocument, 0, q, 0);
+ q->disconnect(oldDocument.data(), 0, q, 0);
}
QTextDocument *doc = document->document();
@@ -2535,14 +2590,15 @@ void BaseTextEditorWidgetPrivate::setupDocumentSignals(BaseTextDocument *documen
q->setCursorWidth(2); // Applies to the document layout
QObject::connect(documentLayout, SIGNAL(updateBlock(QTextBlock)), q, SLOT(slotUpdateBlockNotify(QTextBlock)));
+ QObject::connect(documentLayout, SIGNAL(updateExtraArea()), q, SLOT(slotUpdateExtraArea()));
QObject::connect(q, SIGNAL(requestBlockUpdate(QTextBlock)), documentLayout, SIGNAL(updateBlock(QTextBlock)));
QObject::connect(doc, SIGNAL(modificationChanged(bool)), q, SIGNAL(changed()));
QObject::connect(doc, SIGNAL(contentsChange(int,int,int)), q,
SLOT(editorContentsChange(int,int,int)), Qt::DirectConnection);
- QObject::connect(document, SIGNAL(changed()), q, SIGNAL(changed()));
- QObject::connect(document, SIGNAL(titleChanged(QString)), q, SLOT(setDisplayName(QString)));
- QObject::connect(document, SIGNAL(aboutToReload()), q, SLOT(documentAboutToBeReloaded()));
- QObject::connect(document, SIGNAL(reloaded()), q, SLOT(documentReloaded()));
+ QObject::connect(document.data(), SIGNAL(changed()), q, SIGNAL(changed()));
+ QObject::connect(document.data(), SIGNAL(titleChanged(QString)), q, SLOT(setDisplayName(QString)));
+ QObject::connect(document.data(), SIGNAL(aboutToReload()), q, SLOT(documentAboutToBeReloaded()));
+ QObject::connect(document.data(), SIGNAL(reloaded()), q, SLOT(documentReloaded()));
q->slotUpdateExtraAreaWidth();
}
@@ -2607,13 +2663,7 @@ void BaseTextEditorWidgetPrivate::snippetTabOrBacktab(bool forward)
QPoint BaseTextEditorWidget::toolTipPosition(const QTextCursor &c) const
{
const QPoint cursorPos = mapToGlobal(cursorRect(c).bottomRight() + QPoint(1,1));
- return cursorPos + QPoint(d->m_extraArea->width(),
-#ifdef Q_OS_WIN
- -24
-#else
- -16
-#endif
- );
+ return cursorPos + QPoint(d->m_extraArea->width(), HostOsInfo::isWindowsHost() ? -24 : -16);
}
void BaseTextEditorWidget::processTooltipRequest(const QTextCursor &c)
@@ -2819,11 +2869,10 @@ QString BaseTextEditorWidgetPrivate::copyBlockSelection()
if (endOffset < 0)
--endPos;
selection += text.mid(startPos, endPos - startPos);
- if (endOffset < 0) {
+ if (endOffset < 0)
selection += QString(ts.m_tabSize + endOffset, QLatin1Char(' '));
- } else if (endOffset > 0) {
+ else if (endOffset > 0)
selection += QString(endOffset, QLatin1Char(' '));
- }
}
if (block == lastBlock)
break;
@@ -3150,9 +3199,8 @@ void BaseTextEditorWidget::paintEvent(QPaintEvent *e)
QRectF rr = line.naturalTextRect();
rr.moveTop(rr.top() + r.top());
rr.setLeft(r.left() + x);
- if (line.lineNumber() == eline.lineNumber()) {
+ if (line.lineNumber() == eline.lineNumber())
rr.setRight(r.left() + ex);
- }
painter.fillRect(rr, d->m_searchScopeFormat.background());
QColor lineCol = d->m_searchScopeFormat.foreground().color();
@@ -3304,9 +3352,8 @@ void BaseTextEditorWidget::paintEvent(QPaintEvent *e)
QRectF rr = line.naturalTextRect();
rr.moveTop(rr.top() + r.top());
rr.setLeft(r.left() + x);
- if (line.lineNumber() == eline.lineNumber()) {
+ if (line.lineNumber() == eline.lineNumber())
rr.setRight(r.left() + ex);
- }
painter.fillRect(rr, palette().highlight());
if ((d->m_blockSelection.anchor == BaseTextBlockSelection::TopLeft
&& block == d->m_blockSelection.firstBlock.block())
@@ -3373,6 +3420,7 @@ void BaseTextEditorWidget::paintEvent(QPaintEvent *e)
o.start = relativePos;
o.length = 1;
o.format.setForeground(palette().base());
+ o.format.setBackground(palette().text());
selections.append(o);
}
}
@@ -3395,11 +3443,8 @@ void BaseTextEditorWidget::paintEvent(QPaintEvent *e)
cursor_pen = painter.pen();
}
-#ifndef Q_OS_MAC // no visible cursor on mac
- if (blockSelectionCursorRect.isValid())
+ if (!HostOsInfo::isMacHost() && blockSelectionCursorRect.isValid())
painter.fillRect(blockSelectionCursorRect, palette().text());
-#endif
-
}
offset.ry() += r.height();
@@ -3667,13 +3712,7 @@ int BaseTextEditorWidget::extraAreaWidth(int *markWidthPtr) const
fnt.setItalic(d->m_currentLineNumberFormat.font().italic());
const QFontMetrics linefm(fnt);
- int digits = 2;
- int max = qMax(1, blockCount());
- while (max >= 100) {
- max /= 10;
- ++digits;
- }
- space += linefm.width(QLatin1Char('9')) * digits;
+ space += linefm.width(QLatin1Char('9')) * lineNumberDigits();
}
int markWidth = 0;
@@ -3800,7 +3839,7 @@ void BaseTextEditorWidget::extraAreaPaintEvent(QPaintEvent *e)
int count = 0;
it = marks.constEnd() - 1;
while (it != marks.constBegin()) {
- if ((*it)->visible())
+ if ((*it)->isVisible())
++count;
if (count == 3)
break;
@@ -3810,7 +3849,7 @@ void BaseTextEditorWidget::extraAreaPaintEvent(QPaintEvent *e)
TextMarks::const_iterator end = marks.constEnd();
for ( ; it != end; ++it) {
ITextMark *mark = *it;
- if (!mark->visible())
+ if (!mark->isVisible())
continue;
const int height = fmLineSpacing - 1;
const int width = int(.5 + height * mark->widthFactor());
@@ -3884,7 +3923,7 @@ void BaseTextEditorWidget::extraAreaPaintEvent(QPaintEvent *e)
}
if (d->m_lineNumbersVisible) {
- const QString &number = QString::number(blockNumber + 1);
+ const QString &number = lineNumber(blockNumber);
bool selected = (
(selStart < block.position() + block.length()
@@ -3899,7 +3938,7 @@ void BaseTextEditorWidget::extraAreaPaintEvent(QPaintEvent *e)
painter.setFont(f);
painter.setPen(d->m_currentLineNumberFormat.foreground().color());
}
- painter.drawText(QRectF(markWidth, top, extraAreaWidth - markWidth - 4, height), Qt::AlignRight, number);
+ painter.drawText(QRectF(markWidth, top + lineNumberTopPositionOffset(blockNumber), extraAreaWidth - markWidth - 4, height), Qt::AlignRight, number);
if (selected)
painter.restore();
}
@@ -3984,11 +4023,10 @@ void BaseTextEditorWidget::slotModificationChanged(bool m)
if (oldLastSaveRevision != documentLayout->lastSaveRevision) {
QTextBlock block = doc->begin();
while (block.isValid()) {
- if (block.revision() < 0 || block.revision() != oldLastSaveRevision) {
+ if (block.revision() < 0 || block.revision() != oldLastSaveRevision)
block.setRevision(-documentLayout->lastSaveRevision - 1);
- } else {
+ else
block.setRevision(documentLayout->lastSaveRevision);
- }
block = block.next();
}
}
@@ -4074,7 +4112,13 @@ void BaseTextEditorWidget::updateHighlights()
&& d->m_animator == 0) {
d->m_parenthesesMatchingTimer->start(50);
} else {
- // use 0-timer, not direct call, to give the syntax highlighter a chance
+ // when we uncheck "highlight matching parentheses"
+ // we need clear current selection before viewport update
+ // otherwise we get sticky highlighted parentheses
+ if (!d->m_displaySettings.m_highlightMatchingParentheses)
+ setExtraSelections(ParenthesesMatchingSelection, QList<QTextEdit::ExtraSelection>());
+
+ // use 0-timer, not direct call, to give the syntax highlighter a chance
// to update the parentheses information
d->m_parenthesesMatchingTimer->start(0);
}
@@ -4122,6 +4166,11 @@ void BaseTextEditorWidget::slotUpdateBlockNotify(const QTextBlock &block)
blockRecursion = false;
}
+void BaseTextEditorWidget::slotUpdateExtraArea()
+{
+ d->m_extraArea->update();
+}
+
void BaseTextEditorWidget::timerEvent(QTimerEvent *e)
{
if (e->timerId() == d->autoScrollTimer.timerId()) {
@@ -4197,9 +4246,8 @@ void BaseTextEditorWidget::mouseMoveEvent(QMouseEvent *e)
// get visual column
int column = tabSettings().columnAt(cursor.block().text(), cursor.positionInBlock());
- if (cursor.positionInBlock() == cursor.block().length()-1) {
+ if (cursor.positionInBlock() == cursor.block().length()-1)
column += (e->pos().x() - cursorRect().center().x())/QFontMetricsF(font()).width(QLatin1Char(' '));
- }
d->m_blockSelection.moveAnchor(cursor.blockNumber(), column);
setTextCursor(d->m_blockSelection.selection(tabSettings()));
viewport()->update();
@@ -4252,10 +4300,8 @@ void BaseTextEditorWidget::mousePressEvent(QMouseEvent *e)
}
}
-#ifdef Q_OS_LINUX
- if (handleForwardBackwardMouseButtons(e))
+ if (HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(e))
return;
-#endif
QPlainTextEdit::mousePressEvent(e);
}
@@ -4263,22 +4309,45 @@ void BaseTextEditorWidget::mousePressEvent(QMouseEvent *e)
void BaseTextEditorWidget::mouseReleaseEvent(QMouseEvent *e)
{
if (mouseNavigationEnabled()
- && d->m_linkPressed
- && e->modifiers() & Qt::ControlModifier
- && !(e->modifiers() & Qt::ShiftModifier)
- && e->button() == Qt::LeftButton
- ) {
+ && d->m_linkPressed
+ && e->modifiers() & Qt::ControlModifier
+ && !(e->modifiers() & Qt::ShiftModifier)
+ && e->button() == Qt::LeftButton
+ ) {
+
+ Core::EditorManager* editorManager = Core::EditorManager::instance();
+ editorManager->addCurrentPositionToNavigationHistory();
+ Core::IEditor *editor = Core::EditorManager::currentEditor();
const QTextCursor cursor = cursorForPosition(e->pos());
- if (openLink(findLinkAt(cursor))) {
+ Link symbolLink = findLinkAt(cursor);
+ if (((!(e->modifiers() & Qt::AltModifier)) == openLinksInNextSplit()) &&
+ (editorManager->hasSplitter())) {
+ if (forceOpenLinksInNextSplit()) {
+ editorManager->gotoOtherSplit();
+ } else {
+ bool isVisible = false;
+ foreach (Core::IEditor *visEditor, editorManager->visibleEditors())
+ if (visEditor->document() &&
+ (symbolLink.fileName == visEditor->document()->fileName()) &&
+ (editor != visEditor)) {
+ isVisible = true;
+ editorManager->activateEditor(visEditor);
+ break;
+ }
+
+ if (!isVisible)
+ editorManager->gotoOtherSplit();
+ }
+ }
+
+ if (openLink(symbolLink)) {
clearLink();
return;
}
}
-#ifndef Q_OS_LINUX
- if (handleForwardBackwardMouseButtons(e))
+ if (!HostOsInfo::isLinuxHost() && handleForwardBackwardMouseButtons(e))
return;
-#endif
QPlainTextEdit::mouseReleaseEvent(e);
}
@@ -4366,6 +4435,7 @@ void BaseTextEditorWidget::extraAreaMouseEvent(QMouseEvent *e)
int markWidth;
extraAreaWidth(&markWidth);
+ const bool inMarkArea = e->pos().x() <= markWidth && e->pos().x() >= 0;
if (d->m_codeFoldingVisible
&& e->type() == QEvent::MouseMove && e->buttons() == 0) { // mouse tracking
@@ -4386,9 +4456,22 @@ void BaseTextEditorWidget::extraAreaMouseEvent(QMouseEvent *e)
// Set whether the mouse cursor is a hand or normal arrow
if (e->type() == QEvent::MouseMove) {
- bool hand = (e->pos().x() <= markWidth);
- if (hand != (d->m_extraArea->cursor().shape() == Qt::PointingHandCursor))
- d->m_extraArea->setCursor(hand ? Qt::PointingHandCursor : Qt::ArrowCursor);
+ if (inMarkArea) {
+ //Find line by cursor position
+ int line = cursor.blockNumber() + 1;
+ emit editor()->markTooltipRequested(editor(), mapToGlobal(e->pos()), line);
+ }
+
+ if (e->buttons() & Qt::LeftButton && !d->m_markDragStart.isNull()) {
+ int dist = (e->pos() - d->m_markDragStart).manhattanLength();
+ if (dist > QApplication::startDragDistance())
+ d->m_markDragging = true;
+ }
+
+ if (d->m_markDragging)
+ d->m_extraArea->setCursor(inMarkArea ? Qt::DragMoveCursor : Qt::ForbiddenCursor);
+ else if (inMarkArea != (d->m_extraArea->cursor().shape() == Qt::PointingHandCursor))
+ d->m_extraArea->setCursor(inMarkArea ? Qt::PointingHandCursor : Qt::ArrowCursor);
}
if (e->type() == QEvent::MouseButtonPress || e->type() == QEvent::MouseButtonDblClick) {
@@ -4406,7 +4489,7 @@ void BaseTextEditorWidget::extraAreaMouseEvent(QMouseEvent *e)
toggleBlockVisible(c);
d->moveCursorVisible(false);
}
- } else if (d->m_lineNumbersVisible && e->pos().x() > markWidth) {
+ } else if (d->m_lineNumbersVisible && !inMarkArea) {
QTextCursor selection = cursor;
selection.setVisualNavigation(true);
d->extraAreaSelectionAnchorBlockNumber = selection.blockNumber();
@@ -4415,6 +4498,18 @@ void BaseTextEditorWidget::extraAreaMouseEvent(QMouseEvent *e)
setTextCursor(selection);
} else {
d->extraAreaToggleMarkBlockNumber = cursor.blockNumber();
+ d->m_markDragging = false;
+ QTextBlock block = cursor.document()->findBlockByNumber(d->extraAreaToggleMarkBlockNumber);
+ if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
+ TextMarks marks = data->marks();
+ for (int i = marks.size(); --i >= 0; ) {
+ ITextMark *mark = marks.at(i);
+ if (mark->isDraggable()) {
+ d->m_markDragStart = e->pos();
+ break;
+ }
+ }
+ }
}
}
} else if (d->extraAreaSelectionAnchorBlockNumber >= 0) {
@@ -4448,25 +4543,41 @@ void BaseTextEditorWidget::extraAreaMouseEvent(QMouseEvent *e)
if (e->type() == QEvent::MouseButtonRelease && e->button() == Qt::LeftButton) {
int n = d->extraAreaToggleMarkBlockNumber;
d->extraAreaToggleMarkBlockNumber = -1;
- if (cursor.blockNumber() == n) {
- if (TextBlockUserData *data = static_cast<TextBlockUserData *>(cursor.block().userData())) {
- foreach (ITextMark *mark, data->marks()) {
- if (mark->clickable()) {
+ const bool sameLine = cursor.blockNumber() == n;
+ const bool wasDragging = d->m_markDragging;
+ d->m_markDragging = false;
+ d->m_markDragStart = QPoint();
+ QTextBlock block = cursor.document()->findBlockByNumber(n);
+ if (TextBlockUserData *data = static_cast<TextBlockUserData *>(block.userData())) {
+ TextMarks marks = data->marks();
+ for (int i = marks.size(); --i >= 0; ) {
+ ITextMark *mark = marks.at(i);
+ if (sameLine) {
+ if (mark->isClickable()) {
mark->clicked();
return;
}
+ } else {
+ if (wasDragging && mark->isDraggable()) {
+ if (inMarkArea) {
+ mark->dragToLine(cursor.blockNumber() + 1);
+ d->m_extraArea->setCursor(Qt::PointingHandCursor);
+ } else {
+ d->m_extraArea->setCursor(Qt::ArrowCursor);
+ }
+ return;
+ }
}
}
-
- int line = n + 1;
- ITextEditor::MarkRequestKind kind;
- if (QApplication::keyboardModifiers() & Qt::ShiftModifier)
- kind = ITextEditor::BookmarkRequest;
- else
- kind = ITextEditor::BreakpointRequest;
-
- emit editor()->markRequested(editor(), line, kind);
}
+ int line = n + 1;
+ ITextEditor::MarkRequestKind kind;
+ if (QApplication::keyboardModifiers() & Qt::ShiftModifier)
+ kind = ITextEditor::BookmarkRequest;
+ else
+ kind = ITextEditor::BreakpointRequest;
+
+ emit editor()->markRequested(editor(), line, kind);
}
}
}
@@ -4475,9 +4586,25 @@ void BaseTextEditorWidget::ensureCursorVisible()
{
QTextBlock block = textCursor().block();
if (!block.isVisible()) {
- while (!block.isVisible() && block.previous().isValid())
+ BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(document()->documentLayout());
+ QTC_ASSERT(documentLayout, return);
+
+ // Open all parent folds of current line.
+ int indent = BaseTextDocumentLayout::foldingIndent(block);
+ block = block.previous();
+ while (block.isValid()) {
+ const int indent2 = BaseTextDocumentLayout::foldingIndent(block);
+ if (BaseTextDocumentLayout::canFold(block) && indent2 < indent) {
+ BaseTextDocumentLayout::doFoldOrUnfold(block, /* unfold = */ true);
+ if (block.isVisible())
+ break;
+ indent = indent2;
+ }
block = block.previous();
- toggleBlockVisible(block);
+ }
+
+ documentLayout->requestUpdate();
+ documentLayout->emitDocumentSizeChanged();
}
QPlainTextEdit::ensureCursorVisible();
}
@@ -4499,12 +4626,12 @@ const TabSettings &BaseTextEditorWidget::tabSettings() const
return d->m_document->tabSettings();
}
-void BaseTextEditorWidget::setLanguageSettingsId(const QString &settingsId)
+void BaseTextEditorWidget::setLanguageSettingsId(Core::Id settingsId)
{
d->m_tabSettingsId = settingsId;
}
-QString BaseTextEditorWidget::languageSettingsId() const
+Core::Id BaseTextEditorWidget::languageSettingsId() const
{
return d->m_tabSettingsId;
}
@@ -5017,11 +5144,15 @@ void BaseTextEditorAnimator::finish()
void BaseTextEditorWidget::_q_matchParentheses()
{
- if (isReadOnly())
+ if (isReadOnly()
+ || !(d->m_displaySettings.m_highlightMatchingParentheses
+ || d->m_displaySettings.m_animateMatchingParentheses))
return;
QTextCursor backwardMatch = textCursor();
QTextCursor forwardMatch = textCursor();
+ if (overwriteMode())
+ backwardMatch.movePosition(QTextCursor::Right);
const TextBlockUserData::MatchType backwardMatchType = TextBlockUserData::matchCursorBackward(&backwardMatch);
const TextBlockUserData::MatchType forwardMatchType = TextBlockUserData::matchCursorForward(&forwardMatch);
@@ -5038,27 +5169,23 @@ void BaseTextEditorWidget::_q_matchParentheses()
if (backwardMatchType == TextBlockUserData::Mismatch) {
sel.cursor = backwardMatch;
sel.format = d->m_mismatchFormat;
+ extraSelections.append(sel);
} else {
- if (d->m_displaySettings.m_animateMatchingParentheses) {
- animatePosition = backwardMatch.selectionStart();
- } else if (d->m_formatRange) {
- sel.cursor = backwardMatch;
- sel.format = d->m_rangeFormat;
- extraSelections.append(sel);
- }
-
sel.cursor = backwardMatch;
sel.format = d->m_matchFormat;
sel.cursor.setPosition(backwardMatch.selectionStart());
- sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
+ sel.cursor.setPosition(sel.cursor.position() + 1, QTextCursor::KeepAnchor);
extraSelections.append(sel);
+ if (d->m_displaySettings.m_animateMatchingParentheses && sel.cursor.block().isVisible())
+ animatePosition = backwardMatch.selectionStart();
+
sel.cursor.setPosition(backwardMatch.selectionEnd());
- sel.cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
+ sel.cursor.setPosition(sel.cursor.position() - 1, QTextCursor::KeepAnchor);
+ extraSelections.append(sel);
}
- extraSelections.append(sel);
}
if (forwardMatch.hasSelection()) {
@@ -5066,27 +5193,23 @@ void BaseTextEditorWidget::_q_matchParentheses()
if (forwardMatchType == TextBlockUserData::Mismatch) {
sel.cursor = forwardMatch;
sel.format = d->m_mismatchFormat;
+ extraSelections.append(sel);
} else {
- if (d->m_displaySettings.m_animateMatchingParentheses) {
- animatePosition = forwardMatch.selectionEnd()-1;
- } else if (d->m_formatRange) {
- sel.cursor = forwardMatch;
- sel.format = d->m_rangeFormat;
- extraSelections.append(sel);
- }
-
sel.cursor = forwardMatch;
sel.format = d->m_matchFormat;
sel.cursor.setPosition(forwardMatch.selectionStart());
- sel.cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor);
+ sel.cursor.setPosition(sel.cursor.position() + 1, QTextCursor::KeepAnchor);
extraSelections.append(sel);
sel.cursor.setPosition(forwardMatch.selectionEnd());
- sel.cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor);
+ sel.cursor.setPosition(sel.cursor.position() - 1, QTextCursor::KeepAnchor);
+ extraSelections.append(sel);
+
+ if (d->m_displaySettings.m_animateMatchingParentheses && sel.cursor.block().isVisible())
+ animatePosition = forwardMatch.selectionEnd() - 1;
}
- extraSelections.append(sel);
}
@@ -5107,13 +5230,13 @@ void BaseTextEditorWidget::_q_matchParentheses()
d->m_animator->setPosition(animatePosition);
QPalette pal;
pal.setBrush(QPalette::Text, d->m_matchFormat.foreground());
- pal.setBrush(QPalette::Base, d->m_rangeFormat.background());
+ pal.setBrush(QPalette::Base, d->m_matchFormat.background());
d->m_animator->setData(font(), pal, characterAt(d->m_animator->position()));
connect(d->m_animator, SIGNAL(updateRequest(int,QPointF,QRectF)),
this, SLOT(_q_animateUpdate(int,QPointF,QRectF)));
}
-
- setExtraSelections(ParenthesesMatchingSelection, extraSelections);
+ if (d->m_displaySettings.m_highlightMatchingParentheses)
+ setExtraSelections(ParenthesesMatchingSelection, extraSelections);
}
void BaseTextEditorWidget::_q_highlightBlocks()
@@ -5379,11 +5502,10 @@ void BaseTextEditorWidget::setIfdefedOutBlocks(const QList<BaseTextEditorWidget:
bool set = false;
if (rangeNumber < blocks.size()) {
const BlockRange &range = blocks.at(rangeNumber);
- if (block.position() >= range.first && ((block.position() + block.length() - 1) <= range.last || !range.last)) {
+ if (block.position() >= range.first && ((block.position() + block.length() - 1) <= range.last || !range.last))
set = BaseTextDocumentLayout::setIfdefedOut(block);
- } else {
+ else
cleared = BaseTextDocumentLayout::clearIfdefedOut(block);
- }
if (block.contains(range.last))
++rangeNumber;
} else {
@@ -5610,9 +5732,7 @@ void BaseTextEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
d->m_searchResultFormat.setBackground(searchResultFormat.background());
// Matching braces
- d->m_matchFormat.setForeground(parenthesesFormat.foreground());
- d->m_rangeFormat.setBackground(parenthesesFormat.background());
-
+ d->m_matchFormat = parenthesesFormat;
// snippests
d->m_occurrencesFormat = fs.toTextCharFormat(C_OCCURRENCES);
@@ -5812,9 +5932,8 @@ void BaseTextEditorWidget::copy()
void BaseTextEditorWidget::paste()
{
- if (d->m_inBlockSelectionMode) {
+ if (d->m_inBlockSelectionMode)
d->removeBlockSelection();
- }
QPlainTextEdit::paste();
}
@@ -5852,9 +5971,7 @@ QMimeData *BaseTextEditorWidget::createMimeDataFromSelection() const
QTextCursor cursor = textCursor();
QMimeData *mimeData = new QMimeData;
- // Copy the selected text as plain text
- QString text = cursor.selectedText();
- convertToPlainText(text);
+ QString text = plainTextFromSelection();
mimeData->setText(text);
// Copy the selected text as HTML
@@ -6072,6 +6189,28 @@ QMimeData *BaseTextEditorWidget::duplicateMimeData(const QMimeData *source) cons
return mimeData;
}
+QString BaseTextEditorWidget::lineNumber(int blockNumber) const
+{
+ return QString::number(blockNumber + 1);
+}
+
+int BaseTextEditorWidget::lineNumberTopPositionOffset(int blockNumber) const
+{
+ Q_UNUSED(blockNumber)
+ return 0;
+}
+
+int BaseTextEditorWidget::lineNumberDigits() const
+{
+ int digits = 2;
+ int max = qMax(1, blockCount());
+ while (max >= 100) {
+ max /= 10;
+ ++digits;
+ }
+ return digits;
+}
+
void BaseTextEditorWidget::appendMenuActionsFromContext(QMenu *menu, const Core::Id menuContextId)
{
Core::ActionContainer *mcontext = Core::ActionManager::actionContainer(menuContextId);
@@ -6098,8 +6237,8 @@ void BaseTextEditorWidget::appendStandardContextMenuActions(QMenu *menu)
if (a && a->isEnabled())
menu->addAction(a);
- BaseTextDocument *doc = baseTextDocument();
- if (doc->codec()->name() == QString(QLatin1String("UTF-8"))) {
+ QSharedPointer<BaseTextDocument> doc = baseTextDocument();
+ if (doc->codec()->name() == QByteArray("UTF-8") && doc->supportsUtf8Bom()) {
a = Core::ActionManager::command(Constants::SWITCH_UTF8BOM)->action();
if (a && a->isEnabled()) {
a->setText(doc->format().hasUtf8Bom ? tr("Delete UTF-8 BOM on Save")
@@ -6274,12 +6413,12 @@ QString BaseTextEditor::contextHelpId() const
return m_contextHelpId;
}
-Internal::RefactorMarkers BaseTextEditorWidget::refactorMarkers() const
+RefactorMarkers BaseTextEditorWidget::refactorMarkers() const
{
return d->m_refactorOverlay->markers();
}
-void BaseTextEditorWidget::setRefactorMarkers(const Internal::RefactorMarkers &markers)
+void BaseTextEditorWidget::setRefactorMarkers(const RefactorMarkers &markers)
{
foreach (const RefactorMarker &marker, d->m_refactorOverlay->markers())
requestBlockUpdate(marker.cursor.block());
@@ -6300,7 +6439,7 @@ void BaseTextEditorWidget::doFoo() {
#endif
}
-void Internal::BaseTextBlockSelection::moveAnchor(int blockNumber, int visualColumn)
+void BaseTextBlockSelection::moveAnchor(int blockNumber, int visualColumn)
{
if (visualColumn >= 0) {
if (anchor % 2) {
@@ -6337,7 +6476,7 @@ void Internal::BaseTextBlockSelection::moveAnchor(int blockNumber, int visualCol
lastBlock.movePosition(QTextCursor::EndOfBlock);
}
-QTextCursor Internal::BaseTextBlockSelection::selection(const TabSettings &ts) const
+QTextCursor BaseTextBlockSelection::selection(const TabSettings &ts) const
{
QTextCursor cursor = firstBlock;
if (anchor <= TopRight) {
@@ -6352,7 +6491,7 @@ QTextCursor Internal::BaseTextBlockSelection::selection(const TabSettings &ts) c
return cursor;
}
-void Internal::BaseTextBlockSelection::fromSelection(const TabSettings &ts, const QTextCursor &selection)
+void BaseTextBlockSelection::fromSelection(const TabSettings &ts, const QTextCursor &selection)
{
firstBlock = selection;
firstBlock.setPosition(selection.selectionStart());
@@ -6458,7 +6597,7 @@ int BaseTextEditorWidget::rowCount() const
@see uppercaseSelection, lowercaseSelection
*/
-void BaseTextEditorWidget::transformSelection(Internal::TransformationMethod method)
+void BaseTextEditorWidget::transformSelection(TransformationMethod method)
{
if (hasBlockSelection()) {
transformBlockSelection(method);
@@ -6491,7 +6630,7 @@ void BaseTextEditorWidget::transformSelection(Internal::TransformationMethod met
setTextCursor(cursor);
}
-void BaseTextEditorWidget::transformBlockSelection(Internal::TransformationMethod method)
+void BaseTextEditorWidget::transformBlockSelection(TransformationMethod method)
{
QTextCursor cursor = textCursor();
int minPos = cursor.anchor();
@@ -6560,7 +6699,7 @@ IAssistInterface *BaseTextEditorWidget::createAssistInterface(AssistKind kind,
AssistReason reason) const
{
Q_UNUSED(kind);
- return new DefaultAssistInterface(document(), position(), d->m_document, reason);
+ return new DefaultAssistInterface(document(), position(), d->m_document.data(), reason);
}
QString TextEditor::BaseTextEditorWidget::foldReplacementText(const QTextBlock &) const
diff --git a/src/plugins/texteditor/basetexteditor.h b/src/plugins/texteditor/basetexteditor.h
index d2a623796a..7c7445bd72 100644
--- a/src/plugins/texteditor/basetexteditor.h
+++ b/src/plugins/texteditor/basetexteditor.h
@@ -33,10 +33,12 @@
#include "itexteditor.h"
#include "codeassist/assistenums.h"
-#include <find/ifindsupport.h>
#include <coreplugin/editormanager/editormanager.h>
+#include <coreplugin/id.h>
+#include <find/ifindsupport.h>
#include <QPlainTextEdit>
+#include <QSharedPointer>
QT_BEGIN_NAMESPACE
class QToolBar;
@@ -57,11 +59,11 @@ class IAssistMonitorInterface;
class IAssistInterface;
class IAssistProvider;
class ICodeStylePreferences;
+typedef QList<RefactorMarker> RefactorMarkers;
namespace Internal {
class BaseTextEditorWidgetPrivate;
class TextEditorOverlay;
- typedef QList<RefactorMarker> RefactorMarkers;
typedef QString (QString::*TransformationMethod)() const;
}
@@ -179,6 +181,12 @@ public:
void setLineNumbersVisible(bool b);
bool lineNumbersVisible() const;
+ void setOpenLinksInNextSplit(bool b);
+ bool openLinksInNextSplit() const;
+
+ void setForceOpenLinksInNextSplit(bool b);
+ bool forceOpenLinksInNextSplit() const;
+
void setMarksVisible(bool b);
bool marksVisible() const;
@@ -346,6 +354,13 @@ protected:
bool canInsertFromMimeData(const QMimeData *source) const;
void insertFromMimeData(const QMimeData *source);
+ virtual QString plainTextFromSelection() const;
+ static QString convertToPlainText(const QString &txt);
+
+ virtual QString lineNumber(int blockNumber) const;
+ virtual int lineNumberTopPositionOffset(int blockNumber) const;
+ virtual int lineNumberDigits() const;
+
static QString msgTextTooLarge(quint64 size);
private:
@@ -356,8 +371,8 @@ public:
void duplicateFrom(BaseTextEditorWidget *editor);
protected:
- BaseTextDocument *baseTextDocument() const;
- void setBaseTextDocument(BaseTextDocument *doc);
+ QSharedPointer<BaseTextDocument> baseTextDocument() const;
+ void setBaseTextDocument(const QSharedPointer<BaseTextDocument> &doc);
void setDefaultPath(const QString &defaultPath);
@@ -389,8 +404,8 @@ public:
virtual void extraAreaMouseEvent(QMouseEvent *);
const TabSettings &tabSettings() const;
- void setLanguageSettingsId(const QString &settingsId);
- QString languageSettingsId() const;
+ void setLanguageSettingsId(Core::Id settingsId);
+ Core::Id languageSettingsId() const;
void setCodeStyle(ICodeStylePreferences *settings);
@@ -418,8 +433,8 @@ public:
QList<QTextEdit::ExtraSelection> extraSelections(ExtraSelectionKind kind) const;
QString extraSelectionTooltip(int pos) const;
- Internal::RefactorMarkers refactorMarkers() const;
- void setRefactorMarkers(const Internal::RefactorMarkers &markers);
+ RefactorMarkers refactorMarkers() const;
+ void setRefactorMarkers(const RefactorMarkers &markers);
signals:
void refactorMarkerClicked(const TextEditor::RefactorMarker &marker);
@@ -524,6 +539,7 @@ protected:
virtual QString foldReplacementText(const QTextBlock &block) const;
protected slots:
+ virtual void slotUpdateExtraArea();
virtual void slotUpdateExtraAreaWidth();
virtual void slotModificationChanged(bool);
virtual void slotUpdateRequest(const QRect &r, int dy);
diff --git a/src/plugins/texteditor/basetexteditor_p.h b/src/plugins/texteditor/basetexteditor_p.h
index f30d742ccb..84dd9bfbc9 100644
--- a/src/plugins/texteditor/basetexteditor_p.h
+++ b/src/plugins/texteditor/basetexteditor_p.h
@@ -36,10 +36,11 @@
#include "fontsettings.h"
#include "refactoroverlay.h"
+#include <coreplugin/id.h>
#include <utils/changeset.h>
#include <QBasicTimer>
-#include <QSharedData>
+#include <QSharedPointer>
#include <QPointer>
#include <QScopedPointer>
@@ -74,73 +75,6 @@ public:
void fromSelection(const TabSettings &ts, const QTextCursor &selection);
};
-//========== Pointers with reference count ==========
-
-template <class T> class QRefCountData : public QSharedData
-{
-public:
- QRefCountData(T *data) { m_data = data; }
-
- ~QRefCountData() { delete m_data; }
-
- T *m_data;
-};
-
-/* MOSTLY COPIED FROM QSHAREDDATA(-POINTER) */
-template <class T> class QRefCountPointer
-{
-public:
- inline T &operator*() { return d ? *(d->m_data) : 0; }
- inline const T &operator*() const { return d ? *(d->m_data) : 0; }
- inline T *operator->() { return d ? d->m_data : 0; }
- inline const T *operator->() const { return d ? d->m_data : 0; }
- inline operator T *() { return d ? d->m_data : 0; }
- inline operator const T *() const { return d ? d->m_data : 0; }
-
- inline bool operator==(const QRefCountPointer<T> &other) const { return d == other.d; }
- inline bool operator!=(const QRefCountPointer<T> &other) const { return d != other.d; }
-
- inline QRefCountPointer() { d = 0; }
- inline ~QRefCountPointer() { if (d && !d->ref.deref()) delete d; }
-
- explicit QRefCountPointer(T *data) {
- if (data) {
- d = new QRefCountData<T>(data);
- d->ref.ref();
- }
- else {
- d = 0;
- }
- }
- inline QRefCountPointer(const QRefCountPointer<T> &o) : d(o.d) { if (d) d->ref.ref(); }
- inline QRefCountPointer<T> & operator=(const QRefCountPointer<T> &o) {
- if (o.d != d) {
- if (d && !d->ref.deref())
- delete d;
- //todo: atomic assign of pointers
- d = o.d;
- if (d)
- d->ref.ref();
- }
- return *this;
- }
- inline QRefCountPointer &operator=(T *o) {
- if (d == 0 || d->m_data != o) {
- if (d && !d->ref.deref())
- delete d;
- d = new QRefCountData<T>(o);
- if (d)
- d->ref.ref();
- }
- return *this;
- }
-
- inline bool operator!() const { return !d; }
-
-private:
- QRefCountData<T> *d;
-};
-
//================BaseTextEditorPrivate==============
struct BaseTextEditorPrivateHighlightBlocks
@@ -167,7 +101,7 @@ public:
~BaseTextEditorWidgetPrivate();
void setupBasicEditActions(TextEditorActionHandler *actionHandler);
- void setupDocumentSignals(BaseTextDocument *document);
+ void setupDocumentSignals(const QSharedPointer<BaseTextDocument> &document);
void updateLineSelectionColor();
void print(QPrinter *printer);
@@ -183,7 +117,7 @@ public:
QList<QTextEdit::ExtraSelection> m_syntaxHighlighterSelections;
QTextEdit::ExtraSelection m_lineSelection;
- QRefCountPointer<BaseTextDocument> m_document;
+ QSharedPointer<BaseTextDocument> m_document;
QByteArray m_tempState;
QByteArray m_tempNavigationState;
@@ -197,13 +131,12 @@ public:
bool m_formatRange;
QTextCharFormat m_matchFormat;
QTextCharFormat m_mismatchFormat;
- QTextCharFormat m_rangeFormat;
QTimer *m_parenthesesMatchingTimer;
// end parentheses matcher
QWidget *m_extraArea;
- QString m_tabSettingsId;
+ Core::Id m_tabSettingsId;
ICodeStylePreferences *m_codeStylePreferences;
DisplaySettings m_displaySettings;
FontSettings m_fontSettings;
@@ -293,6 +226,9 @@ public:
QPointer<BaseTextEditorAnimator> m_animator;
int m_cursorBlockNumber;
+ QPoint m_markDragStart;
+ bool m_markDragging;
+
QScopedPointer<AutoCompleter> m_autoCompleter;
QScopedPointer<Indenter> m_indenter;
diff --git a/src/plugins/texteditor/basetextmark.cpp b/src/plugins/texteditor/basetextmark.cpp
index f7a4967f1e..d8a377d954 100644
--- a/src/plugins/texteditor/basetextmark.cpp
+++ b/src/plugins/texteditor/basetextmark.cpp
@@ -61,9 +61,8 @@ void BaseTextMarkRegistry::add(BaseTextMark *mark)
foreach (Core::IEditor *editor, em->editorsForFileName(mark->fileName())) {
if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
ITextMarkable *markableInterface = textEditor->markableInterface();
- if (markableInterface->addMark(mark)) {
+ if (markableInterface->addMark(mark))
break;
- }
}
}
}
diff --git a/src/plugins/texteditor/behaviorsettingspage.h b/src/plugins/texteditor/behaviorsettingspage.h
index 113ec1d8f8..18aff4ab99 100644
--- a/src/plugins/texteditor/behaviorsettingspage.h
+++ b/src/plugins/texteditor/behaviorsettingspage.h
@@ -47,7 +47,7 @@ class CodeStylePool;
class BehaviorSettingsPageParameters
{
public:
- QString id;
+ Core::Id id;
QString displayName;
QString settingsPrefix;
};
diff --git a/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp b/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp
index 80e40bd370..330c95bc57 100644
--- a/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp
+++ b/src/plugins/texteditor/codeassist/basicproposalitemlistmodel.cpp
@@ -193,14 +193,21 @@ void BasicProposalItemListModel::filter(const QString &prefix)
/*
* This code builds a regular expression in order to more intelligently match
- * camel-case style. This means upper-case characters will be rewritten as follows:
+ * camel-case and underscore names.
*
- * A => [a-z0-9_]*A (for any but the first capital letter)
+ * For any but the first letter, the following replacements are made:
+ * A => [a-z0-9_]*A
+ * a => (?:[a-zA-Z0-9]*_)?a
*
- * Meaning it allows any sequence of lower-case characters to preceed an
- * upper-case character. So for example gAC matches getActionController.
+ * That means any sequence of lower-case or underscore characters can preceed an
+ * upper-case character. And any sequence of lower-case or upper case characters -
+ * followed by an underscore can preceed a lower-case character.
*
- * It also implements the first-letter-only case sensitivity.
+ * Examples: (case sensitive mode)
+ * gAC matches getActionController
+ * gac matches get_action_controller
+ *
+ * It also implements the fully and first-letter-only case sensitivity.
*/
const TextEditor::CaseSensitivity caseSensitivity =
TextEditorSettings::instance()->completionSettings().m_caseSensitivity;
@@ -208,21 +215,28 @@ void BasicProposalItemListModel::filter(const QString &prefix)
QString keyRegExp;
keyRegExp += QLatin1Char('^');
bool first = true;
- const QLatin1String wordContinuation("[a-z0-9_]*");
+ const QLatin1String uppercaseWordContinuation("[a-z0-9_]*");
+ const QLatin1String lowercaseWordContinuation("(?:[a-zA-Z0-9]*_)?");
foreach (const QChar &c, prefix) {
if (caseSensitivity == TextEditor::CaseInsensitive ||
(caseSensitivity == TextEditor::FirstLetterCaseSensitive && !first)) {
keyRegExp += QLatin1String("(?:");
- if (c.isUpper() && !first)
- keyRegExp += wordContinuation;
+ if (!first)
+ keyRegExp += uppercaseWordContinuation;
keyRegExp += QRegExp::escape(c.toUpper());
keyRegExp += QLatin1Char('|');
+ if (!first)
+ keyRegExp += lowercaseWordContinuation;
keyRegExp += QRegExp::escape(c.toLower());
keyRegExp += QLatin1Char(')');
} else {
- if (c.isUpper() && !first)
- keyRegExp += wordContinuation;
+ if (!first) {
+ if (c.isUpper())
+ keyRegExp += uppercaseWordContinuation;
+ else
+ keyRegExp += lowercaseWordContinuation;
+ }
keyRegExp += QRegExp::escape(c);
}
diff --git a/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp b/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
index 95db0eeb2f..c708b44947 100644
--- a/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
+++ b/src/plugins/texteditor/codeassist/functionhintproposalwidget.cpp
@@ -32,6 +32,7 @@
#include "codeassistant.h"
#include <utils/faketooltip.h>
+#include <utils/hostosinfo.h>
#include <QDebug>
#include <QApplication>
@@ -191,14 +192,12 @@ bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e)
{
switch (e->type()) {
case QEvent::ShortcutOverride:
- if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
+ if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape)
d->m_escapePressed = true;
- }
break;
case QEvent::KeyPress:
- if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape) {
+ if (static_cast<QKeyEvent*>(e)->key() == Qt::Key_Escape)
d->m_escapePressed = true;
- }
if (d->m_model->size() > 1) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if (ke->key() == Qt::Key_Up) {
@@ -220,9 +219,8 @@ bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e)
break;
case QEvent::WindowDeactivate:
case QEvent::FocusOut:
- if (obj != d->m_underlyingWidget) {
+ if (obj != d->m_underlyingWidget)
break;
- }
abort();
break;
case QEvent::MouseButtonPress:
@@ -233,11 +231,10 @@ bool FunctionHintProposalWidget::eventFilter(QObject *obj, QEvent *e)
if (!d->m_popupFrame->isAncestorOf(widget)) {
abort();
} else if (e->type() == QEvent::Wheel) {
- if (static_cast<QWheelEvent*>(e)->delta() > 0) {
+ if (static_cast<QWheelEvent*>(e)->delta() > 0)
previousPage();
- } else {
+ else
nextPage();
- }
return true;
}
}
@@ -287,11 +284,9 @@ void FunctionHintProposalWidget::updateContent()
void FunctionHintProposalWidget::updatePosition()
{
const QDesktopWidget *desktop = QApplication::desktop();
-#ifdef Q_OS_MAC
- const QRect &screen = desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget));
-#else
- const QRect &screen = desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget));
-#endif
+ const QRect &screen = Utils::HostOsInfo::isMacHost()
+ ? desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget))
+ : desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget));
d->m_pager->setFixedWidth(d->m_pager->minimumSizeHint().width());
diff --git a/src/plugins/texteditor/codeassist/genericproposalwidget.cpp b/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
index 50970c2bac..3b449cd312 100644
--- a/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
+++ b/src/plugins/texteditor/codeassist/genericproposalwidget.cpp
@@ -39,6 +39,7 @@
#include <texteditor/texteditorconstants.h>
#include <utils/faketooltip.h>
+#include <utils/hostosinfo.h>
#include <QRect>
#include <QLatin1String>
@@ -55,6 +56,7 @@
#include <QDesktopWidget>
#include <QLabel>
+using namespace Utils;
namespace TextEditor {
@@ -134,13 +136,12 @@ QVariant ModelAdapter::data(const QModelIndex &index, int role) const
if (index.row() >= m_completionModel->size())
return QVariant();
- if (role == Qt::DisplayRole) {
+ if (role == Qt::DisplayRole)
return m_completionModel->text(index.row());
- } else if (role == Qt::DecorationRole) {
+ else if (role == Qt::DecorationRole)
return m_completionModel->icon(index.row());
- } else if (role == Qt::WhatsThisRole) {
+ else if (role == Qt::WhatsThisRole)
return m_completionModel->detail(index.row());
- }
return QVariant();
}
@@ -311,15 +312,15 @@ void GenericProposalWidgetPrivate::maybeShowInfoTip()
GenericProposalWidget::GenericProposalWidget()
: d(new GenericProposalWidgetPrivate(this))
{
-#ifdef Q_OS_MAC
- if (d->m_completionListView->horizontalScrollBar())
- d->m_completionListView->horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
- if (d->m_completionListView->verticalScrollBar())
- d->m_completionListView->verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
-#else
- // This improves the look with QGTKStyle.
- setFrameStyle(d->m_completionListView->frameStyle());
-#endif
+ if (HostOsInfo::isMacHost()) {
+ if (d->m_completionListView->horizontalScrollBar())
+ d->m_completionListView->horizontalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
+ if (d->m_completionListView->verticalScrollBar())
+ d->m_completionListView->verticalScrollBar()->setAttribute(Qt::WA_MacMiniSize);
+ } else {
+ // This improves the look with QGTKStyle.
+ setFrameStyle(d->m_completionListView->frameStyle());
+ }
d->m_completionListView->setFrameStyle(QFrame::NoFrame);
d->m_completionListView->setAttribute(Qt::WA_MacShowFocusRect, false);
d->m_completionListView->setUniformItemSizes(true);
@@ -507,11 +508,9 @@ void GenericProposalWidget::updatePositionAndSize()
// Determine the position, keeping the popup on the screen
const QDesktopWidget *desktop = QApplication::desktop();
-#ifdef Q_OS_MAC
- const QRect screen = desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget));
-#else
- const QRect screen = desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget));
-#endif
+ const QRect screen = HostOsInfo::isMacHost()
+ ? desktop->availableGeometry(desktop->screenNumber(d->m_underlyingWidget))
+ : desktop->screenGeometry(desktop->screenNumber(d->m_underlyingWidget));
QPoint pos = d->m_displayRect.bottomLeft();
pos.rx() -= 16 + fw; // Space for the icons
@@ -555,11 +554,7 @@ bool GenericProposalWidget::eventFilter(QObject *o, QEvent *e)
switch (ke->key()) {
case Qt::Key_N:
case Qt::Key_P:
-#ifdef Q_OS_MAC
- if (ke->modifiers() == Qt::MetaModifier) {
-#else
- if (ke->modifiers() == Qt::ControlModifier) {
-#endif
+ if (ke->modifiers() == Qt::KeyboardModifiers(HostOsInfo::controlModifier())) {
e->accept();
return true;
}
@@ -575,11 +570,7 @@ bool GenericProposalWidget::eventFilter(QObject *o, QEvent *e)
case Qt::Key_P:
// select next/previous completion
d->m_explicitlySelected = true;
-#ifdef Q_OS_MAC
- if (ke->modifiers() == Qt::MetaModifier) {
-#else
- if (ke->modifiers() == Qt::ControlModifier) {
-#endif
+ if (ke->modifiers() == Qt::KeyboardModifiers(HostOsInfo::controlModifier())) {
int change = (ke->key() == Qt::Key_N) ? 1 : -1;
int nrows = d->m_model->size();
int row = d->m_completionListView->currentIndex().row();
diff --git a/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp b/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp
new file mode 100644
index 0000000000..096efdb3a4
--- /dev/null
+++ b/src/plugins/texteditor/codeassist/keywordscompletionassist.cpp
@@ -0,0 +1,277 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "keywordscompletionassist.h"
+
+#include <texteditor/codeassist/iassistinterface.h>
+#include <texteditor/codeassist/genericproposal.h>
+#include <texteditor/codeassist/ifunctionhintproposalmodel.h>
+#include <texteditor/codeassist/functionhintproposal.h>
+#include <texteditor/codeassist/basicproposalitemlistmodel.h>
+#include "completionsettings.h"
+#include "texteditorsettings.h"
+#include "basetexteditor.h"
+
+#include <QtGui/QTextCursor>
+
+using namespace TextEditor;
+
+// --------------------------
+// Keywords
+// --------------------------
+Keywords::Keywords()
+{
+
+}
+
+// Note: variables and functions must be sorted
+Keywords::Keywords(const QStringList &variabels, const QStringList &functions, const QMap<QString, QStringList> &functionArgs)
+ : m_variables(variabels), m_functions(functions), m_functionArgs(functionArgs)
+{
+
+}
+
+bool Keywords::isVariable(const QString &word) const
+{
+ return qBinaryFind(m_variables, word) != m_variables.constEnd();
+}
+
+bool Keywords::isFunction(const QString &word) const
+{
+ return qBinaryFind(m_functions, word) != m_functions.constEnd();
+}
+
+QStringList Keywords::variables() const
+{
+ return m_variables;
+}
+
+QStringList Keywords::functions() const
+{
+ return m_functions;
+}
+
+QStringList Keywords::argsForFunction(const QString &function) const
+{
+ return m_functionArgs.value(function);
+}
+
+
+// --------------------------
+// KeywordsAssistProposalItem
+// --------------------------
+KeywordsAssistProposalItem::KeywordsAssistProposalItem(Keywords keywords)
+ : m_keywords(keywords)
+{
+}
+
+KeywordsAssistProposalItem::~KeywordsAssistProposalItem()
+{}
+
+bool KeywordsAssistProposalItem::prematurelyApplies(const QChar &c) const
+{
+ // only '(' in case of a function
+ if (c == QLatin1Char('(') && m_keywords.isFunction(text()))
+ return true;
+ return false;
+}
+
+void KeywordsAssistProposalItem::applyContextualContent(TextEditor::BaseTextEditor *editor,
+ int basePosition) const
+{
+ const CompletionSettings &settings = TextEditorSettings::instance()->completionSettings();
+
+ int replaceLength = editor->position() - basePosition;
+ QString toInsert = text();
+ int cursorOffset = 0;
+ if (m_keywords.isFunction(toInsert) && settings.m_autoInsertBrackets) {
+ if (settings.m_spaceAfterFunctionName) {
+ if (editor->textAt(editor->position(), 2) == QLatin1String(" (")) {
+ cursorOffset = 2;
+ } else if (editor->characterAt(editor->position()) == QLatin1Char('(')
+ || editor->characterAt(editor->position()) == QLatin1Char(' ')) {
+ replaceLength += 1;
+ toInsert += QLatin1String(" (");
+ } else {
+ toInsert += QLatin1String(" ()");
+ cursorOffset = -1;
+ }
+ } else {
+ if (editor->characterAt(editor->position()) == QLatin1Char('(')) {
+ cursorOffset = 1;
+ } else {
+ toInsert += QLatin1String("()");
+ cursorOffset = -1;
+ }
+ }
+ }
+
+ editor->setCursorPosition(basePosition);
+ editor->replace(replaceLength, toInsert);
+ if (cursorOffset)
+ editor->setCursorPosition(editor->position() + cursorOffset);
+}
+
+// -------------------------
+// KeywordsFunctionHintModel
+// -------------------------
+KeywordsFunctionHintModel::KeywordsFunctionHintModel(const QStringList &functionSymbols)
+ : m_functionSymbols(functionSymbols)
+{}
+
+KeywordsFunctionHintModel::~KeywordsFunctionHintModel()
+{}
+
+void KeywordsFunctionHintModel::reset()
+{}
+
+int KeywordsFunctionHintModel::size() const
+{
+ return m_functionSymbols.size();
+}
+
+QString KeywordsFunctionHintModel::text(int index) const
+{
+ return m_functionSymbols.at(index);
+}
+
+int KeywordsFunctionHintModel::activeArgument(const QString &prefix) const
+{
+ Q_UNUSED(prefix);
+ return 1;
+}
+
+// ---------------------------------
+// KeywordsCompletionAssistProcessor
+// ---------------------------------
+KeywordsCompletionAssistProcessor::KeywordsCompletionAssistProcessor(Keywords keywords)
+ : m_startPosition(-1)
+ , m_variableIcon(QLatin1String(":/codemodel/images/keyword.png"))
+ , m_functionIcon(QLatin1String(":/codemodel/images/func.png"))
+ , m_keywords(keywords)
+{}
+
+KeywordsCompletionAssistProcessor::~KeywordsCompletionAssistProcessor()
+{}
+
+IAssistProposal *KeywordsCompletionAssistProcessor::perform(const IAssistInterface *interface)
+{
+ m_interface.reset(interface);
+
+ if (isInComment())
+ return 0;
+
+ if (interface->reason() == IdleEditor && !acceptsIdleEditor())
+ return 0;
+
+ if (m_startPosition == -1)
+ m_startPosition = findStartOfName();
+
+ int nextCharPos = m_startPosition + m_word.length();
+ if (m_keywords.isFunction(m_word)
+ && m_interface->characterAt(nextCharPos) == QLatin1Char('(')) {
+ QStringList functionSymbols = m_keywords.argsForFunction(m_word);
+ IFunctionHintProposalModel *model =
+ new KeywordsFunctionHintModel(functionSymbols);
+ IAssistProposal *proposal = new FunctionHintProposal(m_startPosition, model);
+ return proposal;
+ } else {
+ QList<TextEditor::BasicProposalItem *> items;
+ addWordsToProposalList(&items, m_keywords.variables(), m_variableIcon);
+ addWordsToProposalList(&items, m_keywords.functions(), m_functionIcon);
+ return new GenericProposal(m_startPosition, new BasicProposalItemListModel(items));
+ }
+}
+
+QChar KeywordsCompletionAssistProcessor::startOfCommentChar() const
+{
+ return QLatin1Char('#');
+}
+
+bool KeywordsCompletionAssistProcessor::acceptsIdleEditor()
+{
+ const int pos = m_interface->position();
+ QChar characterUnderCursor = m_interface->characterAt(pos);
+ if (!characterUnderCursor.isLetterOrNumber()) {
+ m_startPosition = findStartOfName();
+ if (pos - m_startPosition >= 3 && !isInComment())
+ return true;
+ }
+ return false;
+}
+
+int KeywordsCompletionAssistProcessor::findStartOfName(int pos)
+{
+ if (pos == -1)
+ pos = m_interface->position();
+
+ QChar chr = m_interface->characterAt(pos-1);
+ if (chr == QLatin1Char('('))
+ --pos;
+ // Skip to the start of a name
+ do {
+ chr = m_interface->characterAt(--pos);
+ } while (chr.isLetterOrNumber() || chr == QLatin1Char('_'));
+
+ int start = ++pos;
+ m_word.clear();
+ do {
+ m_word += m_interface->characterAt(pos);
+ chr = m_interface->characterAt(++pos);
+ } while ((chr.isLetterOrNumber() || chr == QLatin1Char('_'))
+ && chr != QLatin1Char('('));
+
+ return start;
+}
+
+bool KeywordsCompletionAssistProcessor::isInComment() const
+{
+ QTextCursor tc(m_interface->textDocument());
+ tc.setPosition(m_interface->position());
+ tc.movePosition(QTextCursor::StartOfLine, QTextCursor::KeepAnchor);
+ const QString &lineBeginning = tc.selectedText();
+ if (lineBeginning.contains(startOfCommentChar()))
+ return true;
+ return false;
+}
+
+void KeywordsCompletionAssistProcessor::addWordsToProposalList(QList<BasicProposalItem *> *items, const QStringList &words, const QIcon &icon)
+{
+ if (!items)
+ return;
+
+ for (int i = 0; i < words.count(); ++i) {
+ BasicProposalItem *item = new KeywordsAssistProposalItem(m_keywords);
+ item->setText(words.at(i));
+ item->setIcon(icon);
+ items->append(item);
+ }
+}
+
+
diff --git a/src/plugins/texteditor/codeassist/keywordscompletionassist.h b/src/plugins/texteditor/codeassist/keywordscompletionassist.h
new file mode 100644
index 0000000000..7c8f8eac66
--- /dev/null
+++ b/src/plugins/texteditor/codeassist/keywordscompletionassist.h
@@ -0,0 +1,113 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef KEYWORDSCOMPLETIONASSIST_H
+#define KEYWORDSCOMPLETIONASSIST_H
+
+#include "iassistprocessor.h"
+#include "basicproposalitem.h"
+#include "ifunctionhintproposalmodel.h"
+
+#include <QtGui/QIcon>
+#include <QtCore/QStringList>
+
+namespace TextEditor {
+
+class TEXTEDITOR_EXPORT Keywords
+{
+public:
+ Keywords();
+ Keywords(const QStringList &variabels, const QStringList &functions, const QMap<QString, QStringList> &functionArgs);
+ bool isVariable(const QString &word) const;
+ bool isFunction(const QString &word) const;
+
+ QStringList variables() const;
+ QStringList functions() const;
+ QStringList argsForFunction(const QString &function) const;
+
+private:
+ QStringList m_variables;
+ QStringList m_functions;
+ QMap<QString, QStringList> m_functionArgs;
+};
+
+class TEXTEDITOR_EXPORT KeywordsAssistProposalItem : public TextEditor::BasicProposalItem
+{
+public:
+ KeywordsAssistProposalItem(Keywords keywords);
+ virtual ~KeywordsAssistProposalItem();
+
+ virtual bool prematurelyApplies(const QChar &c) const;
+ virtual void applyContextualContent(TextEditor::BaseTextEditor *editor,
+ int basePosition) const;
+private:
+ Keywords m_keywords;
+};
+
+class TEXTEDITOR_EXPORT KeywordsFunctionHintModel : public TextEditor::IFunctionHintProposalModel
+{
+public:
+ KeywordsFunctionHintModel(const QStringList &functionSymbols);
+ virtual ~KeywordsFunctionHintModel();
+
+ virtual void reset();
+ virtual int size() const;
+ virtual QString text(int index) const;
+ virtual int activeArgument(const QString &prefix) const;
+
+private:
+ QStringList m_functionSymbols;
+};
+
+class TEXTEDITOR_EXPORT KeywordsCompletionAssistProcessor : public TextEditor::IAssistProcessor
+{
+public:
+ KeywordsCompletionAssistProcessor(Keywords keywords);
+ virtual ~KeywordsCompletionAssistProcessor();
+
+ virtual TextEditor::IAssistProposal *perform(const TextEditor::IAssistInterface *interface);
+ virtual QChar startOfCommentChar() const;
+
+private:
+ bool acceptsIdleEditor();
+ int findStartOfName(int pos = -1);
+ bool isInComment() const;
+ void addWordsToProposalList(QList<BasicProposalItem *> *items, const QStringList &words, const QIcon &icon);
+
+ int m_startPosition;
+ QString m_word;
+ QScopedPointer<const TextEditor::IAssistInterface> m_interface;
+ const QIcon m_variableIcon;
+ const QIcon m_functionIcon;
+ Keywords m_keywords;
+};
+
+} // TextEditor
+
+#endif // KEYWORDSCOMPLETIONASSISTPROCESSOR_H
diff --git a/src/plugins/texteditor/codeassist/quickfixassistprocessor.cpp b/src/plugins/texteditor/codeassist/quickfixassistprocessor.cpp
index 6d3dcf64f4..fa3e64017b 100644
--- a/src/plugins/texteditor/codeassist/quickfixassistprocessor.cpp
+++ b/src/plugins/texteditor/codeassist/quickfixassistprocessor.cpp
@@ -55,12 +55,12 @@ IAssistProposal *QuickFixAssistProcessor::perform(const IAssistInterface *interf
QSharedPointer<const IAssistInterface> assistInterface(interface);
- QList<QuickFixOperation::Ptr> quickFixes;
+ QuickFixOperations quickFixes;
const QuickFixAssistProvider *quickFixProvider =
static_cast<const QuickFixAssistProvider *>(provider());
foreach (QuickFixFactory *factory, quickFixProvider->quickFixFactories())
- quickFixes += factory->matchingOperations(assistInterface);
+ factory->matchingOperations(assistInterface, quickFixes);
if (!quickFixes.isEmpty()) {
QList<BasicProposalItem *> items;
diff --git a/src/plugins/texteditor/codestylepool.cpp b/src/plugins/texteditor/codestylepool.cpp
index 7c79f0964f..102ca1a225 100644
--- a/src/plugins/texteditor/codestylepool.cpp
+++ b/src/plugins/texteditor/codestylepool.cpp
@@ -40,9 +40,9 @@
using namespace TextEditor;
-static const char *codeStyleDataKey = "CodeStyleData";
-static const char *displayNameKey = "DisplayName";
-static const char *codeStyleDocKey = "QtCreatorCodeStyle";
+static const char codeStyleDataKey[] = "CodeStyleData";
+static const char displayNameKey[] = "DisplayName";
+static const char codeStyleDocKey[] = "QtCreatorCodeStyle";
namespace TextEditor {
namespace Internal {
@@ -115,7 +115,7 @@ CodeStylePool::~CodeStylePool()
QString CodeStylePool::settingsDir() const
{
- const QString suffix = d->m_factory ? d->m_factory->languageId() : QLatin1String("default");
+ const QString suffix = d->m_factory ? d->m_factory->languageId().toString() : QLatin1String("default");
return customCodeStylesPath().append(suffix);
}
diff --git a/src/plugins/texteditor/colorschemeedit.cpp b/src/plugins/texteditor/colorschemeedit.cpp
index c892b8f33a..b85bdf35a4 100644
--- a/src/plugins/texteditor/colorschemeedit.cpp
+++ b/src/plugins/texteditor/colorschemeedit.cpp
@@ -61,8 +61,9 @@ public:
void setFormatDescriptions(const FormatDescriptions *descriptions)
{
+ beginResetModel();
m_descriptions = descriptions;
- reset();
+ endResetModel();
}
void setBaseFont(const QFont &font)
diff --git a/src/plugins/texteditor/displaysettings.cpp b/src/plugins/texteditor/displaysettings.cpp
index 15fe1bae6c..609d7cfc7e 100644
--- a/src/plugins/texteditor/displaysettings.cpp
+++ b/src/plugins/texteditor/displaysettings.cpp
@@ -41,9 +41,12 @@ static const char displayFoldingMarkersKey[] = "DisplayFoldingMarkers";
static const char highlightCurrentLineKey[] = "HighlightCurrentLine2Key";
static const char highlightBlocksKey[] = "HighlightBlocksKey";
static const char animateMatchingParenthesesKey[] = "AnimateMatchingParenthesesKey";
+static const char highlightMatchingParenthesesKey[] = "HightlightMatchingParenthesesKey";
static const char markTextChangesKey[] = "MarkTextChanges";
static const char autoFoldFirstCommentKey[] = "AutoFoldFirstComment";
static const char centerCursorOnScrollKey[] = "CenterCursorOnScroll";
+static const char openLinksInNextSplitKey[] = "OpenLinksInNextSplitKey";
+static const char forceOpenLinksInNextSplitKey[] = "ForceOpenLinksInNextSplitKey";
static const char groupPostfix[] = "DisplaySettings";
namespace TextEditor {
@@ -58,9 +61,12 @@ DisplaySettings::DisplaySettings() :
m_highlightCurrentLine(false),
m_highlightBlocks(false),
m_animateMatchingParentheses(true),
+ m_highlightMatchingParentheses(true),
m_markTextChanges(true),
m_autoFoldFirstComment(true),
- m_centerCursorOnScroll(false)
+ m_centerCursorOnScroll(false),
+ m_openLinksInNextSplit(true),
+ m_forceOpenLinksInNextSplit(false)
{
}
@@ -79,9 +85,12 @@ void DisplaySettings::toSettings(const QString &category, QSettings *s) const
s->setValue(QLatin1String(highlightCurrentLineKey), m_highlightCurrentLine);
s->setValue(QLatin1String(highlightBlocksKey), m_highlightBlocks);
s->setValue(QLatin1String(animateMatchingParenthesesKey), m_animateMatchingParentheses);
+ s->setValue(QLatin1String(highlightMatchingParenthesesKey), m_highlightMatchingParentheses);
s->setValue(QLatin1String(markTextChangesKey), m_markTextChanges);
s->setValue(QLatin1String(autoFoldFirstCommentKey), m_autoFoldFirstComment);
s->setValue(QLatin1String(centerCursorOnScrollKey), m_centerCursorOnScroll);
+ s->setValue(QLatin1String(openLinksInNextSplitKey), m_openLinksInNextSplit);
+ s->setValue(QLatin1String(forceOpenLinksInNextSplitKey), m_forceOpenLinksInNextSplit);
s->endGroup();
}
@@ -103,9 +112,12 @@ void DisplaySettings::fromSettings(const QString &category, const QSettings *s)
m_highlightCurrentLine = s->value(group + QLatin1String(highlightCurrentLineKey), m_highlightCurrentLine).toBool();
m_highlightBlocks = s->value(group + QLatin1String(highlightBlocksKey), m_highlightBlocks).toBool();
m_animateMatchingParentheses = s->value(group + QLatin1String(animateMatchingParenthesesKey), m_animateMatchingParentheses).toBool();
+ m_highlightMatchingParentheses = s->value(group + QLatin1String(highlightMatchingParenthesesKey), m_highlightMatchingParentheses).toBool();
m_markTextChanges = s->value(group + QLatin1String(markTextChangesKey), m_markTextChanges).toBool();
m_autoFoldFirstComment = s->value(group + QLatin1String(autoFoldFirstCommentKey), m_autoFoldFirstComment).toBool();
m_centerCursorOnScroll = s->value(group + QLatin1String(centerCursorOnScrollKey), m_centerCursorOnScroll).toBool();
+ m_openLinksInNextSplit = s->value(group + QLatin1String(openLinksInNextSplitKey), m_openLinksInNextSplit).toBool();
+ m_forceOpenLinksInNextSplit = s->value(group + QLatin1String(forceOpenLinksInNextSplitKey), m_forceOpenLinksInNextSplit).toBool();
}
bool DisplaySettings::equals(const DisplaySettings &ds) const
@@ -119,9 +131,12 @@ bool DisplaySettings::equals(const DisplaySettings &ds) const
&& m_highlightCurrentLine == ds.m_highlightCurrentLine
&& m_highlightBlocks == ds.m_highlightBlocks
&& m_animateMatchingParentheses == ds.m_animateMatchingParentheses
+ && m_highlightMatchingParentheses == ds.m_highlightMatchingParentheses
&& m_markTextChanges == ds.m_markTextChanges
&& m_autoFoldFirstComment== ds.m_autoFoldFirstComment
&& m_centerCursorOnScroll == ds.m_centerCursorOnScroll
+ && m_openLinksInNextSplit == ds.m_openLinksInNextSplit
+ && m_forceOpenLinksInNextSplit == ds.m_forceOpenLinksInNextSplit
;
}
diff --git a/src/plugins/texteditor/displaysettings.h b/src/plugins/texteditor/displaysettings.h
index d6b8a91da4..991117f4bb 100644
--- a/src/plugins/texteditor/displaysettings.h
+++ b/src/plugins/texteditor/displaysettings.h
@@ -55,9 +55,12 @@ public:
bool m_highlightCurrentLine;
bool m_highlightBlocks;
bool m_animateMatchingParentheses;
+ bool m_highlightMatchingParentheses;
bool m_markTextChanges;
bool m_autoFoldFirstComment;
bool m_centerCursorOnScroll;
+ bool m_openLinksInNextSplit;
+ bool m_forceOpenLinksInNextSplit;
bool equals(const DisplaySettings &ds) const;
};
diff --git a/src/plugins/texteditor/displaysettingspage.cpp b/src/plugins/texteditor/displaysettingspage.cpp
index 8009fba9ec..ed3904db25 100644
--- a/src/plugins/texteditor/displaysettingspage.cpp
+++ b/src/plugins/texteditor/displaysettingspage.cpp
@@ -74,6 +74,7 @@ QWidget *DisplaySettingsPage::createPage(QWidget *parent)
QWidget *w = new QWidget(parent);
d->m_page = new Internal::Ui::DisplaySettingsPage;
d->m_page->setupUi(w);
+ connect(d->m_page->openLinksInNextSplit, SIGNAL(toggled(bool)), this, SLOT(updateForceOpenLinksInNextSplit(bool)));
settingsToUI();
if (d->m_searchKeywords.isEmpty()) {
QTextStream(&d->m_searchKeywords) << d->m_page->displayLineNumbers->text()
@@ -82,9 +83,12 @@ QWidget *DisplaySettingsPage::createPage(QWidget *parent)
<< ' ' << d->m_page->highlightBlocks->text()
<< ' ' << d->m_page->visualizeWhitespace->text()
<< ' ' << d->m_page->animateMatchingParentheses->text()
+ << ' ' << d->m_page->highlightMatchingParentheses->text()
<< ' ' << d->m_page->enableTextWrapping->text()
<< ' ' << d->m_page->autoFoldFirstComment->text()
- << ' ' << d->m_page->centerOnScroll->text();
+ << ' ' << d->m_page->centerOnScroll->text()
+ << ' ' << d->m_page->openLinksInNextSplit->text()
+ << ' ' << d->m_page->forceOpenLinksInNextSplit->text();
d->m_searchKeywords.remove(QLatin1Char('&'));
}
return w;
@@ -108,6 +112,13 @@ void DisplaySettingsPage::finish()
d->m_page = 0;
}
+void DisplaySettingsPage::updateForceOpenLinksInNextSplit(bool openLinksInNextSplitChecked)
+{
+ d->m_page->forceOpenLinksInNextSplit->setEnabled(openLinksInNextSplitChecked);
+ if (!openLinksInNextSplitChecked)
+ d->m_page->forceOpenLinksInNextSplit->setChecked(openLinksInNextSplitChecked);
+}
+
void DisplaySettingsPage::settingsFromUI(DisplaySettings &displaySettings) const
{
displaySettings.m_displayLineNumbers = d->m_page->displayLineNumbers->isChecked();
@@ -119,9 +130,12 @@ void DisplaySettingsPage::settingsFromUI(DisplaySettings &displaySettings) const
displaySettings.m_highlightCurrentLine = d->m_page->highlightCurrentLine->isChecked();
displaySettings.m_highlightBlocks = d->m_page->highlightBlocks->isChecked();
displaySettings.m_animateMatchingParentheses = d->m_page->animateMatchingParentheses->isChecked();
+ displaySettings.m_highlightMatchingParentheses = d->m_page->highlightMatchingParentheses->isChecked();
displaySettings.m_markTextChanges = d->m_page->markTextChanges->isChecked();
displaySettings.m_autoFoldFirstComment = d->m_page->autoFoldFirstComment->isChecked();
displaySettings.m_centerCursorOnScroll = d->m_page->centerOnScroll->isChecked();
+ displaySettings.m_openLinksInNextSplit = d->m_page->openLinksInNextSplit->isChecked();
+ displaySettings.m_forceOpenLinksInNextSplit = d->m_page->forceOpenLinksInNextSplit->isChecked();
}
void DisplaySettingsPage::settingsToUI()
@@ -136,9 +150,12 @@ void DisplaySettingsPage::settingsToUI()
d->m_page->highlightCurrentLine->setChecked(displaySettings.m_highlightCurrentLine);
d->m_page->highlightBlocks->setChecked(displaySettings.m_highlightBlocks);
d->m_page->animateMatchingParentheses->setChecked(displaySettings.m_animateMatchingParentheses);
+ d->m_page->highlightMatchingParentheses->setChecked(displaySettings.m_highlightMatchingParentheses);
d->m_page->markTextChanges->setChecked(displaySettings.m_markTextChanges);
d->m_page->autoFoldFirstComment->setChecked(displaySettings.m_autoFoldFirstComment);
d->m_page->centerOnScroll->setChecked(displaySettings.m_centerCursorOnScroll);
+ d->m_page->openLinksInNextSplit->setChecked(displaySettings.m_openLinksInNextSplit);
+ d->m_page->forceOpenLinksInNextSplit->setChecked(displaySettings.m_forceOpenLinksInNextSplit);
}
const DisplaySettings &DisplaySettingsPage::displaySettings() const
diff --git a/src/plugins/texteditor/displaysettingspage.h b/src/plugins/texteditor/displaysettingspage.h
index 19c5807c89..2b4886dd3e 100644
--- a/src/plugins/texteditor/displaysettingspage.h
+++ b/src/plugins/texteditor/displaysettingspage.h
@@ -41,7 +41,7 @@ class DisplaySettings;
class DisplaySettingsPageParameters
{
public:
- QString id;
+ Core::Id id;
QString displayName;
QString settingsPrefix;
};
@@ -65,6 +65,9 @@ public:
signals:
void displaySettingsChanged(const TextEditor::DisplaySettings &);
+private slots:
+ void updateForceOpenLinksInNextSplit(bool openLinksInNextSplitChecked);
+
private:
void settingsFromUI(DisplaySettings &displaySettings) const;
void settingsToUI();
diff --git a/src/plugins/texteditor/displaysettingspage.ui b/src/plugins/texteditor/displaysettingspage.ui
index c136ebaece..5053a8b103 100644
--- a/src/plugins/texteditor/displaysettingspage.ui
+++ b/src/plugins/texteditor/displaysettingspage.ui
@@ -6,11 +6,61 @@
<rect>
<x>0</x>
<y>0</y>
- <width>450</width>
- <height>288</height>
+ <width>501</width>
+ <height>323</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_3">
+ <item row="0" column="0">
+ <widget class="QGroupBox" name="groupBoxText">
+ <property name="title">
+ <string>Text Wrapping</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout">
+ <item row="0" column="0">
+ <widget class="QCheckBox" name="enableTextWrapping">
+ <property name="text">
+ <string>Enable text &amp;wrapping</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QCheckBox" name="showWrapColumn">
+ <property name="text">
+ <string>Display right &amp;margin at column:</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QSpinBox" name="wrapColumn">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="maximum">
+ <number>999</number>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ </item>
<item row="2" column="0">
<spacer name="verticalSpacer">
<property name="orientation">
@@ -30,24 +80,27 @@
<string>Display</string>
</property>
<layout class="QGridLayout" name="gridLayout_2">
- <item row="0" column="0">
- <widget class="QCheckBox" name="displayLineNumbers">
+ <item row="4" column="1">
+ <widget class="QCheckBox" name="highlightMatchingParentheses">
<property name="text">
- <string>Display line &amp;numbers</string>
+ <string>&amp;Highlight matching parentheses</string>
</property>
</widget>
</item>
- <item row="0" column="1">
- <widget class="QCheckBox" name="highlightCurrentLine">
+ <item row="2" column="0">
+ <widget class="QCheckBox" name="markTextChanges">
<property name="text">
- <string>Highlight current &amp;line</string>
+ <string>Mark &amp;text changes</string>
</property>
</widget>
</item>
- <item row="1" column="0">
- <widget class="QCheckBox" name="displayFoldingMarkers">
+ <item row="4" column="0">
+ <widget class="QCheckBox" name="visualizeWhitespace">
+ <property name="toolTip">
+ <string>Show tabs and spaces.</string>
+ </property>
<property name="text">
- <string>Display &amp;folding markers</string>
+ <string>&amp;Visualize whitespace</string>
</property>
</widget>
</item>
@@ -58,20 +111,24 @@
</property>
</widget>
</item>
- <item row="2" column="0">
- <widget class="QCheckBox" name="markTextChanges">
+ <item row="5" column="0">
+ <widget class="QCheckBox" name="centerOnScroll">
<property name="text">
- <string>Mark &amp;text changes</string>
+ <string>Center &amp;cursor on scroll</string>
</property>
</widget>
</item>
- <item row="4" column="0">
- <widget class="QCheckBox" name="visualizeWhitespace">
- <property name="toolTip">
- <string>Show tabs and spaces.</string>
+ <item row="1" column="0">
+ <widget class="QCheckBox" name="displayFoldingMarkers">
+ <property name="text">
+ <string>Display &amp;folding markers</string>
</property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QCheckBox" name="highlightCurrentLine">
<property name="text">
- <string>&amp;Visualize whitespace</string>
+ <string>Highlight current &amp;line</string>
</property>
</widget>
</item>
@@ -82,68 +139,52 @@
</property>
</widget>
</item>
- <item row="4" column="1">
- <widget class="QCheckBox" name="autoFoldFirstComment">
+ <item row="0" column="0">
+ <widget class="QCheckBox" name="displayLineNumbers">
<property name="text">
- <string>Auto-fold first &amp;comment</string>
+ <string>Display line &amp;numbers</string>
</property>
</widget>
</item>
- <item row="5" column="0">
- <widget class="QCheckBox" name="centerOnScroll">
+ <item row="6" column="0">
+ <widget class="QCheckBox" name="autoFoldFirstComment">
<property name="text">
- <string>Center &amp;cursor on scroll</string>
+ <string>Auto-fold first &amp;comment</string>
</property>
</widget>
</item>
- </layout>
- </widget>
- </item>
- <item row="0" column="0">
- <widget class="QGroupBox" name="groupBoxText">
- <property name="title">
- <string>Text Wrapping</string>
- </property>
- <layout class="QGridLayout" name="gridLayout">
- <item row="0" column="0">
- <widget class="QCheckBox" name="enableTextWrapping">
+ <item row="5" column="1">
+ <widget class="QCheckBox" name="openLinksInNextSplit">
<property name="text">
- <string>Enable text &amp;wrapping</string>
+ <string>Open Links in Another Split</string>
</property>
</widget>
</item>
- <item row="1" column="0">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <item>
- <widget class="QCheckBox" name="showWrapColumn">
- <property name="text">
- <string>Display right &amp;margin at column:</string>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QSpinBox" name="wrapColumn">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="maximum">
- <number>999</number>
- </property>
- </widget>
- </item>
+ <item row="6" column="1">
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
- <spacer name="horizontalSpacer">
+ <spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
+ <property name="sizeType">
+ <enum>QSizePolicy::Fixed</enum>
+ </property>
<property name="sizeHint" stdset="0">
<size>
- <width>40</width>
+ <width>20</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
+ <item>
+ <widget class="QCheckBox" name="forceOpenLinksInNextSplit">
+ <property name="text">
+ <string>Force Open Links in Next Split</string>
+ </property>
+ </widget>
+ </item>
</layout>
</item>
</layout>
diff --git a/src/plugins/texteditor/fontsettings.cpp b/src/plugins/texteditor/fontsettings.cpp
index 43ce075df9..919278b2fa 100644
--- a/src/plugins/texteditor/fontsettings.cpp
+++ b/src/plugins/texteditor/fontsettings.cpp
@@ -53,13 +53,13 @@ static const bool DEFAULT_ANTIALIAS = true;
#ifdef Q_OS_MAC
enum { DEFAULT_FONT_SIZE = 12 };
- static const char *DEFAULT_FONT_FAMILY = "Monaco";
+ static const char DEFAULT_FONT_FAMILY[] = "Monaco";
#elif defined(Q_OS_UNIX)
enum { DEFAULT_FONT_SIZE = 9 };
- static const char *DEFAULT_FONT_FAMILY = "Monospace";
+ static const char DEFAULT_FONT_FAMILY[] = "Monospace";
#else
enum { DEFAULT_FONT_SIZE = 10 };
- static const char *DEFAULT_FONT_FAMILY = "Courier";
+ static const char DEFAULT_FONT_FAMILY[] = "Courier";
#endif
} // anonymous namespace
@@ -132,7 +132,7 @@ bool FontSettings::fromSettings(const QString &category,
// Load color scheme from ini file
foreach (const FormatDescription &desc, descriptions) {
const TextStyle id = desc.id();
- const QString fmt = s->value(group + Constants::nameForStyle(id), QString()).toString();
+ const QString fmt = s->value(group + QLatin1String(Constants::nameForStyle(id)), QString()).toString();
Format format;
if (fmt.isEmpty()) {
format.setForeground(desc.foreground());
@@ -260,6 +260,12 @@ void FontSettings::setAntialias(bool antialias)
* Returns the format for the given font category.
*/
Format &FontSettings::formatFor(TextStyle category)
+
+{
+ return m_scheme.formatFor(category);
+}
+
+Format FontSettings::formatFor(TextStyle category) const
{
return m_scheme.formatFor(category);
}
diff --git a/src/plugins/texteditor/fontsettings.h b/src/plugins/texteditor/fontsettings.h
index a648f043cd..58c2b02bdd 100644
--- a/src/plugins/texteditor/fontsettings.h
+++ b/src/plugins/texteditor/fontsettings.h
@@ -85,6 +85,7 @@ public:
void setAntialias(bool antialias);
Format &formatFor(TextStyle category);
+ Format formatFor(TextStyle category) const;
QString colorSchemeFileName() const;
void setColorSchemeFileName(const QString &fileName);
diff --git a/src/plugins/texteditor/fontsettingspage.cpp b/src/plugins/texteditor/fontsettingspage.cpp
index 4c3d19775f..c36d39bd25 100644
--- a/src/plugins/texteditor/fontsettingspage.cpp
+++ b/src/plugins/texteditor/fontsettingspage.cpp
@@ -100,8 +100,9 @@ public:
void setColorSchemes(const QList<ColorSchemeEntry> &colorSchemes)
{
+ beginResetModel();
m_colorSchemes = colorSchemes;
- reset();
+ endResetModel();
}
const ColorSchemeEntry &colorSchemeAt(int index) const
@@ -116,13 +117,13 @@ class FontSettingsPagePrivate
{
public:
FontSettingsPagePrivate(const TextEditor::FormatDescriptions &fd,
- const QString &id,
+ Core::Id id,
const QString &displayName,
const QString &category);
~FontSettingsPagePrivate();
public:
- const QString m_id;
+ const Core::Id m_id;
const QString m_displayName;
const QString m_settingsGroup;
@@ -173,7 +174,7 @@ static QString createColorSchemeFileName(const QString &pattern)
// ------- FontSettingsPagePrivate
FontSettingsPagePrivate::FontSettingsPagePrivate(const TextEditor::FormatDescriptions &fd,
- const QString &id,
+ Core::Id id,
const QString &displayName,
const QString &category) :
m_id(id),
@@ -247,18 +248,16 @@ QColor FormatDescription::foreground() const
{
if (m_id == C_LINE_NUMBER) {
const QColor bg = QApplication::palette().background().color();
- if (bg.value() < 128) {
+ if (bg.value() < 128)
return QApplication::palette().foreground().color();
- } else {
+ else
return QApplication::palette().dark().color();
- }
} else if (m_id == C_CURRENT_LINE_NUMBER) {
const QColor bg = QApplication::palette().background().color();
- if (bg.value() < 128) {
+ if (bg.value() < 128)
return QApplication::palette().foreground().color();
- } else {
+ else
return m_format.foreground();
- }
} else if (m_id == C_OCCURRENCES_UNUSED) {
return Qt::darkYellow;
} else if (m_id == C_PARENTHESES) {
@@ -314,10 +313,10 @@ QColor FormatDescription::background() const
// ------------ FontSettingsPage
FontSettingsPage::FontSettingsPage(const FormatDescriptions &fd,
- const QString &id,
+ Core::Id id,
QObject *parent) :
TextEditorOptionsPage(parent),
- d_ptr(new FontSettingsPagePrivate(fd, id, tr("Font && Colors"), category()))
+ d_ptr(new FontSettingsPagePrivate(fd, id, tr("Font && Colors"), category().toString()))
{
setId(d_ptr->m_id);
setDisplayName(d_ptr->m_displayName);
diff --git a/src/plugins/texteditor/fontsettingspage.h b/src/plugins/texteditor/fontsettingspage.h
index a59d29f8d6..5cbf09d144 100644
--- a/src/plugins/texteditor/fontsettingspage.h
+++ b/src/plugins/texteditor/fontsettingspage.h
@@ -88,9 +88,7 @@ class TEXTEDITOR_EXPORT FontSettingsPage : public TextEditorOptionsPage
Q_OBJECT
public:
- FontSettingsPage(const FormatDescriptions &fd,
- const QString &id,
- QObject *parent = 0);
+ FontSettingsPage(const FormatDescriptions &fd, Core::Id id, QObject *parent = 0);
~FontSettingsPage();
diff --git a/src/plugins/texteditor/generichighlighter/highlightdefinitionhandler.cpp b/src/plugins/texteditor/generichighlighter/highlightdefinitionhandler.cpp
index 629ceaffa7..b359240406 100644
--- a/src/plugins/texteditor/generichighlighter/highlightdefinitionhandler.cpp
+++ b/src/plugins/texteditor/generichighlighter/highlightdefinitionhandler.cpp
@@ -135,55 +135,54 @@ bool HighlightDefinitionHandler::startElement(const QString &,
const QString &qName,
const QXmlAttributes &atts)
{
- if (qName == kList) {
+ if (qName == kList)
listElementStarted(atts);
- } else if (qName == kItem) {
+ else if (qName == kItem)
itemElementStarted();
- } else if (qName == kContext) {
+ else if (qName == kContext)
contextElementStarted(atts);
- } else if (qName == kItemData) {
+ else if (qName == kItemData)
itemDataElementStarted(atts);
- } else if (qName == kComment) {
+ else if (qName == kComment)
commentElementStarted(atts);
- } else if (qName == kKeywords) {
+ else if (qName == kKeywords)
keywordsElementStarted(atts);
- } else if (qName == kFolding) {
+ else if (qName == kFolding)
foldingElementStarted(atts);
- } else if (qName == kDetectChar) {
+ else if (qName == kDetectChar)
detectCharStarted(atts);
- } else if (qName == kDetect2Chars) {
+ else if (qName == kDetect2Chars)
detect2CharsStarted(atts);
- } else if (qName == kAnyChar) {
+ else if (qName == kAnyChar)
anyCharStarted(atts);
- } else if (qName == kStringDetect) {
+ else if (qName == kStringDetect)
stringDetectedStarted(atts);
- } else if (qName == kRegExpr) {
+ else if (qName == kRegExpr)
regExprStarted(atts);
- } else if (qName == kKeyword) {
+ else if (qName == kKeyword)
keywordStarted(atts);
- } else if (qName == kInt) {
+ else if (qName == kInt)
intStarted(atts);
- } else if (qName == kFloat) {
+ else if (qName == kFloat)
floatStarted(atts);
- } else if (qName == kHlCOct) {
+ else if (qName == kHlCOct)
hlCOctStarted(atts);
- } else if (qName == kHlCHex) {
+ else if (qName == kHlCHex)
hlCHexStarted(atts);
- } else if (qName == kHlCStringChar) {
+ else if (qName == kHlCStringChar)
hlCStringCharStarted(atts);
- } else if (qName == kHlCChar) {
+ else if (qName == kHlCChar)
hlCCharStarted(atts);
- } else if (qName == kRangeDetect) {
+ else if (qName == kRangeDetect)
rangeDetectStarted(atts);
- } else if (qName == kLineContinue) {
+ else if (qName == kLineContinue)
lineContinue(atts);
- } else if (qName == kIncludeRules) {
+ else if (qName == kIncludeRules)
includeRulesStarted(atts);
- } else if (qName == kDetectSpaces) {
+ else if (qName == kDetectSpaces)
detectSpacesStarted(atts);
- } else if (qName == kDetectIdentifier) {
+ else if (qName == kDetectIdentifier)
detectIdentifier(atts);
- }
return true;
}
@@ -351,7 +350,7 @@ void HighlightDefinitionHandler::keywordStarted(const QXmlAttributes &atts)
}
void HighlightDefinitionHandler::intStarted(const QXmlAttributes &atts)
-{
+{
ruleElementStarted(atts, QSharedPointer<Rule>(new IntRule));
}
@@ -361,17 +360,17 @@ void HighlightDefinitionHandler::floatStarted(const QXmlAttributes &atts)
}
void HighlightDefinitionHandler::hlCOctStarted(const QXmlAttributes &atts)
-{
+{
ruleElementStarted(atts, QSharedPointer<Rule>(new HlCOctRule));
}
void HighlightDefinitionHandler::hlCHexStarted(const QXmlAttributes &atts)
-{
+{
ruleElementStarted(atts, QSharedPointer<Rule>(new HlCHexRule));
}
void HighlightDefinitionHandler::hlCStringCharStarted(const QXmlAttributes &atts)
-{
+{
ruleElementStarted(atts, QSharedPointer<Rule>(new HlCStringCharRule));
}
@@ -389,7 +388,7 @@ void HighlightDefinitionHandler::rangeDetectStarted(const QXmlAttributes &atts)
}
void HighlightDefinitionHandler::lineContinue(const QXmlAttributes &atts)
-{
+{
ruleElementStarted(atts, QSharedPointer<Rule>(new LineContinueRule));
}
diff --git a/src/plugins/texteditor/generichighlighter/highlighter.h b/src/plugins/texteditor/generichighlighter/highlighter.h
index ad853c2315..81a7dd37ff 100644
--- a/src/plugins/texteditor/generichighlighter/highlighter.h
+++ b/src/plugins/texteditor/generichighlighter/highlighter.h
@@ -30,8 +30,8 @@
#ifndef HIGHLIGHTER_H
#define HIGHLIGHTER_H
-#include "basetextdocumentlayout.h"
-#include "syntaxhighlighter.h"
+#include "../basetextdocumentlayout.h"
+#include "../syntaxhighlighter.h"
#include <QString>
#include <QVector>
diff --git a/src/plugins/texteditor/generichighlighter/highlightersettingspage.cpp b/src/plugins/texteditor/generichighlighter/highlightersettingspage.cpp
index 2646df9f79..3f093a7884 100644
--- a/src/plugins/texteditor/generichighlighter/highlightersettingspage.cpp
+++ b/src/plugins/texteditor/generichighlighter/highlightersettingspage.cpp
@@ -43,11 +43,11 @@ using namespace Internal;
struct HighlighterSettingsPage::HighlighterSettingsPagePrivate
{
- explicit HighlighterSettingsPagePrivate(const QString &id);
+ explicit HighlighterSettingsPagePrivate(Core::Id id);
void ensureInitialized();
bool m_initialized;
- const QString m_id;
+ const Core::Id m_id;
const QString m_displayName;
const QString m_settingsPrefix;
@@ -59,7 +59,7 @@ struct HighlighterSettingsPage::HighlighterSettingsPagePrivate
};
HighlighterSettingsPage::HighlighterSettingsPagePrivate::
-HighlighterSettingsPagePrivate(const QString &id) :
+HighlighterSettingsPagePrivate(Core::Id id) :
m_initialized(false),
m_id(id),
m_displayName(tr("Generic Highlighter")),
@@ -75,7 +75,7 @@ void HighlighterSettingsPage::HighlighterSettingsPagePrivate::ensureInitialized(
m_settings.fromSettings(m_settingsPrefix, Core::ICore::settings());
}
-HighlighterSettingsPage::HighlighterSettingsPage(const QString &id, QObject *parent) :
+HighlighterSettingsPage::HighlighterSettingsPage(Core::Id id, QObject *parent) :
TextEditorOptionsPage(parent),
m_requestMimeTypeRegistration(false),
m_d(new HighlighterSettingsPagePrivate(id))
diff --git a/src/plugins/texteditor/generichighlighter/highlightersettingspage.h b/src/plugins/texteditor/generichighlighter/highlightersettingspage.h
index 82da3b0605..770ef4c4cf 100644
--- a/src/plugins/texteditor/generichighlighter/highlightersettingspage.h
+++ b/src/plugins/texteditor/generichighlighter/highlightersettingspage.h
@@ -30,7 +30,7 @@
#ifndef HIGHLIGHTERSETTINGSPAGE_H
#define HIGHLIGHTERSETTINGSPAGE_H
-#include "texteditoroptionspage.h"
+#include "../texteditoroptionspage.h"
QT_BEGIN_NAMESPACE
template <class> class QList;
@@ -49,7 +49,7 @@ class HighlighterSettingsPage : public TextEditorOptionsPage
Q_OBJECT
public:
- HighlighterSettingsPage(const QString &id, QObject *parent);
+ HighlighterSettingsPage(Core::Id id, QObject *parent);
~HighlighterSettingsPage();
QWidget *createPage(QWidget *parent);
diff --git a/src/plugins/texteditor/generichighlighter/keywordlist.cpp b/src/plugins/texteditor/generichighlighter/keywordlist.cpp
index 020d5cd949..486d1cb5e0 100644
--- a/src/plugins/texteditor/generichighlighter/keywordlist.cpp
+++ b/src/plugins/texteditor/generichighlighter/keywordlist.cpp
@@ -35,7 +35,7 @@ using namespace Internal;
void KeywordList::addKeyword(const QString &keyword)
{
if (keyword.isEmpty())
- return;
+ return;
m_keywords.insert(keyword);
}
diff --git a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
index 85f8b14714..7de036c564 100644
--- a/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
+++ b/src/plugins/texteditor/generichighlighter/managedefinitionsdialog.cpp
@@ -54,7 +54,7 @@ ManageDefinitionsDialog::ManageDefinitionsDialog(
m_definitionsMetaData(metaDataList),
m_path(path)
{
- ui.setupUi(this);
+ ui.setupUi(this);
ui.definitionsTable->setHorizontalHeaderLabels(
QStringList() << tr("Name") << tr("Installed") << tr("Available"));
ui.definitionsTable->horizontalHeader()->setResizeMode(0, QHeaderView::Stretch);
diff --git a/src/plugins/texteditor/generichighlighter/rule.cpp b/src/plugins/texteditor/generichighlighter/rule.cpp
index b350f3435a..53cce34bc4 100644
--- a/src/plugins/texteditor/generichighlighter/rule.cpp
+++ b/src/plugins/texteditor/generichighlighter/rule.cpp
@@ -163,7 +163,7 @@ bool Rule::charPredicateMatchSucceed(const QString &text,
}
bool Rule::matchSucceed(const QString &text, const int length, ProgressData *progress)
-{
+{
if (m_firstNonSpace && !progress->isOnlySpacesSoFar())
return false;
diff --git a/src/plugins/texteditor/generichighlighter/specificrules.h b/src/plugins/texteditor/generichighlighter/specificrules.h
index b4af493598..25e4e42195 100644
--- a/src/plugins/texteditor/generichighlighter/specificrules.h
+++ b/src/plugins/texteditor/generichighlighter/specificrules.h
@@ -124,7 +124,7 @@ public:
void setPattern(const QString &pattern);
void setInsensitive(const QString &insensitive);
- void setMinimal(const QString &minimal);
+ void setMinimal(const QString &minimal);
private:
virtual bool doMatchSucceed(const QString &text,
diff --git a/src/plugins/texteditor/icodestylepreferences.cpp b/src/plugins/texteditor/icodestylepreferences.cpp
index e911098120..490877f910 100644
--- a/src/plugins/texteditor/icodestylepreferences.cpp
+++ b/src/plugins/texteditor/icodestylepreferences.cpp
@@ -39,7 +39,7 @@
using namespace TextEditor;
-static const char *currentPreferencesKey = "CurrentPreferences";
+static const char currentPreferencesKey[] = "CurrentPreferences";
namespace TextEditor {
namespace Internal {
@@ -114,9 +114,8 @@ void ICodeStylePreferences::setTabSettings(const TabSettings &settings)
d->m_tabSettings = settings;
emit tabSettingsChanged(d->m_tabSettings);
- if (!currentDelegate()) {
+ if (!currentDelegate())
emit currentTabSettingsChanged(d->m_tabSettings);
- }
}
TabSettings ICodeStylePreferences::tabSettings() const
diff --git a/src/plugins/texteditor/icodestylepreferencesfactory.h b/src/plugins/texteditor/icodestylepreferencesfactory.h
index 3048e931c3..d4fd82fb31 100644
--- a/src/plugins/texteditor/icodestylepreferencesfactory.h
+++ b/src/plugins/texteditor/icodestylepreferencesfactory.h
@@ -32,6 +32,8 @@
#include "texteditor_global.h"
+#include <coreplugin/id.h>
+
#include <QObject>
namespace TextEditor {
@@ -47,7 +49,7 @@ class TEXTEDITOR_EXPORT ICodeStylePreferencesFactory : public QObject
public:
explicit ICodeStylePreferencesFactory(QObject *parent = 0);
- virtual QString languageId() = 0;
+ virtual Core::Id languageId() = 0;
virtual QString displayName() = 0;
virtual ICodeStylePreferences *createCodeStyle() const = 0;
virtual QWidget *createEditor(ICodeStylePreferences *preferences, QWidget *parent) const = 0;
diff --git a/src/plugins/texteditor/itexteditor.h b/src/plugins/texteditor/itexteditor.h
index 20362d98d4..556d309180 100644
--- a/src/plugins/texteditor/itexteditor.h
+++ b/src/plugins/texteditor/itexteditor.h
@@ -116,6 +116,7 @@ signals:
void markContextMenuRequested(TextEditor::ITextEditor *editor, int line, QMenu *menu);
void tooltipOverrideRequested(TextEditor::ITextEditor *editor, const QPoint &globalPos, int position, bool *handled);
void tooltipRequested(TextEditor::ITextEditor *editor, const QPoint &globalPos, int position);
+ void markTooltipRequested(TextEditor::ITextEditor *editor, const QPoint &globalPos, int line);
void contextHelpIdRequested(TextEditor::ITextEditor *editor, int position);
};
diff --git a/src/plugins/texteditor/itextmark.cpp b/src/plugins/texteditor/itextmark.cpp
index dd2ee94065..7582739da4 100644
--- a/src/plugins/texteditor/itextmark.cpp
+++ b/src/plugins/texteditor/itextmark.cpp
@@ -80,7 +80,7 @@ ITextMark::Priority ITextMark::priority() const
return m_priority;
}
-bool ITextMark::visible() const
+bool ITextMark::isVisible() const
{
return m_visible;
}
@@ -102,7 +102,7 @@ void ITextMark::setWidthFactor(double factor)
m_widthFactor = factor;
}
-bool ITextMark::clickable() const
+bool ITextMark::isClickable() const
{
return false;
}
@@ -110,6 +110,16 @@ bool ITextMark::clickable() const
void ITextMark::clicked()
{}
+bool ITextMark::isDraggable() const
+{
+ return false;
+}
+
+void ITextMark::dragToLine(int lineNumber)
+{
+ Q_UNUSED(lineNumber);
+}
+
ITextMarkable *ITextMark::markableInterface() const
{
return m_markableInterface;
diff --git a/src/plugins/texteditor/itextmark.h b/src/plugins/texteditor/itextmark.h
index 9dc0dc3421..3f5693bb4f 100644
--- a/src/plugins/texteditor/itextmark.h
+++ b/src/plugins/texteditor/itextmark.h
@@ -74,16 +74,18 @@ public:
virtual void updateLineNumber(int lineNumber);
virtual void updateBlock(const QTextBlock &block);
virtual void removedFromEditor();
- virtual bool clickable() const;
+ virtual bool isClickable() const;
virtual void clicked();
+ virtual bool isDraggable() const;
+ virtual void dragToLine(int lineNumber);
void setIcon(const QIcon &icon);
// call this if the icon has changed.
void updateMarker();
Priority priority() const;
void setPriority(Priority prioriy);
- bool visible() const;
- void setVisible(bool visible);
+ bool isVisible() const;
+ void setVisible(bool isVisible);
double widthFactor() const;
void setWidthFactor(double factor);
diff --git a/src/plugins/texteditor/linenumberfilter.cpp b/src/plugins/texteditor/linenumberfilter.cpp
index 7a3bc8b85c..80ab0eb288 100644
--- a/src/plugins/texteditor/linenumberfilter.cpp
+++ b/src/plugins/texteditor/linenumberfilter.cpp
@@ -44,6 +44,9 @@ using namespace TextEditor::Internal;
LineNumberFilter::LineNumberFilter(QObject *parent)
: ILocatorFilter(parent)
{
+ setId("Line in current document");
+ setDisplayName(tr("Line in Current Document"));
+ setPriority(High);
setShortcutString(QString(QLatin1Char('l')));
setIncludedByDefault(true);
}
diff --git a/src/plugins/texteditor/linenumberfilter.h b/src/plugins/texteditor/linenumberfilter.h
index fc6ed951b7..f5539ca401 100644
--- a/src/plugins/texteditor/linenumberfilter.h
+++ b/src/plugins/texteditor/linenumberfilter.h
@@ -49,9 +49,6 @@ class LineNumberFilter : public Locator::ILocatorFilter
public:
explicit LineNumberFilter(QObject *parent = 0);
- QString displayName() const { return tr("Line in Current Document"); }
- QString id() const { return QLatin1String("Line in current document"); }
- Locator::ILocatorFilter::Priority priority() const { return Locator::ILocatorFilter::High; }
QList<Locator::FilterEntry> matchesFor(QFutureInterface<Locator::FilterEntry> &future, const QString &entry);
void accept(Locator::FilterEntry selection) const;
void refresh(QFutureInterface<void> &) {}
diff --git a/src/plugins/texteditor/outlinefactory.cpp b/src/plugins/texteditor/outlinefactory.cpp
index 07ae321fe6..f8322c5ec3 100644
--- a/src/plugins/texteditor/outlinefactory.cpp
+++ b/src/plugins/texteditor/outlinefactory.cpp
@@ -106,9 +106,8 @@ void OutlineWidgetStack::restoreSettings(int position)
const bool toggleSync = settings->value(outLineKey(position), true).toBool();
toggleSyncButton()->setChecked(toggleSync);
- if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
+ if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
outlineWidget->restoreSettings(position);
- }
}
void OutlineWidgetStack::saveSettings(int position)
@@ -118,9 +117,8 @@ void OutlineWidgetStack::saveSettings(int position)
QSettings *settings = Core::ICore::settings();
settings->setValue(outLineKey(position), toggleSyncButton()->isEnabled());
- if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget())) {
+ if (IOutlineWidget *outlineWidget = qobject_cast<IOutlineWidget*>(currentWidget()))
outlineWidget->saveSettings(position);
- }
}
bool OutlineWidgetStack::isCursorSynchronized() const
diff --git a/src/plugins/texteditor/plaintexteditor.cpp b/src/plugins/texteditor/plaintexteditor.cpp
index bb37d01704..4adb6e8bac 100644
--- a/src/plugins/texteditor/plaintexteditor.cpp
+++ b/src/plugins/texteditor/plaintexteditor.cpp
@@ -51,9 +51,11 @@
#include <QDebug>
-using namespace TextEditor;
+using namespace Core;
using namespace TextEditor::Internal;
+namespace TextEditor {
+
PlainTextEditor::PlainTextEditor(PlainTextEditorWidget *editor)
: BaseTextEditor(editor)
{
@@ -90,7 +92,7 @@ Core::IEditor *PlainTextEditor::duplicate(QWidget *parent)
Core::Id PlainTextEditor::id() const
{
- return Core::Constants::K_DEFAULT_TEXT_EDITOR_ID;
+ return Core::Id(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
}
void PlainTextEditorWidget::unCommentSelection()
@@ -218,11 +220,13 @@ QString PlainTextEditorWidget::findDefinitionId(const Core::MimeType &mimeType,
void PlainTextEditorWidget::acceptMissingSyntaxDefinitionInfo()
{
- Core::ICore::showOptionsDialog(QLatin1String(Constants::TEXT_EDITOR_SETTINGS_CATEGORY),
- QLatin1String(Constants::TEXT_EDITOR_HIGHLIGHTER_SETTINGS));
+ ICore::showOptionsDialog(Constants::TEXT_EDITOR_SETTINGS_CATEGORY,
+ Constants::TEXT_EDITOR_HIGHLIGHTER_SETTINGS);
}
void PlainTextEditorWidget::ignoreMissingSyntaxDefinitionInfo()
{
m_ignoreMissingSyntaxDefinition = true;
}
+
+} // namespace TextEditor
diff --git a/src/plugins/texteditor/plaintexteditorfactory.cpp b/src/plugins/texteditor/plaintexteditorfactory.cpp
index 4a096e105b..32d73f64df 100644
--- a/src/plugins/texteditor/plaintexteditorfactory.cpp
+++ b/src/plugins/texteditor/plaintexteditorfactory.cpp
@@ -65,7 +65,7 @@ PlainTextEditorFactory::~PlainTextEditorFactory()
Core::Id PlainTextEditorFactory::id() const
{
- return Core::Constants::K_DEFAULT_TEXT_EDITOR_ID;
+ return Core::Id(Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
}
QString PlainTextEditorFactory::displayName() const
@@ -91,7 +91,7 @@ void PlainTextEditorFactory::updateEditorInfoBar(Core::IEditor *editor)
if (!file)
return;
PlainTextEditorWidget *textEditor = static_cast<PlainTextEditorWidget *>(editorEditable->editorWidget());
- const QString infoSyntaxDefinition = QLatin1String(Constants::INFO_SYNTAX_DEFINITION);
+ Core::Id infoSyntaxDefinition(Constants::INFO_SYNTAX_DEFINITION);
if (textEditor->isMissingSyntaxDefinition() &&
!textEditor->ignoreMissingSyntaxDefinition() &&
TextEditorSettings::instance()->highlighterSettings().alertWhenNoDefinition()) {
diff --git a/src/plugins/texteditor/quickfix.h b/src/plugins/texteditor/quickfix.h
index dc9f1188c1..d4317aab6c 100644
--- a/src/plugins/texteditor/quickfix.h
+++ b/src/plugins/texteditor/quickfix.h
@@ -90,6 +90,9 @@ private:
QString _description;
};
+typedef QList<QuickFixOperation::Ptr> QuickFixOperations;
+typedef QSharedPointer<const IAssistInterface> QuickFixInterface;
+
/*!
The QuickFixFactory is responsible for generating QuickFixOperation s which are
applicable to the given QuickFixState.
@@ -107,10 +110,9 @@ class TEXTEDITOR_EXPORT QuickFixFactory: public QObject
public:
QuickFixFactory(QObject *parent = 0);
- virtual ~QuickFixFactory();
+ ~QuickFixFactory();
- virtual QList<QuickFixOperation::Ptr>
- matchingOperations(const QSharedPointer<const IAssistInterface> &interface) = 0;
+ virtual void matchingOperations(const QuickFixInterface &interface, QuickFixOperations &result) = 0;
};
} // namespace TextEditor
diff --git a/src/plugins/texteditor/refactoroverlay.cpp b/src/plugins/texteditor/refactoroverlay.cpp
index e8d58ac4c6..e2d729cbf6 100644
--- a/src/plugins/texteditor/refactoroverlay.cpp
+++ b/src/plugins/texteditor/refactoroverlay.cpp
@@ -53,16 +53,15 @@ void RefactorOverlay::paint(QPainter *painter, const QRect &clip)
paintMarker(m_markers.at(i), painter, clip);
}
- if (BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(m_editor->document()->documentLayout())) {
+ if (BaseTextDocumentLayout *documentLayout = qobject_cast<BaseTextDocumentLayout*>(m_editor->document()->documentLayout()))
documentLayout->setRequiredWidth(m_maxWidth);
- }
}
RefactorMarker RefactorOverlay::markerAt(const QPoint &pos) const
{
QPointF offset = m_editor->contentOffset();
- foreach(const RefactorMarker &marker, m_markers) {
+ foreach (const RefactorMarker &marker, m_markers) {
if (marker.rect.translated(offset.toPoint()).contains(pos))
return marker;
}
diff --git a/src/plugins/texteditor/snippets/snippeteditor.cpp b/src/plugins/texteditor/snippets/snippeteditor.cpp
index 032afe0b78..f6093fb9b3 100644
--- a/src/plugins/texteditor/snippets/snippeteditor.cpp
+++ b/src/plugins/texteditor/snippets/snippeteditor.cpp
@@ -53,7 +53,7 @@ SnippetEditor::SnippetEditor(SnippetEditorWidget *editor)
Core::Id SnippetEditor::id() const
{
- return Constants::SNIPPET_EDITOR_ID;
+ return Core::Id(Constants::SNIPPET_EDITOR_ID);
}
SnippetEditorWidget::SnippetEditorWidget(QWidget *parent) : BaseTextEditorWidget(parent)
diff --git a/src/plugins/texteditor/snippets/snippetssettingspage.cpp b/src/plugins/texteditor/snippets/snippetssettingspage.cpp
index 116e2dcac3..a4e95023c1 100644
--- a/src/plugins/texteditor/snippets/snippetssettingspage.cpp
+++ b/src/plugins/texteditor/snippets/snippetssettingspage.cpp
@@ -164,8 +164,9 @@ QVariant SnippetsTableModel::headerData(int section, Qt::Orientation orientation
void SnippetsTableModel::load(const QString &groupId)
{
+ beginResetModel();
m_activeGroupId = groupId;
- reset();
+ endResetModel();
}
QList<QString> SnippetsTableModel::groupIds() const
@@ -218,14 +219,16 @@ void SnippetsTableModel::revertBuitInSnippet(const QModelIndex &modelIndex)
void SnippetsTableModel::restoreRemovedBuiltInSnippets()
{
+ beginResetModel();
m_collection->restoreRemovedSnippets(m_activeGroupId);
- reset();
+ endResetModel();
}
void SnippetsTableModel::resetSnippets()
{
+ beginResetModel();
m_collection->reset(m_activeGroupId);
- reset();
+ endResetModel();
}
void SnippetsTableModel::replaceSnippet(const Snippet &snippet, const QModelIndex &modelIndex)
@@ -265,10 +268,10 @@ class SnippetsSettingsPagePrivate : public QObject
{
Q_OBJECT
public:
- SnippetsSettingsPagePrivate(const QString &id);
+ SnippetsSettingsPagePrivate(Core::Id id);
~SnippetsSettingsPagePrivate() { delete m_model; }
- const QString &id() const { return m_id; }
+ Core::Id id() const { return m_id; }
const QString &displayName() const { return m_displayName; }
bool isKeyword(const QString &s) const { return m_keywords.contains(s, Qt::CaseInsensitive); }
void configureUi(QWidget *parent);
@@ -298,7 +301,7 @@ private:
bool settingsChanged() const;
void writeSettings();
- const QString m_id;
+ const Core::Id m_id;
const QString m_displayName;
const QString m_settingsPrefix;
SnippetsTableModel *m_model;
@@ -308,7 +311,7 @@ private:
Ui::SnippetsSettingsPage m_ui;
};
-SnippetsSettingsPagePrivate::SnippetsSettingsPagePrivate(const QString &id) :
+SnippetsSettingsPagePrivate::SnippetsSettingsPagePrivate(Core::Id id) :
m_id(id),
m_displayName(tr("Snippets")),
m_settingsPrefix(QLatin1String("Text")),
@@ -554,7 +557,7 @@ void SnippetsSettingsPagePrivate::decorateEditors(const TextEditor::FontSettings
}
// SnippetsSettingsPage
-SnippetsSettingsPage::SnippetsSettingsPage(const QString &id, QObject *parent) :
+SnippetsSettingsPage::SnippetsSettingsPage(Core::Id id, QObject *parent) :
TextEditorOptionsPage(parent),
d(new SnippetsSettingsPagePrivate(id))
{
diff --git a/src/plugins/texteditor/snippets/snippetssettingspage.h b/src/plugins/texteditor/snippets/snippetssettingspage.h
index 5d66d9d7d8..04737b71d3 100644
--- a/src/plugins/texteditor/snippets/snippetssettingspage.h
+++ b/src/plugins/texteditor/snippets/snippetssettingspage.h
@@ -30,7 +30,7 @@
#ifndef SNIPPETSSETTINGSPAGE_H
#define SNIPPETSSETTINGSPAGE_H
-#include "texteditoroptionspage.h"
+#include "../texteditoroptionspage.h"
namespace TextEditor {
namespace Internal {
@@ -42,7 +42,7 @@ class SnippetsSettingsPage : public TextEditorOptionsPage
Q_OBJECT
public:
- SnippetsSettingsPage(const QString &id, QObject *parent);
+ SnippetsSettingsPage(Core::Id id, QObject *parent);
~SnippetsSettingsPage();
bool matches(const QString &s) const;
diff --git a/src/plugins/texteditor/storagesettings.cpp b/src/plugins/texteditor/storagesettings.cpp
index dd14719f4b..0616d80528 100644
--- a/src/plugins/texteditor/storagesettings.cpp
+++ b/src/plugins/texteditor/storagesettings.cpp
@@ -36,11 +36,11 @@
namespace TextEditor {
-static const char * const cleanWhitespaceKey = "cleanWhitespace";
-static const char * const inEntireDocumentKey = "inEntireDocument";
-static const char * const addFinalNewLineKey = "addFinalNewLine";
-static const char * const cleanIndentationKey = "cleanIndentation";
-static const char * const groupPostfix = "StorageSettings";
+static const char cleanWhitespaceKey[] = "cleanWhitespace";
+static const char inEntireDocumentKey[] = "inEntireDocument";
+static const char addFinalNewLineKey[] = "addFinalNewLine";
+static const char cleanIndentationKey[] = "cleanIndentation";
+static const char groupPostfix[] = "StorageSettings";
StorageSettings::StorageSettings()
: m_cleanWhitespace(true),
diff --git a/src/plugins/texteditor/syntaxhighlighter.cpp b/src/plugins/texteditor/syntaxhighlighter.cpp
index ab0df28139..90f2e272e0 100644
--- a/src/plugins/texteditor/syntaxhighlighter.cpp
+++ b/src/plugins/texteditor/syntaxhighlighter.cpp
@@ -40,6 +40,8 @@
#include <qtextedit.h>
#include <qtimer.h>
+#include <math.h>
+
using namespace TextEditor;
class TextEditor::SyntaxHighlighterPrivate
@@ -755,4 +757,38 @@ void SyntaxHighlighter::setExtraAdditionalFormats(const QTextBlock& block,
d->inReformatBlocks = wasInReformatBlocks;
}
+/* Generate at least n different colors for highlighting, excluding background
+ * color. */
+
+QList<QColor> SyntaxHighlighter::generateColors(int n, const QColor &background)
+{
+ QList<QColor> result;
+ // Assign a color gradient. Generate a sufficient number of colors
+ // by using ceil and looping from 0..step.
+ const double oneThird = 1.0 / 3.0;
+ const int step = qRound(ceil(pow(double(n), oneThird)));
+ result.reserve(step * step * step);
+ const int factor = 255 / step;
+ const int half = factor / 2;
+ const int bgRed = background.red();
+ const int bgGreen = background.green();
+ const int bgBlue = background.blue();
+ for (int r = step; r >= 0; --r) {
+ const int red = r * factor;
+ if (bgRed - half > red || bgRed + half <= red) {
+ for (int g = step; g >= 0; --g) {
+ const int green = g * factor;
+ if (bgGreen - half > green || bgGreen + half <= green) {
+ for (int b = step; b >= 0 ; --b) {
+ const int blue = b * factor;
+ if (bgBlue - half > blue || bgBlue + half <= blue)
+ result.append(QColor(red, green, blue));
+ }
+ }
+ }
+ }
+ }
+ return result;
+}
+
#include "moc_syntaxhighlighter.cpp"
diff --git a/src/plugins/texteditor/syntaxhighlighter.h b/src/plugins/texteditor/syntaxhighlighter.h
index 3a4fe0db0b..2f3ad075ae 100644
--- a/src/plugins/texteditor/syntaxhighlighter.h
+++ b/src/plugins/texteditor/syntaxhighlighter.h
@@ -66,6 +66,8 @@ public:
void setExtraAdditionalFormats(const QTextBlock& block, const QList<QTextLayout::FormatRange> &formats);
+ static QList<QColor> generateColors(int n, const QColor &background);
+
public Q_SLOTS:
void rehighlight();
void rehighlightBlock(const QTextBlock &block);
diff --git a/src/plugins/texteditor/tabsettings.cpp b/src/plugins/texteditor/tabsettings.cpp
index e46c45a415..733e06dc4d 100644
--- a/src/plugins/texteditor/tabsettings.cpp
+++ b/src/plugins/texteditor/tabsettings.cpp
@@ -243,11 +243,10 @@ bool TabSettings::guessSpacesForTabs(const QTextBlock &_block) const
if (!block.isValid() || block.length() == 0)
continue;
const QChar firstChar = doc->characterAt(block.position());
- if (firstChar == QLatin1Char(' ')) {
+ if (firstChar == QLatin1Char(' '))
return true;
- } else if (firstChar == QLatin1Char('\t')) {
+ else if (firstChar == QLatin1Char('\t'))
return false;
- }
}
if (done)
break;
diff --git a/src/plugins/texteditor/texteditor.pro b/src/plugins/texteditor/texteditor.pro
index d123c07569..e4e9be0c66 100644
--- a/src/plugins/texteditor/texteditor.pro
+++ b/src/plugins/texteditor/texteditor.pro
@@ -7,7 +7,6 @@ greaterThan(QT_MAJOR_VERSION, 4): QT += printsupport
include(../../qtcreatorplugin.pri)
include(texteditor_dependencies.pri)
INCLUDEPATH += generichighlighter \
- tooltip \
snippets \
codeassist
SOURCES += texteditorplugin.cpp \
@@ -65,10 +64,6 @@ SOURCES += texteditorplugin.cpp \
refactoringchanges.cpp \
refactoroverlay.cpp \
outlinefactory.cpp \
- tooltip/tooltip.cpp \
- tooltip/tips.cpp \
- tooltip/tipcontents.cpp \
- tooltip/tipfactory.cpp \
basehoverhandler.cpp \
helpitem.cpp \
autocompleter.cpp \
@@ -116,7 +111,8 @@ SOURCES += texteditorplugin.cpp \
codestyleeditor.cpp \
circularclipboard.cpp \
circularclipboardassist.cpp \
- itextmark.cpp
+ itextmark.cpp \
+ codeassist/keywordscompletionassist.cpp
HEADERS += texteditorplugin.h \
textfilewizard.h \
@@ -179,12 +175,6 @@ HEADERS += texteditorplugin.h \
refactoroverlay.h \
outlinefactory.h \
ioutlinewidget.h \
- tooltip/tooltip.h \
- tooltip/tips.h \
- tooltip/tipcontents.h \
- tooltip/reuse.h \
- tooltip/effects.h \
- tooltip/tipfactory.h \
basehoverhandler.h \
helpitem.h \
autocompleter.h \
@@ -235,7 +225,8 @@ HEADERS += texteditorplugin.h \
basefilefind_p.h \
circularclipboard.h \
circularclipboardassist.h \
- itextmark.h
+ itextmark.h \
+ codeassist/keywordscompletionassist.h
FORMS += \
displaysettingspage.ui \
@@ -251,12 +242,3 @@ FORMS += \
RESOURCES += texteditor.qrc
OTHER_FILES += TextEditor.mimetypes.xml
-
-
-
-
-
-
-
-
-
diff --git a/src/plugins/texteditor/texteditor.qbs b/src/plugins/texteditor/texteditor.qbs
index fc8d395779..897deaf8d3 100644
--- a/src/plugins/texteditor/texteditor.qbs
+++ b/src/plugins/texteditor/texteditor.qbs
@@ -6,21 +6,15 @@ QtcPlugin {
name: "TextEditor"
Depends { name: "Qt"; submodules: ["widgets", "xml", "network", "script", "printsupport"] }
- Depends { name: "cpp" }
Depends { name: "Core" }
Depends { name: "Find" }
Depends { name: "Locator" }
- cpp.includePaths: [
- ".",
- "..",
+ cpp.includePaths: base.concat([
"generichighlighter",
- "tooltip",
"snippets",
- "codeassist",
- "../../libs",
- buildDirectory
- ]
+ "codeassist"
+ ])
files: [
"TextEditor.mimetypes.xml",
@@ -62,10 +56,10 @@ QtcPlugin {
"codestyleselectorwidget.h",
"codestyleselectorwidget.ui",
"colorscheme.cpp",
+ "colorscheme.h",
"colorschemeedit.cpp",
"colorschemeedit.h",
"colorschemeedit.ui",
- "colorscheme.h",
"completionsettings.cpp",
"completionsettings.h",
"convenience.cpp",
@@ -91,9 +85,9 @@ QtcPlugin {
"helpitem.cpp",
"helpitem.h",
"icodestylepreferences.cpp",
+ "icodestylepreferences.h",
"icodestylepreferencesfactory.cpp",
"icodestylepreferencesfactory.h",
- "icodestylepreferences.h",
"indenter.cpp",
"indenter.h",
"ioutlinewidget.h",
@@ -108,9 +102,9 @@ QtcPlugin {
"outlinefactory.cpp",
"outlinefactory.h",
"plaintexteditor.cpp",
+ "plaintexteditor.h",
"plaintexteditorfactory.cpp",
"plaintexteditorfactory.h",
- "plaintexteditor.h",
"quickfix.cpp",
"quickfix.h",
"refactoringchanges.cpp",
@@ -132,18 +126,18 @@ QtcPlugin {
"tabsettingswidget.cpp",
"tabsettingswidget.h",
"tabsettingswidget.ui",
+ "texteditor.qrc",
+ "texteditor_global.h",
"texteditoractionhandler.cpp",
"texteditoractionhandler.h",
"texteditorconstants.cpp",
"texteditorconstants.h",
- "texteditor_global.h",
"texteditoroptionspage.cpp",
"texteditoroptionspage.h",
"texteditoroverlay.cpp",
"texteditoroverlay.h",
"texteditorplugin.cpp",
"texteditorplugin.h",
- "texteditor.qrc",
"texteditorsettings.cpp",
"texteditorsettings.h",
"textfilewizard.cpp",
@@ -192,6 +186,9 @@ QtcPlugin {
"ifunctionhintproposalmodel.h",
"igenericproposalmodel.cpp",
"igenericproposalmodel.h",
+ "ikeywords.h",
+ "keywordscompletionassist.cpp",
+ "keywordscompletionassist.h",
"quickfixassistprocessor.cpp",
"quickfixassistprocessor.h",
"quickfixassistprovider.cpp",
@@ -217,8 +214,8 @@ QtcPlugin {
"highlightdefinitionmetadata.cpp",
"highlightdefinitionmetadata.h",
"highlighter.cpp",
- "highlighterexception.h",
"highlighter.h",
+ "highlighterexception.h",
"highlightersettings.cpp",
"highlightersettings.h",
"highlightersettingspage.cpp",
@@ -253,12 +250,12 @@ QtcPlugin {
"plaintextsnippetprovider.cpp",
"plaintextsnippetprovider.h",
"reuse.h",
+ "snippet.cpp",
+ "snippet.h",
"snippetassistcollector.cpp",
"snippetassistcollector.h",
- "snippet.cpp",
"snippeteditor.cpp",
"snippeteditor.h",
- "snippet.h",
"snippetscollection.cpp",
"snippetscollection.h",
"snippetssettings.cpp",
@@ -269,25 +266,8 @@ QtcPlugin {
]
}
- Group {
- prefix: "tooltip/"
- files: [
- "effects.h",
- "reuse.h",
- "tipcontents.cpp",
- "tipcontents.h",
- "tipfactory.cpp",
- "tipfactory.h",
- "tips.cpp",
- "tips.h",
- "tooltip.cpp",
- "tooltip.h"
- ]
- }
-
ProductModule {
Depends { name: "Find" }
Depends { name: "Locator" }
}
}
-
diff --git a/src/plugins/texteditor/texteditoractionhandler.cpp b/src/plugins/texteditor/texteditoractionhandler.cpp
index f6b206c82b..80c90d9012 100644
--- a/src/plugins/texteditor/texteditoractionhandler.cpp
+++ b/src/plugins/texteditor/texteditoractionhandler.cpp
@@ -512,9 +512,8 @@ void TextEditorActionHandler::updateActions(UpdateMode um)
m_unfoldAllAction->setEnabled((m_optionalActions & UnCollapseAll));
m_visualizeWhitespaceAction->setChecked(m_currentEditor->displaySettings().m_visualizeWhitespace);
- if (m_textWrappingAction) {
+ if (m_textWrappingAction)
m_textWrappingAction->setChecked(m_currentEditor->displaySettings().m_textWrapping);
- }
updateRedoAction();
updateUndoAction();
@@ -538,9 +537,8 @@ void TextEditorActionHandler::updateCopyAction()
const bool hasCopyableText = m_currentEditor && m_currentEditor->textCursor().hasSelection();
if (m_cutAction)
m_cutAction->setEnabled(hasCopyableText && updateMode() == WriteMode);
- if (m_copyAction) {
+ if (m_copyAction)
m_copyAction->setEnabled(hasCopyableText);
- }
}
void TextEditorActionHandler::gotoAction()
diff --git a/src/plugins/texteditor/texteditoroptionspage.cpp b/src/plugins/texteditor/texteditoroptionspage.cpp
index 13bbf7fe2d..3aa3dd43fd 100644
--- a/src/plugins/texteditor/texteditoroptionspage.cpp
+++ b/src/plugins/texteditor/texteditoroptionspage.cpp
@@ -38,7 +38,7 @@ using namespace TextEditor;
TextEditorOptionsPage::TextEditorOptionsPage(QObject *parent) :
Core::IOptionsPage(parent)
{
- setCategory(QLatin1String(Constants::TEXT_EDITOR_SETTINGS_CATEGORY));
+ setCategory(Constants::TEXT_EDITOR_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("TextEditor", Constants::TEXT_EDITOR_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::TEXT_EDITOR_SETTINGS_CATEGORY_ICON));
}
diff --git a/src/plugins/texteditor/texteditoroverlay.cpp b/src/plugins/texteditor/texteditoroverlay.cpp
index fc2f952d71..354cb8c852 100644
--- a/src/plugins/texteditor/texteditoroverlay.cpp
+++ b/src/plugins/texteditor/texteditoroverlay.cpp
@@ -91,9 +91,8 @@ void TextEditorOverlay::addOverlaySelection(int begin, int end,
selection.m_cursor_begin = QTextCursor(document->docHandle(), begin);
selection.m_cursor_end = QTextCursor(document->docHandle(), end);
- if (overlaySelectionFlags & ExpandBegin) {
+ if (overlaySelectionFlags & ExpandBegin)
selection.m_cursor_begin.setKeepPositionOnInsert(true);
- }
if (overlaySelectionFlags & LockSize)
selection.m_fixedLength = (end - begin);
@@ -248,7 +247,7 @@ QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, co
points += selection.at(0).bottomRight() + QPointF(margin+1, 0);
- for(int i = 1; i < selection.count()-1; ++i) {
+ for (int i = 1; i < selection.count()-1; ++i) {
#define MAX3(a,b,c) qMax(a, qMax(b,c))
qreal x = MAX3(selection.at(i-1).right(),
@@ -265,7 +264,7 @@ QPainterPath TextEditorOverlay::createSelectionPath(const QTextCursor &begin, co
points += selection.at(selection.count()-1).bottomLeft() + QPointF(-margin, margin+extra);
points += selection.at(selection.count()-1).topLeft() + QPointF(-margin, 0);
- for(int i = selection.count()-2; i > 0; --i) {
+ for (int i = selection.count()-2; i > 0; --i) {
#define MIN3(a,b,c) qMin(a, qMin(b,c))
qreal x = MIN3(selection.at(i-1).left(),
selection.at(i).left(),
diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp
index faf8b180e0..00f14d4b13 100644
--- a/src/plugins/texteditor/texteditorplugin.cpp
+++ b/src/plugins/texteditor/texteditorplugin.cpp
@@ -274,9 +274,14 @@ void TextEditorPlugin::invokeQuickFix()
void TextEditorPlugin::updateSearchResultsFont(const FontSettings &settings)
{
- if (m_searchResultWindow)
+ if (m_searchResultWindow) {
m_searchResultWindow->setTextEditorFont(QFont(settings.family(),
- settings.fontSize() * settings.fontZoom() / 100));
+ settings.fontSize() * settings.fontZoom() / 100),
+ settings.formatFor(TextEditor::C_TEXT).foreground(),
+ settings.formatFor(TextEditor::C_TEXT).background(),
+ settings.formatFor(TextEditor::C_SEARCH_RESULT).foreground(),
+ settings.formatFor(TextEditor::C_SEARCH_RESULT).background());
+ }
}
void TextEditorPlugin::updateVariable(const QByteArray &variable)
diff --git a/src/plugins/texteditor/texteditorsettings.cpp b/src/plugins/texteditor/texteditorsettings.cpp
index b34bedb27c..2f7342ea07 100644
--- a/src/plugins/texteditor/texteditorsettings.cpp
+++ b/src/plugins/texteditor/texteditorsettings.cpp
@@ -69,11 +69,11 @@ public:
HighlighterSettingsPage *m_highlighterSettingsPage;
SnippetsSettingsPage *m_snippetsSettingsPage;
- QMap<QString, ICodeStylePreferencesFactory *> m_languageToFactory;
+ QMap<Core::Id, ICodeStylePreferencesFactory *> m_languageToFactory;
- QMap<QString, ICodeStylePreferences *> m_languageToCodeStyle;
- QMap<QString, CodeStylePool *> m_languageToCodeStylePool;
- QMap<QString, QString> m_mimeTypeToLanguage;
+ QMap<Core::Id, ICodeStylePreferences *> m_languageToCodeStyle;
+ QMap<Core::Id, CodeStylePool *> m_languageToCodeStylePool;
+ QMap<QString, Core::Id> m_mimeTypeToLanguage;
CompletionSettings m_completionSettings;
@@ -256,31 +256,31 @@ TextEditorSettings::TextEditorSettings(QObject *parent)
"(in diff editor)."), Qt::blue));
m_d->m_fontSettingsPage = new FontSettingsPage(formatDescr,
- QLatin1String(Constants::TEXT_EDITOR_FONT_SETTINGS),
+ Constants::TEXT_EDITOR_FONT_SETTINGS,
this);
ExtensionSystem::PluginManager::addObject(m_d->m_fontSettingsPage);
// Add the GUI used to configure the tab, storage and interaction settings
TextEditor::BehaviorSettingsPageParameters behaviorSettingsPageParameters;
- behaviorSettingsPageParameters.id = QLatin1String(Constants::TEXT_EDITOR_BEHAVIOR_SETTINGS);
+ behaviorSettingsPageParameters.id = Constants::TEXT_EDITOR_BEHAVIOR_SETTINGS;
behaviorSettingsPageParameters.displayName = tr("Behavior");
behaviorSettingsPageParameters.settingsPrefix = QLatin1String("text");
m_d->m_behaviorSettingsPage = new BehaviorSettingsPage(behaviorSettingsPageParameters, this);
ExtensionSystem::PluginManager::addObject(m_d->m_behaviorSettingsPage);
TextEditor::DisplaySettingsPageParameters displaySettingsPageParameters;
- displaySettingsPageParameters.id = QLatin1String(Constants::TEXT_EDITOR_DISPLAY_SETTINGS),
+ displaySettingsPageParameters.id = Constants::TEXT_EDITOR_DISPLAY_SETTINGS;
displaySettingsPageParameters.displayName = tr("Display");
displaySettingsPageParameters.settingsPrefix = QLatin1String("text");
m_d->m_displaySettingsPage = new DisplaySettingsPage(displaySettingsPageParameters, this);
ExtensionSystem::PluginManager::addObject(m_d->m_displaySettingsPage);
m_d->m_highlighterSettingsPage =
- new HighlighterSettingsPage(QLatin1String(Constants::TEXT_EDITOR_HIGHLIGHTER_SETTINGS), this);
+ new HighlighterSettingsPage(Constants::TEXT_EDITOR_HIGHLIGHTER_SETTINGS, this);
ExtensionSystem::PluginManager::addObject(m_d->m_highlighterSettingsPage);
m_d->m_snippetsSettingsPage =
- new SnippetsSettingsPage(QLatin1String(Constants::TEXT_EDITOR_SNIPPETS_SETTINGS), this);
+ new SnippetsSettingsPage(Constants::TEXT_EDITOR_SNIPPETS_SETTINGS, this);
ExtensionSystem::PluginManager::addObject(m_d->m_snippetsSettingsPage);
connect(m_d->m_fontSettingsPage, SIGNAL(changed(TextEditor::FontSettings)),
@@ -411,12 +411,12 @@ void TextEditorSettings::registerCodeStyleFactory(ICodeStylePreferencesFactory *
m_d->m_languageToFactory.insert(factory->languageId(), factory);
}
-QMap<QString, ICodeStylePreferencesFactory *> TextEditorSettings::codeStyleFactories() const
+QMap<Core::Id, ICodeStylePreferencesFactory *> TextEditorSettings::codeStyleFactories() const
{
return m_d->m_languageToFactory;
}
-ICodeStylePreferencesFactory *TextEditorSettings::codeStyleFactory(const QString &languageId) const
+ICodeStylePreferencesFactory *TextEditorSettings::codeStyleFactory(Core::Id languageId) const
{
return m_d->m_languageToFactory.value(languageId);
}
@@ -426,17 +426,17 @@ ICodeStylePreferences *TextEditorSettings::codeStyle() const
return m_d->m_behaviorSettingsPage->codeStyle();
}
-ICodeStylePreferences *TextEditorSettings::codeStyle(const QString &languageId) const
+ICodeStylePreferences *TextEditorSettings::codeStyle(Core::Id languageId) const
{
return m_d->m_languageToCodeStyle.value(languageId, codeStyle());
}
-QMap<QString, ICodeStylePreferences *> TextEditorSettings::codeStyles() const
+QMap<Core::Id, ICodeStylePreferences *> TextEditorSettings::codeStyles() const
{
return m_d->m_languageToCodeStyle;
}
-void TextEditorSettings::registerCodeStyle(const QString &languageId, ICodeStylePreferences *prefs)
+void TextEditorSettings::registerCodeStyle(Core::Id languageId, ICodeStylePreferences *prefs)
{
m_d->m_languageToCodeStyle.insert(languageId, prefs);
}
@@ -446,22 +446,22 @@ CodeStylePool *TextEditorSettings::codeStylePool() const
return m_d->m_behaviorSettingsPage->codeStylePool();
}
-CodeStylePool *TextEditorSettings::codeStylePool(const QString &languageId) const
+CodeStylePool *TextEditorSettings::codeStylePool(Core::Id languageId) const
{
return m_d->m_languageToCodeStylePool.value(languageId);
}
-void TextEditorSettings::registerCodeStylePool(const QString &languageId, CodeStylePool *pool)
+void TextEditorSettings::registerCodeStylePool(Core::Id languageId, CodeStylePool *pool)
{
m_d->m_languageToCodeStylePool.insert(languageId, pool);
}
-void TextEditorSettings::registerMimeTypeForLanguageId(const QString &mimeType, const QString &languageId)
+void TextEditorSettings::registerMimeTypeForLanguageId(const QString &mimeType, Core::Id languageId)
{
m_d->m_mimeTypeToLanguage.insert(mimeType, languageId);
}
-QString TextEditorSettings::languageId(const QString &mimeType) const
+Core::Id TextEditorSettings::languageId(const QString &mimeType) const
{
return m_d->m_mimeTypeToLanguage.value(mimeType);
}
diff --git a/src/plugins/texteditor/texteditorsettings.h b/src/plugins/texteditor/texteditorsettings.h
index c654cff430..9468555967 100644
--- a/src/plugins/texteditor/texteditorsettings.h
+++ b/src/plugins/texteditor/texteditorsettings.h
@@ -32,6 +32,8 @@
#include "texteditor_global.h"
+#include <coreplugin/id.h>
+
#include <QObject>
QT_BEGIN_NAMESPACE
@@ -87,21 +89,21 @@ public:
void setCompletionSettings(const TextEditor::CompletionSettings &);
- ICodeStylePreferencesFactory *codeStyleFactory(const QString &languageId) const;
- QMap<QString, ICodeStylePreferencesFactory *> codeStyleFactories() const;
+ ICodeStylePreferencesFactory *codeStyleFactory(Core::Id languageId) const;
+ QMap<Core::Id, ICodeStylePreferencesFactory *> codeStyleFactories() const;
void registerCodeStyleFactory(ICodeStylePreferencesFactory *codeStyleFactory);
CodeStylePool *codeStylePool() const;
- CodeStylePool *codeStylePool(const QString &languageId) const;
- void registerCodeStylePool(const QString &languageId, CodeStylePool *pool);
+ CodeStylePool *codeStylePool(Core::Id languageId) const;
+ void registerCodeStylePool(Core::Id languageId, CodeStylePool *pool);
ICodeStylePreferences *codeStyle() const;
- ICodeStylePreferences *codeStyle(const QString &languageId) const;
- QMap<QString, ICodeStylePreferences *> codeStyles() const;
- void registerCodeStyle(const QString &languageId, ICodeStylePreferences *prefs);
+ ICodeStylePreferences *codeStyle(Core::Id languageId) const;
+ QMap<Core::Id, ICodeStylePreferences *> codeStyles() const;
+ void registerCodeStyle(Core::Id languageId, ICodeStylePreferences *prefs);
- void registerMimeTypeForLanguageId(const QString &mimeType, const QString &languageId);
- QString languageId(const QString &mimeType) const;
+ void registerMimeTypeForLanguageId(const QString &mimeType, Core::Id languageId);
+ Core::Id languageId(const QString &mimeType) const;
signals:
void fontSettingsChanged(const TextEditor::FontSettings &);
diff --git a/src/plugins/todo/optionspage.cpp b/src/plugins/todo/optionspage.cpp
index edef58ae70..5200853756 100644
--- a/src/plugins/todo/optionspage.cpp
+++ b/src/plugins/todo/optionspage.cpp
@@ -49,9 +49,9 @@ OptionsPage::OptionsPage(const Settings &settings, QObject *parent) :
{
setSettings(settings);
- setId(QLatin1String("TodoSettings"));
+ setId("TodoSettings");
setDisplayName(tr("To-Do"));
- setCategory(QLatin1String("To-Do"));
+ setCategory("To-Do");
setDisplayCategory(tr("To-Do"));
setCategoryIcon(QLatin1String(Constants::ICON_TODO));
}
diff --git a/src/plugins/todo/todo.pro b/src/plugins/todo/todo.pro
index b9a659a42c..97e6f95b64 100644
--- a/src/plugins/todo/todo.pro
+++ b/src/plugins/todo/todo.pro
@@ -4,8 +4,6 @@ TARGET = Todo
include(../../qtcreatorplugin.pri)
include(todo_dependencies.pri)
-DEFINES += QT_NO_CAST_FROM_ASCII
-
HEADERS += todoplugin.h \
keyword.h \
constants.h \
diff --git a/src/plugins/todo/todo.qbs b/src/plugins/todo/todo.qbs
index 8629356c0e..78b9710d0b 100644
--- a/src/plugins/todo/todo.qbs
+++ b/src/plugins/todo/todo.qbs
@@ -13,23 +13,15 @@ QtcPlugin {
Depends { name: "CppTools" }
Depends { name: "QmlJs" }
- Depends { name: "cpp" }
- cpp.defines: base.concat(["QT_NO_CAST_FROM_ASCII"])
- cpp.includePaths: [
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
"constants.h",
"cpptodoitemsscanner.cpp",
"cpptodoitemsscanner.h",
"keyword.cpp",
+ "keyword.h",
"keyworddialog.cpp",
"keyworddialog.h",
"keyworddialog.ui",
- "keyword.h",
"lineparser.cpp",
"lineparser.h",
"optionsdialog.cpp",
@@ -52,6 +44,6 @@ QtcPlugin {
"todooutputpane.h",
"todoplugin.cpp",
"todoplugin.h",
- "todoplugin.qrc"
+ "todoplugin.qrc",
]
}
diff --git a/src/plugins/updateinfo/updateinfo.qbs b/src/plugins/updateinfo/updateinfo.qbs
index 716ff5e686..94fd2e2b1f 100644
--- a/src/plugins/updateinfo/updateinfo.qbs
+++ b/src/plugins/updateinfo/updateinfo.qbs
@@ -5,12 +5,13 @@ import "../QtcPlugin.qbs" as QtcPlugin
QtcPlugin {
name: "UpdateInfo"
+ Depends { name: "cpp" }
Depends { name: "Core" }
Depends { name: "ExtensionSystem" }
Depends { name: "Qt"; submodules: ["widgets", "xml", "network"] }
property bool enable: false
- property var pluginspecreplacements: ({"UPDATEINFO_EXPERIMENTAL_STR": (enable ? "false": "true")})
+ pluginspecreplacements: ({"UPDATEINFO_EXPERIMENTAL_STR": (enable ? "false": "true")})
cpp.includePaths: [
"..",
@@ -21,6 +22,6 @@ QtcPlugin {
"updateinfobutton.cpp",
"updateinfobutton.h",
"updateinfoplugin.cpp",
- "updateinfoplugin.h"
+ "updateinfoplugin.h",
]
}
diff --git a/src/plugins/updateinfo/updateinfoplugin.cpp b/src/plugins/updateinfo/updateinfoplugin.cpp
index 167c9d3329..699bfef42b 100644
--- a/src/plugins/updateinfo/updateinfoplugin.cpp
+++ b/src/plugins/updateinfo/updateinfoplugin.cpp
@@ -98,9 +98,8 @@ UpdateInfoPlugin::~UpdateInfoPlugin()
void UpdateInfoPlugin::startCheckTimer(uint milliseconds)
{
- if (d->currentTimerId != 0) {
+ if (d->currentTimerId != 0)
stopCurrentCheckTimer();
- }
d->currentTimerId = startTimer(milliseconds);
}
@@ -150,9 +149,8 @@ bool UpdateInfoPlugin::initialize(const QStringList & /* arguments */, QString *
QDomDocument UpdateInfoPlugin::checkForUpdates()
{
- if (QThread::currentThread() == QCoreApplication::instance()->thread()) {
+ if (QThread::currentThread() == QCoreApplication::instance()->thread())
qWarning() << Q_FUNC_INFO << " Was not designed to run in main/gui thread -> it is using updaterProcess.waitForFinished()";
- }
//starting
QProcess updaterProcess;
@@ -166,7 +164,7 @@ QDomDocument UpdateInfoPlugin::checkForUpdates()
qWarning() << "Get update info application crashed.";
//return; //maybe there is some output
}
- QString updaterOutput = updaterProcess.readAllStandardOutput();
+ QByteArray updaterOutput = updaterProcess.readAllStandardOutput();
QDomDocument updatesDomDocument;
updatesDomDocument.setContent(updaterOutput);
@@ -203,9 +201,8 @@ void UpdateInfoPlugin::reactOnUpdaterOutput()
void UpdateInfoPlugin::startUpdaterUiApplication()
{
QProcess::startDetached(d->updaterProgram, QStringList() << d->updaterRunUiArgument);
- if (!d->updateInfoProgress.isNull()) {
+ if (!d->updateInfoProgress.isNull())
d->updateInfoProgress->setKeepOnFinish(Core::FutureProgress::HideOnFinish); //this is fading out the last updateinfo
- }
startCheckTimer(OneMinute);
}
diff --git a/src/plugins/valgrind/callgrind/callgrindcallmodel.cpp b/src/plugins/valgrind/callgrind/callgrindcallmodel.cpp
index 4228f5e16e..641eb9bd85 100644
--- a/src/plugins/valgrind/callgrind/callgrindcallmodel.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindcallmodel.cpp
@@ -188,9 +188,8 @@ QVariant CallModel::data(const QModelIndex &index, int role) const
return parentCost;
}
- if (role == FunctionCallRole) {
+ if (role == FunctionCallRole)
return QVariant::fromValue(call);
- }
if (role == RelativeTotalCostRole) {
const quint64 totalCost = d->m_data->totalCost(d->m_event);
diff --git a/src/plugins/valgrind/callgrind/callgrindcontroller.cpp b/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
index 4fe36f6a8f..bcccd143ce 100644
--- a/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindcontroller.cpp
@@ -28,12 +28,12 @@
****************************************************************************/
#include "callgrindcontroller.h"
+#include "../valgrindprocess.h"
#include <QDebug>
#include <QDir>
-#include <valgrindprocess.h>
-
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <ssh/sftpchannel.h>
@@ -79,15 +79,15 @@ QString toOptionString(CallgrindController::Option option)
switch (option) {
case CallgrindController::Dump:
- return "--dump";
+ return QLatin1String("--dump");
case CallgrindController::ResetEventCounters:
- return "--zero";
+ return QLatin1String("--zero");
case CallgrindController::Pause:
- return "--instr=off";
+ return QLatin1String("--instr=off");
case CallgrindController::UnPause:
- return "--instr=on";
+ return QLatin1String("--instr=on");
default:
- return ""; // never reached
+ return QString(); // never reached
}
}
@@ -134,11 +134,7 @@ void CallgrindController::run(Option option)
#if CALLGRIND_CONTROL_DEBUG
m_process->setProcessChannelMode(QProcess::ForwardedChannels);
#endif
-#ifdef Q_OS_WIN
- int pid = 0;
-#else
- const int pid = m_valgrindProc->pid();
-#endif
+ const int pid = Utils::HostOsInfo::isWindowsHost() ? 0 : m_valgrindProc->pid();
m_process->run(CALLGRIND_CONTROL_BINARY,
QStringList() << optionString << QString::number(pid),
QString(), QString());
@@ -201,7 +197,7 @@ void CallgrindController::getLocalDataFile()
QTC_ASSERT(m_valgrindProc, return);
// we look for callgrind.out.PID, but there may be updated ones called ~.PID.NUM
- QString baseFileName = QString("callgrind.out.%1").
+ QString baseFileName = QString::fromLatin1("callgrind.out.%1").
arg(m_valgrindProc->pid());
const QString workingDir = m_valgrindProc->workingDirectory();
// first, set the to-be-parsed file to callgrind.out.PID
@@ -212,13 +208,13 @@ void CallgrindController::getLocalDataFile()
emit statusMessage(tr("Downloading remote profile data..."));
m_ssh = remote->connection();
// if there are files like callgrind.out.PID.NUM, set it to the most recent one of those
- QString cmd = QString("ls -t %1* | head -n 1").arg(fileName);
+ QString cmd = QString::fromLatin1("ls -t %1* | head -n 1").arg(fileName);
m_findRemoteFile = m_ssh->createRemoteProcess(cmd.toUtf8());
connect(m_findRemoteFile.data(), SIGNAL(readyReadStandardOutput()), this,
SLOT(foundRemoteFile()));
m_findRemoteFile->start();
} else {
- QDir dir(workingDir, QString("%1.*").arg(baseFileName), QDir::Time);
+ QDir dir(workingDir, QString::fromLatin1("%1.*").arg(baseFileName), QDir::Time);
QStringList outputFiles = dir.entryList();
// if there are files like callgrind.out.PID.NUM, set it to the most recent one of those
if (!outputFiles.isEmpty())
@@ -242,13 +238,13 @@ void CallgrindController::foundRemoteFile()
void CallgrindController::sftpInitialized()
{
cleanupTempFile();
- QTemporaryFile dataFile(QDir::tempPath() + QDir::separator() + "callgrind.out.");
+ QTemporaryFile dataFile(QDir::tempPath() + QDir::separator() + QLatin1String("callgrind.out."));
QTC_ASSERT(dataFile.open(), return);
m_tempDataFile = dataFile.fileName();
dataFile.setAutoRemove(false);
dataFile.close();
- m_downloadJob = m_sftp->downloadFile(m_remoteFile, m_tempDataFile, QSsh::SftpOverwriteExisting);
+ m_downloadJob = m_sftp->downloadFile(QString::fromLocal8Bit(m_remoteFile), m_tempDataFile, QSsh::SftpOverwriteExisting);
}
void CallgrindController::sftpJobFinished(QSsh::SftpJobId job, const QString &error)
diff --git a/src/plugins/valgrind/callgrind/callgrindcycledetection.cpp b/src/plugins/valgrind/callgrind/callgrindcycledetection.cpp
index 29f2024ed3..3ebd6aefa1 100644
--- a/src/plugins/valgrind/callgrind/callgrindcycledetection.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindcycledetection.cpp
@@ -95,7 +95,7 @@ void CycleDetection::tarjan(Node *node)
cycle->setFile(node->function->fileId());
m_cycle++;
qint64 id = -1;
- m_data->addCompressedFunction(QString("cycle %1").arg(m_cycle), id);
+ m_data->addCompressedFunction(QString::fromLatin1("cycle %1").arg(m_cycle), id);
cycle->setName(id);
cycle->setObject(node->function->objectId());
cycle->setFunctions(functions);
diff --git a/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp b/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp
index 242800637d..10abb6cc0f 100644
--- a/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp
+++ b/src/plugins/valgrind/callgrind/callgrinddatamodel.cpp
@@ -212,7 +212,7 @@ QModelIndex DataModel::indexForObject(const Function *function) const
static QString noWrap(const QString &str)
{
QString escapedStr = str;
- return escapedStr.replace(QLatin1Char('-'), "&#8209;");
+ return escapedStr.replace(QLatin1Char('-'), QLatin1String("&#8209;"));
}
static QString shortenTemplate(QString str)
@@ -258,37 +258,39 @@ QVariant DataModel::data(const QModelIndex &index, int role) const
if (!d->m_verboseToolTips)
return data(index, Qt::DisplayRole);
- QString ret = "<html><head><style>\
+ QString ret = QLatin1String("<html><head><style>\
dt { font-weight: bold; }\
dd { font-family: monospace; }\
tr.head, td.head { font-weight: bold; }\
tr.head { text-decoration: underline; }\
td.group { padding-left: 20px; }\
td { white-space: nowrap; }\
- </style></head>\n";
+ </style></head>\n<body><dl>");
+ QString entry = QLatin1String("<dt>%1</dt><dd>%2</dd>\n");
// body, function info first
- ret += "<body><dl>";
- ret += "<dt>" + tr("Function:") + "</dt><dd>" + Qt::escape(func->name()) + "</dd>\n";
- ret += "<dt>" + tr("File:") + "</dt><dd>" + func->file() + "</dd>\n";
+ ret += entry.arg(tr("Function:")).arg(Qt::escape(func->name()));
+ ret += entry.arg(tr("File:")).arg(func->file());
if (!func->costItems().isEmpty()) {
const CostItem *firstItem = func->costItems().first();
for (int i = 0; i < d->m_data->positions().size(); ++i) {
- ret += "<dt>" + ParseData::prettyStringForPosition(d->m_data->positions().at(i)) + "</dt>";
- ret += "<dd>" + QString::number(firstItem->position(i)) + "</dd>\n";
+ ret += entry.arg(ParseData::prettyStringForPosition(d->m_data->positions().at(i)))
+ .arg(firstItem->position(i));
}
}
- ret += "<dt>" + tr("Object:") + "</dt><dd>" + func->object() + "</dd>\n";
- ret += "<dt>" + tr("Called:") + "</dt><dd>" + tr("%n time(s)", 0, func->called()) + "</dd>\n";
- ret += "</dl><p/>";
+ ret += entry.arg(tr("Object:")).arg(func->object());
+ ret += entry.arg(tr("Called:")).arg(tr("%n time(s)", 0, func->called()));
+ ret += QLatin1String("</dl><p/>");
// self/inclusive costs
- ret += "<table>";
- ret += "<thead><tr class='head'><td>" + tr("Events") + "</td>";
- ret += "<td class='group'>" + tr("Self costs") + "</td><td>" + tr("(%)") + "</td>";
- ret += "<td class='group'>" + tr("Incl. costs") + "</td><td>" + tr("(%)") + "</td>";
- ret += "</tr></thead>";
- ret += "<tbody>";
+ entry = QLatin1String("<td class='group'>%1</td><td>%2</td>");
+ ret += QLatin1String("<table>");
+ ret += QLatin1String("<thead><tr class='head'>");
+ ret += QLatin1String("<td>") + tr("Events") + QLatin1String("</td>");
+ ret += entry.arg(tr("Self costs")).arg(tr("(%)"));
+ ret += entry.arg(tr("Incl. costs")).arg(tr("(%)"));
+ ret += QLatin1String("</tr></thead>");
+ ret += QLatin1String("<tbody>");
for (int i = 0; i < d->m_data->events().size(); ++i) {
quint64 selfCost = func->selfCost(i);
quint64 inclCost = func->inclusiveCost(i);
@@ -297,22 +299,21 @@ QVariant DataModel::data(const QModelIndex &index, int role) const
const float relSelfCost = (float)qRound((float)selfCost / totalCost * 10000) / 100;
const float relInclCost = (float)qRound((float)inclCost / totalCost * 10000) / 100;
- ret += "<tr>";
- ret += "<td class='head'><nobr>" + noWrap(ParseData::prettyStringForEvent(d->m_data->events().at(i))) + "</nobr></td>";
- ret += "<td class='group'>" + tr("%1").arg(selfCost) + "</td>";
- ret += "<td>" + tr("(%1%)").arg(relSelfCost) + "</td>";
- ret += "<td class='group'>" + tr("%1").arg(inclCost) + "</td>";
- ret += "<td>" + tr("(%1%)").arg(relInclCost) + "</td>";
- ret += "</tr>";
+ ret += QLatin1String("<tr>");
+ ret += QLatin1String("<td class='head'><nobr>") +
+ noWrap(ParseData::prettyStringForEvent(d->m_data->events().at(i)))
+ + QLatin1String("</nobr></td>");
+ ret += entry.arg(selfCost).arg(tr("(%1%)").arg(relSelfCost));
+ ret += entry.arg(inclCost).arg(tr("(%1%)").arg(relInclCost));
+ ret += QLatin1String("</tr>");
}
- ret += "</tbody></table>";
- ret += "</body></html>";
+ ret += QLatin1String("</tbody></table>");
+ ret += QLatin1String("</body></html>");
return ret;
}
- if (role == FunctionRole) {
+ if (role == FunctionRole)
return QVariant::fromValue(func);
- }
if (role == ParentCostRole) {
const quint64 totalCost = d->m_data->totalCost(d->m_event);
@@ -324,18 +325,15 @@ QVariant DataModel::data(const QModelIndex &index, int role) const
const quint64 totalCost = d->m_data->totalCost(d->m_event);
if (index.column() == SelfCostColumn)
return double(func->selfCost(d->m_event)) / totalCost;
- if (index.column() == InclusiveCostColumn) {
+ if (index.column() == InclusiveCostColumn)
return double(func->inclusiveCost(d->m_event)) / totalCost;
- }
}
- if (role == LineNumberRole) {
+ if (role == LineNumberRole)
return func->lineNumber();
- }
- if (role == FileNameRole) {
+ if (role == FileNameRole)
return func->file();
- }
if (role == Qt::TextAlignmentRole) {
if (index.column() == CalledColumn)
diff --git a/src/plugins/valgrind/callgrind/callgrindfunction.cpp b/src/plugins/valgrind/callgrind/callgrindfunction.cpp
index 24cc289d02..914a837b11 100644
--- a/src/plugins/valgrind/callgrind/callgrindfunction.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindfunction.cpp
@@ -201,15 +201,14 @@ QString Function::location() const
if (!f.isEmpty()) {
QFileInfo info(f);
- if (info.exists()) {
+ if (info.exists())
f = info.canonicalFilePath();
- }
}
QString o = object();
if (o.isEmpty())
return QString();
- if (f.isEmpty() || f == "???")
+ if (f.isEmpty() || f == QLatin1String("???"))
return o;
if (pos.isEmpty())
return QCoreApplication::translate("Valgrind::Callgrind::Function", "%1 in %2").arg(f, o);
@@ -287,11 +286,10 @@ void Function::addCostItem(const CostItem *item)
d->m_costItems.append(item);
// accumulate costs
- if (item->call()) {
+ if (item->call())
d->accumulateCost(d->m_inclusiveCost, item->costs());
- } else {
+ else
d->accumulateCost(d->m_selfCost, item->costs());
- }
}
void Function::finalize()
diff --git a/src/plugins/valgrind/callgrind/callgrindparsedata.cpp b/src/plugins/valgrind/callgrind/callgrindparsedata.cpp
index e470ec4043..fb3a312943 100644
--- a/src/plugins/valgrind/callgrind/callgrindparsedata.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindparsedata.cpp
@@ -137,9 +137,8 @@ void ParseData::Private::addCompressedString(NameLookupTable &lookup, const QStr
void ParseData::Private::cycleDetection()
{
- if (m_cycleCacheValid) {
+ if (m_cycleCacheValid)
return;
- }
cleanupFunctionCycles();
Internal::CycleDetection algorithm(m_q);
m_cycleCache = algorithm.run(m_functions);
@@ -182,13 +181,13 @@ QString ParseData::prettyStringForEvent(const QString &event)
QString type;
if (event.contains(QLatin1Char('L')))
type = ParseData::Private::tr("Last-level"); // first, "L" overwrites the others
- else if (event.at(0) == 'I')
+ else if (event.at(0) == QLatin1Char('I'))
type = ParseData::Private::tr("Instruction");
- else if (event.at(0) == 'D')
+ else if (event.at(0) == QLatin1Char('D'))
type = ParseData::Private::tr("Cache");
- else if (event.leftRef(2) == "Bc")
+ else if (event.leftRef(2) == QLatin1String("Bc"))
type = ParseData::Private::tr("Conditional branches");
- else if (event.leftRef(2) == "Bi")
+ else if (event.leftRef(2) == QLatin1String("Bi"))
type = ParseData::Private::tr("Indirect branches");
QStringList prettyString;
@@ -198,7 +197,7 @@ QString ParseData::prettyStringForEvent(const QString &event)
prettyString << ParseData::Private::tr("level %1").arg(event.at(1));
prettyString << (isRead ? ParseData::Private::tr("read") : ParseData::Private::tr("write"));
- if (event.at(0) == 'B')
+ if (event.at(0) == QLatin1Char('B'))
prettyString << (isMiss ? ParseData::Private::tr("mispredicted") : ParseData::Private::tr("executed"));
else
prettyString << (isMiss ? ParseData::Private::tr("miss") : ParseData::Private::tr("access"));
@@ -221,9 +220,9 @@ void ParseData::setEvents(const QStringList &events)
QString ParseData::prettyStringForPosition(const QString &position)
{
- if (position == "line")
+ if (position == QLatin1String("line"))
return ParseData::Private::tr("Line:"); // as in: "line number"
- else if (position == "instr")
+ else if (position == QLatin1String("instr"))
return ParseData::Private::tr("Instruction"); // as in: "instruction address"
return ParseData::Private::tr("Position:"); // never reached, in theory
}
@@ -243,7 +242,7 @@ void ParseData::setPositions(const QStringList &positions)
d->m_positions = positions;
d->m_lineNumberPositionIndex = -1;
for (int i = 0; i < positions.size(); ++i) {
- if (positions.at(i) == "line") {
+ if (positions.at(i) == QLatin1String("line")) {
d->m_lineNumberPositionIndex = i;
break;
}
diff --git a/src/plugins/valgrind/callgrind/callgrindparser.cpp b/src/plugins/valgrind/callgrind/callgrindparser.cpp
index 06398502b9..ff2125c471 100644
--- a/src/plugins/valgrind/callgrind/callgrindparser.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindparser.cpp
@@ -537,9 +537,8 @@ void Parser::Private::parseCostItem(const char *begin, const char *end)
skipSpace(&current, end);
}
- if (call) {
+ if (call)
call->setCosts(costItem->costs());
- }
currentFunction->addCostItem(costItem);
}
diff --git a/src/plugins/valgrind/callgrind/callgrindproxymodel.cpp b/src/plugins/valgrind/callgrind/callgrindproxymodel.cpp
index 1f5eb50d48..85b46f59be 100644
--- a/src/plugins/valgrind/callgrind/callgrindproxymodel.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindproxymodel.cpp
@@ -116,9 +116,8 @@ bool DataProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_
return false;
// if the filter regexp is a non-empty string, ignore our filters
- if (!filterRegExp().isEmpty()) {
+ if (!filterRegExp().isEmpty())
return QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
- }
// check max rows
if (m_maxRows > 0 && source_row > m_maxRows)
@@ -141,9 +140,8 @@ bool DataProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_
break;
}
}
- if (!isValid) {
+ if (!isValid)
return false;
- }
}
// check minimum inclusive costs
diff --git a/src/plugins/valgrind/callgrind/callgrindrunner.cpp b/src/plugins/valgrind/callgrind/callgrindrunner.cpp
index 5de3f0ca08..e0e37e0810 100644
--- a/src/plugins/valgrind/callgrind/callgrindrunner.cpp
+++ b/src/plugins/valgrind/callgrind/callgrindrunner.cpp
@@ -54,7 +54,7 @@ CallgrindRunner::CallgrindRunner(QObject *parent)
QString CallgrindRunner::tool() const
{
- return QString("callgrind");
+ return QLatin1String("callgrind");
}
Parser *CallgrindRunner::parser() const
diff --git a/src/plugins/valgrind/callgrind/callgrindrunner.h b/src/plugins/valgrind/callgrind/callgrindrunner.h
index 025a61ca2b..0479cf1964 100644
--- a/src/plugins/valgrind/callgrind/callgrindrunner.h
+++ b/src/plugins/valgrind/callgrind/callgrindrunner.h
@@ -30,7 +30,7 @@
#ifndef VALGRIND_CALLGRIND_CALLGRINDRUNNER_H
#define VALGRIND_CALLGRIND_CALLGRINDRUNNER_H
-#include <valgrindrunner.h>
+#include "../valgrindrunner.h"
#include "callgrindcontroller.h"
diff --git a/src/plugins/valgrind/callgrindengine.cpp b/src/plugins/valgrind/callgrindengine.cpp
index 0eec66ecdc..b4bc9fedbb 100644
--- a/src/plugins/valgrind/callgrindengine.cpp
+++ b/src/plugins/valgrind/callgrindengine.cpp
@@ -68,19 +68,19 @@ QStringList CallgrindEngine::toolArguments() const
QTC_ASSERT(callgrindSettings, return arguments);
if (callgrindSettings->enableCacheSim())
- arguments << "--cache-sim=yes";
+ arguments << QLatin1String("--cache-sim=yes");
if (callgrindSettings->enableBranchSim())
- arguments << "--branch-sim=yes";
+ arguments << QLatin1String("--branch-sim=yes");
if (callgrindSettings->collectBusEvents())
- arguments << "--collect-bus=yes";
+ arguments << QLatin1String("--collect-bus=yes");
if (callgrindSettings->collectSystime())
- arguments << "--collect-systime=yes";
+ arguments << QLatin1String("--collect-systime=yes");
if (m_markAsPaused)
- arguments << "--instr-atstart=no";
+ arguments << QLatin1String("--instr-atstart=no");
// add extra arguments
if (!m_argumentForToggleCollect.isEmpty())
diff --git a/src/plugins/valgrind/callgrindhelper.cpp b/src/plugins/valgrind/callgrindhelper.cpp
index d1f846244c..ab6651ee66 100644
--- a/src/plugins/valgrind/callgrindhelper.cpp
+++ b/src/plugins/valgrind/callgrindhelper.cpp
@@ -67,7 +67,7 @@ QString CallgrindHelper::toPercent(float costs, const QLocale &locale)
return locale.toString(costs, 'f', 1) + locale.percent();
if (costs > 0.009f)
return locale.toString(costs, 'f', 2) + locale.percent();
- return QString("<") + locale.toString(0.01f) + locale.percent();
+ return QLatin1Char('<') + locale.toString(0.01f) + locale.percent();
}
} // namespace Internal
diff --git a/src/plugins/valgrind/callgrindtool.cpp b/src/plugins/valgrind/callgrindtool.cpp
index e4d438bfc3..c7790a997b 100644
--- a/src/plugins/valgrind/callgrindtool.cpp
+++ b/src/plugins/valgrind/callgrindtool.cpp
@@ -516,7 +516,7 @@ CallgrindTool::~CallgrindTool()
Core::Id CallgrindTool::id() const
{
- return "Callgrind";
+ return Core::Id("Callgrind");
}
ProjectExplorer::RunMode CallgrindTool::runMode() const
@@ -553,7 +553,7 @@ void CallgrindTool::extensionsInitialized()
editorContextMenu->addSeparator(analyzerContext);
action = new QAction(tr("Profile Costs of this Function and its Callees"), this);
- action->setIcon(QIcon(Analyzer::Constants::ANALYZER_CONTROL_START_ICON));
+ action->setIcon(QIcon(QLatin1String(Analyzer::Constants::ANALYZER_CONTROL_START_ICON)));
connect(action, SIGNAL(triggered()), d, SLOT(handleShowCostsOfFunction()));
cmd = Core::ActionManager::registerAction(action, "Analyzer.Callgrind.ShowCostsOfFunction",
analyzerContext);
@@ -631,13 +631,13 @@ QWidget *CallgrindToolPrivate::createWidgets()
Utils::FancyMainWindow *mw = AnalyzerManager::mainWindow();
m_visualisation = new Visualisation(mw);
m_visualisation->setFrameStyle(QFrame::NoFrame);
- m_visualisation->setObjectName("Valgrind.CallgrindTool.Visualisation");
+ m_visualisation->setObjectName(QLatin1String("Valgrind.CallgrindTool.Visualisation"));
m_visualisation->setModel(m_dataModel);
connect(m_visualisation, SIGNAL(functionActivated(const Valgrind::Callgrind::Function*)),
this, SLOT(visualisationFunctionSelected(const Valgrind::Callgrind::Function*)));
m_callersView = new CostView(mw);
- m_callersView->setObjectName("Valgrind.CallgrindTool.CallersView");
+ m_callersView->setObjectName(QLatin1String("Valgrind.CallgrindTool.CallersView"));
m_callersView->sortByColumn(CallModel::CostColumn);
m_callersView->setFrameStyle(QFrame::NoFrame);
// enable sorting
@@ -649,7 +649,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
this, SLOT(callerFunctionSelected(QModelIndex)));
m_calleesView = new CostView(mw);
- m_calleesView->setObjectName("Valgrind.CallgrindTool.CalleesView");
+ m_calleesView->setObjectName(QLatin1String("Valgrind.CallgrindTool.CalleesView"));
m_calleesView->sortByColumn(CallModel::CostColumn);
m_calleesView->setFrameStyle(QFrame::NoFrame);
// enable sorting
@@ -661,7 +661,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
this, SLOT(calleeFunctionSelected(QModelIndex)));
m_flatView = new CostView(mw);
- m_flatView->setObjectName("Valgrind.CallgrindTool.FlatView");
+ m_flatView->setObjectName(QLatin1String("Valgrind.CallgrindTool.FlatView"));
m_flatView->sortByColumn(DataModel::SelfCostColumn);
m_flatView->setFrameStyle(QFrame::NoFrame);
m_flatView->setAttribute(Qt::WA_MacShowFocusRect, false);
@@ -821,7 +821,7 @@ QWidget *CallgrindToolPrivate::createWidgets()
// filtering
action = new QAction(tr("Show Project Costs Only"), this);
- action->setIcon(QIcon(Core::Constants::ICON_FILTER));
+ action->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
action->setToolTip(tr("Show only profiling info that originated from this project source."));
action->setCheckable(true);
connect(action, SIGNAL(toggled(bool)), this, SLOT(handleFilterProjectCosts()));
@@ -883,7 +883,7 @@ void CallgrindToolPrivate::showParserResults(const ParseData *data)
if (data->events().isEmpty()) {
msg = tr("Parsing finished, no data.");
} else {
- const QString costStr = QString("%1 %2").arg(QString::number(data->totalCost(0)), data->events().first());
+ const QString costStr = QString::fromLatin1("%1 %2").arg(QString::number(data->totalCost(0)), data->events().first());
msg = tr("Parsing finished, total cost of %1 reported.").arg(costStr);
}
} else {
@@ -985,7 +985,7 @@ void CallgrindToolPrivate::createTextMarks()
const QModelIndex index = model->index(row, DataModel::InclusiveCostColumn);
QString fileName = index.data(DataModel::FileNameRole).toString();
- if (fileName.isEmpty() || fileName == "???")
+ if (fileName.isEmpty() || fileName == QLatin1String("???"))
continue;
bool ok = false;
@@ -1000,7 +1000,7 @@ void CallgrindToolPrivate::createTextMarks()
continue; // isEmpty == true => file does not exist, continue then
// create only one text mark per location
- const QString location = QString("%1:%2").arg(fileName, QString::number(lineNumber));
+ const QString location = QString::fromLatin1("%1:%2").arg(fileName, QString::number(lineNumber));
if (locations.contains(location))
continue;
locations << location;
diff --git a/src/plugins/valgrind/callgrindvisualisation.cpp b/src/plugins/valgrind/callgrindvisualisation.cpp
index 1acbe1ad5c..9da37c6711 100644
--- a/src/plugins/valgrind/callgrindvisualisation.cpp
+++ b/src/plugins/valgrind/callgrindvisualisation.cpp
@@ -228,7 +228,7 @@ Visualisation::Private::Private(Visualisation *qq)
, m_model(new DataProxyModel(qq))
{
// setup scene
- m_scene.setObjectName("Visualisation Scene");
+ m_scene.setObjectName(QLatin1String("Visualisation Scene"));
///NOTE: with size 100x100 the Qt-internal mouse selection fails...
m_scene.setSceneRect(0, 0, 1024, 1024);
@@ -256,9 +256,8 @@ void Visualisation::Private::handleMousePressEvent(QMouseEvent *event,
if (itemAtPos) {
const Function *func = q->functionForItem(itemAtPos);
- if (doubleClicked) {
+ if (doubleClicked)
q->functionActivated(func);
- }
else {
q->scene()->clearSelection();
itemAtPos->setSelected(true);
@@ -283,7 +282,7 @@ Visualisation::Visualisation(QWidget *parent)
: QGraphicsView(parent)
, d(new Private(this))
{
- setObjectName("Visualisation View");
+ setObjectName(QLatin1String("Visualisation View"));
setScene(&d->m_scene);
setRenderHint(QPainter::Antialiasing);
}
diff --git a/src/plugins/valgrind/memcheck/memcheckrunner.cpp b/src/plugins/valgrind/memcheck/memcheckrunner.cpp
index 6d6de55c90..8029c7b847 100644
--- a/src/plugins/valgrind/memcheck/memcheckrunner.cpp
+++ b/src/plugins/valgrind/memcheck/memcheckrunner.cpp
@@ -30,9 +30,9 @@
#include "memcheckrunner.h"
-#include <xmlprotocol/error.h>
-#include <xmlprotocol/status.h>
-#include <xmlprotocol/threadedparser.h>
+#include "../xmlprotocol/error.h"
+#include "../xmlprotocol/status.h"
+#include "../xmlprotocol/threadedparser.h"
#include <utils/qtcassert.h>
@@ -83,7 +83,7 @@ MemcheckRunner::~MemcheckRunner()
QString MemcheckRunner::tool() const
{
- return QString("memcheck");
+ return QLatin1String("memcheck");
}
void MemcheckRunner::setParser(XmlProtocol::ThreadedParser *parser)
@@ -110,10 +110,10 @@ bool MemcheckRunner::start()
connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected()));
QStringList memcheckArguments;
- memcheckArguments << QString("--xml=yes")
- << QString("--xml-socket=127.0.0.1:%1").arg(QString::number(xmlPortNumber))
- << QString("--child-silent-after-fork=yes")
- << QString("--log-socket=127.0.0.1:%1").arg(QString::number(logPortNumber))
+ memcheckArguments << QLatin1String("--xml=yes")
+ << QString::fromLatin1("--xml-socket=127.0.0.1:%1").arg(xmlPortNumber)
+ << QLatin1String("--child-silent-after-fork=yes")
+ << QString::fromLatin1("--log-socket=127.0.0.1:%1").arg(logPortNumber)
<< valgrindArguments();
setValgrindArguments(memcheckArguments);
}
@@ -139,10 +139,10 @@ bool MemcheckRunner::start()
connect(&d->logServer, SIGNAL(newConnection()), SLOT(logSocketConnected()));
QStringList memcheckArguments;
- memcheckArguments << QString("--xml=yes")
- << QString("--xml-socket=%1:%2").arg(ip, QString::number(xmlPortNumber))
- << QString("--child-silent-after-fork=yes")
- << QString("--log-socket=%1:%2").arg(ip, QString::number(logPortNumber));
+ memcheckArguments << QLatin1String("--xml=yes")
+ << QString::fromLatin1("--xml-socket=%1:%2").arg(ip).arg(xmlPortNumber)
+ << QLatin1String("--child-silent-after-fork=yes")
+ << QString::fromLatin1("--log-socket=%1:%2").arg(ip).arg(logPortNumber);
setValgrindArguments(memcheckArguments);
}
diff --git a/src/plugins/valgrind/memcheck/memcheckrunner.h b/src/plugins/valgrind/memcheck/memcheckrunner.h
index 480a8bcf40..251be84c40 100644
--- a/src/plugins/valgrind/memcheck/memcheckrunner.h
+++ b/src/plugins/valgrind/memcheck/memcheckrunner.h
@@ -31,7 +31,7 @@
#ifndef VALGRIND_PROTOCOL_MEMCHECKRUNNER_H
#define VALGRIND_PROTOCOL_MEMCHECKRUNNER_H
-#include <valgrindrunner.h>
+#include "../valgrindrunner.h"
namespace Valgrind {
diff --git a/src/plugins/valgrind/memcheckengine.cpp b/src/plugins/valgrind/memcheckengine.cpp
index 812e2cb6b7..ec3bef87ee 100644
--- a/src/plugins/valgrind/memcheckengine.cpp
+++ b/src/plugins/valgrind/memcheckengine.cpp
@@ -99,9 +99,9 @@ QStringList MemcheckEngine::toolArguments() const
arguments << QLatin1String("--track-origins=yes");
foreach (const QString &file, memcheckSettings->suppressionFiles())
- arguments << QString("--suppressions=%1").arg(file);
+ arguments << QString::fromLatin1("--suppressions=%1").arg(file);
- arguments << QString("--num-callers=%1").arg(memcheckSettings->numCallers());
+ arguments << QString::fromLatin1("--num-callers=%1").arg(memcheckSettings->numCallers());
return arguments;
}
@@ -119,7 +119,7 @@ void MemcheckEngine::receiveLogMessage(const QByteArray &b)
{
QString error = QString::fromLocal8Bit(b);
// workaround https://bugs.kde.org/show_bug.cgi?id=255888
- error.remove(QRegExp("==*== </valgrindoutput>", Qt::CaseSensitive, QRegExp::Wildcard));
+ error.remove(QRegExp(QLatin1String("==*== </valgrindoutput>"), Qt::CaseSensitive, QRegExp::Wildcard));
error = error.trimmed();
diff --git a/src/plugins/valgrind/memcheckerrorview.cpp b/src/plugins/valgrind/memcheckerrorview.cpp
index 05599a0a89..8943616975 100644
--- a/src/plugins/valgrind/memcheckerrorview.cpp
+++ b/src/plugins/valgrind/memcheckerrorview.cpp
@@ -169,7 +169,7 @@ static QString makeFrameName(const Frame &frame, const QString &relativeTo,
if (link && !f.isEmpty() && QFile::exists(fullPath)) {
// make a hyperlink label
- path = QString("<a href=\"file://%1:%2\" %4>%3</a>")
+ path = QString::fromLatin1("<a href=\"file://%1:%2\" %4>%3</a>")
.arg(fullPath, QString::number(frame.line()), path, linkAttr);
}
@@ -177,7 +177,7 @@ static QString makeFrameName(const Frame &frame, const QString &relativeTo,
return QCoreApplication::translate("Valgrind::Internal", "%1 in %2").arg(Qt::escape(fn), path);
if (!path.isEmpty())
return path;
- return QString("0x%1").arg(frame.instructionPointer(), 0, 16);
+ return QString::fromLatin1("0x%1").arg(frame.instructionPointer(), 0, 16);
}
static QString relativeToPath()
@@ -216,7 +216,7 @@ QWidget *MemcheckErrorDelegate::createDetailsWidget(const QModelIndex &errorInde
// code + white-space:pre so the padding (see below) works properly
// don't include frameName here as it should wrap if required and pre-line is not supported
// by Qt yet it seems
- const QString displayTextTemplate = QString("<code style='white-space:pre'>%1:</code> %2");
+ const QString displayTextTemplate = QString::fromLatin1("<code style='white-space:pre'>%1:</code> %2");
const QString relativeTo = relativeToPath();
const Error error = errorIndex.data(ErrorListModel::ErrorRole).value<Error>();
@@ -227,11 +227,11 @@ QWidget *MemcheckErrorDelegate::createDetailsWidget(const QModelIndex &errorInde
errorLabel->setIndent(0);
QPalette p = errorLabel->palette();
QColor lc = p.color(QPalette::Text);
- QString linkStyle = QString("style=\"color:rgba(%1, %2, %3, %4);\"")
+ QString linkStyle = QString::fromLatin1("style=\"color:rgba(%1, %2, %3, %4);\"")
.arg(lc.red()).arg(lc.green()).arg(lc.blue()).arg(int(0.7 * 255));
p.setBrush(QPalette::Text, p.highlightedText());
errorLabel->setPalette(p);
- errorLabel->setText(QString("%1&nbsp;&nbsp;<span %4>%2</span>")
+ errorLabel->setText(QString::fromLatin1("%1&nbsp;&nbsp;<span %4>%2</span>")
.arg(error.what(), errorLocation(errorIndex, error, true, linkStyle),
linkStyle));
connect(errorLabel, SIGNAL(linkActivated(QString)), SLOT(openLinkInEditor(QString)));
@@ -265,7 +265,7 @@ QWidget *MemcheckErrorDelegate::createDetailsWidget(const QModelIndex &errorInde
p.setBrush(QPalette::Base, p.alternateBase());
frameLabel->setPalette(p);
}
- frameLabel->setFont(QFont("monospace"));
+ frameLabel->setFont(QFont(QLatin1String("monospace")));
connect(frameLabel, SIGNAL(linkActivated(QString)), SLOT(openLinkInEditor(QString)));
// pad frameNr to 2 chars since only 50 frames max are supported by valgrind
const QString displayText = displayTextTemplate
@@ -343,7 +343,7 @@ void MemcheckErrorDelegate::paint(QPainter *painter, const QStyleOptionViewItem
const int widthLeft = opt.rect.width() - (pos.x() + whatWidth + space + s_itemMargin);
if (widthLeft > 0) {
QFont monospace = opt.font;
- monospace.setFamily("monospace");
+ monospace.setFamily(QLatin1String("monospace"));
QFontMetrics metrics(monospace);
QColor nameColor = textColor;
nameColor.setAlphaF(0.7);
@@ -414,9 +414,8 @@ void MemcheckErrorDelegate::copy()
const QString relativeTo = relativeToPath();
foreach (const Stack &stack, error.stacks()) {
- if (!stack.auxWhat().isEmpty()) {
+ if (!stack.auxWhat().isEmpty())
stream << stack.auxWhat();
- }
int i = 1;
foreach (const Frame &frame, stack.frames()) {
stream << " " << i++ << ": " << makeFrameName(frame, relativeTo) << "\n";
@@ -430,7 +429,7 @@ void MemcheckErrorDelegate::copy()
void MemcheckErrorDelegate::openLinkInEditor(const QString &link)
{
const int pathStart = strlen("file://");
- const int pathEnd = link.lastIndexOf(':');
+ const int pathEnd = link.lastIndexOf(QLatin1Char(':'));
const QString path = link.mid(pathStart, pathEnd - pathStart);
const int line = link.mid(pathEnd + 1).toInt(0);
TextEditor::BaseTextEditorWidget::openEditorAt(path, qMax(line, 0));
@@ -445,7 +444,7 @@ MemcheckErrorView::MemcheckErrorView(QWidget *parent)
m_copyAction = new QAction(this);
m_copyAction->setText(tr("Copy Selection"));
- m_copyAction->setIcon(QIcon(Core::Constants::ICON_COPY));
+ m_copyAction->setIcon(QIcon(QLatin1String(Core::Constants::ICON_COPY)));
m_copyAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_C));
m_copyAction->setShortcutContext(Qt::WidgetWithChildrenShortcut);
connect(m_copyAction, SIGNAL(triggered()), itemDelegate(), SLOT(copy()));
diff --git a/src/plugins/valgrind/memchecktool.cpp b/src/plugins/valgrind/memchecktool.cpp
index db722c391d..5e82687068 100644
--- a/src/plugins/valgrind/memchecktool.cpp
+++ b/src/plugins/valgrind/memchecktool.cpp
@@ -86,6 +86,7 @@
#include <utils/stylehelper.h>
using namespace Analyzer;
+using namespace ProjectExplorer;
using namespace Valgrind::XmlProtocol;
namespace Valgrind {
@@ -116,11 +117,11 @@ void MemcheckErrorFilterProxyModel::setFilterExternalIssues(bool filter)
bool MemcheckErrorFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
- // we only deal with toplevel items
+ // We only deal with toplevel items.
if (sourceParent.isValid())
return true;
- // because toplevel items have no parent, we can't use sourceParent to find them. we just use
+ // Because toplevel items have no parent, we can't use sourceParent to find them. we just use
// sourceParent as an invalid index, telling the model that the index we're looking for has no
// parent.
QAbstractItemModel *model = sourceModel();
@@ -130,23 +131,21 @@ bool MemcheckErrorFilterProxyModel::filterAcceptsRow(int sourceRow, const QModel
const Error error = sourceIndex.data(ErrorListModel::ErrorRole).value<Error>();
- // filter on kind
+ // Filter on kind
if (!m_acceptedKinds.contains(error.kind()))
return false;
- // filter non-project stuff
+ // Filter non-project stuff
if (m_filterExternalIssues && !error.stacks().isEmpty()) {
// ALGORITHM: look at last five stack frames, if none of these is inside any open projects,
// assume this error was created by an external library
- ProjectExplorer::SessionManager *session
- = ProjectExplorer::ProjectExplorerPlugin::instance()->session();
+ SessionManager *session = ProjectExplorerPlugin::instance()->session();
QSet<QString> validFolders;
- foreach (ProjectExplorer::Project *project, session->projects()) {
+ foreach (Project *project, session->projects()) {
validFolders << project->projectDirectory();
- foreach (ProjectExplorer::Target *target, project->targets()) {
- foreach (ProjectExplorer::BuildConfiguration *config, target->buildConfigurations()) {
+ foreach (Target *target, project->targets()) {
+ foreach (BuildConfiguration *config, target->buildConfigurations())
validFolders << config->buildDirectory();
- }
}
}
@@ -155,7 +154,7 @@ bool MemcheckErrorFilterProxyModel::filterAcceptsRow(int sourceRow, const QModel
const int framesToLookAt = qMin(6, frames.size());
bool inProject = false;
- for ( int i = 0; i < framesToLookAt; ++i ) {
+ for (int i = 0; i < framesToLookAt; ++i) {
const Frame &frame = frames.at(i);
foreach (const QString &folder, validFolders) {
if (frame.object().startsWith(folder)) {
@@ -228,14 +227,11 @@ void MemcheckTool::settingsDestroyed(QObject *settings)
void MemcheckTool::maybeActiveRunConfigurationChanged()
{
AnalyzerSettings *settings = 0;
- ProjectExplorer::ProjectExplorerPlugin *pe = ProjectExplorer::ProjectExplorerPlugin::instance();
- if (ProjectExplorer::Project *project = pe->startupProject()) {
- if (ProjectExplorer::Target *target = project->activeTarget()) {
- if (ProjectExplorer::RunConfiguration *rc = target->activeRunConfiguration()) {
+ ProjectExplorerPlugin *pe = ProjectExplorerPlugin::instance();
+ if (Project *project = pe->startupProject())
+ if (Target *target = project->activeTarget())
+ if (RunConfiguration *rc = target->activeRunConfiguration())
settings = rc->extraAspect<AnalyzerRunConfigurationAspect>();
- }
- }
- }
if (!settings) // fallback to global settings
settings = AnalyzerGlobalSettings::instance();
@@ -283,12 +279,12 @@ void MemcheckTool::maybeActiveRunConfigurationChanged()
Core::Id MemcheckTool::id() const
{
- return "Memcheck";
+ return Core::Id("Memcheck");
}
-ProjectExplorer::RunMode MemcheckTool::runMode() const
+RunMode MemcheckTool::runMode() const
{
- return ProjectExplorer::MemcheckRunMode;
+ return MemcheckRunMode;
}
QString MemcheckTool::displayName() const
@@ -346,7 +342,7 @@ public:
//if no frame belonging to the project was found, return the first one that is not malloc/new
foreach (const Frame &frame, frames) {
if (!frame.functionName().isEmpty() && frame.functionName() != QLatin1String("malloc")
- && !frame.functionName().startsWith("operator new(") )
+ && !frame.functionName().startsWith(QLatin1String("operator new(")))
{
return frame;
}
@@ -386,14 +382,14 @@ QWidget *MemcheckTool::createWidgets()
m_errorView->setSelectionBehavior(QAbstractItemView::SelectRows);
m_errorView->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
m_errorView->setAutoScroll(false);
- m_errorView->setObjectName("Valgrind.MemcheckTool.ErrorView");
+ m_errorView->setObjectName(QLatin1String("Valgrind.MemcheckTool.ErrorView"));
QDockWidget *errorDock = AnalyzerManager::createDockWidget
(this, tr("Memory Issues"), m_errorView, Qt::BottomDockWidgetArea);
errorDock->show();
mw->splitDockWidget(mw->toolBarDockWidget(), errorDock, Qt::Vertical);
- connect(ProjectExplorer::ProjectExplorerPlugin::instance(),
+ connect(ProjectExplorerPlugin::instance(),
SIGNAL(updateRunActions()), SLOT(maybeActiveRunConfigurationChanged()));
//
@@ -429,7 +425,7 @@ QWidget *MemcheckTool::createWidgets()
m_goNext = action;
QToolButton *filterButton = new QToolButton;
- filterButton->setIcon(QIcon(Core::Constants::ICON_FILTER));
+ filterButton->setIcon(QIcon(QLatin1String(Core::Constants::ICON_FILTER)));
filterButton->setText(tr("Error Filter"));
filterButton->setPopupMode(QToolButton::InstantPopup);
@@ -451,10 +447,10 @@ QWidget *MemcheckTool::createWidgets()
}
IAnalyzerEngine *MemcheckTool::createEngine(const AnalyzerStartParameters &sp,
- ProjectExplorer::RunConfiguration *runConfiguration)
+ RunConfiguration *runConfiguration)
{
m_frameFinder->setFiles(runConfiguration ? runConfiguration->target()
- ->project()->files(ProjectExplorer::Project::AllFiles) : QStringList());
+ ->project()->files(Project::AllFiles) : QStringList());
MemcheckEngine *engine = new MemcheckEngine(this, sp, runConfiguration);
@@ -480,7 +476,7 @@ void MemcheckTool::engineStarting(const IAnalyzerEngine *engine)
clearErrorView();
QString dir;
- if (ProjectExplorer::RunConfiguration *rc = engine->runConfiguration())
+ if (RunConfiguration *rc = engine->runConfiguration())
dir = rc->target()->project()->projectDirectory() + QDir::separator();
const MemcheckEngine *mEngine = dynamic_cast<const MemcheckEngine *>(engine);
diff --git a/src/plugins/valgrind/suppressiondialog.cpp b/src/plugins/valgrind/suppressiondialog.cpp
index d959f1d8d3..b235bdf0e4 100644
--- a/src/plugins/valgrind/suppressiondialog.cpp
+++ b/src/plugins/valgrind/suppressiondialog.cpp
@@ -83,7 +83,7 @@ static QString suppressionText(const Error &error)
newName = frame.object();
if (!newName.isEmpty())
- sup.setName(newName + '[' + sup.kind() + ']');
+ sup.setName(newName + QLatin1Char('[') + sup.kind() + QLatin1Char(']'));
}
return sup.toString();
diff --git a/src/plugins/valgrind/valgrind.qbs b/src/plugins/valgrind/valgrind.qbs
index dfdc6d6582..e3add86457 100644
--- a/src/plugins/valgrind/valgrind.qbs
+++ b/src/plugins/valgrind/valgrind.qbs
@@ -13,15 +13,6 @@ QtcPlugin {
Depends { name: "RemoteLinux" }
Depends { name: "CPlusPlus"}
- Depends { name: "cpp" }
- cpp.includePaths: [
- ".",
- "valgrind",
- "..",
- "../../libs",
- buildDirectory
- ]
-
files: [
"callgrindcostdelegate.cpp",
"callgrindcostdelegate.h",
@@ -54,16 +45,16 @@ QtcPlugin {
"valgrindengine.h",
"valgrindplugin.cpp",
"valgrindplugin.h",
+ "valgrindprocess.cpp",
+ "valgrindprocess.h",
+ "valgrindrunner.cpp",
+ "valgrindrunner.h",
"valgrindsettings.cpp",
"valgrindsettings.h",
"valgrindtool.cpp",
"valgrindtool.h",
"workarounds.cpp",
"workarounds.h",
- "valgrindprocess.cpp",
- "valgrindprocess.h",
- "valgrindrunner.cpp",
- "valgrindrunner.h",
"callgrind/callgrindabstractmodel.h",
"callgrind/callgrindcallmodel.cpp",
"callgrind/callgrindcallmodel.h",
@@ -115,7 +106,6 @@ QtcPlugin {
"xmlprotocol/suppression.cpp",
"xmlprotocol/suppression.h",
"xmlprotocol/threadedparser.cpp",
- "xmlprotocol/threadedparser.h"
+ "xmlprotocol/threadedparser.h",
]
}
-
diff --git a/src/plugins/valgrind/valgrindconfigwidget.cpp b/src/plugins/valgrind/valgrindconfigwidget.cpp
index 79bba85fd5..e39eff145c 100644
--- a/src/plugins/valgrind/valgrindconfigwidget.cpp
+++ b/src/plugins/valgrind/valgrindconfigwidget.cpp
@@ -33,6 +33,7 @@
#include "ui_valgrindconfigwidget.h"
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -63,12 +64,12 @@ ValgrindConfigWidget::ValgrindConfigWidget(ValgrindBaseSettings *settings,
connect(m_settings, SIGNAL(valgrindExecutableChanged(QString)),
m_ui->valgrindExeChooser, SLOT(setPath(QString)));
-#ifdef Q_OS_WIN
- // FIXME: On Window we know that we don't have a local valgrind
- // executable, so having the "Browse" button in the path chooser
- // (which is needed for the remote executable) is confusing.
- m_ui->valgrindExeChooser->buttonAtIndex(0)->hide();
-#endif
+ if (Utils::HostOsInfo::isWindowsHost()) {
+ // FIXME: On Window we know that we don't have a local valgrind
+ // executable, so having the "Browse" button in the path chooser
+ // (which is needed for the remote executable) is confusing.
+ m_ui->valgrindExeChooser->buttonAtIndex(0)->hide();
+ }
//
// Callgrind
diff --git a/src/plugins/valgrind/valgrindengine.cpp b/src/plugins/valgrind/valgrindengine.cpp
index 1cf374b9cb..74f49dd959 100644
--- a/src/plugins/valgrind/valgrindengine.cpp
+++ b/src/plugins/valgrind/valgrindengine.cpp
@@ -36,7 +36,7 @@
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/progressmanager/futureprogress.h>
#include <extensionsystem/pluginmanager.h>
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <analyzerbase/analyzermanager.h>
#include <QApplication>
@@ -45,9 +45,12 @@
#define VALGRIND_DEBUG_OUTPUT 0
using namespace Analyzer;
-using namespace Valgrind::Internal;
+using namespace Core;
using namespace Utils;
+namespace Valgrind {
+namespace Internal {
+
const int progressMaximum = 1000000;
ValgrindEngine::ValgrindEngine(IAnalyzerTool *tool, const AnalyzerStartParameters &sp,
@@ -79,25 +82,25 @@ bool ValgrindEngine::start()
{
emit starting(this);
- Core::FutureProgress *fp = Core::ICore::progressManager()->addTask(m_progress->future(),
- progressTitle(), "valgrind");
- fp->setKeepOnFinish(Core::FutureProgress::HideOnFinish);
+ FutureProgress *fp = ICore::progressManager()->addTask(m_progress->future(),
+ progressTitle(), QLatin1String("valgrind"));
+ fp->setKeepOnFinish(FutureProgress::HideOnFinish);
m_progress->setProgressRange(0, progressMaximum);
m_progress->reportStarted();
m_progressWatcher->setFuture(m_progress->future());
m_progress->setProgressValue(progressMaximum / 10);
+ const AnalyzerStartParameters &sp = startParameters();
#if VALGRIND_DEBUG_OUTPUT
- emit outputReceived(tr("Valgrind options: %1").arg(toolArguments().join(" ")), Utils::DebugFormat);
- emit outputReceived(tr("Working directory: %1").arg(m_workingDirectory), Utils::DebugFormat);
- emit outputReceived(tr("Command-line arguments: %1").arg(m_commandLineArguments), Utils::DebugFormat);
+ emit outputReceived(tr("Valgrind options: %1").arg(toolArguments().join(QLatin1Char(' '))), DebugFormat);
+ emit outputReceived(tr("Working directory: %1").arg(sp.workingDirectory), DebugFormat);
+ emit outputReceived(tr("Commandline arguments: %1").arg(sp.debuggeeArgs), DebugFormat);
#endif
- const AnalyzerStartParameters &sp = startParameters();
runner()->setWorkingDirectory(sp.workingDirectory);
QString valgrindExe = m_settings->subConfig<ValgrindBaseSettings>()->valgrindExecutable();
if (!sp.analyzerCmdPrefix.isEmpty())
- valgrindExe = sp.analyzerCmdPrefix + ' ' + valgrindExe;
+ valgrindExe = sp.analyzerCmdPrefix + QLatin1Char(' ') + valgrindExe;
runner()->setValgrindExecutable(valgrindExe);
runner()->setValgrindArguments(toolArguments());
runner()->setDebuggeeExecutable(sp.debuggee);
@@ -140,12 +143,12 @@ void ValgrindEngine::handleProgressCanceled()
void ValgrindEngine::handleProgressFinished()
{
- QApplication::alert(Core::ICore::mainWindow(), 3000);
+ QApplication::alert(ICore::mainWindow(), 3000);
}
void ValgrindEngine::runnerFinished()
{
- emit outputReceived(tr("** Analyzing finished **\n"), Utils::NormalMessageFormat);
+ emit outputReceived(tr("** Analyzing finished **\n"), NormalMessageFormat);
emit finished();
m_progress->reportFinished();
@@ -156,7 +159,7 @@ void ValgrindEngine::runnerFinished()
this, SLOT(runnerFinished()));
}
-void ValgrindEngine::receiveProcessOutput(const QByteArray &b, Utils::OutputFormat format)
+void ValgrindEngine::receiveProcessOutput(const QByteArray &output, OutputFormat format)
{
int progress = m_progress->progressValue();
if (progress < 5 * progressMaximum / 10)
@@ -164,33 +167,30 @@ void ValgrindEngine::receiveProcessOutput(const QByteArray &b, Utils::OutputForm
else if (progress < 9 * progressMaximum / 10)
progress += progress / 1000;
m_progress->setProgressValue(progress);
- emit outputReceived(QString::fromLocal8Bit(b), format);
+ emit outputReceived(QString::fromLocal8Bit(output), format);
}
-void ValgrindEngine::receiveProcessError(const QString &error, QProcess::ProcessError e)
+void ValgrindEngine::receiveProcessError(const QString &message, QProcess::ProcessError error)
{
- if (e == QProcess::FailedToStart) {
+ if (error == QProcess::FailedToStart) {
const QString &valgrind = m_settings->subConfig<ValgrindBaseSettings>()->valgrindExecutable();
- if (!valgrind.isEmpty()) {
- emit outputReceived(tr("** Error: \"%1\" could not be started: %2 **\n").arg(valgrind).arg(error), Utils::ErrorMessageFormat);
- } else {
- emit outputReceived(tr("** Error: no valgrind executable set **\n"), Utils::ErrorMessageFormat);
- }
- } else if (m_isStopping && e == QProcess::Crashed) { // process gets killed on stop
- emit outputReceived(tr("** Process Terminated **\n"), Utils::ErrorMessageFormat);
+ if (!valgrind.isEmpty())
+ emit outputReceived(tr("** Error: \"%1\" could not be started: %2 **\n").arg(valgrind).arg(message), ErrorMessageFormat);
+ else
+ emit outputReceived(tr("** Error: no valgrind executable set **\n"), ErrorMessageFormat);
+ } else if (m_isStopping && error == QProcess::Crashed) { // process gets killed on stop
+ emit outputReceived(tr("** Process Terminated **\n"), ErrorMessageFormat);
} else {
- emit outputReceived(QString("** %1 **\n").arg(error), Utils::ErrorMessageFormat);
+ emit outputReceived(QString::fromLatin1("** %1 **\n").arg(message), ErrorMessageFormat);
}
if (m_isStopping)
return;
- ///FIXME: get a better API for this into Qt Creator
- QList<Core::IOutputPane *> panes = ExtensionSystem::PluginManager::getObjects<Core::IOutputPane>();
- foreach (Core::IOutputPane *pane, panes) {
- if (pane->displayName() == tr("Application Output")) {
- pane->popup(Core::IOutputPane::NoModeSwitch);
- break;
- }
- }
+ QObject *obj = ExtensionSystem::PluginManager::getObjectByName(QLatin1String("AppOutputPane"));
+ if (IOutputPane *pane = qobject_cast<IOutputPane *>(obj))
+ pane->popup(IOutputPane::NoModeSwitch);
}
+
+} // namespace Internal
+} // namepsace Valgrind
diff --git a/src/plugins/valgrind/valgrindengine.h b/src/plugins/valgrind/valgrindengine.h
index 47bb650164..f58f0bfc83 100644
--- a/src/plugins/valgrind/valgrindengine.h
+++ b/src/plugins/valgrind/valgrindengine.h
@@ -32,19 +32,13 @@
#define VALGRINDENGINE_H
#include <analyzerbase/ianalyzerengine.h>
-
#include <utils/environment.h>
-
#include <valgrind/valgrindrunner.h>
-#include <QString>
-#include <QByteArray>
#include <QFutureInterface>
#include <QFutureWatcher>
-namespace Analyzer {
-class AnalyzerSettings;
-}
+namespace Analyzer { class AnalyzerSettings; }
namespace Valgrind {
namespace Internal {
@@ -78,8 +72,8 @@ private slots:
void handleProgressFinished();
void runnerFinished();
- void receiveProcessOutput(const QByteArray &, Utils::OutputFormat);
- void receiveProcessError(const QString &, QProcess::ProcessError);
+ void receiveProcessOutput(const QByteArray &output, Utils::OutputFormat format);
+ void receiveProcessError(const QString &message, QProcess::ProcessError error);
private:
bool m_isStopping;
diff --git a/src/plugins/valgrind/valgrindplugin.cpp b/src/plugins/valgrind/valgrindplugin.cpp
index 71f5d85b80..005d0a4c4f 100644
--- a/src/plugins/valgrind/valgrindplugin.cpp
+++ b/src/plugins/valgrind/valgrindplugin.cpp
@@ -40,9 +40,10 @@
#include <analyzerbase/analyzerstartparameters.h>
#include <analyzerbase/startremotedialog.h>
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/projectexplorer.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
#include <QDebug>
@@ -91,9 +92,8 @@ void ValgrindPlugin::startValgrindTool(IAnalyzerTool *tool, StartMode mode)
bool ValgrindPlugin::initialize(const QStringList &, QString *)
{
StartModes modes;
-#ifndef Q_OS_WIN
- modes.append(StartMode(StartLocal));
-#endif
+ if (!Utils::HostOsInfo::isWindowsHost())
+ modes.append(StartMode(StartLocal));
modes.append(StartMode(StartRemote));
AnalyzerManager::addTool(new MemcheckTool(this), modes);
diff --git a/src/plugins/valgrind/valgrindprocess.cpp b/src/plugins/valgrind/valgrindprocess.cpp
index 407c7e728e..6fa61b288a 100644
--- a/src/plugins/valgrind/valgrindprocess.cpp
+++ b/src/plugins/valgrind/valgrindprocess.cpp
@@ -201,13 +201,13 @@ void RemoteValgrindProcess::connected()
QString cmd;
if (!m_workingDir.isEmpty())
- cmd += QString("cd '%1' && ").arg(m_workingDir);
+ cmd += QString::fromLatin1("cd '%1' && ").arg(m_workingDir);
QString arguments;
Utils::QtcProcess::addArgs(&arguments, m_valgrindArgs);
Utils::QtcProcess::addArg(&arguments, m_debuggee);
Utils::QtcProcess::addArgs(&arguments, m_debuggeeArgs);
- cmd += m_valgrindExe + ' ' + arguments;
+ cmd += m_valgrindExe + QLatin1Char(' ') + arguments;
m_process = m_connection->createRemoteProcess(cmd.toUtf8());
connect(m_process.data(), SIGNAL(readyReadStandardError()), this, SLOT(standardError()));
@@ -240,12 +240,12 @@ void RemoteValgrindProcess::processStarted()
const QString proc = m_valgrindExe.split(QLatin1Char(' ')).last();
// sleep required since otherwise we might only match "bash -c..."
// and not the actual valgrind run
- const QString cmd = QString("sleep 1; ps ax" // list all processes with aliased name
- " | grep '\\b%1.*%2'" // find valgrind process
- " | tail -n 1" // limit to single process
- // we pick the last one, first would be "bash -c ..."
- " | awk '{print $1;}'" // get pid
- ).arg(proc, QFileInfo(m_debuggee).fileName());
+ const QString cmd = QString::fromLatin1("sleep 1; ps ax" // list all processes with aliased name
+ " | grep '\\b%1.*%2'" // find valgrind process
+ " | tail -n 1" // limit to single process
+ // we pick the last one, first would be "bash -c ..."
+ " | awk '{print $1;}'" // get pid
+ ).arg(proc, QFileInfo(m_debuggee).fileName());
m_findPID = m_connection->createRemoteProcess(cmd.toUtf8());
connect(m_findPID.data(), SIGNAL(readyReadStandardError()), this, SLOT(standardError()));
@@ -297,11 +297,11 @@ void RemoteValgrindProcess::close()
QTC_ASSERT(m_connection->state() == QSsh::SshConnection::Connected, return);
if (m_process) {
if (m_pid) {
- const QString killTemplate = QString("kill -%2 %1" // kill
+ const QString killTemplate = QString::fromLatin1("kill -%2 %1" // kill
).arg(m_pid);
- const QString niceKill = killTemplate.arg("SIGTERM");
- const QString brutalKill = killTemplate.arg("SIGKILL");
+ const QString niceKill = killTemplate.arg(QLatin1String("SIGTERM"));
+ const QString brutalKill = killTemplate.arg(QLatin1String("SIGKILL"));
const QString remoteCall = niceKill + QLatin1String("; sleep 1; ") + brutalKill;
QSsh::SshRemoteProcess::Ptr cleanup = m_connection->createRemoteProcess(remoteCall.toUtf8());
diff --git a/src/plugins/valgrind/valgrindrunner.cpp b/src/plugins/valgrind/valgrindrunner.cpp
index 00f563b72d..55e2a26faa 100644
--- a/src/plugins/valgrind/valgrindrunner.cpp
+++ b/src/plugins/valgrind/valgrindrunner.cpp
@@ -31,9 +31,10 @@
#include "valgrindrunner.h"
#include "valgrindprocess.h"
+#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <utils/qtcassert.h>
-#include <utils/environment.h>
#include <ssh/sshconnection.h>
#include <ssh/sshremoteprocess.h>
@@ -89,12 +90,11 @@ void ValgrindRunner::Private::run(ValgrindProcess *_process)
// consider appending our options last so they override any interfering user-supplied options
// -q as suggested by valgrind manual
QStringList valgrindArgs = valgrindArguments;
- valgrindArgs << QString("--tool=%1").arg(q->tool());
+ valgrindArgs << QString::fromLatin1("--tool=%1").arg(q->tool());
-#ifdef Q_OS_MAC
- // May be slower to start but without it we get no filenames for symbols.
- valgrindArgs << QLatin1String("--dsymutil=yes");
-#endif
+ if (Utils::HostOsInfo::isMacHost())
+ // May be slower to start but without it we get no filenames for symbols.
+ valgrindArgs << QLatin1String("--dsymutil=yes");
QObject::connect(process, SIGNAL(processOutput(QByteArray,Utils::OutputFormat)),
q, SIGNAL(processOutputReceived(QByteArray,Utils::OutputFormat)));
diff --git a/src/plugins/valgrind/valgrindsettings.cpp b/src/plugins/valgrind/valgrindsettings.cpp
index aab6fe3d5b..7d89a79e8e 100644
--- a/src/plugins/valgrind/valgrindsettings.cpp
+++ b/src/plugins/valgrind/valgrindsettings.cpp
@@ -172,7 +172,7 @@ QString ValgrindBaseSettings::valgrindExecutable() const
return m_valgrindExecutable;
}
-QString ValgrindBaseSettings::id() const
+Core::Id ValgrindBaseSettings::id() const
{
return "Analyzer.Valgrind.Settings";
}
@@ -296,9 +296,9 @@ QVariantMap ValgrindGlobalSettings::defaults() const
QVariantMap map = ValgrindBaseSettings::defaults();
// Memcheck
- map.insert(suppressionFilesC, QStringList());
- map.insert(lastSuppressionDirectoryC, QString());
- map.insert(lastSuppressionHistoryC, QStringList());
+ map.insert(QLatin1String(suppressionFilesC), QStringList());
+ map.insert(QLatin1String(lastSuppressionDirectoryC), QString());
+ map.insert(QLatin1String(lastSuppressionHistoryC), QStringList());
// Callgrind
map.insert(QLatin1String(callgrindCostFormatC), CostDelegate::FormatRelative);
@@ -312,9 +312,9 @@ void ValgrindGlobalSettings::fromMap(const QVariantMap &map)
ValgrindBaseSettings::fromMap(map);
// Memcheck
- m_suppressionFiles = map.value(suppressionFilesC).toStringList();
- m_lastSuppressionDirectory = map.value(lastSuppressionDirectoryC).toString();
- m_lastSuppressionHistory = map.value(lastSuppressionHistoryC).toStringList();
+ m_suppressionFiles = map.value(QLatin1String(suppressionFilesC)).toStringList();
+ m_lastSuppressionDirectory = map.value(QLatin1String(lastSuppressionDirectoryC)).toString();
+ m_lastSuppressionHistory = map.value(QLatin1String(lastSuppressionHistoryC)).toStringList();
// Callgrind
// special code as the default one does not cope with the enum properly
@@ -324,14 +324,21 @@ void ValgrindGlobalSettings::fromMap(const QVariantMap &map)
setIfPresent(map, QLatin1String(callgrindShortenTemplates), &m_shortenTemplates);
}
+AbstractAnalyzerSubConfig *ValgrindGlobalSettings::clone()
+{
+ ValgrindGlobalSettings *other = new ValgrindGlobalSettings;
+ other->fromMap(toMap());
+ return other;
+}
+
QVariantMap ValgrindGlobalSettings::toMap() const
{
QVariantMap map = ValgrindBaseSettings::toMap();
// Memcheck
- map.insert(suppressionFilesC, m_suppressionFiles);
- map.insert(lastSuppressionDirectoryC, m_lastSuppressionDirectory);
- map.insert(lastSuppressionHistoryC, m_lastSuppressionHistory);
+ map.insert(QLatin1String(suppressionFilesC), m_suppressionFiles);
+ map.insert(QLatin1String(lastSuppressionDirectoryC), m_lastSuppressionDirectory);
+ map.insert(QLatin1String(lastSuppressionHistoryC), m_lastSuppressionHistory);
// Callgrind
map.insert(QLatin1String(callgrindCostFormatC), m_costFormat);
@@ -442,8 +449,8 @@ QVariantMap ValgrindProjectSettings::defaults() const
QVariantMap map = ValgrindBaseSettings::defaults();
// Memcheck
- map.insert(addedSuppressionFilesC, QStringList());
- map.insert(removedSuppressionFilesC, QStringList());
+ map.insert(QLatin1String(addedSuppressionFilesC), QStringList());
+ map.insert(QLatin1String(removedSuppressionFilesC), QStringList());
return map;
}
@@ -453,8 +460,15 @@ void ValgrindProjectSettings::fromMap(const QVariantMap &map)
ValgrindBaseSettings::fromMap(map);
// Memcheck
- setIfPresent(map, addedSuppressionFilesC, &m_addedSuppressionFiles);
- setIfPresent(map, removedSuppressionFilesC, &m_disabledGlobalSuppressionFiles);
+ setIfPresent(map, QLatin1String(addedSuppressionFilesC), &m_addedSuppressionFiles);
+ setIfPresent(map, QLatin1String(removedSuppressionFilesC), &m_disabledGlobalSuppressionFiles);
+}
+
+AbstractAnalyzerSubConfig *ValgrindProjectSettings::clone()
+{
+ ValgrindProjectSettings *other = new ValgrindProjectSettings;
+ other->fromMap(toMap());
+ return other;
}
QVariantMap ValgrindProjectSettings::toMap() const
@@ -462,8 +476,8 @@ QVariantMap ValgrindProjectSettings::toMap() const
QVariantMap map = ValgrindBaseSettings::toMap();
// Memcheck
- map.insert(addedSuppressionFilesC, m_addedSuppressionFiles);
- map.insert(removedSuppressionFilesC, m_disabledGlobalSuppressionFiles);
+ map.insert(QLatin1String(addedSuppressionFilesC), m_addedSuppressionFiles);
+ map.insert(QLatin1String(removedSuppressionFilesC), m_disabledGlobalSuppressionFiles);
return map;
}
diff --git a/src/plugins/valgrind/valgrindsettings.h b/src/plugins/valgrind/valgrindsettings.h
index 1989b1d2f4..b7d56d06b8 100644
--- a/src/plugins/valgrind/valgrindsettings.h
+++ b/src/plugins/valgrind/valgrindsettings.h
@@ -55,7 +55,7 @@ public:
virtual QVariantMap defaults() const;
virtual void fromMap(const QVariantMap &map);
- virtual QString id() const;
+ virtual Core::Id id() const;
virtual QString displayName() const;
signals:
@@ -173,6 +173,7 @@ public:
QVariantMap toMap() const;
QVariantMap defaults() const;
void fromMap(const QVariantMap &map);
+ virtual AbstractAnalyzerSubConfig *clone();
/*
* Global memcheck settings
@@ -230,6 +231,7 @@ public:
QVariantMap toMap() const;
QVariantMap defaults() const;
void fromMap(const QVariantMap &map);
+ virtual AbstractAnalyzerSubConfig *clone();
/**
* Per-project memcheck settings, saves a diff to the global suppression files list
diff --git a/src/plugins/valgrind/valgrindtool.cpp b/src/plugins/valgrind/valgrindtool.cpp
index ada0e79508..37144fe933 100644
--- a/src/plugins/valgrind/valgrindtool.cpp
+++ b/src/plugins/valgrind/valgrindtool.cpp
@@ -31,7 +31,7 @@
#include <remotelinux/remotelinuxrunconfiguration.h>
-#include <projectexplorer/applicationrunconfiguration.h>
+#include <projectexplorer/localapplicationrunconfiguration.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/target.h>
diff --git a/src/plugins/valgrind/xmlprotocol/error.cpp b/src/plugins/valgrind/xmlprotocol/error.cpp
index 744cd87d67..f7c8cbca35 100644
--- a/src/plugins/valgrind/xmlprotocol/error.cpp
+++ b/src/plugins/valgrind/xmlprotocol/error.cpp
@@ -224,29 +224,23 @@ QString Error::toXml() const
}
foreach (const Stack &stack, d->stacks) {
- if (!stack.auxWhat().isEmpty()) {
+ if (!stack.auxWhat().isEmpty())
stream << " <auxwhat>" << stack.auxWhat() << "</auxwhat>\n";
- }
stream << " <stack>\n";
foreach (const Frame &frame, stack.frames()) {
stream << " <frame>\n";
stream << " <ip>0x" << QString::number(frame.instructionPointer(), 16) << "</ip>\n";
- if (!frame.object().isEmpty()) {
+ if (!frame.object().isEmpty())
stream << " <obj>" << frame.object() << "</obj>\n";
- }
- if (!frame.functionName().isEmpty()) {
+ if (!frame.functionName().isEmpty())
stream << " <fn>" << frame.functionName() << "</fn>\n";
- }
- if (!frame.directory().isEmpty()) {
+ if (!frame.directory().isEmpty())
stream << " <dir>" << frame.directory() << "</dir>\n";
- }
- if (!frame.file().isEmpty()) {
+ if (!frame.file().isEmpty())
stream << " <file>" << frame.file() << "</file>\n";
- }
- if (frame.line() != -1) {
+ if (frame.line() != -1)
stream << " <line>" << frame.line() << "</line>";
- }
stream << " </frame>\n";
}
diff --git a/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp b/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp
index 89fc938c84..78e5982a25 100644
--- a/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp
+++ b/src/plugins/valgrind/xmlprotocol/modelhelpers.cpp
@@ -45,7 +45,7 @@ QString toolTipForFrame(const Frame &frame)
if (!frame.file().isEmpty()) {
location = frame.directory() + QDir::separator() + frame.file();
if (frame.line() > 0)
- location += ':' + QString::number(frame.line());
+ location += QLatin1Char(':') + QString::number(frame.line());
}
typedef QPair<QString, QString> StringPair;
@@ -60,14 +60,14 @@ QString toolTipForFrame(const Frame &frame)
if (frame.instructionPointer())
lines << qMakePair(QCoreApplication::translate("Valgrind::XmlProtocol",
"Instruction pointer:"),
- QString::fromAscii("0x%1").arg(frame.instructionPointer(), 0, 16));
+ QString::fromLatin1("0x%1").arg(frame.instructionPointer(), 0, 16));
if (!frame.object().isEmpty())
lines << qMakePair(QCoreApplication::translate("Valgrind::XmlProtocol", "Object:"), frame.object());
- QString html = "<html>"
+ QString html = QLatin1String("<html>"
"<head>"
"<style>dt { font-weight:bold; } dd { font-family: monospace; }</style>\n"
- "<body><dl>";
+ "<body><dl>");
foreach (const StringPair &pair, lines) {
html += QLatin1String("<dt>");
@@ -76,7 +76,7 @@ QString toolTipForFrame(const Frame &frame)
html += pair.second;
html += QLatin1String("</dd>\n");
}
- html += "</dl></body></html>";
+ html += QLatin1String("</dl></body></html>");
return html;
}
diff --git a/src/plugins/valgrind/xmlprotocol/parser.cpp b/src/plugins/valgrind/xmlprotocol/parser.cpp
index 5b0372076c..ca76a006f5 100644
--- a/src/plugins/valgrind/xmlprotocol/parser.cpp
+++ b/src/plugins/valgrind/xmlprotocol/parser.cpp
@@ -221,9 +221,8 @@ QXmlStreamReader::TokenType Parser::Private::blockingReadNext()
QIODevice *dev = reader.device();
QAbstractSocket *sock = qobject_cast<QAbstractSocket *>(dev);
- if (!sock || sock->state() != QAbstractSocket::ConnectedState) {
+ if (!sock || sock->state() != QAbstractSocket::ConnectedState)
throw ParserException(dev->errorString());
- }
}
} else if (reader.hasError()) {
throw ParserException(reader.errorString()); //TODO add line, column?
diff --git a/src/plugins/valgrind/xmlprotocol/stackmodel.cpp b/src/plugins/valgrind/xmlprotocol/stackmodel.cpp
index 099aa99b4f..cdabdc1665 100644
--- a/src/plugins/valgrind/xmlprotocol/stackmodel.cpp
+++ b/src/plugins/valgrind/xmlprotocol/stackmodel.cpp
@@ -219,8 +219,9 @@ void StackModel::setError(const Error &error)
{
if (d->error == error)
return;
+ beginResetModel();
d->error = error;
- reset();
+ endResetModel();
}
void StackModel::clear()
diff --git a/src/plugins/valgrind/xmlprotocol/suppression.cpp b/src/plugins/valgrind/xmlprotocol/suppression.cpp
index 135174b101..e55b9e0ff7 100644
--- a/src/plugins/valgrind/xmlprotocol/suppression.cpp
+++ b/src/plugins/valgrind/xmlprotocol/suppression.cpp
@@ -105,11 +105,10 @@ void SuppressionFrame::setObject(const QString &obj)
QString SuppressionFrame::toString() const
{
- if (!d->fun.isEmpty()) {
+ if (!d->fun.isEmpty())
return QLatin1String("fun:") + d->fun;
- } else {
+ else
return QLatin1String("obj:") + d->obj;
- }
}
class Suppression::Private : public QSharedData
diff --git a/src/plugins/valgrind/xmlprotocol/threadedparser.cpp b/src/plugins/valgrind/xmlprotocol/threadedparser.cpp
index f1340bb414..991a1564d9 100644
--- a/src/plugins/valgrind/xmlprotocol/threadedparser.cpp
+++ b/src/plugins/valgrind/xmlprotocol/threadedparser.cpp
@@ -39,7 +39,7 @@
#include <QIODevice>
#include <QMetaType>
#include <QThread>
-#include <QSharedPointer>
+#include <QPointer>
namespace {
@@ -74,7 +74,7 @@ public:
Private()
{}
- QWeakPointer<Thread> parserThread;
+ QPointer<Thread> parserThread;
QString errorString;
};
diff --git a/src/plugins/vcsbase/baseannotationhighlighter.cpp b/src/plugins/vcsbase/baseannotationhighlighter.cpp
index 2a47900411..093a38db56 100644
--- a/src/plugins/vcsbase/baseannotationhighlighter.cpp
+++ b/src/plugins/vcsbase/baseannotationhighlighter.cpp
@@ -29,7 +29,6 @@
#include "baseannotationhighlighter.h"
-#include <math.h>
#include <QSet>
#include <QDebug>
#include <QColor>
@@ -81,26 +80,12 @@ BaseAnnotationHighlighter::~BaseAnnotationHighlighter()
void BaseAnnotationHighlighter::setChangeNumbers(const ChangeNumbers &changeNumbers)
{
- QColor bg = d->m_background;
d->m_changeNumberMap.clear();
if (!changeNumbers.isEmpty()) {
// Assign a color gradient to annotation change numbers. Give
// each change number a unique color.
- const double oneThird = 1.0 / 3.0;
- const int step = qRound(ceil(pow(double(changeNumbers.count()), oneThird)));
- QList<QColor> colors;
- const int factor = 255 / step;
- int half = factor / 2;
- for (int i=0; i<=step; ++i)
- for (int j=0; j<=step; ++j)
- for (int k=0; k<=step; ++k) {
- QColor c(i*factor, j*factor, k*factor);
- if ((bg.red() - half > c.red() ||bg.red() + half <= c.red())
- && (bg.green() - half > c.green() || bg.green() + half <= c.green())
- && (bg.blue() - half > c.blue() || bg.blue() + half <= c.blue()))
- colors.prepend(c);
- }
-
+ const QList<QColor> colors =
+ TextEditor::SyntaxHighlighter::generateColors(changeNumbers.size(), d->m_background);
int m = 0;
const int cstep = colors.count() / changeNumbers.count();
const ChangeNumbers::const_iterator cend = changeNumbers.constEnd();
diff --git a/src/plugins/vcsbase/basevcseditorfactory.cpp b/src/plugins/vcsbase/basevcseditorfactory.cpp
index e52dcdeb9b..b46c321b48 100644
--- a/src/plugins/vcsbase/basevcseditorfactory.cpp
+++ b/src/plugins/vcsbase/basevcseditorfactory.cpp
@@ -62,7 +62,7 @@ public:
BaseVcsEditorFactoryPrivate::BaseVcsEditorFactoryPrivate(const VcsBaseEditorParameters *t) :
m_type(t),
- m_id(t->id),
+ m_id(QByteArray(t->id)),
m_mimeTypes(QStringList(QLatin1String(t->mimeType))),
m_editorHandler(new TextEditor::TextEditorActionHandler(t->context))
{
diff --git a/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp b/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp
index fe45e788da..146fe25c53 100644
--- a/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp
+++ b/src/plugins/vcsbase/basevcssubmiteditorfactory.cpp
@@ -49,7 +49,7 @@ public:
BaseVcsSubmitEditorFactoryPrivate::BaseVcsSubmitEditorFactoryPrivate(const VcsBaseSubmitEditorParameters *parameters) :
m_parameters(parameters),
- m_id(parameters->id),
+ m_id(QByteArray(parameters->id)),
m_displayName(QLatin1String(parameters->displayName)),
m_mimeTypes(QLatin1String(parameters->mimeType))
{
diff --git a/src/plugins/vcsbase/checkoutjobs.cpp b/src/plugins/vcsbase/checkoutjobs.cpp
index d8a83004df..d2509da6ed 100644
--- a/src/plugins/vcsbase/checkoutjobs.cpp
+++ b/src/plugins/vcsbase/checkoutjobs.cpp
@@ -29,8 +29,8 @@
#include "checkoutjobs.h"
-#include <vcsbaseplugin.h>
-#include <vcsbaseoutputwindow.h>
+#include "vcsbaseplugin.h"
+#include "vcsbaseoutputwindow.h"
#include <QDebug>
#include <QQueue>
@@ -162,11 +162,10 @@ void ProcessCheckoutJob::slotFinished (int exitCode, QProcess::ExitStatus exitSt
switch (exitStatus) {
case QProcess::NormalExit:
emit output(tr("The process terminated with exit code %1.").arg(exitCode));
- if (exitCode == 0) {
+ if (exitCode == 0)
slotNext();
- } else {
+ else
emit failed(tr("The process returned exit code %1.").arg(exitCode));
- }
break;
case QProcess::CrashExit:
emit failed(tr("The process terminated in an abnormal way."));
diff --git a/src/plugins/vcsbase/checkoutwizarddialog.cpp b/src/plugins/vcsbase/checkoutwizarddialog.cpp
index 6630faa32c..fecf506c31 100644
--- a/src/plugins/vcsbase/checkoutwizarddialog.cpp
+++ b/src/plugins/vcsbase/checkoutwizarddialog.cpp
@@ -53,7 +53,7 @@ CheckoutWizardDialog::CheckoutWizardDialog(const QList<QWizardPage *> &parameter
m_progressPageId(-1)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
- foreach(QWizardPage *wp, parameterPages)
+ foreach (QWizardPage *wp, parameterPages)
addPage(wp);
m_progressPageId = parameterPages.size();
setPage(m_progressPageId, m_progressPage);
diff --git a/src/plugins/vcsbase/cleandialog.cpp b/src/plugins/vcsbase/cleandialog.cpp
index 710f4a173f..bae7480cbb 100644
--- a/src/plugins/vcsbase/cleandialog.cpp
+++ b/src/plugins/vcsbase/cleandialog.cpp
@@ -64,7 +64,7 @@ static void removeFileRecursion(const QFileInfo &f, QString *errorMessage)
return;
if (f.isDir()) {
const QDir dir(f.absoluteFilePath());
- foreach(const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden))
+ foreach (const QFileInfo &fi, dir.entryInfoList(QDir::AllEntries|QDir::NoDotAndDotDot|QDir::Hidden))
removeFileRecursion(fi, errorMessage);
QDir parent = f.absoluteDir();
if (!parent.rmdir(f.fileName()))
@@ -108,7 +108,7 @@ CleanFilesTask::CleanFilesTask(const QString &repository, const QStringList &fil
void CleanFilesTask::run()
{
- foreach(const QString &name, m_files)
+ foreach (const QString &name, m_files)
removeFileRecursion(QFileInfo(name), &m_errorMessage);
if (!m_errorMessage.isEmpty()) {
// Format and emit error.
diff --git a/src/plugins/vcsbase/commonsettingspage.cpp b/src/plugins/vcsbase/commonsettingspage.cpp
index 52c0af4a94..7bcc354d4e 100644
--- a/src/plugins/vcsbase/commonsettingspage.cpp
+++ b/src/plugins/vcsbase/commonsettingspage.cpp
@@ -109,7 +109,7 @@ CommonOptionsPage::CommonOptionsPage(QObject *parent) :
{
m_settings.fromSettings(Core::ICore::settings());
- setId(QLatin1String(Constants::VCS_COMMON_SETTINGS_ID));
+ setId(Constants::VCS_COMMON_SETTINGS_ID);
setDisplayName(QCoreApplication::translate("VcsBase", Constants::VCS_COMMON_SETTINGS_NAME));
}
diff --git a/src/plugins/vcsbase/commonvcssettings.cpp b/src/plugins/vcsbase/commonvcssettings.cpp
index e8614ddc0b..4d06c661cc 100644
--- a/src/plugins/vcsbase/commonvcssettings.cpp
+++ b/src/plugins/vcsbase/commonvcssettings.cpp
@@ -29,6 +29,8 @@
#include "commonvcssettings.h"
+#include <utils/hostosinfo.h>
+
#include <QSettings>
#include <QDebug>
@@ -51,11 +53,9 @@ static inline QString sshPasswordPromptDefault()
const QByteArray envSetting = qgetenv("SSH_ASKPASS");
if (!envSetting.isEmpty())
return QString::fromLocal8Bit(envSetting);
-#ifdef Q_OS_WIN
- return QLatin1String("win-ssh-askpass");
-#else
+ if (Utils::HostOsInfo::isWindowsHost())
+ return QLatin1String("win-ssh-askpass");
return QLatin1String("ssh-askpass");
-#endif
}
namespace VcsBase {
@@ -79,11 +79,10 @@ void CommonVcsSettings::toSettings(QSettings *s) const
s->setValue(QLatin1String(lineWrapWidthKeyC), lineWrapWidth);
s->setValue(QLatin1String(patchCommandKeyC), patchCommand);
// Do not store the default setting to avoid clobbering the environment.
- if (sshPasswordPrompt != sshPasswordPromptDefault()) {
+ if (sshPasswordPrompt != sshPasswordPromptDefault())
s->setValue(QLatin1String(sshPasswordPromptKeyC), sshPasswordPrompt);
- } else {
+ else
s->remove(QLatin1String(sshPasswordPromptKeyC));
- }
s->endGroup();
}
diff --git a/src/plugins/vcsbase/diffhighlighter.cpp b/src/plugins/vcsbase/diffhighlighter.cpp
index 57a613b9c7..85052ddcbc 100644
--- a/src/plugins/vcsbase/diffhighlighter.cpp
+++ b/src/plugins/vcsbase/diffhighlighter.cpp
@@ -116,7 +116,7 @@ DiffFormats DiffHighlighterPrivate::analyzeLine(const QString &text) const
{
// Do not match on git "--- a/" as a deleted line, check
// file first
- if (m_filePattern.exactMatch(text))
+ if (m_filePattern.indexIn(text) == 0)
return DiffFileFormat;
if (text.startsWith(m_diffInIndicator))
return DiffInFormat;
@@ -130,9 +130,8 @@ DiffFormats DiffHighlighterPrivate::analyzeLine(const QString &text) const
} // namespace Internal
// --- DiffHighlighter
-DiffHighlighter::DiffHighlighter(const QRegExp &filePattern,
- QTextDocument *document) :
- TextEditor::SyntaxHighlighter(document),
+DiffHighlighter::DiffHighlighter(const QRegExp &filePattern) :
+ TextEditor::SyntaxHighlighter(static_cast<QTextDocument *>(0)),
d(new Internal::DiffHighlighterPrivate(filePattern))
{
}
@@ -256,9 +255,4 @@ void DiffHighlighter::setFormats(const QVector<QTextCharFormat> &s)
}
}
-QRegExp DiffHighlighter::filePattern() const
-{
- return d->m_filePattern;
-}
-
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/diffhighlighter.h b/src/plugins/vcsbase/diffhighlighter.h
index cf2d1b8a22..be55af5fc2 100644
--- a/src/plugins/vcsbase/diffhighlighter.h
+++ b/src/plugins/vcsbase/diffhighlighter.h
@@ -51,8 +51,7 @@ class VCSBASE_EXPORT DiffHighlighter : public TextEditor::SyntaxHighlighter
Q_OBJECT
public:
- explicit DiffHighlighter(const QRegExp &filePattern,
- QTextDocument *document = 0);
+ explicit DiffHighlighter(const QRegExp &filePattern);
~DiffHighlighter();
void highlightBlock(const QString &text);
@@ -60,8 +59,6 @@ public:
// Set formats from a sequence of type QTextCharFormat
void setFormats(const QVector<QTextCharFormat> &s);
- QRegExp filePattern() const;
-
private:
Internal::DiffHighlighterPrivate *const d;
};
diff --git a/src/libs/utils/images/removesubmitfield.png b/src/plugins/vcsbase/images/removesubmitfield.png
index e4139afc55..e4139afc55 100644
--- a/src/libs/utils/images/removesubmitfield.png
+++ b/src/plugins/vcsbase/images/removesubmitfield.png
Binary files differ
diff --git a/src/libs/utils/submiteditorwidget.cpp b/src/plugins/vcsbase/submiteditorwidget.cpp
index 184a1bcd25..3fe2a078ba 100644
--- a/src/libs/utils/submiteditorwidget.cpp
+++ b/src/plugins/vcsbase/submiteditorwidget.cpp
@@ -29,6 +29,7 @@
#include "submiteditorwidget.h"
#include "submitfieldwidget.h"
+#include "submitfilemodel.h"
#include "ui_submiteditorwidget.h"
#include <QDebug>
@@ -46,17 +47,15 @@
enum { debug = 0 };
enum { defaultLineWidth = 72 };
-enum { checkableColumn = 0 };
-
/*!
- \class Utils::SubmitEditorWidget
+ \class VcsBase::SubmitEditorWidget
\brief Presents a VCS commit message in a text editor and a
checkable list of modified files in a list window.
The user can delete files from the list by unchecking them or diff the selection
- by doubleclicking. A list model which contains the file in a column
- specified by fileNameColumn should be set using setFileModel().
+ by doubleclicking. A list model which contains state and file columns should be
+ set using setFileModel().
Additionally, standard creator actions can be registered:
Undo/redo will be set up to work with the description editor.
@@ -71,7 +70,7 @@ enum { checkableColumn = 0 };
editor closes.
*/
-namespace Utils {
+namespace VcsBase {
// QActionPushButton: A push button tied to an action
// (similar to a QToolButton)
@@ -117,28 +116,6 @@ public slots:
};
// Helpers to retrieve model data
-static inline bool listModelChecked(const QAbstractItemModel *model, int row, int column = 0)
-{
- const QModelIndex checkableIndex = model->index(row, column, QModelIndex());
- return model->data(checkableIndex, Qt::CheckStateRole).toInt() == Qt::Checked;
-}
-
-static void setListModelChecked(QAbstractItemModel *model, bool checked, int column = 0)
-{
- const QVariant data = QVariant(int(checked ? Qt::Checked : Qt::Unchecked));
- const int count = model->rowCount();
- for (int i = 0; i < count; i++) {
- const QModelIndex checkableIndex = model->index(i, column, QModelIndex());
- model->setData(checkableIndex, data, Qt::CheckStateRole);
- }
-}
-
-static inline QString listModelText(const QAbstractItemModel *model, int row, int column)
-{
- const QModelIndex index = model->index(row, column, QModelIndex());
- return model->data(index, Qt::DisplayRole).toString();
-}
-
// Convenience to extract a list of selected indexes
QList<int> selectedRows(const QAbstractItemView *view)
{
@@ -163,7 +140,6 @@ struct SubmitEditorWidgetPrivate
Ui::SubmitEditorWidget m_ui;
bool m_filesSelected;
- int m_fileNameColumn;
int m_activatedRow;
bool m_emptyFileListEnabled;
@@ -180,7 +156,6 @@ struct SubmitEditorWidgetPrivate
SubmitEditorWidgetPrivate::SubmitEditorWidgetPrivate() :
m_filesSelected(false),
- m_fileNameColumn(1),
m_activatedRow(-1),
m_emptyFileListEnabled(false),
m_fieldLayout(0),
@@ -242,9 +217,8 @@ void SubmitEditorWidget::registerActions(QAction *editorUndoAction, QAction *edi
if (submitAction) {
if (debug) {
- int count = 0;
- if (const QAbstractItemModel *model = d->m_ui.fileView->model())
- count = model->rowCount();
+ const SubmitFileModel *model = fileModel();
+ int count = model ? model->rowCount() : 0;
qDebug() << Q_FUNC_INFO << submitAction << count << "items";
}
d->m_commitEnabled = !canSubmit();
@@ -332,7 +306,7 @@ QString SubmitEditorWidget::descriptionText() const
QString rc = trimMessageText(lineWrap() ? wrappedText(d->m_ui.description) :
d->m_ui.description->toPlainText());
// append field entries
- foreach(const SubmitFieldWidget *fw, d->m_fieldWidgets)
+ foreach (const SubmitFieldWidget *fw, d->m_fieldWidgets)
rc += fw->fieldValues();
return cleanupDescription(rc);
}
@@ -385,16 +359,6 @@ void SubmitEditorWidget::setDescriptionMandatory(bool v)
d->m_descriptionMandatory = v;
}
-int SubmitEditorWidget::fileNameColumn() const
-{
- return d->m_fileNameColumn;
-}
-
-void SubmitEditorWidget::setFileNameColumn(int c)
-{
- d->m_fileNameColumn = c;
-}
-
QAbstractItemView::SelectionMode SubmitEditorWidget::fileListSelectionMode() const
{
return d->m_ui.fileView->selectionMode();
@@ -405,7 +369,7 @@ void SubmitEditorWidget::setFileListSelectionMode(QAbstractItemView::SelectionMo
d->m_ui.fileView->setSelectionMode(sm);
}
-void SubmitEditorWidget::setFileModel(QAbstractItemModel *model)
+void SubmitEditorWidget::setFileModel(SubmitFileModel *model)
{
d->m_ui.fileView->clearSelection(); // trigger the change signals
@@ -434,54 +398,39 @@ void SubmitEditorWidget::setFileModel(QAbstractItemModel *model)
updateActions();
}
-QAbstractItemModel *SubmitEditorWidget::fileModel() const
+SubmitFileModel *SubmitEditorWidget::fileModel() const
{
- return d->m_ui.fileView->model();
-}
-
-QStringList SubmitEditorWidget::selectedFiles() const
-{
- const QList<int> selection = selectedRows(d->m_ui.fileView);
- if (selection.empty())
- return QStringList();
-
- QStringList rc;
- const QAbstractItemModel *model = d->m_ui.fileView->model();
- const int count = selection.size();
- for (int i = 0; i < count; i++)
- rc.push_back(listModelText(model, selection.at(i), fileNameColumn()));
- return rc;
+ return static_cast<SubmitFileModel *>(d->m_ui.fileView->model());
}
QStringList SubmitEditorWidget::checkedFiles() const
{
QStringList rc;
- const QAbstractItemModel *model = d->m_ui.fileView->model();
+ const SubmitFileModel *model = fileModel();
if (!model)
return rc;
const int count = model->rowCount();
for (int i = 0; i < count; i++)
- if (listModelChecked(model, i, checkableColumn))
- rc.push_back(listModelText(model, i, fileNameColumn()));
+ if (model->checked(i))
+ rc.push_back(model->file(i));
return rc;
}
-CompletingTextEdit *SubmitEditorWidget::descriptionEdit() const
+Utils::CompletingTextEdit *SubmitEditorWidget::descriptionEdit() const
{
return d->m_ui.description;
}
void SubmitEditorWidget::triggerDiffSelected()
{
- const QStringList sel = selectedFiles();
+ const QList<int> sel = selectedRows(d->m_ui.fileView);
if (!sel.empty())
emit diffSelected(sel);
}
void SubmitEditorWidget::diffActivatedDelayed()
{
- const QStringList files = QStringList(listModelText(d->m_ui.fileView->model(), d->m_activatedRow, fileNameColumn()));
- emit diffSelected(files);
+ emit diffSelected(QList<int>() << d->m_activatedRow);
}
void SubmitEditorWidget::diffActivated(const QModelIndex &index)
@@ -554,10 +503,10 @@ bool SubmitEditorWidget::hasSelection() const
int SubmitEditorWidget::checkedFilesCount() const
{
int checkedCount = 0;
- if (const QAbstractItemModel *model = d->m_ui.fileView->model()) {
+ if (const SubmitFileModel *model = fileModel()) {
const int count = model->rowCount();
for (int i = 0; i < count; ++i)
- if (listModelChecked(model, i, checkableColumn))
+ if (model->checked(i))
++checkedCount;
}
return checkedCount;
@@ -648,11 +597,10 @@ void SubmitEditorWidget::editorCustomContextMenuRequested(const QPoint &pos)
// Extend
foreach (const SubmitEditorWidgetPrivate::AdditionalContextMenuAction &a, d->descriptionEditContextMenuActions) {
if (a.second) {
- if (a.first >= 0) {
+ if (a.first >= 0)
menu->insertAction(menu->actions().at(a.first), a.second);
- } else {
+ else
menu->addAction(a.second);
- }
}
}
menu->exec(d->m_ui.description->mapToGlobal(pos));
@@ -662,24 +610,20 @@ void SubmitEditorWidget::checkAllToggled()
{
if (d->m_ignoreChange)
return;
- if (d->m_ui.checkAllCheckBox->checkState() == Qt::Checked
- || d->m_ui.checkAllCheckBox->checkState() == Qt::PartiallyChecked) {
- setListModelChecked(d->m_ui.fileView->model(), true, checkableColumn);
- } else {
- setListModelChecked(d->m_ui.fileView->model(), false, checkableColumn);
- }
+ Qt::CheckState checkState = d->m_ui.checkAllCheckBox->checkState();
+ fileModel()->setAllChecked(checkState == Qt::Checked || checkState == Qt::PartiallyChecked);
// Reset that again, so that the user can't do it
d->m_ui.checkAllCheckBox->setTristate(false);
}
void SubmitEditorWidget::checkAll()
{
- setListModelChecked(d->m_ui.fileView->model(), true, checkableColumn);
+ fileModel()->setAllChecked(true);
}
void SubmitEditorWidget::uncheckAll()
{
- setListModelChecked(d->m_ui.fileView->model(), false, checkableColumn);
+ fileModel()->setAllChecked(false);
}
void SubmitEditorWidget::fileListCustomContextMenuRequested(const QPoint & pos)
@@ -714,6 +658,6 @@ void SubmitEditorWidget::setEmptyFileListEnabled(bool e)
}
}
-} // namespace Utils
+} // namespace VcsBase
#include "submiteditorwidget.moc"
diff --git a/src/libs/utils/submiteditorwidget.h b/src/plugins/vcsbase/submiteditorwidget.h
index 9c236087e7..27cddad96e 100644
--- a/src/libs/utils/submiteditorwidget.h
+++ b/src/plugins/vcsbase/submiteditorwidget.h
@@ -30,30 +30,28 @@
#ifndef SUBMITEDITORWIDGET_H
#define SUBMITEDITORWIDGET_H
-#include "utils_global.h"
-#include "completingtextedit.h"
+#include "vcsbase_global.h"
+
+#include <utils/completingtextedit.h>
#include <QWidget>
#include <QAbstractItemView>
QT_BEGIN_NAMESPACE
-class QListWidgetItem;
class QAction;
-class QAbstractItemModel;
class QModelIndex;
-class QLineEdit;
QT_END_NAMESPACE
-namespace Utils {
+namespace VcsBase {
class SubmitFieldWidget;
struct SubmitEditorWidgetPrivate;
+class SubmitFileModel;
-class QTCREATOR_UTILS_EXPORT SubmitEditorWidget : public QWidget
+class VCSBASE_EXPORT SubmitEditorWidget : public QWidget
{
Q_OBJECT
Q_PROPERTY(QString descriptionText READ descriptionText WRITE setDescriptionText DESIGNABLE true)
- Q_PROPERTY(int fileNameColumn READ fileNameColumn WRITE setFileNameColumn DESIGNABLE false)
Q_PROPERTY(QAbstractItemView::SelectionMode fileListSelectionMode READ fileListSelectionMode WRITE setFileListSelectionMode DESIGNABLE true)
Q_PROPERTY(bool lineWrap READ lineWrap WRITE setLineWrap DESIGNABLE true)
Q_PROPERTY(int lineWrapWidth READ lineWrapWidth WRITE setLineWrapWidth DESIGNABLE true)
@@ -79,9 +77,6 @@ public:
bool isEmptyFileListEnabled() const;
void setEmptyFileListEnabled(bool e);
- int fileNameColumn() const;
- void setFileNameColumn(int c);
-
bool lineWrap() const;
void setLineWrap(bool);
@@ -94,16 +89,13 @@ public:
QAbstractItemView::SelectionMode fileListSelectionMode() const;
void setFileListSelectionMode(QAbstractItemView::SelectionMode sm);
- void setFileModel(QAbstractItemModel *model);
- QAbstractItemModel *fileModel() const;
+ void setFileModel(SubmitFileModel *model);
+ SubmitFileModel *fileModel() const;
// Files to be included in submit
QStringList checkedFiles() const;
- // Selected files for diff
- QStringList selectedFiles() const;
-
- CompletingTextEdit *descriptionEdit() const;
+ Utils::CompletingTextEdit *descriptionEdit() const;
void addDescriptionEditContextMenuAction(QAction *a);
void insertDescriptionEditContextMenuAction(int pos, QAction *a);
@@ -114,7 +106,7 @@ public:
virtual bool canSubmit() const;
signals:
- void diffSelected(const QStringList &);
+ void diffSelected(const QList<int> &);
void fileSelectionChanged(bool someFileSelected);
void submitActionTextChanged(const QString &);
void submitActionEnabledChanged(bool);
@@ -151,6 +143,6 @@ private:
SubmitEditorWidgetPrivate *d;
};
-} // namespace Utils
+} // namespace VcsBase
#endif // SUBMITEDITORWIDGET_H
diff --git a/src/libs/utils/submiteditorwidget.ui b/src/plugins/vcsbase/submiteditorwidget.ui
index 526408e11f..ab37981bb2 100644
--- a/src/libs/utils/submiteditorwidget.ui
+++ b/src/plugins/vcsbase/submiteditorwidget.ui
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
- <class>Utils::SubmitEditorWidget</class>
- <widget class="QWidget" name="Utils::SubmitEditorWidget">
+ <class>VcsBase::SubmitEditorWidget</class>
+ <widget class="QWidget" name="VcsBase::SubmitEditorWidget">
<property name="geometry">
<rect>
<x>0</x>
@@ -99,7 +99,7 @@
<customwidget>
<class>Utils::CompletingTextEdit</class>
<extends>QTextEdit</extends>
- <header>utils/completingtextedit.h</header>
+ <header location="global">utils/completingtextedit.h</header>
</customwidget>
</customwidgets>
<resources/>
diff --git a/src/libs/utils/submitfieldwidget.cpp b/src/plugins/vcsbase/submitfieldwidget.cpp
index 2063a3b2c1..61d629e701 100644
--- a/src/libs/utils/submitfieldwidget.cpp
+++ b/src/plugins/vcsbase/submitfieldwidget.cpp
@@ -52,7 +52,7 @@ static void inline setComboBlocked(QComboBox *cb, int index)
}
/*!
- \class Utils::SubmitFieldWidget
+ \class VcsBase::SubmitFieldWidget
\brief A widget for editing submit message fields like "reviewed-by:",
"signed-off-by:".
@@ -63,7 +63,7 @@ static void inline setComboBlocked(QComboBox *cb, int index)
completer can be added.
*/
-namespace Utils {
+namespace VcsBase {
// Field/Row entry
struct FieldEntry {
@@ -142,7 +142,7 @@ struct SubmitFieldWidgetPrivate {
};
SubmitFieldWidgetPrivate::SubmitFieldWidgetPrivate() :
- removeFieldIcon(QLatin1String(":/utils/images/removesubmitfield.png")),
+ removeFieldIcon(QLatin1String(":/vcsbase/images/removesubmitfield.png")),
completer(0),
hasBrowseButton(false),
allowDuplicateFields(false),
@@ -227,7 +227,7 @@ void SubmitFieldWidget::setHasBrowseButton(bool on)
if (d->hasBrowseButton == on)
return;
d->hasBrowseButton = on;
- foreach(const FieldEntry &fe, d->fieldEntries)
+ foreach (const FieldEntry &fe, d->fieldEntries)
fe.browseButton->setVisible(on);
}
@@ -251,7 +251,7 @@ void SubmitFieldWidget::setCompleter(QCompleter *c)
if (c == d->completer)
return;
d->completer = c;
- foreach(const FieldEntry &fe, d->fieldEntries)
+ foreach (const FieldEntry &fe, d->fieldEntries)
fe.lineEdit->setCompleter(c);
}
@@ -271,7 +271,7 @@ QString SubmitFieldWidget::fieldValues() const
const QChar newLine = QLatin1Char('\n');
// Format as "RevBy: value\nSigned-Off: value\n"
QString rc;
- foreach(const FieldEntry &fe, d->fieldEntries) {
+ foreach (const FieldEntry &fe, d->fieldEntries) {
const QString value = fe.lineEdit->text().trimmed();
if (!value.isEmpty()) {
rc += fe.combo->currentText();
@@ -344,11 +344,10 @@ void SubmitFieldWidget::slotComboIndexChanged(int comboIndex)
return;
// Accept new index or reset combo to previous value?
int &previousIndex = d->fieldEntries[pos].comboIndex;
- if (comboIndexChange(pos, comboIndex)) {
+ if (comboIndexChange(pos, comboIndex))
previousIndex = comboIndex;
- } else {
+ else
setComboBlocked(d->fieldEntries.at(pos).combo, previousIndex);
- }
if (debug)
qDebug() << '<' << Q_FUNC_INFO << pos;
}
diff --git a/src/libs/utils/submitfieldwidget.h b/src/plugins/vcsbase/submitfieldwidget.h
index 5d38c33c73..1c194e3d3f 100644
--- a/src/libs/utils/submitfieldwidget.h
+++ b/src/plugins/vcsbase/submitfieldwidget.h
@@ -30,7 +30,7 @@
#ifndef SUBMITFIELDWIDGET_H
#define SUBMITFIELDWIDGET_H
-#include "utils_global.h"
+#include "vcsbase_global.h"
#include <QWidget>
@@ -38,11 +38,11 @@ QT_BEGIN_NAMESPACE
class QCompleter;
QT_END_NAMESPACE
-namespace Utils {
+namespace VcsBase {
struct SubmitFieldWidgetPrivate;
-class QTCREATOR_UTILS_EXPORT SubmitFieldWidget : public QWidget
+class VCSBASE_EXPORT SubmitFieldWidget : public QWidget
{
Q_OBJECT
Q_PROPERTY(QStringList fields READ fields WRITE setFields DESIGNABLE true)
@@ -87,6 +87,6 @@ private:
SubmitFieldWidgetPrivate *d;
};
-} // namespace Utils
+} // namespace VcsBase
#endif // SUBMITFIELDWIDGET_H
diff --git a/src/plugins/vcsbase/submitfilemodel.cpp b/src/plugins/vcsbase/submitfilemodel.cpp
index ea4c72e1d6..f5d4a4212a 100644
--- a/src/plugins/vcsbase/submitfilemodel.cpp
+++ b/src/plugins/vcsbase/submitfilemodel.cpp
@@ -31,6 +31,7 @@
#include "vcsbaseconstants.h"
#include <coreplugin/fileiconprovider.h>
+#include <utils/qtcassert.h>
#include <QStandardItem>
#include <QFileInfo>
@@ -42,12 +43,15 @@ namespace VcsBase {
// Helpers:
// --------------------------------------------------------------------------
+enum { fileColumn = 1 };
+
static QList<QStandardItem *> createFileRow(const QString &fileName, const QString &status,
- bool checked, const QVariant &v)
+ CheckMode checked, const QVariant &v)
{
QStandardItem *statusItem = new QStandardItem(status);
- statusItem->setCheckable(true);
- statusItem->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
+ statusItem->setCheckable(checked != Uncheckable);
+ if (checked != Uncheckable)
+ statusItem->setCheckState(checked == Checked ? Qt::Checked : Qt::Unchecked);
statusItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsUserCheckable|Qt::ItemIsEnabled);
statusItem->setData(v);
QStandardItem *fileItem = new QStandardItem(fileName);
@@ -78,23 +82,14 @@ SubmitFileModel::SubmitFileModel(QObject *parent) :
setHorizontalHeaderLabels(headerLabels);
}
-QList<QStandardItem *> SubmitFileModel::addFile(const QString &fileName, const QString &status, bool checked,
+QList<QStandardItem *> SubmitFileModel::addFile(const QString &fileName, const QString &status, CheckMode checkMode,
const QVariant &v)
{
- const QList<QStandardItem *> row = createFileRow(fileName, status, checked, v);
+ const QList<QStandardItem *> row = createFileRow(fileName, status, checkMode, v);
appendRow(row);
return row;
}
-QList<QStandardItem *> SubmitFileModel::rowAt(int row) const
-{
- const int colCount = columnCount();
- QList<QStandardItem *> rc;
- for (int c = 0; c < colCount; c++)
- rc.push_back(item(row, c));
- return rc;
-}
-
QString SubmitFileModel::state(int row) const
{
if (row < 0 || row >= rowCount())
@@ -106,7 +101,7 @@ QString SubmitFileModel::file(int row) const
{
if (row < 0 || row >= rowCount())
return QString();
- return item(row, 1)->text();
+ return item(row, fileColumn)->text();
}
bool SubmitFileModel::checked(int row) const
@@ -116,6 +111,19 @@ bool SubmitFileModel::checked(int row) const
return (item(row)->checkState() == Qt::Checked);
}
+void SubmitFileModel::setChecked(int row, bool check)
+{
+ if (row >= 0 || row < rowCount())
+ item(row)->setCheckState(check ? Qt::Checked : Qt::Unchecked);
+}
+
+void SubmitFileModel::setAllChecked(bool check)
+{
+ int rows = rowCount();
+ for (int row = 0; row < rows; ++row)
+ item(row)->setCheckState(check ? Qt::Checked : Qt::Unchecked);
+}
+
QVariant SubmitFileModel::extraData(int row) const
{
if (row < 0 || row >= rowCount())
@@ -132,26 +140,39 @@ bool SubmitFileModel::hasCheckedFiles() const
return false;
}
-QList<QStandardItem *> SubmitFileModel::findRow(const QString &text, int column) const
-{
- // Single item
- const QList<QStandardItem *> items = findItems(text, Qt::MatchExactly, column);
- if (items.empty())
- return items;
- // Compile row
- return rowAt(items.front()->row());
- }
-
-unsigned SubmitFileModel::filter(const QStringList &filter, int column)
+unsigned int SubmitFileModel::filterFiles(const QStringList &filter)
{
- unsigned rc = 0;
+ unsigned int rc = 0;
for (int r = rowCount() - 1; r >= 0; r--)
- if (const QStandardItem *i = item(r, column))
- if (!filter.contains(i->text())) {
- qDeleteAll(takeRow(r));
- rc++;
- }
+ if (!filter.contains(file(r))) {
+ removeRow(r);
+ rc++;
+ }
return rc;
}
+/*! Updates user selections from \a source model.
+ *
+ * Assumption: Both model are sorted with the same order, and there
+ * are no duplicate entries.
+ */
+void SubmitFileModel::updateSelections(SubmitFileModel *source)
+{
+ QTC_ASSERT(source, return);
+ int rows = rowCount();
+ int sourceRows = source->rowCount();
+ int lastMatched = 0;
+ for (int i = 0; i < rows; ++i) {
+ // Since both models are sorted with the same order, there is no need
+ // to test rows earlier than latest match found
+ for (int j = lastMatched; j < sourceRows; ++j) {
+ if (file(i) == source->file(j) && state(i) == source->state(j)) {
+ setChecked(i, source->checked(j));
+ lastMatched = j + 1; // No duplicates, start on next entry
+ break;
+ }
+ }
+ }
+}
+
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/submitfilemodel.h b/src/plugins/vcsbase/submitfilemodel.h
index bd8b4ab5fc..f7d7132766 100644
--- a/src/plugins/vcsbase/submitfilemodel.h
+++ b/src/plugins/vcsbase/submitfilemodel.h
@@ -36,6 +36,13 @@
namespace VcsBase {
+enum CheckMode
+{
+ Unchecked,
+ Checked,
+ Uncheckable
+};
+
class VCSBASE_EXPORT SubmitFileModel : public QStandardItemModel
{
Q_OBJECT
@@ -44,24 +51,22 @@ public:
// Convenience to create and add rows containing a file plus status text.
QList<QStandardItem *> addFile(const QString &fileName, const QString &status = QString(),
- bool checked = true, const QVariant &data = QVariant());
-
- // Find convenience that returns the whole row (as opposed to QStandardItemModel::find).
- QList<QStandardItem *> findRow(const QString &text, int column = 0) const;
-
- // Convenience to obtain a row
- QList<QStandardItem *> rowAt(int row) const;
+ CheckMode checkMode = Checked, const QVariant &data = QVariant());
QString state(int row) const;
QString file(int row) const;
bool checked(int row) const;
+ void setChecked(int row, bool check);
+ void setAllChecked(bool check);
QVariant extraData(int row) const;
bool hasCheckedFiles() const;
// Filter for entries contained in the filter list. Returns the
// number of deleted entries.
- unsigned filter(const QStringList &filter, int column);
+ unsigned int filterFiles(const QStringList &filter);
+
+ virtual void updateSelections(SubmitFileModel *source);
};
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsbase.pro b/src/plugins/vcsbase/vcsbase.pro
index 89a932f02c..2b2d68a33b 100644
--- a/src/plugins/vcsbase/vcsbase.pro
+++ b/src/plugins/vcsbase/vcsbase.pro
@@ -1,6 +1,6 @@
TEMPLATE = lib
TARGET = VcsBase
-DEFINES += VCSBASE_LIBRARY QT_NO_CAST_FROM_ASCII
+DEFINES += VCSBASE_LIBRARY
include(../../qtcreatorplugin.pri)
include(vcsbase_dependencies.pri)
HEADERS += vcsbase_global.h \
@@ -31,7 +31,9 @@ HEADERS += vcsbase_global.h \
command.h \
vcsbaseclient.h \
vcsbaseclientsettings.h \
- vcsbaseeditorparameterwidget.h
+ vcsbaseeditorparameterwidget.h \
+ submitfieldwidget.h \
+ submiteditorwidget.h
SOURCES += vcsplugin.cpp \
vcsbaseplugin.cpp \
@@ -59,7 +61,9 @@ SOURCES += vcsplugin.cpp \
command.cpp \
vcsbaseclient.cpp \
vcsbaseclientsettings.cpp \
- vcsbaseeditorparameterwidget.cpp
+ vcsbaseeditorparameterwidget.cpp \
+ submitfieldwidget.cpp \
+ submiteditorwidget.cpp
RESOURCES += vcsbase.qrc
@@ -67,5 +71,6 @@ FORMS += commonsettingspage.ui \
nicknamedialog.ui \
checkoutprogresswizardpage.ui \
basecheckoutwizardpage.ui \
- cleandialog.ui
+ cleandialog.ui \
+ submiteditorwidget.ui
diff --git a/src/plugins/vcsbase/vcsbase.qbs b/src/plugins/vcsbase/vcsbase.qbs
index 91245e75d8..b5265d7b8c 100644
--- a/src/plugins/vcsbase/vcsbase.qbs
+++ b/src/plugins/vcsbase/vcsbase.qbs
@@ -14,18 +14,8 @@ QtcPlugin {
Depends { name: "CppTools" }
Depends { name: "CPlusPlus" }
- cpp.includePaths: [
- ".",
- "..",
- "../../libs",
- "../../libs/3rdparty",
- buildDirectory
- ]
-
files: [
"VcsBase.mimetypes.xml",
- "vcsbase.qrc",
- "vcsbase_global.h",
"baseannotationhighlighter.cpp",
"baseannotationhighlighter.h",
"basecheckoutwizard.cpp",
@@ -63,8 +53,15 @@ QtcPlugin {
"nicknamedialog.ui",
"submiteditorfile.cpp",
"submiteditorfile.h",
+ "submiteditorwidget.cpp",
+ "submiteditorwidget.h",
+ "submiteditorwidget.ui",
+ "submitfieldwidget.cpp",
+ "submitfieldwidget.h",
"submitfilemodel.cpp",
"submitfilemodel.h",
+ "vcsbase.qrc",
+ "vcsbase_global.h",
"vcsbaseclient.cpp",
"vcsbaseclient.h",
"vcsbaseclientsettings.cpp",
@@ -87,7 +84,7 @@ QtcPlugin {
"vcsplugin.cpp",
"vcsplugin.h",
"images/diff.png",
- "images/submit.png"
+ "images/removesubmitfield.png",
+ "images/submit.png",
]
}
-
diff --git a/src/plugins/vcsbase/vcsbase.qrc b/src/plugins/vcsbase/vcsbase.qrc
index 4da5d9ca9f..2bd826fbae 100644
--- a/src/plugins/vcsbase/vcsbase.qrc
+++ b/src/plugins/vcsbase/vcsbase.qrc
@@ -2,6 +2,7 @@
<qresource prefix="/vcsbase" >
<file>VcsBase.mimetypes.xml</file>
<file>images/diff.png</file>
+ <file>images/removesubmitfield.png</file>
<file>images/submit.png</file>
</qresource>
</RCC>
diff --git a/src/plugins/vcsbase/vcsbaseclientsettings.cpp b/src/plugins/vcsbase/vcsbaseclientsettings.cpp
index b2e0d3facf..9a9b51fc1e 100644
--- a/src/plugins/vcsbase/vcsbaseclientsettings.cpp
+++ b/src/plugins/vcsbase/vcsbaseclientsettings.cpp
@@ -30,6 +30,7 @@
#include "vcsbaseclientsettings.h"
#include <utils/environment.h>
+#include <utils/hostosinfo.h>
#include <utils/synchronousprocess.h>
#include <QSettings>
@@ -350,7 +351,7 @@ QString VcsBaseClientSettings::binaryPath() const
if (d->m_binaryFullPath.isEmpty()) {
d->m_binaryFullPath = Utils::Environment::systemEnvironment().searchInPath(
stringValue(binaryPathKey), stringValue(pathKey).split(
- Utils::SynchronousProcess::pathSeparator()));
+ Utils::HostOsInfo::pathListSeparator()));
}
return d->m_binaryFullPath;
}
diff --git a/src/plugins/vcsbase/vcsbaseeditor.cpp b/src/plugins/vcsbase/vcsbaseeditor.cpp
index 07c5507453..45f60c410f 100644
--- a/src/plugins/vcsbase/vcsbaseeditor.cpp
+++ b/src/plugins/vcsbase/vcsbaseeditor.cpp
@@ -178,37 +178,12 @@ private:
VcsBaseEditor::VcsBaseEditor(VcsBaseEditorWidget *widget,
const VcsBaseEditorParameters *type) :
BaseTextEditor(widget),
- m_id(type->id),
+ m_id(QByteArray(type->id)),
m_temporary(false)
{
setContext(Core::Context(type->context, TextEditor::Constants::C_TEXTEDITOR));
}
-// Diff editor: creates a browse combo in the toolbar for diff output.
-class VcsBaseDiffEditor : public VcsBaseEditor
-{
-public:
- VcsBaseDiffEditor(VcsBaseEditorWidget *, const VcsBaseEditorParameters *type);
-
- QComboBox *diffFileBrowseComboBox() const { return m_diffFileBrowseComboBox; }
-
-private:
- QComboBox *m_diffFileBrowseComboBox;
-};
-
-VcsBaseDiffEditor::VcsBaseDiffEditor(VcsBaseEditorWidget *w, const VcsBaseEditorParameters *type) :
- VcsBaseEditor(w, type),
- m_diffFileBrowseComboBox(new QComboBox)
-{
- m_diffFileBrowseComboBox->setMinimumContentsLength(20);
- // Make the combo box prefer to expand
- QSizePolicy policy = m_diffFileBrowseComboBox->sizePolicy();
- policy.setHorizontalPolicy(QSizePolicy::Expanding);
- m_diffFileBrowseComboBox->setSizePolicy(policy);
-
- insertExtraToolBarWidget(Left, m_diffFileBrowseComboBox);
-}
-
// ----------- VcsBaseEditorPrivate
namespace Internal {
@@ -365,6 +340,7 @@ void ChangeTextCursorHandler::fillContextMenu(QMenu *menu, EditorContentType typ
default:
break;
}
+ widget->addChangeActions(menu, m_currentChange);
}
QString ChangeTextCursorHandler::currentContents() const
@@ -384,7 +360,7 @@ void ChangeTextCursorHandler::slotCopyRevision()
QAction *ChangeTextCursorHandler::createDescribeAction(const QString &change) const
{
- QAction *a = new QAction(VcsBaseEditorWidget::tr("Describe change %1").arg(change), 0);
+ QAction *a = new QAction(VcsBaseEditorWidget::tr("Describe Change %1").arg(change), 0);
connect(a, SIGNAL(triggered()), this, SLOT(slotDescribe()));
return a;
}
@@ -589,6 +565,9 @@ public:
VcsBaseEditorWidgetPrivate(VcsBaseEditorWidget* editorWidget, const VcsBaseEditorParameters *type);
AbstractTextCursorHandler *findTextCursorHandler(const QTextCursor &cursor);
+ // creates a browse combo in the toolbar for quick access to entries.
+ // Can be used for diff and log. Combo created on first call.
+ QComboBox *entriesComboBox();
const VcsBaseEditorParameters *m_parameters;
@@ -596,7 +575,8 @@ public:
QString m_diffBaseDirectory;
QRegExp m_diffFilePattern;
- QList<int> m_diffSections; // line number where this section starts
+ QRegExp m_logEntryPattern;
+ QList<int> m_entrySections; // line number where this section starts
int m_cursorLine;
QString m_annotateRevisionTextFormat;
QString m_annotatePreviousRevisionTextFormat;
@@ -608,6 +588,9 @@ public:
QList<AbstractTextCursorHandler *> m_textCursorHandlers;
QColor m_backgroundColor;
+
+private:
+ QComboBox *m_entriesComboBox;
};
VcsBaseEditorWidgetPrivate::VcsBaseEditorWidgetPrivate(VcsBaseEditorWidget *editorWidget,
@@ -619,7 +602,8 @@ VcsBaseEditorWidgetPrivate::VcsBaseEditorWidgetPrivate(VcsBaseEditorWidget *edit
m_fileLogAnnotateEnabled(false),
m_editor(0),
m_configurationWidget(0),
- m_mouseDragging(false)
+ m_mouseDragging(false),
+ m_entriesComboBox(0)
{
m_textCursorHandlers.append(new ChangeTextCursorHandler(editorWidget));
m_textCursorHandlers.append(new UrlTextCursorHandler(editorWidget));
@@ -635,6 +619,21 @@ AbstractTextCursorHandler *VcsBaseEditorWidgetPrivate::findTextCursorHandler(con
return 0;
}
+QComboBox *VcsBaseEditorWidgetPrivate::entriesComboBox()
+{
+ if (m_entriesComboBox)
+ return m_entriesComboBox;
+ m_entriesComboBox = new QComboBox;
+ m_entriesComboBox->setMinimumContentsLength(20);
+ // Make the combo box prefer to expand
+ QSizePolicy policy = m_entriesComboBox->sizePolicy();
+ policy.setHorizontalPolicy(QSizePolicy::Expanding);
+ m_entriesComboBox->setSizePolicy(policy);
+
+ m_editor->insertExtraToolBarWidget(TextEditor::BaseTextEditor::Left, m_entriesComboBox);
+ return m_entriesComboBox;
+}
+
} // namespace Internal
/*!
@@ -668,25 +667,44 @@ VcsBaseEditorWidget::VcsBaseEditorWidget(const VcsBaseEditorParameters *type, QW
setMimeType(QLatin1String(d->m_parameters->mimeType));
}
+void VcsBaseEditorWidget::setDiffFilePattern(const QRegExp &pattern)
+{
+ QTC_ASSERT(pattern.isValid() && pattern.captureCount() >= 1, return);
+ d->m_diffFilePattern = pattern;
+}
+
+void VcsBaseEditorWidget::setLogEntryPattern(const QRegExp &pattern)
+{
+ QTC_ASSERT(pattern.isValid() && pattern.captureCount() >= 1, return);
+ d->m_logEntryPattern = pattern;
+}
+
void VcsBaseEditorWidget::init()
{
+ d->m_editor = editor();
switch (d->m_parameters->type) {
case RegularCommandOutput:
case LogOutput:
+ connect(d->entriesComboBox(), SIGNAL(activated(int)), this, SLOT(slotJumpToEntry(int)));
+ connect(this, SIGNAL(textChanged()), this, SLOT(slotPopulateLogBrowser()));
+ connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged()));
+ break;
case AnnotateOutput:
// Annotation highlighting depends on contents, which is set later on
connect(this, SIGNAL(textChanged()), this, SLOT(slotActivateAnnotation()));
break;
- case DiffOutput: {
- DiffHighlighter *dh = createDiffHighlighter();
- setCodeFoldingSupported(true);
- baseTextDocument()->setSyntaxHighlighter(dh);
- d->m_diffFilePattern = dh->filePattern();
+ case DiffOutput:
+ // Diff: set up diff file browsing
+ connect(d->entriesComboBox(), SIGNAL(activated(int)), this, SLOT(slotJumpToEntry(int)));
connect(this, SIGNAL(textChanged()), this, SLOT(slotPopulateDiffBrowser()));
- connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotDiffCursorPositionChanged()));
- }
+ connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(slotCursorPositionChanged()));
break;
}
+ if (hasDiff()) {
+ DiffHighlighter *dh = new DiffHighlighter(d->m_diffFilePattern);
+ setCodeFoldingSupported(true);
+ baseTextDocument()->setSyntaxHighlighter(dh);
+ }
TextEditor::TextEditorSettings::instance()->initializeEditor(this);
// override revisions display (green or red bar on the left, marking changes):
setRevisionsVisible(false);
@@ -772,11 +790,10 @@ QTextCodec *VcsBaseEditorWidget::codec() const
void VcsBaseEditorWidget::setCodec(QTextCodec *c)
{
- if (c) {
+ if (c)
baseTextDocument()->setCodec(c);
- } else {
+ else
qWarning("%s: Attempt to set 0 codec.", Q_FUNC_INFO);
- }
}
EditorContentType VcsBaseEditorWidget::contentType() const
@@ -791,17 +808,7 @@ bool VcsBaseEditorWidget::isModified() const
TextEditor::BaseTextEditor *VcsBaseEditorWidget::createEditor()
{
- TextEditor::BaseTextEditor *editor = 0;
- if (d->m_parameters->type == DiffOutput) {
- // Diff: set up diff file browsing
- VcsBaseDiffEditor *de = new VcsBaseDiffEditor(this, d->m_parameters);
- QComboBox *diffBrowseComboBox = de->diffFileBrowseComboBox();
- connect(diffBrowseComboBox, SIGNAL(activated(int)), this, SLOT(slotDiffBrowse(int)));
- editor = de;
- } else {
- editor = new VcsBaseEditor(this, d->m_parameters);
- }
- d->m_editor = editor;
+ TextEditor::BaseTextEditor *editor = new VcsBaseEditor(this, d->m_parameters);
// Pass on signals.
connect(this, SIGNAL(describeRequested(QString,QString)),
@@ -813,10 +820,9 @@ TextEditor::BaseTextEditor *VcsBaseEditorWidget::createEditor()
void VcsBaseEditorWidget::slotPopulateDiffBrowser()
{
- VcsBaseDiffEditor *de = static_cast<VcsBaseDiffEditor*>(editor());
- QComboBox *diffBrowseComboBox = de->diffFileBrowseComboBox();
- diffBrowseComboBox->clear();
- d->m_diffSections.clear();
+ QComboBox *entriesComboBox = d->entriesComboBox();
+ entriesComboBox->clear();
+ d->m_entrySections.clear();
// Create a list of section line numbers (diffed files)
// and populate combo with filenames.
const QTextBlock cend = document()->end();
@@ -825,24 +831,52 @@ void VcsBaseEditorWidget::slotPopulateDiffBrowser()
for (QTextBlock it = document()->begin(); it != cend; it = it.next(), lineNumber++) {
const QString text = it.text();
// Check for a new diff section (not repeating the last filename)
- if (d->m_diffFilePattern.exactMatch(text)) {
+ if (d->m_diffFilePattern.indexIn(text) == 0) {
const QString file = fileNameFromDiffSpecification(it);
if (!file.isEmpty() && lastFileName != file) {
lastFileName = file;
// ignore any headers
- d->m_diffSections.push_back(d->m_diffSections.empty() ? 0 : lineNumber);
- diffBrowseComboBox->addItem(QFileInfo(file).fileName());
+ d->m_entrySections.push_back(d->m_entrySections.empty() ? 0 : lineNumber);
+ entriesComboBox->addItem(QFileInfo(file).fileName());
+ }
+ }
+ }
+}
+
+void VcsBaseEditorWidget::slotPopulateLogBrowser()
+{
+ QComboBox *entriesComboBox = d->entriesComboBox();
+ entriesComboBox->clear();
+ d->m_entrySections.clear();
+ // Create a list of section line numbers (log entries)
+ // and populate combo with subjects (if any).
+ const QTextBlock cend = document()->end();
+ int lineNumber = 0;
+ for (QTextBlock it = document()->begin(); it != cend; it = it.next(), lineNumber++) {
+ const QString text = it.text();
+ // Check for a new log section (not repeating the last filename)
+ if (d->m_logEntryPattern.indexIn(text) != -1) {
+ d->m_entrySections.push_back(d->m_entrySections.empty() ? 0 : lineNumber);
+ QString entry = d->m_logEntryPattern.cap(1);
+ QString subject = revisionSubject(it);
+ if (!subject.isEmpty()) {
+ if (subject.length() > 100) {
+ subject.truncate(97);
+ subject.append(QLatin1String("..."));
+ }
+ entry.append(QLatin1String(" - ")).append(subject);
}
+ entriesComboBox->addItem(entry);
}
}
}
-void VcsBaseEditorWidget::slotDiffBrowse(int index)
+void VcsBaseEditorWidget::slotJumpToEntry(int index)
{
- // goto diffed file as indicated by index/line number
- if (index < 0 || index >= d->m_diffSections.size())
+ // goto diff/log entry as indicated by index/line number
+ if (index < 0 || index >= d->m_entrySections.size())
return;
- const int lineNumber = d->m_diffSections.at(index) + 1; // TextEdit uses 1..n convention
+ const int lineNumber = d->m_entrySections.at(index) + 1; // TextEdit uses 1..n convention
// check if we need to do something, especially to avoid messing up navigation history
int currentLine, currentColumn;
convertPosition(position(), &currentLine, &currentColumn);
@@ -867,24 +901,22 @@ static int sectionOfLine(int line, const QList<int> &sections)
return sectionCount - 1;
}
-void VcsBaseEditorWidget::slotDiffCursorPositionChanged()
+void VcsBaseEditorWidget::slotCursorPositionChanged()
{
- // Adapt diff file browse combo to new position
+ // Adapt entries combo to new position
// if the cursor goes across a file line.
- QTC_ASSERT(d->m_parameters->type == DiffOutput, return);
const int newCursorLine = textCursor().blockNumber();
if (newCursorLine == d->m_cursorLine)
return;
// Which section does it belong to?
d->m_cursorLine = newCursorLine;
- const int section = sectionOfLine(d->m_cursorLine, d->m_diffSections);
+ const int section = sectionOfLine(d->m_cursorLine, d->m_entrySections);
if (section != -1) {
- VcsBaseDiffEditor *de = static_cast<VcsBaseDiffEditor*>(editor());
- QComboBox *diffBrowseComboBox = de->diffFileBrowseComboBox();
- if (diffBrowseComboBox->currentIndex() != section) {
- const bool blocked = diffBrowseComboBox->blockSignals(true);
- diffBrowseComboBox->setCurrentIndex(section);
- diffBrowseComboBox->blockSignals(blocked);
+ QComboBox *entriesComboBox = d->entriesComboBox();
+ if (entriesComboBox->currentIndex() != section) {
+ const bool blocked = entriesComboBox->blockSignals(true);
+ entriesComboBox->setCurrentIndex(section);
+ entriesComboBox->blockSignals(blocked);
}
}
}
@@ -900,7 +932,9 @@ void VcsBaseEditorWidget::contextMenuEvent(QContextMenuEvent *e)
Internal::AbstractTextCursorHandler *handler = d->findTextCursorHandler(cursor);
if (handler != 0)
handler->fillContextMenu(menu, d->m_parameters->type);
- break;
+ // Fall-through for log (might have diff)
+ if (d->m_parameters->type != LogOutput)
+ break;
}
case DiffOutput: {
menu->addSeparator();
@@ -909,23 +943,22 @@ void VcsBaseEditorWidget::contextMenuEvent(QContextMenuEvent *e)
menu->addSeparator();
// Apply/revert diff chunk.
const DiffChunk chunk = diffChunk(cursorForPosition(e->pos()));
- const bool canApply = canApplyDiffChunk(chunk);
+ if (!canApplyDiffChunk(chunk))
+ break;
// Apply a chunk from a diff loaded into the editor. This typically will
// not have the 'source' property set and thus will only work if the working
// directory matches that of the patch (see findDiffFile()). In addition,
// the user has "Open With" and choose the right diff editor so that
// fileNameFromDiffSpecification() works.
QAction *applyAction = menu->addAction(tr("Apply Chunk..."));
- applyAction->setEnabled(canApply);
applyAction->setData(qVariantFromValue(Internal::DiffChunkAction(chunk, false)));
connect(applyAction, SIGNAL(triggered()), this, SLOT(slotApplyDiffChunk()));
// Revert a chunk from a VCS diff, which might be linked to reloading the diff.
QAction *revertAction = menu->addAction(tr("Revert Chunk..."));
- revertAction->setEnabled(canApply);
revertAction->setData(qVariantFromValue(Internal::DiffChunkAction(chunk, true)));
connect(revertAction, SIGNAL(triggered()), this, SLOT(slotApplyDiffChunk()));
- }
break;
+ }
default:
break;
}
@@ -984,11 +1017,9 @@ void VcsBaseEditorWidget::mouseReleaseEvent(QMouseEvent *e)
void VcsBaseEditorWidget::mouseDoubleClickEvent(QMouseEvent *e)
{
- if (d->m_parameters->type == DiffOutput) {
- if (e->button() == Qt::LeftButton &&!(e->modifiers() & Qt::ShiftModifier)) {
- QTextCursor cursor = cursorForPosition(e->pos());
- jumpToChangeFromDiff(cursor);
- }
+ if (hasDiff() && e->button() == Qt::LeftButton && !(e->modifiers() & Qt::ShiftModifier)) {
+ QTextCursor cursor = cursorForPosition(e->pos());
+ jumpToChangeFromDiff(cursor);
}
TextEditor::BaseTextEditorWidget::mouseDoubleClickEvent(e);
}
@@ -996,8 +1027,7 @@ void VcsBaseEditorWidget::mouseDoubleClickEvent(QMouseEvent *e)
void VcsBaseEditorWidget::keyPressEvent(QKeyEvent *e)
{
// Do not intercept return in editable patches.
- if (d->m_parameters->type == DiffOutput && isReadOnly()
- && (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return)) {
+ if (hasDiff() && isReadOnly() && (e->key() == Qt::Key_Enter || e->key() == Qt::Key_Return)) {
jumpToChangeFromDiff(textCursor());
return;
}
@@ -1104,7 +1134,7 @@ void VcsBaseEditorWidget::jumpToChangeFromDiff(QTextCursor cursor)
DiffChunk VcsBaseEditorWidget::diffChunk(QTextCursor cursor) const
{
DiffChunk rc;
- QTC_ASSERT(d->m_parameters->type == DiffOutput, return rc);
+ QTC_ASSERT(hasDiff(), return rc);
// Search back for start of chunk.
QTextBlock block = cursor.block();
if (block.isValid() && TextEditor::BaseTextDocumentLayout::foldingIndent(block) <= 1)
@@ -1113,9 +1143,8 @@ DiffChunk VcsBaseEditorWidget::diffChunk(QTextCursor cursor) const
int chunkStart = 0;
for ( ; block.isValid() ; block = block.previous()) {
- if (checkChunkLine(block.text(), &chunkStart)) {
+ if (checkChunkLine(block.text(), &chunkStart))
break;
- }
}
if (!chunkStart || !block.isValid())
return rc;
@@ -1142,11 +1171,10 @@ DiffChunk VcsBaseEditorWidget::diffChunk(QTextCursor cursor) const
void VcsBaseEditorWidget::setPlainTextData(const QByteArray &data)
{
- if (data.size() > Core::EditorManager::maxTextFileSize()) {
+ if (data.size() > Core::EditorManager::maxTextFileSize())
setPlainText(msgTextTooLarge(data.size()));
- } else {
+ else
setPlainText(codec()->toUnicode(data));
- }
}
void VcsBaseEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
@@ -1155,7 +1183,12 @@ void VcsBaseEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
d->m_backgroundColor = fs.toTextCharFormat(TextEditor::C_TEXT)
.brushProperty(QTextFormat::BackgroundBrush).color();
- if (d->m_parameters->type == DiffOutput) {
+ if (d->m_parameters->type == AnnotateOutput) {
+ if (BaseAnnotationHighlighter *highlighter = qobject_cast<BaseAnnotationHighlighter *>(baseTextDocument()->syntaxHighlighter())) {
+ highlighter->setBackgroundColor(d->m_backgroundColor);
+ highlighter->rehighlight();
+ }
+ } else if (hasDiff()) {
if (DiffHighlighter *highlighter = qobject_cast<DiffHighlighter*>(baseTextDocument()->syntaxHighlighter())) {
static QVector<TextEditor::TextStyle> categories;
if (categories.isEmpty()) {
@@ -1168,11 +1201,6 @@ void VcsBaseEditorWidget::setFontSettings(const TextEditor::FontSettings &fs)
highlighter->setFormats(fs.toTextCharFormats(categories));
highlighter->rehighlight();
}
- } else if (d->m_parameters->type == AnnotateOutput) {
- if (BaseAnnotationHighlighter *highlighter = qobject_cast<BaseAnnotationHighlighter *>(baseTextDocument()->syntaxHighlighter())) {
- highlighter->setBackgroundColor(d->m_backgroundColor);
- highlighter->rehighlight();
- }
}
}
@@ -1382,6 +1410,12 @@ QString VcsBaseEditorWidget::findDiffFile(const QString &f) const
if (in.isFile())
return in.absoluteFilePath();
+ // 4) remove trailing tab char and try again: At least git appends \t when the
+ // filename contains spaces. Since the diff commend does use \t all of a sudden,
+ // too, when seeing spaces in a filename, I expect the same behavior in other VCS.
+ if (f.endsWith(QLatin1Char('\t')))
+ return findDiffFile(f.left(f.length() - 1));
+
return QString();
}
@@ -1426,6 +1460,24 @@ bool VcsBaseEditorWidget::applyDiffChunk(const DiffChunk &dc, bool revert) const
return VcsBasePlugin::runPatch(dc.asPatch(), QString(), 0, revert);
}
+QString VcsBaseEditorWidget::fileNameFromDiffSpecification(const QTextBlock &inBlock) const
+{
+ // Go back chunks
+ for (QTextBlock block = inBlock; block.isValid(); block = block.previous()) {
+ const QString line = block.text();
+ if (d->m_diffFilePattern.indexIn(line) != -1) {
+ QString cap = d->m_diffFilePattern.cap(1);
+ if (!cap.isEmpty())
+ return findDiffFile(cap);
+ }
+ }
+ return QString();
+}
+
+void VcsBaseEditorWidget::addChangeActions(QMenu *, const QString &)
+{
+}
+
QString VcsBaseEditorWidget::decorateVersion(const QString &revision) const
{
return revision;
@@ -1437,6 +1489,23 @@ bool VcsBaseEditorWidget::isValidRevision(const QString &revision) const
return true;
}
+QString VcsBaseEditorWidget::revisionSubject(const QTextBlock &inBlock) const
+{
+ Q_UNUSED(inBlock);
+ return QString();
+}
+
+bool VcsBaseEditorWidget::hasDiff() const
+{
+ switch (d->m_parameters->type) {
+ case DiffOutput:
+ case LogOutput:
+ return true;
+ default:
+ return false;
+ }
+}
+
void VcsBaseEditorWidget::slotApplyDiffChunk()
{
const QAction *a = qobject_cast<QAction *>(sender());
@@ -1449,11 +1518,10 @@ void VcsBaseEditorWidget::slotApplyDiffChunk()
return;
if (applyDiffChunk(chunkAction.chunk, chunkAction.revert)) {
- if (chunkAction.revert) {
+ if (chunkAction.revert)
emit diffChunkReverted(chunkAction.chunk);
- } else {
+ else
emit diffChunkApplied(chunkAction.chunk);
- }
}
}
@@ -1500,4 +1568,28 @@ Core::IEditor* VcsBaseEditorWidget::locateEditorByTag(const QString &tag)
} // namespace VcsBase
+#ifdef WITH_TESTS
+#include <QTest>
+
+void VcsBase::VcsBaseEditorWidget::testDiffFileResolving()
+{
+ QFETCH(QByteArray, header);
+ QFETCH(QByteArray, fileName);
+ QTextDocument doc(QString::fromLatin1(header));
+ init();
+ QTextBlock block = doc.lastBlock();
+ QVERIFY(fileNameFromDiffSpecification(block).endsWith(QString::fromLatin1(fileName)));
+}
+
+void VcsBase::VcsBaseEditorWidget::testLogResolving(QByteArray &data,
+ const QByteArray &entry1,
+ const QByteArray &entry2)
+{
+ init();
+ setPlainText(QLatin1String(data));
+ QCOMPARE(d->entriesComboBox()->itemText(0), QString::fromLatin1(entry1));
+ QCOMPARE(d->entriesComboBox()->itemText(1), QString::fromLatin1(entry2));
+}
+#endif
+
#include "vcsbaseeditor.moc"
diff --git a/src/plugins/vcsbase/vcsbaseeditor.h b/src/plugins/vcsbase/vcsbaseeditor.h
index 01b663f345..24885d2475 100644
--- a/src/plugins/vcsbase/vcsbaseeditor.h
+++ b/src/plugins/vcsbase/vcsbaseeditor.h
@@ -38,6 +38,7 @@
QT_BEGIN_NAMESPACE
class QAction;
+class QRegExp;
class QTextCodec;
class QTextCursor;
QT_END_NAMESPACE
@@ -99,6 +100,11 @@ protected:
// virtual functions).
explicit VcsBaseEditorWidget(const VcsBaseEditorParameters *type,
QWidget *parent);
+ // Pattern for diff header. File name must be in the first capture group
+ void setDiffFilePattern(const QRegExp &pattern);
+ // Pattern for log entry. hash/revision number must be in the first capture group
+ void setLogEntryPattern(const QRegExp &pattern);
+
public:
void init();
@@ -187,7 +193,6 @@ public:
static Core::IEditor* locateEditorByTag(const QString &tag);
static QString editorTag(EditorContentType t, const QString &workingDirectory, const QStringList &files,
const QString &revision = QString());
-
signals:
// These signals also exist in the opaque editable (IEditor) that is
// handled by the editor manager for convenience. They are emitted
@@ -217,8 +222,9 @@ public slots:
private slots:
void slotActivateAnnotation();
void slotPopulateDiffBrowser();
- void slotDiffBrowse(int);
- void slotDiffCursorPositionChanged();
+ void slotPopulateLogBrowser();
+ void slotJumpToEntry(int);
+ void slotCursorPositionChanged();
void slotAnnotateRevision();
void slotApplyDiffChunk();
void slotPaste();
@@ -227,25 +233,22 @@ protected:
/* A helper that can be used to locate a file in a diff in case it
* is relative. Tries to derive the directory from base directory,
* source and version control. */
- QString findDiffFile(const QString &f) const;
+ virtual QString findDiffFile(const QString &f) const;
- virtual bool canApplyDiffChunk(const DiffChunk &dc) const;
- // Revert a patch chunk. Default implementation uses patch.exe
- virtual bool applyDiffChunk(const DiffChunk &dc, bool revert = false) const;
+ virtual void addChangeActions(QMenu *menu, const QString &change);
-private:
// Implement to return a set of change identifiers in
// annotation mode
virtual QSet<QString> annotationChanges() const = 0;
// Implement to identify a change number at the cursor position
virtual QString changeUnderCursor(const QTextCursor &) const = 0;
// Factory functions for highlighters
- virtual DiffHighlighter *createDiffHighlighter() const = 0;
virtual BaseAnnotationHighlighter *createAnnotationHighlighter(const QSet<QString> &changes,
const QColor &bg) const = 0;
- // Implement to return a local file name from the diff file specification
+ // Returns a local file name from the diff file specification
// (text cursor at position above change hunk)
- virtual QString fileNameFromDiffSpecification(const QTextBlock &diffFileSpec) const = 0;
+ QString fileNameFromDiffSpecification(const QTextBlock &inBlock) const;
+
// Implement to return decorated annotation change for "Annotate version"
virtual QString decorateVersion(const QString &revision) const;
// Implement to return the previous version[s] of an annotation change
@@ -253,6 +256,19 @@ private:
virtual QStringList annotationPreviousVersions(const QString &revision) const;
// Implement to validate revisions
virtual bool isValidRevision(const QString &revision) const;
+ // Implement to return subject for a change line in log
+ virtual QString revisionSubject(const QTextBlock &inBlock) const;
+
+private:
+ bool canApplyDiffChunk(const DiffChunk &dc) const;
+ // Revert a patch chunk. Default implementation uses patch.exe
+ bool applyDiffChunk(const DiffChunk &dc, bool revert = false) const;
+
+ // Indicates if the editor has diff contents. If true, an appropriate
+ // highlighter is used and double-click inside a diff chunk jumps to
+ // the relevant file and line
+ bool hasDiff() const;
+
// cut out chunk and determine file name.
DiffChunk diffChunk(QTextCursor cursor) const;
@@ -260,6 +276,12 @@ private:
friend class Internal::ChangeTextCursorHandler;
Internal::VcsBaseEditorWidgetPrivate *const d;
+
+#ifdef WITH_TESTS
+public:
+ void testDiffFileResolving();
+ void testLogResolving(QByteArray &data, const QByteArray &entry1, const QByteArray &entry2);
+#endif
};
} // namespace VcsBase
diff --git a/src/plugins/vcsbase/vcsbaseoptionspage.cpp b/src/plugins/vcsbase/vcsbaseoptionspage.cpp
index 51b6cb61db..de07fb1e3e 100644
--- a/src/plugins/vcsbase/vcsbaseoptionspage.cpp
+++ b/src/plugins/vcsbase/vcsbaseoptionspage.cpp
@@ -44,7 +44,7 @@ namespace VcsBase {
VcsBaseOptionsPage::VcsBaseOptionsPage(QObject *parent) :
Core::IOptionsPage(parent)
{
- setCategory(QLatin1String(Constants::VCS_SETTINGS_CATEGORY));
+ setCategory(Constants::VCS_SETTINGS_CATEGORY);
setDisplayCategory(QCoreApplication::translate("VcsBase", Constants::VCS_SETTINGS_TR_CATEGORY));
setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_VCS_ICON));
}
diff --git a/src/plugins/vcsbase/vcsbaseplugin.cpp b/src/plugins/vcsbase/vcsbaseplugin.cpp
index 52935f76e6..ac4846548c 100644
--- a/src/plugins/vcsbase/vcsbaseplugin.cpp
+++ b/src/plugins/vcsbase/vcsbaseplugin.cpp
@@ -282,9 +282,8 @@ void StateListener::slotStateChanged()
&state.currentProjectTopLevel);
if (projectControl) {
// If we have both, let the file's one take preference
- if (fileControl && projectControl != fileControl) {
+ if (fileControl && projectControl != fileControl)
state.clearProject();
- }
} else {
state.clearProject(); // No control found
}
@@ -410,6 +409,15 @@ QString VcsBasePluginState::topLevel() const
return hasFile() ? data->m_state.currentFileTopLevel : data->m_state.currentProjectTopLevel;
}
+QString VcsBasePluginState::currentDirectoryOrTopLevel() const
+{
+ if (hasFile())
+ return data->m_state.currentFileDirectory;
+ else if (data->m_state.hasProject())
+ return data->m_state.currentProjectTopLevel;
+ return QString();
+}
+
bool VcsBasePluginState::equals(const Internal::State &rhs) const
{
return data->m_state.equals(rhs);
@@ -973,10 +981,8 @@ bool VcsBasePlugin::runFullySynchronous(const QString &workingDirectory,
if (binary.isEmpty())
return false;
- VcsBase::VcsBaseOutputWindow *outputWindow = VcsBase::VcsBaseOutputWindow::instance();
-
if (logCommandToWindow)
- outputWindow->appendCommand(workingDirectory, binary, arguments);
+ VcsBase::VcsBaseOutputWindow::instance()->appendCommand(workingDirectory, binary, arguments);
QProcess process;
process.setWorkingDirectory(workingDirectory);
diff --git a/src/plugins/vcsbase/vcsbaseplugin.h b/src/plugins/vcsbase/vcsbaseplugin.h
index 2a80e48621..570f370c44 100644
--- a/src/plugins/vcsbase/vcsbaseplugin.h
+++ b/src/plugins/vcsbase/vcsbaseplugin.h
@@ -99,6 +99,7 @@ public:
// the file one.
QString topLevel() const;
+ QString currentDirectoryOrTopLevel() const;
bool equals(const VcsBasePluginState &rhs) const;
friend VCSBASE_EXPORT QDebug operator<<(QDebug in, const VcsBasePluginState &state);
diff --git a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
index 9e52791a05..3bb4c8ed18 100644
--- a/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
+++ b/src/plugins/vcsbase/vcsbasesubmiteditor.cpp
@@ -30,10 +30,13 @@
#include "vcsbasesubmiteditor.h"
#include "commonvcssettings.h"
-#include "vcsbaseoutputwindow.h"
-#include "vcsplugin.h"
#include "nicknamedialog.h"
#include "submiteditorfile.h"
+#include "submiteditorwidget.h"
+#include "submitfieldwidget.h"
+#include "submitfilemodel.h"
+#include "vcsbaseoutputwindow.h"
+#include "vcsplugin.h"
#include <aggregation/aggregate.h>
#include <cplusplus/Control.h>
@@ -44,17 +47,17 @@
#include <cplusplus/Symbol.h>
#include <cplusplus/Symbols.h>
#include <cplusplus/TranslationUnit.h>
-#include <coreplugin/idocument.h>
#include <coreplugin/icore.h>
-#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/id.h>
+#include <coreplugin/idocument.h>
+#include <coreplugin/mainwindow.h>
#include <coreplugin/actionmanager/actionmanager.h>
+#include <coreplugin/editormanager/editormanager.h>
#include <utils/completingtextedit.h>
-#include <utils/submiteditorwidget.h>
#include <utils/checkablemessagebox.h>
#include <utils/synchronousprocess.h>
-#include <utils/submitfieldwidget.h>
#include <utils/fileutils.h>
+#include <utils/qtcassert.h>
#include <find/basetextfind.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>
@@ -118,7 +121,7 @@ static const char *belongingClassName(const CPlusPlus::Function *function)
/*!
\class VcsBase::VcsBaseSubmitEditor
- \brief Base class for a submit editor based on the Utils::SubmitEditorWidget.
+ \brief Base class for a submit editor based on the SubmitEditorWidget.
Presents the commit message in a text editor and an
checkable list of modified files in a list window. The user can delete
@@ -207,7 +210,7 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
connect(d->m_file, SIGNAL(saveMe(QString*,QString,bool)),
this, SLOT(save(QString*,QString,bool)));
- connect(d->m_widget, SIGNAL(diffSelected(QStringList)), this, SLOT(slotDiffSelectedVcsFiles(QStringList)));
+ connect(d->m_widget, SIGNAL(diffSelected(QList<int>)), this, SLOT(slotDiffSelectedVcsFiles(QList<int>)));
connect(d->m_widget->descriptionEdit(), SIGNAL(textChanged()), this, SLOT(slotDescriptionChanged()));
const CommonVcsSettings settings = VcsPlugin::instance()->settings();
@@ -238,6 +241,9 @@ VcsBaseSubmitEditor::VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *pa
connect(VcsPlugin::instance(),
SIGNAL(settingsChanged(VcsBase::Internal::CommonVcsSettings)),
this, SLOT(slotUpdateEditorSettings(VcsBase::Internal::CommonVcsSettings)));
+ connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)),
+ this, SLOT(slotRefreshCommitData()));
+ connect(Core::ICore::mainWindow(), SIGNAL(windowActivated()), this, SLOT(slotRefreshCommitData()));
Aggregation::Aggregate *aggregate = new Aggregation::Aggregate;
aggregate->add(new Find::BaseTextFind(d->m_widget->descriptionEdit()));
@@ -257,6 +263,12 @@ void VcsBaseSubmitEditor::slotUpdateEditorSettings(const CommonVcsSettings &s)
setLineWrap(s.lineWrap);
}
+void VcsBaseSubmitEditor::slotRefreshCommitData()
+{
+ if (Core::EditorManager::currentEditor() == this)
+ updateFileModel();
+}
+
// Return a trimmed list of non-empty field texts
static inline QStringList fieldTexts(const QString &fileContents)
{
@@ -308,16 +320,6 @@ void VcsBaseSubmitEditor::unregisterActions(QAction *editorUndoAction, QAction
d->m_diffAction = d->m_submitAction = 0;
}
-int VcsBaseSubmitEditor::fileNameColumn() const
-{
- return d->m_widget->fileNameColumn();
-}
-
-void VcsBaseSubmitEditor::setFileNameColumn(int c)
-{
- d->m_widget->setFileNameColumn(c);
-}
-
QAbstractItemView::SelectionMode VcsBaseSubmitEditor::fileListSelectionMode() const
{
return d->m_widget->fileListSelectionMode();
@@ -426,7 +428,7 @@ Core::IEditor *VcsBaseSubmitEditor::duplicate(QWidget * /*parent*/)
Core::Id VcsBaseSubmitEditor::id() const
{
- return d->m_parameters->id;
+ return Core::Id(QByteArray(d->m_parameters->id));
}
static QToolBar *createToolBar(const QWidget *someWidget, QAction *submitAction, QAction *diffAction)
@@ -476,17 +478,21 @@ QStringList VcsBaseSubmitEditor::checkedFiles() const
return d->m_widget->checkedFiles();
}
-void VcsBaseSubmitEditor::setFileModel(QAbstractItemModel *m, const QString &repositoryDirectory)
+void VcsBaseSubmitEditor::setFileModel(SubmitFileModel *model, const QString &repositoryDirectory)
{
- d->m_widget->setFileModel(m);
+ QTC_ASSERT(model, return);
+ if (SubmitFileModel *oldModel = d->m_widget->fileModel()) {
+ model->updateSelections(oldModel);
+ delete oldModel;
+ }
+ d->m_widget->setFileModel(model);
QSet<QString> uniqueSymbols;
const CPlusPlus::Snapshot cppSnapShot = CPlusPlus::CppModelManagerInterface::instance()->snapshot();
// Iterate over the files and get interesting symbols
- for (int row = 0; row < m->rowCount(); ++row) {
- const QString fileName = m->data(m->index(row, d->m_widget->fileNameColumn())).toString();
- const QFileInfo fileInfo(repositoryDirectory, fileName);
+ for (int row = 0; row < model->rowCount(); ++row) {
+ const QFileInfo fileInfo(repositoryDirectory, model->file(row));
// Add file name
uniqueSymbols.insert(fileInfo.fileName());
@@ -529,14 +535,30 @@ void VcsBaseSubmitEditor::setFileModel(QAbstractItemModel *m, const QString &rep
}
}
-QAbstractItemModel *VcsBaseSubmitEditor::fileModel() const
+SubmitFileModel *VcsBaseSubmitEditor::fileModel() const
{
return d->m_widget->fileModel();
}
-void VcsBaseSubmitEditor::slotDiffSelectedVcsFiles(const QStringList &rawList)
+QStringList VcsBaseSubmitEditor::rowsToFiles(const QList<int> &rows) const
+{
+ if (rows.empty())
+ return QStringList();
+
+ QStringList rc;
+ const SubmitFileModel *model = fileModel();
+ const int count = rows.size();
+ for (int i = 0; i < count; i++)
+ rc.push_back(model->file(rows.at(i)));
+ return rc;
+}
+
+void VcsBaseSubmitEditor::slotDiffSelectedVcsFiles(const QList<int> &rawList)
{
- emit diffSelectedFiles(rawList);
+ if (d->m_parameters->diffType == VcsBaseSubmitEditorParameters::DiffRows)
+ emit diffSelectedFiles(rawList);
+ else
+ emit diffSelectedFiles(rowsToFiles(rawList));
}
bool VcsBaseSubmitEditor::save(QString *errorString, const QString &fileName, bool autoSave)
@@ -801,11 +823,10 @@ void VcsBaseSubmitEditor::filterUntrackedFilesOfProject(const QString &repositor
const QDir repoDir(repositoryDirectory);
for (QStringList::iterator it = untrackedFiles->begin(); it != untrackedFiles->end(); ) {
const QString path = QDir::toNativeSeparators(repoDir.absoluteFilePath(*it));
- if (nativeProjectFiles.contains(path)) {
+ if (nativeProjectFiles.contains(path))
++it;
- } else {
+ else
it = untrackedFiles->erase(it);
- }
}
}
diff --git a/src/plugins/vcsbase/vcsbasesubmiteditor.h b/src/plugins/vcsbase/vcsbasesubmiteditor.h
index 4b95951211..59d89a9899 100644
--- a/src/plugins/vcsbase/vcsbasesubmiteditor.h
+++ b/src/plugins/vcsbase/vcsbasesubmiteditor.h
@@ -38,17 +38,16 @@
QT_BEGIN_NAMESPACE
class QIcon;
-class QAbstractItemModel;
class QAction;
QT_END_NAMESPACE
-namespace Utils { class SubmitEditorWidget; }
-
namespace VcsBase {
namespace Internal {
class CommonVcsSettings;
}
struct VcsBaseSubmitEditorPrivate;
+class SubmitEditorWidget;
+class SubmitFileModel;
class VCSBASE_EXPORT VcsBaseSubmitEditorParameters
{
@@ -57,12 +56,12 @@ public:
const char *id;
const char *displayName;
const char *context;
+ enum DiffType { DiffRows, DiffFiles } diffType;
};
class VCSBASE_EXPORT VcsBaseSubmitEditor : public Core::IEditor
{
Q_OBJECT
- Q_PROPERTY(int fileNameColumn READ fileNameColumn WRITE setFileNameColumn DESIGNABLE false)
Q_PROPERTY(QAbstractItemView::SelectionMode fileListSelectionMode READ fileListSelectionMode WRITE setFileListSelectionMode DESIGNABLE true)
Q_PROPERTY(bool lineWrap READ lineWrap WRITE setLineWrap DESIGNABLE true)
Q_PROPERTY(int lineWrapWidth READ lineWrapWidth WRITE setLineWrapWidth DESIGNABLE true)
@@ -71,7 +70,7 @@ class VCSBASE_EXPORT VcsBaseSubmitEditor : public Core::IEditor
protected:
explicit VcsBaseSubmitEditor(const VcsBaseSubmitEditorParameters *parameters,
- Utils::SubmitEditorWidget *editorWidget);
+ SubmitEditorWidget *editorWidget);
public:
// Register the actions with the submit editor widget.
@@ -95,9 +94,6 @@ public:
bool forcePrompt = false,
bool canCommitOnFailure = true) const;
- int fileNameColumn() const;
- void setFileNameColumn(int c);
-
QAbstractItemView::SelectionMode fileListSelectionMode() const;
void setFileListSelectionMode(QAbstractItemView::SelectionMode sm);
@@ -132,8 +128,10 @@ public:
QStringList checkedFiles() const;
- void setFileModel(QAbstractItemModel *m, const QString &repositoryDirectory = QString());
- QAbstractItemModel *fileModel() const;
+ void setFileModel(SubmitFileModel *m, const QString &repositoryDirectory = QString());
+ SubmitFileModel *fileModel() const;
+ virtual void updateFileModel() { }
+ QStringList rowsToFiles(const QList<int> &rows) const;
// Utilities returning some predefined icons for actions
static QIcon diffIcon();
@@ -152,15 +150,17 @@ public:
signals:
void diffSelectedFiles(const QStringList &files);
+ void diffSelectedFiles(const QList<int> &rows);
private slots:
- void slotDiffSelectedVcsFiles(const QStringList &rawList);
+ void slotDiffSelectedVcsFiles(const QList<int> &rawList);
bool save(QString *errorString, const QString &fileName, bool autoSave);
void slotDescriptionChanged();
void slotCheckSubmitMessage();
void slotInsertNickName();
void slotSetFieldNickName(int);
void slotUpdateEditorSettings(const VcsBase::Internal::CommonVcsSettings &);
+ void slotRefreshCommitData();
protected:
/* These hooks allow for modifying the contents that goes to
diff --git a/src/plugins/vcsbase/vcsconfigurationpage.cpp b/src/plugins/vcsbase/vcsconfigurationpage.cpp
index 7caa4cbf32..a9f1552b4f 100644
--- a/src/plugins/vcsbase/vcsconfigurationpage.cpp
+++ b/src/plugins/vcsbase/vcsconfigurationpage.cpp
@@ -83,8 +83,8 @@ bool VcsConfigurationPage::isComplete() const
void VcsConfigurationPage::openConfiguration()
{
- Core::ICore::showOptionsDialog(QLatin1String(VcsBase::Constants::VCS_SETTINGS_CATEGORY),
- d->m_versionControl->id().toString());
+ Core::ICore::showOptionsDialog(Constants::VCS_SETTINGS_CATEGORY,
+ d->m_versionControl->id());
}
} // namespace VcsBase
diff --git a/src/plugins/welcome/welcome.qbs b/src/plugins/welcome/welcome.qbs
index d999ee58c5..a99fe82ab9 100644
--- a/src/plugins/welcome/welcome.qbs
+++ b/src/plugins/welcome/welcome.qbs
@@ -10,19 +10,11 @@ QtcPlugin {
Depends { name: "ProjectExplorer" }
Depends { name: "cpp" }
- cpp.defines: project.additionalCppDefines
- cpp.includePaths: [
- "..",
- "../../libs",
- "../../../src/shared/scriptwrapper",
- "../../Core/dynamiclibrary",
- buildDirectory
- ]
+ cpp.includePaths: base.concat("../../shared/scriptwrapper")
files: [
"welcome_global.h",
"welcomeplugin.cpp",
- "welcomeplugin.h"
+ "welcomeplugin.h",
]
}
-
diff --git a/src/plugins/welcome/welcomeplugin.cpp b/src/plugins/welcome/welcomeplugin.cpp
index c063d02a3f..b3a80ae66d 100644
--- a/src/plugins/welcome/welcomeplugin.cpp
+++ b/src/plugins/welcome/welcomeplugin.cpp
@@ -40,6 +40,7 @@
#include <projectexplorer/projectexplorer.h>
+#include <utils/hostosinfo.h>
#include <utils/styledbar.h>
#include <utils/iwelcomepage.h>
#include <utils/networkaccessmanager.h>
@@ -68,6 +69,7 @@
enum { debug = 0 };
using namespace ExtensionSystem;
+using namespace Utils;
static const char currentPageSettingsKeyC[] = "WelcomeTab";
@@ -261,11 +263,10 @@ void WelcomeMode::initPlugins()
engine->setOutputWarningsToStandardError(false);
engine->setNetworkAccessManagerFactory(m_networkAccessManagerFactory);
QString pluginPath = applicationDirPath();
-#ifdef Q_OS_MAC
- pluginPath += QLatin1String("/../PlugIns");
-#else
- pluginPath += QLatin1String("/../" IDE_LIBRARY_BASENAME "/qtcreator");
-#endif
+ if (HostOsInfo::isMacHost())
+ pluginPath += QLatin1String("/../PlugIns");
+ else
+ pluginPath += QLatin1String("/../" IDE_LIBRARY_BASENAME "/qtcreator");
engine->addImportPath(QDir::cleanPath(pluginPath));
facilitateQml(engine);
foreach (Utils::IWelcomePage *plugin, plugins) {
@@ -284,17 +285,13 @@ void WelcomeMode::initPlugins()
QString WelcomeMode::platform() const
{
-#if defined(Q_OS_WIN)
- return QLatin1String("windows");
-#elif defined(Q_OS_MAC)
- return QLatin1String("mac");
-#elif defined(Q_OS_LINUX)
- return QLatin1String("linux");
-#elif defined(Q_OS_UNIX)
- return QLatin1String("unix");
-#else
- return QLatin1String("other")
-#endif
+ switch (HostOsInfo::hostOs()) {
+ case HostOsInfo::HostOsWindows: return QLatin1String("windows");
+ case HostOsInfo::HostOsMac: return QLatin1String("mac");
+ case HostOsInfo::HostOsLinux: return QLatin1String("linux");
+ case HostOsInfo::HostOsOtherUnix: return QLatin1String("unix");
+ default: return QLatin1String("other");
+ }
}
void WelcomeMode::welcomePluginAdded(QObject *obj)
@@ -310,11 +307,10 @@ void WelcomeMode::welcomePluginAdded(QObject *obj)
if (pluginHash.contains(plugin->id())) {
Utils::IWelcomePage* pluginOther = pluginHash.value(plugin->id());
- if (pluginOther->priority() > plugin->priority()) {
+ if (pluginOther->priority() > plugin->priority())
m_pluginList.removeAll(pluginOther);
- } else {
+ else
return;
- }
}
int insertPos = 0;
diff --git a/src/share/share.qbs b/src/share/share.qbs
deleted file mode 100644
index b4f4f030e3..0000000000
--- a/src/share/share.qbs
+++ /dev/null
@@ -1,41 +0,0 @@
-import qbs.base 1.0
-
-Product {
- type: ["installed_content"]
- name: "SharedConditionally"
-
- Group {
- qbs.installDir: "share/qtcreator/externaltools"
- fileTags: ["install"]
- prefix: "qtcreator/externaltools/"
- files: [
- "lrelease.xml",
- "lupdate.xml",
- "qmlviewer.xml",
- "qmlscene.xml",
- "sort.xml",
- ]
- }
-
- Group {
- condition: qbs.targetOS == "linux"
- qbs.installDir: "share/qtcreator/externaltools"
- fileTags: ["install"]
- files: ["qtcreator/externaltools/vi.xml"]
- }
-
- Group {
- condition: qbs.targetOS == "mac"
- qbs.installDir: "share/qtcreator/externaltools"
- fileTags: ["install"]
- files: ["qtcreator/externaltools/vi_mac.xml"]
- }
-
- Group {
- condition: qbs.targetOS == "windows"
- qbs.installDir: "share/qtcreator/externaltools"
- fileTags: ["install"]
- files: ["qtcreator/externaltools/notepad_win.xml"]
- }
-}
-
diff --git a/src/shared/cpaster/cgi.cpp b/src/shared/cpaster/cgi.cpp
index 169cb26e8d..0c64e02c52 100644
--- a/src/shared/cpaster/cgi.cpp
+++ b/src/shared/cpaster/cgi.cpp
@@ -161,13 +161,13 @@ inline const char *unicodeToHTML(ushort unicode_char)
case 0x00BD: return "frac12"; // (189 ) vulgar fraction one half = fraction one half
case 0x00BE: return "frac34"; // (190 ) vulgar fraction three quarters = fraction three quarters
case 0x00BF: return "iquest"; // (191 ) inverted question mark = turned question mark
- case 0x00C0: return "Agrave"; // (192 ) capital letter A with grave = capital letter
+ case 0x00C0: return "Agrave"; // (192 ) capital letter A with grave = capital letter
case 0x00C1: return "Aacute"; // (193 ) capital letter A with acute
case 0x00C2: return "Acirc"; // (194 ) capital letter A with circumflex
case 0x00C3: return "Atilde"; // (195 ) capital letter A with tilde
case 0x00C4: return "Auml"; // (196 ) capital letter A with diaeresis
- case 0x00C5: return "Aring"; // (197 ) capital letter A with ring above = capital letter
- case 0x00C6: return "AElig"; // (198 ) capital letter AE = capital ligature
+ case 0x00C5: return "Aring"; // (197 ) capital letter A with ring above = capital letter
+ case 0x00C6: return "AElig"; // (198 ) capital letter AE = capital ligature
case 0x00C7: return "Ccedil"; // (199 ) capital letter C with cedilla
case 0x00C8: return "Egrave"; // (200 ) capital letter E with grave
case 0x00C9: return "Eacute"; // (201 ) capital letter E with acute
@@ -185,7 +185,7 @@ inline const char *unicodeToHTML(ushort unicode_char)
case 0x00D5: return "Otilde"; // (213 ) capital letter O with tilde
case 0x00D6: return "Ouml"; // (214 ) capital letter O with diaeresis
case 0x00D7: return "times"; // (215 ) multiplication sign
- case 0x00D8: return "Oslash"; // (216 ) capital letter O with stroke = capital letter
+ case 0x00D8: return "Oslash"; // (216 ) capital letter O with stroke = capital letter
case 0x00D9: return "Ugrave"; // (217 ) capital letter U with grave
case 0x00DA: return "Uacute"; // (218 ) capital letter U with acute
case 0x00DB: return "Ucirc"; // (219 ) capital letter U with circumflex
@@ -193,13 +193,13 @@ inline const char *unicodeToHTML(ushort unicode_char)
case 0x00DD: return "Yacute"; // (221 ) capital letter Y with acute
case 0x00DE: return "THORN"; // (222 ) capital letter THORN
case 0x00DF: return "szlig"; // (223 ) small letter sharp s = ess-zed
- case 0x00E0: return "agrave"; // (224 ) small letter a with grave = small letter
+ case 0x00E0: return "agrave"; // (224 ) small letter a with grave = small letter
case 0x00E1: return "aacute"; // (225 ) small letter a with acute
case 0x00E2: return "acirc"; // (226 ) small letter a with circumflex
case 0x00E3: return "atilde"; // (227 ) small letter a with tilde
case 0x00E4: return "auml"; // (228 ) small letter a with diaeresis
- case 0x00E5: return "aring"; // (229 ) small letter a with ring above = small letter
- case 0x00E6: return "aelig"; // (230 ) small letter ae = small letter
+ case 0x00E5: return "aring"; // (229 ) small letter a with ring above = small letter
+ case 0x00E6: return "aelig"; // (230 ) small letter ae = small letter
case 0x00E7: return "ccedil"; // (231 ) small letter c with cedilla
case 0x00E8: return "egrave"; // (232 ) small letter e with grave
case 0x00E9: return "eacute"; // (233 ) small letter e with acute
@@ -217,7 +217,7 @@ inline const char *unicodeToHTML(ushort unicode_char)
case 0x00F5: return "otilde"; // (245 ) small letter o with tilde
case 0x00F6: return "ouml"; // (246 ) small letter o with diaeresis
case 0x00F7: return "divide"; // (247 ) division sign
- case 0x00F8: return "oslash"; // (248 ) small letter o with stroke = small letter
+ case 0x00F8: return "oslash"; // (248 ) small letter o with stroke = small letter
case 0x00F9: return "ugrave"; // (249 ) small letter u with grave
case 0x00FA: return "uacute"; // (250 ) small letter u with acute
case 0x00FB: return "ucirc"; // (251 ) small letter u with circumflex
diff --git a/src/shared/help/bookmarkmanager.cpp b/src/shared/help/bookmarkmanager.cpp
index daca7fd5a6..7cf164d0f0 100644
--- a/src/shared/help/bookmarkmanager.cpp
+++ b/src/shared/help/bookmarkmanager.cpp
@@ -397,12 +397,10 @@ void BookmarkWidget::customContextMenuRequested(const QPoint &point)
if (!pickedAction)
return;
- if (pickedAction == showItem) {
+ if (pickedAction == showItem)
emit linkActivated(data);
- }
- else if (pickedAction == showItemNewTab) {
+ else if (pickedAction == showItemNewTab)
emit createPage(QUrl(data), false);
- }
else if (pickedAction == removeItem) {
bookmarkManager->removeBookmarkItem(treeView,
filterBookmarkModel->mapToSource(index));
@@ -674,11 +672,10 @@ QModelIndex BookmarkManager::addNewFolder(const QModelIndex& index)
item->setData(QLatin1String("Folder"), Qt::UserRole + 10);
item->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirClosedIcon));
- if (index.isValid()) {
+ if (index.isValid())
treeModel->itemFromIndex(index)->appendRow(item);
- } else {
+ else
treeModel->appendRow(item);
- }
return treeModel->indexFromItem(item);
}
@@ -785,9 +782,8 @@ void BookmarkManager::setupBookmarkModels()
}
}
parents.last()->appendRow(item);
- if (type == QLatin1String("Folder")) {
+ if (type == QLatin1String("Folder"))
parents << item; lastDepths << depth;
- }
}
if (type != QLatin1String("Folder")) {
diff --git a/src/shared/help/indexwindow.cpp b/src/shared/help/indexwindow.cpp
index 57ef6cba5f..92d8cfc357 100644
--- a/src/shared/help/indexwindow.cpp
+++ b/src/shared/help/indexwindow.cpp
@@ -36,6 +36,7 @@
#include "topicchooser.h"
#include <utils/filterlineedit.h>
+#include <utils/hostosinfo.h>
#include <utils/styledbar.h>
#include <QLayout>
@@ -164,13 +165,12 @@ bool IndexWindow::eventFilter(QObject *obj, QEvent *e)
}
}
}
-#ifdef Q_OS_MAC
- else if (obj == m_indexWidget && e->type() == QEvent::KeyPress) {
+ else if (Utils::HostOsInfo::isMacHost() && obj == m_indexWidget
+ && e->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent*>(e);
if (ke->key() == Qt::Key_Return || ke->key() == Qt::Key_Enter)
m_indexWidget->activateCurrentItem();
}
-#endif
return QWidget::eventFilter(obj, e);
}
diff --git a/src/shared/proparser/ioutils.cpp b/src/shared/proparser/ioutils.cpp
index bc969b9521..6706f80bee 100644
--- a/src/shared/proparser/ioutils.cpp
+++ b/src/shared/proparser/ioutils.cpp
@@ -29,8 +29,8 @@
#include "ioutils.h"
-#include <QDir>
-#include <QFile>
+#include <qdir.h>
+#include <qfile.h>
#ifdef Q_OS_WIN
# include <windows.h>
@@ -42,7 +42,7 @@
QT_BEGIN_NAMESPACE
-using namespace ProFileEvaluatorInternal;
+using namespace QMakeInternal;
IoUtils::FileType IoUtils::fileType(const QString &fileName)
{
diff --git a/src/shared/proparser/ioutils.h b/src/shared/proparser/ioutils.h
index f29b41480a..865e4a7511 100644
--- a/src/shared/proparser/ioutils.h
+++ b/src/shared/proparser/ioutils.h
@@ -30,11 +30,11 @@
#ifndef IOUTILS_H
#define IOUTILS_H
-#include <QString>
+#include <qstring.h>
QT_BEGIN_NAMESPACE
-namespace ProFileEvaluatorInternal {
+namespace QMakeInternal {
/*!
This class provides replacement functionality for QFileInfo, QFile & QDir,
diff --git a/src/shared/proparser/profileevaluator.cpp b/src/shared/proparser/profileevaluator.cpp
index eb361ff2ba..47012d99fd 100644
--- a/src/shared/proparser/profileevaluator.cpp
+++ b/src/shared/proparser/profileevaluator.cpp
@@ -34,7 +34,7 @@
#include <QDir>
-using namespace ProFileEvaluatorInternal;
+using namespace QMakeInternal;
QT_BEGIN_NAMESPACE
@@ -43,7 +43,7 @@ void ProFileEvaluator::initialize()
QMakeEvaluator::initStatics();
}
-ProFileEvaluator::ProFileEvaluator(QMakeGlobals *option, QMakeParser *parser,
+ProFileEvaluator::ProFileEvaluator(ProFileGlobals *option, QMakeParser *parser,
QMakeHandler *handler)
: d(new QMakeEvaluator(option, parser, handler))
{
@@ -81,7 +81,7 @@ QStringList ProFileEvaluator::values(const QString &variableName) const
QStringList ProFileEvaluator::values(const QString &variableName, const ProFile *pro) const
{
// It makes no sense to put any kind of magic into expanding these
- const ProStringList &values = d->m_valuemapStack.at(0).value(ProKey(variableName));
+ const ProStringList &values = d->m_valuemapStack.first().value(ProKey(variableName));
QStringList ret;
ret.reserve(values.size());
foreach (const ProString &str, values)
@@ -92,16 +92,17 @@ QStringList ProFileEvaluator::values(const QString &variableName, const ProFile
QString ProFileEvaluator::sysrootify(const QString &path, const QString &baseDir) const
{
+ ProFileGlobals *option = static_cast<ProFileGlobals *>(d->m_option);
#ifdef Q_OS_WIN
Qt::CaseSensitivity cs = Qt::CaseInsensitive;
#else
Qt::CaseSensitivity cs = Qt::CaseSensitive;
#endif
const bool isHostSystemPath =
- d->m_option->sysroot.isEmpty() || path.startsWith(d->m_option->sysroot, cs)
+ option->sysroot.isEmpty() || path.startsWith(option->sysroot, cs)
|| path.startsWith(baseDir, cs) || path.startsWith(d->m_outputDir, cs);
- return isHostSystemPath ? path : d->m_option->sysroot + path;
+ return isHostSystemPath ? path : option->sysroot + path;
}
QStringList ProFileEvaluator::absolutePathValues(
@@ -214,6 +215,21 @@ void ProFileEvaluator::setCumulative(bool on)
}
#endif
+void ProFileEvaluator::setExtraVars(const QHash<QString, QStringList> &extraVars)
+{
+ ProValueMap map;
+ QHash<QString, QStringList>::const_iterator it = extraVars.constBegin();
+ QHash<QString, QStringList>::const_iterator end = extraVars.constEnd();
+ for ( ; it != end; ++it)
+ map.insert(ProKey(it.key()), ProStringList(it.value()));
+ d->setExtraVars(map);
+}
+
+void ProFileEvaluator::setExtraConfigs(const QStringList &extraConfigs)
+{
+ d->setExtraConfigs(ProStringList(extraConfigs));
+}
+
void ProFileEvaluator::setOutputDir(const QString &dir)
{
d->m_outputDir = dir;
diff --git a/src/shared/proparser/profileevaluator.h b/src/shared/proparser/profileevaluator.h
index 926d2509f5..a172536411 100644
--- a/src/shared/proparser/profileevaluator.h
+++ b/src/shared/proparser/profileevaluator.h
@@ -31,6 +31,7 @@
#define PROFILEEVALUATOR_H
#include "qmake_global.h"
+#include "qmakeglobals.h"
#include "qmakeevaluator.h"
#include "proitems.h"
@@ -39,11 +40,16 @@
QT_BEGIN_NAMESPACE
-class QMakeGlobals;
class QMakeParser;
class QMakeEvaluator;
class QMakeHandler;
+class QMAKE_EXPORT ProFileGlobals : public QMakeGlobals
+{
+public:
+ QString sysroot;
+};
+
class QMAKE_EXPORT ProFileEvaluator
{
public:
@@ -59,13 +65,15 @@ public:
// Call this from a concurrency-free context
static void initialize();
- ProFileEvaluator(QMakeGlobals *option, QMakeParser *parser, QMakeHandler *handler);
+ ProFileEvaluator(ProFileGlobals *option, QMakeParser *parser, QMakeHandler *handler);
~ProFileEvaluator();
ProFileEvaluator::TemplateType templateType() const;
#ifdef PROEVALUATOR_CUMULATIVE
void setCumulative(bool on); // Default is false
#endif
+ void setExtraVars(const QHash<QString, QStringList> &extraVars);
+ void setExtraConfigs(const QStringList &extraConfigs);
void setOutputDir(const QString &dir); // Default is empty
bool loadNamedSpec(const QString &specDir, bool hostSpec);
diff --git a/src/shared/proparser/proitems.cpp b/src/shared/proparser/proitems.cpp
index 9aab65f3af..cf42efe92b 100644
--- a/src/shared/proparser/proitems.cpp
+++ b/src/shared/proparser/proitems.cpp
@@ -29,10 +29,10 @@
#include "proitems.h"
-#include <QFileInfo>
-#include <QSet>
-#include <QStringList>
-#include <QTextStream>
+#include <qfileinfo.h>
+#include <qset.h>
+#include <qstringlist.h>
+#include <qtextstream.h>
QT_BEGIN_NAMESPACE
@@ -155,14 +155,14 @@ QString &ProString::toQString(QString &tmp) const
return tmp.setRawData(m_string.constData() + m_offset, m_length);
}
-QChar *ProString::prepareAppend(int extraLen)
+QChar *ProString::prepareExtend(int extraLen, int thisTarget, int extraTarget)
{
if (m_string.isDetached() && m_length + extraLen <= m_string.capacity()) {
m_string.reserve(0); // Prevent the resize() below from reallocating
QChar *ptr = (QChar *)m_string.constData();
- if (m_offset)
- memmove(ptr, ptr + m_offset, m_length * 2);
- ptr += m_length;
+ if (m_offset != thisTarget)
+ memmove(ptr + thisTarget, ptr + m_offset, m_length * 2);
+ ptr += extraTarget;
m_offset = 0;
m_length += extraLen;
m_string.resize(m_length);
@@ -171,13 +171,51 @@ QChar *ProString::prepareAppend(int extraLen)
} else {
QString neu(m_length + extraLen, Qt::Uninitialized);
QChar *ptr = (QChar *)neu.constData();
- memcpy(ptr, m_string.constData() + m_offset, m_length * 2);
- ptr += m_length;
+ memcpy(ptr + thisTarget, m_string.constData() + m_offset, m_length * 2);
+ ptr += extraTarget;
*this = ProString(neu);
return ptr;
}
}
+ProString &ProString::prepend(const ProString &other)
+{
+ if (other.m_length) {
+ if (!m_length) {
+ *this = other;
+ } else {
+ QChar *ptr = prepareExtend(other.m_length, other.m_length, 0);
+ memcpy(ptr, other.constData(), other.m_length * 2);
+ if (!m_file)
+ m_file = other.m_file;
+ }
+ }
+ return *this;
+}
+
+ProString &ProString::append(const QLatin1String other)
+{
+ const char *latin1 = other.latin1();
+#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
+ int size = other.size();
+#else
+ int size = strlen(latin1);
+#endif
+ if (size) {
+ QChar *ptr = prepareExtend(size, 0, m_length);
+ for (int i = 0; i < size; i++)
+ *ptr++ = QLatin1Char(latin1[i]);
+ }
+ return *this;
+}
+
+ProString &ProString::append(QChar other)
+{
+ QChar *ptr = prepareExtend(1, 0, m_length);
+ *ptr = other;
+ return *this;
+}
+
// If pending != 0, prefix with space if appending to non-empty non-pending
ProString &ProString::append(const ProString &other, bool *pending)
{
@@ -187,10 +225,10 @@ ProString &ProString::append(const ProString &other, bool *pending)
} else {
QChar *ptr;
if (pending && !*pending) {
- ptr = prepareAppend(1 + other.m_length);
+ ptr = prepareExtend(1 + other.m_length, 0, m_length);
*ptr++ = 32;
} else {
- ptr = prepareAppend(other.m_length);
+ ptr = prepareExtend(other.m_length, 0, m_length);
}
memcpy(ptr, other.m_string.constData() + other.m_offset, other.m_length * 2);
if (other.m_file)
@@ -223,7 +261,7 @@ ProString &ProString::append(const ProStringList &other, bool *pending, bool ski
else
totalLength--;
- QChar *ptr = prepareAppend(totalLength);
+ QChar *ptr = prepareExtend(totalLength, 0, m_length);
for (int i = startIdx; i < sz; ++i) {
if (putSpace)
*ptr++ = 32;
diff --git a/src/shared/proparser/proitems.h b/src/shared/proparser/proitems.h
index 797b92b164..7680844b7d 100644
--- a/src/shared/proparser/proitems.h
+++ b/src/shared/proparser/proitems.h
@@ -32,9 +32,9 @@
#include "qmake_global.h"
-#include <QString>
-#include <QVector>
-#include <QHash>
+#include <qstring.h>
+#include <qvector.h>
+#include <qhash.h>
QT_BEGIN_NAMESPACE
@@ -77,9 +77,18 @@ public:
ProString &setSource(const ProFile *pro) { m_file = pro; return *this; }
const ProFile *sourceFile() const { return m_file; }
- ProString &operator+=(const ProString &other);
+ ProString &prepend(const ProString &other);
ProString &append(const ProString &other, bool *pending = 0);
+ ProString &append(const QString &other) { return append(ProString(other)); }
+ ProString &append(const QLatin1String other);
+ ProString &append(const char *other) { return append(QLatin1String(other)); }
+ ProString &append(QChar other);
ProString &append(const ProStringList &other, bool *pending = 0, bool skipEmpty1st = false);
+ ProString &operator+=(const ProString &other) { return append(other); }
+ ProString &operator+=(const QString &other) { return append(other); }
+ ProString &operator+=(const QLatin1String other) { return append(other); }
+ ProString &operator+=(const char *other) { return append(other); }
+ ProString &operator+=(QChar other) { return append(other); }
void chop(int n) { Q_ASSERT(n <= m_length); m_length -= n; }
void chopFront(int n) { Q_ASSERT(n <= m_length); m_offset += n; m_length -= n; }
@@ -154,7 +163,7 @@ private:
int m_offset, m_length;
const ProFile *m_file;
mutable uint m_hash;
- QChar *prepareAppend(int extraLen);
+ QChar *prepareExtend(int extraLen, int thisTarget, int extraTarget);
uint updatedHash() const;
friend uint qHash(const ProString &str);
friend QString operator+(const ProString &one, const ProString &two);
@@ -235,6 +244,7 @@ public:
{ return contains(ProString(str), cs); }
bool contains(const char *str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;
};
+Q_DECLARE_TYPEINFO(ProStringList, Q_MOVABLE_TYPE);
inline ProStringList operator+(const ProStringList &one, const ProStringList &two)
{ ProStringList ret = one; ret += two; return ret; }
diff --git a/src/shared/proparser/qmake_global.h b/src/shared/proparser/qmake_global.h
index 86d14e5a9d..5354b838a4 100644
--- a/src/shared/proparser/qmake_global.h
+++ b/src/shared/proparser/qmake_global.h
@@ -52,4 +52,8 @@
# define ALWAYS_INLINE inline
#endif
+#ifdef PROEVALUATOR_FULL
+# define PROEVALUATOR_DEBUG
+#endif
+
#endif
diff --git a/src/shared/proparser/qmakebuiltins.cpp b/src/shared/proparser/qmakebuiltins.cpp
index 74201e1de5..741df83153 100644
--- a/src/shared/proparser/qmakebuiltins.cpp
+++ b/src/shared/proparser/qmakebuiltins.cpp
@@ -34,15 +34,15 @@
#include "qmakeparser.h"
#include "ioutils.h"
-#include <QByteArray>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QList>
-#include <QRegExp>
-#include <QSet>
-#include <QStringList>
-#include <QTextStream>
+#include <qbytearray.h>
+#include <qdir.h>
+#include <qfile.h>
+#include <qfileinfo.h>
+#include <qlist.h>
+#include <qregexp.h>
+#include <qset.h>
+#include <qstringlist.h>
+#include <qtextstream.h>
#ifdef Q_OS_UNIX
#include <time.h>
@@ -65,7 +65,7 @@
#define QT_PCLOSE pclose
#endif
-using namespace ProFileEvaluatorInternal;
+using namespace QMakeInternal;
QT_BEGIN_NAMESPACE
@@ -315,8 +315,10 @@ QMakeEvaluator::writeFile(const QString &ctx, const QString &fn, QIODevice::Open
void QMakeEvaluator::runProcess(QProcess *proc, const QString &command) const
{
proc->setWorkingDirectory(currentDirectory());
+# ifdef PROEVALUATOR_SETENV
if (!m_option->environment.isEmpty())
proc->setProcessEnvironment(m_option->environment);
+# endif
# ifdef Q_OS_WIN
proc->setNativeArguments(QLatin1String("/v:off /s /c \"") + command + QLatin1Char('"'));
proc->start(m_option->getEnv(QLatin1String("COMSPEC")), QStringList());
@@ -347,7 +349,7 @@ QByteArray QMakeEvaluator::getCommandOutput(const QString &args) const
#else
QByteArray out;
if (FILE *proc = QT_POPEN(QString(QLatin1String("cd ")
- + IoUtils::shellQuote(currentDirectory())
+ + IoUtils::shellQuote(QDir::toNativeSeparators(currentDirectory()))
+ QLatin1String(" && ") + args).toLocal8Bit().constData(), "r")) {
while (!feof(proc)) {
char buff[10 * 1024];
@@ -383,13 +385,12 @@ void QMakeEvaluator::populateDeps(
}
}
-ProStringList QMakeEvaluator::evaluateExpandFunction(
- const ProKey &func, const ushort *&tokPtr)
+ProStringList QMakeEvaluator::evaluateBuiltinExpand(
+ const ProKey &func, const ProStringList &args)
{
- QHash<ProKey, ProFunctionDef>::ConstIterator it =
- m_functionDefs.replaceFunctions.constFind(func);
- if (it != m_functionDefs.replaceFunctions.constEnd())
- return evaluateFunction(*it, prepareFunctionArgs(tokPtr), 0);
+ ProStringList ret;
+
+ traceMsg("calling built-in $$%s(%s)", dbgKey(func), dbgSepStrList(args));
ExpandFunc func_t = ExpandFunc(statics.expands.value(func));
if (func_t == 0) {
@@ -401,11 +402,6 @@ ProStringList QMakeEvaluator::evaluateExpandFunction(
deprecationWarning(fL1S("Using uppercased builtin functions is deprecated."));
}
}
-
- //why don't the builtin functions just use args_list? --Sam
- const ProStringList &args = expandVariableReferences(tokPtr, 5, true);
- ProStringList ret;
-
switch (func_t) {
case E_BASENAME:
case E_DIRNAME:
@@ -684,16 +680,15 @@ ProStringList QMakeEvaluator::evaluateExpandFunction(
ProValueMap vars;
QString fn = resolvePath(m_option->expandEnvVars(args.at(0).toQString(m_tmp1)));
fn.detach();
- if (evaluateFileInto(fn, QMakeHandler::EvalAuxFile, &vars, LoadProOnly))
+ if (evaluateFileInto(fn, &vars, LoadProOnly))
ret = vars.value(map(args.at(1)));
}
break;
case E_EVAL:
- if (args.count() != 1) {
+ if (args.count() != 1)
evalError(fL1S("eval(variable) requires one argument."));
- } else {
+ else
ret += values(map(args.at(0)));
- }
break;
case E_LIST: {
QString tmp;
@@ -945,17 +940,9 @@ ProStringList QMakeEvaluator::evaluateExpandFunction(
if (args.count() != 1) {
evalError(fL1S("shadowed(path) requires one argument."));
} else {
- QString val = resolvePath(args.at(0).toQString(m_tmp1));
- QString rstr;
- if (m_option->source_root.isEmpty()) {
- rstr = val;
- } else if (val.startsWith(m_option->source_root)
- && (val.length() == m_option->source_root.length()
- || val.at(m_option->source_root.length()) == QLatin1Char('/'))) {
- rstr = m_option->build_root + val.mid(m_option->source_root.length());
- } else {
+ QString rstr = m_option->shadowedPath(resolvePath(args.at(0).toQString(m_tmp1)));
+ if (rstr.isEmpty())
break;
- }
ret << (rstr.isSharedWith(m_tmp1) ? args.at(0) : ProString(rstr).setSource(args.at(0)));
}
break;
@@ -1044,19 +1031,12 @@ ProStringList QMakeEvaluator::evaluateExpandFunction(
return ret;
}
-QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
- const ProKey &function, const ushort *&tokPtr)
+QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBuiltinConditional(
+ const ProKey &function, const ProStringList &args)
{
- QHash<ProKey, ProFunctionDef>::ConstIterator it =
- m_functionDefs.testFunctions.constFind(function);
- if (it != m_functionDefs.testFunctions.constEnd())
- return evaluateBoolFunction(*it, prepareFunctionArgs(tokPtr), function);
+ traceMsg("calling built-in %s(%s)", dbgKey(function), dbgSepStrList(args));
TestFunc func_t = (TestFunc)statics.functions.value(function);
-
- //why don't the builtin functions just use args_list? --Sam
- const ProStringList &args = expandVariableReferences(tokPtr, 5, true);
-
switch (func_t) {
case T_DEFINED: {
if (args.count() < 1 || args.count() > 2) {
@@ -1087,18 +1067,19 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
return ReturnFalse;
}
const ProKey &var = map(args.at(0));
- for (int i = m_valuemapStack.size(); --i > 0; ) {
- ProValueMap::Iterator it = m_valuemapStack[i].find(var);
- if (it != m_valuemapStack.at(i).end()) {
+ for (ProValueMapStack::Iterator vmi = m_valuemapStack.end();
+ --vmi != m_valuemapStack.begin(); ) {
+ ProValueMap::Iterator it = (*vmi).find(var);
+ if (it != (*vmi).end()) {
if (it->constBegin() == statics.fakeValue.constBegin()) {
// This is stupid, but qmake doesn't propagate deletions
- m_valuemapStack[0][var] = ProStringList();
+ m_valuemapStack.first()[var] = ProStringList();
} else {
- m_valuemapStack[0][var] = *it;
+ m_valuemapStack.first()[var] = *it;
}
- m_valuemapStack[i].erase(it);
- while (--i)
- m_valuemapStack[i].remove(var);
+ (*vmi).erase(it);
+ while (--vmi != m_valuemapStack.begin())
+ (*vmi).remove(var);
break;
}
}
@@ -1111,7 +1092,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
ProValueMap vars;
QString fn = resolvePath(m_option->expandEnvVars(args.at(0).toQString(m_tmp1)));
fn.detach();
- if (!evaluateFileInto(fn, QMakeHandler::EvalAuxFile, &vars, LoadProOnly))
+ if (!evaluateFileInto(fn, &vars, LoadProOnly))
return ReturnFalse;
if (args.count() == 2)
return returnBool(vars.contains(map(args.at(1))));
@@ -1137,8 +1118,8 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
#endif
case T_EVAL: {
VisitReturn ret = ReturnFalse;
- ProFile *pro = m_parser->parsedProBlock(fL1S("(eval)"),
- args.join(statics.field_sep));
+ ProFile *pro = m_parser->parsedProBlock(args.join(statics.field_sep),
+ m_current.pro->fileName(), m_current.line);
if (pro) {
if (m_cumulative || pro->isOk()) {
m_locationStack.push(m_current);
@@ -1155,7 +1136,8 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
evalError(fL1S("if(condition) requires one argument."));
return ReturnFalse;
}
- return returnBool(evaluateConditional(args.at(0).toQString(), fL1S("(if)")));
+ return returnBool(evaluateConditional(args.at(0).toQString(),
+ m_current.pro->fileName(), m_current.line));
}
case T_CONFIG: {
if (args.count() < 1 || args.count() > 2) {
@@ -1169,9 +1151,8 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
for (int i = configs.size() - 1; i >= 0; i--) {
for (int mut = 0; mut < mutuals.count(); mut++) {
- if (configs[i] == mutuals[mut].trimmed()) {
+ if (configs[i] == mutuals[mut].trimmed())
return returnBool(configs[i] == args[0]);
- }
}
}
return ReturnFalse;
@@ -1323,10 +1304,10 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
fn.detach();
bool ok;
if (parseInto.isEmpty()) {
- ok = evaluateFile(fn, QMakeHandler::EvalIncludeFile, LoadProOnly | flags);
+ ok = evaluateFileChecked(fn, QMakeHandler::EvalIncludeFile, LoadProOnly | flags);
} else {
ProValueMap symbols;
- if ((ok = evaluateFileInto(fn, QMakeHandler::EvalAuxFile, &symbols, LoadAll | flags))) {
+ if ((ok = evaluateFileInto(fn, &symbols, LoadAll | flags))) {
ProValueMap newMap;
for (ProValueMap::ConstIterator
it = m_valuemapStack.top().constBegin(),
@@ -1360,9 +1341,20 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
return returnBool(evaluateFeatureFile(m_option->expandEnvVars(args.at(0).toQString()),
ignore_error) || ignore_error);
}
- case T_DEBUG:
- // Yup - do nothing. Nothing is going to enable debug output anyway.
- return ReturnFalse;
+ case T_DEBUG: {
+#ifdef PROEVALUATOR_DEBUG
+ if (args.count() != 2) {
+ evalError(fL1S("debug(level, message) requires two arguments."));
+ return ReturnFalse;
+ }
+ int level = args.at(0).toInt();
+ if (level <= m_debugLevel) {
+ const QString &msg = m_option->expandEnvVars(args.at(1).toQString(m_tmp2));
+ debugMsg(level, "Project DEBUG: %s", qPrintable(msg));
+ }
+#endif
+ return ReturnTrue;
+ }
case T_LOG:
case T_ERROR:
case T_WARNING:
@@ -1400,7 +1392,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
return returnBool(proc.exitStatus() == QProcess::NormalExit && proc.exitCode() == 0);
#else
return returnBool(system((QLatin1String("cd ")
- + IoUtils::shellQuote(currentDirectory())
+ + IoUtils::shellQuote(QDir::toNativeSeparators(currentDirectory()))
+ QLatin1String(" && ") + args.at(0)).toLocal8Bit().constData()) == 0);
#endif
}
@@ -1419,9 +1411,8 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
}
const QString &file = resolvePath(m_option->expandEnvVars(args.at(0).toQString(m_tmp1)));
- if (IoUtils::exists(file)) {
+ if (IoUtils::exists(file))
return ReturnTrue;
- }
int slsh = file.lastIndexOf(QLatin1Char('/'));
QString fn = file.mid(slsh+1);
if (fn.contains(QLatin1Char('*')) || fn.contains(QLatin1Char('?'))) {
diff --git a/src/shared/proparser/qmakeevaluator.cpp b/src/shared/proparser/qmakeevaluator.cpp
index e0fc60736c..04a2f0f71b 100644
--- a/src/shared/proparser/qmakeevaluator.cpp
+++ b/src/shared/proparser/qmakeevaluator.cpp
@@ -34,20 +34,20 @@
#include "qmakeevaluator_p.h"
#include "ioutils.h"
-#include <QByteArray>
-#include <QDateTime>
-#include <QDebug>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QList>
-#include <QRegExp>
-#include <QSet>
-#include <QStack>
-#include <QString>
-#include <QStringList>
+#include <qbytearray.h>
+#include <qdatetime.h>
+#include <qdebug.h>
+#include <qdir.h>
+#include <qfile.h>
+#include <qfileinfo.h>
+#include <qlist.h>
+#include <qregexp.h>
+#include <qset.h>
+#include <qstack.h>
+#include <qstring.h>
+#include <qstringlist.h>
#ifdef PROEVALUATOR_THREAD_SAFE
-# include <QThreadPool>
+# include <qthreadpool.h>
#endif
#ifdef Q_OS_UNIX
@@ -59,7 +59,7 @@
#include <stdio.h>
#include <stdlib.h>
-using namespace ProFileEvaluatorInternal;
+using namespace QMakeInternal;
QT_BEGIN_NAMESPACE
@@ -94,7 +94,7 @@ QMakeBaseEnv::~QMakeBaseEnv()
delete evaluator;
}
-namespace ProFileEvaluatorInternal {
+namespace QMakeInternal {
QMakeStatics statics;
}
@@ -163,7 +163,11 @@ const ProKey &QMakeEvaluator::map(const ProKey &var)
QMakeEvaluator::QMakeEvaluator(QMakeGlobals *option,
QMakeParser *parser, QMakeHandler *handler)
- : m_option(option), m_parser(parser), m_handler(handler)
+ :
+#ifdef PROEVALUATOR_DEBUG
+ m_debugLevel(option->debugLevel),
+#endif
+ m_option(option), m_parser(parser), m_handler(handler)
{
// So that single-threaded apps don't have to call initialize() for now.
initStatics();
@@ -398,40 +402,56 @@ static ALWAYS_INLINE void addStrList(
void QMakeEvaluator::evaluateExpression(
const ushort *&tokPtr, ProStringList *ret, bool joined)
{
+ debugMsg(2, joined ? "evaluating joined expression" : "evaluating expression");
if (joined)
*ret << ProString();
bool pending = false;
forever {
ushort tok = *tokPtr++;
- if (tok & TokNewStr)
+ if (tok & TokNewStr) {
+ debugMsg(2, "new string");
pending = false;
+ }
ushort maskedTok = tok & TokMask;
switch (maskedTok) {
case TokLine:
m_current.line = *tokPtr++;
break;
- case TokLiteral:
- addStr(getStr(tokPtr), ret, pending, joined);
- break;
- case TokHashLiteral:
- addStr(getHashStr(tokPtr), ret, pending, joined);
- break;
- case TokVariable:
- addStrList(values(map(getHashStr(tokPtr))), tok, ret, pending, joined);
- break;
- case TokProperty:
- addStr(propertyValue(getHashStr(tokPtr)).setSource(currentProFile()),
- ret, pending, joined);
- break;
- case TokEnvVar:
- addStrList(split_value_list(m_option->getEnv(getStr(tokPtr).toQString(m_tmp1))),
- tok, ret, pending, joined);
- break;
+ case TokLiteral: {
+ const ProString &val = getStr(tokPtr);
+ debugMsg(2, "literal %s", dbgStr(val));
+ addStr(val, ret, pending, joined);
+ break; }
+ case TokHashLiteral: {
+ const ProKey &val = getHashStr(tokPtr);
+ debugMsg(2, "hashed literal %s", dbgStr(val.toString()));
+ addStr(val, ret, pending, joined);
+ break; }
+ case TokVariable: {
+ const ProKey &var = getHashStr(tokPtr);
+ const ProStringList &val = values(map(var));
+ debugMsg(2, "variable %s => %s", dbgKey(var), dbgStrList(val));
+ addStrList(val, tok, ret, pending, joined);
+ break; }
+ case TokProperty: {
+ const ProKey &var = getHashStr(tokPtr);
+ const ProString &val = propertyValue(var);
+ debugMsg(2, "property %s => %s", dbgKey(var), dbgStr(val));
+ addStr(val, ret, pending, joined);
+ break; }
+ case TokEnvVar: {
+ const ProString &var = getStr(tokPtr);
+ const ProStringList &val = split_value_list(m_option->getEnv(var.toQString(m_tmp1)));
+ debugMsg(2, "env var %s => %s", dbgStr(var), dbgStrList(val));
+ addStrList(val, tok, ret, pending, joined);
+ break; }
case TokFuncName: {
const ProKey &func = getHashStr(tokPtr);
+ debugMsg(2, "function %s", dbgKey(func));
addStrList(evaluateExpandFunction(func, tokPtr), tok, ret, pending, joined);
break; }
default:
+ debugMsg(2, "evaluated expression => %s", dbgStrList(*ret));
tokPtr--;
return;
}
@@ -489,6 +509,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
const ushort *tokPtr)
{
+ traceMsg("entering block");
ProStringList curr;
bool okey = true, or_op = false, invert = false;
uint blockLen;
@@ -525,12 +546,18 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
m_skipLevel--;
#endif
} else {
- if (okey)
+ if (okey) {
+ traceMsg("taking 'then' branch");
ret = blockLen ? visitProBlock(tokPtr) : ReturnTrue;
+ traceMsg("finished 'then' branch");
+ }
tokPtr += blockLen;
blockLen = getBlockLen(tokPtr);
- if (!okey)
+ if (!okey) {
+ traceMsg("taking 'else' branch");
ret = blockLen ? visitProBlock(tokPtr) : ReturnTrue;
+ traceMsg("finished 'else' branch");
+ }
}
tokPtr += blockLen;
okey = true, or_op = false; // force next evaluation
@@ -554,6 +581,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
uint exprLen = getBlockLen(tokPtr);
tokPtr += exprLen;
blockLen = getBlockLen(tokPtr);
+ traceMsg("skipped loop");
ret = ReturnTrue;
}
tokPtr += blockLen;
@@ -565,7 +593,10 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
const ProKey &name = getHashStr(tokPtr);
blockLen = getBlockLen(tokPtr);
visitProFunctionDef(tok, name, tokPtr);
+ traceMsg("defined %s function %s",
+ tok == TokTestDef ? "test" : "replace", dbgKey(name));
} else {
+ traceMsg("skipped function definition");
skipHashStr(tokPtr);
blockLen = getBlockLen(tokPtr);
}
@@ -573,12 +604,15 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
okey = true, or_op = false; // force next evaluation
continue;
case TokNot:
+ traceMsg("NOT");
invert ^= true;
continue;
case TokAnd:
+ traceMsg("AND");
or_op = false;
continue;
case TokOr:
+ traceMsg("OR");
or_op = true;
continue;
case TokCondition:
@@ -588,8 +622,12 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
evalError(fL1S("Conditional must expand to exactly one word."));
okey = false;
} else {
- okey = isActiveConfig(curr.at(0).toQString(m_tmp2), true) ^ invert;
+ okey = isActiveConfig(curr.at(0).toQString(m_tmp2), true);
+ traceMsg("condition %s is %s", dbgStr(curr.at(0)), dbgBool(okey));
+ okey ^= invert;
}
+ } else {
+ traceMsg("skipped condition %s", curr.size() == 1 ? dbgStr(curr.at(0)) : "<invalid>");
}
or_op = !okey; // tentatively force next evaluation
invert = false;
@@ -603,12 +641,16 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
skipExpression(tokPtr);
okey = false;
} else {
+ traceMsg("evaluating test function %s", dbgStr(curr.at(0)));
ret = evaluateConditionalFunction(curr.at(0).toKey(), tokPtr);
switch (ret) {
case ReturnTrue: okey = true; break;
case ReturnFalse: okey = false; break;
- default: return ret;
+ default:
+ traceMsg("aborting block, function status: %s", dbgReturn(ret));
+ return ret;
}
+ traceMsg("test function returned %s", dbgBool(okey));
okey ^= invert;
}
} else if (m_cumulative) {
@@ -622,6 +664,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
#endif
} else {
skipExpression(tokPtr);
+ traceMsg("skipped test function %s", curr.size() == 1 ? dbgStr(curr.at(0)) : "<invalid>");
}
or_op = !okey; // tentatively force next evaluation
invert = false;
@@ -638,8 +681,11 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
case TokNext:
ret = ReturnNext;
ctrlstm:
- if (!m_skipLevel && okey != or_op)
+ if (!m_skipLevel && okey != or_op) {
+ traceMsg("flow control statement '%s', aborting block", dbgReturn(ret));
return ret;
+ }
+ traceMsg("skipped flow control statement '%s'", dbgReturn(ret));
okey = false, or_op = true; // force next evaluation
continue;
default: {
@@ -651,9 +697,12 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProBlock(
Q_ASSERT_X(false, "visitProBlock", "unexpected item type");
continue;
}
- if (ret != ReturnTrue && ret != ReturnFalse)
+ if (ret != ReturnTrue && ret != ReturnFalse) {
+ traceMsg("aborting block, status: %s", dbgReturn(ret));
return ret;
+ }
}
+ traceMsg("leaving block, okey=%s", dbgBool(okey));
return returnBool(okey);
}
@@ -713,6 +762,11 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProLoop(
}
}
+ if (infinite)
+ traceMsg("entering infinite loop for %s", dbgKey(variable));
+ else
+ traceMsg("entering loop for %s over %s", dbgKey(variable), dbgStrList(list));
+
forever {
if (infinite) {
if (!variable.isEmpty())
@@ -721,6 +775,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProLoop(
evalError(fL1S("Ran into infinite loop (> 1000 iterations)."));
break;
}
+ traceMsg("loop iteration %d", index);
} else {
ProString val;
do {
@@ -728,6 +783,7 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProLoop(
goto do_break;
val = list.at(index++);
} while (val.isEmpty()); // stupid, but qmake is like that
+ traceMsg("loop iteration %s", dbgStr(val));
m_valuemapStack.top()[variable] = ProStringList(val);
}
@@ -748,6 +804,8 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProLoop(
}
do_break:
+ traceMsg("done looping");
+
if (!variable.isEmpty())
m_valuemapStack.top()[variable] = oldVarVal;
return ret;
@@ -798,6 +856,7 @@ void QMakeEvaluator::visitProVariable(
// We could make a union of modified and unmodified values,
// but this will break just as much as it fixes, so leave it as is.
replaceInList(&valuesRef(varName), regexp, replace, global, m_tmp2);
+ debugMsg(2, "replaced %s with %s", dbgQStr(pattern), dbgQStr(replace));
} else {
ProStringList varVal = expandVariableReferences(tokPtr, sizeHint);
switch (tok) {
@@ -828,13 +887,16 @@ void QMakeEvaluator::visitProVariable(
}
}
}
+ debugMsg(2, "assigning");
break;
case TokAppendUnique: // *=
insertUnique(&valuesRef(varName), varVal);
+ debugMsg(2, "appending unique");
break;
case TokAppend: // +=
zipEmpty(&varVal);
valuesRef(varName) += varVal;
+ debugMsg(2, "appending");
break;
case TokRemove: // -=
if (!m_cumulative) {
@@ -842,9 +904,11 @@ void QMakeEvaluator::visitProVariable(
} else {
// We are stingy with our values, too.
}
+ debugMsg(2, "removing");
break;
}
}
+ traceMsg("%s := %s", dbgKey(varName), dbgStrList(values(varName)));
if (varName == statics.strTEMPLATE)
setTemplate();
@@ -1047,7 +1111,7 @@ bool QMakeEvaluator::loadSpecInternal()
if (!evaluateFeatureFile(QLatin1String("spec_pre.prf")))
return false;
QString spec = m_qmakespec + QLatin1String("/qmake.conf");
- if (!evaluateFileDirect(spec, QMakeHandler::EvalConfigFile, LoadProOnly)) {
+ if (!evaluateFile(spec, QMakeHandler::EvalConfigFile, LoadProOnly)) {
evalError(fL1S("Could not read qmake configuration file %1.").arg(spec));
return false;
}
@@ -1087,17 +1151,17 @@ bool QMakeEvaluator::loadSpec()
QMakeEvaluator evaluator(m_option, m_parser, m_handler);
if (!m_superfile.isEmpty()) {
valuesRef(ProKey("_QMAKE_SUPER_CACHE_")) << ProString(m_superfile);
- if (!evaluator.evaluateFileDirect(m_superfile, QMakeHandler::EvalConfigFile, LoadProOnly))
+ if (!evaluator.evaluateFile(m_superfile, QMakeHandler::EvalConfigFile, LoadProOnly))
return false;
}
if (!m_conffile.isEmpty()) {
valuesRef(ProKey("_QMAKE_CONF_")) << ProString(m_conffile);
- if (!evaluator.evaluateFileDirect(m_conffile, QMakeHandler::EvalConfigFile, LoadProOnly))
+ if (!evaluator.evaluateFile(m_conffile, QMakeHandler::EvalConfigFile, LoadProOnly))
return false;
}
if (!m_cachefile.isEmpty()) {
valuesRef(ProKey("_QMAKE_CACHE_")) << ProString(m_cachefile);
- if (!evaluator.evaluateFileDirect(m_cachefile, QMakeHandler::EvalConfigFile, LoadProOnly))
+ if (!evaluator.evaluateFile(m_cachefile, QMakeHandler::EvalConfigFile, LoadProOnly))
return false;
}
if (qmakespec.isEmpty()) {
@@ -1133,18 +1197,18 @@ bool QMakeEvaluator::loadSpec()
m_qmakespec = QDir::cleanPath(qmakespec);
if (!m_superfile.isEmpty()
- && !evaluateFileDirect(m_superfile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
+ && !evaluateFile(m_superfile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
return false;
}
if (!loadSpecInternal())
return false;
updateFeaturePaths(); // The spec extends the feature search path, so rebuild the cache.
if (!m_conffile.isEmpty()
- && !evaluateFileDirect(m_conffile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
+ && !evaluateFile(m_conffile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
return false;
}
if (!m_cachefile.isEmpty()
- && !evaluateFileDirect(m_cachefile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
+ && !evaluateFile(m_cachefile, QMakeHandler::EvalConfigFile, LoadProOnly)) {
return false;
}
return true;
@@ -1161,10 +1225,10 @@ void QMakeEvaluator::setupProject()
vars[ProKey("OUT_PWD")] << ProString(m_outputDir).setSource(proFile);
}
-void QMakeEvaluator::visitCmdLine(const QString &cmds)
+void QMakeEvaluator::evaluateCommand(const QString &cmds, const QString &where)
{
if (!cmds.isEmpty()) {
- if (ProFile *pro = m_parser->parsedProBlock(fL1S("(command line)"), cmds)) {
+ if (ProFile *pro = m_parser->parsedProBlock(cmds, where, -1)) {
if (pro->isOk()) {
m_locationStack.push(m_current);
visitProBlock(pro, pro->tokPtr());
@@ -1175,6 +1239,28 @@ void QMakeEvaluator::visitCmdLine(const QString &cmds)
}
}
+void QMakeEvaluator::evaluateConfigFeatures()
+{
+ QSet<QString> processed;
+ forever {
+ bool finished = true;
+ ProStringList configs = values(statics.strCONFIG);
+ for (int i = configs.size() - 1; i >= 0; --i) {
+ QString config = configs.at(i).toQString(m_tmp1).toLower();
+ if (!processed.contains(config)) {
+ config.detach();
+ processed.insert(config);
+ if (evaluateFeatureFile(config, true)) {
+ finished = false;
+ break;
+ }
+ }
+ }
+ if (finished)
+ break;
+ }
+}
+
QMakeEvaluator::VisitReturn QMakeEvaluator::visitProFile(
ProFile *pro, QMakeHandler::EvalFileType type, LoadFlags flags)
{
@@ -1243,6 +1329,10 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProFile(
loadDefaults();
}
+ for (ProValueMap::ConstIterator it = m_extraVars.constBegin();
+ it != m_extraVars.constEnd(); ++it)
+ m_valuemapStack.first().insert(it.key(), it.value());
+
m_handler->aboutToEval(currentProFile(), pro, type);
m_profileStack.push(pro);
valuesRef(ProKey("PWD")) = ProStringList(ProString(currentDirectory()));
@@ -1251,34 +1341,29 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::visitProFile(
evaluateFeatureFile(QLatin1String("default_pre.prf"));
- visitCmdLine(m_option->precmds);
+ evaluateCommand(m_option->precmds, fL1S("(command line)"));
+
+ // After user configs, to override them
+ if (!m_extraConfigs.isEmpty())
+ evaluateCommand(fL1S("CONFIG += ") + m_extraConfigs.join(fL1S(" ")), fL1S("(extra configs)"));
}
+ debugMsg(1, "visiting file %s", qPrintable(pro->fileName()));
visitProBlock(pro, pro->tokPtr());
+ debugMsg(1, "done visiting file %s", qPrintable(pro->fileName()));
if (flags & LoadPostFiles) {
- visitCmdLine(m_option->postcmds);
+ evaluateCommand(m_option->postcmds, fL1S("(command line -after)"));
+
+ // Again, to ensure the project does not mess with us.
+ // Specifically, do not allow a project to override debug/release within a
+ // debug_and_release build pass - it's too late for that at this point anyway.
+ if (!m_extraConfigs.isEmpty())
+ evaluateCommand(fL1S("CONFIG += ") + m_extraConfigs.join(fL1S(" ")), fL1S("(extra configs)"));
evaluateFeatureFile(QLatin1String("default_post.prf"));
- QSet<QString> processed;
- forever {
- bool finished = true;
- ProStringList configs = values(statics.strCONFIG);
- for (int i = configs.size() - 1; i >= 0; --i) {
- QString config = configs.at(i).toQString(m_tmp1).toLower();
- if (!processed.contains(config)) {
- config.detach();
- processed.insert(config);
- if (evaluateFeatureFile(config, true)) {
- finished = false;
- break;
- }
- }
- }
- if (finished)
- break;
- }
+ evaluateConfigFeatures();
}
m_profileStack.pop();
valuesRef(ProKey("PWD")) = ProStringList(ProString(currentDirectory()));
@@ -1550,10 +1635,40 @@ QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateBoolFunction(
return ReturnFalse;
}
-bool QMakeEvaluator::evaluateConditional(const QString &cond, const QString &context)
+QMakeEvaluator::VisitReturn QMakeEvaluator::evaluateConditionalFunction(
+ const ProKey &func, const ushort *&tokPtr)
+{
+ QHash<ProKey, ProFunctionDef>::ConstIterator it =
+ m_functionDefs.testFunctions.constFind(func);
+ if (it != m_functionDefs.testFunctions.constEnd()) {
+ const QList<ProStringList> args = prepareFunctionArgs(tokPtr);
+ traceMsg("calling %s(%s)", dbgKey(func), dbgStrListList(args));
+ return evaluateBoolFunction(*it, args, func);
+ }
+
+ //why don't the builtin functions just use args_list? --Sam
+ return evaluateBuiltinConditional(func, expandVariableReferences(tokPtr, 5, true));
+}
+
+ProStringList QMakeEvaluator::evaluateExpandFunction(
+ const ProKey &func, const ushort *&tokPtr)
+{
+ QHash<ProKey, ProFunctionDef>::ConstIterator it =
+ m_functionDefs.replaceFunctions.constFind(func);
+ if (it != m_functionDefs.replaceFunctions.constEnd()) {
+ const QList<ProStringList> args = prepareFunctionArgs(tokPtr);
+ traceMsg("calling $$%s(%s)", dbgKey(func), dbgStrListList(args));
+ return evaluateFunction(*it, args, 0);
+ }
+
+ //why don't the builtin functions just use args_list? --Sam
+ return evaluateBuiltinExpand(func, expandVariableReferences(tokPtr, 5, true));
+}
+
+bool QMakeEvaluator::evaluateConditional(const QString &cond, const QString &where, int line)
{
bool ret = false;
- ProFile *pro = m_parser->parsedProBlock(context, cond, QMakeParser::TestGrammar);
+ ProFile *pro = m_parser->parsedProBlock(cond, where, line, QMakeParser::TestGrammar);
if (pro) {
if (pro->isOk()) {
m_locationStack.push(m_current);
@@ -1570,22 +1685,24 @@ void QMakeEvaluator::checkRequirements(const ProStringList &deps)
{
ProStringList &failed = valuesRef(ProKey("QMAKE_FAILED_REQUIREMENTS"));
foreach (const ProString &dep, deps)
- if (!evaluateConditional(dep.toQString(), fL1S("(requires)")))
+ if (!evaluateConditional(dep.toQString(), m_current.pro->fileName(), m_current.line))
failed << dep;
}
#endif
ProValueMap *QMakeEvaluator::findValues(const ProKey &variableName, ProValueMap::Iterator *rit)
{
- for (int i = m_valuemapStack.size(); --i >= 0; ) {
- ProValueMap::Iterator it = m_valuemapStack[i].find(variableName);
- if (it != m_valuemapStack[i].end()) {
+ ProValueMapStack::Iterator vmi = m_valuemapStack.end();
+ do {
+ --vmi;
+ ProValueMap::Iterator it = (*vmi).find(variableName);
+ if (it != (*vmi).end()) {
if (it->constBegin() == statics.fakeValue.constBegin())
return 0;
*rit = it;
- return &m_valuemapStack[i];
+ return &(*vmi);
}
- }
+ } while (vmi != m_valuemapStack.begin());
return 0;
}
@@ -1597,28 +1714,34 @@ ProStringList &QMakeEvaluator::valuesRef(const ProKey &variableName)
it->clear();
return *it;
}
- for (int i = m_valuemapStack.size() - 1; --i >= 0; ) {
- ProValueMap::ConstIterator it = m_valuemapStack.at(i).constFind(variableName);
- if (it != m_valuemapStack.at(i).constEnd()) {
- ProStringList &ret = m_valuemapStack.top()[variableName];
- if (it->constBegin() != statics.fakeValue.constBegin())
- ret = *it;
- return ret;
- }
+ ProValueMapStack::Iterator vmi = m_valuemapStack.end();
+ if (--vmi != m_valuemapStack.begin()) {
+ do {
+ --vmi;
+ ProValueMap::ConstIterator it = (*vmi).constFind(variableName);
+ if (it != (*vmi).constEnd()) {
+ ProStringList &ret = m_valuemapStack.top()[variableName];
+ if (it->constBegin() != statics.fakeValue.constBegin())
+ ret = *it;
+ return ret;
+ }
+ } while (vmi != m_valuemapStack.begin());
}
return m_valuemapStack.top()[variableName];
}
ProStringList QMakeEvaluator::values(const ProKey &variableName) const
{
- for (int i = m_valuemapStack.size(); --i >= 0; ) {
- ProValueMap::ConstIterator it = m_valuemapStack.at(i).constFind(variableName);
- if (it != m_valuemapStack.at(i).constEnd()) {
+ ProValueMapStack::ConstIterator vmi = m_valuemapStack.constEnd();
+ do {
+ --vmi;
+ ProValueMap::ConstIterator it = (*vmi).constFind(variableName);
+ if (it != (*vmi).constEnd()) {
if (it->constBegin() == statics.fakeValue.constBegin())
break;
return *it;
}
- }
+ } while (vmi != m_valuemapStack.constBegin());
return ProStringList();
}
@@ -1630,7 +1753,7 @@ ProString QMakeEvaluator::first(const ProKey &variableName) const
return ProString();
}
-bool QMakeEvaluator::evaluateFileDirect(
+bool QMakeEvaluator::evaluateFile(
const QString &fileName, QMakeHandler::EvalFileType type, LoadFlags flags)
{
if (ProFile *pro = m_parser->parsedProFile(fileName, true)) {
@@ -1648,13 +1771,13 @@ bool QMakeEvaluator::evaluateFileDirect(
#endif
return ok;
} else {
- if (!(flags & LoadSilent) && IoUtils::exists(fileName))
- languageWarning(fL1S("Include file %1 not found").arg(fileName));
+ if (!(flags & LoadSilent) && !IoUtils::exists(fileName))
+ evalError(fL1S("WARNING: Include file %1 not found").arg(fileName));
return false;
}
}
-bool QMakeEvaluator::evaluateFile(
+bool QMakeEvaluator::evaluateFileChecked(
const QString &fileName, QMakeHandler::EvalFileType type, LoadFlags flags)
{
if (fileName.isEmpty())
@@ -1667,7 +1790,7 @@ bool QMakeEvaluator::evaluateFile(
return false;
}
} while ((ref = ref->m_caller));
- return evaluateFileDirect(fileName, type, flags);
+ return evaluateFile(fileName, type, flags);
}
bool QMakeEvaluator::evaluateFeatureFile(const QString &fileName, bool silent)
@@ -1700,7 +1823,7 @@ bool QMakeEvaluator::evaluateFeatureFile(const QString &fileName, bool silent)
goto cool;
#endif
if (!silent)
- languageWarning(fL1S("Cannot find feature %1").arg(fileName));
+ evalError(fL1S("Cannot find feature %1").arg(fileName));
return false;
cool:
@@ -1719,7 +1842,7 @@ bool QMakeEvaluator::evaluateFeatureFile(const QString &fileName, bool silent)
#endif
// The path is fully normalized already.
- bool ok = evaluateFileDirect(fn, QMakeHandler::EvalFeatureFile, LoadProOnly);
+ bool ok = evaluateFile(fn, QMakeHandler::EvalFeatureFile, LoadProOnly);
#ifdef PROEVALUATOR_CUMULATIVE
m_cumulative = cumulative;
@@ -1727,14 +1850,13 @@ bool QMakeEvaluator::evaluateFeatureFile(const QString &fileName, bool silent)
return ok;
}
-bool QMakeEvaluator::evaluateFileInto(const QString &fileName, QMakeHandler::EvalFileType type,
- ProValueMap *values, LoadFlags flags)
+bool QMakeEvaluator::evaluateFileInto(const QString &fileName, ProValueMap *values, LoadFlags flags)
{
QMakeEvaluator visitor(m_option, m_parser, m_handler);
visitor.m_caller = this;
visitor.m_outputDir = m_outputDir;
visitor.m_featureRoots = m_featureRoots;
- if (!visitor.evaluateFile(fileName, type, flags))
+ if (!visitor.evaluateFileChecked(fileName, QMakeHandler::EvalAuxFile, flags))
return false;
*values = visitor.m_valuemapStack.top();
#ifdef PROEVALUATOR_FULL
@@ -1751,7 +1873,117 @@ void QMakeEvaluator::message(int type, const QString &msg) const
{
if (!m_skipLevel)
m_handler->message(type, msg,
- m_current.line ? m_current.pro->fileName() : QString(), m_current.line);
+ m_current.line ? m_current.pro->fileName() : QString(),
+ m_current.line != 0xffff ? m_current.line : -1);
+}
+
+#ifdef PROEVALUATOR_DEBUG
+void QMakeEvaluator::debugMsgInternal(int level, const char *fmt, ...) const
+{
+ va_list ap;
+
+ if (level <= m_debugLevel) {
+ fprintf(stderr, "DEBUG %d: ", level);
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fputc('\n', stderr);
+ }
+}
+
+void QMakeEvaluator::traceMsgInternal(const char *fmt, ...) const
+{
+ va_list ap;
+
+ if (!m_current.pro)
+ fprintf(stderr, "DEBUG 1: ");
+ else if (m_current.line <= 0)
+ fprintf(stderr, "DEBUG 1: %s: ", qPrintable(m_current.pro->fileName()));
+ else
+ fprintf(stderr, "DEBUG 1: %s:%d: ", qPrintable(m_current.pro->fileName()), m_current.line);
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+ fputc('\n', stderr);
+}
+
+QString QMakeEvaluator::formatValue(const ProString &val, bool forceQuote)
+{
+ QString ret;
+ ret.reserve(val.size() + 2);
+ const QChar *chars = val.constData();
+ bool quote = forceQuote || val.isEmpty();
+ for (int i = 0, l = val.size(); i < l; i++) {
+ QChar c = chars[i];
+ ushort uc = c.unicode();
+ if (uc < 32) {
+ switch (uc) {
+ case '\r':
+ ret += QLatin1String("\\r");
+ break;
+ case '\n':
+ ret += QLatin1String("\\n");
+ break;
+ case '\t':
+ ret += QLatin1String("\\t");
+ break;
+ default:
+ ret += QString::fromLatin1("\\x%1").arg(uc, 2, 16, QLatin1Char('0'));
+ break;
+ }
+ } else {
+ switch (uc) {
+ case '\\':
+ ret += QLatin1String("\\\\");
+ break;
+ case '"':
+ ret += QLatin1String("\\\"");
+ break;
+ case '\'':
+ ret += QLatin1String("\\'");
+ break;
+ case 32:
+ quote = true;
+ // fallthrough
+ default:
+ ret += c;
+ break;
+ }
+ }
+ }
+ if (quote) {
+ ret.prepend(QLatin1Char('"'));
+ ret.append(QLatin1Char('"'));
+ }
+ return ret;
+}
+
+QString QMakeEvaluator::formatValueList(const ProStringList &vals, bool commas)
+{
+ QString ret;
+
+ foreach (const ProString &str, vals) {
+ if (!ret.isEmpty()) {
+ if (commas)
+ ret += QLatin1Char(',');
+ ret += QLatin1Char(' ');
+ }
+ ret += formatValue(str);
+ }
+ return ret;
}
+QString QMakeEvaluator::formatValueListList(const QList<ProStringList> &lists)
+{
+ QString ret;
+
+ foreach (const ProStringList &list, lists) {
+ if (!ret.isEmpty())
+ ret += QLatin1String(", ");
+ ret += formatValueList(list);
+ }
+ return ret;
+}
+#endif
+
QT_END_NAMESPACE
diff --git a/src/shared/proparser/qmakeevaluator.h b/src/shared/proparser/qmakeevaluator.h
index be55b0dbba..c8c199f7bb 100644
--- a/src/shared/proparser/qmakeevaluator.h
+++ b/src/shared/proparser/qmakeevaluator.h
@@ -37,13 +37,14 @@
#include "qmakeparser.h"
#include "ioutils.h"
-#include <QList>
-#include <QSet>
-#include <QStack>
-#include <QString>
-#include <QStringList>
+#include <qlist.h>
+#include <qlinkedlist.h>
+#include <qset.h>
+#include <qstack.h>
+#include <qstring.h>
+#include <qstringlist.h>
#ifndef QT_BOOTSTRAPPED
-# include <QProcess>
+# include <qprocess.h>
#endif
QT_BEGIN_NAMESPACE
@@ -70,6 +71,17 @@ public:
virtual void doneWithEval(ProFile *parent) = 0;
};
+// We use a QLinkedList based stack instead of a QVector based one (QStack), so that
+// the addresses of value maps stay constant. The qmake generators rely on that.
+class QMAKE_EXPORT ProValueMapStack : public QLinkedList<ProValueMap>
+{
+public:
+ inline void push(const ProValueMap &t) { append(t); }
+ inline ProValueMap pop() { return takeLast(); }
+ ProValueMap &top() { return last(); }
+ const ProValueMap &top() const { return last(); }
+};
+
class QMAKE_EXPORT QMakeEvaluator
{
public:
@@ -88,11 +100,18 @@ public:
QMakeHandler *handler);
~QMakeEvaluator();
+ void setExtraVars(const ProValueMap &extraVars) { m_extraVars = extraVars; }
+ void setExtraConfigs(const ProStringList &extraConfigs) { m_extraConfigs = extraConfigs; }
+ void setOutputDir(const QString &outputDir) { m_outputDir = outputDir; }
+
ProStringList values(const ProKey &variableName) const;
ProStringList &valuesRef(const ProKey &variableName);
ProString first(const ProKey &variableName) const;
ProString propertyValue(const ProKey &val) const;
+ ProString dirSep() const { return m_dirSep; }
+ bool isHostBuild() const { return m_hostBuild; }
+
enum VisitReturn {
ReturnFalse,
ReturnTrue,
@@ -119,7 +138,7 @@ public:
bool loadSpec();
void initFrom(const QMakeEvaluator &other);
void setupProject();
- void visitCmdLine(const QString &cmds);
+ void evaluateCommand(const QString &cmds, const QString &where);
VisitReturn visitProFile(ProFile *pro, QMakeHandler::EvalFileType type,
LoadFlags flags);
VisitReturn visitProBlock(ProFile *pro, const ushort *tokPtr);
@@ -143,16 +162,17 @@ public:
QString currentDirectory() const;
ProFile *currentProFile() const;
QString resolvePath(const QString &fileName) const
- { return ProFileEvaluatorInternal::IoUtils::resolvePath(currentDirectory(), fileName); }
+ { return QMakeInternal::IoUtils::resolvePath(currentDirectory(), fileName); }
- bool evaluateFileDirect(const QString &fileName, QMakeHandler::EvalFileType type,
- LoadFlags flags);
bool evaluateFile(const QString &fileName, QMakeHandler::EvalFileType type,
LoadFlags flags);
+ bool evaluateFileChecked(const QString &fileName, QMakeHandler::EvalFileType type,
+ LoadFlags flags);
bool evaluateFeatureFile(const QString &fileName, bool silent = false);
- bool evaluateFileInto(const QString &fileName, QMakeHandler::EvalFileType type,
+ bool evaluateFileInto(const QString &fileName,
ProValueMap *values, // output-only
LoadFlags flags);
+ void evaluateConfigFeatures();
void message(int type, const QString &msg) const;
void evalError(const QString &msg) const
{ message(QMakeHandler::EvalError, msg); }
@@ -171,7 +191,10 @@ public:
ProStringList evaluateExpandFunction(const ProKey &function, const ushort *&tokPtr);
VisitReturn evaluateConditionalFunction(const ProKey &function, const ushort *&tokPtr);
- bool evaluateConditional(const QString &cond, const QString &context);
+ ProStringList evaluateBuiltinExpand(const ProKey &function, const ProStringList &args);
+ VisitReturn evaluateBuiltinConditional(const ProKey &function, const ProStringList &args);
+
+ bool evaluateConditional(const QString &cond, const QString &where, int line = -1);
#ifdef PROEVALUATOR_FULL
void checkRequirements(const ProStringList &deps);
#endif
@@ -204,17 +227,35 @@ public:
enum { m_skipLevel = 0 };
#endif
+#ifdef PROEVALUATOR_DEBUG
+ void debugMsgInternal(int level, const char *fmt, ...) const;
+ void traceMsgInternal(const char *fmt, ...) const;
+ static QString formatValue(const ProString &val, bool forceQuote = false);
+ static QString formatValueList(const ProStringList &vals, bool commas = false);
+ static QString formatValueListList(const QList<ProStringList> &vals);
+
+ const int m_debugLevel;
+#else
+ ALWAYS_INLINE void debugMsgInternal(int, const char *, ...) const {}
+ ALWAYS_INLINE void traceMsgInternal(const char *, ...) const {}
+
+ enum { m_debugLevel = 0 };
+#endif
+
struct Location {
Location() : pro(0), line(0) {}
- Location(ProFile *_pro, int _line) : pro(_pro), line(_line) {}
+ Location(ProFile *_pro, ushort _line) : pro(_pro), line(_line) {}
+ void clear() { pro = 0; line = 0; }
ProFile *pro;
- int line;
+ ushort line;
};
Location m_current; // Currently evaluated location
QStack<Location> m_locationStack; // All execution location changes
QStack<ProFile *> m_profileStack; // Includes only
+ ProValueMap m_extraVars;
+ ProStringList m_extraConfigs;
QString m_outputDir;
int m_listCount;
@@ -234,7 +275,7 @@ public:
ProString m_dirSep;
ProFunctionDefs m_functionDefs;
ProStringList m_returnValue;
- QStack<ProValueMap> m_valuemapStack; // VariableName must be us-ascii, the content however can be non-us-ascii.
+ ProValueMapStack m_valuemapStack; // VariableName must be us-ascii, the content however can be non-us-ascii.
QString m_tmp1, m_tmp2, m_tmp3, m_tmp[2]; // Temporaries for efficient toQString
mutable QString m_mtmp;
diff --git a/src/shared/proparser/qmakeevaluator_p.h b/src/shared/proparser/qmakeevaluator_p.h
index 9db8bfb5c6..49cced3927 100644
--- a/src/shared/proparser/qmakeevaluator_p.h
+++ b/src/shared/proparser/qmakeevaluator_p.h
@@ -32,11 +32,38 @@
#include "proitems.h"
-#include <QRegExp>
+#include <qregexp.h>
+
+#define debugMsg if (!m_debugLevel) {} else debugMsgInternal
+#define traceMsg if (!m_debugLevel) {} else traceMsgInternal
+#ifdef PROEVALUATOR_DEBUG
+# define dbgBool(b) (b ? "true" : "false")
+# define dbgReturn(r) \
+ (r == ReturnError ? "error" : \
+ r == ReturnBreak ? "break" : \
+ r == ReturnNext ? "next" : \
+ r == ReturnReturn ? "return" : \
+ "<invalid>")
+# define dbgKey(s) qPrintable(s.toString().toQString())
+# define dbgStr(s) qPrintable(formatValue(s, true))
+# define dbgStrList(s) qPrintable(formatValueList(s))
+# define dbgSepStrList(s) qPrintable(formatValueList(s, true))
+# define dbgStrListList(s) qPrintable(formatValueListList(s))
+# define dbgQStr(s) dbgStr(ProString(s))
+#else
+# define dbgBool(b) 0
+# define dbgReturn(r) 0
+# define dbgKey(s) 0
+# define dbgStr(s) 0
+# define dbgStrList(s) 0
+# define dbgSepStrList(s) 0
+# define dbgStrListList(s) 0
+# define dbgQStr(s) 0
+#endif
QT_BEGIN_NAMESPACE
-namespace ProFileEvaluatorInternal {
+namespace QMakeInternal {
struct QMakeStatics {
QString field_sep;
diff --git a/src/shared/proparser/qmakeglobals.cpp b/src/shared/proparser/qmakeglobals.cpp
index 01cac4866e..c19d4a0485 100644
--- a/src/shared/proparser/qmakeglobals.cpp
+++ b/src/shared/proparser/qmakeglobals.cpp
@@ -32,21 +32,21 @@
#include "qmakeevaluator.h"
#include "ioutils.h"
-#include <QByteArray>
-#include <QDateTime>
-#include <QDebug>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QList>
-#include <QRegExp>
-#include <QSet>
-#include <QStack>
-#include <QString>
-#include <QStringList>
-#include <QTextStream>
+#include <qbytearray.h>
+#include <qdatetime.h>
+#include <qdebug.h>
+#include <qdir.h>
+#include <qfile.h>
+#include <qfileinfo.h>
+#include <qlist.h>
+#include <qregexp.h>
+#include <qset.h>
+#include <qstack.h>
+#include <qstring.h>
+#include <qstringlist.h>
+#include <qtextstream.h>
#ifdef PROEVALUATOR_THREAD_SAFE
-# include <QThreadPool>
+# include <qthreadpool.h>
#endif
#ifdef Q_OS_UNIX
@@ -93,6 +93,9 @@ QMakeGlobals::QMakeGlobals()
do_cache = true;
+#ifdef PROEVALUATOR_DEBUG
+ debugLevel = 0;
+#endif
#ifdef Q_OS_WIN
dirlist_sep = QLatin1Char(';');
dir_sep = QLatin1Char('\\');
@@ -108,43 +111,119 @@ QMakeGlobals::~QMakeGlobals()
qDeleteAll(baseEnvs);
}
-void QMakeGlobals::setCommandLineArguments(const QStringList &args)
+QString QMakeGlobals::cleanSpec(QMakeCmdLineParserState &state, const QString &spec)
{
- QStringList _precmds, _preconfigs, _postcmds, _postconfigs;
- bool after = false;
+ QString ret = QDir::cleanPath(spec);
+ if (ret.contains(QLatin1Char('/'))) {
+ QString absRet = QDir(state.pwd).absoluteFilePath(ret);
+ if (QFile::exists(absRet))
+ ret = QDir::cleanPath(absRet);
+ }
+ return ret;
+}
- bool isConf = false;
- foreach (const QString &arg, args) {
- if (isConf) {
- isConf = false;
- if (after)
- _postconfigs << arg;
+QMakeGlobals::ArgumentReturn QMakeGlobals::addCommandLineArguments(
+ QMakeCmdLineParserState &state, QStringList &args, int *pos)
+{
+ enum { ArgNone, ArgConfig, ArgSpec, ArgXSpec, ArgTmpl, ArgTmplPfx, ArgCache } argState = ArgNone;
+ for (; *pos < args.count(); (*pos)++) {
+ QString arg = args.at(*pos);
+ switch (argState) {
+ case ArgConfig:
+ if (state.after)
+ state.postconfigs << arg;
else
- _preconfigs << arg;
- } else if (arg.startsWith(QLatin1Char('-'))) {
- if (arg == QLatin1String("-after")) {
- after = true;
- } else if (arg == QLatin1String("-config")) {
- isConf = true;
- } else if (arg == QLatin1String("-win32")) {
- dir_sep = QLatin1Char('\\');
- } else if (arg == QLatin1String("-unix")) {
- dir_sep = QLatin1Char('/');
+ state.preconfigs << arg;
+ break;
+ case ArgSpec:
+ qmakespec = args[*pos] = cleanSpec(state, arg);
+ break;
+ case ArgXSpec:
+ xqmakespec = args[*pos] = cleanSpec(state, arg);
+ break;
+ case ArgTmpl:
+ user_template = arg;
+ break;
+ case ArgTmplPfx:
+ user_template_prefix = arg;
+ break;
+ case ArgCache:
+ cachefile = args[*pos] = QDir::cleanPath(QDir(state.pwd).absoluteFilePath(arg));
+ break;
+ default:
+ if (arg.startsWith(QLatin1Char('-'))) {
+ if (arg == QLatin1String("-after"))
+ state.after = true;
+ else if (arg == QLatin1String("-config"))
+ argState = ArgConfig;
+ else if (arg == QLatin1String("-nocache"))
+ do_cache = false;
+ else if (arg == QLatin1String("-cache"))
+ argState = ArgCache;
+ else if (arg == QLatin1String("-platform") || arg == QLatin1String("-spec"))
+ argState = ArgSpec;
+ else if (arg == QLatin1String("-xplatform") || arg == QLatin1String("-xspec"))
+ argState = ArgXSpec;
+ else if (arg == QLatin1String("-template") || arg == QLatin1String("-t"))
+ argState = ArgTmpl;
+ else if (arg == QLatin1String("-template_prefix") || arg == QLatin1String("-tp"))
+ argState = ArgTmplPfx;
+ else if (arg == QLatin1String("-win32"))
+ dir_sep = QLatin1Char('\\');
+ else if (arg == QLatin1String("-unix"))
+ dir_sep = QLatin1Char('/');
+ else
+ return ArgumentUnknown;
+ } else if (arg.contains(QLatin1Char('='))) {
+ if (state.after)
+ state.postcmds << arg;
+ else
+ state.precmds << arg;
+ } else {
+ return ArgumentUnknown;
}
- } else if (arg.contains(QLatin1Char('='))) {
- if (after)
- _postcmds << arg;
- else
- _precmds << arg;
+ continue;
}
+ argState = ArgNone;
}
+ if (argState != ArgNone)
+ return ArgumentMalformed;
+ return ArgumentsOk;
+}
- if (!_preconfigs.isEmpty())
- _precmds << (fL1S("CONFIG += ") + _preconfigs.join(fL1S(" ")));
- precmds = _precmds.join(fL1S("\n"));
- if (!_postconfigs.isEmpty())
- _postcmds << (fL1S("CONFIG += ") + _postconfigs.join(fL1S(" ")));
- postcmds = _postcmds.join(fL1S("\n"));
+void QMakeGlobals::commitCommandLineArguments(QMakeCmdLineParserState &state)
+{
+ if (!state.preconfigs.isEmpty())
+ state.precmds << (fL1S("CONFIG += ") + state.preconfigs.join(fL1S(" ")));
+ precmds = state.precmds.join(fL1S("\n"));
+ if (!state.postconfigs.isEmpty())
+ state.postcmds << (fL1S("CONFIG += ") + state.postconfigs.join(fL1S(" ")));
+ postcmds = state.postcmds.join(fL1S("\n"));
+
+ if (xqmakespec.isEmpty())
+ xqmakespec = qmakespec;
+}
+
+void QMakeGlobals::useEnvironment()
+{
+ if (xqmakespec.isEmpty())
+ xqmakespec = getEnv(QLatin1String("XQMAKESPEC"));
+ if (qmakespec.isEmpty()) {
+ qmakespec = getEnv(QLatin1String("QMAKESPEC"));
+ if (xqmakespec.isEmpty())
+ xqmakespec = qmakespec;
+ }
+}
+
+void QMakeGlobals::setCommandLineArguments(const QString &pwd, const QStringList &_args)
+{
+ QStringList args = _args;
+
+ QMakeCmdLineParserState state(pwd);
+ for (int pos = 0; pos < args.size(); pos++)
+ addCommandLineArguments(state, args, &pos);
+ commitCommandLineArguments(state);
+ useEnvironment();
}
void QMakeGlobals::setDirectories(const QString &input_dir, const QString &output_dir)
@@ -167,13 +246,25 @@ void QMakeGlobals::setDirectories(const QString &input_dir, const QString &outpu
}
}
+QString QMakeGlobals::shadowedPath(const QString &fileName) const
+{
+ if (source_root.isEmpty())
+ return fileName;
+ if (fileName.startsWith(source_root)
+ && (fileName.length() == source_root.length()
+ || fileName.at(source_root.length()) == QLatin1Char('/'))) {
+ return build_root + fileName.mid(source_root.length());
+ }
+ return QString();
+}
+
QString QMakeGlobals::getEnv(const QString &var) const
{
-#ifndef QT_BOOTSTRAPPED
- if (!environment.isEmpty())
- return environment.value(var);
-#endif
+#ifdef PROEVALUATOR_SETENV
+ return environment.value(var);
+#else
return QString::fromLocal8Bit(qgetenv(var.toLocal8Bit().constData()));
+#endif
}
QStringList QMakeGlobals::getPathListEnv(const QString &var) const
@@ -201,6 +292,7 @@ QString QMakeGlobals::expandEnvVars(const QString &str) const
return string;
}
+#ifndef QT_BUILD_QMAKE
#ifdef PROEVALUATOR_INIT_PROPS
bool QMakeGlobals::initProperties()
{
@@ -257,5 +349,6 @@ void QMakeGlobals::setProperties(const QHash<QString, QString> &props)
properties.insert(ProKey(it.key()), ProString(it.value()));
}
#endif
+#endif // QT_BUILD_QMAKE
QT_END_NAMESPACE
diff --git a/src/shared/proparser/qmakeglobals.h b/src/shared/proparser/qmakeglobals.h
index ca4fbfd27e..25d0141d12 100644
--- a/src/shared/proparser/qmakeglobals.h
+++ b/src/shared/proparser/qmakeglobals.h
@@ -33,14 +33,18 @@
#include "qmake_global.h"
#include "proitems.h"
-#include <QHash>
-#include <QStringList>
+#ifdef QT_BUILD_QMAKE
+# include <property.h>
+#endif
+
+#include <qhash.h>
+#include <qstringlist.h>
#ifndef QT_BOOTSTRAPPED
-# include <QProcess>
+# include <qprocess.h>
#endif
#ifdef PROEVALUATOR_THREAD_SAFE
-# include <QMutex>
-# include <QWaitCondition>
+# include <qmutex.h>
+# include <qwaitcondition.h>
#endif
QT_BEGIN_NAMESPACE
@@ -76,6 +80,15 @@ public:
QMakeEvaluator *evaluator;
};
+class QMAKE_EXPORT QMakeCmdLineParserState
+{
+public:
+ QMakeCmdLineParserState(const QString &_pwd) : pwd(_pwd), after(false) {}
+ QString pwd;
+ QStringList precmds, preconfigs, postcmds, postconfigs;
+ bool after;
+};
+
class QMAKE_EXPORT QMakeGlobals
{
public:
@@ -85,37 +98,55 @@ public:
bool do_cache;
QString dir_sep;
QString dirlist_sep;
- QString qmakespec;
- QString xqmakespec;
QString cachefile;
-#ifndef QT_BOOTSTRAPPED
+#ifdef PROEVALUATOR_SETENV
QProcessEnvironment environment;
#endif
- QString sysroot;
QString qmake_abslocation;
+
+ QString qmakespec, xqmakespec;
QString user_template, user_template_prefix;
+ QString precmds, postcmds;
- // -nocache, -cache, -spec, QMAKESPEC
- // -set persistent value
- void setCommandLineArguments(const QStringList &args);
+#ifdef PROEVALUATOR_DEBUG
+ int debugLevel;
+#endif
+
+ enum ArgumentReturn { ArgumentUnknown, ArgumentMalformed, ArgumentsOk };
+ ArgumentReturn addCommandLineArguments(QMakeCmdLineParserState &state,
+ QStringList &args, int *pos);
+ void commitCommandLineArguments(QMakeCmdLineParserState &state);
+ void setCommandLineArguments(const QString &pwd, const QStringList &args);
+ void useEnvironment();
void setDirectories(const QString &input_dir, const QString &output_dir);
-#ifdef PROEVALUATOR_INIT_PROPS
- bool initProperties();
+#ifdef QT_BUILD_QMAKE
+ void setQMakeProperty(QMakeProperty *prop) { property = prop; }
+ ProString propertyValue(const ProKey &name) const { return property->value(name); }
#else
+# ifdef PROEVALUATOR_INIT_PROPS
+ bool initProperties();
+# else
void setProperties(const QHash<QString, QString> &props);
-#endif
+# endif
ProString propertyValue(const ProKey &name) const { return properties.value(name); }
+#endif
QString expandEnvVars(const QString &str) const;
+ QString shadowedPath(const QString &fileName) const;
private:
QString getEnv(const QString &) const;
QStringList getPathListEnv(const QString &var) const;
+ QString cleanSpec(QMakeCmdLineParserState &state, const QString &spec);
+
QString source_root, build_root;
- QString precmds, postcmds;
+#ifdef QT_BUILD_QMAKE
+ QMakeProperty *property;
+#else
QHash<ProKey, ProString> properties;
+#endif
#ifdef PROEVALUATOR_THREAD_SAFE
QMutex mutex;
diff --git a/src/shared/proparser/qmakeparser.cpp b/src/shared/proparser/qmakeparser.cpp
index 3be4506cc2..8fc662431f 100644
--- a/src/shared/proparser/qmakeparser.cpp
+++ b/src/shared/proparser/qmakeparser.cpp
@@ -30,11 +30,11 @@
#include "qmakeparser.h"
#include "ioutils.h"
-using namespace ProFileEvaluatorInternal;
+using namespace QMakeInternal;
-#include <QFile>
+#include <qfile.h>
#ifdef PROPARSER_THREAD_SAFE
-# include <QThreadPool>
+# include <qthreadpool.h>
#endif
QT_BEGIN_NAMESPACE
@@ -199,10 +199,11 @@ ProFile *QMakeParser::parsedProFile(const QString &fileName, bool cache)
return pro;
}
-ProFile *QMakeParser::parsedProBlock(const QString &name, const QString &contents, SubGrammar grammar)
+ProFile *QMakeParser::parsedProBlock(
+ const QString &contents, const QString &name, int line, SubGrammar grammar)
{
ProFile *pro = new ProFile(name);
- if (!read(pro, contents, grammar)) {
+ if (!read(pro, contents, line, grammar)) {
delete pro;
pro = 0;
}
@@ -219,9 +220,17 @@ bool QMakeParser::read(ProFile *pro)
return false;
}
- QString content(QString::fromLocal8Bit(file.readAll()));
+ QByteArray bcont = file.readAll();
+ if (bcont.startsWith("\xef\xbb\xbf")) {
+ // UTF-8 BOM will cause subtle errors
+ m_handler->message(QMakeParserHandler::ParserIoError,
+ fL1S("Unexpected UTF-8 BOM in %1").arg(pro->fileName()));
+ return false;
+ }
+ QString content(QString::fromLocal8Bit(bcont));
+ bcont.clear();
file.close();
- return read(pro, content, FullGrammar);
+ return read(pro, content, 1, FullGrammar);
}
void QMakeParser::putTok(ushort *&tokPtr, ushort tok)
@@ -261,10 +270,10 @@ void QMakeParser::finalizeHashStr(ushort *buf, uint len)
buf[-2] = (ushort)(hash >> 16);
}
-bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
+bool QMakeParser::read(ProFile *pro, const QString &in, int line, SubGrammar grammar)
{
m_proFile = pro;
- m_lineNo = 1;
+ m_lineNo = line;
// Final precompiled token stream buffer
QString tokBuff;
@@ -315,7 +324,6 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
m_operator = NoOperator;
m_markLine = m_lineNo;
m_inError = false;
- Context context = CtxTest;
int parens = 0; // Braces in value context
int argc = 0;
int wordCount = 0; // Number of words in currently accumulated expression
@@ -326,8 +334,15 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
ushort quote = 0;
ushort term = 0;
- ushort *ptr = buf;
- ptr += 4;
+ Context context;
+ ushort *ptr;
+ if (grammar == ValueGrammar) {
+ context = CtxPureValue;
+ ptr = tokPtr + 2;
+ } else {
+ context = CtxTest;
+ ptr = buf + 4;
+ }
ushort *xprPtr = ptr;
#define FLUSH_LHS_LITERAL() \
@@ -379,11 +394,23 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
putTok(tokPtr, TokValueTerminator); \
} while (0)
+ const ushort *end; // End of this line
+ const ushort *cptr; // Start of next line
+ bool lineCont;
+ int indent;
+
+ if (context == CtxPureValue) {
+ end = (const ushort *)in.unicode() + in.length();
+ cptr = 0;
+ lineCont = false;
+ indent = 0; // just gcc being stupid
+ goto nextChr;
+ }
+
forever {
ushort c;
// First, skip leading whitespace
- int indent;
for (indent = 0; ; ++cur, ++indent) {
c = *cur;
if (c == '\n') {
@@ -398,8 +425,6 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
}
// Then strip comments. Yep - no escaping is possible.
- const ushort *end; // End of this line
- const ushort *cptr; // Start of next line
for (cptr = cur;; ++cptr) {
c = *cptr;
if (c == '#') {
@@ -428,7 +453,6 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
}
// Then look for line continuations. Yep - no escaping here as well.
- bool lineCont;
forever {
// We don't have to check for underrun here, as we already determined
// that the line is non-empty.
@@ -503,6 +527,8 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
if (tok == TokVariable && c == '(')
tok = TokFuncName;
notfunc:
+ if (ptr == xprPtr)
+ languageWarning(fL1S("Missing name in expansion"));
if (quote)
tok |= TokQuoted;
if (needSep) {
@@ -586,7 +612,7 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
*ptr++ = ' ';
}
goto nextChr;
- } else if (c == ' ' || c == '\t') {
+ } else if ((c == ' ' || c == '\t') && context != CtxPureValue) {
putSpace = true;
goto nextChr;
} else if (c == '!' && ptr == xprPtr && context == CtxTest) {
@@ -596,12 +622,12 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
} else if (c == '\'' || c == '"') {
quote = c;
goto nextChr;
- } else if (c == ' ' || c == '\t') {
- FLUSH_LITERAL();
- goto nextWord;
} else if (context == CtxArgs) {
// Function arg context
- if (c == '(') {
+ if (c == ' ' || c == '\t') {
+ FLUSH_RHS_LITERAL();
+ goto nextWord;
+ } else if (c == '(') {
++parens;
} else if (c == ')') {
if (--parens < 0) {
@@ -637,7 +663,10 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
}
} else if (context == CtxTest) {
// Test or LHS context
- if (c == '(') {
+ if (c == ' ' || c == '\t') {
+ FLUSH_LHS_LITERAL();
+ goto nextWord;
+ } else if (c == '(') {
FLUSH_LHS_LITERAL();
if (wordCount != 1) {
if (wordCount)
@@ -733,8 +762,11 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
ptr = ++tokPtr;
goto nextToken;
}
- } else { // context == CtxValue
- if (c == '{') {
+ } else if (context == CtxValue) {
+ if (c == ' ' || c == '\t') {
+ FLUSH_RHS_LITERAL();
+ goto nextWord;
+ } else if (c == '{') {
++parens;
} else if (c == '}') {
if (!parens) {
@@ -790,6 +822,8 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
if (context == CtxValue) {
tokPtr[-1] = 0; // sizehint
putTok(tokPtr, TokValueTerminator);
+ } else if (context == CtxPureValue) {
+ putTok(tokPtr, TokValueTerminator);
} else {
bogusTest(tokPtr);
}
@@ -797,6 +831,9 @@ bool QMakeParser::read(ProFile *pro, const QString &in, SubGrammar grammar)
FLUSH_VALUE_LIST();
if (parens)
languageWarning(fL1S("Possible braces mismatch"));
+ } else if (context == CtxPureValue) {
+ tokPtr = ptr;
+ putTok(tokPtr, TokValueTerminator);
} else {
finalizeCond(tokPtr, buf, ptr, wordCount);
}
@@ -1108,11 +1145,10 @@ void QMakeParser::finalizeCall(ushort *&tokPtr, ushort *uc, ushort *ptr, int arg
uint nlen = uce[1];
if (uce[nlen + 2] == TokFuncTerminator) {
m_tmp.setRawData((QChar *)uce + 2, nlen);
- if (m_tmp == statics.strhost_build) {
+ if (m_tmp == statics.strhost_build)
m_proFile->setHostBuild(true);
- } else {
+ else
parseError(fL1S("Unknown option() %1.").arg(m_tmp));
- }
return;
}
}
diff --git a/src/shared/proparser/qmakeparser.h b/src/shared/proparser/qmakeparser.h
index c81915353c..7db2015841 100644
--- a/src/shared/proparser/qmakeparser.h
+++ b/src/shared/proparser/qmakeparser.h
@@ -32,11 +32,12 @@
#include "qmake_global.h"
#include "proitems.h"
-#include <QHash>
-#include <QStack>
+
+#include <qhash.h>
+#include <qstack.h>
#ifdef PROPARSER_THREAD_SAFE
-# include <QMutex>
-# include <QWaitCondition>
+# include <qmutex.h>
+# include <qwaitcondition.h>
#endif
QT_BEGIN_NAMESPACE
@@ -75,10 +76,10 @@ public:
QMakeParser(ProFileCache *cache, QMakeParserHandler *handler);
- enum SubGrammar { FullGrammar, TestGrammar };
+ enum SubGrammar { FullGrammar, TestGrammar, ValueGrammar };
// fileName is expected to be absolute and cleanPath()ed.
ProFile *parsedProFile(const QString &fileName, bool cache = false);
- ProFile *parsedProBlock(const QString &name, const QString &contents,
+ ProFile *parsedProBlock(const QString &contents, const QString &name, int line = 0,
SubGrammar grammar = FullGrammar);
private:
@@ -104,7 +105,7 @@ private:
StCond // Conditionals met on current line
};
- enum Context { CtxTest, CtxValue, CtxArgs };
+ enum Context { CtxTest, CtxValue, CtxPureValue, CtxArgs };
struct ParseCtx {
int parens; // Nesting of non-functional parentheses
int argc; // Number of arguments in current function call
@@ -115,7 +116,7 @@ private:
};
bool read(ProFile *pro);
- bool read(ProFile *pro, const QString &content, SubGrammar grammar);
+ bool read(ProFile *pro, const QString &content, int line, SubGrammar grammar);
ALWAYS_INLINE void putTok(ushort *&tokPtr, ushort tok);
ALWAYS_INLINE void putBlockLen(ushort *&tokPtr, uint len);
diff --git a/src/shared/qtlockedfile/qtlockedfile_win.cpp b/src/shared/qtlockedfile/qtlockedfile_win.cpp
index 5119ac9472..dcc7e602fa 100644
--- a/src/shared/qtlockedfile/qtlockedfile_win.cpp
+++ b/src/shared/qtlockedfile/qtlockedfile_win.cpp
@@ -49,7 +49,7 @@ static QString errorCodeToString(DWORD errorCode)
if (data != 0)
LocalFree(data);
- if (result.endsWith('\n'))
+ if (result.endsWith(QLatin1Char('\n')))
result.truncate(result.length() - 1);
return result;
diff --git a/src/shared/qtsingleapplication/qtlocalpeer.cpp b/src/shared/qtsingleapplication/qtlocalpeer.cpp
index 1da7056f67..824a2062b5 100644
--- a/src/shared/qtsingleapplication/qtlocalpeer.cpp
+++ b/src/shared/qtsingleapplication/qtlocalpeer.cpp
@@ -62,7 +62,7 @@ QtLocalPeer::QtLocalPeer(QObject *parent, const QString &appId)
+ QString::number(idNum, 16);
#if defined(Q_OS_WIN)
if (!pProcessIdToSessionId) {
- QLibrary lib("kernel32");
+ QLibrary lib(QLatin1String("kernel32"));
pProcessIdToSessionId = (PProcessIdToSessionId)lib.resolve("ProcessIdToSessionId");
}
if (pProcessIdToSessionId) {
diff --git a/src/tools/QtcTool.qbs b/src/tools/QtcTool.qbs
index 7669496dca..2ae70db106 100644
--- a/src/tools/QtcTool.qbs
+++ b/src/tools/QtcTool.qbs
@@ -1,12 +1,17 @@
import qbs.base 1.0
+import "../../qbs/defaults.js" as Defaults
Application {
Depends { name: "cpp" }
- cpp.defines: project.additionalCppDefines
+ cpp.defines: Defaults.defines(qbs)
cpp.linkerFlags: {
if (qbs.buildVariant == "release" && (qbs.toolchain == "gcc" || qbs.toolchain == "mingw"))
return ["-Wl,-s"]
}
- destination: "bin"
+ Group {
+ fileTagsFilter: product.type
+ qbs.install: true
+ qbs.installDir: "bin"
+ }
}
diff --git a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp
index 34ef873ad7..85b88ef295 100644
--- a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp
+++ b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.cpp
@@ -86,7 +86,7 @@ class MkVisitor: protected SymbolVisitor
if (interfaces.contains(b) || isMiscNode(b)) {
QString className = oo(b->symbols().first()->name());
- if (className.endsWith("AST")) {
+ if (className.endsWith(QLatin1String("AST"))) {
className.chop(3);
QString funcName = className;
@@ -141,13 +141,13 @@ public:
Q_ASSERT(klass != 0);
QString className = oo(klass->name());
- if (className == "AST")
+ if (className == QLatin1String("AST"))
continue;
QString baseClassName = className;
baseClassName.chop(3);
- QString retTy = false;
+ QString retTy;
QString funcName = getAcceptFunctionName(b, &retTy);
std::cout
@@ -222,13 +222,13 @@ public:
Q_ASSERT(klass != 0);
QString className = oo(klass->name());
- if (className == "AST")
+ if (className == QLatin1String("AST"))
continue;
QString baseClassName = className;
baseClassName.chop(3);
- QString current = "_current";
+ QString current = QLatin1String("_current");
current += baseClassName;
std::cout << " " << qPrintable(baseClassName) << "Ty " << qPrintable(current) << ";" << std::endl;
@@ -255,7 +255,7 @@ public:
Q_ASSERT(klass != 0);
QString className = oo(klass->name());
- if (className == "AST")
+ if (className == QLatin1String("AST"))
continue;
QString baseClassName = className;
@@ -264,7 +264,7 @@ public:
QString retTy;
QString funcName = getAcceptFunctionName(b, &retTy);
- QString current = "_current";
+ QString current = QLatin1String("_current");
current += baseClassName;
std::cout << "Semantic::" << qPrintable(baseClassName) << "Ty Semantic::"
@@ -322,10 +322,10 @@ public:
if (PointerType *ptrTy = decl->type()->asPointerType()) {
if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {
const QString eltTyName = oo(namedTy->name());
- if (eltTyName.endsWith("ListAST")) {
+ if (eltTyName.endsWith(QLatin1String("ListAST"))) {
QString name = eltTyName;
name.chop(7);
- name += "AST";
+ name += QLatin1String("AST");
Control *control = context.thisDocument()->control();
const Name *n = control->identifier(name.toLatin1().constData());
@@ -352,7 +352,7 @@ public:
if (ClassOrNamespace *ty = context.lookupType(namedTy->name(), klass)) {
QString className = oo(ty->symbols().first()->name());
QString baseClassName = className;
- if (baseClassName.endsWith("AST")) {
+ if (baseClassName.endsWith(QLatin1String("AST"))) {
baseClassName.chop(3);
QString retTy;
@@ -394,7 +394,7 @@ protected:
virtual bool visit(Class *klass) {
const QString className = oo(klass->name());
- if (! className.endsWith("AST"))
+ if (! className.endsWith(QLatin1String("AST")))
return false;
ClassOrNamespace *b = context.lookupType(klass);
@@ -429,7 +429,7 @@ void printUsage()
std::cout << "Usage: " << qPrintable(QFileInfo(qApp->arguments().at(0)).fileName())
<< " [-v] [path to AST.h]\n\n"
<< "Print a visitor class based on AST.h to stdout.\n\n";
- const QString defaulPath = QFileInfo(PATH_AST_H).canonicalFilePath();
+ const QString defaulPath = QFileInfo(QLatin1String(PATH_AST_H)).canonicalFilePath();
std::cout << "Default path: " << qPrintable(defaulPath) << '.' << "\n";
}
@@ -442,18 +442,19 @@ int main(int argc, char *argv[])
bool optionVerbose = false;
// Process options & arguments
- if (args.contains("-v")) {
+ if (args.contains(QLatin1String("-v"))) {
optionVerbose = true;
- args.removeOne("-v");
+ args.removeOne(QLatin1String("-v"));
}
- const bool helpRequested = args.contains("-h") || args.contains("-help");
+ const bool helpRequested = args.contains(QLatin1String("-h"))
+ || args.contains(QLatin1String("-help"));
if (helpRequested || args.count() >= 2) {
printUsage();
return helpRequested ? EXIT_SUCCESS : EXIT_FAILURE;
}
// Run the preprocessor
- QString fileName = PATH_AST_H;
+ QString fileName = QLatin1String(PATH_AST_H);
if (!args.isEmpty())
fileName = args.first();
diff --git a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro
index aa942fc5fa..ce0a4bc7aa 100644
--- a/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro
+++ b/src/tools/cplusplus-mkvisitor/cplusplus-mkvisitor.pro
@@ -9,5 +9,6 @@ include(../../../qtcreator.pri)
include(../../libs/cplusplus/cplusplus-lib.pri)
include(../../../src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri)
+DEFINES *= QT_NO_CAST_FROM_ASCII
DEFINES += PATH_AST_H=\\\"$$PWD/../../libs/3rdparty/cplusplus/AST.h\\\"
SOURCES += cplusplus-mkvisitor.cpp
diff --git a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp b/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp
index b9542dc678..9d81422f0e 100644
--- a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp
+++ b/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.cpp
@@ -65,7 +65,7 @@ void executeCommand(const QString &command, const QStringList &arguments, const
process.setStandardOutputFile(outputFile, QIODevice::Truncate);
process.start(command, arguments);
if (!process.waitForStarted()) {
- out << QString("Error: Process \"%1\" did not start within timeout: %2.")
+ out << QString::fromLatin1("Error: Process \"%1\" did not start within timeout: %2.")
.arg(fullCommand, process.errorString())
<< endl;
exit(EXIT_FAILURE);
@@ -73,14 +73,15 @@ void executeCommand(const QString &command, const QStringList &arguments, const
if (!process.waitForFinished()) {
if (!verbose)
out << process.readAll() << endl;
- out << QString("Error: Process \"%1\" did not finish within timeout.").arg(fullCommand)
+ out << QString::fromLatin1("Error: Process \"%1\" did not finish within timeout.")
+ .arg(fullCommand)
<< endl;
exit(EXIT_FAILURE);
}
const int exitCode = process.exitCode();
if (exitCode != 0) {
out << process.readAllStandardError() << endl;
- out << QString("Error: Process \"%1\" finished with non zero exit value %2")
+ out << QString::fromLatin1("Error: Process \"%1\" finished with non zero exit value %2")
.arg(fullCommand, exitCode) << endl;
exit(EXIT_FAILURE);
}
@@ -89,9 +90,9 @@ void executeCommand(const QString &command, const QStringList &arguments, const
SystemPreprocessor::SystemPreprocessor(bool verbose)
: m_verbose(verbose)
{
- m_knownCompilers[portableExecutableName("gcc")]
+ m_knownCompilers[portableExecutableName(QLatin1String("gcc"))]
= QLatin1String("-DCPLUSPLUS_WITHOUT_QT -U__BLOCKS__ -xc++ -E -include");
- m_knownCompilers[portableExecutableName("cl")]
+ m_knownCompilers[portableExecutableName(QLatin1String("cl"))]
= QLatin1String("/DCPLUSPLUS_WITHOUT_QT /U__BLOCKS__ /TP /E /I . /FI");
QMapIterator<QString, QString> i(m_knownCompilers);
@@ -112,14 +113,17 @@ SystemPreprocessor::SystemPreprocessor(bool verbose)
void SystemPreprocessor::check() const
{
QTextStream out(stderr);
- if (!QFile::exists(PATH_PREPROCESSOR_CONFIG)) {
- out << QString("Error: File \"%1\" does not exist.").arg(PATH_PREPROCESSOR_CONFIG) << endl;
+ if (!QFile::exists(QLatin1String(PATH_PREPROCESSOR_CONFIG))) {
+ out << QString::fromLatin1("Error: File \"%1\" does not exist.")
+ .arg(QLatin1String(PATH_PREPROCESSOR_CONFIG))
+ << endl;
exit(EXIT_FAILURE);
}
if (m_compiler.isEmpty()) {
const QString triedCompilers
= QStringList(m_knownCompilers.keys()).join(QLatin1String(", "));
- out << QString("Error: No compiler found. Tried %1.").arg(triedCompilers) << endl;
+ out << QString::fromLatin1("Error: No compiler found. Tried %1.").arg(triedCompilers)
+ << endl;
exit(EXIT_FAILURE);
}
}
@@ -129,7 +133,7 @@ void SystemPreprocessor::preprocessFile(const QString &inputFile, const QString
check();
if (!QFile::exists(inputFile)) {
QTextStream out(stderr);
- out << QString("Error: File \"%1\" does not exist.").arg(inputFile) << endl;
+ out << QString::fromLatin1("Error: File \"%1\" does not exist.").arg(inputFile) << endl;
exit(EXIT_FAILURE);
}
const QStringList arguments = QStringList(m_compilerArguments)
diff --git a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri b/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri
index 99002ad0d0..c84010be2c 100644
--- a/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri
+++ b/src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri
@@ -1,6 +1,7 @@
DEPENDPATH += $$PWD
INCLUDEPATH += $$PWD $$PWD/../../libs/utils
+DEFINES *= QT_NO_CAST_FROM_ASCII
DEFINES += PATH_PREPROCESSOR_CONFIG=\\\"$$PWD/pp-configuration.inc\\\"
DEFINES += QTCREATOR_UTILS_STATIC_LIB
diff --git a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp
index 0d5373f6b6..dea4f1e086 100644
--- a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp
+++ b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.cpp
@@ -169,7 +169,7 @@ protected:
const QString className = oo(klass->name());
- if (className.endsWith("AST")) {
+ if (className.endsWith(QLatin1String("AST"))) {
if (className == QLatin1String("AST"))
_nodes.base = ast;
else {
@@ -276,9 +276,8 @@ protected:
if (NamedType *namedTy = ptrTy->elementType()->asNamedType()) {
QByteArray typeName = namedTy->name()->identifier()->chars();
- if (typeName.endsWith("AST") && memberName != "next") {
+ if (typeName.endsWith("AST") && memberName != "next")
*out << " accept(" << memberName.constData() << ", visitor);" << endl;
- }
}
}
}
@@ -286,9 +285,8 @@ protected:
for (unsigned i = 0; i < klass->baseClassCount(); ++i) {
const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();
- if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {
+ if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0))
visitMembers(baseClassSpec->symbol);
- }
}
}
@@ -550,9 +548,8 @@ protected:
for (unsigned i = 0; i < klass->baseClassCount(); ++i) {
const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();
- if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {
+ if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0))
visitMembers(baseClassSpec->symbol);
- }
}
}
@@ -693,9 +690,8 @@ protected:
for (unsigned i = 0; i < klass->baseClassCount(); ++i) {
const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();
- if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {
+ if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0))
visitMembers(baseClassSpec->symbol);
- }
}
}
@@ -826,9 +822,8 @@ protected:
for (unsigned i = 0; i < klass->baseClassCount(); ++i) {
const QByteArray baseClassName = klass->baseClassAt(i)->identifier()->chars();
- if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0)) {
+ if (ClassSpecifierAST *baseClassSpec = classMap.value(baseClassName, 0))
visitMembers(baseClassSpec->symbol);
- }
}
}
@@ -1198,11 +1193,10 @@ void generateAST_cpp(const Snapshot &snapshot, const QDir &cplusplusDir)
QTextStream os(&method);
const QStringList fields = collectFieldNames(info.classAST, true);
- if (info.firstToken) {
+ if (info.firstToken)
generateFirstToken(os, className, fields);
- } else if (info.lastToken) {
+ else if (info.lastToken)
generateLastToken(os, className, fields);
- }
changes.replace(info.start, info.end, method);
}
@@ -1414,11 +1408,16 @@ QStringList generateAST_H(const Snapshot &snapshot, const QDir &cplusplusDir, co
cursors[classAST] = removeCastMethods(classAST);
const QString className = oo(classAST->symbol->name());
const QString methodName = QLatin1String("as") + className.mid(0, className.length() - 3);
- replacementCastMethods[classAST] = QString(" virtual %1 *%2() { return this; }\n").arg(className, methodName);
- castMethods.append(QString(" virtual %1 *%2() { return 0; }\n").arg(className, methodName));
+ replacementCastMethods[classAST]
+ = QString::fromLatin1(" virtual %1 *%2() { return this; }\n")
+ .arg(className, methodName);
+ castMethods.append(
+ QString::fromLatin1(" virtual %1 *%2() { return 0; }\n")
+ .arg(className, methodName));
astDerivedClasses.append(className);
- constructors[classAST] = removeConstructors(classAST, AST_h_document->translationUnit(), &document);
+ constructors[classAST] = removeConstructors(classAST, AST_h_document->translationUnit(),
+ &document);
replacementConstructors[classAST] = createConstructor(classAST);
}
@@ -1594,7 +1593,7 @@ void generateASTPatternBuilder_h(const QDir &cplusplusDir)
<< endl;
Control *control = AST_h_document->control();
- QSet<QString> listClasses;
+ QSet<QString> classesSet;
foreach (ClassSpecifierAST *classNode, astNodes.deriveds) {
Class *klass = classNode->symbol;
@@ -1612,7 +1611,7 @@ void generateASTPatternBuilder_h(const QDir &cplusplusDir)
const QString className = oo(klass->name());
- if (! className.endsWith("AST"))
+ if (! className.endsWith(QLatin1String("AST")))
continue;
const QString methodName = className.left(className.length() - 3);
@@ -1633,9 +1632,9 @@ void generateASTPatternBuilder_h(const QDir &cplusplusDir)
continue;
const QString tyName = oo(ptrTy->elementType());
- if (tyName.endsWith("ListAST"))
- listClasses.insert(tyName);
- if (tyName.endsWith("AST")) {
+ if (tyName.endsWith(QLatin1String("ListAST")))
+ classesSet.insert(tyName);
+ if (tyName.endsWith(QLatin1String("AST"))) {
if (! first)
out << ", ";
@@ -1664,7 +1663,9 @@ void generateASTPatternBuilder_h(const QDir &cplusplusDir)
<< endl;
}
- foreach (const QString &className, listClasses) {
+ QStringList classesList = classesSet.toList();
+ qSort(classesList);
+ foreach (const QString &className, classesList) {
const QString methodName = className.left(className.length() - 3);
const QString elementName = className.left(className.length() - 7) + QLatin1String("AST");
out
@@ -1699,8 +1700,10 @@ void printUsage()
<< "to AST.h and print the paths of the written files. Run this tool after\n"
<< "modifying AST.h."
<< "\n\n";
- const QString defaultPathCppFrontend = QFileInfo(PATH_CPP_FRONTEND).canonicalFilePath();
- const QString defaultPathDumpersFile = QFileInfo(PATH_DUMPERS_FILE).canonicalFilePath();
+ const QString defaultPathCppFrontend
+ = QFileInfo(QLatin1String(PATH_CPP_FRONTEND)).canonicalFilePath();
+ const QString defaultPathDumpersFile
+ = QFileInfo(QLatin1String(PATH_DUMPERS_FILE)).canonicalFilePath();
std::cout << "Default values:" << "\n"
<< " frontend-dir: " << qPrintable(defaultPathCppFrontend) << "\n"
<< " dumpers-file: " << qPrintable(defaultPathDumpersFile) << "\n";
@@ -1712,10 +1715,11 @@ int main(int argc, char *argv[])
QStringList args = app.arguments();
args.removeFirst();
- QString pathCppFrontend = PATH_CPP_FRONTEND;
- QString pathDumpersFile = PATH_DUMPERS_FILE;
+ QString pathCppFrontend = QLatin1String(PATH_CPP_FRONTEND);
+ QString pathDumpersFile = QLatin1String(PATH_DUMPERS_FILE);
- const bool helpRequested = args.contains("-h") || args.contains("-help");
+ const bool helpRequested = args.contains(QLatin1String("-h"))
+ || args.contains(QLatin1String("-help"));
if (args.count() == 1 || args.count() >= 3 || helpRequested) {
printUsage();
return helpRequested ? EXIT_SUCCESS : EXIT_FAILURE;
diff --git a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro
index 7b0e853cd4..73bbfd0cc8 100644
--- a/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro
+++ b/src/tools/cplusplus-update-frontend/cplusplus-update-frontend.pro
@@ -10,6 +10,7 @@ INCLUDEPATH += . ../../libs
include(../../../qtcreator.pri)
include(../../libs/cplusplus/cplusplus-lib.pri)
+DEFINES *= QT_NO_CAST_FROM_ASCII
DEFINES += PATH_CPP_FRONTEND=\\\"$$PWD/../../libs/3rdparty/cplusplus\\\"
DEFINES += PATH_DUMPERS_FILE=\\\"$$PWD/../../../tests/tools/cplusplus-ast2png/dumpers.inc\\\"
SOURCES += cplusplus-update-frontend.cpp ../../libs/utils/changeset.cpp
diff --git a/src/tools/examplesscanner/helpextractor.cpp b/src/tools/examplesscanner/helpextractor.cpp
index ca2c21338b..1e5d24afa0 100644
--- a/src/tools/examplesscanner/helpextractor.cpp
+++ b/src/tools/examplesscanner/helpextractor.cpp
@@ -242,11 +242,10 @@ QString HelpExtractor::loadDescription(const QString &name)
int errorLine, errorColumn;
QDomDocument exampleDoc;
- if (ba.isEmpty()) {
+ if (ba.isEmpty())
qDebug() << "No documentation found for" << name << "Is the documentation built?";
- } else if (!exampleDoc.setContent(ba, false, &errorMsg, &errorLine, &errorColumn)) {
+ else if (!exampleDoc.setContent(ba, false, &errorMsg, &errorLine, &errorColumn))
qDebug() << "Error loading documentation for " << name << ": " << errorMsg << errorLine << errorColumn;
- }
QDomNodeList paragraphs = exampleDoc.elementsByTagName("p");
if (paragraphs.length() < 1)
@@ -255,9 +254,8 @@ QString HelpExtractor::loadDescription(const QString &name)
QString description = QLatin1String("");
for (int p = 0; p < int(paragraphs.length()); ++p) {
description = extractTextFromParagraph(paragraphs.item(p));
- if (isSummaryOf(description, name)) {
+ if (isSummaryOf(description, name))
break;
- }
}
return description;
}
diff --git a/src/tools/qml2puppet/qml2puppet.pro b/src/tools/qml2puppet/qml2puppet.pro
new file mode 100644
index 0000000000..b8e17814be
--- /dev/null
+++ b/src/tools/qml2puppet/qml2puppet.pro
@@ -0,0 +1,9 @@
+TEMPLATE = subdirs
+
+include(../../../qtcreator.pri)
+
+greaterThan(QT_MAJOR_VERSION, 4) {
+ QT += declarative-private core-private
+ SUBDIRS += qml2puppet
+}
+
diff --git a/src/tools/qml2puppet/qml2puppet/qml2puppet.pro b/src/tools/qml2puppet/qml2puppet/qml2puppet.pro
new file mode 100644
index 0000000000..e1934d87f1
--- /dev/null
+++ b/src/tools/qml2puppet/qml2puppet/qml2puppet.pro
@@ -0,0 +1,12 @@
+TARGET = qml2puppet
+
+TEMPLATE = app
+
+include(../../../../qtcreator.pri)
+
+DESTDIR = $$IDE_BIN_PATH
+include(../../../rpath.pri)
+
+include(../../../../share/qtcreator/qml/qmlpuppet/qml2puppet/qml2puppet.pri)
+
+isEmpty(PRECOMPILED_HEADER):PRECOMPILED_HEADER = $$PWD/../../../shared/qtcreator_pch.h
diff --git a/src/tools/qmlprofilertool/qmlprofilerapplication.cpp b/src/tools/qmlprofilertool/qmlprofilerapplication.cpp
index 3afb1c17b3..cad7f9f4e1 100644
--- a/src/tools/qmlprofilertool/qmlprofilerapplication.cpp
+++ b/src/tools/qmlprofilertool/qmlprofilerapplication.cpp
@@ -123,15 +123,13 @@ bool QmlProfilerApplication::parseArguments()
for (int argPos = 1; argPos < arguments().size(); ++argPos) {
const QString arg = arguments().at(argPos);
if (arg == QLatin1String("-attach") || arg == QLatin1String("-a")) {
- if (argPos + 1 == arguments().size()) {
+ if (argPos + 1 == arguments().size())
return false;
- }
m_hostName = arguments().at(++argPos);
m_runMode = AttachMode;
} else if (arg == QLatin1String("-port") || arg == QLatin1String("-p")) {
- if (argPos + 1 == arguments().size()) {
+ if (argPos + 1 == arguments().size())
return false;
- }
const QString portStr = arguments().at(++argPos);
bool isNumber;
m_port = portStr.toUShort(&isNumber);
@@ -359,11 +357,10 @@ void QmlProfilerApplication::traceFinished()
void QmlProfilerApplication::recordingChanged()
{
- if (m_qmlProfilerClient.isRecording()) {
+ if (m_qmlProfilerClient.isRecording())
print(QLatin1String("Recording is on."));
- } else {
+ else
print(QLatin1String("Recording is off."));
- }
}
void QmlProfilerApplication::print(const QString &line)
diff --git a/src/tools/qmlpuppet/qmlpuppet/qmlpuppet.pro b/src/tools/qmlpuppet/qmlpuppet/qmlpuppet.pro
index 66acfec5db..1f5f0070e7 100644
--- a/src/tools/qmlpuppet/qmlpuppet/qmlpuppet.pro
+++ b/src/tools/qmlpuppet/qmlpuppet/qmlpuppet.pro
@@ -8,3 +8,5 @@ DESTDIR = $$IDE_BIN_PATH
include(../../../rpath.pri)
include(../../../../share/qtcreator/qml/qmlpuppet/qmlpuppet/qmlpuppet.pri)
+
+isEmpty(PRECOMPILED_HEADER):PRECOMPILED_HEADER = $$PWD/../../../shared/qtcreator_pch.h
diff --git a/src/tools/qtcdebugger/main.cpp b/src/tools/qtcdebugger/main.cpp
index f771616586..23ea477ba5 100644
--- a/src/tools/qtcdebugger/main.cpp
+++ b/src/tools/qtcdebugger/main.cpp
@@ -222,7 +222,7 @@ static inline bool registryReplaceStringKey(HKEY rootHandle, // HKEY_LOCAL_MACHI
break;
}
rc = true;
- } while(false);
+ } while (false);
if (handle)
RegCloseKey(handle);
return rc;
diff --git a/src/tools/qtcdebugger/qtcdebugger.qbs b/src/tools/qtcdebugger/qtcdebugger.qbs
index bc416fb95b..5b86287746 100644
--- a/src/tools/qtcdebugger/qtcdebugger.qbs
+++ b/src/tools/qtcdebugger/qtcdebugger.qbs
@@ -21,6 +21,6 @@ QtcTool {
files: [
"main.cpp",
"../../shared/registryaccess/registryaccess.cpp",
- "../../shared/registryaccess/registryaccess.h"
+ "../../shared/registryaccess/registryaccess.h",
]
}
diff --git a/src/tools/qtcreatorcrashhandler/backtracecollector.cpp b/src/tools/qtcreatorcrashhandler/backtracecollector.cpp
new file mode 100644
index 0000000000..c275dc2af3
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/backtracecollector.cpp
@@ -0,0 +1,128 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "backtracecollector.h"
+
+#include <QDebug>
+#include <QScopedPointer>
+#include <QTemporaryFile>
+
+const char GdbBatchCommands[] =
+ "set height 0\n"
+ "set width 0\n"
+ "thread\n"
+ "thread apply all backtrace full\n";
+
+class BacktraceCollectorPrivate
+{
+public:
+ BacktraceCollectorPrivate() : errorOccurred(false) {}
+
+ bool errorOccurred;
+ QScopedPointer<QTemporaryFile> commandFile;
+ QProcess debugger;
+ QString output;
+};
+
+BacktraceCollector::BacktraceCollector(QObject *parent) :
+ QObject(parent), d(new BacktraceCollectorPrivate)
+{
+ connect(&d->debugger, SIGNAL(finished(int,QProcess::ExitStatus)),
+ SLOT(onDebuggerFinished(int,QProcess::ExitStatus)));
+ connect(&d->debugger, SIGNAL(error(QProcess::ProcessError)),
+ SLOT(onDebuggerError(QProcess::ProcessError)));
+ connect(&d->debugger, SIGNAL(readyRead()), SLOT(onDebuggerOutputAvailable()));
+ d->debugger.setProcessChannelMode(QProcess::MergedChannels);
+}
+
+BacktraceCollector::~BacktraceCollector()
+{
+ delete d;
+}
+
+void BacktraceCollector::run(Q_PID pid)
+{
+ d->debugger.start(QLatin1String("gdb"), QStringList()
+ << QLatin1String("--nw") // Do not use a window interface.
+ << QLatin1String("--nx") // Do not read .gdbinit file.
+ << QLatin1String("--batch") // Exit after processing options.
+ << QLatin1String("--command") << createTemporaryCommandFile()
+ << QLatin1String("--pid") << QString::number(pid)
+ );
+}
+
+bool BacktraceCollector::isRunning() const
+{
+ return d->debugger.state() == QProcess::Running;
+}
+
+void BacktraceCollector::kill()
+{
+ d->debugger.kill();
+}
+
+void BacktraceCollector::onDebuggerFinished(int exitCode, QProcess::ExitStatus /*exitStatus*/)
+{
+ if (d->errorOccurred) {
+ emit error(QLatin1String("QProcess: ") + d->debugger.errorString());
+ return;
+ }
+ if (exitCode != 0) {
+ emit error(QString::fromLatin1("Debugger exited with code %1.").arg(exitCode));
+ return;
+ }
+ emit backtrace(d->output);
+}
+
+void BacktraceCollector::onDebuggerError(QProcess::ProcessError /*error*/)
+{
+ d->errorOccurred = true;
+}
+
+QString BacktraceCollector::createTemporaryCommandFile()
+{
+ d->commandFile.reset(new QTemporaryFile);
+ if (!d->commandFile->open()) {
+ emit error(QLatin1String("Error: Could not create temporary command file."));
+ return QString();
+ }
+ if (d->commandFile->write(GdbBatchCommands) == -1) {
+ emit error(QLatin1String("Error: Could not write temporary command file."));
+ return QString();
+ }
+ d->commandFile->close();
+ return d->commandFile->fileName();
+}
+
+void BacktraceCollector::onDebuggerOutputAvailable()
+{
+ const QString newChunk = QString::fromLocal8Bit(d->debugger.readAll());
+ d->output.append(newChunk);
+ emit backtraceChunk(newChunk);
+}
diff --git a/src/tools/qtcreatorcrashhandler/backtracecollector.h b/src/tools/qtcreatorcrashhandler/backtracecollector.h
new file mode 100644
index 0000000000..0fc14a4cd6
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/backtracecollector.h
@@ -0,0 +1,64 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef BACKTRACECOLLECTOR_H
+#define BACKTRACECOLLECTOR_H
+
+#include <QProcess>
+
+class BacktraceCollectorPrivate;
+
+class BacktraceCollector : public QObject
+{
+ Q_OBJECT
+public:
+ explicit BacktraceCollector(QObject *parent = 0);
+ ~BacktraceCollector();
+
+ void run(Q_PID pid);
+ bool isRunning() const;
+ void kill();
+
+signals:
+ void error(const QString &errorMessage);
+ void backtrace(const QString &backtrace);
+ void backtraceChunk(const QString &chunk);
+
+private slots:
+ void onDebuggerOutputAvailable();
+ void onDebuggerFinished(int exitCode, QProcess::ExitStatus exitStatus);
+ void onDebuggerError(QProcess::ProcessError err);
+
+private:
+ QString createTemporaryCommandFile();
+
+ BacktraceCollectorPrivate *d;
+};
+
+#endif // BACKTRACECOLLECTOR_H
diff --git a/src/tools/qtcreatorcrashhandler/crashhandler.cpp b/src/tools/qtcreatorcrashhandler/crashhandler.cpp
new file mode 100644
index 0000000000..c0247ff8ff
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandler.cpp
@@ -0,0 +1,313 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "crashhandler.h"
+#include "crashhandlerdialog.h"
+#include "backtracecollector.h"
+#include "utils.h"
+
+#include <utils/environment.h>
+
+#include <QApplication>
+#include <QDebug>
+#include <QDesktopServices>
+#include <QDir>
+#include <QFile>
+#include <QRegExp>
+#include <QTextStream>
+#include <QUrl>
+#include <QVector>
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <errno.h>
+#include <unistd.h>
+
+#include <sys/types.h>
+#include <sys/wait.h>
+
+static const char FileDistroInformation[] = "/etc/lsb-release";
+static const char FileKernelVersion[] = "/proc/version";
+static const char QtCreatorExecutable[] = "qtcreator";
+
+static QString collectLinuxDistributionInfo()
+{
+ return QString::fromLatin1(fileContents(QLatin1String(FileDistroInformation)));
+}
+
+static QString collectKernelVersionInfo()
+{
+ return QString::fromLatin1(fileContents(QLatin1String(FileKernelVersion)));
+}
+
+// Convience class for interacting with exec() family of functions.
+class CExecList : public QVector<char *>
+{
+public:
+ CExecList(const QStringList &list)
+ {
+ foreach (const QString &item, list)
+ append(qstrdup(item.toLatin1().data()));
+ append(0);
+ }
+
+ ~CExecList()
+ {
+ for (int i = 0; i < size(); ++i)
+ delete[] value(i);
+ }
+};
+
+class CrashHandlerPrivate
+{
+public:
+ CrashHandlerPrivate(pid_t pid, const QString &signalName, CrashHandler *crashHandler)
+ : pid(pid),
+ creatorInPath(Utils::Environment::systemEnvironment().searchInPath(QLatin1String(QtCreatorExecutable))),
+ dialog(crashHandler, signalName) {}
+
+ const pid_t pid;
+ const QString creatorInPath; // Backup debugger.
+
+ BacktraceCollector backtraceCollector;
+ CrashHandlerDialog dialog;
+
+ QStringList restartAppCommandLine;
+ QStringList restartAppEnvironment;
+};
+
+CrashHandler::CrashHandler(pid_t pid, const QString &signalName, QObject *parent)
+ : QObject(parent), d(new CrashHandlerPrivate(pid, signalName, this))
+{
+ connect(&d->backtraceCollector, SIGNAL(error(QString)), SLOT(onError(QString)));
+ connect(&d->backtraceCollector, SIGNAL(backtraceChunk(QString)), SLOT(onBacktraceChunk(QString)));
+ connect(&d->backtraceCollector, SIGNAL(backtrace(QString)), SLOT(onBacktraceFinished(QString)));
+
+ d->dialog.appendDebugInfo(collectKernelVersionInfo());
+ d->dialog.appendDebugInfo(collectLinuxDistributionInfo());
+
+ if (!collectRestartAppData()) {
+ d->dialog.disableRestartAppCheckBox();
+ if (d->creatorInPath.isEmpty())
+ d->dialog.disableDebugAppButton();
+ }
+
+ d->dialog.show();
+}
+
+CrashHandler::~CrashHandler()
+{
+ delete d;
+}
+
+void CrashHandler::run()
+{
+ d->backtraceCollector.run(d->pid);
+}
+
+void CrashHandler::onError(const QString &errorMessage)
+{
+ d->dialog.setToFinalState();
+
+ QTextStream(stderr) << errorMessage;
+ const QString text = QLatin1String("There occured a problem providing the backtrace. "
+ "Please make sure to have the debugger \"gdb\" installed.\n");
+ d->dialog.appendDebugInfo(text);
+ d->dialog.appendDebugInfo(errorMessage);
+}
+
+void CrashHandler::onBacktraceChunk(const QString &chunk)
+{
+ d->dialog.appendDebugInfo(chunk);
+ QTextStream(stdout) << chunk;
+}
+
+void CrashHandler::onBacktraceFinished(const QString &backtrace)
+{
+ d->dialog.setToFinalState();
+
+ // Select first line of relevant thread.
+
+ // Example debugger output:
+ // ...
+ // [Current thread is 1 (Thread 0x7f1c33c79780 (LWP 975))]
+ // ...
+ // Thread 1 (Thread 0x7f1c33c79780 (LWP 975)):
+ // ...
+ QRegExp rx(QLatin1String("\\[Current thread is (\\d+)"));
+ const int pos = rx.indexIn(backtrace);
+ if (pos == -1)
+ return;
+ const QString threadNumber = rx.cap(1);
+ const QString textToSelect = QString::fromLatin1("Thread %1").arg(threadNumber);
+ d->dialog.selectLineWithContents(textToSelect);
+}
+
+void CrashHandler::openBugTracker()
+{
+ QDesktopServices::openUrl(QUrl(QLatin1String(URL_BUGTRACKER)));
+}
+
+bool CrashHandler::collectRestartAppData()
+{
+ const QString procDir = QString::fromLatin1("/proc/%1").arg(d->pid);
+
+ // Get command line.
+ // man 5 proc: /proc/[pid]/cmdline
+ // The command-line arguments appear in this file as a set of strings separated by
+ // null bytes ('\0'), with a further null byte after the last string.
+ const QString procCmdFileName = procDir + QLatin1String("/cmdline");
+ QList<QByteArray> commandLine = fileContents(procCmdFileName).split('\0');
+ if (commandLine.size() < 2) {
+ qWarning("%s: Unexpected format in file '%s'.\n", Q_FUNC_INFO, qPrintable(procCmdFileName));
+ return false;
+ }
+ commandLine.removeLast();
+ foreach (const QByteArray &item, commandLine)
+ d->restartAppCommandLine.append(QString::fromLatin1(item));
+
+ // Get environment.
+ // man 5 proc: /proc/[pid]/environ
+ // The entries are separated by null bytes ('\0'), and there may be a null byte at the end.
+ const QString procEnvFileName = procDir + QLatin1String("/environ");
+ QList<QByteArray> environment = fileContents(procEnvFileName).split('\0');
+ if (environment.isEmpty()) {
+ qWarning("%s: Unexpected format in file '%s'.\n", Q_FUNC_INFO, qPrintable(procEnvFileName));
+ return false;
+ }
+ if (environment.last().isEmpty())
+ environment.removeLast();
+ foreach (const QByteArray &item, environment)
+ d->restartAppEnvironment.append(QString::fromLatin1(item));
+
+ return true;
+}
+
+void CrashHandler::runCommand(QStringList commandLine, QStringList environment, WaitMode waitMode)
+{
+ // TODO: If QTBUG-2284 is resolved, use QProcess::startDetached() here.
+ // We can't use QProcess::startDetached because of bug
+ //
+ // QTBUG-2284
+ // QProcess::startDetached does not support setting an environment for the new process
+ //
+ // therefore, we use fork-exec.
+
+ pid_t pid = fork();
+ switch (pid) {
+ case -1: // error
+ qFatal("%s: fork() failed.", Q_FUNC_INFO);
+ break;
+ case 0: { // child
+ CExecList argv(commandLine);
+ CExecList envp(environment);
+ qDebug("Running\n");
+ for (int i = 0; argv[i]; ++i)
+ qDebug(" %s", argv[i]);
+ if (!environment.isEmpty()) {
+ qDebug("\nwith environment:\n");
+ for (int i = 0; envp[i]; ++i)
+ qDebug(" %s", envp[i]);
+ }
+
+ // The standards pipes must be open, otherwise the application will
+ // receive a SIGPIPE as soon as these are used.
+ if (freopen("/dev/null", "r", stdin) == 0)
+ qFatal("%s: freopen() failed for stdin: %s.\n", Q_FUNC_INFO, strerror(errno));
+ if (freopen("/dev/null", "w", stdout) == 0)
+ qFatal("%s: freopen() failed for stdout: %s.\n", Q_FUNC_INFO, strerror(errno));
+ if (freopen("/dev/null", "w", stderr) == 0)
+ qFatal("%s: freopen() failed for stderr: %s.\n.", Q_FUNC_INFO, strerror(errno));
+
+ if (environment.isEmpty())
+ execv(argv[0], argv.data());
+ else
+ execve(argv[0], argv.data(), envp.data());
+ _exit(EXIT_FAILURE);
+ } default: // parent
+ if (waitMode == WaitForExit) {
+ while (true) {
+ int status;
+ if (waitpid(pid, &status, 0) == -1) {
+ if (errno == EINTR) // Signal handler of QProcess for SIGCHLD was triggered.
+ continue;
+ perror("waitpid() failed unexpectedly");
+ }
+ if (WIFEXITED(status)) {
+ qDebug("Child exited with exit code %d.", WEXITSTATUS(status));
+ break;
+ } else if (WIFSIGNALED(status)) {
+ qDebug("Child terminated by signal %d.", WTERMSIG(status));
+ break;
+ }
+ }
+ }
+ break;
+ }
+}
+
+void CrashHandler::restartApplication()
+{
+ runCommand(d->restartAppCommandLine, d->restartAppEnvironment, DontWaitForExit);
+}
+
+void CrashHandler::debugApplication()
+{
+ // User requested to debug the app while our debugger is running.
+ if (d->backtraceCollector.isRunning()) {
+ if (!d->dialog.runDebuggerWhileBacktraceNotFinished())
+ return;
+ if (d->backtraceCollector.isRunning()) {
+ d->backtraceCollector.disconnect();
+ d->backtraceCollector.kill();
+ d->dialog.setToFinalState();
+ d->dialog.appendDebugInfo(tr("\n\nCollecting backtrace aborted by user."));
+ QCoreApplication::processEvents(); // Show the last appended output immediately.
+ }
+ }
+
+ // Prepare command.
+ QString executable = d->creatorInPath;
+ if (!d->restartAppCommandLine.isEmpty())
+ executable = d->restartAppCommandLine.at(0);
+ const QStringList commandLine = QStringList()
+ << executable
+ << QLatin1String("-debug")
+ << QString::number(d->pid);
+
+ QStringList environment;
+ if (!d->restartAppEnvironment.isEmpty())
+ environment = d->restartAppEnvironment;
+
+ // The UI is blocked/frozen anyway, so hide the dialog while debugging.
+ d->dialog.hide();
+ runCommand(commandLine, environment, WaitForExit);
+ d->dialog.show();
+}
diff --git a/src/tools/qtcreatorcrashhandler/crashhandler.h b/src/tools/qtcreatorcrashhandler/crashhandler.h
new file mode 100644
index 0000000000..bf4c1991da
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandler.h
@@ -0,0 +1,69 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CRASHHANDLER_H
+#define CRASHHANDLER_H
+
+#include <QObject>
+
+QT_BEGIN_NAMESPACE
+class QString;
+QT_END_NAMESPACE
+
+class ApplicationInfo;
+class CrashHandlerPrivate;
+
+class CrashHandler : public QObject
+{
+ Q_OBJECT
+public:
+ explicit CrashHandler(pid_t pid, const QString &signalName, QObject *parent = 0);
+ ~CrashHandler();
+
+ void run();
+
+public slots:
+ void onError(const QString &errorMessage);
+ void onBacktraceChunk(const QString &chunk);
+ void onBacktraceFinished(const QString &backtrace);
+
+ void openBugTracker();
+ void restartApplication();
+ void debugApplication();
+
+private:
+ bool collectRestartAppData();
+
+ enum WaitMode { WaitForExit, DontWaitForExit };
+ static void runCommand(QStringList commandLine, QStringList environment, WaitMode waitMode);
+
+ CrashHandlerPrivate *d;
+};
+
+#endif // CRASHHANDLER_H
diff --git a/src/tools/qtcreatorcrashhandler/crashhandlerdialog.cpp b/src/tools/qtcreatorcrashhandler/crashhandlerdialog.cpp
new file mode 100644
index 0000000000..5d23255753
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandlerdialog.cpp
@@ -0,0 +1,180 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "crashhandler.h"
+#include "crashhandlerdialog.h"
+#include "ui_crashhandlerdialog.h"
+#include "utils.h"
+
+#include <app/app_version.h>
+#include <utils/checkablemessagebox.h>
+
+#include <QClipboard>
+#include <QIcon>
+#include <QSettings>
+
+static const char SettingsApplication[] = "QtCreator";
+static const char SettingsKeySkipWarningAbortingBacktrace[]
+ = "CrashHandler/SkipWarningAbortingBacktrace";
+
+CrashHandlerDialog::CrashHandlerDialog(CrashHandler *handler, const QString &signalName,
+ QWidget *parent) :
+ QDialog(parent),
+ m_crashHandler(handler),
+ m_ui(new Ui::CrashHandlerDialog)
+{
+ m_ui->setupUi(this);
+ m_ui->introLabel->setTextFormat(Qt::RichText);
+ m_ui->introLabel->setOpenExternalLinks(true);
+ m_ui->debugInfoEdit->setReadOnly(true);
+ m_ui->progressBar->setMinimum(0);
+ m_ui->progressBar->setMaximum(0);
+
+ const QStyle * const style = QApplication::style();
+ m_ui->closeButton->setIcon(style->standardIcon(QStyle::SP_DialogCloseButton));
+
+ const int iconSize = style->pixelMetric(QStyle::PM_MessageBoxIconSize, 0);
+ QIcon icon = style->standardIcon(QStyle::SP_MessageBoxCritical);
+ m_ui->iconLabel->setPixmap(icon.pixmap(iconSize, iconSize));
+
+ connect(m_ui->copyToClipBoardButton, SIGNAL(clicked()), this, SLOT(copyToClipboardClicked()));
+ connect(m_ui->reportBugButton, SIGNAL(clicked()), m_crashHandler, SLOT(openBugTracker()));
+ connect(m_ui->debugAppButton, SIGNAL(clicked()), m_crashHandler, SLOT(debugApplication()));
+ connect(m_ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));
+
+ setApplicationInfo(signalName);
+}
+
+CrashHandlerDialog::~CrashHandlerDialog()
+{
+ delete m_ui;
+}
+
+bool CrashHandlerDialog::runDebuggerWhileBacktraceNotFinished()
+{
+ // Check settings.
+ QSettings settings(QSettings::IniFormat, QSettings::UserScope,
+ QLatin1String(Core::Constants::IDE_SETTINGSVARIANT_STR),
+ QLatin1String(SettingsApplication));
+ if (settings.value(QLatin1String(SettingsKeySkipWarningAbortingBacktrace), false).toBool())
+ return true;
+
+ // Ask user.
+ const QString title = tr("Run Debugger And Abort Collecting Backtrace?");
+ const QString message = tr(
+ "<html><head/><body>"
+ "<p><b>Run the debugger and abort collecting backtrace?</b></p>"
+ "<p>You have requested to run the debugger while collecting the backtrace was not "
+ "finished.</p>"
+ "</body></html>");
+ const QString checkBoxText = tr("Do not &ask again.");
+ bool checkBoxSetting = false;
+ const QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(this,
+ title, message, checkBoxText, &checkBoxSetting,
+ QDialogButtonBox::Yes|QDialogButtonBox::No, QDialogButtonBox::No);
+ if (checkBoxSetting)
+ settings.setValue(QLatin1String(SettingsKeySkipWarningAbortingBacktrace), checkBoxSetting);
+
+ return button == QDialogButtonBox::Yes;
+}
+
+void CrashHandlerDialog::setToFinalState()
+{
+ m_ui->progressBar->hide();
+ m_ui->copyToClipBoardButton->setEnabled(true);
+ m_ui->reportBugButton->setEnabled(true);
+}
+
+void CrashHandlerDialog::disableRestartAppCheckBox()
+{
+ m_ui->restartAppCheckBox->setDisabled(true);
+}
+
+void CrashHandlerDialog::disableDebugAppButton()
+{
+ m_ui->debugAppButton->setDisabled(true);
+}
+
+void CrashHandlerDialog::setApplicationInfo(const QString &signalName)
+{
+ const QString ideName = QLatin1String("Qt Creator");
+ const QString title = tr("%1 has closed unexpectedly (Signal \"%2\")").arg(ideName, signalName);
+ const QString introLabelContents = tr(
+ "<p><b>%1.</b></p>"
+ "<p>Please file a <a href='%2'>bug report</a> with the debug information provided below.</p>")
+ .arg(title, QLatin1String(URL_BUGTRACKER));
+ m_ui->introLabel->setText(introLabelContents);
+ setWindowTitle(title);
+
+ QString revision;
+#ifdef IDE_REVISION
+ revision = tr(" from revision %1").arg(QString::fromLatin1(Core::Constants::IDE_REVISION_STR).left(10));
+#endif
+ const QString versionInformation = tr(
+ "%1 %2%3, built on %4 at %5, based on Qt %6 (%7 bit)\n")
+ .arg(ideName, QLatin1String(Core::Constants::IDE_VERSION_LONG), revision,
+ QLatin1String(__DATE__), QLatin1String(__TIME__), QLatin1String(QT_VERSION_STR),
+ QString::number(QSysInfo::WordSize));
+ m_ui->debugInfoEdit->append(versionInformation);
+}
+
+void CrashHandlerDialog::appendDebugInfo(const QString &chunk)
+{
+ m_ui->debugInfoEdit->append(chunk);
+}
+
+void CrashHandlerDialog::selectLineWithContents(const QString &text)
+{
+ // The selected line will be the first line visible.
+
+ // Go to end.
+ QTextCursor cursor = m_ui->debugInfoEdit->textCursor();
+ cursor.movePosition(QTextCursor::End);
+ m_ui->debugInfoEdit->setTextCursor(cursor);
+
+ // Find text by searching backwards.
+ m_ui->debugInfoEdit->find(text, QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);
+
+ // Highlight whole line.
+ cursor = m_ui->debugInfoEdit->textCursor();
+ cursor.select(QTextCursor::LineUnderCursor);
+ m_ui->debugInfoEdit->setTextCursor(cursor);
+}
+
+void CrashHandlerDialog::copyToClipboardClicked()
+{
+ QApplication::clipboard()->setText(m_ui->debugInfoEdit->toPlainText());
+}
+
+void CrashHandlerDialog::close()
+{
+ if (m_ui->restartAppCheckBox->isEnabled() && m_ui->restartAppCheckBox->isChecked())
+ m_crashHandler->restartApplication();
+ qApp->quit();
+}
diff --git a/src/tools/qtcreatorcrashhandler/crashhandlerdialog.h b/src/tools/qtcreatorcrashhandler/crashhandlerdialog.h
new file mode 100644
index 0000000000..fc9ff7921a
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandlerdialog.h
@@ -0,0 +1,71 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CRASHHANDLERDIALOG_H
+#define CRASHHANDLERDIALOG_H
+
+#include <QDialog>
+
+QT_BEGIN_NAMESPACE
+class QString;
+namespace Ui {
+class CrashHandlerDialog;
+}
+QT_END_NAMESPACE
+
+class CrashHandler;
+
+class CrashHandlerDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit CrashHandlerDialog(CrashHandler *handler, const QString &signalName,
+ QWidget *parent = 0);
+ ~CrashHandlerDialog();
+
+public:
+ void setApplicationInfo(const QString &signalName);
+ void appendDebugInfo(const QString &chunk);
+ void selectLineWithContents(const QString &text);
+ void setToFinalState();
+ void disableRestartAppCheckBox();
+ void disableDebugAppButton();
+ bool runDebuggerWhileBacktraceNotFinished();
+
+private slots:
+ void copyToClipboardClicked();
+ void close();
+
+private:
+ CrashHandler *m_crashHandler;
+ Ui::CrashHandlerDialog *m_ui;
+};
+
+#endif // CRASHHANDLERDIALOG_H
diff --git a/src/tools/qtcreatorcrashhandler/crashhandlerdialog.ui b/src/tools/qtcreatorcrashhandler/crashhandlerdialog.ui
new file mode 100644
index 0000000000..9a7b67a003
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandlerdialog.ui
@@ -0,0 +1,147 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>CrashHandlerDialog</class>
+ <widget class="QDialog" name="CrashHandlerDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>600</width>
+ <height>800</height>
+ </rect>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>500</width>
+ <height>300</height>
+ </size>
+ </property>
+ <property name="windowTitle">
+ <string>Dialog</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout_2">
+ <property name="sizeConstraint">
+ <enum>QLayout::SetDefaultConstraint</enum>
+ </property>
+ <item>
+ <widget class="QLabel" name="iconLabel">
+ <property name="text">
+ <string>Icon</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QLabel" name="introLabel">
+ <property name="text">
+ <string>Some useful information here...</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer_2">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="QProgressBar" name="progressBar">
+ <property name="value">
+ <number>24</number>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QTextEdit" name="debugInfoEdit"/>
+ </item>
+ <item alignment="Qt::AlignRight">
+ <widget class="QCheckBox" name="restartAppCheckBox">
+ <property name="text">
+ <string>&amp;Restart Qt Creator on close</string>
+ </property>
+ <property name="checked">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QPushButton" name="copyToClipBoardButton">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="toolTip">
+ <string>Copy the whole contents to clipboard.</string>
+ </property>
+ <property name="text">
+ <string>C&amp;opy to clipboard</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="reportBugButton">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="toolTip">
+ <string>Open the bug tracker web site.</string>
+ </property>
+ <property name="text">
+ <string>Report this &amp;bug</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <spacer name="horizontalSpacer">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QPushButton" name="debugAppButton">
+ <property name="enabled">
+ <bool>true</bool>
+ </property>
+ <property name="toolTip">
+ <string>Debug the application with a new instance of Qt Creator. During debugging the crash handler will be hidden.</string>
+ </property>
+ <property name="text">
+ <string>Attach and &amp;Debug</string>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QPushButton" name="closeButton">
+ <property name="toolTip">
+ <string>Quit the handler and the crashed application.</string>
+ </property>
+ <property name="text">
+ <string>&amp;Close</string>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp b/src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp
new file mode 100644
index 0000000000..cc48afa731
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandlersetup.cpp
@@ -0,0 +1,134 @@
+/**************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "crashhandlersetup.h"
+
+#include <QtGlobal>
+
+#if !defined(QT_NO_DEBUG) && defined(Q_OS_LINUX)
+#define BUILD_CRASH_HANDLER
+#endif
+
+#ifdef BUILD_CRASH_HANDLER
+
+#include <QApplication>
+#include <QDebug>
+#include <QString>
+
+#include <stdlib.h>
+
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#ifdef Q_WS_X11
+#include <qx11info_x11.h>
+#include <X11/Xlib.h>
+#endif
+
+static const char *crashHandlerPathC;
+static void *signalHandlerStack;
+
+extern "C" void signalHandler(int signal)
+{
+#ifdef Q_WS_X11
+ // Kill window since it's frozen anyway.
+ if (QX11Info::display())
+ close(ConnectionNumber(QX11Info::display()));
+#endif
+ pid_t pid = fork();
+ switch (pid) {
+ case -1: // error
+ break;
+ case 0: // child
+ execl(crashHandlerPathC, crashHandlerPathC, strsignal(signal), (char *) 0);
+ _exit(EXIT_FAILURE);
+ default: // parent
+ waitpid(pid, 0, 0);
+ _exit(EXIT_FAILURE);
+ break;
+ }
+}
+#endif // BUILD_CRASH_HANDLER
+
+void setupCrashHandler()
+{
+#ifdef BUILD_CRASH_HANDLER
+ const QString crashHandlerPath = qApp->applicationDirPath()
+ + QLatin1String("/qtcreator_crash_handler");
+ crashHandlerPathC = qstrdup(qPrintable(crashHandlerPath));
+
+ // Setup an alternative stack for the signal handler. This way we are able to handle SIGSEGV
+ // even if the normal process stack is exhausted.
+ stack_t ss;
+ ss.ss_sp = signalHandlerStack = malloc(SIGSTKSZ); // Usual requirements for alternative signal stack.
+ if (ss.ss_sp == 0) {
+ qWarning("Warning: Could not allocate space for alternative signal stack (%s).", Q_FUNC_INFO);
+ return;
+ }
+ ss.ss_size = SIGSTKSZ;
+ ss.ss_flags = 0;
+ if (sigaltstack(&ss, 0) == -1) {
+ qWarning("Warning: Failed to set alternative signal stack (%s).", Q_FUNC_INFO);
+ return;
+ }
+
+ // Install signal handler for calling the crash handler.
+ struct sigaction sa;
+ if (sigemptyset(&sa.sa_mask) == -1) {
+ qWarning("Warning: Failed to empty signal set (%s).", Q_FUNC_INFO);
+ return;
+ }
+ sa.sa_handler = &signalHandler;
+ // SA_RESETHAND - Restore signal action to default after signal handler has been called.
+ // SA_NODEFER - Don't block the signal after it was triggered (otherwise blocked signals get
+ // inherited via fork() and execve()). Without this the signal will not be delivered to the
+ // restarted Qt Creator.
+ // SA_ONSTACK - Use alternative stack.
+ sa.sa_flags = SA_RESETHAND | SA_NODEFER | SA_ONSTACK;
+ const int signalsToHandle[] = { SIGILL, SIGFPE, SIGSEGV, SIGBUS, 0 };
+ for (int i = 0; signalsToHandle[i]; ++i) {
+ if (sigaction(signalsToHandle[i], &sa, 0) == -1 ) {
+ qWarning("Warning: Failed to install signal handler for signal \"%s\" (%s).",
+ strsignal(signalsToHandle[i]), Q_FUNC_INFO);
+ }
+ }
+#endif // BUILD_CRASH_HANDLER
+}
+
+void cleanupCrashHandler()
+{
+#ifdef BUILD_CRASH_HANDLER
+ delete[] crashHandlerPathC;
+ free(signalHandlerStack);
+#endif
+}
diff --git a/src/tools/qtcreatorcrashhandler/crashhandlersetup.h b/src/tools/qtcreatorcrashhandler/crashhandlersetup.h
new file mode 100644
index 0000000000..02c50ef230
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/crashhandlersetup.h
@@ -0,0 +1,36 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#ifndef CRASHHANDLERSETUP_H
+#define CRASHHANDLERSETUP_H
+
+void setupCrashHandler();
+void cleanupCrashHandler();
+
+#endif // CRASHHANDLERSETUP_H
diff --git a/src/plugins/qmldesigner/designercore/include/metainfoparser.h b/src/tools/qtcreatorcrashhandler/main.cpp
index 9b6d8a7f99..5f4002a19f 100644
--- a/src/plugins/qmldesigner/designercore/include/metainfoparser.h
+++ b/src/tools/qtcreatorcrashhandler/main.cpp
@@ -27,43 +27,42 @@
**
****************************************************************************/
-#ifndef METAINFOPARSER_H
-#define METAINFOPARSER_H
+#include "crashhandler.h"
+#include "utils.h"
-#include "corelib_global.h"
-#include <QXmlStreamReader>
-#include <QString>
+#include <QApplication>
#include <QFile>
-#include <metainfo.h>
-
-namespace QmlDesigner {
-
-class ItemLibraryEntry;
-
-namespace Internal {
+#include <QProcess>
+#include <QString>
+#include <QStyle>
+#include <QTextStream>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
-class TEST_CORESHARED_EXPORT MetaInfoParser
+// Called by signal handler of qtcreator.
+// Usage: $0 <name of signal causing the crash>
+int main(int argc, char *argv[])
{
-public:
- MetaInfoParser(const MetaInfo &metaInfo);
-
- void parseFile(const QString &path);
+ QApplication app(argc, argv);
+ app.setApplicationName(QLatin1String(APPLICATION_NAME));
+ app.setWindowIcon(QApplication::style()->standardIcon(QStyle::SP_MessageBoxCritical));
-protected:
- void errorHandling(QXmlStreamReader &reader, QFile &file);
- void tokenHandler(QXmlStreamReader &reader);
- void metaInfoHandler(QXmlStreamReader &reader);
- void handleMetaInfoElement(QXmlStreamReader &reader);
- void handleNodeElement(QXmlStreamReader &reader);
- void handleNodeItemLibraryEntryElement(QXmlStreamReader &reader, const QString &className, const QIcon &icon);
- void handleItemLibraryEntryPropertyElement(QXmlStreamReader &reader, ItemLibraryEntry &itemLibraryEntry);
- void handleItemLibraryEntryQmlElement(QXmlStreamReader &reader, ItemLibraryEntry &itemLibraryEntry);
+ // Check usage.
+ Q_PID parentPid = getppid();
+ QString parentExecutable = QFile::symLinkTarget(QString::fromLatin1("/proc/%1/exe")
+ .arg(QString::number(parentPid)));
+ if (argc > 2 || !parentExecutable.contains(QLatin1String("qtcreator"))) {
+ QTextStream err(stderr);
+ err << QString::fromLatin1("This crash handler will be called by Qt Creator itself. "
+ "Do not call this manually.\n");
+ return EXIT_FAILURE;
+ }
-private:
- MetaInfo m_metaInfo;
-};
+ // Run.
+ CrashHandler *crashHandler = new CrashHandler(parentPid, app.arguments().at(1));
+ crashHandler->run();
+ return app.exec();
}
-}
-#endif // METAINFOPARSER_H
diff --git a/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.pro b/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.pro
new file mode 100644
index 0000000000..bfcb41e303
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.pro
@@ -0,0 +1,31 @@
+include(../../../qtcreator.pri)
+
+TARGET = qtcreator_crash_handler
+DESTDIR = $$IDE_BIN_PATH
+
+CONFIG -= app_bundle
+TEMPLATE = app
+
+SOURCES += \
+ main.cpp \
+ backtracecollector.cpp \
+ crashhandlerdialog.cpp \
+ crashhandler.cpp \
+ utils.cpp \
+ ../../libs/utils/checkablemessagebox.cpp \
+ ../../libs/utils/environment.cpp
+
+
+HEADERS += \
+ backtracecollector.h \
+ crashhandlerdialog.h \
+ crashhandler.h \
+ utils.h \
+ ../../libs/utils/checkablemessagebox.h \
+ ../../libs/utils/environment.h
+
+FORMS += \
+ crashhandlerdialog.ui
+
+target.path = /bin
+INSTALLS += target
diff --git a/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs b/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs
new file mode 100644
index 0000000000..35d6187d56
--- /dev/null
+++ b/src/tools/qtcreatorcrashhandler/qtcreatorcrashhandler.qbs
@@ -0,0 +1,33 @@
+import qbs.base 1.0
+import "../QtcTool.qbs" as QtcTool
+
+QtcTool {
+ name: "qtcreator_crash_handler"
+ condition: qbs.targetOS == "linux" && qbs.buildVariant == "debug"
+
+ cpp.includePaths: [
+ buildDirectory,
+ "../../libs"
+ ]
+
+ Depends { name: "cpp" }
+ Depends { name: "Qt.widgets" }
+ Depends { name: "app_version_header" }
+
+ files: [
+ "../../libs/utils/checkablemessagebox.cpp",
+ "../../libs/utils/checkablemessagebox.h",
+ "../../libs/utils/environment.cpp",
+ "../../libs/utils/environment.h",
+ "backtracecollector.cpp",
+ "backtracecollector.h",
+ "crashhandler.cpp",
+ "crashhandler.h",
+ "crashhandlerdialog.cpp",
+ "crashhandlerdialog.h",
+ "crashhandlerdialog.ui",
+ "main.cpp",
+ "utils.cpp",
+ "utils.h"
+ ]
+}
diff --git a/tests/auto/icheckbuild/tst_icheckbuild.cpp b/src/tools/qtcreatorcrashhandler/utils.cpp
index c3140dfc79..bb885e3ce9 100644
--- a/tests/auto/icheckbuild/tst_icheckbuild.cpp
+++ b/src/tools/qtcreatorcrashhandler/utils.cpp
@@ -27,23 +27,17 @@
**
****************************************************************************/
-#include <QtTest>
-#include "ichecklib.h"
-#include <QDebug>
-
-class tst_icheckbuild : public QObject
-{
- Q_OBJECT
+#include "utils.h"
-private slots:
- void doTests();
-};
+#include <QDebug>
+#include <QFile>
-void tst_icheckbuild::doTests()
+QByteArray fileContents(const QString &filePath)
{
- qDebug() << "icheck build was successful";
+ QFile file(filePath);
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ qWarning("Warning: Could not open '%s'.", qPrintable(filePath));
+ return QByteArray();
+ }
+ return file.readAll();
}
-
-QTEST_MAIN(tst_icheckbuild)
-
-#include "tst_icheckbuild.moc"
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/QmlComponent01.qml b/src/tools/qtcreatorcrashhandler/utils.h
index 863420f147..e136a276e8 100644
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/QmlComponent01.qml
+++ b/src/tools/qtcreatorcrashhandler/utils.h
@@ -27,19 +27,15 @@
**
****************************************************************************/
-import Qt 4.7
+#ifndef UTILS_H
+#define UTILS_H
-Rectangle {
- color: "#ddffdd"
+#include <QByteArray>
+#include <QString>
- Image {
- source: "apple.svg"
- anchors.right: parent.right
- anchors.bottom: parent.bottom
- }
+const char APPLICATION_NAME[] = "Qt Creator Crash Handler";
+const char URL_BUGTRACKER[] = "https://bugreports.qt-project.org/";
- Text {
- text: "QmlComponent01"
- font.pointSize: 14
- }
-}
+QByteArray fileContents(const QString &filePath);
+
+#endif // UTILS_H
diff --git a/src/tools/qtcreatorwidgets/customwidgets.cpp b/src/tools/qtcreatorwidgets/customwidgets.cpp
index 8250f6b2d8..56dc7f7314 100644
--- a/src/tools/qtcreatorwidgets/customwidgets.cpp
+++ b/src/tools/qtcreatorwidgets/customwidgets.cpp
@@ -303,11 +303,10 @@ DetailsWidgetContainerExtension::DetailsWidgetContainerExtension(Utils::DetailsW
void DetailsWidgetContainerExtension::addWidget(QWidget *widget)
{
- if (m_detailsWidget->widget()) {
+ if (m_detailsWidget->widget())
qWarning("Cannot add 2nd child to DetailsWidget");
- } else {
+ else
m_detailsWidget->setWidget(widget);
- }
}
int DetailsWidgetContainerExtension::count() const
diff --git a/src/tools/qtpromaker/main.cpp b/src/tools/qtpromaker/main.cpp
index b10b5646b0..622466df03 100644
--- a/src/tools/qtpromaker/main.cpp
+++ b/src/tools/qtpromaker/main.cpp
@@ -58,7 +58,7 @@ static const char *defaultExtensions[] =
typedef QHash<QByteArray, QByteArray> Extensions;
-static QByteArray proExtension = "pro";
+static QString proExtension = QLatin1String("pro");
class FileClass
@@ -67,7 +67,7 @@ public:
FileClass() {}
//! suffixes is a comma separated string of extensions.
- FileClass(const QByteArray &suffixes, const QString &varName)
+ FileClass(const QByteArray &suffixes, const QByteArray &varName)
: m_suffixes(',' + suffixes + ','), m_varName(varName)
{}
@@ -111,7 +111,7 @@ private:
typedef QMap<QString, Dummy> Files;
QByteArray m_suffixes;
- QString m_varName;
+ QByteArray m_varName;
Files m_files;
};
@@ -194,18 +194,18 @@ void Project::handleItem(const QString &item)
void Project::handleBinary(const QString &item)
{
QStringList args;
- args.append("--batch-silent");
- args.append("--nx");
- args.append("--quiet");
- args.append("-i");
- args.append("mi");
- args.append("--se=" + item);
- args.append("-ex");
- args.append("interpreter-exec mi -file-list-exec-source-files");
- args.append("-ex");
- args.append("quit");
+ args.append(QLatin1String("--batch-silent"));
+ args.append(QLatin1String("--nx"));
+ args.append(QLatin1String("--quiet"));
+ args.append(QLatin1String("-i"));
+ args.append(QLatin1String("mi"));
+ args.append(QLatin1String("--se=") + item);
+ args.append(QLatin1String("-ex"));
+ args.append(QLatin1String("interpreter-exec mi -file-list-exec-source-files"));
+ args.append(QLatin1String("-ex"));
+ args.append(QLatin1String("quit"));
QProcess proc;
- proc.start("gdb", args);
+ proc.start(QLatin1String("gdb"), args);
if (!proc.waitForStarted()) {
qDebug() << "COULD NOT START";
return;
@@ -222,11 +222,11 @@ void Project::handleBinary(const QString &item)
QString input = QString::fromLatin1(ba, ba.size());
// ^done,files=[{file="<<C++-namespaces>>",{file=...,fullname=}
// "}] (gdb)
- int first = input.indexOf('{');
- input = input.mid(first, input.lastIndexOf('}') - first);
- foreach (QString item, input.split("},{")) {
+ int first = input.indexOf(QLatin1Char('{'));
+ input = input.mid(first, input.lastIndexOf(QLatin1Char('}')) - first);
+ foreach (QString item, input.split(QLatin1String("},{"))) {
//qDebug() << "ITEM: " << item;
- int full = item.indexOf(",fullname=\"");
+ int full = item.indexOf(QLatin1String(",fullname=\""));
if (full != -1)
item = item.mid(full + 11);
else
@@ -249,7 +249,7 @@ void Project::handleDir(const QString &item)
it.next();
const QFileInfo fi = it.fileInfo();
if (fi.isDir()) {
- if (fi.fileName() == ".." || fi.fileName() == ".")
+ if (fi.fileName() == QLatin1String("..") || fi.fileName() == QLatin1String("."))
continue;
const QString filePath = fi.filePath();
if (m_treeLevel < targetDepth) {
@@ -280,21 +280,17 @@ void Project::writeProFile()
QFile file(m_outputFileName);
if (file.exists()) {
if (!forceOverWrite) {
- qWarning("%s", qPrintable(QString(
- "%1 not overwritten. Use -f if this should be done.")
- .arg(m_outputFileName)));
+ qWarning("%s not overwritten. Use -f if this should be done.", qPrintable(m_outputFileName));
return;
}
if (!file.remove()) {
- qWarning("%s", qPrintable(QString(
- "%1 could not be deleted.").arg(m_outputFileName)));
+ qWarning("%s could not be deleted.", qPrintable(m_outputFileName));
return;
}
}
if (!file.open(QIODevice::WriteOnly)) {
- qWarning("%s", qPrintable(QString(
- "%1 cannot be written").arg(m_outputFileName)));
+ qWarning("%s cannot be written", qPrintable(m_outputFileName));
return;
}
@@ -359,7 +355,7 @@ int main(int argc, char *argv[])
// Override by command line.
for (int i = 1, n = args.size(); i < n; ++i) {
const QString arg = args.at(i);
- if (arg == "-h" || arg == "--help" || arg == "-help") {
+ if (arg == QLatin1String("-h") || arg == QLatin1String("--help") || arg == QLatin1String("-help")) {
qWarning() << "Usage: " << qPrintable(args.at(0))
<< " [-f] [-o out.pro] [dir...]"
<< "\n\n"
@@ -373,14 +369,14 @@ int main(int argc, char *argv[])
}
bool handled = true;
- if (arg == "-f" || arg == "--force" || arg == "-force") {
+ if (arg == QLatin1String("-f") || arg == QLatin1String("--force") || arg == QLatin1String("-force")) {
forceOverWrite = true;
} else if (i < n - 1) {
- if (arg == "-o" || arg == "--output" || arg == "-output")
+ if (arg == QLatin1String("-o") || arg == QLatin1String("--output") || arg == QLatin1String("-output"))
outputFileName = args.at(++i);
- else if (arg == "-d" || arg == "--depth" || arg == "-depth")
+ else if (arg == QLatin1String("-d") || arg == QLatin1String("--depth") || arg == QLatin1String("-depth"))
targetDepth = args.at(++i).toInt();
- else if (arg == "-s" || arg == "--separator" || arg == "-separator")
+ else if (arg == QLatin1String("-s") || arg == QLatin1String("--separator") || arg == QLatin1String("-separator"))
subProjectSeparator = args.at(++i);
else
handled = false;
@@ -395,13 +391,12 @@ int main(int argc, char *argv[])
// Fallbacks.
if (paths.isEmpty()) {
QDir dir = QDir::currentPath();
- outputFileName = dir.dirName() + '.' + proExtension;
- paths.append(".");
+ outputFileName = dir.dirName() + QLatin1Char('.') + proExtension;
+ paths.append(QLatin1String("."));
}
- if (outputFileName.isEmpty()) {
- outputFileName = QDir(paths.at(0)).dirName() + '.' + proExtension;
- }
+ if (outputFileName.isEmpty())
+ outputFileName = QDir(paths.at(0)).dirName() + QLatin1Char('.') + proExtension;
if (targetDepth == -1)
targetDepth = 1000000; // "infinity"
diff --git a/src/tools/sdktool/addkitoperation.cpp b/src/tools/sdktool/addkitoperation.cpp
index 232f990d95..92982ee85f 100644
--- a/src/tools/sdktool/addkitoperation.cpp
+++ b/src/tools/sdktool/addkitoperation.cpp
@@ -364,11 +364,16 @@ QVariantMap AddKitOperation::addKit(const QVariantMap &map,
<< QLatin1String(DEBUGGER) << QLatin1String(DEBUGGER_ENGINE), QVariant(debuggerType));
data << KeyValuePair(QStringList() << kit << QLatin1String(DATA)
<< QLatin1String(DEBUGGER) << QLatin1String(DEBUGGER_BINARY), QVariant(debugger));
- data << KeyValuePair(QStringList() << kit << QLatin1String(DATA) << DEVICE_TYPE, QVariant(deviceType));
- data << KeyValuePair(QStringList() << kit << QLatin1String(DATA) << SYSROOT, QVariant(sysRoot));
- data << KeyValuePair(QStringList() << kit << QLatin1String(DATA) << TOOLCHAIN, QVariant(tc));
- data << KeyValuePair(QStringList() << kit << QLatin1String(DATA) << QT, QVariant(qtId));
- data << KeyValuePair(QStringList() << kit << QLatin1String(DATA) << MKSPEC, QVariant(mkspec));
+ data << KeyValuePair(QStringList() << kit << QLatin1String(DATA)
+ << QLatin1String(DEVICE_TYPE), QVariant(deviceType));
+ data << KeyValuePair(QStringList() << kit << QLatin1String(DATA)
+ << QLatin1String(SYSROOT), QVariant(sysRoot));
+ data << KeyValuePair(QStringList() << kit << QLatin1String(DATA)
+ << QLatin1String(TOOLCHAIN), QVariant(tc));
+ data << KeyValuePair(QStringList() << kit << QLatin1String(DATA)
+ << QLatin1String(QT), QVariant(qtId));
+ data << KeyValuePair(QStringList() << kit << QLatin1String(DATA)
+ << QLatin1String(MKSPEC), QVariant(mkspec));
data << KeyValuePair(QStringList() << QLatin1String(DEFAULT), QVariant(defaultKit));
data << KeyValuePair(QStringList() << QLatin1String(COUNT), QVariant(count + 1));
diff --git a/src/tools/sdktool/addqtoperation.cpp b/src/tools/sdktool/addqtoperation.cpp
index cd3f654e5c..1ab4b56c71 100644
--- a/src/tools/sdktool/addqtoperation.cpp
+++ b/src/tools/sdktool/addqtoperation.cpp
@@ -131,21 +131,17 @@ bool AddQtOperation::setArguments(const QStringList &args)
m_extra << pair;
}
- if (m_id.isEmpty()) {
+ if (m_id.isEmpty())
std::cerr << "Error no id was passed." << std::endl << std::endl;
- }
- if (m_displayName.isEmpty()) {
+ if (m_displayName.isEmpty())
std::cerr << "Error no display name was passed." << std::endl << std::endl;
- }
- if (m_qmake.isEmpty()) {
+ if (m_qmake.isEmpty())
std::cerr << "Error no qmake was passed." << std::endl << std::endl;
- }
- if (m_type.isEmpty()) {
+ if (m_type.isEmpty())
std::cerr << "Error no type was passed." << std::endl << std::endl;
- }
return !m_id.isEmpty() && !m_displayName.isEmpty() && !m_qmake.isEmpty() && !m_type.isEmpty();
}
diff --git a/src/tools/sdktool/main.cpp b/src/tools/sdktool/main.cpp
index 7662c0ea0c..ea926bbe85 100644
--- a/src/tools/sdktool/main.cpp
+++ b/src/tools/sdktool/main.cpp
@@ -144,7 +144,7 @@ int parseArguments(const QStringList &args, Settings *s, const QList<Operation *
return -1;
}
- return 1;
+ return 0;
}
int main(int argc, char *argv[])
diff --git a/src/tools/sdktool/rmkeysoperation.cpp b/src/tools/sdktool/rmkeysoperation.cpp
index 6a263d67ca..fcd356afa1 100644
--- a/src/tools/sdktool/rmkeysoperation.cpp
+++ b/src/tools/sdktool/rmkeysoperation.cpp
@@ -113,7 +113,7 @@ bool RmKeysOperation::test() const
return false;
data.clear();
- data.append("subkeys/subsubkeys");
+ data.append(QLatin1String("subkeys/subsubkeys"));
result = rmKeys(testMap, data);
if (result.count() != 3
@@ -131,7 +131,7 @@ bool RmKeysOperation::test() const
return false;
data.clear();
- data.append("subkeys/testbool");
+ data.append(QLatin1String("subkeys/testbool"));
result = rmKeys(testMap, data);
if (result.count() != 3
diff --git a/src/tools/sdktool/rmkitoperation.cpp b/src/tools/sdktool/rmkitoperation.cpp
index 80798f98cc..5fc00694d5 100644
--- a/src/tools/sdktool/rmkitoperation.cpp
+++ b/src/tools/sdktool/rmkitoperation.cpp
@@ -115,7 +115,7 @@ bool RmKitOperation::test() const
QVariantMap result = rmKit(map, QLatin1String("testId"));
if (result.count() != 4
- || !result.contains("Profile.0")
+ || !result.contains(QLatin1String("Profile.0"))
|| !result.contains(QLatin1String(COUNT))
|| result.value(QLatin1String(COUNT)).toInt() != 1
|| !result.contains(QLatin1String(DEFAULT))
@@ -130,7 +130,7 @@ bool RmKitOperation::test() const
result = rmKit(map, QLatin1String("testId2"));
if (result.count() != 4
- || !result.contains("Profile.0")
+ || !result.contains(QLatin1String("Profile.0"))
|| !result.contains(QLatin1String(COUNT))
|| result.value(QLatin1String(COUNT)).toInt() != 1
|| !result.contains(QLatin1String(DEFAULT))
diff --git a/src/tools/sdktool/sdktool.pro b/src/tools/sdktool/sdktool.pro
index ecb13e8d33..ea634465ff 100644
--- a/src/tools/sdktool/sdktool.pro
+++ b/src/tools/sdktool/sdktool.pro
@@ -7,6 +7,8 @@ CONFIG -= app_bundle
QT -= gui test
+isEmpty(PRECOMPILED_HEADER):PRECOMPILED_HEADER = $$PWD/../../shared/qtcreator_pch.h
+
SOURCES += \
main.cpp \
addkeysoperation.cpp \
diff --git a/src/tools/sdktool/sdktool.qbs b/src/tools/sdktool/sdktool.qbs
index 1ecea9e4c1..7d8e571a90 100644
--- a/src/tools/sdktool/sdktool.qbs
+++ b/src/tools/sdktool/sdktool.qbs
@@ -4,17 +4,16 @@ import "../QtcTool.qbs" as QtcTool
QtcTool {
name: "sdktool"
- cpp.includePaths: [buildDirectory]
- cpp.defines: base.concat([qbs.targetOS === "mac"
- ? 'DATA_PATH="."' : 'DATA_PATH="../share/qtcreator"'])
-
Depends { name: "cpp" }
Depends { name: "Qt.core" }
Depends { name: "Utils" }
Depends { name: "app_version_header" }
+ cpp.includePaths: "../../libs"
+ cpp.defines: base.concat([qbs.targetOS === "mac"
+ ? 'DATA_PATH="."' : 'DATA_PATH="../share/qtcreator"'])
+
files: [
- "main.cpp",
"addkeysoperation.cpp",
"addkeysoperation.h",
"addkitoperation.cpp",
@@ -29,8 +28,9 @@ QtcTool {
"findvalueoperation.h",
"getoperation.cpp",
"getoperation.h",
- "operation.h",
+ "main.cpp",
"operation.cpp",
+ "operation.h",
"rmkeysoperation.cpp",
"rmkeysoperation.h",
"rmkitoperation.cpp",
@@ -40,6 +40,6 @@ QtcTool {
"rmtoolchainoperation.cpp",
"rmtoolchainoperation.h",
"settings.cpp",
- "settings.h"
+ "settings.h",
]
}
diff --git a/src/tools/tools.pro b/src/tools/tools.pro
index 1f499584d5..3a48a7918f 100644
--- a/src/tools/tools.pro
+++ b/src/tools/tools.pro
@@ -2,6 +2,7 @@ TEMPLATE = subdirs
SUBDIRS = qtpromaker \
qmlpuppet \
+ ../plugins/cpaster/frontend \
sdktool
win32 {
@@ -21,5 +22,11 @@ win32 {
QT_BREAKPAD_ROOT_PATH = $$(QT_BREAKPAD_ROOT_PATH)
!isEmpty(QT_BREAKPAD_ROOT_PATH) {
SUBDIRS += qtcrashhandler
+} else {
+ linux-* {
+ # Build only in debug mode.
+ debug_and_release|CONFIG(debug, debug|release) {
+ SUBDIRS += qtcreatorcrashhandler
+ }
+ }
}
-
diff --git a/src/tools/valgrindfake/valgrindfake.pro b/src/tools/valgrindfake/valgrindfake.pro
index 1b26d7b93a..7bded95bb5 100644
--- a/src/tools/valgrindfake/valgrindfake.pro
+++ b/src/tools/valgrindfake/valgrindfake.pro
@@ -5,6 +5,8 @@ QT += network xml
macx:CONFIG -= app_bundle
+isEmpty(PRECOMPILED_HEADER):PRECOMPILED_HEADER = $$PWD/../../shared/qtcreator_pch.h
+
HEADERS += outputgenerator.h
SOURCES += main.cpp \
outputgenerator.cpp
diff --git a/src/tools/win64interrupt/win64interrupt.c b/src/tools/win64interrupt/win64interrupt.c
index b2de2ba67c..f2327f8a1c 100644
--- a/src/tools/win64interrupt/win64interrupt.c
+++ b/src/tools/win64interrupt/win64interrupt.c
@@ -35,7 +35,7 @@
#error Must target Windows NT 5.0.1 or later for DebugBreakProcess
#endif
-#include <Windows.h>
+#include <windows.h>
#include <stdio.h>
/* To debug break a 64bit application under Windows, you must call
diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro
index 4bb160e3d4..449876b36e 100644
--- a/tests/auto/auto.pro
+++ b/tests/auto/auto.pro
@@ -9,7 +9,6 @@ SUBDIRS += \
environment \
fakevim \
generichighlighter \
-# icheckbuild \
profilewriter \
ioutils \
qtcprocess \
diff --git a/tests/auto/cplusplus/ast/tst_ast.cpp b/tests/auto/cplusplus/ast/tst_ast.cpp
index 3b88e82a5e..e1da51d9c8 100644
--- a/tests/auto/cplusplus/ast/tst_ast.cpp
+++ b/tests/auto/cplusplus/ast/tst_ast.cpp
@@ -136,6 +136,16 @@ private slots:
void assignment_1();
void assignment_2();
+ // constructor declarations
+ void cpp_constructor_one_unamed_arg();
+ void cpp_constructor_one_unamed_arg_namespace();
+ void cpp_constructor_one_knowntype_arg();
+ void cpp_constructor_one_const_arg();
+ void cpp_constructor_one_ref_arg();
+ void cpp_constructor_one_named_arg();
+ void cpp_constructor_no_arg();
+ void cpp_constructor_multiple_args();
+
// objc++
void objc_simple_class();
void objc_attributes_followed_by_at_keyword();
@@ -1050,6 +1060,150 @@ void tst_AST::cpp_initializer_or_function_declaration()
QCOMPARE(param->type_specifier_list->value->asNamedTypeSpecifier()->name->asSimpleName()->identifier_token, 4U);
}
+void tst_AST::cpp_constructor_one_unamed_arg()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo(QString /*name*/) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
+void tst_AST::cpp_constructor_one_unamed_arg_namespace()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("Foo::QFileInfo::QFileInfo(QString /*name*/) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
+void tst_AST::cpp_constructor_one_named_arg()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo(QString name) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
+void tst_AST::cpp_constructor_one_knowntype_arg()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo(int /*name*/) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
+
+void tst_AST::cpp_constructor_one_const_arg()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo(const QString /*name*/) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
+void tst_AST::cpp_constructor_one_ref_arg()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo(QString & /*name*/) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
+void tst_AST::cpp_constructor_no_arg()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo() {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause == 0);
+}
+
+void tst_AST::cpp_constructor_multiple_args()
+{
+ QSharedPointer<TranslationUnit> unit(parseDeclaration("QFileInfo::QFileInfo(QString /*name*/, QString /*type*/) {}"));
+ AST *ast = unit->ast();
+ QVERIFY(ast != 0);
+
+ FunctionDefinitionAST *funDef = ast->asFunctionDefinition();
+ QVERIFY(funDef != 0);
+ QVERIFY(funDef->declarator != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list != 0);
+ QVERIFY(funDef->declarator->postfix_declarator_list->lastValue() != 0);
+
+ FunctionDeclaratorAST *funDecl = funDef->declarator->postfix_declarator_list->lastValue()->asFunctionDeclarator();
+ QVERIFY(funDecl != 0);
+ QVERIFY(funDecl->parameter_declaration_clause != 0);
+ QVERIFY(funDecl->parameter_declaration_clause->parameter_declaration_list != 0);
+}
+
void tst_AST::objc_simple_class()
{
QSharedPointer<TranslationUnit> unit(parseDeclaration("\n"
diff --git a/tests/auto/cplusplus/checksymbols/checksymbols.pro b/tests/auto/cplusplus/checksymbols/checksymbols.pro
new file mode 100644
index 0000000000..c7ea673be8
--- /dev/null
+++ b/tests/auto/cplusplus/checksymbols/checksymbols.pro
@@ -0,0 +1,4 @@
+include(../../qttest.pri)
+include(../shared/shared.pri)
+include(../../../../src/plugins/cpptools/cpptools.pri)
+SOURCES += tst_checksymbols.cpp
diff --git a/tests/auto/cplusplus/checksymbols/tst_checksymbols.cpp b/tests/auto/cplusplus/checksymbols/tst_checksymbols.cpp
new file mode 100644
index 0000000000..ff43c68e3b
--- /dev/null
+++ b/tests/auto/cplusplus/checksymbols/tst_checksymbols.cpp
@@ -0,0 +1,452 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <CppDocument.h>
+#include <pp.h>
+
+#include <cpptools/cppchecksymbols.h>
+#include <cpptools/cppsemanticinfo.h>
+#include <texteditor/semantichighlighter.h>
+#include <utils/fileutils.h>
+
+#include <QDebug>
+#include <QDir>
+#include <QList>
+#include <QtTest>
+
+/*!
+ Tests CheckSymbols, the "data provider" of the semantic highlighter.
+ */
+
+using namespace CPlusPlus;
+using namespace CppTools;
+
+typedef CheckSymbols::Use Use;
+typedef CheckSymbols::UseKind UseKind;
+
+static QString useKindToString(UseKind useKind)
+{
+ switch (useKind) {
+ case SemanticInfo::Unknown:
+ return QLatin1String("SemanticInfo::Unknown");
+ case SemanticInfo::TypeUse:
+ return QLatin1String("SemanticInfo::TypeUse");
+ case SemanticInfo::LocalUse:
+ return QLatin1String("SemanticInfo::LocalUse");
+ case SemanticInfo::FieldUse:
+ return QLatin1String("SemanticInfo::FieldUse");
+ case SemanticInfo::EnumerationUse:
+ return QLatin1String("SemanticInfo::EnumerationUse");
+ case SemanticInfo::VirtualMethodUse:
+ return QLatin1String("SemanticInfo::VirtualMethodUse");
+ case SemanticInfo::LabelUse:
+ return QLatin1String("SemanticInfo::LabelUse");
+ case SemanticInfo::MacroUse:
+ return QLatin1String("SemanticInfo::MacroUse");
+ case SemanticInfo::FunctionUse:
+ return QLatin1String("SemanticInfo::FunctionUse");
+ case SemanticInfo::PseudoKeywordUse:
+ return QLatin1String("SemanticInfo::PseudoKeywordUse");
+ default:
+ return QLatin1String("Unknown Kind");
+ }
+}
+
+// The following two functions are "enhancements" for QCOMPARE().
+namespace QTest {
+
+bool operator==(const Use& lhs, const Use& rhs)
+{
+ return
+ lhs.line == rhs.line &&
+ lhs.column == rhs.column &&
+ lhs.length == rhs.length &&
+ lhs.kind == rhs.kind;
+}
+
+template<>
+char *toString(const Use &use)
+{
+ QByteArray ba = "Use(";
+ ba += QByteArray::number(use.line);
+ ba += ", " + QByteArray::number(use.column);
+ ba += ", " + QByteArray::number(use.length);
+ ba += ", " + useKindToString(static_cast<UseKind>(use.kind)).toLatin1();
+ ba += ")";
+ return qstrdup(ba.data());
+}
+
+} // namespace QTest
+
+namespace {
+
+class TestData
+{
+public:
+ Snapshot snapshot;
+ Document::Ptr document;
+
+ TestData(const QByteArray &source,
+ Document::ParseMode parseMode = Document::ParseTranlationUnit)
+ {
+ // Write source to temprorary file
+ const QString filePath = QDir::tempPath() + QLatin1String("/file.h");
+ document = Document::create(filePath);
+ Utils::FileSaver documentSaver(document->fileName());
+ documentSaver.write(source);
+ documentSaver.finalize();
+
+ // Preprocess source
+ Environment env;
+ Preprocessor preprocess(0, &env);
+ const QByteArray preprocessedSource = preprocess.run(filePath, QLatin1String(source));
+ document->setUtf8Source(preprocessedSource);
+ QVERIFY(document->parse(parseMode));
+ document->check();
+ snapshot.insert(document);
+ }
+
+ static void check(QByteArray source, QList<Use> expectedUses,
+ QList<Use> macroUses = QList<Use>())
+ {
+ TestData env(source);
+
+ // Collect symbols
+ LookupContext context(env.document, env.snapshot);
+ CheckSymbols::Future future = CheckSymbols::go(env.document, context, macroUses);
+ future.waitForFinished();
+
+ const int resultCount = future.resultCount();
+ QList<Use> actualUses;
+ for (int i = 0; i < resultCount; ++i) {
+ const Use use = future.resultAt(i);
+ // When adding tests, you may want to uncomment the
+ // following line in order to print out all found uses.
+// qDebug() << QTest::toString(use);
+ actualUses.append(use);
+ }
+
+ // Checks
+ QVERIFY(resultCount > 0);
+ QCOMPARE(resultCount, expectedUses.count());
+
+ for (int i = 0; i < resultCount; ++i) {
+ const Use actualUse = actualUses.at(i);
+ const Use expectedUse = expectedUses.at(i);
+ QVERIFY(actualUse.isValid());
+ QVERIFY(expectedUse.isValid());
+ QCOMPARE(actualUse, expectedUse);
+ }
+ }
+};
+
+} // anonymous namespace
+
+class tst_CheckSymbols: public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void test_checksymbols_TypeUse();
+ void test_checksymbols_LocalUse();
+ void test_checksymbols_FieldUse();
+ void test_checksymbols_EnumerationUse();
+ void test_checksymbols_VirtualMethodUse();
+ void test_checksymbols_LabelUse();
+ void test_checksymbols_MacroUse();
+ void test_checksymbols_FunctionUse();
+ void test_checksymbols_PseudoKeywordUse();
+ void test_checksymbols_StaticUse();
+ void test_checksymbols_VariableHasTheSameNameAsEnumUse();
+ void test_checksymbols_NestedClassOfEnclosingTemplateUse();
+};
+
+void tst_CheckSymbols::test_checksymbols_TypeUse()
+{
+ const QByteArray source =
+ "namespace N {}\n"
+ "using namespace N;\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 11, 1, SemanticInfo::TypeUse)
+ << Use(2, 17, 1, SemanticInfo::TypeUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_LocalUse()
+{
+ const QByteArray source =
+ "int f()\n"
+ "{\n"
+ " int i;\n"
+ "}\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 5, 1, SemanticInfo::FunctionUse)
+ << Use(3, 8, 1, SemanticInfo::LocalUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_FieldUse()
+{
+ const QByteArray source =
+ "struct F {\n"
+ " int i;\n"
+ " F() { i = 0; }\n"
+ "};\n"
+ "int f()\n"
+ "{\n"
+ " F s;\n"
+ " s.i = 2;\n"
+ "}\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 8, 1, SemanticInfo::TypeUse)
+ << Use(2, 9, 1, SemanticInfo::FieldUse)
+ << Use(3, 5, 1, SemanticInfo::TypeUse)
+ << Use(3, 11, 1, SemanticInfo::FieldUse)
+ << Use(5, 5, 1, SemanticInfo::FunctionUse)
+ << Use(7, 5, 1, SemanticInfo::TypeUse)
+ << Use(7, 7, 1, SemanticInfo::LocalUse)
+ << Use(8, 7, 1, SemanticInfo::FieldUse)
+ << Use(8, 5, 1, SemanticInfo::LocalUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_EnumerationUse()
+{
+ const QByteArray source =
+ "enum E { Red, Green, Blue };\n"
+ "E e = Red\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 22, 4, SemanticInfo::EnumerationUse)
+ << Use(1, 15, 5, SemanticInfo::EnumerationUse)
+ << Use(1, 6, 1, SemanticInfo::TypeUse)
+ << Use(1, 10, 3, SemanticInfo::EnumerationUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_VirtualMethodUse()
+{
+ const QByteArray source =
+ "class B {\n"
+ " virtual isThere();\n"
+ "};\n"
+ "class D: public B {\n"
+ " isThere();\n"
+ "};\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 7, 1, SemanticInfo::TypeUse)
+ << Use(2, 13, 7, SemanticInfo::VirtualMethodUse)
+ << Use(4, 17, 1, SemanticInfo::TypeUse)
+ << Use(4, 7, 1, SemanticInfo::TypeUse)
+ << Use(5, 5, 7, SemanticInfo::VirtualMethodUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_LabelUse()
+{
+ const QByteArray source =
+ "int f()\n"
+ "{\n"
+ " goto g;\n"
+ " g: return 1;\n"
+ "}\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 5, 1, SemanticInfo::FunctionUse)
+ << Use(3, 9, 1, SemanticInfo::LabelUse)
+ << Use(4, 4, 1, SemanticInfo::LabelUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_MacroUse()
+{
+ const QByteArray source =
+ "#define FOO 1+1\n"
+ "int f() { FOO }\n";
+ const QList<Use> macroUses = QList<Use>()
+ << Use(1, 9, 3, SemanticInfo::MacroUse)
+ << Use(2, 11, 3, SemanticInfo::MacroUse);
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 9, 3, SemanticInfo::MacroUse)
+ << Use(2, 11, 3, SemanticInfo::MacroUse)
+ << Use(2, 5, 1, SemanticInfo::FunctionUse);
+
+ TestData::check(source, expectedUses, macroUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_FunctionUse()
+{
+ const QByteArray source =
+ "int f();\n"
+ "int g() { f(); }\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 5, 1, SemanticInfo::FunctionUse)
+ << Use(2, 5, 1, SemanticInfo::FunctionUse)
+ << Use(2, 11, 1, SemanticInfo::FunctionUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_PseudoKeywordUse()
+{
+ const QByteArray source =
+ "class D : public B {"
+ " virtual void f() override {}\n"
+ " virtual void f() final {}\n"
+ "};\n";
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 7, 1, SemanticInfo::TypeUse)
+ << Use(1, 37, 1, SemanticInfo::VirtualMethodUse)
+ << Use(1, 41, 8, SemanticInfo::PseudoKeywordUse)
+ << Use(2, 17, 1, SemanticInfo::VirtualMethodUse)
+ << Use(2, 21, 5, SemanticInfo::PseudoKeywordUse);
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_StaticUse()
+{
+ const QByteArray source =
+ "struct Outer\n"
+ "{\n"
+ " static int Foo;\n"
+ " struct Inner\n"
+ " {\n"
+ " Outer *outer;\n"
+ " void foo();\n"
+ " };\n"
+ "};\n"
+ "\n"
+ "int Outer::Foo = 42;\n"
+ "\n"
+ "void Outer::Inner::foo()\n"
+ "{\n"
+ " Foo = 7;\n"
+ " Outer::Foo = 7;\n"
+ " outer->Foo = 7;\n"
+ "}\n"
+ ;
+
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 8, 5, SemanticInfo::TypeUse)
+ << Use(3, 16, 3, SemanticInfo::FieldUse)
+ << Use(4, 12, 5, SemanticInfo::TypeUse)
+ << Use(6, 16, 5, SemanticInfo::FieldUse)
+ << Use(6, 9, 5, SemanticInfo::TypeUse)
+ << Use(7, 14, 3, SemanticInfo::FunctionUse)
+ << Use(11, 12, 3, SemanticInfo::FieldUse)
+ << Use(11, 5, 5, SemanticInfo::TypeUse)
+ << Use(13, 20, 3, SemanticInfo::FunctionUse)
+ << Use(13, 6, 5, SemanticInfo::TypeUse)
+ << Use(13, 13, 5, SemanticInfo::TypeUse)
+ << Use(15, 5, 3, SemanticInfo::FieldUse)
+ << Use(16, 12, 3, SemanticInfo::FieldUse)
+ << Use(16, 5, 5, SemanticInfo::TypeUse)
+ << Use(17, 5, 5, SemanticInfo::FieldUse)
+ << Use(17, 12, 3, SemanticInfo::FieldUse)
+ ;
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_VariableHasTheSameNameAsEnumUse()
+{
+ const QByteArray source =
+ "struct Foo\n"
+ "{\n"
+ " enum E { bar, baz };\n"
+ "};\n"
+ "\n"
+ "struct Boo\n"
+ "{\n"
+ " int foo;\n"
+ " int bar;\n"
+ " int baz;\n"
+ "};\n"
+ ;
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 8, 3, SemanticInfo::TypeUse)
+ << Use(3, 19, 3, SemanticInfo::EnumerationUse)
+ << Use(3, 14, 3, SemanticInfo::EnumerationUse)
+ << Use(3, 10, 1, SemanticInfo::TypeUse)
+ << Use(6, 8, 3, SemanticInfo::TypeUse)
+ << Use(8, 9, 3, SemanticInfo::FieldUse)
+ << Use(9, 9, 3, SemanticInfo::FieldUse)
+ << Use(10, 9, 3, SemanticInfo::FieldUse)
+ ;
+
+ TestData::check(source, expectedUses);
+}
+
+void tst_CheckSymbols::test_checksymbols_NestedClassOfEnclosingTemplateUse()
+{
+ const QByteArray source =
+ "struct Foo { int bar; };\n"
+ "\n"
+ "template<typename T>\n"
+ "struct Outer\n"
+ "{\n"
+ " struct Nested { T nt; } nested;\n"
+ "};\n"
+ "\n"
+ "void fun()\n"
+ "{\n"
+ " Outer<Foo> list;\n"
+ " list.nested.nt.bar;\n"
+ "}\n"
+ ;
+
+ const QList<Use> expectedUses = QList<Use>()
+ << Use(1, 8, 3, SemanticInfo::TypeUse)
+ << Use(1, 18, 3, SemanticInfo::FieldUse)
+ << Use(3, 19, 1, SemanticInfo::TypeUse)
+ << Use(4, 8, 5, SemanticInfo::TypeUse)
+ << Use(6, 23, 2, SemanticInfo::FieldUse)
+ << Use(6, 12, 6, SemanticInfo::TypeUse)
+ << Use(6, 29, 6, SemanticInfo::FieldUse)
+ << Use(6, 21, 1, SemanticInfo::TypeUse)
+ << Use(9, 6, 3, SemanticInfo::FunctionUse)
+ << Use(11, 11, 3, SemanticInfo::TypeUse)
+ << Use(11, 16, 4, SemanticInfo::LocalUse)
+ << Use(11, 5, 5, SemanticInfo::TypeUse)
+ << Use(12, 20, 3, SemanticInfo::FieldUse)
+ << Use(12, 17, 2, SemanticInfo::FieldUse)
+ << Use(12, 10, 6, SemanticInfo::FieldUse)
+ << Use(12, 5, 4, SemanticInfo::LocalUse)
+ ;
+
+ TestData::check(source, expectedUses);
+}
+
+QTEST_APPLESS_MAIN(tst_CheckSymbols)
+#include "tst_checksymbols.moc"
diff --git a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp
index 63b049d689..ba0eb2dfff 100644
--- a/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp
+++ b/tests/auto/cplusplus/codeformatter/tst_codeformatter.cpp
@@ -116,6 +116,7 @@ private Q_SLOTS:
void functionBodyAndBraces4();
void constructor1();
void constructor2();
+ void constructor3();
void caseBody1();
void caseBody2();
void caseBody3();
@@ -1875,6 +1876,42 @@ void tst_CodeFormatter::constructor2()
checkIndent(data);
}
+void tst_CodeFormatter::constructor3()
+{
+ QList<Line> data;
+ data << Line("class Foo {")
+ << Line(" Foo() : _a{0}, _b{1, {2, {3, \"foo\"}, 3}}")
+ << Line(" {")
+ << Line(" _b = 0")
+ << Line(" }")
+ << Line(" int _a;")
+ << Line(" Foo()")
+ << Line(" ~ : _foo{1},")
+ << Line(" ~ _bar{2},")
+ << Line(" ~ _carooooo(")
+ << Line(" ~ foo() + 12),")
+ << Line(" ~ _carooooo{foo(),")
+ << Line(" ~ 12}")
+ << Line(" {")
+ << Line(" _b = 0")
+ << Line(" }")
+ << Line(" int _b;")
+ << Line(" Foo()")
+ << Line(" ~ : _foo{1}")
+ << Line(" ~ , _bar{2}")
+ << Line(" ~ , _carooooo{")
+ << Line(" ~ foo() + 12}")
+ << Line(" ~ , _carooooo{foo(),")
+ << Line(" ~ 12}")
+ << Line(" {")
+ << Line(" _b = 0")
+ << Line(" }")
+ << Line("};")
+ ;
+ CppCodeStyleSettings codeStyle;
+ checkIndent(data);
+}
+
void tst_CodeFormatter::caseBody1()
{
QList<Line> data;
diff --git a/tests/auto/cplusplus/cplusplus.pro b/tests/auto/cplusplus/cplusplus.pro
index 6a7091a552..f5d49f3b2d 100644
--- a/tests/auto/cplusplus/cplusplus.pro
+++ b/tests/auto/cplusplus/cplusplus.pro
@@ -11,4 +11,5 @@ SUBDIRS = \
typeprettyprinter \
simplifytypes \
misc \
- cxx11
+ cxx11 \
+ checksymbols
diff --git a/tests/auto/cplusplus/cxx11/data/aliasDecl.1.cpp b/tests/auto/cplusplus/cxx11/data/aliasDecl.1.cpp
new file mode 100644
index 0000000000..99384acaa1
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/aliasDecl.1.cpp
@@ -0,0 +1,4 @@
+using Foo = int;
+using Bar = std::vector<int>::value_type;
+using A [[foo]] = const float;
+using B alignas(void*) = C *;
diff --git a/tests/auto/cplusplus/cxx11/data/alignofAlignas.1.cpp b/tests/auto/cplusplus/cxx11/data/alignofAlignas.1.cpp
new file mode 100644
index 0000000000..5ba43661ed
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/alignofAlignas.1.cpp
@@ -0,0 +1,2 @@
+int i = alignof(int);
+int t = alignof(C::foo) * 7 + alignof(Foo *);
diff --git a/tests/auto/cplusplus/cxx11/data/braceInitializers.1.cpp b/tests/auto/cplusplus/cxx11/data/braceInitializers.1.cpp
new file mode 100644
index 0000000000..94e8fae241
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/braceInitializers.1.cpp
@@ -0,0 +1,18 @@
+Type var1 = { 1, 2, 3};
+Type var2{1, 2, 3};
+Type var3({1, 2, 3});
+
+class C {
+ Type var1 = {1, 2, 3};
+ Type var2{1, 2, 3};
+};
+
+void main() {
+ var1 = {1, 2, {3, 4} };
+ Type var2{{1, 2, 3}, 4};
+ var3 += {1, 2};
+}
+
+T foo() {
+ return {1, 2, {"foo", 7}};
+}
diff --git a/tests/auto/cplusplus/cxx11/data/braceInitializers.1.errors.txt b/tests/auto/cplusplus/cxx11/data/braceInitializers.1.errors.txt
new file mode 100644
index 0000000000..e69de29bb2
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/braceInitializers.1.errors.txt
diff --git a/tests/auto/cplusplus/cxx11/data/braceInitializers.2.cpp b/tests/auto/cplusplus/cxx11/data/braceInitializers.2.cpp
new file mode 100644
index 0000000000..4dc183d8f5
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/braceInitializers.2.cpp
@@ -0,0 +1,7 @@
+class C {
+ C() : _x{12}, _y({12}) {}
+ C(int i) : _x{{{12, 2}, {"foo"}}, {bar}}... {}
+ C(int i) : _x({{12, 2}, {"foo"}}, {bar})... {}
+};
+
+void foo(int i = {1, 2, 3});
diff --git a/tests/auto/cplusplus/cxx11/data/braceInitializers.3.cpp b/tests/auto/cplusplus/cxx11/data/braceInitializers.3.cpp
new file mode 100644
index 0000000000..5105b4690c
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/braceInitializers.3.cpp
@@ -0,0 +1,6 @@
+auto x = int{};
+auto y = Foo{};
+auto z = typename Foo<T>{};
+
+auto d = new C(1, abc...);
+auto e = new C{1, 2, 3};
diff --git a/tests/auto/cplusplus/cxx11/data/declType.1.cpp b/tests/auto/cplusplus/cxx11/data/declType.1.cpp
new file mode 100644
index 0000000000..fd86589abf
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/declType.1.cpp
@@ -0,0 +1,11 @@
+template <class T, class R>
+auto foo(T t, R r) -> decltype(t + r)
+{}
+
+int x;
+decltype(x) foo;
+decltype(x) foo();
+
+// this does not work yet, as decltype is only parsed as a simple-specifier
+// and not also as a nested-name-specifier
+//decltype(vec)::value_type a;
diff --git a/tests/auto/cplusplus/cxx11/data/defaultdeleteInitializer.1.cpp b/tests/auto/cplusplus/cxx11/data/defaultdeleteInitializer.1.cpp
new file mode 100644
index 0000000000..7ec9e9b91e
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/defaultdeleteInitializer.1.cpp
@@ -0,0 +1,8 @@
+class C {
+ C() = default;
+ C(const C &) = delete;
+ C &operator=(const C &) = default;
+
+ void foo() = delete;
+ template <class T> void bar(T) = delete;
+};
diff --git a/tests/auto/cplusplus/cxx11/data/enums.1.cpp b/tests/auto/cplusplus/cxx11/data/enums.1.cpp
new file mode 100644
index 0000000000..c8cd725ad0
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/enums.1.cpp
@@ -0,0 +1,11 @@
+enum { A, B };
+enum : int;
+enum : int { A, B };
+enum Foo1 { A, B };
+enum Foo2 : int;
+enum Foo3 : int { A, B };
+enum class Foo4 : int;
+enum struct Foo5;
+enum class Foo6 { A, B };
+enum struct Foo7 { A, B };
+enum struct Foo8 : long long;
diff --git a/tests/auto/cplusplus/cxx11/data/packExpansion.1.cpp b/tests/auto/cplusplus/cxx11/data/packExpansion.1.cpp
new file mode 100644
index 0000000000..eca6796e38
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/packExpansion.1.cpp
@@ -0,0 +1,4 @@
+template <class ... Args>
+int foo(Args args...) {
+ bar(args..., {args...}, e, f);
+}
diff --git a/tests/auto/cplusplus/cxx11/data/rangeFor.1.cpp b/tests/auto/cplusplus/cxx11/data/rangeFor.1.cpp
new file mode 100644
index 0000000000..3a9a2e7d4f
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/rangeFor.1.cpp
@@ -0,0 +1,5 @@
+int main() {
+ for (int x : {1, 2, 3}) {}
+ for (int x : foo) ;
+ for (int& x : array) x += 2;
+}
diff --git a/tests/auto/cplusplus/cxx11/data/refQualifier.1.cpp b/tests/auto/cplusplus/cxx11/data/refQualifier.1.cpp
new file mode 100644
index 0000000000..172ede9ae0
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/refQualifier.1.cpp
@@ -0,0 +1,21 @@
+void foo() noexcept;
+class C {
+ void foo() const noexcept final override;
+ void foo() const & noexcept final override;
+ void foo() const && noexcept final override;
+ auto foo() const noexcept -> void final override;
+ auto foo() const & noexcept -> void final override;
+ auto foo() const && noexcept -> void final override;
+ void foo();
+ void foo() &;
+ void foo() &&;
+};
+
+int main() {
+ void (C::*p)() const;
+ void (C::*p)() const &;
+ void (C::*p)() const &&;
+ void (C::*p)();
+ void (C::*p)() &;
+ void (C::*p)() &&;
+}
diff --git a/tests/auto/cplusplus/cxx11/data/templateGreaterGreater.1.cpp b/tests/auto/cplusplus/cxx11/data/templateGreaterGreater.1.cpp
new file mode 100644
index 0000000000..c07d0a0e4f
--- /dev/null
+++ b/tests/auto/cplusplus/cxx11/data/templateGreaterGreater.1.cpp
@@ -0,0 +1,10 @@
+template <class i, int j = 1>
+class Y {};
+template <int i>
+class X {};
+
+Y<X<6>, 7> x;
+Y<X<1>> y;
+X< (1 >> 2) > z;
+auto a = static_cast<X<1>>(X<1>());
+
diff --git a/tests/auto/cplusplus/cxx11/tst_cxx11.cpp b/tests/auto/cplusplus/cxx11/tst_cxx11.cpp
index 82b99336cd..51a9f05aeb 100644
--- a/tests/auto/cplusplus/cxx11/tst_cxx11.cpp
+++ b/tests/auto/cplusplus/cxx11/tst_cxx11.cpp
@@ -39,11 +39,13 @@ using namespace CPlusPlus;
#define VERIFY_ERRORS() \
do { \
- QFile e(testdata(errorFile)); \
QByteArray expectedErrors; \
- if (e.open(QFile::ReadOnly)) \
- expectedErrors = QTextStream(&e).readAll().toUtf8(); \
- QCOMPARE(errors, expectedErrors); \
+ if (!errorFile.isEmpty()) { \
+ QFile e(testdata(errorFile)); \
+ if (e.open(QFile::ReadOnly)) \
+ expectedErrors = QTextStream(&e).readAll().toUtf8(); \
+ } \
+ QCOMPARE(QString::fromLatin1(errors), QString::fromLatin1(expectedErrors)); \
} while (0)
@@ -106,6 +108,8 @@ class tst_cxx11: public QObject
doc->translationUnit()->setCxxOxEnabled(true);
doc->check();
doc->control()->setDiagnosticClient(0);
+ } else {
+ qWarning() << "could not read file" << fileName;
}
return doc;
}
@@ -114,12 +118,8 @@ private Q_SLOTS:
//
// checks for the syntax
//
- void inlineNamespace_data();
- void inlineNamespace();
- void staticAssert();
- void staticAssert_data();
- void noExcept();
- void noExcept_data();
+ void parse_data();
+ void parse();
//
// checks for the semantic
@@ -128,15 +128,29 @@ private Q_SLOTS:
};
-void tst_cxx11::inlineNamespace_data()
+void tst_cxx11::parse_data()
{
QTest::addColumn<QString>("file");
QTest::addColumn<QString>("errorFile");
QTest::newRow("inlineNamespace.1") << "inlineNamespace.1.cpp" << "inlineNamespace.1.errors.txt";
+ QTest::newRow("staticAssert.1") << "staticAssert.1.cpp" << "staticAssert.1.errors.txt";
+ QTest::newRow("noExcept.1") << "noExcept.1.cpp" << "noExcept.1.errors.txt";
+ QTest::newRow("braceInitializers.1") << "braceInitializers.1.cpp" << "braceInitializers.1.errors.txt";
+ QTest::newRow("braceInitializers.2") << "braceInitializers.2.cpp" << "";
+ QTest::newRow("braceInitializers.3") << "braceInitializers.3.cpp" << "";
+ QTest::newRow("defaultdeleteInitializer.1") << "defaultdeleteInitializer.1.cpp" << "";
+ QTest::newRow("refQualifier.1") << "refQualifier.1.cpp" << "";
+ QTest::newRow("alignofAlignas.1") << "alignofAlignas.1.cpp" << "";
+ QTest::newRow("rangeFor.1") << "rangeFor.1.cpp" << "";
+ QTest::newRow("aliasDecl.1") << "aliasDecl.1.cpp" << "";
+ QTest::newRow("enums.1") << "enums.1.cpp" << "";
+ QTest::newRow("templateGreaterGreater.1") << "templateGreaterGreater.1.cpp" << "";
+ QTest::newRow("packExpansion.1") << "packExpansion.1.cpp" << "";
+ QTest::newRow("declType.1") << "declType.1.cpp" << "";
}
-void tst_cxx11::inlineNamespace()
+void tst_cxx11::parse()
{
QFETCH(QString, file);
QFETCH(QString, errorFile);
@@ -166,49 +180,5 @@ void tst_cxx11::inlineNamespaceLookup()
QCOMPARE(results.size(), 1); // the symbol is visible from the global scope
}
-void tst_cxx11::staticAssert_data()
-{
- QTest::addColumn<QString>("file");
- QTest::addColumn<QString>("errorFile");
-
- QTest::newRow("staticAssert.1") << "staticAssert.1.cpp" << "staticAssert.1.errors.txt";
-}
-
-void tst_cxx11::staticAssert()
-{
- QFETCH(QString, file);
- QFETCH(QString, errorFile);
-
- QByteArray errors;
- Document::Ptr doc = document(file, &errors);
-
- if (! qgetenv("DEBUG").isNull())
- printf("%s\n", errors.constData());
-
- VERIFY_ERRORS();
-}
-
-void tst_cxx11::noExcept_data()
-{
- QTest::addColumn<QString>("file");
- QTest::addColumn<QString>("errorFile");
-
- QTest::newRow("noExcept.1") << "noExcept.1.cpp" << "noExcept.1.errors.txt";
-}
-
-void tst_cxx11::noExcept()
-{
- QFETCH(QString, file);
- QFETCH(QString, errorFile);
-
- QByteArray errors;
- Document::Ptr doc = document(file, &errors);
-
- if (! qgetenv("DEBUG").isNull())
- printf("%s\n", errors.constData());
-
- VERIFY_ERRORS();
-}
-
QTEST_APPLESS_MAIN(tst_cxx11)
#include "tst_cxx11.moc"
diff --git a/tests/auto/cplusplus/findusages/tst_findusages.cpp b/tests/auto/cplusplus/findusages/tst_findusages.cpp
index b80087a139..339d852ca0 100644
--- a/tests/auto/cplusplus/findusages/tst_findusages.cpp
+++ b/tests/auto/cplusplus/findusages/tst_findusages.cpp
@@ -77,8 +77,11 @@ class tst_FindUsages: public QObject
private Q_SLOTS:
void inlineMethod();
+ void lambdaCaptureByValue();
+ void lambdaCaptureByReference();
void shadowedNames_1();
void shadowedNames_2();
+ void staticVariables();
// Qt keywords
void qproperty_1();
@@ -88,6 +91,9 @@ private Q_SLOTS:
// void objc_methods();
// void objc_fields();
// void objc_classes();
+
+ // templates
+ void instantiateTemplateWithNestedClass();
};
void tst_FindUsages::inlineMethod()
@@ -125,6 +131,70 @@ void tst_FindUsages::inlineMethod()
QCOMPARE(findUsages.references().size(), 2);
}
+void tst_FindUsages::lambdaCaptureByValue()
+{
+ const QByteArray src = "\n"
+ "void f() {\n"
+ " int test;\n"
+ " [test] { ++test; };\n"
+ "}\n";
+ Document::Ptr doc = Document::create("lambdaCaptureByValue");
+ doc->setUtf8Source(src);
+ doc->parse();
+ doc->check();
+
+ QVERIFY(doc->diagnosticMessages().isEmpty());
+ QCOMPARE(doc->globalSymbolCount(), 1U);
+
+ Snapshot snapshot;
+ snapshot.insert(doc);
+
+ Function *f = doc->globalSymbolAt(0)->asFunction();
+ QVERIFY(f);
+ QCOMPARE(f->memberCount(), 1U);
+ Block *b = f->memberAt(0)->asBlock();
+ QCOMPARE(b->memberCount(), 2U);
+ Declaration *d = b->memberAt(0)->asDeclaration();
+ QVERIFY(d);
+ QCOMPARE(d->name()->identifier()->chars(), "test");
+
+ FindUsages findUsages(src, doc, snapshot);
+ findUsages(d);
+ QCOMPARE(findUsages.usages().size(), 3);
+}
+
+void tst_FindUsages::lambdaCaptureByReference()
+{
+ const QByteArray src = "\n"
+ "void f() {\n"
+ " int test;\n"
+ " [&test] { ++test; };\n"
+ "}\n";
+ Document::Ptr doc = Document::create("lambdaCaptureByReference");
+ doc->setUtf8Source(src);
+ doc->parse();
+ doc->check();
+
+ QVERIFY(doc->diagnosticMessages().isEmpty());
+ QCOMPARE(doc->globalSymbolCount(), 1U);
+
+ Snapshot snapshot;
+ snapshot.insert(doc);
+
+ Function *f = doc->globalSymbolAt(0)->asFunction();
+ QVERIFY(f);
+ QCOMPARE(f->memberCount(), 1U);
+ Block *b = f->memberAt(0)->asBlock();
+ QCOMPARE(b->memberCount(), 2U);
+ Declaration *d = b->memberAt(0)->asDeclaration();
+ QVERIFY(d);
+ QCOMPARE(d->name()->identifier()->chars(), "test");
+
+ FindUsages findUsages(src, doc, snapshot);
+ findUsages(d);
+ QCOMPARE(findUsages.usages().size(), 3);
+}
+
void tst_FindUsages::shadowedNames_1()
{
const QByteArray src = "\n"
@@ -188,6 +258,52 @@ void tst_FindUsages::shadowedNames_2()
QCOMPARE(findUsages.usages().size(), 3);
}
+void tst_FindUsages::staticVariables()
+{
+ const QByteArray src = "\n"
+ "struct Outer\n"
+ "{\n"
+ " static int Foo;\n"
+ " struct Inner\n"
+ " {\n"
+ " Outer *outer;\n"
+ " void foo();\n"
+ " };\n"
+ "};\n"
+ "\n"
+ "int Outer::Foo = 42;\n"
+ "\n"
+ "void Outer::Inner::foo()\n"
+ "{\n"
+ " Foo = 7;\n"
+ " Outer::Foo = 7;\n"
+ " outer->Foo = 7;\n"
+ "}\n"
+ ;
+ Document::Ptr doc = Document::create("staticVariables");
+ doc->setUtf8Source(src);
+ doc->parse();
+ doc->check();
+
+ QVERIFY(doc->diagnosticMessages().isEmpty());
+ QCOMPARE(doc->globalSymbolCount(), 3U);
+
+ Snapshot snapshot;
+ snapshot.insert(doc);
+
+ Class *c = doc->globalSymbolAt(0)->asClass();
+ QVERIFY(c);
+ QCOMPARE(c->name()->identifier()->chars(), "Outer");
+ QCOMPARE(c->memberCount(), 2U);
+ Declaration *d = c->memberAt(0)->asDeclaration();
+ QVERIFY(d);
+ QCOMPARE(d->name()->identifier()->chars(), "Foo");
+
+ FindUsages findUsages(src, doc, snapshot);
+ findUsages(d);
+ QCOMPARE(findUsages.usages().size(), 5);
+}
+
#if 0
@interface Clazz {} +(void)method:(int)arg; @end
@implementation Clazz +(void)method:(int)arg {
@@ -285,5 +401,48 @@ void tst_FindUsages::qproperty_1()
QCOMPARE(findUsages.references().size(), 2);
}
+void tst_FindUsages::instantiateTemplateWithNestedClass()
+{
+ const QByteArray src = "\n"
+ "struct Foo\n"
+ "{ int bar; };\n"
+ "template <typename T>\n"
+ "struct Template\n"
+ "{\n"
+ " struct Nested\n"
+ " {\n"
+ " T t;\n"
+ " }nested;\n"
+ "};\n"
+ "void f()\n"
+ "{\n"
+ " Template<Foo> templateFoo;\n"
+ " templateFoo.nested.t.bar;\n"
+ "}\n"
+ ;
+
+ Document::Ptr doc = Document::create("simpleTemplate");
+ doc->setUtf8Source(src);
+ doc->parse();
+ doc->check();
+
+ QVERIFY(doc->diagnosticMessages().isEmpty());
+ QCOMPARE(doc->globalSymbolCount(), 3U);
+
+ Snapshot snapshot;
+ snapshot.insert(doc);
+
+ Class *classFoo = doc->globalSymbolAt(0)->asClass();
+ QVERIFY(classFoo);
+ QCOMPARE(classFoo->memberCount(), 1U);
+ Declaration *barDeclaration = classFoo->memberAt(0)->asDeclaration();
+ QVERIFY(barDeclaration);
+ QCOMPARE(barDeclaration->name()->identifier()->chars(), "bar");
+
+ FindUsages findUsages(src, doc, snapshot);
+ findUsages(barDeclaration);
+ QCOMPARE(findUsages.usages().size(), 2);
+}
+
QTEST_APPLESS_MAIN(tst_FindUsages)
#include "tst_findusages.moc"
diff --git a/tests/auto/cplusplus/preprocessor/tst_preprocessor.cpp b/tests/auto/cplusplus/preprocessor/tst_preprocessor.cpp
index b1c90f0c39..2a985f5a09 100644
--- a/tests/auto/cplusplus/preprocessor/tst_preprocessor.cpp
+++ b/tests/auto/cplusplus/preprocessor/tst_preprocessor.cpp
@@ -216,6 +216,12 @@ public:
*m_output = m_pp.run(fileName, src, nolines, true);
}
+ virtual void markAsIncludeGuard(const QByteArray &macroName)
+ { m_includeGuardMacro = macroName; }
+
+ QByteArray includeGuard() const
+ { return m_includeGuardMacro; }
+
QList<Block> skippedBlocks() const
{ return m_skippedBlocks; }
@@ -246,6 +252,7 @@ private:
Preprocessor m_pp;
QList<QDir> m_includePaths;
unsigned m_includeDepth;
+ QByteArray m_includeGuardMacro;
QList<Block> m_skippedBlocks;
QList<Include> m_recordedIncludes;
QList<QByteArray> m_expandedMacros;
@@ -329,6 +336,7 @@ private slots:
void dont_eagerly_expand_data();
void comparisons_data();
void comparisons();
+ void comments_before_args();
void comments_within();
void comments_within_data();
void comments_within2();
@@ -339,6 +347,8 @@ private slots:
void multiline_strings_data();
void skip_unknown_directives();
void skip_unknown_directives_data();
+ void include_guard();
+ void include_guard_data();
};
// Remove all #... lines, and 'simplify' string, to allow easily comparing the result
@@ -1239,6 +1249,28 @@ void tst_Preprocessor::comments_within_data()
QTest::newRow("case 7") << original << expected;
}
+void tst_Preprocessor::comments_before_args()
+{
+ Client *client = 0; // no client.
+ Environment env;
+
+ Preprocessor preprocess(client, &env);
+ preprocess.setKeepComments(true);
+ QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
+ "\n#define foo(a,b) int a = b;"
+ "\nfoo/*C comment*/(a,1)\n"
+ "\nfoo/**Doxygen comment*/(b,2)\n"
+ "\nfoo//C++ comment\n(c,3)\n"
+ "\nfoo///Doxygen C++ comment\n(d,4)\n"
+ "\nfoo/*multiple*///comments\n/**as well*/(e,5)\n",
+ true, false);
+
+ preprocessed = preprocessed.simplified();
+// DUMP_OUTPUT(preprocessed);
+ QCOMPARE(simplified(preprocessed),
+ QString("int a=1;int b=2;int c=3;int d=4;int e=5;"));
+}
+
void tst_Preprocessor::comments_within2()
{
compare_input_output(true);
@@ -1458,6 +1490,88 @@ void tst_Preprocessor::skip_unknown_directives_data()
QTest::newRow("case 1") << original << expected;
}
+void tst_Preprocessor::include_guard()
+{
+ QFETCH(QString, includeGuard);
+ QFETCH(QString, input);
+
+ QByteArray output;
+ Environment env;
+ MockClient client(&env, &output);
+ Preprocessor preprocess(&client, &env);
+ preprocess.setKeepComments(true);
+ /*QByteArray prep =*/ preprocess.run(QLatin1String("<test-case>"), input);
+ QCOMPARE(QString::fromUtf8(client.includeGuard()), includeGuard);
+}
+
+void tst_Preprocessor::include_guard_data()
+{
+ QTest::addColumn<QString>("includeGuard");
+ QTest::addColumn<QString>("input");
+
+ QTest::newRow("basic-test") << "BASIC_TEST"
+ << "#ifndef BASIC_TEST\n"
+ "#define BASIC_TEST\n"
+ "\n"
+ "#endif // BASIC_TEST\n";
+ QTest::newRow("comments-1") << "GUARD"
+ << "/* some\n"
+ " * copyright\n"
+ " * header.\n"
+ " */\n"
+ "#ifndef GUARD\n"
+ "#define GUARD\n"
+ "\n"
+ "#endif // GUARD\n";
+ QTest::newRow("comments-2") << "GUARD"
+ << "#ifndef GUARD\n"
+ "#define GUARD\n"
+ "\n"
+ "#endif // GUARD\n"
+ "/* some\n"
+ " * trailing\n"
+ " * comments.\n"
+ " */\n"
+ ;
+ QTest::newRow("nested-ifdef") << "GUARD"
+ << "#ifndef GUARD\n"
+ "#define GUARD\n"
+ "#ifndef NOT_GUARD\n"
+ "#define NOT_GUARD\n"
+ "#endif // NOT_GUARD\n"
+ "\n"
+ "#endif // GUARD\n"
+ ;
+ QTest::newRow("leading-tokens") << ""
+ << "int i;\n"
+ "#ifndef GUARD\n"
+ "#define GUARD\n"
+ "\n"
+ "#endif // GUARD\n"
+ ;
+ QTest::newRow("trailing-tokens") << ""
+ << "#ifndef GUARD\n"
+ "#define GUARD\n"
+ "\n"
+ "#endif // GUARD\n"
+ "int i;\n"
+ ;
+ QTest::newRow("surprising-but-correct") << "GUARD"
+ << "#ifndef GUARD\n"
+ "int i;\n"
+ "\n"
+ "#define GUARD\n"
+ "#endif // GUARD\n"
+ ;
+ QTest::newRow("incomplete-1") << ""
+ << "#ifndef GUARD\n"
+ ;
+ QTest::newRow("incomplete-2") << "GUARD"
+ << "#ifndef GUARD\n"
+ "#define GUARD\n"
+ ;
+}
+
void tst_Preprocessor::compare_input_output(bool keepComments)
{
QFETCH(QByteArray, input);
diff --git a/tests/auto/cplusplus/semantic/tst_semantic.cpp b/tests/auto/cplusplus/semantic/tst_semantic.cpp
index bdc77773f1..fa17702461 100644
--- a/tests/auto/cplusplus/semantic/tst_semantic.cpp
+++ b/tests/auto/cplusplus/semantic/tst_semantic.cpp
@@ -481,12 +481,12 @@ void tst_Semantic::template_instance_1()
QVERIFY(decl);
FullySpecifiedType templArgs[] = { control->integerType(IntegerType::Int) };
- const Name *templId = control->templateNameId(control->identifier("QList"), templArgs, 1);
+ const Name *templId = control->templateNameId(control->identifier("QList"), false, templArgs, 1);
FullySpecifiedType genTy = DeprecatedGenTemplateInstance::instantiate(templId, decl, control);
Overview oo;
- oo.setShowReturnTypes(true);
+ oo.showReturnTypes = true;
const QString genDecl = oo.prettyType(genTy);
QCOMPARE(genDecl, QString::fromLatin1("void (const int &)"));
diff --git a/tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter.cpp b/tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter.cpp
index 6444bedb8d..f5bc5e4674 100644
--- a/tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter.cpp
+++ b/tests/auto/cplusplus/typeprettyprinter/tst_typeprettyprinter.cpp
@@ -27,25 +27,23 @@
**
****************************************************************************/
-#include <QtTest>
#include <QObject>
-#include <QList>
+#include <QtTest>
-#include <FullySpecifiedType.h>
-#include <Type.h>
#include <CoreTypes.h>
-#include <Symbols.h>
-#include <TranslationUnit.h>
-#include <Control.h>
-#include <Names.h>
+#include <FullySpecifiedType.h>
#include <Literals.h>
#include <Overview.h>
-#include <Scope.h>
+#include <Symbols.h>
+#include <Type.h>
#include <TypePrettyPrinter.h>
//TESTED_COMPONENT=src/libs/cplusplus
using namespace CPlusPlus;
+Q_DECLARE_METATYPE(CPlusPlus::FullySpecifiedType)
+Q_DECLARE_METATYPE(Overview::StarBindFlags)
+
class tst_TypePrettyPrinter: public QObject
{
Q_OBJECT
@@ -55,160 +53,359 @@ private Q_SLOTS:
void basic_data();
};
-Q_DECLARE_METATYPE(CPlusPlus::FullySpecifiedType);
-
-TranslationUnit *unit;
-
-const Identifier *nameId(const QString &name)
+static const Identifier *nameId(const QString &name)
{ return new Identifier(name.toLatin1().constData(), name.toLatin1().size()); }
-Argument *arg(const QString &name, const FullySpecifiedType &ty)
+static Argument *arg(const QString &name, const FullySpecifiedType &ty)
{
- Argument *a = new Argument(unit, 0, nameId(name));
+ Argument *a = new Argument(0, 0, nameId(name));
a->setType(ty);
return a;
}
-FullySpecifiedType voidTy()
+static FullySpecifiedType voidTy()
{ return FullySpecifiedType(new VoidType); }
-FullySpecifiedType intTy()
+static FullySpecifiedType intTy()
{ return FullySpecifiedType(new IntegerType(IntegerType::Int)); }
-FullySpecifiedType fnTy(const QString &name, const FullySpecifiedType &ret)
+static FullySpecifiedType fnTy(const QString &name, const FullySpecifiedType &ret)
{
- Function *fn = new Function(unit, 0, nameId(name));
+ Function *fn = new Function(0, 0, nameId(name));
fn->setReturnType(ret);
return FullySpecifiedType(fn);
}
-FullySpecifiedType fnTy(const QString &name, const FullySpecifiedType &ret, const FullySpecifiedType &a0)
+static FullySpecifiedType fnTy(const QString &name, const FullySpecifiedType &ret,
+ const FullySpecifiedType &a0)
{
- Function *fn = new Function(unit, 0, nameId(name));
+ Function *fn = new Function(0, 0, nameId(name));
fn->setReturnType(ret);
fn->addMember(arg("a0", a0));
return FullySpecifiedType(fn);
}
-FullySpecifiedType ptr(const FullySpecifiedType &el)
+static FullySpecifiedType fnTy(const QString &name, const FullySpecifiedType &ret,
+ const FullySpecifiedType &a0, const FullySpecifiedType &a1,
+ const FullySpecifiedType &a2)
+{
+ Function *fn = new Function(0, 0, nameId(name));
+ fn->setReturnType(ret);
+ fn->addMember(arg("a0", a0));
+ fn->addMember(arg("a1", a1));
+ fn->addMember(arg("a1", a2));
+ return FullySpecifiedType(fn);
+}
+
+static FullySpecifiedType ptr(const FullySpecifiedType &el)
{ return FullySpecifiedType(new PointerType(el)); }
-FullySpecifiedType ref(const FullySpecifiedType &el)
+static FullySpecifiedType ref(const FullySpecifiedType &el)
{ return FullySpecifiedType(new ReferenceType(el, false)); }
-FullySpecifiedType rref(const FullySpecifiedType &el)
+static FullySpecifiedType rref(const FullySpecifiedType &el)
{ return FullySpecifiedType(new ReferenceType(el, true)); }
-FullySpecifiedType arr(const FullySpecifiedType &el)
+static FullySpecifiedType arr(const FullySpecifiedType &el)
{ return FullySpecifiedType(new ArrayType(el, 4)); }
-FullySpecifiedType cnst(const FullySpecifiedType &el)
+static FullySpecifiedType cnst(const FullySpecifiedType &el)
{ FullySpecifiedType r(el); r.setConst(true); return r; }
+static QString toString(Overview::StarBindFlags starBindFlags)
+{
+ QString result;
+ if (starBindFlags & Overview::BindToIdentifier)
+ result += QLatin1Char('n');
+ if (starBindFlags & Overview::BindToTypeName)
+ result += QLatin1Char('t');
+ if (starBindFlags & Overview::BindToLeftSpecifier)
+ result += QLatin1String("Sl");
+ if (starBindFlags & Overview::BindToRightSpecifier)
+ result += QLatin1String("Sr");
+ return result;
+}
-
-void addRow(const FullySpecifiedType &f, QString result, QString name = QString())
+static void addRow(const FullySpecifiedType &f, Overview::StarBindFlags starBindFlags,
+ const QString &result, const QString &name = QString())
{
- QTest::newRow(result.toLatin1().constData()) << f << name << result;
+ const QString dataTag
+ = QString::fromLatin1("'%1' with star binding '%2'").arg(result, toString(starBindFlags));
+ QTest::newRow(dataTag.toLatin1().constData()) << f << starBindFlags << name << result;
}
void tst_TypePrettyPrinter::basic_data()
{
- // seems it now works without a translation unit
-// Control c;
-// TranslationUnit t(&c, 0);
-// unit = 0;
-
QTest::addColumn<FullySpecifiedType>("type");
+ QTest::addColumn<Overview::StarBindFlags>("starBindFlags");
QTest::addColumn<QString>("name");
QTest::addColumn<QString>("result");
- addRow(voidTy(), "void");
- addRow(cnst(voidTy()), "const void");
- addRow(ptr(fnTy("foo", voidTy())), "void (*)()");
- addRow(ptr(fnTy("foo", voidTy())), "void (*foo)()", "foo");
-
- // named types
- addRow(voidTy(), "void foo", "foo");
- addRow(ptr(voidTy()), "void *foo", "foo");
- addRow(cnst(ptr(voidTy())), "void *const foo", "foo");
- addRow(arr(voidTy()), "void foo[]", "foo");
- addRow(ptr(arr(voidTy())), "void (*foo)[]", "foo");
-
- // pointers
- addRow(ptr(voidTy()), "void *");
- addRow(ptr(ptr(voidTy())), "void **");
-
- addRow(ptr(cnst(voidTy())), "const void *");
- addRow(cnst(ptr(cnst(voidTy()))), "const void *const");
- addRow(cnst(ptr(voidTy())), "void *const");
-
- addRow(ptr(ptr(cnst(voidTy()))), "const void **");
- addRow(ptr(cnst(ptr(cnst(voidTy())))), "const void *const*");
- addRow(cnst(ptr(ptr(cnst(voidTy())))), "const void **const");
- addRow(cnst(ptr(cnst(ptr(cnst(voidTy()))))), "const void *const*const");
- addRow(ptr(cnst(ptr(voidTy()))), "void *const*");
- addRow(cnst(ptr(ptr(voidTy()))), "void **const");
- addRow(cnst(ptr(cnst(ptr(voidTy())))), "void *const*const");
-
- addRow(arr(voidTy()), "void[]");
- addRow(arr(ptr(voidTy())), "void *[]");
- addRow(ptr(arr(voidTy())), "void (*)[]");
- addRow(ptr(arr(arr(voidTy()))), "void (*)[][]");
- addRow(ptr(arr(ptr(voidTy()))), "void *(*)[]");
- addRow(arr(ptr(arr(voidTy()))), "void (*[])[]");
-
- // references
- addRow(ref(voidTy()), "void &");
- addRow(ref(ref(voidTy())), "void & &");
-
- addRow(ref(cnst(voidTy())), "const void &");
- addRow(cnst(ref(cnst(voidTy()))), "const void &const");
- addRow(cnst(ref(voidTy())), "void &const");
-
- addRow(ref(ref(cnst(voidTy()))), "const void & &");
- addRow(ref(cnst(ref(cnst(voidTy())))), "const void &const&");
- addRow(cnst(ref(ref(cnst(voidTy())))), "const void & &const");
- addRow(cnst(ref(cnst(ref(cnst(voidTy()))))), "const void &const&const");
- addRow(ref(cnst(ref(voidTy()))), "void &const&");
- addRow(cnst(ref(ref(voidTy()))), "void & &const");
- addRow(cnst(ref(cnst(ref(voidTy())))), "void &const&const");
-
- addRow(arr(voidTy()), "void[]");
- addRow(arr(ref(voidTy())), "void &[]");
- addRow(ref(arr(voidTy())), "void (&)[]");
- addRow(ref(arr(arr(voidTy()))), "void (&)[][]");
- addRow(ref(arr(ref(voidTy()))), "void &(&)[]");
- addRow(arr(ref(arr(voidTy()))), "void (&[])[]");
-
- // rvalue references
- addRow(rref(voidTy()), "void &&");
- addRow(rref(cnst(voidTy())), "const void &&");
-
- addRow(rref(arr(voidTy())), "void (&&)[]");
- addRow(rref(arr(arr(voidTy()))), "void (&&)[][]");
-
- // simple functions
- addRow(ptr(fnTy("foo", voidTy(), intTy())), "void (*foo)(int)", "foo");
- addRow(ptr(fnTy("foo", voidTy(), ptr(voidTy()))), "void (*foo)(void *)", "foo");
- addRow(fnTy("foo", voidTy(), intTy()), "void foo(int)", "foo");
- addRow(fnTy("foo", voidTy(), ptr(voidTy())), "void foo(void *)", "foo");
-
- // functions with ptr or ref returns
- addRow(ptr(fnTy("foo", ptr(voidTy()), intTy())), "void *(*foo)(int)", "foo");
- addRow(ptr(fnTy("foo", ref(voidTy()), ptr(voidTy()))), "void &(*foo)(void *)", "foo");
- addRow(fnTy("foo", ptr(voidTy()), intTy()), "void *foo(int)", "foo");
- addRow(fnTy("foo", ref(voidTy()), ptr(voidTy())), "void &foo(void *)", "foo");
+ // Define some often used flag combinations.
+ const Overview::StarBindFlags bindToNothing = 0;
+ const Overview::StarBindFlags bindToBothSpecifiers
+ = Overview::StarBindFlags(Overview::BindToLeftSpecifier | Overview::BindToRightSpecifier);
+ const Overview::StarBindFlags bindToNameAndType
+ = Overview::StarBindFlags(Overview::BindToIdentifier | Overview::BindToTypeName);
+ const Overview::StarBindFlags bindToTypeAndRightSpecifier
+ = Overview::StarBindFlags(Overview::BindToTypeName | Overview::BindToRightSpecifier);
+ const Overview::StarBindFlags bindToAll = Overview::StarBindFlags(Overview::BindToIdentifier
+ | Overview::BindToTypeName | Overview::BindToLeftSpecifier | Overview::BindToRightSpecifier);
+
+ // The star bindings should not affect declarations without a star or reference sign.
+ addRow(voidTy(), bindToNothing, "void");
+ addRow(voidTy(), bindToAll, "void");
+ addRow(voidTy(), bindToAll, "void foo", "foo");
+ addRow(voidTy(), bindToNothing, "void foo", "foo");
+
+ addRow(cnst(voidTy()), bindToNothing, "const void");
+ addRow(cnst(voidTy()), bindToAll, "const void");
+ addRow(cnst(voidTy()), bindToNothing, "const void foo", "foo");
+ addRow(cnst(voidTy()), bindToAll, "const void foo", "foo");
+
+ addRow(arr(voidTy()), bindToNothing, "void[]");
+ addRow(arr(voidTy()), bindToAll, "void[]");
+ addRow(arr(voidTy()), bindToNothing, "void foo[]", "foo");
+ addRow(arr(voidTy()), bindToAll, "void foo[]", "foo");
+
+ addRow(fnTy("foo", voidTy(), intTy()), bindToNothing, "void foo(int)", "foo");
+ addRow(fnTy("foo", voidTy(), intTy()), bindToAll, "void foo(int)", "foo");
+
+ // Pointers to functions and arrays are also excluded. It seems to be quite unusal to have
+ // a space there.
+ addRow(ptr(fnTy("foo", voidTy())), bindToAll, "void (*)()");
+ addRow(ptr(fnTy("foo", voidTy())), bindToNothing, "void (*)()");
+ addRow(ptr(fnTy("foo", voidTy())), bindToAll, "void (*foo)()", "foo");
+ addRow(ptr(fnTy("foo", voidTy())), bindToNothing, "void (*foo)()", "foo");
+
+ addRow(ptr(arr(voidTy())), bindToNothing, "void (*)[]");
+ addRow(ptr(arr(voidTy())), bindToAll, "void (*)[]");
+
+ addRow(ptr(arr(arr(voidTy()))), bindToNothing, "void (*)[][]");
+ addRow(ptr(arr(arr(voidTy()))), bindToAll, "void (*)[][]");
+
+ // Pointers only
+ addRow(ptr(voidTy()), Overview::BindToTypeName, "void*");
+ addRow(ptr(voidTy()), bindToAll, "void*");
+ addRow(ptr(voidTy()), bindToNothing, "void *");
+ addRow(ptr(voidTy()), Overview::BindToIdentifier, "void *foo", "foo");
+ addRow(ptr(voidTy()), Overview::BindToTypeName, "void* foo", "foo");
+ addRow(ptr(voidTy()), bindToNameAndType, "void*foo", "foo");
+ addRow(ptr(voidTy()), bindToAll, "void*foo", "foo");
+ addRow(ptr(voidTy()), bindToNothing, "void * foo", "foo");
+
+ addRow(ptr(ptr(voidTy())), Overview::BindToTypeName, "void**");
+ addRow(ptr(ptr(voidTy())), bindToAll, "void**");
+ addRow(ptr(ptr(voidTy())), bindToNothing, "void **");
+ addRow(ptr(ptr(voidTy())), Overview::BindToIdentifier, "void **foo", "foo");
+ addRow(ptr(ptr(voidTy())), Overview::BindToTypeName, "void** foo", "foo");
+ addRow(ptr(ptr(voidTy())), bindToNameAndType, "void**foo", "foo");
+ addRow(ptr(ptr(voidTy())), bindToAll, "void**foo", "foo");
+ addRow(ptr(ptr(voidTy())), bindToNothing, "void ** foo", "foo");
+
+ addRow(ptr(cnst(voidTy())), bindToAll, "const void*");
+ addRow(ptr(cnst(voidTy())), bindToNothing, "const void *");
+
+ addRow(cnst(ptr(voidTy())), Overview::BindToIdentifier, "void * const foo", "foo");
+ addRow(cnst(ptr(voidTy())), Overview::BindToTypeName, "void* const foo", "foo");
+ addRow(cnst(ptr(voidTy())), Overview::BindToRightSpecifier, "void *const foo", "foo");
+ addRow(cnst(ptr(voidTy())), bindToTypeAndRightSpecifier, "void*const foo", "foo");
+ addRow(cnst(ptr(voidTy())), bindToAll, "void*const foo", "foo");
+ addRow(cnst(ptr(voidTy())), bindToNothing, "void * const foo", "foo");
+
+ addRow(cnst(ptr(cnst(voidTy()))), bindToAll, "const void*const");
+ addRow(cnst(ptr(cnst(voidTy()))), Overview::BindToTypeName, "const void* const");
+ addRow(cnst(ptr(cnst(voidTy()))), Overview::BindToRightSpecifier, "const void *const");
+ addRow(cnst(ptr(cnst(voidTy()))), bindToNothing, "const void * const");
+
+ addRow(cnst(ptr(voidTy())), Overview::BindToIdentifier, "void * const");
+ addRow(cnst(ptr(voidTy())), Overview::BindToTypeName, "void* const");
+ addRow(cnst(ptr(voidTy())), Overview::BindToRightSpecifier, "void *const");
+ addRow(cnst(ptr(voidTy())), bindToTypeAndRightSpecifier, "void*const");
+ addRow(cnst(ptr(voidTy())), bindToAll, "void*const");
+ addRow(cnst(ptr(voidTy())), bindToNothing, "void * const");
+
+ addRow(ptr(ptr(cnst(voidTy()))), Overview::BindToIdentifier, "const void **");
+ addRow(ptr(cnst(ptr(cnst(voidTy())))), Overview::BindToIdentifier, "const void * const *");
+ addRow(cnst(ptr(ptr(cnst(voidTy())))), Overview::BindToIdentifier, "const void ** const");
+
+ addRow(ptr(cnst(ptr(voidTy()))), bindToNothing, "void * const *");
+ addRow(ptr(cnst(ptr(voidTy()))), bindToAll, "void*const*");
+ addRow(cnst(ptr(ptr(voidTy()))), bindToNothing, "void ** const");
+ addRow(cnst(ptr(ptr(voidTy()))), bindToAll, "void**const");
+
+ addRow(cnst(ptr(cnst(ptr(voidTy())))), bindToNothing, "void * const * const");
+ addRow(cnst(ptr(cnst(ptr(voidTy())))), bindToAll, "void*const*const");
+ addRow(cnst(ptr(ptr(cnst(ptr(voidTy()))))), bindToNothing, "void * const ** const");
+ addRow(cnst(ptr(ptr(cnst(ptr(voidTy()))))), bindToAll, "void*const**const");
+
+ addRow(cnst(ptr(cnst(ptr(cnst(voidTy()))))), Overview::BindToLeftSpecifier, "const void * const* const");
+ addRow(cnst(ptr(cnst(ptr(cnst(voidTy()))))), Overview::BindToRightSpecifier, "const void *const *const");
+ addRow(cnst(ptr(cnst(ptr(cnst(voidTy()))))), bindToBothSpecifiers, "const void *const*const");
+ addRow(cnst(ptr(cnst(ptr(cnst(voidTy()))))), bindToNothing, "const void * const * const");
+ addRow(cnst(ptr(cnst(ptr(cnst(voidTy()))))), bindToAll, "const void*const*const");
+
+ // Pointers and arrays
+ addRow(arr(ptr(voidTy())), bindToNothing, "void * argv[]", "argv");
+ addRow(arr(ptr(voidTy())), bindToAll, "void*argv[]", "argv");
+
+ addRow(arr(ptr(voidTy())), bindToNothing, "void *[]");
+ addRow(arr(ptr(voidTy())), bindToAll, "void*[]");
+
+ addRow(ptr(arr(ptr(voidTy()))), bindToNothing, "void *(*)[]");
+ addRow(ptr(arr(ptr(voidTy()))), bindToAll, "void*(*)[]");
+
+ addRow(arr(ptr(arr(voidTy()))), bindToNothing, "void (*[])[]");
+ addRow(arr(ptr(arr(voidTy()))), bindToAll, "void (*[])[]");
+
+ addRow(ptr(arr(voidTy())), bindToAll, "void (*foo)[]", "foo");
+ addRow(ptr(arr(voidTy())), bindToNothing, "void (*foo)[]", "foo");
+
+ // Pointers to functions
+ addRow(ptr(fnTy("foo", voidTy(), intTy())), bindToNothing, "void (*foo)(int)", "foo");
+ addRow(ptr(fnTy("foo", voidTy(), intTy())), bindToAll, "void (*foo)(int)", "foo");
+
+ addRow(ptr(fnTy("foo", voidTy(), ptr(voidTy()))), bindToNothing, "void (*foo)(void *)", "foo");
+ addRow(ptr(fnTy("foo", voidTy(), ptr(voidTy()))), bindToAll, "void (*foo)(void*)", "foo");
+
+ // Pointers in more complex declarations
+ FullySpecifiedType complexType1
+ = ptr(fnTy("foo", voidTy(), intTy(), ptr(voidTy()), ptr(ptr(intTy()))));
+ addRow(complexType1, bindToNothing, "void (*foo)(int, void *, int **)", "foo");
+ addRow(complexType1, bindToAll, "void (*foo)(int, void*, int**)", "foo");
+
+ FullySpecifiedType complexType2 = ptr(fnTy("foo", voidTy(),
+ intTy(), cnst(ptr(cnst(voidTy()))), cnst(ptr(cnst(ptr(intTy()))))));
+ addRow(complexType2, Overview::BindToLeftSpecifier,
+ "void (*foo)(int, const void * const, int * const* const)", "foo");
+ addRow(complexType2, Overview::BindToRightSpecifier,
+ "void (*foo)(int, const void *const, int *const *const)", "foo");
+ addRow(complexType2, bindToBothSpecifiers,
+ "void (*foo)(int, const void *const, int *const*const)", "foo");
+ addRow(complexType2, bindToNothing,
+ "void (*foo)(int, const void * const, int * const * const)", "foo");
+ addRow(complexType2, bindToAll,
+ "void (*foo)(int, const void*const, int*const*const)", "foo");
+
+ // References only
+ addRow(ref(voidTy()), bindToNothing, "void &");
+ addRow(ref(voidTy()), bindToAll, "void&");
+
+ addRow(ref(ref(voidTy())), bindToNothing, "void & &");
+ addRow(ref(ref(voidTy())), bindToAll, "void& &");
+
+ addRow(ref(cnst(voidTy())), bindToNothing, "const void &");
+ addRow(ref(cnst(voidTy())), bindToAll, "const void&");
+
+ addRow(cnst(ref(cnst(voidTy()))), Overview::BindToRightSpecifier, "const void &const");
+ addRow(cnst(ref(cnst(voidTy()))), Overview::BindToTypeName, "const void& const");
+ addRow(cnst(ref(cnst(voidTy()))), bindToNothing, "const void & const");
+ addRow(cnst(ref(cnst(voidTy()))), bindToAll, "const void&const");
+
+ addRow(cnst(ref(voidTy())), Overview::BindToRightSpecifier, "void &const");
+ addRow(cnst(ref(voidTy())), Overview::BindToTypeName, "void& const");
+ addRow(cnst(ref(voidTy())), bindToNothing, "void & const");
+ addRow(cnst(ref(voidTy())), bindToAll, "void&const");
+
+ addRow(ref(ref(cnst(voidTy()))), bindToNothing, "const void & &");
+ addRow(ref(ref(cnst(voidTy()))), bindToAll, "const void& &");
+
+ addRow(ref(cnst(ref(cnst(voidTy())))), Overview::BindToTypeName, "const void& const &");
+ addRow(ref(cnst(ref(cnst(voidTy())))), Overview::BindToLeftSpecifier, "const void & const&");
+ addRow(ref(cnst(ref(cnst(voidTy())))), Overview::BindToRightSpecifier, "const void &const &");
+ addRow(ref(cnst(ref(cnst(voidTy())))), bindToBothSpecifiers, "const void &const&");
+ addRow(ref(cnst(ref(cnst(voidTy())))), bindToNothing, "const void & const &");
+ addRow(ref(cnst(ref(cnst(voidTy())))), bindToAll, "const void&const&");
+
+ addRow(cnst(ref(ref(cnst(voidTy())))), bindToBothSpecifiers, "const void & &const");
+ addRow(cnst(ref(ref(cnst(voidTy())))), bindToNothing, "const void & & const");
+ addRow(cnst(ref(ref(cnst(voidTy())))), bindToAll, "const void& &const");
+
+ addRow(cnst(ref(cnst(ref(cnst(voidTy()))))), Overview::BindToLeftSpecifier, "const void & const& const");
+ addRow(cnst(ref(cnst(ref(cnst(voidTy()))))), Overview::BindToRightSpecifier, "const void &const &const");
+ addRow(cnst(ref(cnst(ref(cnst(voidTy()))))), bindToBothSpecifiers, "const void &const&const");
+ addRow(cnst(ref(cnst(ref(cnst(voidTy()))))), bindToNothing, "const void & const & const");
+ addRow(cnst(ref(cnst(ref(cnst(voidTy()))))), bindToAll, "const void&const&const");
+
+ addRow(ref(cnst(ref(voidTy()))), bindToNothing, "void & const &");
+ addRow(ref(cnst(ref(voidTy()))), bindToAll, "void&const&");
+
+ addRow(cnst(ref(ref(voidTy()))), bindToNothing, "void & & const");
+ addRow(cnst(ref(ref(voidTy()))), bindToAll, "void& &const");
+
+ addRow(cnst(ref(cnst(ref(voidTy())))), Overview::BindToLeftSpecifier, "void & const& const");
+ addRow(cnst(ref(cnst(ref(voidTy())))), Overview::BindToRightSpecifier, "void &const &const");
+ addRow(cnst(ref(cnst(ref(voidTy())))), bindToBothSpecifiers, "void &const&const");
+ addRow(cnst(ref(cnst(ref(voidTy())))), bindToNothing, "void & const & const");
+ addRow(cnst(ref(cnst(ref(voidTy())))), bindToAll, "void&const&const");
+
+ addRow(ref(fnTy("foo", voidTy())), bindToNothing, "void (&foo)()", "foo");
+ addRow(ref(fnTy("foo", voidTy())), bindToAll, "void (&foo)()", "foo");
+
+ addRow(arr(ref(voidTy())), bindToNothing, "void &[]");
+ addRow(arr(ref(voidTy())), bindToAll, "void&[]");
+
+ addRow(ref(arr(voidTy())), bindToNothing, "void (&)[]");
+ addRow(ref(arr(voidTy())), bindToAll, "void (&)[]");
+
+ addRow(ref(arr(arr(voidTy()))), bindToNothing, "void (&)[][]");
+ addRow(ref(arr(arr(voidTy()))), bindToAll, "void (&)[][]");
+
+ addRow(ref(arr(ref(voidTy()))), bindToNothing, "void &(&)[]");
+ addRow(ref(arr(ref(voidTy()))), bindToAll, "void&(&)[]");
+
+ addRow(arr(ref(arr(voidTy()))), bindToNothing, "void (&[])[]");
+ addRow(arr(ref(arr(voidTy()))), bindToAll, "void (&[])[]");
+
+ // Rvalue References
+ addRow(rref(voidTy()), bindToNothing, "void &&");
+ addRow(rref(voidTy()), bindToAll, "void&&");
+
+ addRow(rref(cnst(voidTy())), bindToNothing, "const void &&");
+ addRow(rref(cnst(voidTy())), bindToAll, "const void&&");
+
+ addRow(rref(cnst(voidTy())), bindToNothing, "const void && foo", "foo");
+ addRow(rref(cnst(voidTy())), bindToAll, "const void&&foo", "foo");
+
+ addRow(rref(arr(voidTy())), bindToNothing, "void (&&)[]");
+ addRow(rref(arr(voidTy())), bindToAll, "void (&&)[]");
+
+ addRow(rref(arr(arr(voidTy()))), bindToNothing, "void (&&)[][]");
+ addRow(rref(arr(arr(voidTy()))), bindToAll, "void (&&)[][]");
+
+ // Pointers and references mixed
+ addRow(cnst(ref(ptr(voidTy()))), bindToBothSpecifiers, "void *&const");
+ addRow(cnst(ref(ptr(voidTy()))), bindToNothing, "void *& const");
+ addRow(cnst(ref(ptr(voidTy()))), bindToAll, "void*&const");
+
+ // Functions with pointer parameters
+ addRow(fnTy("foo", voidTy(), ptr(voidTy())), bindToNothing, "void foo(void *)", "foo");
+ addRow(fnTy("foo", voidTy(), ptr(voidTy())), bindToAll, "void foo(void*)", "foo");
+
+ // Functions with pointer or reference returns
+ addRow(ptr(fnTy("foo", ptr(voidTy()), intTy())), bindToNothing, "void *(*foo)(int)", "foo");
+ addRow(ptr(fnTy("foo", ptr(voidTy()), intTy())), bindToAll, "void*(*foo)(int)", "foo");
+
+ addRow(ptr(fnTy("foo", ref(voidTy()), ptr(voidTy()))), bindToNothing, "void &(*foo)(void *)", "foo");
+ addRow(ptr(fnTy("foo", ref(voidTy()), ptr(voidTy()))), bindToAll, "void&(*foo)(void*)", "foo");
+
+ addRow(fnTy("foo", ptr(voidTy()), intTy()), bindToNothing, "void *foo(int)", "foo");
+ addRow(fnTy("foo", ptr(voidTy()), intTy()), bindToAll, "void*foo(int)", "foo");
+
+ addRow(fnTy("foo", ref(voidTy()), ptr(voidTy())), bindToNothing, "void &foo(void *)", "foo");
+ addRow(fnTy("foo", ref(voidTy()), ptr(voidTy())), bindToAll, "void&foo(void*)", "foo");
}
void tst_TypePrettyPrinter::basic()
{
QFETCH(FullySpecifiedType, type);
+ QFETCH(Overview::StarBindFlags, starBindFlags);
QFETCH(QString, name);
QFETCH(QString, result);
Overview o;
- o.setShowReturnTypes(true);
+ o.showReturnTypes = true;
+ o.starBindFlags = starBindFlags;
TypePrettyPrinter pp(&o);
QCOMPARE(pp(type, name), result);
}
diff --git a/tests/auto/debugger/debugger.pro b/tests/auto/debugger/debugger.pro
index e3cebaa8f0..fa95b89dca 100644
--- a/tests/auto/debugger/debugger.pro
+++ b/tests/auto/debugger/debugger.pro
@@ -1,7 +1,10 @@
TEMPLATE = subdirs
-SUBDIRS = dumpers.pro version.pro namedemangler.pro
+SUBDIRS += version.pro
+SUBDIRS += dumpers.pro
+#SUBDIRS += olddumpers.pro
+SUBDIRS += namedemangler.pro
!win32-msvc*: SUBDIRS += gdb.pro
diff --git a/tests/auto/debugger/dumpers.pro b/tests/auto/debugger/dumpers.pro
index 3f7e295972..26594b5f0c 100644
--- a/tests/auto/debugger/dumpers.pro
+++ b/tests/auto/debugger/dumpers.pro
@@ -1,23 +1,25 @@
-greaterThan(QT_MAJOR_VERSION, 4): QT += core-private
+
include(../qttest.pri)
-include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
DEBUGGERDIR = $$IDE_SOURCE_TREE/src/plugins/debugger
-UTILSDIR = $$IDE_SOURCE_TREE/src/libs/utils
-MACROSDIR = $$IDE_SOURCE_TREE/share/qtcreator/dumper
+DUMPERDIR = $$IDE_SOURCE_TREE/share/qtcreator/dumper
SOURCES += \
- $$DEBUGGERDIR/gdb/gdbmi.cpp \
- $$MACROSDIR/dumper.cpp \
+ $$DEBUGGERDIR/debuggerprotocol.cpp \
+ $$DEBUGGERDIR/watchdata.cpp \
+ $$DEBUGGERDIR/watchutils.cpp \
tst_dumpers.cpp
-exists($$QMAKE_INCDIR_QT/QtCore/private/qobject_p.h):DEFINES += USE_PRIVATE
-
-DEFINES += MACROSDEBUG
-
-win32:DEFINES += _CRT_SECURE_NO_WARNINGS
+HEADERS += \
+ $$DEBUGGERDIR/debuggerprotocol.h \
+ $$DEBUGGERDIR/watchdata.h \
+ $$DEBUGGERDIR/watchutils.h \
-DEFINES -= QT_USE_FAST_CONCATENATION QT_USE_FAST_OPERATOR_PLUS
-DEFINES -= QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
+!isEmpty(vcproj) {
+ DEFINES += DUMPERDIR=\"$$DUMPERDIR\"
+} else {
+ DEFINES += DUMPERDIR=\\\"$$DUMPERDIR\\\"
+}
-INCLUDEPATH += $$DEBUGGERDIR $$UTILSDIR $$MACROSDIR
+INCLUDEPATH += $$DEBUGGERDIR
+DEFINES += QT_NO_CAST_FROM_ASCII
diff --git a/tests/auto/debugger/gdb.pro b/tests/auto/debugger/gdb.pro
index 164bb5b75e..7fc000fbc9 100644
--- a/tests/auto/debugger/gdb.pro
+++ b/tests/auto/debugger/gdb.pro
@@ -9,4 +9,4 @@ INCLUDEPATH += $$DEBUGGERDIR $$UTILSDIR
SOURCES += \
tst_gdb.cpp \
- $$DEBUGGERDIR/gdb/gdbmi.cpp \
+ $$DEBUGGERDIR/debuggerprotocol.cpp \
diff --git a/tests/auto/debugger/namedemangler.pro b/tests/auto/debugger/namedemangler.pro
index d175689fca..da9dba3a30 100644
--- a/tests/auto/debugger/namedemangler.pro
+++ b/tests/auto/debugger/namedemangler.pro
@@ -1,10 +1,9 @@
include(../qttest.pri)
-LIBS *= -L$$IDE_LIBRARY_PATH -lUtils
-
DEBUGGERDIR = $$IDE_SOURCE_TREE/src/plugins/debugger
INCLUDEPATH += $$DEBUGGERDIR
SOURCES = tst_namedemangler.cpp
include($$DEBUGGERDIR/namedemangler/namedemangler.pri)
+include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
diff --git a/tests/auto/debugger/olddumpers.pro b/tests/auto/debugger/olddumpers.pro
new file mode 100644
index 0000000000..82c17f71ea
--- /dev/null
+++ b/tests/auto/debugger/olddumpers.pro
@@ -0,0 +1,23 @@
+greaterThan(QT_MAJOR_VERSION, 4): QT += core-private
+include(../qttest.pri)
+include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+
+DEBUGGERDIR = $$IDE_SOURCE_TREE/src/plugins/debugger
+UTILSDIR = $$IDE_SOURCE_TREE/src/libs/utils
+MACROSDIR = $$IDE_SOURCE_TREE/share/qtcreator/dumper
+
+SOURCES += \
+ $$DEBUGGERDIR/gdb/gdbmi.cpp \
+ $$MACROSDIR/dumper.cpp \
+ tst_olddumpers.cpp
+
+exists($$QMAKE_INCDIR_QT/QtCore/private/qobject_p.h):DEFINES += USE_PRIVATE
+
+DEFINES += MACROSDEBUG
+
+win32:DEFINES += _CRT_SECURE_NO_WARNINGS
+
+DEFINES -= QT_USE_FAST_CONCATENATION QT_USE_FAST_OPERATOR_PLUS
+DEFINES -= QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
+
+INCLUDEPATH += $$DEBUGGERDIR $$UTILSDIR $$MACROSDIR
diff --git a/tests/auto/debugger/tst_dumpers.cpp b/tests/auto/debugger/tst_dumpers.cpp
index e8b04646a3..d5e88b3252 100644
--- a/tests/auto/debugger/tst_dumpers.cpp
+++ b/tests/auto/debugger/tst_dumpers.cpp
@@ -27,2475 +27,3924 @@
**
****************************************************************************/
-#define private public // Give us access to private 'backward' member of QMapNode.
-# include <QMap>
-#undef private
-
-#include "gdb/gdbmi.h"
-#include "dumper.h"
-#include "dumper_p.h"
-
-#include "json.h"
-
-#ifdef USE_PRIVATE
-#include <private/qobject_p.h>
-#else
-#warning "No private headers for this Qt version available"
-#endif
-
-#include <QStandardItemModel>
-#include <QStringListModel>
+#include "debuggerprotocol.h"
+#include "watchdata.h"
+#include "watchutils.h"
#include <QtTest>
-//#include <QtTest/qtest_gui.h>
-
-//TESTED_COMPONENT=src/plugins/debugger/gdb
-
-static const char *pointerPrintFormat()
-{
- return sizeof(quintptr) == sizeof(long) ? "0x%lx" : "0x%llx";
-}
-
-#undef NS
-#ifdef QT_NAMESPACE
-# define STRINGIFY0(s) #s
-# define STRINGIFY1(s) STRINGIFY0(s)
-# define NS STRINGIFY1(QT_NAMESPACE) "::"
-#else
-# define NS ""
-#endif
+#include <QTemporaryFile>
+#include <QTemporaryDir>
using namespace Debugger;
-using namespace Debugger::Internal;
+using namespace Internal;
-static QByteArray operator<<(QByteArray ba, const QByteArray &replacement)
+static QByteArray noValue = "\001";
+
+static QByteArray nameFromIName(const QByteArray &iname)
{
- int pos = ba.indexOf('%');
- Q_ASSERT(pos != -1);
- return ba.replace(pos, 1, replacement);
+ int pos = iname.lastIndexOf('.');
+ return pos == -1 ? iname : iname.mid(pos + 1);
}
-static QByteArray &operator<<=(QByteArray &ba, const QByteArray &replacement)
+static QByteArray parentIName(const QByteArray &iname)
{
- int pos = ba.indexOf('%');
- Q_ASSERT(pos != -1);
- return ba.replace(pos, 1, replacement);
+ int pos = iname.lastIndexOf('.');
+ return pos == -1 ? QByteArray() : iname.left(pos);
}
-
-template <typename T>
-inline QByteArray N(T t) { return QByteArray::number(t); }
-
-static const char gdbmi1[] =
- "[frame={level=\"0\",addr=\"0x00000000004061ca\","
- "func=\"main\",file=\"test1.cpp\","
- "fullname=\"/home/apoenitz/work/test1/test1.cpp\",line=\"209\"}]";
-
-static const char gdbmi2[] =
- "[frame={level=\"0\",addr=\"0x00002ac058675840\","
- "func=\"QApplication\",file=\"/home/apoenitz/dev/qt/src/gui/kernel/qapplication.cpp\","
- "fullname=\"/home/apoenitz/dev/qt/src/gui/kernel/qapplication.cpp\",line=\"592\"},"
- "frame={level=\"1\",addr=\"0x00000000004061e0\",func=\"main\",file=\"test1.cpp\","
- "fullname=\"/home/apoenitz/work/test1/test1.cpp\",line=\"209\"}]";
-
-static const char gdbmi3[] =
- "[stack={frame={level=\"0\",addr=\"0x00000000004061ca\","
- "func=\"main\",file=\"test1.cpp\","
- "fullname=\"/home/apoenitz/work/test1/test1.cpp\",line=\"209\"}}]";
-
-static const char gdbmi4[] =
- "&\"source /home/apoenitz/dev/ide/main/bin/gdb/qt4macros\\n\""
- "4^done\n";
-
-static const char gdbmi5[] =
- "[reason=\"breakpoint-hit\",bkptno=\"1\",thread-id=\"1\","
- "frame={addr=\"0x0000000000405738\",func=\"main\","
- "args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\"0x7fff1ac78f28\"}],"
- "file=\"test1.cpp\",fullname=\"/home/apoenitz/work/test1/test1.cpp\","
- "line=\"209\"}]";
-
-static const char gdbmi8[] =
- "[data={locals={{name=\"a\"},{name=\"w\"}}}]";
-
-static const char gdbmi9[] =
- "[data={locals=[name=\"baz\",name=\"urgs\",name=\"purgs\"]}]";
-
-static const char gdbmi10[] =
- "[name=\"urgs\",numchild=\"1\",type=\"Urgs\"]";
-
-static const char gdbmi11[] =
- "[{name=\"size\",value=\"1\",type=\"size_t\",readonly=\"true\"},"
- "{name=\"0\",value=\"one\",type=\"QByteArray\"}]";
-
-static const char gdbmi12[] =
- "[{iname=\"local.hallo\",value=\"\\\"\\\\\\00382\\t\\377\",type=\"QByteArray\","
- "numchild=\"0\"}]";
-
-
-static const char jsont1[] =
- "{\"Size\":100564,\"UID\":0,\"GID\":0,\"Permissions\":33261,"
- "\"ATime\":1242370878000,\"MTime\":1239154689000}";
-
-struct Int3 {
- Int3() { i1 = 42; i2 = 43; i3 = 44; }
- int i1, i2, i3;
-};
-
-struct QString3 {
- QString3() { s1 = "a"; s2 = "b"; s3 = "c"; }
- QString s1, s2, s3;
-};
-
-class tst_Dumpers : public QObject
+struct Value
{
- Q_OBJECT
-
-public:
- tst_Dumpers() {}
+ Value()
+ : value(noValue), hasPtrSuffix(false)
+ {}
+ Value(const char *str)
+ : value(str), hasPtrSuffix(false)
+ {}
+ Value(const QByteArray &ba)
+ : value(ba), hasPtrSuffix(false)
+ {}
- void testMi(const char* input)
+ bool matches(const QString &actualValue0) const
{
- GdbMi gdbmi;
- gdbmi.fromString(QByteArray(input));
- QCOMPARE('\n' + QString::fromLatin1(gdbmi.toString(false)),
- '\n' + QString(input));
+ if (value == noValue)
+ return true;
+ QString actualValue = actualValue0;
+ if (actualValue == QLatin1String(" "))
+ actualValue.clear(); // FIXME: Remove later.
+ QString self = QString::fromLatin1(value.data(), value.size());
+ if (hasPtrSuffix)
+ return actualValue.startsWith(self + QLatin1String(" @0x"))
+ || actualValue.startsWith(self + QLatin1String("@0x"));
+ return actualValue == self;
}
- void testJson(const char* input)
- {
- QCOMPARE('\n' + Utils::JsonStringValue(QLatin1String(input)).value(),
- '\n' + QString(input));
- }
-
-private slots:
- void mi1() { testMi(gdbmi1); }
- void mi2() { testMi(gdbmi2); }
- void mi3() { testMi(gdbmi3); }
- //void mi4() { testMi(gdbmi4); }
- void mi5() { testMi(gdbmi5); }
- void mi8() { testMi(gdbmi8); }
- void mi9() { testMi(gdbmi9); }
- void mi10() { testMi(gdbmi10); }
- void mi11() { testMi(gdbmi11); }
- //void mi12() { testMi(gdbmi12); }
-
- void json1() { testJson(jsont1); }
-
- void infoBreak();
- void niceType();
- void niceType_data();
-
- void dumperCompatibility();
- void dumpQAbstractItemAndModelIndex();
- void dumpQAbstractItemModel();
- void dumpQByteArray();
- void dumpQChar();
- void dumpQDateTime();
- void dumpQDir();
- void dumpQFile();
- void dumpQFileInfo();
- void dumpQHash();
- void dumpQHashNode();
- void dumpQImage();
- void dumpQImageData();
- void dumpQLinkedList();
- void dumpQList_int();
- void dumpQList_int_star();
- void dumpQList_char();
- void dumpQList_QString();
- void dumpQList_QString3();
- void dumpQList_Int3();
- void dumpQLocale();
- void dumpQMap();
- void dumpQMapNode();
-#ifdef USE_PRIVATE
- void dumpQObject();
- void dumpQObjectChildList();
- void dumpQObjectMethodList();
- void dumpQObjectPropertyList();
- void dumpQObjectSignal();
- void dumpQObjectSignalList();
- void dumpQObjectSlot();
- void dumpQObjectSlotList();
-#endif
- void dumpQPixmap();
- void dumpQSharedPointer();
- void dumpQString();
- void dumpQTextCodec();
- void dumpQVariant_invalid();
- void dumpQVariant_QString();
- void dumpQVariant_QStringList();
-#ifndef Q_CC_MSVC
- void dumpStdVector();
-#endif // !Q_CC_MSVC
- void dumpQWeakPointer();
- void initTestCase();
-
-private:
- void dumpQAbstractItemHelper(QModelIndex &index);
- void dumpQAbstractItemModelHelper(QAbstractItemModel &m);
- template <typename K, typename V> void dumpQHashNodeHelper(QHash<K, V> &hash);
- void dumpQImageHelper(const QImage &img);
- void dumpQImageDataHelper(QImage &img);
- template <typename T> void dumpQLinkedListHelper(QLinkedList<T> &l);
- void dumpQLocaleHelper(QLocale &loc);
- template <typename K, typename V> void dumpQMapHelper(QMap<K, V> &m);
- template <typename K, typename V> void dumpQMapNodeHelper(QMap<K, V> &m);
- void dumpQObjectChildListHelper(QObject &o);
- void dumpQObjectSignalHelper(QObject &o, int sigNum);
-#if QT_VERSION >= 0x040500
- template <typename T>
- void dumpQSharedPointerHelper(QSharedPointer<T> &ptr);
- template <typename T>
- void dumpQWeakPointerHelper(QWeakPointer<T> &ptr);
-#endif
- void dumpQTextCodecHelper(QTextCodec *codec);
+ QByteArray value;
+ bool hasPtrSuffix;
};
-void tst_Dumpers::infoBreak()
-{
- // This tests the regular expression used in GdbEngine::extractDataFromInfoBreak
- // to discover breakpoints in constructors.
-
- // Copied from gdbengine.cpp:
-
- QRegExp re("MULTIPLE.*(0x[0-9a-f]+) in (.*)\\s+at (.*):([\\d]+)([^\\d]|$)");
- re.setMinimal(true);
-
- QCOMPARE(re.indexIn(
- "2 breakpoint keep y <MULTIPLE> 0x0040168e\n"
- "2.1 y 0x0040168e "
- "in MainWindow::MainWindow(QWidget*) at mainwindow.cpp:7\n"
- "2.2 y 0x00401792 "
- "in MainWindow::MainWindow(QWidget*) at mainwindow.cpp:7\n"), 33);
- QCOMPARE(re.cap(1), QString("0x0040168e"));
- QCOMPARE(re.cap(2).trimmed(), QString("MainWindow::MainWindow(QWidget*)"));
- QCOMPARE(re.cap(3), QString("mainwindow.cpp"));
- QCOMPARE(re.cap(4), QString("7"));
-
-
- QCOMPARE(re.indexIn(
- "Num Type Disp Enb Address What"
- "4 breakpoint keep y <MULTIPLE> 0x00000000004066ad"
- "4.1 y 0x00000000004066ad in CTorTester"
- " at /main/tests/manual/gdbdebugger/simple/app.cpp:124"), 88);
-
- QCOMPARE(re.cap(1), QString("0x00000000004066ad"));
- QCOMPARE(re.cap(2).trimmed(), QString("CTorTester"));
- QCOMPARE(re.cap(3), QString("/main/tests/manual/gdbdebugger/simple/app.cpp"));
- QCOMPARE(re.cap(4), QString("124"));
-}
-
-//
-// type simplification
-//
-
-static QString chopConst(QString type)
-{
- while (1) {
- if (type.startsWith("const"))
- type = type.mid(5);
- else if (type.startsWith(' '))
- type = type.mid(1);
- else if (type.endsWith("const"))
- type.chop(5);
- else if (type.endsWith(' '))
- type.chop(1);
- else
- break;
- }
- return type;
-}
-
-QString niceType(QString type)
-{
- type.replace('*', '@');
-
- for (int i = 0; i < 10; ++i) {
- int start = type.indexOf("std::allocator<");
- if (start == -1)
- break;
- // search for matching '>'
- int pos;
- int level = 0;
- for (pos = start + 12; pos < type.size(); ++pos) {
- int c = type.at(pos).unicode();
- if (c == '<') {
- ++level;
- } else if (c == '>') {
- --level;
- if (level == 0)
- break;
- }
- }
- QString alloc = type.mid(start, pos + 1 - start).trimmed();
- QString inner = alloc.mid(15, alloc.size() - 16).trimmed();
- //qDebug() << "MATCH: " << pos << alloc << inner;
-
- if (inner == QLatin1String("char"))
- // std::string
- type.replace(QLatin1String("basic_string<char, std::char_traits<char>, "
- "std::allocator<char> >"), QLatin1String("string"));
- else if (inner == QLatin1String("wchar_t"))
- // std::wstring
- type.replace(QLatin1String("basic_string<wchar_t, std::char_traits<wchar_t>, "
- "std::allocator<wchar_t> >"), QLatin1String("wstring"));
-
- // std::vector, std::deque, std::list
- QRegExp re1(QString("(vector|list|deque)<%1, %2\\s*>").arg(inner, alloc));
- if (re1.indexIn(type) != -1)
- type.replace(re1.cap(0), QString("%1<%2>").arg(re1.cap(1), inner));
-
-
- // std::stack
- QRegExp re6(QString("stack<%1, std::deque<%2> >").arg(inner, inner));
- re6.setMinimal(true);
- if (re6.indexIn(type) != -1)
- type.replace(re6.cap(0), QString("stack<%1>").arg(inner));
-
- // std::set
- QRegExp re4(QString("set<%1, std::less<%2>, %3\\s*>").arg(inner, inner, alloc));
- re4.setMinimal(true);
- if (re4.indexIn(type) != -1)
- type.replace(re4.cap(0), QString("set<%1>").arg(inner));
-
-
- // std::map
- if (inner.startsWith("std::pair<")) {
- // search for outermost ','
- int pos;
- int level = 0;
- for (pos = 10; pos < inner.size(); ++pos) {
- int c = inner.at(pos).unicode();
- if (c == '<')
- ++level;
- else if (c == '>')
- --level;
- else if (c == ',' && level == 0)
- break;
- }
- QString ckey = inner.mid(10, pos - 10);
- QString key = chopConst(ckey);
- QString value = inner.mid(pos + 2, inner.size() - 3 - pos);
-
- QRegExp re5(QString("map<%1, %2, std::less<%3>, %4\\s*>")
- .arg(key, value, key, alloc));
- re5.setMinimal(true);
- if (re5.indexIn(type) != -1)
- type.replace(re5.cap(0), QString("map<%1, %2>").arg(key, value));
- else {
- QRegExp re7(QString("map<const %1, %2, std::less<const %3>, %4\\s*>")
- .arg(key, value, key, alloc));
- re7.setMinimal(true);
- if (re7.indexIn(type) != -1)
- type.replace(re7.cap(0), QString("map<const %1, %2>").arg(key, value));
- }
- }
- }
- type.replace('@', '*');
- type.replace(QLatin1String(" >"), QString(QLatin1Char('>')));
- return type;
-}
-
-void tst_Dumpers::niceType()
-{
- // cf. watchutils.cpp
- QFETCH(QString, input);
- QFETCH(QString, simplified);
- QCOMPARE(::niceType(input), simplified);
-}
-
-void tst_Dumpers::niceType_data()
+struct Pointer : Value
{
- QTest::addColumn<QString>("input");
- QTest::addColumn<QString>("simplified");
-
- QTest::newRow("list")
- << "std::list<int, std::allocator<int> >"
- << "std::list<int>";
-
- QTest::newRow("combined")
- << "std::vector<std::list<int, std::allocator<int> >*, "
- "std::allocator<std::list<int, std::allocator<int> >*> >"
- << "std::vector<std::list<int>*>";
-
- QTest::newRow("stack")
- << "std::stack<int, std::deque<int, std::allocator<int> > >"
- << "std::stack<int>";
-
- QTest::newRow("map")
- << "std::map<myns::QString, Foo, std::less<myns::QString>, "
- "std::allocator<std::pair<const myns::QString, Foo> > >"
- << "std::map<myns::QString, Foo>";
-
- QTest::newRow("map2")
- << "std::map<const char*, Foo, std::less<const char*>, "
- "std::allocator<std::pair<const char* const, Foo> > >"
- << "std::map<const char*, Foo>";
-}
-
-//
-// Dumpers
-//
+ Pointer() { hasPtrSuffix = true; }
+ Pointer(const QByteArray &value) : Value(value) { hasPtrSuffix = true; }
+};
-static void testDumper(QByteArray expected0, const void *data, QByteArray outertype,
- bool dumpChildren, QByteArray innertype = "", QByteArray exp = "",
- int extraInt0 = 0, int extraInt1 = 0, int extraInt2 = 0, int extraInt3 = 0)
-{
- sprintf(xDumpInBuffer, "%s%c%s%c%s%c%s%c%s%c",
- outertype.data(), 0, "iname", 0, exp.data(), 0,
- innertype.data(), 0, "iname", 0);
- //qDebug() << "FIXME qDumpObjectData440 signature to use const void *";
- void *res = qDumpObjectData440(2, 42, data, dumpChildren,
- extraInt0, extraInt1, extraInt2, extraInt3);
- QString expected(expected0);
- char buf[100];
- sprintf(buf, pointerPrintFormat(), (quintptr)data);
- if ((!expected.startsWith('t') && !expected.startsWith('f'))
- || expected.startsWith("type"))
- expected = "tiname='$I',addr='$A'," + expected;
- expected.replace("$I", "iname");
- expected.replace("$T", QByteArray(outertype));
- expected.replace("$A", QByteArray(buf));
- expected.replace('\'', '"');
- QString actual____ = QString::fromLatin1(xDumpOutBuffer);
- actual____.replace('\'', '"');
- QCOMPARE(res, xDumpOutBuffer);
- if (actual____ != expected) {
- QStringList l1 = actual____.split(",");
- QStringList l2 = expected.split(",");
- for (int i = 0; i < l1.size() && i < l2.size(); ++i) {
- if (l1.at(i) == l2.at(i))
- qWarning() << "== " << l1.at(i);
- else
- //qWarning() << "!= " << l1.at(i).right(30) << l2.at(i).right(30);
- qWarning() << "!= " << l1.at(i) << l2.at(i);
- }
- if (l1.size() != l2.size())
- qWarning() << "!= size: " << l1.size() << l2.size();
+struct Type
+{
+ Type()
+ {}
+ Type(const char *str)
+ : type(str)
+ {}
+ Type(const QByteArray &ba)
+ : type(ba)
+ {}
+ bool matches(const QByteArray &actualType0, const QByteArray &nameSpace) const
+ {
+ QByteArray actualType = actualType0;
+ actualType.replace(' ', "");
+ QByteArray expectedType = type;
+ expectedType.replace(' ', "");
+ expectedType.replace('@', nameSpace);
+ return actualType == expectedType;
}
- QCOMPARE(actual____, expected);
-}
-
-QByteArray str(const void *p)
-{
- char buf[100];
- sprintf(buf, pointerPrintFormat(), (quintptr)p);
- return buf;
-}
+ QByteArray type;
+};
-static const void *deref(const void *p)
+struct Deque : Type
{
- return *reinterpret_cast<const char* const*>(p);
-}
+ Deque(const QByteArray &inner)
+ : Type("std::deque<" + inner + ", std::allocator<" + inner + ">>")
+ {}
+};
-void tst_Dumpers::dumperCompatibility()
+struct Check
{
- // Ensure that no arbitrary padding is introduced by QVectorTypedData.
- const size_t qVectorDataSize = 16;
- QCOMPARE(sizeof(QVectorData), qVectorDataSize);
- QVectorTypedData<int> *v = 0;
- QCOMPARE(size_t(&v->array), qVectorDataSize);
-}
+ Check() {}
-static const QByteArray utfToBase64(const QString &string)
-{
- return QByteArray(reinterpret_cast<const char *>(string.utf16()), 2 * string.size()).toBase64();
-}
+ Check(const QByteArray &iname, const Value &value,
+ const Type &type)
+ : iname(iname), expectedName(nameFromIName(iname)),
+ expectedValue(value), expectedType(type)
+ {}
-static const char *boolToVal(bool b)
-{
- return b ? "'true'" : "'false'";
-}
+ Check(const QByteArray &iname, const QByteArray &name,
+ const Value &value, const Type &type)
+ : iname(iname), expectedName(name),
+ expectedValue(value), expectedType(type)
+ {}
-static const QByteArray ptrToBa(const void *p, bool symbolicNull = true)
-{
- return QByteArray().append(p == 0 && symbolicNull ?
- "<null>" :
- QByteArray("0x") + QByteArray::number((quintptr) p, 16));
-}
+ QByteArray iname;
+ QByteArray expectedName;
+ Value expectedValue;
+ Type expectedType;
+};
-static const QByteArray generateQStringSpec(const QString &str, bool isNull = false)
+struct CheckType : public Check
{
- if (isNull)
- return QByteArray("value='IiIgKG51bGwp',valueencoded='5',"
- "type='" NS "QString',numchild='0'");
- return
- QByteArray("value='%',valueencoded='2',type='" NS "QString',numchild='0'")
- << utfToBase64(str);
-}
+ CheckType(const QByteArray &iname, const QByteArray &name,
+ const Type &type)
+ : Check(iname, name, noValue, type)
+ {}
-static const QByteArray generateQCharSpec(const QChar& ch)
-{
- return QByteArray("value='%',valueencoded='2',type='" NS "QChar',numchild='0'")
- << utfToBase64(QString(QLatin1String("'%1' (%2, 0x%3)")).
- arg(ch).arg(ch.unicode()).arg(ch.unicode(), 0, 16));
-}
+ CheckType(const QByteArray &iname, const Type &type)
+ : Check(iname, noValue, type)
+ {}
+};
-static const QByteArray generateBoolSpec(bool b)
+struct Profile
{
- return QByteArray("value=%,type='bool',numchild='0'")
- << boolToVal(b);
-}
+ Profile(const QByteArray &contents) : contents(contents) {}
-static const QByteArray generateLongSpec(long n)
-{
- return QByteArray("value='%',type='long',numchild='0'")
- << N(qlonglong(n));
-}
+ QByteArray contents;
+};
-static const QByteArray generateIntSpec(int n)
+struct GuiProfile : public Profile
{
- return QByteArray("value='%',type='int',numchild='0'")
- << N(n);
-}
+ GuiProfile() : Profile("QT+=gui\ngreaterThan(QT_MAJOR_VERSION, 4):QT *= widgets\n") {}
+};
-const QByteArray createExp(const void *ptr,
- const QByteArray &type, const QByteArray &method)
+struct Cxx11Profile : public Profile
{
- return QByteArray("exp='((" NSX "%" NSY "*)%)->%'")
- << type << ptrToBa(ptr) << method;
-}
+ //Cxx11Profile() : Profile("CONFIG += c++11") {}
+ Cxx11Profile() : Profile("QMAKE_CXXFLAGS += -std=c++0x") {}
+};
-// Helper functions.
+struct ForceC {};
-template <typename T> static const char *typeToString()
-{
- return "<unknown type>";
-}
-template <typename T> const QByteArray valToString(const T &)
-{
- return "<unknown value>";
-}
-template <> const QByteArray valToString(const int &n)
+class Data
{
- return QByteArray().append(N(n));
-}
-template <> const QByteArray valToString(const QString &s)
-{
- return QByteArray(utfToBase64(s)).append("',valueencoded='2");
-}
-template <> const QByteArray valToString(int * const &p)
-{
- return ptrToBa(p);
-}
-template <typename T> const QByteArray derefValToString(const T &v)
-{
- return valToString(v);
-}
-template <> const QByteArray derefValToString(int * const &ptr)
-{
- return valToString(*ptr);
-}
-const QString stripPtrType(const QString &ptrTypeStr)
-{
- return ptrTypeStr.mid(0, ptrTypeStr.size() - 2);
-}
-template <> const char *typeToString<int>()
-{
- return "int";
-}
-template <> const char *typeToString<QString>()
-{
- return NS"QString";
-}
-template <> const char *typeToString<int *>()
-{
- return "int *";
-}
-template <typename T> bool isSimpleType()
-{
- return false;
-}
-template <> bool isSimpleType<int>()
-{
- return true;
-}
-template <typename T> bool isPointer()
-{
- return false;
-}
-template <> bool isPointer<int *>()
-{
- return true;
-}
-
-template <typename T> static const char *typeToNumchild()
-{
- return "1";
-}
-template <> const char *typeToNumchild<int>()
-{
- return "0";
-}
-template <> const char *typeToNumchild<QString>()
-{
- return "0";
-}
-template <typename K, typename V>
-QByteArray getMapType()
-{
- return QByteArray(typeToString<K>()) + "@" + QByteArray(typeToString<V>());
-}
-template <typename K, typename V>
-void getMapNodeParams(size_t &nodeSize, size_t &valOffset)
-{
-#if QT_VERSION >= 0x040500
- typedef QMapNode<K, V> NodeType;
- NodeType *node = 0;
- nodeSize = sizeof(NodeType);
- valOffset = size_t(&node->value);
-#else
- nodeSize = sizeof(K) + sizeof(V) + 2*sizeof(void *);
- valOffset = sizeof(K);
-#endif
-}
+public:
+ Data() {}
+ Data(const QByteArray &code) : code(code), forceC(false) {}
-void tst_Dumpers::dumpQAbstractItemHelper(QModelIndex &index)
-{
- const QAbstractItemModel *model = index.model();
- const QString &rowStr = N(index.row());
- const QString &colStr = N(index.column());
- const QByteArray &internalPtrStrSymbolic = ptrToBa(index.internalPointer());
- const QByteArray &internalPtrStrValue = ptrToBa(index.internalPointer(), false);
- const QByteArray &modelPtrStr = ptrToBa(model);
- QByteArray indexSpecSymbolic = QByteArray().append(rowStr + "," + colStr + ",").
- append(internalPtrStrSymbolic + "," + modelPtrStr);
- QByteArray indexSpecValue = QByteArray().append(rowStr + "," + colStr + ",").
- append(internalPtrStrValue + "," + modelPtrStr);
- QByteArray expected = QByteArray("tiname='iname',addr='").append(ptrToBa(&index)).
- append("',type='" NS "QAbstractItem',addr='$").append(indexSpecSymbolic).
- append("',value='").append(valToString(model->data(index).toString())).
- append("',numchild='%',children=[");
- int rowCount = model->rowCount(index);
- int columnCount = model->columnCount(index);
- expected <<= N(rowCount * columnCount);
- for (int row = 0; row < rowCount; ++row) {
- for (int col = 0; col < columnCount; ++col) {
- const QModelIndex &childIndex = model->index(row, col, index);
- expected.append("{name='[").append(valToString(row)).append(",").
- append(N(col)).append("]',numchild='%',addr='$").
- append(N(childIndex.row())).append(",").
- append(N(childIndex.column())).append(",").
- append(ptrToBa(childIndex.internalPointer())).append(",").
- append(modelPtrStr).append("',type='" NS "QAbstractItem',value='").
- append(valToString(model->data(childIndex).toString())).append("'}");
- expected <<= N(model->rowCount(childIndex)
- * model->columnCount(childIndex));
- if (col < columnCount - 1 || row < rowCount - 1)
- expected.append(",");
- }
- }
- expected.append("]");
- testDumper(expected, &index, NS"QAbstractItem", true, indexSpecValue);
-}
+ Data(const QByteArray &includes, const QByteArray &code)
+ : includes(includes), code(code), forceC(false)
+ {}
-void tst_Dumpers::dumpQAbstractItemAndModelIndex()
-{
- class PseudoTreeItemModel : public QAbstractItemModel
+ const Data &operator%(const Check &check) const
{
- public:
- PseudoTreeItemModel() : QAbstractItemModel(), parent1(0),
- parent1Child(1), parent2(10), parent2Child1(11), parent2Child2(12)
- {}
-
- int columnCount(const QModelIndex &parent = QModelIndex()) const
- {
- Q_UNUSED(parent);
- return 1;
- }
-
- QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
- {
- return !index.isValid() || role != Qt::DisplayRole ?
- QVariant() : *static_cast<int *>(index.internalPointer());
- }
-
- QModelIndex index(int row, int column,
- const QModelIndex & parent = QModelIndex()) const
- {
- QModelIndex index;
- if (column == 0) {
- if (!parent.isValid()) {
- if (row == 0)
- index = createIndex(row, column, &parent1);
- else if (row == 1)
- index = createIndex(row, column, &parent2);
- } else if (parent.internalPointer() == &parent1 && row == 0) {
- index = createIndex(row, column, &parent1Child);
- } else if (parent.internalPointer() == &parent2) {
- index = createIndex(row, column,
- row == 0 ? &parent2Child1 : &parent2Child2);
- }
- }
- return index;
- }
-
- QModelIndex parent(const QModelIndex & index) const
- {
- QModelIndex parent;
- if (index.isValid()) {
- if (index.internalPointer() == &parent1Child)
- parent = createIndex(0, 0, &parent1);
- else if (index.internalPointer() == &parent2Child1 ||
- index.internalPointer() == &parent2Child2)
- parent = createIndex(1, 0, &parent2);
- }
- return parent;
- }
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const
- {
- int rowCount;
- if (!parent.isValid() || parent.internalPointer() == &parent2)
- rowCount = 2;
- else if (parent.internalPointer() == &parent1)
- rowCount = 1;
- else
- rowCount = 0;
- return rowCount;
- }
-
- private:
- mutable int parent1;
- mutable int parent1Child;
- mutable int parent2;
- mutable int parent2Child1;
- mutable int parent2Child2;
- };
-
- PseudoTreeItemModel m2;
-
- // Case 1: ModelIndex with no children.
- QStringListModel m(QStringList() << "item1" << "item2" << "item3");
- QModelIndex index = m.index(2, 0);
-
- testDumper(QByteArray("type='$T',value='(2, 0)',numchild='5',children=["
- "{name='row',value='2',type='int',numchild='0'},"
- "{name='column',value='0',type='int',numchild='0'},"
- "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
- "type='$T',numchild='1'},"
- "{name='internalId',%},"
- "{name='model',value='%',type='" NS "QAbstractItemModel*',"
- "numchild='1'}]")
- << generateQStringSpec(N(index.internalId()))
- << ptrToBa(&m),
- &index, NS"QModelIndex", true);
-
- // Case 2: ModelIndex with one child.
- QModelIndex index2 = m2.index(0, 0);
- dumpQAbstractItemHelper(index2);
-
- qDebug() << "FIXME: invalid indices should not have children";
- testDumper(QByteArray("type='$T',value='(0, 0)',numchild='5',children=["
- "{name='row',value='0',type='int',numchild='0'},"
- "{name='column',value='0',type='int',numchild='0'},"
- "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
- "type='$T',numchild='1'},"
- "{name='internalId',%},"
- "{name='model',value='%',type='" NS "QAbstractItemModel*',"
- "numchild='1'}]")
- << generateQStringSpec(N(index2.internalId()))
- << ptrToBa(&m2),
- &index2, NS"QModelIndex", true);
-
-
- // Case 3: ModelIndex with two children.
- QModelIndex index3 = m2.index(1, 0);
- dumpQAbstractItemHelper(index3);
-
- testDumper(QByteArray("type='$T',value='(1, 0)',numchild='5',children=["
- "{name='row',value='1',type='int',numchild='0'},"
- "{name='column',value='0',type='int',numchild='0'},"
- "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
- "type='$T',numchild='1'},"
- "{name='internalId',%},"
- "{name='model',value='%',type='" NS "QAbstractItemModel*',"
- "numchild='1'}]")
- << generateQStringSpec(N(index3.internalId()))
- << ptrToBa(&m2),
- &index3, NS"QModelIndex", true);
-
-
- // Case 4: ModelIndex with a parent.
- index = m2.index(0, 0, index3);
- testDumper(QByteArray("type='$T',value='(0, 0)',numchild='5',children=["
- "{name='row',value='0',type='int',numchild='0'},"
- "{name='column',value='0',type='int',numchild='0'},"
- "{name='parent',value='(1, 0)',exp='(('$T'*)$A)->parent()',"
- "type='$T',numchild='1'},"
- "{name='internalId',%},"
- "{name='model',value='%',type='" NS "QAbstractItemModel*',"
- "numchild='1'}]")
- << generateQStringSpec(N(index.internalId()))
- << ptrToBa(&m2),
- &index, NS"QModelIndex", true);
-
-
- // Case 5: Empty ModelIndex
- QModelIndex index4;
- testDumper("type='$T',value='<invalid>',numchild='0'",
- &index4, NS"QModelIndex", true);
-}
-
-void tst_Dumpers::dumpQAbstractItemModelHelper(QAbstractItemModel &m)
-{
- QByteArray address = ptrToBa(&m);
- QByteArray expected = QByteArray("tiname='iname',addr='%',"
- "type='" NS "QAbstractItemModel',value='(%,%)',numchild='1',children=["
- "{numchild='1',name='" NS "QObject',addr='%',value='%',"
- "valueencoded='2',type='" NS "QObject',displayedtype='%'}")
- << address
- << N(m.rowCount())
- << N(m.columnCount())
- << address
- << utfToBase64(m.objectName())
- << m.metaObject()->className();
-
- for (int row = 0; row < m.rowCount(); ++row) {
- for (int column = 0; column < m.columnCount(); ++column) {
- QModelIndex mi = m.index(row, column);
- expected.append(QByteArray(",{name='[%,%]',value='%',"
- "valueencoded='2',numchild='%',addr='$%,%,%,%',"
- "type='" NS "QAbstractItem'}")
- << N(row)
- << N(column)
- << utfToBase64(m.data(mi).toString())
- << N(row * column)
- << N(mi.row())
- << N(mi.column())
- << ptrToBa(mi.internalPointer())
- << ptrToBa(mi.model()));
- }
+ checks.insert("local." + check.iname, check);
+ return *this;
}
- expected.append("]");
- testDumper(expected, &m, NS"QAbstractItemModel", true);
-}
-
-void tst_Dumpers::dumpQAbstractItemModel()
-{
- // Case 1: No rows, one column.
- QStringList strList;
- QStringListModel model(strList);
- dumpQAbstractItemModelHelper(model);
-
- // Case 2: One row, one column.
- strList << "String 1";
- model.setStringList(strList);
- dumpQAbstractItemModelHelper(model);
-
- // Case 3: Two rows, one column.
- strList << "String 2";
- model.setStringList(strList);
- dumpQAbstractItemModelHelper(model);
-
- // Case 4: No rows, two columns.
- QStandardItemModel model2(0, 2);
- dumpQAbstractItemModelHelper(model2);
-
- // Case 5: One row, two columns.
- QStandardItem item1("Item (0,0)");
- QStandardItem item2("(Item (0,1)");
- model2.appendRow(QList<QStandardItem *>() << &item1 << &item2);
- dumpQAbstractItemModelHelper(model2);
-
- // Case 6: Two rows, two columns
- QStandardItem item3("Item (1,0");
- QStandardItem item4("Item (1,1)");
- model2.appendRow(QList<QStandardItem *>() << &item3 << &item4);
- dumpQAbstractItemModelHelper(model);
-}
-
-void tst_Dumpers::dumpQByteArray()
-{
- // Case 1: Empty object.
- QByteArray ba;
- testDumper("value='',valueencoded='1',type='" NS "QByteArray',numchild='0',"
- "childtype='char',childnumchild='0',children=[]",
- &ba, NS"QByteArray", true);
-
- // Case 2: One element.
- ba.append('a');
- testDumper("value='YQ==',valueencoded='1',type='" NS "QByteArray',numchild='1',"
- "childtype='char',childnumchild='0',children=[{value='61 (97 'a')'}]",
- &ba, NS"QByteArray", true);
-
- // Case 3: Two elements.
- ba.append('b');
- testDumper("value='YWI=',valueencoded='1',type='" NS "QByteArray',numchild='2',"
- "childtype='char',childnumchild='0',children=["
- "{value='61 (97 'a')'},{value='62 (98 'b')'}]",
- &ba, NS"QByteArray", true);
-
- // Case 4: > 100 elements.
- ba = QByteArray(101, 'a');
- QByteArray children;
- for (int i = 0; i < 101; i++)
- children.append("{value='61 (97 'a')'},");
- children.chop(1);
- testDumper(QByteArray("value='YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"
- "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"
- "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ== <size: 101, cut...>',"
- "valueencoded='1',type='" NS "QByteArray',numchild='101',"
- "childtype='char',childnumchild='0',children=[%]") << children,
- &ba, NS"QByteArray", true);
-
- // Case 5: Regular and special characters and the replacement character.
- ba = QByteArray("abc\a\n\r\033\'\"?");
- testDumper("value='YWJjBwoNGyciPw==',valueencoded='1',type='" NS "QByteArray',"
- "numchild='10',childtype='char',childnumchild='0',children=["
- "{value='61 (97 'a')'},{value='62 (98 'b')'},"
- "{value='63 (99 'c')'},{value='07 (7 '?')'},"
- "{value='0a (10 '?')'},{value='0d (13 '?')'},"
- "{value='1b (27 '?')'},{value='27 (39 '?')'},"
- "{value='22 (34 '?')'},{value='3f (63 '?')'}]",
- &ba, NS"QByteArray", true);
-}
-
-void tst_Dumpers::dumpQChar()
-{
- // Case 1: Printable ASCII character.
- QChar c('X');
- testDumper("value=''X', ucs=88',numchild='0'",
- &c, NS"QChar", false);
-
- // Case 2: Printable non-ASCII character.
- c = QChar(0x600);
- testDumper("value=''?', ucs=1536',numchild='0'",
- &c, NS"QChar", false);
-
- // Case 3: Non-printable ASCII character.
- c = QChar::fromAscii('\a');
- testDumper("value=''?', ucs=7',numchild='0'",
- &c, NS"QChar", false);
-
- // Case 4: Non-printable non-ASCII character.
- c = QChar(0x9f);
- testDumper("value=''?', ucs=159',numchild='0'",
- &c, NS"QChar", false);
-
- // Case 5: Printable ASCII Character that looks like the replacement character.
- c = QChar::fromAscii('?');
- testDumper("value=''?', ucs=63',numchild='0'",
- &c, NS"QChar", false);
-}
-
-void tst_Dumpers::dumpQDateTime()
-{
- // Case 1: Null object.
- QDateTime d;
- testDumper("value='(null)',type='$T',numchild='0'",
- &d, NS"QDateTime", true);
-
- // Case 2: Non-null object.
- d = QDateTime::currentDateTime();
- testDumper(QByteArray("value='%',valueencoded='2',"
- "type='$T',numchild='1',children=["
- "{name='toTime_t',%},"
- "{name='toString',%},"
- "{name='toString_(ISO)',%},"
- "{name='toString_(SystemLocale)',%},"
- "{name='toString_(Locale)',%}]")
- << utfToBase64(d.toString())
- << generateLongSpec((d.toTime_t()))
- << generateQStringSpec(d.toString())
- << generateQStringSpec(d.toString(Qt::ISODate))
- << generateQStringSpec(d.toString(Qt::SystemLocaleDate))
- << generateQStringSpec(d.toString(Qt::LocaleDate)),
- &d, NS"QDateTime", true);
-
-}
-
-void tst_Dumpers::dumpQDir()
-{
- // Case 1: Current working directory.
- QDir dir = QDir::current();
- testDumper(QByteArray("value='%',valueencoded='2',type='" NS "QDir',numchild='3',"
- "children=[{name='absolutePath',%},{name='canonicalPath',%}]")
- << utfToBase64(dir.absolutePath())
- << generateQStringSpec(dir.absolutePath())
- << generateQStringSpec(dir.canonicalPath()),
- &dir, NS"QDir", true);
-
- // Case 2: Root directory.
- dir = QDir::root();
- testDumper(QByteArray("value='%',valueencoded='2',type='" NS "QDir',numchild='3',"
- "children=[{name='absolutePath',%},{name='canonicalPath',%}]")
- << utfToBase64(dir.absolutePath())
- << generateQStringSpec(dir.absolutePath())
- << generateQStringSpec(dir.canonicalPath()),
- &dir, NS"QDir", true);
-}
-
-
-void tst_Dumpers::dumpQFile()
-{
- // Case 1: Empty file name => Does not exist.
- QFile file1("");
- testDumper(QByteArray("value='',valueencoded='2',type='$T',numchild='2',"
- "children=[{name='fileName',value='',valueencoded='2',type='" NS "QString',"
- "numchild='0'},"
- "{name='exists',value='false',type='bool',numchild='0'}]"),
- &file1, NS"QFile", true);
-
- // Case 2: File that is known to exist.
- QTemporaryFile file2;
- file2.open();
- testDumper(QByteArray("value='%',valueencoded='2',type='$T',numchild='2',"
- "children=[{name='fileName',value='%',valueencoded='2',type='" NS "QString',"
- "numchild='0'},"
- "{name='exists',value='true',type='bool',numchild='0'}]")
- << utfToBase64(file2.fileName()) << utfToBase64(file2.fileName()),
- &file2, NS"QFile", true);
-
- // Case 3: File with a name that most likely does not exist.
- QFile file3("jfjfdskjdflsdfjfdls");
- testDumper(QByteArray("value='%',valueencoded='2',type='$T',numchild='2',"
- "children=[{name='fileName',value='%',valueencoded='2',type='" NS "QString',"
- "numchild='0'},"
- "{name='exists',value='false',type='bool',numchild='0'}]")
- << utfToBase64(file3.fileName()) << utfToBase64(file3.fileName()),
- &file3, NS"QFile", true);
-}
-
-void tst_Dumpers::dumpQFileInfo()
-{
- QFileInfo fi(".");
- QByteArray expected("value='%',valueencoded='2',type='$T',numchild='3',"
- "children=["
- "{name='absolutePath',%},"
- "{name='absoluteFilePath',%},"
- "{name='canonicalPath',%},"
- "{name='canonicalFilePath',%},"
- "{name='completeBaseName',%},"
- "{name='completeSuffix',%},"
- "{name='baseName',%},"
-#ifdef QX
- "{name='isBundle',%},"
- "{name='bundleName',%},"
-#endif
- "{name='fileName',%},"
- "{name='filePath',%},"
- "{name='group',%},"
- "{name='owner',%},"
- "{name='path',%},"
- "{name='groupid',%},"
- "{name='ownerid',%},"
- "{name='permissions',value=' ',type='%',numchild='10',"
- "children=[{name='ReadOwner',%},{name='WriteOwner',%},"
- "{name='ExeOwner',%},{name='ReadUser',%},{name='WriteUser',%},"
- "{name='ExeUser',%},{name='ReadGroup',%},{name='WriteGroup',%},"
- "{name='ExeGroup',%},{name='ReadOther',%},{name='WriteOther',%},"
- "{name='ExeOther',%}]},"
- "{name='caching',%},"
- "{name='exists',%},"
- "{name='isAbsolute',%},"
- "{name='isDir',%},"
- "{name='isExecutable',%},"
- "{name='isFile',%},"
- "{name='isHidden',%},"
- "{name='isReadable',%},"
- "{name='isRelative',%},"
- "{name='isRoot',%},"
- "{name='isSymLink',%},"
- "{name='isWritable',%},"
- "{name='created',value='%',valueencoded='2',%,"
- "type='" NS "QDateTime',numchild='1'},"
- "{name='lastModified',value='%',valueencoded='2',%,"
- "type='" NS "QDateTime',numchild='1'},"
- "{name='lastRead',value='%',valueencoded='2',%,"
- "type='" NS "QDateTime',numchild='1'}]");
- expected <<= utfToBase64(fi.filePath());
- expected <<= generateQStringSpec(fi.absolutePath());
- expected <<= generateQStringSpec(fi.absoluteFilePath());
- expected <<= generateQStringSpec(fi.canonicalPath());
- expected <<= generateQStringSpec(fi.canonicalFilePath());
- expected <<= generateQStringSpec(fi.completeBaseName());
- expected <<= generateQStringSpec(fi.completeSuffix(), true);
- expected <<= generateQStringSpec(fi.baseName());
-#ifdef Q_OS_MACX
- expected <<= generateBoolSpec(fi.isBundle());
- expected <<= generateQStringSpec(fi.bundleName());
-#endif
- expected <<= generateQStringSpec(fi.fileName());
- expected <<= generateQStringSpec(fi.filePath());
- expected <<= generateQStringSpec(fi.group());
- expected <<= generateQStringSpec(fi.owner());
- expected <<= generateQStringSpec(fi.path());
- expected <<= generateLongSpec(fi.groupId());
- expected <<= generateLongSpec(fi.ownerId());
- QFile::Permissions perms = fi.permissions();
- expected <<= QByteArray(NS"QFile::Permissions");
- expected <<= generateBoolSpec((perms & QFile::ReadOwner) != 0);
- expected <<= generateBoolSpec((perms & QFile::WriteOwner) != 0);
- expected <<= generateBoolSpec((perms & QFile::ExeOwner) != 0);
- expected <<= generateBoolSpec((perms & QFile::ReadUser) != 0);
- expected <<= generateBoolSpec((perms & QFile::WriteUser) != 0);
- expected <<= generateBoolSpec((perms & QFile::ExeUser) != 0);
- expected <<= generateBoolSpec((perms & QFile::ReadGroup) != 0);
- expected <<= generateBoolSpec((perms & QFile::WriteGroup) != 0);
- expected <<= generateBoolSpec((perms & QFile::ExeGroup) != 0);
- expected <<= generateBoolSpec((perms & QFile::ReadOther) != 0);
- expected <<= generateBoolSpec((perms & QFile::WriteOther) != 0);
- expected <<= generateBoolSpec((perms & QFile::ExeOther) != 0);
- expected <<= generateBoolSpec(fi.caching());
- expected <<= generateBoolSpec(fi.exists());
- expected <<= generateBoolSpec(fi.isAbsolute());
- expected <<= generateBoolSpec(fi.isDir());
- expected <<= generateBoolSpec(fi.isExecutable());
- expected <<= generateBoolSpec(fi.isFile());
- expected <<= generateBoolSpec(fi.isHidden());
- expected <<= generateBoolSpec(fi.isReadable());
- expected <<= generateBoolSpec(fi.isRelative());
- expected <<= generateBoolSpec(fi.isRoot());
- expected <<= generateBoolSpec(fi.isSymLink());
- expected <<= generateBoolSpec(fi.isWritable());
- expected <<= utfToBase64(fi.created().toString());
- expected <<= createExp(&fi, "QFileInfo", "created()");
- expected <<= utfToBase64(fi.lastModified().toString());
- expected <<= createExp(&fi, "QFileInfo", "lastModified()");
- expected <<= utfToBase64(fi.lastRead().toString());
- expected <<= createExp(&fi, "QFileInfo", "lastRead()");
-
- testDumper(expected, &fi, NS"QFileInfo", true);
-}
-
-void tst_Dumpers::dumpQHash()
-{
- QHash<QString, QList<int> > hash;
- hash.insert("Hallo", QList<int>());
- hash.insert("Welt", QList<int>() << 1);
- hash.insert("!", QList<int>() << 1 << 2);
- hash.insert("!", QList<int>() << 1 << 2);
-}
-
-template <typename K, typename V>
-void tst_Dumpers::dumpQHashNodeHelper(QHash<K, V> &hash)
-{
- typename QHash<K, V>::iterator it = hash.begin();
- typedef QHashNode<K, V> HashNode;
- HashNode *dummy = 0;
- HashNode *node =
- reinterpret_cast<HashNode *>(reinterpret_cast<char *>(const_cast<K *>(&it.key())) -
- size_t(&dummy->key));
- const K &key = it.key();
- const V &val = it.value();
- QByteArray expected("value='");
- if (isSimpleType<V>())
- expected.append(valToString(val));
- expected.append("',numchild='2',children=[{name='key',type='").
- append(typeToString<K>()).append("',addr='").append(ptrToBa(&key)).
- append("'},{name='value',type='").append(typeToString<V>()).
- append("',addr='").append(ptrToBa(&val)).append("'}]");
- testDumper(expected, node, NS"QHashNode", true,
- getMapType<K, V>(), "", sizeof(it.key()), sizeof(it.value()));
-}
-
-void tst_Dumpers::dumpQHashNode()
-{
- // Case 1: simple type -> simple type.
- QHash<int, int> hash1;
- hash1[2] = 3;
- dumpQHashNodeHelper(hash1);
-
- // Case 2: simple type -> composite type.
- QHash<int, QString> hash2;
- hash2[5] = "String 7";
- dumpQHashNodeHelper(hash2);
-
- // Case 3: composite type -> simple type
- QHash<QString, int> hash3;
- hash3["String 11"] = 13;
- dumpQHashNodeHelper(hash3);
-
- // Case 4: composite type -> composite type
- QHash<QString, QString> hash4;
- hash4["String 17"] = "String 19";
- dumpQHashNodeHelper(hash4);
-}
-
-void tst_Dumpers::dumpQImageHelper(const QImage &img)
-{
- QByteArray expected = "value='(%x%)',type='" NS "QImage',numchild='0'"
- << N(img.width())
- << N(img.height());
- testDumper(expected, &img, NS"QImage", true);
-}
-
-void tst_Dumpers::dumpQImage()
-{
- // Case 1: Null image.
- QImage img;
- dumpQImageHelper(img);
-
- // Case 2: Normal image.
- img = QImage(3, 700, QImage::Format_RGB555);
- dumpQImageHelper(img);
-
- // Case 3: Invalid image.
- img = QImage(100, 0, QImage::Format_Invalid);
- dumpQImageHelper(img);
-}
-void tst_Dumpers::dumpQImageDataHelper(QImage &img)
-{
-#if QT_VERSION >= 0x050000
- QSKIP("QImage::numBytes deprecated");
-#else
- const QByteArray ba(QByteArray::fromRawData((const char*) img.bits(), img.numBytes()));
- QByteArray expected = QByteArray("tiname='$I',addr='$A',type='" NS "QImageData',").
- append("numchild='0',value='<hover here>',valuetooltipencoded='1',").
- append("valuetooltipsize='").append(N(ba.size())).append("',").
- append("valuetooltip='").append(ba.toBase64()).append("'");
- testDumper(expected, &img, NS"QImageData", false);
-#endif
-}
-
-void tst_Dumpers::dumpQImageData()
-{
- // Case 1: Null image.
- QImage img;
- dumpQImageDataHelper(img);
-
- // Case 2: Normal image.
- img = QImage(3, 700, QImage::Format_RGB555);
- dumpQImageDataHelper(img);
-
- // Case 3: Invalid image.
- img = QImage(100, 0, QImage::Format_Invalid);
- dumpQImageDataHelper(img);
-}
-
-template <typename T>
- void tst_Dumpers::dumpQLinkedListHelper(QLinkedList<T> &l)
-{
- const int size = qMin(l.size(), 1000);
- const QString &sizeStr = N(size);
- const QByteArray elemTypeStr = typeToString<T>();
- QByteArray expected = QByteArray("value='<").append(sizeStr).
- append(" items>',valueeditable='false',numchild='").append(sizeStr).
- append("',childtype='").append(elemTypeStr).append("',childnumchild='").
- append(typeToNumchild<T>()).append("',children=[");
- typename QLinkedList<T>::const_iterator iter = l.constBegin();
- for (int i = 0; i < size; ++i, ++iter) {
- expected.append("{");
- const T &curElem = *iter;
- if (isPointer<T>()) {
- const QString typeStr = stripPtrType(typeToString<T>());
- const QByteArray addrStr = valToString(curElem);
- if (curElem != 0) {
- expected.append("addr='").append(addrStr).append("',type='").
- append(typeStr).append("',value='").
- append(derefValToString(curElem)).append("'");
- } else {
- expected.append("addr='").append(ptrToBa(&curElem)).append("',type='").
- append(typeStr).append("',value='<null>',numchild='0'");
- }
- } else {
- expected.append("addr='").append(ptrToBa(&curElem)).
- append("',value='").append(valToString(curElem)).append("'");
- }
- expected.append("}");
- if (i < size - 1)
- expected.append(",");
+ const Data &operator%(const Profile &profile) const
+ {
+ profileExtra += profile.contents;
+ return *this;
}
- if (size < l.size())
- expected.append(",...");
- expected.append("]");
- testDumper(expected, &l, NS"QLinkedList", true, elemTypeStr);
-}
-
-void tst_Dumpers::dumpQLinkedList()
-{
- // Case 1: Simple element type.
- QLinkedList<int> l;
-
- // Case 1.1: Empty list.
- dumpQLinkedListHelper(l);
-
- // Case 1.2: One element.
- l.append(2);
- dumpQLinkedListHelper(l);
-
- // Case 1.3: Two elements
- l.append(3);
- dumpQLinkedListHelper(l);
-
- // Case 2: Composite element type.
- QLinkedList<QString> l2;
- // Case 2.1: Empty list.
- dumpQLinkedListHelper(l2);
-
- // Case 2.2: One element.
- l2.append("Teststring 1");
- dumpQLinkedListHelper(l2);
-
- // Case 2.3: Two elements.
- l2.append("Teststring 2");
- dumpQLinkedListHelper(l2);
-
- // Case 2.4: > 1000 elements.
- for (int i = 3; i <= 1002; ++i)
- l2.append("Test " + N(i));
-
- // Case 3: Pointer type.
- QLinkedList<int *> l3;
- l3.append(new int(5));
- l3.append(new int(7));
- l3.append(0);
- dumpQLinkedListHelper(l3);
-}
-
-# if 0
- void tst_Debugger::dumpQLinkedList()
+ const Data &operator%(const ForceC &) const
{
- // Case 1: Simple element type.
- QLinkedList<int> l;
-
- // Case 1.1: Empty list.
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "childtype='int',childnumchild='0',children=[]",
- &l, NS"QLinkedList", true, "int");
-
- // Case 1.2: One element.
- l.append(2);
- testDumper("value='<1 items>',valueeditable='false',numchild='1',"
- "childtype='int',childnumchild='0',children=[{addr='%',value='2'}]"
- << ptrToBa(l.constBegin().operator->()),
- &l, NS"QLinkedList", true, "int");
-
- // Case 1.3: Two elements
- l.append(3);
- QByteArray it0 = ptrToBa(l.constBegin().operator->());
- QByteArray it1 = ptrToBa(l.constBegin().operator++().operator->());
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "childtype='int',childnumchild='0',children=[{addr='%',value='2'},"
- "{addr='%',value='3'}]" << it0 << it1,
- &l, NS"QLinkedList", true, "int");
-
- // Case 2: Composite element type.
- QLinkedList<QString> l2;
- QLinkedList<QString>::const_iterator iter;
-
- // Case 2.1: Empty list.
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "childtype='" NS "QString',childnumchild='0',children=[]",
- &l2, NS"QLinkedList", true, NS"QString");
-
- // Case 2.2: One element.
- l2.append("Teststring 1");
- iter = l2.constBegin();
- qDebug() << *iter;
- testDumper("value='<1 items>',valueeditable='false',numchild='1',"
- "childtype='" NS "QString',childnumchild='0',children=[{addr='%',value='%',}]"
- << ptrToBa(iter.operator->()) << utfToBase64(*iter),
- &l2, NS"QLinkedList", true, NS"QString");
-
- // Case 2.3: Two elements.
- QByteArray expected = "value='<2 items>',valueeditable='false',numchild='2',"
- "childtype='int',childnumchild='0',children=[";
- iter = l2.constBegin();
- expected.append("{addr='%',%},"
- << ptrToBa(iter.operator->()) << utfToBase64(*iter));
- ++iter;
- expected.append("{addr='%',%}]"
- << ptrToBa(iter.operator->()) << utfToBase64(*iter));
- testDumper(expected,
- &l, NS"QLinkedList", true, NS"QString");
-
- // Case 2.4: > 1000 elements.
- for (int i = 3; i <= 1002; ++i)
- l2.append("Test " + N(i));
-
- expected = "value='<1002 items>',valueeditable='false',"
- "numchild='1002',childtype='" NS "QString',childnumchild='0',children=['";
- iter = l2.constBegin();
- for (int i = 0; i < 1002; ++i, ++iter)
- expected.append("{addr='%',value='%'},"
- << ptrToBa(iter.operator->()) << utfToBase64(*iter));
- expected.append(",...]");
- testDumper(expected, &l, NS"QLinkedList", true, NS"QString");
-
-
- // Case 3: Pointer type.
- QLinkedList<int *> l3;
- l3.append(new int(5));
- l3.append(new int(7));
- l3.append(0);
- //dumpQLinkedListHelper(l3);
- testDumper("", &l, NS"QLinkedList", true, NS"QString");
+ forceC = true;
+ return *this;
}
-# endif
-void tst_Dumpers::dumpQList_int()
-{
- QList<int> ilist;
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "internal='1',children=[]",
- &ilist, NS"QList", true, "int");
- ilist.append(1);
- ilist.append(2);
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "internal='1',childtype='int',childnumchild='0',children=["
- "{addr='" + str(&ilist.at(0)) + "',value='1'},"
- "{addr='" + str(&ilist.at(1)) + "',value='2'}]",
- &ilist, NS"QList", true, "int");
-}
-
-void tst_Dumpers::dumpQList_int_star()
-{
- QList<int *> ilist;
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "internal='1',children=[]",
- &ilist, NS"QList", true, "int*");
- ilist.append(new int(1));
- ilist.append(0);
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "internal='1',childtype='int*',childnumchild='1',children=["
- "{addr='" + str(deref(&ilist.at(0))) +
- "',type='int',value='1'},"
- "{value='<null>',numchild='0'}]",
- &ilist, NS"QList", true, "int*");
-}
-
-void tst_Dumpers::dumpQList_char()
-{
- QList<char> clist;
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "internal='1',children=[]",
- &clist, NS"QList", true, "char");
- clist.append('a');
- clist.append('b');
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "internal='1',childtype='char',childnumchild='0',children=["
- "{addr='" + str(&clist.at(0)) + "',value=''a', ascii=97'},"
- "{addr='" + str(&clist.at(1)) + "',value=''b', ascii=98'}]",
- &clist, NS"QList", true, "char");
-}
-
-void tst_Dumpers::dumpQList_QString()
-{
- QList<QString> slist;
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "internal='1',children=[]",
- &slist, NS"QList", true, NS"QString");
- slist.append("a");
- slist.append("b");
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "internal='1',childtype='" NS "QString',childnumchild='0',children=["
- "{addr='" + str(&slist.at(0)) + "',value='YQA=',valueencoded='2'},"
- "{addr='" + str(&slist.at(1)) + "',value='YgA=',valueencoded='2'}]",
- &slist, NS"QList", true, NS"QString");
-}
-
-void tst_Dumpers::dumpQList_Int3()
-{
- QList<Int3> i3list;
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "internal='0',children=[]",
- &i3list, NS"QList", true, "Int3");
- i3list.append(Int3());
- i3list.append(Int3());
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "internal='0',childtype='Int3',children=["
- "{addr='" + str(&i3list.at(0)) + "'},"
- "{addr='" + str(&i3list.at(1)) + "'}]",
- &i3list, NS"QList", true, "Int3");
-}
-
-void tst_Dumpers::dumpQList_QString3()
-{
- QList<QString3> s3list;
- testDumper("value='<0 items>',valueeditable='false',numchild='0',"
- "internal='0',children=[]",
- &s3list, NS"QList", true, "QString3");
- s3list.append(QString3());
- s3list.append(QString3());
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "internal='0',childtype='QString3',children=["
- "{addr='" + str(&s3list.at(0)) + "'},"
- "{addr='" + str(&s3list.at(1)) + "'}]",
- &s3list, NS"QList", true, "QString3");
-}
+public:
+ mutable QByteArray profileExtra;
+ QByteArray includes;
+ QByteArray code;
+ mutable bool forceC;
+ mutable QMap<QByteArray, Check> checks;
+};
-void tst_Dumpers::dumpQLocaleHelper(QLocale &loc)
-{
- QByteArray expected = QByteArray("value='%',type='$T',numchild='8',"
- "children=[{name='country',%},"
- "{name='language',%},"
- "{name='measurementSystem',%},"
- "{name='numberOptions',%},"
- "{name='timeFormat_(short)',%},"
- "{name='timeFormat_(long)',%},"
- "{name='decimalPoint',%},"
- "{name='exponential',%},"
- "{name='percent',%},"
- "{name='zeroDigit',%},"
- "{name='groupSeparator',%},"
- "{name='negativeSign',%}]")
- << valToString(loc.name())
- << createExp(&loc, "QLocale", "country()")
- << createExp(&loc, "QLocale", "language()")
- << createExp(&loc, "QLocale", "measurementSystem()")
- << createExp(&loc, "QLocale", "numberOptions()")
- << generateQStringSpec(loc.timeFormat(QLocale::ShortFormat))
- << generateQStringSpec(loc.timeFormat())
- << generateQCharSpec(loc.decimalPoint())
- << generateQCharSpec(loc.exponential())
- << generateQCharSpec(loc.percent())
- << generateQCharSpec(loc.zeroDigit())
- << generateQCharSpec(loc.groupSeparator())
- << generateQCharSpec(loc.negativeSign());
- testDumper(expected, &loc, NS"QLocale", true);
-}
+Q_DECLARE_METATYPE(Data)
-void tst_Dumpers::dumpQLocale()
+class tst_Dumpers : public QObject
{
- QLocale english(QLocale::English);
- dumpQLocaleHelper(english);
-
- QLocale german(QLocale::German);
- dumpQLocaleHelper(german);
+ Q_OBJECT
- QLocale chinese(QLocale::Chinese);
- dumpQLocaleHelper(chinese);
+public:
+ tst_Dumpers() {}
- QLocale swahili(QLocale::Swahili);
- dumpQLocaleHelper(swahili);
-}
+private slots:
+ void dumper();
+ void dumper_data();
+};
-template <typename K, typename V>
- void tst_Dumpers::dumpQMapHelper(QMap<K, V> &map)
-{
- QByteArray sizeStr(valToString(map.size()));
- size_t nodeSize;
- size_t valOff;
- getMapNodeParams<K, V>(nodeSize, valOff);
- int transKeyOffset = static_cast<int>(2*sizeof(void *)) - static_cast<int>(nodeSize);
- int transValOffset = transKeyOffset + valOff;
- bool simpleKey = isSimpleType<K>();
- bool simpleVal = isSimpleType<V>();
- QByteArray expected = QByteArray("value='<").append(sizeStr).append(" items>',numchild='").
- append(sizeStr).append("',extra='simplekey: ").append(N(simpleKey)).
- append(" isSimpleValue: ").append(N(simpleVal)).
- append(" keyOffset: ").append(N(transKeyOffset)).append(" valueOffset: ").
- append(N(transValOffset)).append(" mapnodesize: ").
- append(N(qulonglong(nodeSize))).append("',children=["); // 64bit Linux hack
- typedef typename QMap<K, V>::iterator mapIter;
- for (mapIter it = map.begin(); it != map.end(); ++it) {
- if (it != map.begin())
- expected.append(",");
- const QByteArray keyString =
- QByteArray(valToString(it.key())).replace("valueencoded","keyencoded");
- expected.append("{key='").append(keyString).append("',value='").
- append(valToString(it.value())).append("',");
- if (simpleKey && simpleVal) {
- expected.append("type='").append(typeToString<V>()).
- append("',addr='").append(ptrToBa(&it.value())).append("'");
- } else {
- QByteArray keyTypeStr = typeToString<K>();
- QByteArray valTypeStr = typeToString<V>();
-#if QT_VERSION >= 0x040500
- QMapNode<K, V> *node = 0;
- size_t backwardOffset = size_t(&node->backward) - valOff;
- char *addr = reinterpret_cast<char *>(&(*it)) + backwardOffset;
- expected.append("addr='").append(ptrToBa(addr)).
- append("',type='" NS "QMapNode<").append(keyTypeStr).append(",").
- append(valTypeStr).append(" >").append("'");
-#else
- expected.append("type='" NS "QMapData::Node<").append(keyTypeStr).
- append(",").append(valTypeStr).append(" >").
- append("',exp='*('" NS "QMapData::Node<").append(keyTypeStr).
- append(",").append(valTypeStr).append(" >").
- append(" >'*)").append(ptrToBa(&(*it))).append("'");
-#endif
+void tst_Dumpers::dumper()
+{
+ QFETCH(Data, data);
+
+ bool ok;
+ QString cmd;
+ QByteArray output;
+ QByteArray error;
+
+ QTemporaryDir buildDir(QLatin1String("qt_tst_dumpers_"));
+ const bool keepTemp = qgetenv("QTC_KEEP_TEMP").toInt();
+ buildDir.setAutoRemove(!keepTemp);
+ //qDebug() << "Temp dir: " << buildDir.path();
+ QVERIFY(!buildDir.path().isEmpty());
+
+ const char *mainFile = data.forceC ? "main.c" : "main.cpp";
+
+ QFile proFile(buildDir.path() + QLatin1String("/doit.pro"));
+ ok = proFile.open(QIODevice::ReadWrite);
+ QVERIFY(ok);
+ proFile.write("SOURCES = ");
+ proFile.write(mainFile);
+ proFile.write("\nTARGET = doit\n");
+ proFile.write("QT -= widgets gui\n");
+ proFile.write(data.profileExtra);
+ proFile.close();
+
+ QFile source(buildDir.path() + QLatin1Char('/') + QLatin1String(mainFile));
+ ok = source.open(QIODevice::ReadWrite);
+ QVERIFY(ok);
+ source.write(
+ "\n\nvoid dummyStatement(void *first,...) { (void) first; }"
+ "\n\n" + data.includes +
+ "\n\nvoid stopper() {}"
+ "\n\nint main(int argc, char *argv[])"
+ "\n{"
+ "\n dummyStatement(&argc, &argv);\n"
+ "\n " + data.code +
+ "\n stopper();"
+ "\n return 0;"
+ "\n}\n");
+ source.close();
+
+ QProcess qmake;
+ qmake.setWorkingDirectory(buildDir.path());
+ cmd = QString::fromLatin1("qmake");
+ //qDebug() << "Starting qmake: " << cmd;
+ qmake.start(cmd);
+ ok = qmake.waitForFinished();
+ QVERIFY(ok);
+ output = qmake.readAllStandardOutput();
+ error = qmake.readAllStandardError();
+ //qDebug() << "stdout: " << output;
+ if (!error.isEmpty()) { qDebug() << error; QVERIFY(false); }
+
+ QProcess make;
+ make.setWorkingDirectory(buildDir.path());
+ cmd = QString::fromLatin1("make");
+ //qDebug() << "Starting make: " << cmd;
+ make.start(cmd);
+ ok = make.waitForFinished();
+ QVERIFY(ok);
+ output = make.readAllStandardOutput();
+ error = make.readAllStandardError();
+ //qDebug() << "stdout: " << output;
+ if (!error.isEmpty()) { qDebug() << error; QVERIFY(false); }
+
+ QByteArray dumperDir = DUMPERDIR;
+
+ QSet<QByteArray> expandedINames;
+ expandedINames.insert("local");
+ foreach (const Check &check, data.checks) {
+ QByteArray parent = check.iname;
+ while (true) {
+ parent = parentIName(parent);
+ if (parent.isEmpty())
+ break;
+ expandedINames.insert("local." + parent);
}
- expected.append("}");
}
- expected.append("]");
- mapIter it = map.begin();
- testDumper(expected, *reinterpret_cast<QMapData **>(&it), NS"QMap",
- true, getMapType<K,V>(), "", 0, 0, nodeSize, valOff);
-}
-
-void tst_Dumpers::dumpQMap()
-{
- qDebug() << "QMap<int, int>";
- // Case 1: Simple type -> simple type.
- QMap<int, int> map1;
-
- // Case 1.1: Empty map.
- dumpQMapHelper(map1);
-
- // Case 1.2: One element.
- map1[2] = 3;
- dumpQMapHelper(map1);
-
- // Case 1.3: Two elements.
- map1[3] = 5;
- dumpQMapHelper(map1);
-
- // Case 2: Simple type -> composite type.
- qDebug() << "QMap<int, QString>";
- QMap<int, QString> map2;
-
- // Case 2.1: Empty Map.
- dumpQMapHelper(map2);
-
- // Case 2.2: One element.
- map2[5] = "String 7";
- dumpQMapHelper(map2);
-
- // Case 2.3: Two elements.
- map2[7] = "String 11";
- dumpQMapHelper(map2);
-
- // Case 3: Composite type -> simple type.
- qDebug() << "QMap<QString, int>";
- QMap<QString, int> map3;
-
- // Case 3.1: Empty map.
- dumpQMapHelper(map3);
- // Case 3.2: One element.
- map3["String 13"] = 11;
- dumpQMapHelper(map3);
-
- // Case 3.3: Two elements.
- map3["String 17"] = 13;
- dumpQMapHelper(map3);
-
- // Case 4: Composite type -> composite type.
- QMap<QString, QString> map4;
-
- // Case 4.1: Empty map.
- dumpQMapHelper(map4);
-
- // Case 4.2: One element.
- map4["String 19"] = "String 23";
- dumpQMapHelper(map4);
-
- // Case 4.3: Two elements.
- map4["String 29"] = "String 31";
- dumpQMapHelper(map4);
-
- // Case 4.4: Different value, same key (multimap functionality).
- map4["String 29"] = "String 37";
- dumpQMapHelper(map4);
-}
-
-template <typename K, typename V>
- void tst_Dumpers::dumpQMapNodeHelper(QMap<K, V> &m)
-{
- typename QMap<K, V>::iterator it = m.begin();
- const K &key = it.key();
- const V &val = it.value();
- //const char * const keyType = typeToString(key);
- QByteArray expected = QByteArray("value='',numchild='2',"
- "children=[{name='key',addr='").append(ptrToBa(&key)).
- append("',type='").append(typeToString<K>()).append("',value='").
- append(valToString(key)).append("'},{name='value',addr='").
- append(ptrToBa(&val)).append("',type='").append(typeToString<V>()).
- append("',value='").append(valToString(val)).
- append("'}]");
- size_t nodeSize;
- size_t valOffset;
- getMapNodeParams<K, V>(nodeSize, valOffset);
- testDumper(expected, *reinterpret_cast<QMapData **>(&it), NS"QMapNode",
- true, getMapType<K,V>(), "", 0, 0, nodeSize, valOffset);
-}
-
-void tst_Dumpers::dumpQMapNode()
-{
- // Case 1: simple type -> simple type.
- QMap<int, int> map;
- map[2] = 3;
- dumpQMapNodeHelper(map);
-
- // Case 2: simple type -> composite type.
- QMap<int, QString> map2;
- map2[3] = "String 5";
- dumpQMapNodeHelper(map2);
-
- // Case 3: composite type -> simple type.
- QMap<QString, int> map3;
- map3["String 7"] = 11;
- dumpQMapNodeHelper(map3);
-
- // Case 4: composite type -> composite type.
- QMap<QString, QString> map4;
- map4["String 13"] = "String 17";
- dumpQMapNodeHelper(map4);
-}
-
-#ifdef USE_PRIVATE
-void tst_Dumpers::dumpQObject()
-{
- QObject parent;
- testDumper("value='',valueencoded='2',type='$T',displayedtype='QObject',"
- "numchild='4'",
- &parent, NS"QObject", false);
- testDumper("value='',valueencoded='2',type='$T',displayedtype='QObject',"
- "numchild='4',children=["
- "{name='properties',addr='$A',type='$TPropertyList',"
- "value='<1 items>',numchild='1'},"
- "{name='signals',addr='$A',type='$TSignalList',"
- "value='<2 items>',numchild='2'},"
- "{name='slots',addr='$A',type='$TSlotList',"
- "value='<2 items>',numchild='2'},"
- "{name='parent',value='0x0',type='$T *',numchild='0'},"
- "{name='className',value='QObject',type='',numchild='0'}]",
- &parent, NS"QObject", true);
-
-#if 0
- testDumper("numchild='2',value='<2 items>',type='QObjectSlotList',"
- "children=[{name='2',value='deleteLater()',"
- "numchild='0',addr='$A',type='QObjectSlot'},"
- "{name='3',value='_q_reregisterTimers(void*)',"
- "numchild='0',addr='$A',type='QObjectSlot'}]",
- &parent, NS"QObjectSlotList", true);
-#endif
-
- parent.setObjectName("A Parent");
- testDumper("value='QQAgAFAAYQByAGUAbgB0AA==',valueencoded='2',type='$T',"
- "displayedtype='QObject',numchild='4'",
- &parent, NS"QObject", false);
- QObject child(&parent);
- testDumper("value='',valueencoded='2',type='$T',"
- "displayedtype='QObject',numchild='4'",
- &child, NS"QObject", false);
- child.setObjectName("A Child");
- QByteArray ba ="value='QQAgAEMAaABpAGwAZAA=',valueencoded='2',type='$T',"
- "displayedtype='QObject',numchild='4',children=["
- "{name='properties',addr='$A',type='$TPropertyList',"
- "value='<1 items>',numchild='1'},"
- "{name='signals',addr='$A',type='$TSignalList',"
- "value='<2 items>',numchild='2'},"
- "{name='slots',addr='$A',type='$TSlotList',"
- "value='<2 items>',numchild='2'},"
- "{name='parent',addr='" + str(&parent) + "',"
- "value='QQAgAFAAYQByAGUAbgB0AA==',valueencoded='2',type='$T',"
- "displayedtype='QObject',numchild='1'},"
- "{name='className',value='QObject',type='',numchild='0'}]";
- testDumper(ba, &child, NS"QObject", true);
- connect(&child, SIGNAL(destroyed()), qApp, SLOT(quit()));
- testDumper(ba, &child, NS"QObject", true);
- disconnect(&child, SIGNAL(destroyed()), qApp, SLOT(quit()));
- testDumper(ba, &child, NS"QObject", true);
- child.setObjectName("A renamed Child");
- testDumper("value='QQAgAHIAZQBuAGEAbQBlAGQAIABDAGgAaQBsAGQA',valueencoded='2',"
- "type='$T',displayedtype='QObject',numchild='4'",
- &child, NS"QObject", false);
-}
-
-void tst_Dumpers::dumpQObjectChildListHelper(QObject &o)
-{
- const QObjectList children = o.children();
- const int size = children.size();
- const QString sizeStr = N(size);
- QByteArray expected = QByteArray("numchild='").append(sizeStr).append("',value='<").
- append(sizeStr).append(" items>',type='" NS "QObjectChildList',children=[");
- for (int i = 0; i < size; ++i) {
- const QObject *child = children.at(i);
- expected.append("{addr='").append(ptrToBa(child)).append("',value='").
- append(utfToBase64(child->objectName())).
- append("',valueencoded='2',type='" NS "QObject',displayedtype='").
- append(child->metaObject()->className()).append("',numchild='1'}");
- if (i < size - 1)
- expected.append(",");
+ QByteArray expanded;
+ foreach (const QByteArray &iname, expandedINames) {
+ if (!expanded.isEmpty())
+ expanded.append(',');
+ expanded += iname;
}
- expected.append("]");
- testDumper(expected, &o, NS"QObjectChildList", true);
-}
-
-void tst_Dumpers::dumpQObjectChildList()
-{
- // Case 1: Object with no children.
- QObject o;
- dumpQObjectChildListHelper(o);
-
- // Case 2: Object with one child.
- QObject o2(&o);
- dumpQObjectChildListHelper(o);
- // Case 3: Object with two children.
- QObject o3(&o);
- dumpQObjectChildListHelper(o);
-}
-
-void tst_Dumpers::dumpQObjectMethodList()
-{
- QStringListModel m;
- testDumper("addr='<synthetic>',type='$T',numchild='24',"
- "childtype='" NS "QMetaMethod::Method',childnumchild='0',children=["
- "{name='0 0 destroyed(QObject*)',value='<Signal> (1)'},"
- "{name='1 1 destroyed()',value='<Signal> (1)'},"
- "{name='2 2 deleteLater()',value='<Slot> (2)'},"
- "{name='3 3 _q_reregisterTimers(void*)',value='<Slot> (2)'},"
- "{name='4 4 dataChanged(QModelIndex,QModelIndex)',value='<Signal> (1)'},"
- "{name='5 5 headerDataChanged(Qt::Orientation,int,int)',value='<Signal> (1)'},"
- "{name='6 6 layoutChanged()',value='<Signal> (1)'},"
- "{name='7 7 layoutAboutToBeChanged()',value='<Signal> (1)'},"
- "{name='8 8 rowsAboutToBeInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='9 9 rowsInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='10 10 rowsAboutToBeRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='11 11 rowsRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='12 12 columnsAboutToBeInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='13 13 columnsInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='14 14 columnsAboutToBeRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='15 15 columnsRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
- "{name='16 16 modelAboutToBeReset()',value='<Signal> (1)'},"
- "{name='17 17 modelReset()',value='<Signal> (1)'},"
- "{name='18 18 rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
- "{name='19 19 rowsMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
- "{name='20 20 columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
- "{name='21 21 columnsMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
- "{name='22 22 submit()',value='<Slot> (2)'},"
- "{name='23 23 revert()',value='<Slot> (2)'}]",
- &m, NS"QObjectMethodList", true);
-}
-
-void tst_Dumpers::dumpQObjectPropertyList()
-{
- // Case 1: Model without a parent.
- QStringListModel m(QStringList() << "Test1" << "Test2");
- testDumper("addr='<synthetic>',type='$T',numchild='1',value='<1 items>',"
- "children=[{name='objectName',type='QString',value='',"
- "valueencoded='2',numchild='0'}]",
- &m, NS"QObjectPropertyList", true);
-
- // Case 2: Model with a parent.
- QStringListModel m2(&m);
- testDumper("addr='<synthetic>',type='$T',numchild='1',value='<1 items>',"
- "children=[{name='objectName',type='QString',value='',"
- "valueencoded='2',numchild='0'}]",
- &m2, NS"QObjectPropertyList", true);
-}
-
-static const char *connectionType(uint type)
-{
- Qt::ConnectionType connType = static_cast<Qt::ConnectionType>(type);
- const char *output = "unknown";
- switch (connType) {
- case Qt::AutoConnection: output = "auto"; break;
- case Qt::DirectConnection: output = "direct"; break;
- case Qt::QueuedConnection: output = "queued"; break;
- case Qt::BlockingQueuedConnection: output = "blockingqueued"; break;
- case 3: output = "autocompat"; break;
-#if QT_VERSION >= 0x040600
- case Qt::UniqueConnection: break; // Can't happen.
-#endif
- default:
- qWarning() << "Unknown connection type: " << type;
- break;
- };
- return output;
-};
-
-class Cheater : public QObject
-{
-public:
- static const QObjectPrivate *getPrivate(const QObject &o)
- {
- const Cheater &cheater = static_cast<const Cheater&>(o);
-#if QT_VERSION >= 0x040600
- return dynamic_cast<const QObjectPrivate *>(cheater.d_ptr.data());
-#else
- return dynamic_cast<const QObjectPrivate *>(cheater.d_ptr);
-#endif
+ QByteArray nograb = "-nograb";
+
+ QByteArray cmds =
+ "set confirm off\n"
+ "file doit\n"
+ "break stopper\n"
+ "set auto-load python-scripts off\n"
+ "python execfile('" + dumperDir + "/bridge.py')\n"
+ "python execfile('" + dumperDir + "/dumper.py')\n"
+ "python execfile('" + dumperDir + "/qttypes.py')\n"
+ "bbsetup\n"
+ "run " + nograb + "\n"
+ "up\n"
+ "python print('@%sS@%s@' % ('N', qtNamespace()))\n"
+ "bb options:fancy,autoderef,dyntype vars: expanded:" + expanded + " typeformats:\n"
+ "quit\n";
+
+ if (keepTemp) {
+ QFile logger(buildDir.path() + QLatin1String("/input.txt"));
+ ok = logger.open(QIODevice::ReadWrite);
+ logger.write(cmds);
}
-};
-
-typedef QVector<QObjectPrivate::ConnectionList> ConnLists;
-void tst_Dumpers::dumpQObjectSignalHelper(QObject &o, int sigNum)
-{
- //qDebug() << o.objectName() << sigNum;
- QByteArray expected("addr='<synthetic>',numchild='1',type='" NS "QObjectSignal'");
-#if QT_VERSION >= 0x040400 && QT_VERSION <= 0x040700
- expected.append(",children=[");
- const QObjectPrivate *p = Cheater::getPrivate(o);
- Q_ASSERT(p != 0);
- const ConnLists *connLists = reinterpret_cast<const ConnLists *>(p->connectionLists);
- QObjectPrivate::ConnectionList connList =
- connLists != 0 && connLists->size() > sigNum ?
- connLists->at(sigNum) : QObjectPrivate::ConnectionList();
- int i = 0;
- // FIXME: 4.6 only
- for (QObjectPrivate::Connection *conn = connList.first; conn != 0;
- ++i, conn = conn->nextConnectionList) {
- const QString iStr = N(i);
- expected.append("{name='").append(iStr).append(" receiver',");
- if (conn->receiver == &o)
- expected.append("value='<this>',type='").
- append(o.metaObject()->className()).
- append("',numchild='0',addr='").append(ptrToBa(&o)).append("'");
- else if (conn->receiver == 0)
- expected.append("value='0x0',type='" NS "QObject *',numchild='0'");
- else
- expected.append("addr='").append(ptrToBa(conn->receiver)).append("',value='").
- append(utfToBase64(conn->receiver->objectName())).append("',valueencoded='2',").
- append("type='" NS "QObject',displayedtype='").
- append(conn->receiver->metaObject()->className()).append("',numchild='1'");
- expected.append("},{name='").append(iStr).append(" slot',type='',value='");
- if (conn->receiver != 0)
- expected.append(conn->receiver->metaObject()->method(conn->method).signature());
- else
- expected.append("<invalid receiver>");
- expected.append("',numchild='0'},{name='").append(iStr).append(" type',type='',value='<").
- append(connectionType(conn->connectionType)).append(" connection>',").
- append("numchild='0'}");
- if (conn != connList.last)
- expected.append(",");
+ QProcess debugger;
+ debugger.setWorkingDirectory(buildDir.path());
+ //qDebug() << "Starting debugger ";
+ debugger.start(QLatin1String("gdb -i mi -quiet -nx"));
+ ok = debugger.waitForStarted();
+ debugger.write(cmds);
+ ok = debugger.waitForFinished();
+ QVERIFY(ok);
+ output = debugger.readAllStandardOutput();
+ //qDebug() << "stdout: " << output;
+ error = debugger.readAllStandardError();
+ if (!error.isEmpty()) { qDebug() << error; }
+
+ if (keepTemp) {
+ QFile logger(buildDir.path() + QLatin1String("/output.txt"));
+ ok = logger.open(QIODevice::ReadWrite);
+ logger.write("=== STDOUT ===\n");
+ logger.write(output);
+ logger.write("\n=== STDERR ===\n");
+ logger.write(error);
}
- expected.append("],numchild='").append(N(i)).append("'");
-#endif
- testDumper(expected, &o, NS"QObjectSignal", true, "", "", sigNum);
-}
-
-void tst_Dumpers::dumpQObjectSignal()
-{
- // Case 1: Simple QObject.
- QObject o;
- o.setObjectName("Test");
- testDumper("addr='<synthetic>',numchild='1',type='" NS "QObjectSignal',"
- "children=[],numchild='0'",
- &o, NS"QObjectSignal", true, "", "", 0);
-
- // Case 2: QAbstractItemModel with no connections.
- QStringListModel m(QStringList() << "Test1" << "Test2");
- for (int signalIndex = 0; signalIndex < 17; ++signalIndex)
- dumpQObjectSignalHelper(m, signalIndex);
-
- // Case 3: QAbstractItemModel with connections to itself and to another
- // object, using different connection types.
- qRegisterMetaType<QModelIndex>("QModelIndex");
- connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- &o, SLOT(deleteLater()), Qt::DirectConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(revert()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::BlockingQueuedConnection);
- connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- &m, SLOT(deleteLater()), Qt::AutoConnection);
-#if QT_VERSION >= 0x040600
- connect(&m, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- &m, SLOT(revert()), Qt::UniqueConnection);
-#endif
- for (int signalIndex = 0; signalIndex < 17; ++signalIndex)
- dumpQObjectSignalHelper(m, signalIndex);
-}
-void tst_Dumpers::dumpQObjectSignalList()
-{
- // Case 1: Simple QObject.
- QObject o;
- o.setObjectName("Test");
-
- testDumper("type='" NS "QObjectSignalList',value='<2 items>',"
- "addr='$A',numchild='2',children=["
- "{name='0',value='destroyed(QObject*)',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'},"
- "{name='1',value='destroyed()',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'}]",
- &o, NS"QObjectSignalList", true);
-
- // Case 2: QAbstractItemModel with no connections.
- QStringListModel m(QStringList() << "Test1" << "Test2");
- QByteArray expected = "type='" NS "QObjectSignalList',value='<20 items>',"
- "addr='$A',numchild='20',children=["
- "{name='0',value='destroyed(QObject*)',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'},"
- "{name='1',value='destroyed()',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'},"
- "{name='4',value='dataChanged(QModelIndex,QModelIndex)',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'},"
- "{name='5',value='headerDataChanged(Qt::Orientation,int,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='6',value='layoutChanged()',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'},"
- "{name='7',value='layoutAboutToBeChanged()',numchild='0',"
- "addr='$A',type='" NS "QObjectSignal'},"
- "{name='8',value='rowsAboutToBeInserted(QModelIndex,int,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='9',value='rowsInserted(QModelIndex,int,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='10',value='rowsAboutToBeRemoved(QModelIndex,int,int)',"
- "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
- "{name='11',value='rowsRemoved(QModelIndex,int,int)',"
- "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
- "{name='12',value='columnsAboutToBeInserted(QModelIndex,int,int)',"
- "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
- "{name='13',value='columnsInserted(QModelIndex,int,int)',"
- "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
- "{name='14',value='columnsAboutToBeRemoved(QModelIndex,int,int)',"
- "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
- "{name='15',value='columnsRemoved(QModelIndex,int,int)',"
- "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
- "{name='16',value='modelAboutToBeReset()',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='17',value='modelReset()',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='18',value='rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='19',value='rowsMoved(QModelIndex,int,int,QModelIndex,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='20',value='columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
- "{name='21',value='columnsMoved(QModelIndex,int,int,QModelIndex,int)',"
- "numchild='0',addr='$A',type='" NS "QObjectSignal'}]";
-
-
- testDumper(expected << "0" << "0" << "0" << "0" << "0" << "0",
- &m, NS"QObjectSignalList", true);
-
-
- // Case 3: QAbstractItemModel with connections to itself and to another
- // object, using different connection types.
- qRegisterMetaType<QModelIndex>("QModelIndex");
- connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- &o, SLOT(deleteLater()), Qt::DirectConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(revert()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::BlockingQueuedConnection);
- connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- &m, SLOT(deleteLater()), Qt::AutoConnection);
-
- testDumper(expected << "1" << "1" << "2" << "1" << "0" << "0",
- &m, NS"QObjectSignalList", true);
-}
-
-QByteArray slotIndexList(const QObject *ob)
-{
- QByteArray slotIndices;
- const QMetaObject *mo = ob->metaObject();
- for (int i = 0; i < mo->methodCount(); ++i) {
- const QMetaMethod &mm = mo->method(i);
- if (mm.methodType() == QMetaMethod::Slot) {
- int slotIndex = mo->indexOfSlot(mm.signature());
- Q_ASSERT(slotIndex != -1);
- slotIndices.append(N(slotIndex));
- slotIndices.append(',');
- }
+ int pos1 = output.indexOf("data=");
+ QVERIFY(pos1 != -1);
+ int pos2 = output.indexOf(",typeinfo", pos1);
+ QVERIFY(pos2 != -1);
+ QByteArray contents = output.mid(pos1, pos2 - pos1);
+ contents.replace("\\\"", "\"");
+
+ int pos3 = output.indexOf("@NS@");
+ QVERIFY(pos3 != -1);
+ pos3 += sizeof("@NS@") - 1;
+ int pos4 = output.indexOf("@", pos3);
+ QVERIFY(pos4 != -1);
+ QByteArray nameSpace = output.mid(pos3, pos4 - pos3);
+ //qDebug() << "FOUND NS: " << nameSpace;
+ if (nameSpace == "::")
+ nameSpace.clear();
+
+ GdbMi actual;
+ actual.fromString(contents);
+ ok = false;
+ WatchData local;
+ local.iname = "local";
+
+ QList<WatchData> list;
+ foreach (const GdbMi &child, actual.children()) {
+ WatchData dummy;
+ dummy.iname = child.findChild("iname").data();
+ dummy.name = QLatin1String(child.findChild("name").data());
+ parseWatchData(expandedINames, dummy, child, &list);
}
- slotIndices.chop(1);
- return slotIndices;
-}
-void tst_Dumpers::dumpQObjectSlot()
-{
- // Case 1: Simple QObject.
- QObject o;
- o.setObjectName("Test");
-
- QByteArray slotIndices = slotIndexList(&o);
- QCOMPARE(slotIndices, QByteArray("2,3"));
- QCOMPARE(o.metaObject()->indexOfSlot("deleteLater()"), 2);
-
- QByteArray expected = QByteArray("addr='$A',numchild='1',type='$T',"
- //"children=[{name='1 sender'}],numchild='1'");
- "children=[],numchild='0'");
- qDebug() << "FIXME!";
- testDumper(expected, &o, NS"QObjectSlot", true, "", "", 2);
-
-
- // Case 2: QAbstractItemModel with no connections.
- QStringListModel m(QStringList() << "Test1" << "Test2");
- slotIndices = slotIndexList(&o);
-
- QCOMPARE(slotIndices, QByteArray("2,3"));
- QCOMPARE(o.metaObject()->indexOfSlot("deleteLater()"), 2);
-
- expected = QByteArray("addr='$A',numchild='1',type='$T',"
- //"children=[{name='1 sender'}],numchild='1'");
- "children=[],numchild='0'");
- qDebug() << "FIXME!";
- testDumper(expected, &o, NS"QObjectSlot", true, "", "", 2);
-
-
- // Case 3: QAbstractItemModel with connections to itself and to another
- // o, using different connection types.
- qRegisterMetaType<QModelIndex>("QModelIndex");
- connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- &o, SLOT(deleteLater()), Qt::DirectConnection);
- connect(&o, SIGNAL(destroyed(QObject*)),
- &m, SLOT(revert()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::BlockingQueuedConnection);
- connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- &m, SLOT(deleteLater()), Qt::AutoConnection);
-#if QT_VERSION >= 0x040600
- connect(&m, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
- &m, SLOT(revert()), Qt::UniqueConnection);
-#endif
- expected = QByteArray("addr='$A',numchild='1',type='$T',"
- //"children=[{name='1 sender'}],numchild='1'");
- "children=[],numchild='0'");
- qDebug() << "FIXME!";
- testDumper(expected, &o, NS"QObjectSlot", true, "", "", 2);
-
-}
-
-void tst_Dumpers::dumpQObjectSlotList()
-{
- // Case 1: Simple QObject.
- QObject o;
- o.setObjectName("Test");
- testDumper("numchild='2',value='<2 items>',type='$T',"
- "children=[{name='2',value='deleteLater()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='3',value='_q_reregisterTimers(void*)',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'}]",
- &o, NS"QObjectSlotList", true);
-
- // Case 2: QAbstractItemModel with no connections.
- QStringListModel m(QStringList() << "Test1" << "Test2");
- testDumper("numchild='4',value='<4 items>',type='$T',"
- "children=[{name='2',value='deleteLater()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='3',value='_q_reregisterTimers(void*)',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='22',value='submit()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='23',value='revert()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'}]",
- &m, NS"QObjectSlotList", true);
-
- // Case 3: QAbstractItemModel with connections to itself and to another
- // object, using different connection types.
- qRegisterMetaType<QModelIndex>("QModelIndex");
- connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
- &o, SLOT(deleteLater()), Qt::DirectConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(revert()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::QueuedConnection);
- connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
- &m, SLOT(submit()), Qt::BlockingQueuedConnection);
- connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
- &m, SLOT(deleteLater()), Qt::AutoConnection);
- connect(&o, SIGNAL(destroyed(QObject*)), &m, SLOT(submit()));
- testDumper("numchild='4',value='<4 items>',type='$T',"
- "children=[{name='2',value='deleteLater()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='3',value='_q_reregisterTimers(void*)',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='22',value='submit()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'},"
- "{name='23',value='revert()',numchild='0',"
- "addr='$A',type='" NS "QObjectSlot'}]",
- &m, NS"QObjectSlotList", true);
-}
-#endif
-
-void tst_Dumpers::dumpQPixmap()
-{
- // Case 1: Null Pixmap.
- QPixmap p;
-
- testDumper("value='(0x0)',type='$T',numchild='0'",
- &p, NS"QPixmap", true);
-
-
- // Case 2: Uninitialized non-null pixmap.
- p = QPixmap(20, 100);
- testDumper("value='(20x100)',type='$T',numchild='0'",
- &p, NS"QPixmap", true);
-
-
- // Case 3: Initialized non-null pixmap.
- const char * const pixmap[] = {
- "2 24 3 1", " c None", ". c #DBD3CB", "+ c #FCFBFA",
- " ", " ", " ", ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+",
- ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+", " ", " ", " "
- };
- p = QPixmap(pixmap);
- testDumper("value='(2x24)',type='$T',numchild='0'",
- &p, NS"QPixmap", true);
-}
-
-#if QT_VERSION >= 0x040500
-template<typename T>
-void tst_Dumpers::dumpQSharedPointerHelper(QSharedPointer<T> &ptr)
-{
- struct Cheater : public QSharedPointer<T>
- {
- static const typename QSharedPointer<T>::Data *getData(const QSharedPointer<T> &p)
- {
- return static_cast<const Cheater &>(p).d;
+ foreach (const WatchData &item, list) {
+ if (data.checks.contains(item.iname)) {
+ Check check = data.checks.take(item.iname);
+ if (item.name.toLatin1() != check.expectedName) {
+ qDebug() << "INAME : " << item.iname;
+ qDebug() << "NAME ACTUAL : " << item.name;
+ qDebug() << "NAME EXPECTED: " << check.expectedName;
+ qDebug() << "CONTENTS : " << contents;
+ QVERIFY(false);
+ }
+ if (!check.expectedValue.matches(item.value)) {
+ qDebug() << "INAME : " << item.iname;
+ qDebug() << "VALUE ACTUAL : " << item.value << item.value.toLatin1().toHex();
+ qDebug() << "VALUE EXPECTED: " << check.expectedValue.value << check.expectedValue.value.toHex();
+ qDebug() << "CONTENTS : " << contents;
+ QVERIFY(false);
+ }
+ if (!check.expectedType.matches(item.type, nameSpace)) {
+ qDebug() << "INAME : " << item.iname;
+ qDebug() << "TYPE ACTUAL : " << item.type;
+ qDebug() << "TYPE EXPECTED: " << check.expectedType.type;
+ qDebug() << "CONTENTS : " << contents;
+ QVERIFY(false);
+ }
}
- };
-
- QByteArray expected("value='");
- QString val1 = ptr.isNull() ? "<null>" : valToString(*ptr.data());
- QString val2 = isSimpleType<T>() ? val1 : "";
-/*
- const int *weakAddr;
- const int *strongAddr;
- int weakValue;
- int strongValue;
- if (!ptr.isNull()) {
- weakAddr = reinterpret_cast<const int *>(&Cheater::getData(ptr)->weakref);
- strongAddr = reinterpret_cast<const int *>(&Cheater::getData(ptr)->strongref);
- weakValue = *weakAddr;
- strongValue = *strongAddr;
- } else {
- weakAddr = strongAddr = 0;
- weakValue = strongValue = 0;
}
- expected.append(val2).append("',valueeditable='false',numchild='1',children=[").
- append("{name='data',addr='").append(ptrToBa(ptr.data())).
- append("',type='").append(typeToString<T>()).append("',value='").append(val1).
- append("'},{name='weakref',value='").append(N(weakValue)).
- append("',type='int',addr='").append(ptrToBa(weakAddr)).append("',numchild='0'},").
- append("{name='strongref',value='").append(N(strongValue)).
- append("',type='int',addr='").append(ptrToBa(strongAddr)).append("',numchild='0'}]");
- testDumper(expected, &ptr, NS"QSharedPointer", true, typeToString<T>());
-*/
-}
-#endif
-
-void tst_Dumpers::dumpQSharedPointer()
-{
-#if QT_VERSION >= 0x040500
- // Case 1: Simple type.
- // Case 1.1: Null pointer.
- QSharedPointer<int> simplePtr;
- dumpQSharedPointerHelper(simplePtr);
-
- // Case 1.2: Non-null pointer,
- QSharedPointer<int> simplePtr2(new int(99));
- dumpQSharedPointerHelper(simplePtr2);
-
- // Case 1.3: Shared pointer.
- QSharedPointer<int> simplePtr3 = simplePtr2;
- dumpQSharedPointerHelper(simplePtr2);
-
- // Case 1.4: Weak pointer.
- QWeakPointer<int> simplePtr4(simplePtr2);
- dumpQSharedPointerHelper(simplePtr2);
-
- // Case 2: Composite type.
- // Case 1.1: Null pointer.
- QSharedPointer<QString> compositePtr;
- // TODO: This case is not handled in dumper.cpp (segfault!)
- //dumpQSharedPointerHelper(compoistePtr);
-
- // Case 1.2: Non-null pointer,
- QSharedPointer<QString> compositePtr2(new QString("Test"));
- dumpQSharedPointerHelper(compositePtr2);
-
- // Case 1.3: Shared pointer.
- QSharedPointer<QString> compositePtr3 = compositePtr2;
- dumpQSharedPointerHelper(compositePtr2);
-
- // Case 1.4: Weak pointer.
- QWeakPointer<QString> compositePtr4(compositePtr2);
- dumpQSharedPointerHelper(compositePtr2);
-#endif
-}
-
-void tst_Dumpers::dumpQString()
-{
- QString s;
- testDumper("value='IiIgKG51bGwp',valueencoded='5',type='$T',numchild='0'",
- &s, NS"QString", false);
- s = "abc";
- testDumper("value='YQBiAGMA',valueencoded='2',type='$T',numchild='0'",
- &s, NS"QString", false);
-}
-
-void tst_Dumpers::dumpQVariant_invalid()
-{
- QVariant v;
- testDumper("value='(invalid)',type='$T',numchild='0'",
- &v, NS"QVariant", false);
-}
-
-void tst_Dumpers::dumpQVariant_QString()
-{
- QVariant v = "abc";
- testDumper("value='KFFTdHJpbmcpICJhYmMi',valueencoded='5',type='$T',"
- "numchild='0'",
- &v, NS"QVariant", true);
-/*
- FIXME: the QString version should have a child:
- testDumper("value='KFFTdHJpbmcpICJhYmMi',valueencoded='5',type='$T',"
- "numchild='1',children=[{name='value',value='IgBhAGIAYwAiAA==',"
- "valueencoded='4',type='QString',numchild='0'}]",
- &v, NS"QVariant", true);
-*/
-}
-
-void tst_Dumpers::dumpQVariant_QStringList()
-{
- QVariant v = QStringList() << "Hi";
- testDumper("value='(QStringList) ',type='$T',numchild='1',"
- "children=[{name='value',exp='(*('" NS "QStringList'*)%)',"
- "type='QStringList',numchild='1'}]"
- << QByteArray::number(quintptr(&v)),
- &v, NS"QVariant", true);
-}
-
-#ifndef Q_CC_MSVC
-
-void tst_Dumpers::dumpStdVector()
-{
- std::vector<std::list<int> *> vector;
- QByteArray inner = "std::list<int> *";
- QByteArray innerp = "std::list<int>";
- testDumper("value='<0 items>',valueeditable='false',numchild='0'",
- &vector, "std::vector", false, inner, "", sizeof(std::list<int> *));
- std::list<int> list;
- vector.push_back(new std::list<int>(list));
- testDumper("value='<1 items>',valueeditable='false',numchild='1',"
- "childtype='" + inner + "',childnumchild='1',"
- "children=[{addr='" + str(deref(&vector[0])) + "',type='" + innerp + "'}]",
- &vector, "std::vector", true, inner, "", sizeof(std::list<int> *));
- vector.push_back(0);
- list.push_back(45);
- testDumper("value='<2 items>',valueeditable='false',numchild='2',"
- "childtype='" + inner + "',childnumchild='1',"
- "children=[{addr='" + str(deref(&vector[0])) + "',type='" + innerp + "'},"
- "{addr='" + str(&vector[1]) + "',"
- "type='" + innerp + "',value='<null>',numchild='0'}]",
- &vector, "std::vector", true, inner, "", sizeof(std::list<int> *));
- vector.push_back(new std::list<int>(list));
- vector.push_back(0);
-}
-#endif // !Q_CC_MSVC
-
-void tst_Dumpers::dumpQTextCodecHelper(QTextCodec *codec)
-{
- const QByteArray name = codec->name().toBase64();
- QByteArray expected = QByteArray("value='%',valueencoded='1',type='$T',"
- "numchild='2',children=[{name='name',value='%',type='" NS "QByteArray',"
- "numchild='0',valueencoded='1'},{name='mibEnum',%}]")
- << name << name << generateIntSpec(codec->mibEnum());
- testDumper(expected, codec, NS"QTextCodec", true);
-}
-
-void tst_Dumpers::dumpQTextCodec()
-{
- const QList<QByteArray> &codecNames = QTextCodec::availableCodecs();
- foreach (const QByteArray &codecName, codecNames)
- dumpQTextCodecHelper(QTextCodec::codecForName(codecName));
-}
-
-#if QT_VERSION >= 0x040500
-template <typename T1, typename T2>
- size_t offsetOf(const T1 *klass, const T2 *member)
-{
- return static_cast<size_t>(reinterpret_cast<const char *>(member) -
- reinterpret_cast<const char *>(klass));
+ if (!data.checks.isEmpty()) {
+ qDebug() << "SOME TESTS NOT EXECUTED: ";
+ foreach (const Check &check, data.checks)
+ qDebug() << " TEST NOT FOUND FOR INAME: " << check.iname;
+ qDebug() << "CONTENTS : " << contents;
+ qDebug() << "EXPANDED : " << expanded;
+ QVERIFY(false);
+ }
}
-template <typename T>
-void tst_Dumpers::dumpQWeakPointerHelper(QWeakPointer<T> &ptr)
-{
- typedef QtSharedPointer::ExternalRefCountData Data;
- const size_t dataOffset = 0;
- const Data *d = *reinterpret_cast<const Data **>(
- reinterpret_cast<const char **>(&ptr) + dataOffset);
- const int *weakRefPtr = reinterpret_cast<const int *>(&d->weakref);
- const int *strongRefPtr = reinterpret_cast<const int *>(&d->strongref);
- T *data = ptr.toStrongRef().data();
- const QString dataStr = valToString(*data);
- QByteArray expected("value='");
- if (isSimpleType<T>())
- expected.append(dataStr);
- expected.append("',valueeditable='false',numchild='1',children=[{name='data',addr='").
- append(ptrToBa(data)).append("',type='").append(typeToString<T>()).
- append("',value='").append(dataStr).append("'},{name='weakref',value='").
- append(valToString(*weakRefPtr)).append("',type='int',addr='").
- append(ptrToBa(weakRefPtr)).append("',numchild='0'},{name='strongref',value='").
- append(valToString(*strongRefPtr)).append("',type='int',addr='").
- append(ptrToBa(strongRefPtr)).append("',numchild='0'}]");
- testDumper(expected, &ptr, NS"QWeakPointer", true, typeToString<T>());
-}
+void tst_Dumpers::dumper_data()
+{
+ QTest::addColumn<Data>("data");
+
+ QByteArray fooData =
+ "#include <QHash>\n"
+ "#include <QMap>\n"
+ "#include <QObject>\n"
+ "#include <QString>\n"
+ "class Foo\n"
+ "{\n"
+ "public:\n"
+ " Foo(int i = 0)\n"
+ " : a(i), b(2)\n"
+ " {}\n"
+ " virtual ~Foo()\n"
+ " {\n"
+ " a = 5;\n"
+ " }\n"
+ " void doit()\n"
+ " {\n"
+ " static QObject ob;\n"
+ " m[\"1\"] = \"2\";\n"
+ " h[&ob] = m.begin();\n"
+ " --b;\n"
+ " }\n"
+ "public:\n"
+ " int a, b;\n"
+ " char x[6];\n"
+ "private:\n"
+ " typedef QMap<QString, QString> Map;\n"
+ " Map m;\n"
+ " QHash<QObject *, Map::iterator> h;\n"
+ "};\n";
+
+ QByteArray nsData =
+ "namespace nsA {\n"
+ "namespace nsB {\n"
+ " struct SomeType\n"
+ " {\n"
+ " SomeType(int a) : a(a) {}\n"
+ " int a;\n"
+ " };\n"
+ " } // namespace nsB\n"
+ " } // namespace nsA\n";
+
+ QTest::newRow("AnonymousStruct")
+ << Data("union {\n"
+ " struct { int i; int b; };\n"
+ " struct { float f; };\n"
+ " double d;\n"
+ " } a = { { 42, 43 } };\n (void)a;")
+ % CheckType("a", "a", "union {...}")
+ % Check("a.b", "43", "int")
+ % Check("a.d", "9.1245819032257467e-313", "double")
+ % Check("a.f", "5.88545355e-44", "float")
+ % Check("a.i", "42", "int");
+
+ QTest::newRow("QByteArray0")
+ << Data("#include <QByteArray>\n",
+ "QByteArray ba;")
+ % Check("ba", "ba", "\"\"", "@QByteArray");
+
+ QTest::newRow("QByteArray1")
+ << Data("#include <QByteArray>\n",
+ "QByteArray ba = \"Hello\\\"World\";\n"
+ "ba += char(0);\n"
+ "ba += 1;\n"
+ "ba += 2;\n")
+ % Check("ba", "\"Hello\"World\"", "@QByteArray")
+ % Check("ba.0", "[0]", "72", "char")
+ % Check("ba.11", "[11]", "0", "char")
+ % Check("ba.12", "[12]", "1", "char")
+ % Check("ba.13", "[13]", "2", "char");
+
+ QTest::newRow("QByteArray2")
+ << Data("#include <QByteArray>\n"
+ "#include <QString>\n"
+ "#include <string>\n",
+ "QByteArray ba;\n"
+ "for (int i = 256; --i >= 0; )\n"
+ " ba.append(char(i));\n"
+ "QString s(10000, 'x');\n"
+ "std::string ss(10000, 'c');\n"
+ "dummyStatement(&ba, &s, &ss);\n")
+ % CheckType("ba", "@QByteArray")
+ % Check("s", '"' + QByteArray(10000, 'x') + '"', "@QString")
+ % Check("ss", '"' + QByteArray(10000, 'c') + '"', "std::string");
+
+ QTest::newRow("QByteArray3")
+ << Data("#include <QByteArray>\n",
+ "const char *str1 = \"\356\";\n"
+ "const char *str2 = \"\xee\";\n"
+ "const char *str3 = \"\\ee\";\n"
+ "QByteArray buf1(str1);\n"
+ "QByteArray buf2(str2);\n"
+ "QByteArray buf3(str3);\n"
+ "dummyStatement(&buf1, &buf2, &buf3);\n")
+ % Check("buf1", "\"î\"", "@QByteArray")
+ % Check("buf2", "\"î\"", "@QByteArray")
+ % Check("buf3", "\"\ee\"", "@QByteArray")
+ % CheckType("str1", "char *");
+
+ QTest::newRow("QByteArray4")
+ << Data("#include <QByteArray>\n",
+ "char data[] = { 'H', 'e', 'l', 'l', 'o' };\n"
+ "QByteArray ba1 = QByteArray::fromRawData(data, 4);\n"
+ "QByteArray ba2 = QByteArray::fromRawData(data + 1, 4);\n")
+ % Check("ba1", "\"Hell\"", "@QByteArray")
+ % Check("ba2", "\"ello\"", "@QByteArray");
+
+ QTest::newRow("QDate0")
+ << Data("#include <QDate>\n",
+ "QDate date;\n"
+ "dummyStatement(&date);\n")
+ % CheckType("date", "@QDate")
+ % Check("date.(ISO)", "", "@QString")
+ % Check("date.(Locale)", "", "@QString")
+ % Check("date.(SystemLocale)", "", "@QString")
+ % Check("date.toString", "", "@QString");
+
+ QTest::newRow("QDate1")
+ << Data("#include <QDate>\n",
+ "QDate date;\n"
+ "date.setDate(1980, 1, 1);\n"
+ "dummyStatement(&date);\n")
+ % CheckType("date", "@QDate")
+ % Check("date.(ISO)", "\"1980-01-01\"", "@QString")
+ % CheckType("date.(Locale)", "@QString")
+ % CheckType("date.(SystemLocale)", "@QString")
+ % Check("date.toString", "\"Tue Jan 1 1980\"", "@QString");
+
+ QTest::newRow("QTime0")
+ << Data("#include <QTime>\n",
+ "QTime time;\n")
+ % CheckType("time", "@QTime")
+ % Check("time.(ISO)", "", "@QString")
+ % CheckType("time.(Locale)", "@QString")
+ % CheckType("time.(SystemLocale)", "@QString")
+ % Check("time.toString", "", "@QString");
+
+ QTest::newRow("QTime1")
+ << Data("#include <QTime>\n",
+ "QTime time(13, 15, 32);")
+ % Check("time", "13:15:32", "@QTime")
+ % Check("time.(ISO)", "\"13:15:32\"", "@QString")
+ % CheckType("time.(Locale)", "@QString")
+ % CheckType("time.(SystemLocale)", "@QString")
+ % Check("time.toString", "\"13:15:32\"", "@QString");
+
+ QTest::newRow("QDateTime")
+ << Data("#include <QDateTime>\n",
+ "QDateTime date;\n")
+ % CheckType("date", "@QDateTime")
+ % Check("date.(ISO)", "", "@QString")
+ % Check("date.(Locale)", "", "@QString")
+ % Check("date.(SystemLocale)", "", "@QString")
+ % Check("date.toString", "\"\"", "@QString")
+ % Check("date.toUTC", "", "@QDateTime");
+
+ QTest::newRow("QDir")
+#ifdef Q_OS_WIN
+ << Data("#include <QDir>\n",
+ "QDir dir(\"C:\\\\Program Files\");")
+ % Check("dir", "C:/Program Files", "@QDir")
+ % Check("dir.absolutePath", "C:/Program Files", "@QString")
+ % Check("dir.canonicalPath", "C:/Program Files", "@QString");
+#else
+ << Data("#include <QDir>\n",
+ "QDir dir(\"/tmp\"); QString s = dir.absolutePath();")
+ % Check("dir", "/tmp", "@QDir")
+ % Check("dir.absolutePath", "\"/tmp\"", "@QString")
+ % Check("dir.canonicalPath", "\"/tmp\"", "@QString");
#endif
-void tst_Dumpers::dumpQWeakPointer()
-{
-#if QT_VERSION >= 0x040500
- // Case 1: Simple type.
-
- // Case 1.1: Null pointer.
- QSharedPointer<int> spNull;
- QWeakPointer<int> wp = spNull.toWeakRef();
- testDumper("value='<null>',valueeditable='false',numchild='0'",
- &wp, NS"QWeakPointer", true, "int");
-
- // Case 1.2: Weak pointer is unique.
- QSharedPointer<int> sp(new int(99));
- wp = sp.toWeakRef();
- dumpQWeakPointerHelper(wp);
-
- // Case 1.3: There are other weak pointers.
- QWeakPointer<int> wp2 = sp.toWeakRef();
- dumpQWeakPointerHelper(wp);
-
- // Case 1.4: There are other strong shared pointers as well.
- QSharedPointer<int> sp2(sp);
- dumpQWeakPointerHelper(wp);
-
- // Case 2: Composite type.
- QSharedPointer<QString> spS(new QString("Test"));
- QWeakPointer<QString> wpS = spS.toWeakRef();
- dumpQWeakPointerHelper(wpS);
+ QTest::newRow("QFileInfo")
+#ifdef Q_OS_WIN
+ << Data("#include <QFile>\n"
+ "#include <QFileInfo>\n",
+ "QFile file(\"C:\\\\Program Files\\t\");\n"
+ "file.setObjectName(\"A QFile instance\");\n"
+ "QFileInfo fi(\"C:\\Program Files\\tt\");\n"
+ "QString s = fi.absoluteFilePath();\n")
+ % Check("fi", "\"C:/Program Files/tt\"", "QFileInfo")
+ % Check("file", "\"C:\Program Files\t\"", "QFile")
+ % Check("s", "\"C:/Program Files/tt\"", "QString");
+#else
+ << Data("#include <QFile>\n"
+ "#include <QFileInfo>\n",
+ "QFile file(\"/tmp/t\");\n"
+ "file.setObjectName(\"A QFile instance\");\n"
+ "QFileInfo fi(\"/tmp/tt\");\n"
+ "QString s = fi.absoluteFilePath();\n")
+ % Check("fi", "\"/tmp/tt\"", "@QFileInfo")
+ % Check("file", "\"/tmp/t\"", "@QFile")
+ % Check("s", "\"/tmp/tt\"", "@QString");
#endif
-}
-#define VERIFY_OFFSETOF(member) \
-do { \
- QObjectPrivate *qob = 0; \
- ObjectPrivate *ob = 0; \
- QVERIFY(size_t(&qob->member) == size_t(&ob->member)); \
-} while (0)
-
-
-void tst_Dumpers::initTestCase()
-{
- QVERIFY(sizeof(QWeakPointer<int>) == 2*sizeof(void *));
- QVERIFY(sizeof(QSharedPointer<int>) == 2*sizeof(void *));
-#if QT_VERSION < 0x050000
- QtSharedPointer::ExternalRefCountData d;
- d.weakref = d.strongref = 0; // That's what the destructor expects.
- QVERIFY(sizeof(int) == sizeof(d.weakref));
- QVERIFY(sizeof(int) == sizeof(d.strongref));
-#endif
-#ifdef USE_PRIVATE
- const size_t qObjectPrivateSize = sizeof(QObjectPrivate);
- const size_t objectPrivateSize = sizeof(ObjectPrivate);
- QVERIFY2(qObjectPrivateSize == objectPrivateSize, QString::fromLatin1("QObjectPrivate=%1 ObjectPrivate=%2").arg(qObjectPrivateSize).arg(objectPrivateSize).toLatin1().constData());
- VERIFY_OFFSETOF(threadData);
- VERIFY_OFFSETOF(extraData);
- VERIFY_OFFSETOF(objectName);
- VERIFY_OFFSETOF(connectionLists);
- VERIFY_OFFSETOF(senders);
- VERIFY_OFFSETOF(currentSender);
- VERIFY_OFFSETOF(eventFilters);
- VERIFY_OFFSETOF(currentChildBeingDeleted);
- VERIFY_OFFSETOF(connectedSignals);
- //VERIFY_OFFSETOF(deleteWatch);
-#ifdef QT3_SUPPORT
-#if QT_VERSION < 0x040600
- VERIFY_OFFSETOF(pendingChildInsertedEvents);
-#endif
-#endif
-#if QT_VERSION >= 0x040600
- VERIFY_OFFSETOF(sharedRefcount);
-#endif
-#endif
+ QTest::newRow("QHash1")
+ << Data("#include <QHash>\n",
+ "QHash<QString, QList<int> > hash;\n"
+ "hash.insert(\"Hallo\", QList<int>());\n"
+ "hash.insert(\"Welt\", QList<int>() << 1);\n"
+ "hash.insert(\"!\", QList<int>() << 1 << 2);\n")
+ % Check("hash", "<3 items>", "@QHash<@QString, @QList<int> >")
+ % Check("hash.0", "[0]", "", "@QHashNode<@QString, @QList<int>>")
+ % Check("hash.0.key", "\"Hallo\"", "@QString")
+ % Check("hash.0.value", "<0 items>", "@QList<int>")
+ % Check("hash.1", "[1]", "", "@QHashNode<@QString, @QList<int>>")
+ % Check("hash.1.key", "key", "\"Welt\"", "@QString")
+ % Check("hash.1.value", "value", "<1 items>", "@QList<int>")
+ % Check("hash.1.value.0", "[0]", "1", "int")
+ % Check("hash.2", "[2]", "", "@QHashNode<@QString, @QList<int>>")
+ % Check("hash.2.key", "key", "\"!\"", "@QString")
+ % Check("hash.2.value", "value", "<2 items>", "@QList<int>")
+ % Check("hash.2.value.0", "[0]", "1", "int")
+ % Check("hash.2.value.1", "[1]", "2", "int");
+
+ QTest::newRow("QHash2")
+ << Data("#include <QHash>\n",
+ "QHash<int, float> hash;\n"
+ "hash[11] = 11.0;\n"
+ "hash[22] = 22.0;\n")
+ % Check("hash", "hash", "<2 items>", "@QHash<int, float>")
+ % Check("hash.22", "[22]", "22", "float")
+ % Check("hash.11", "[11]", "11", "float");
+
+ QTest::newRow("QHash3")
+ << Data("#include <QHash>\n",
+ "QHash<QString, int> hash;\n"
+ "hash[\"22.0\"] = 22.0;\n"
+ "hash[\"123.0\"] = 22.0;\n"
+ "hash[\"111111ss111128.0\"] = 28.0;\n"
+ "hash[\"11124.0\"] = 22.0;\n"
+ "hash[\"1111125.0\"] = 22.0;\n"
+ "hash[\"11111126.0\"] = 22.0;\n"
+ "hash[\"111111127.0\"] = 27.0;\n"
+ "hash[\"111111111128.0\"] = 28.0;\n"
+ "hash[\"111111111111111111129.0\"] = 29.0;\n")
+ % Check("hash", "hash", "<9 items>", "@QHash<@QString, int>")
+ % Check("hash.0", "[0]", "", "@QHashNode<@QString, int>")
+ % Check("hash.0.key", "key", "\"123.0\"", "@QString")
+ % Check("hash.0.value", "22", "int")
+ % Check("hash.8", "[8]", "", "@QHashNode<@QString, int>")
+ % Check("hash.8.key", "key", "\"11124.0\"", "@QString")
+ % Check("hash.8.value", "value", "22", "int");
+
+ QTest::newRow("QHash4")
+ << Data("#include <QHash>\n",
+ "QHash<QByteArray, float> hash;\n"
+ "hash[\"22.0\"] = 22.0;\n"
+ "hash[\"123.0\"] = 22.0;\n"
+ "hash[\"111111ss111128.0\"] = 28.0;\n"
+ "hash[\"11124.0\"] = 22.0;\n"
+ "hash[\"1111125.0\"] = 22.0;\n"
+ "hash[\"11111126.0\"] = 22.0;\n"
+ "hash[\"111111127.0\"] = 27.0;\n"
+ "hash[\"111111111128.0\"] = 28.0;\n"
+ "hash[\"111111111111111111129.0\"] = 29.0;\n")
+ % Check("hash", "<9 items>", "@QHash<@QByteArray, float>")
+ % Check("hash.0", "[0]", "", "@QHashNode<@QByteArray, float>")
+ % Check("hash.0.key", "\"123.0\"", "@QByteArray")
+ % Check("hash.0.value", "22", "float")
+ % Check("hash.8", "[8]", "", "@QHashNode<@QByteArray, float>")
+ % Check("hash.8.key", "\"11124.0\"", "@QByteArray")
+ % Check("hash.8.value", "22", "float");
+
+ QTest::newRow("QHash5")
+ << Data("#include <QHash>\n",
+ "QHash<int, QString> hash;\n"
+ "hash[22] = \"22.0\";\n")
+ % Check("hash", "<1 items>", "@QHash<int, @QString>")
+ % Check("hash.0", "[0]", "", "@QHashNode<int, @QString>")
+ % Check("hash.0.key", "22", "int")
+ % Check("hash.0.value", "\"22.0\"", "@QString");
+
+ QTest::newRow("QHash6")
+ << Data("#include <QHash>\n" + fooData,
+ "QHash<QString, Foo> hash;\n"
+ "hash[\"22.0\"] = Foo(22);\n"
+ "hash[\"33.0\"] = Foo(33);\n")
+ % Check("hash", "<2 items>", "@QHash<@QString, Foo>")
+ % Check("hash.0", "[0]", "", "@QHashNode<@QString, Foo>")
+ % Check("hash.0.key", "\"22.0\"", "@QString")
+ % CheckType("hash.0.value", "Foo")
+ % Check("hash.0.value.a", "22", "int")
+ % Check("hash.1", "[1]", "", "@QHashNode<@QString, Foo>")
+ % Check("hash.1.key", "\"33.0\"", "@QString")
+ % CheckType("hash.1.value", "Foo");
+
+ QTest::newRow("QHash7")
+ << Data("#include <QHash>\n"
+ "#include <QPointer>\n",
+ "QObject ob;\n"
+ "QHash<QString, QPointer<QObject> > hash;\n"
+ "hash.insert(\"Hallo\", QPointer<QObject>(&ob));\n"
+ "hash.insert(\"Welt\", QPointer<QObject>(&ob));\n"
+ "hash.insert(\".\", QPointer<QObject>(&ob));\n")
+ % Check("hash", "<3 items>", "@QHash<@QString, @QPointer<@QObject>>")
+ % Check("hash.0", "[0]", "", "@QHashNode<@QString, @QPointer<@QObject>>")
+ % Check("hash.0.key", "\"Hallo\"", "@QString")
+ % CheckType("hash.0.value", "@QPointer<@QObject>")
+ % CheckType("hash.0.value.o", "@QObject")
+ % Check("hash.2", "[2]", "", "@QHashNode<@QString, @QPointer<@QObject>>")
+ % Check("hash.2.key", "\".\"", "@QString")
+ % CheckType("hash.2.value", "@QPointer<@QObject>");
+
+ QTest::newRow("QHashIntFloatIterator")
+ << Data("#include <QHash>\n",
+ "typedef QHash<int, float> Hash;\n"
+ "Hash hash;\n"
+ "hash[11] = 11.0;\n"
+ "hash[22] = 22.0;\n"
+ "hash[33] = 33.0;\n"
+ "hash[44] = 44.0;\n"
+ "hash[55] = 55.0;\n"
+ "hash[66] = 66.0;\n"
+ "Hash::iterator it1 = hash.begin();\n"
+ "Hash::iterator it2 = it1; ++it2;\n"
+ "Hash::iterator it3 = it2; ++it3;\n"
+ "Hash::iterator it4 = it3; ++it4;\n"
+ "Hash::iterator it5 = it4; ++it5;\n"
+ "Hash::iterator it6 = it5; ++it6;\n")
+ % Check("hash", "<6 items>", "Hash")
+ % Check("hash.11", "[11]", "11", "float")
+ % Check("it1.key", "55", "int")
+ % Check("it1.value", "55", "float")
+ % Check("it6.key", "33", "int")
+ % Check("it6.value", "33", "float");
+
+ QTest::newRow("QHostAddress")
+ << Data("#include <QHostAddress>\n",
+ "QHostAddress ha1(129u * 256u * 256u * 256u + 130u);\n"
+ "QHostAddress ha2(\"127.0.0.1\");\n")
+ % Profile("QT += network\n")
+ % Check("ha1", "129.0.0.130", "@QHostAddress")
+ % Check("ha2", "\"127.0.0.1\"", "@QHostAddress");
+
+ QTest::newRow("QImage")
+ << Data("#include <QImage>\n"
+ "#include <QPainter>\n",
+ "QImage im(QSize(200, 200), QImage::Format_RGB32);\n"
+ "im.fill(QColor(200, 100, 130).rgba());\n"
+ "QPainter pain;\n"
+ "pain.begin(&im);\n")
+ % GuiProfile()
+ % Check("im", "(200x200)", "@QImage")
+ % CheckType("pain", "@QPainter");
+
+ QTest::newRow("QPixmap")
+ << Data("#include <QImage>\n"
+ "#include <QPainter>\n"
+ "#include <QApplication>\n",
+ "QApplication app(argc, argv);\n"
+ "QImage im(QSize(200, 200), QImage::Format_RGB32);\n"
+ "im.fill(QColor(200, 100, 130).rgba());\n"
+ "QPainter pain;\n"
+ "pain.begin(&im);\n"
+ "pain.drawLine(2, 2, 130, 130);\n"
+ "pain.end();\n"
+ "QPixmap pm = QPixmap::fromImage(im);\n"
+ "dummyStatement(&pm);\n")
+ % GuiProfile()
+ % Check("im", "(200x200)", "@QImage")
+ % CheckType("pain", "@QPainter")
+ % Check("pm", "(200x200)", "@QPixmap");
+
+ QTest::newRow("QLinkedListInt")
+ << Data("#include <QLinkedList>\n",
+ "QLinkedList<int> list;\n"
+ "list.append(101);\n"
+ "list.append(102);\n")
+ % Check("list", "<2 items>", "@QLinkedList<int>")
+ % Check("list.0", "[0]", "101", "int")
+ % Check("list.1", "[1]", "102", "int");
+
+ QTest::newRow("QLinkedListUInt")
+ << Data("#include <QLinkedList>\n",
+ "QLinkedList<uint> list;\n"
+ "list.append(103);\n"
+ "list.append(104);\n")
+ % Check("list", "<2 items>", "@QLinkedList<unsigned int>")
+ % Check("list.0", "[0]", "103", "unsigned int")
+ % Check("list.1", "[1]", "104", "unsigned int");
+
+ QTest::newRow("QLinkedListFooStar")
+ << Data("#include <QLinkedList>\n" + fooData,
+ "QLinkedList<Foo *> list;\n"
+ "list.append(new Foo(1));\n"
+ "list.append(0);\n"
+ "list.append(new Foo(3));\n")
+ % Check("list", "<3 items>", "@QLinkedList<Foo*>")
+ % CheckType("list.0", "[0]", "Foo")
+ % Check("list.0.a", "1", "int")
+ % Check("list.1", "[1]", "0x0", "Foo *")
+ % CheckType("list.2", "[2]", "Foo")
+ % Check("list.2.a", "3", "int");
+
+ QTest::newRow("QLinkedListULongLong")
+ << Data("#include <QLinkedList>\n",
+ "QLinkedList<qulonglong> list;\n"
+ "list.append(42);\n"
+ "list.append(43);\n")
+ % Check("list", "<2 items>", "@QLinkedList<unsigned long long>")
+ % Check("list.0", "[0]", "42", "unsigned long long")
+ % Check("list.1", "[1]", "43", "unsigned long long");
+
+ QTest::newRow("QLinkedListFoo")
+ << Data("#include <QLinkedList>\n" + fooData,
+ "QLinkedList<Foo> list;\n"
+ "list.append(Foo(1));\n"
+ "list.append(Foo(2));\n")
+ % Check("list", "<2 items>", "@QLinkedList<Foo>")
+ % CheckType("list.0", "[0]", "Foo")
+ % Check("list.0.a", "1", "int")
+ % CheckType("list.1", "[1]", "Foo")
+ % Check("list.1.a", "2", "int");
+
+ QTest::newRow("QLinkedListStdString")
+ << Data("#include <QLinkedList>\n"
+ "#include <string>\n",
+ "QLinkedList<std::string> list;\n"
+ "list.push_back(\"aa\");\n"
+ "list.push_back(\"bb\");\n")
+ % Check("list", "<2 items>", "@QLinkedList<std::string>")
+ % Check("list.0", "[0]", "\"aa\"", "std::string")
+ % Check("list.1", "[1]", "\"bb\"", "std::string");
+
+ QTest::newRow("QListInt")
+ << Data("#include <QList>\n",
+ "QList<int> big;\n"
+ "for (int i = 0; i < 10000; ++i)\n"
+ " big.push_back(i);\n")
+ % Check("big", "<10000 items>", "@QList<int>")
+ % Check("big.0", "[0]", "0", "int")
+ % Check("big.1999", "[1999]", "1999", "int");
+
+ QTest::newRow("QListIntTakeFirst")
+ << Data("#include <QList>\n",
+ "QList<int> l;\n"
+ "l.append(0);\n"
+ "l.append(1);\n"
+ "l.append(2);\n"
+ "l.takeFirst();\n")
+ % Check("l", "<2 items>", "@QList<int>")
+ % Check("l.0", "[0]", "1", "int");
+
+ QTest::newRow("QListStringTakeFirst")
+ << Data("#include <QList>\n"
+ "#include <QString>\n",
+ "QList<QString> l;\n"
+ "l.append(\"0\");\n"
+ "l.append(\"1\");\n"
+ "l.append(\"2\");\n"
+ "l.takeFirst();\n")
+ % Check("l", "<2 items>", "@QList<@QString>")
+ % Check("l.0", "[0]", "\"1\"", "@QString");
+
+ QTest::newRow("QStringListTakeFirst")
+ << Data("#include <QStringList>\n",
+ "QStringList l;\n"
+ "l.append(\"0\");\n"
+ "l.append(\"1\");\n"
+ "l.append(\"2\");\n"
+ "l.takeFirst();\n")
+ % Check("l", "<2 items>", "@QStringList")
+ % Check("l.0", "[0]", "\"1\"", "@QString");
+
+ QTest::newRow("QListIntStar")
+ << Data("#include <QList>\n",
+ "QList<int *> l0, l;\n"
+ "l.append(new int(1));\n"
+ "l.append(new int(2));\n"
+ "l.append(new int(3));\n")
+ % Check("l0", "<0 items>", "@QList<int*>")
+ % Check("l", "<3 items>", "@QList<int*>")
+ % CheckType("l.0", "[0]", "int")
+ % CheckType("l.2", "[2]", "int");
+
+ QTest::newRow("QListUInt")
+ << Data("#include <QList>\n",
+ "QList<uint> l0,l;\n"
+ "l.append(101);\n"
+ "l.append(102);\n"
+ "l.append(102);\n")
+ % Check("l0", "<0 items>", "@QList<unsigned int>")
+ % Check("l", "<3 items>", "@QList<unsigned int>")
+ % Check("l.0", "[0]", "101", "unsigned int")
+ % Check("l.2", "[2]", "102", "unsigned int");
+
+ QTest::newRow("QListUShort")
+ << Data("#include <QList>\n",
+ "QList<ushort> l0,l;\n"
+ "l.append(101);\n"
+ "l.append(102);\n"
+ "l.append(102);\n")
+ % Check("l0", "<0 items>", "@QList<unsigned short>")
+ % Check("l", "<3 items>", "@QList<unsigned short>")
+ % Check("l.0", "[0]", "101", "unsigned short")
+ % Check("l.2", "[2]", "102", "unsigned short");
+
+ QTest::newRow("QListQChar")
+ << Data("#include <QList>\n"
+ "#include <QChar>\n",
+ "QList<QChar> l0, l;\n"
+ "l.append(QChar('a'));\n"
+ "l.append(QChar('b'));\n"
+ "l.append(QChar('c'));\n")
+ % Check("l0", "<0 items>", "@QList<@QChar>")
+ % Check("l", "<3 items>", "@QList<@QChar>")
+ % Check("l.0", "[0]", "'a' (97)", "@QChar")
+ % Check("l.2", "[2]", "'c' (99)", "@QChar");
+
+ QTest::newRow("QListQULongLong")
+ << Data("#include <QList>\n",
+ "QList<qulonglong> l0, l;\n"
+ "l.append(101);\n"
+ "l.append(102);\n"
+ "l.append(102);\n")
+ % Check("l0", "<0 items>", "@QList<unsigned long long>")
+ % Check("l", "<3 items>", "@QList<unsigned long long>")
+ % Check("l.0", "[0]", "101", "unsigned long long")
+ % Check("l.2", "[2]", "102", "unsigned long long");
+
+ QTest::newRow("QListStdString")
+ << Data("#include <QList>\n"
+ "#include <string>\n",
+ "QList<std::string> l0, l;\n"
+ "l.push_back(\"aa\");\n"
+ "l.push_back(\"bb\");\n"
+ "l.push_back(\"cc\");\n"
+ "l.push_back(\"dd\");")
+ % Check("l0", "<0 items>", "@QList<std::string>")
+ % Check("l", "<4 items>", "@QList<std::string>")
+ % CheckType("l.0", "[0]", "std::string")
+ % Check("l.3", "[3]" ,"\"dd\"", "std::string");
+
+ QTest::newRow("QListFoo")
+ << Data("#include <QList>\n" + fooData,
+ "QList<Foo> l0, l;\n"
+ "for (int i = 0; i < 100; ++i)\n"
+ " l.push_back(i + 15);\n")
+ % Check("l0", "<0 items>", "@QList<Foo>")
+ % Check("l", "<100 items>", "@QList<Foo>")
+ % Check("l.0", "[0]", "", "Foo")
+ % Check("l.99", "[99]", "", "Foo");
+
+ QTest::newRow("QListReverse")
+ << Data("#include <QList>\n",
+ "QList<int> l = QList<int>() << 1 << 2 << 3;\n"
+ "typedef std::reverse_iterator<QList<int>::iterator> Reverse;\n"
+ "Reverse rit(l.end());\n"
+ "Reverse rend(l.begin());\n"
+ "QList<int> r;\n"
+ "while (rit != rend)\n"
+ " r.append(*rit++);\n")
+ % Check("l", "<3 items>", "@QList<int>")
+ % Check("l.0", "[0]", "1", "int")
+ % Check("l.1", "[1]", "2", "int")
+ % Check("l.2", "[2]", "3", "int")
+ % Check("r", "<3 items>", "@QList<int>")
+ % Check("r.0", "[0]", "3", "int")
+ % Check("r.1", "[1]", "2", "int")
+ % Check("r.2", "[2]", "1", "int")
+ % Check("rend", "", "Reverse")
+ % Check("rit", "", "Reverse");
+
+ QTest::newRow("QLocale")
+ << Data("#include <QLocale>\n",
+ "QLocale loc = QLocale::system();\n"
+ "QLocale::MeasurementSystem m = loc.measurementSystem();\n"
+ "dummyStatement(&m);\n")
+ % Check("loc", "", "@QLocale")
+ % Check("m", "", "@QLocale::MeasurementSystem");
+
+
+ QTest::newRow("QMapUIntStringList")
+ << Data("#include <QMap>\n"
+ "#include <QStringList>\n",
+ "QMap<uint, QStringList> map;\n"
+ "map[11] = QStringList() << \"11\";\n"
+ "map[22] = QStringList() << \"22\";\n")
+ % Check("map", "<2 items>", "@QMap<unsigned int, @QStringList>")
+ % Check("map.0", "[0]", "", "@QMapNode<unsigned int, @QStringList>")
+ % Check("map.0.key", "11", "unsigned int")
+ % Check("map.0.value", "<1 items>", "@QStringList")
+ % Check("map.0.value.0", "[0]", "\"11\"", "@QString")
+ % Check("map.1", "[1]", "", "@QMapNode<unsigned int, @QStringList>")
+ % Check("map.1.key", "22", "unsigned int")
+ % Check("map.1.value", "<1 items>", "@QStringList")
+ % Check("map.1.value.0", "[0]", "\"22\"", "@QString");
+
+ QTest::newRow("QMapUIntStringListTypedef")
+ << Data("#include <QMap>\n"
+ "#include <QStringList>\n",
+ "typedef QMap<uint, QStringList> T;\n"
+ "T map;\n"
+ "map[11] = QStringList() << \"11\";\n"
+ "map[22] = QStringList() << \"22\";\n")
+ % Check("map", "<2 items>", "T")
+ % Check("map.0", "[0]", "", "@QMapNode<unsigned int, @QStringList>");
+
+ QTest::newRow("QMapUIntFloat")
+ << Data("#include <QMap>\n",
+ "QMap<uint, float> map;\n"
+ "map[11] = 11.0;\n"
+ "map[22] = 22.0;\n")
+ % Check("map", "<2 items>", "@QMap<unsigned int, float>")
+ % Check("map.11", "[11]", "11", "float")
+ % Check("map.22", "[22]", "22", "float");
+
+ QTest::newRow("QMapStringFloat")
+ << Data("#include <QMap>\n"
+ "#include <QString>\n",
+ "QMap<QString, float> map;\n"
+ "map[\"22.0\"] = 22.0;\n")
+ % Check("map", "<1 items>", "@QMap<@QString, float>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, float>")
+ % Check("map.0.key", "\"22.0\"", "@QString")
+ % Check("map.0.value", "22", "float");
+
+ QTest::newRow("QMapIntString")
+ << Data("#include <QMap>\n"
+ "#include <QString>\n",
+ "QMap<int, QString> map;\n"
+ "map[22] = \"22.0\";\n")
+ % Check("map", "<1 items>", "@QMap<int, @QString>")
+ % Check("map.0", "[0]", "", "@QMapNode<int, @QString>")
+ % Check("map.0.key", "22", "int")
+ % Check("map.0.value", "\"22.0\"", "@QString");
+
+ QTest::newRow("QMapStringFoo")
+ << Data("#include <QMap>\n" + fooData +
+ "#include <QString>\n",
+ "QMap<QString, Foo> map;\n"
+ "map[\"22.0\"] = Foo(22);\n"
+ "map[\"33.0\"] = Foo(33);\n")
+ % Check("map", "<2 items>", "@QMap<@QString, Foo>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, Foo>")
+ % Check("map.0.key", "\"22.0\"", "@QString")
+ % Check("map.0.value", "", "Foo")
+ % Check("map.0.value.a", "22", "int")
+ % Check("map.1", "[1]", "", "@QMapNode<@QString, Foo>")
+ % Check("map.1.key", "\"33.0\"", "@QString")
+ % Check("map.1.value", "", "Foo")
+ % Check("map.1.value.a", "33", "int");
+
+ QTest::newRow("QMapStringPointer")
+ << Data("#include <QMap>\n"
+ "#include <QObject>\n"
+ "#include <QPointer>\n"
+ "#include <QString>\n",
+ "QObject ob;\n"
+ "QMap<QString, QPointer<QObject> > map;\n"
+ "map.insert(\"Hallo\", QPointer<QObject>(&ob));\n"
+ "map.insert(\"Welt\", QPointer<QObject>(&ob));\n"
+ "map.insert(\".\", QPointer<QObject>(&ob));\n")
+ % Check("map", "<3 items>", "@QMap<@QString, @QPointer<@QObject>>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.0.key", "\".\"", "@QString")
+ % Check("map.0.value", "", "@QPointer<@QObject>")
+ % Check("map.0.value.o", "", "@QObject")
+ % Check("map.1", "[1]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.1.key", "\"Hallo\"", "@QString")
+ % Check("map.2", "[2]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.2.key", "\"Welt\"", "@QString");
+
+ QTest::newRow("QMapStringList")
+ << Data("#include <QMap>\n"
+ "#include <QList>\n"
+ "#include <QString>\n" + nsData,
+ "QList<nsA::nsB::SomeType *> x;\n"
+ "x.append(new nsA::nsB::SomeType(1));\n"
+ "x.append(new nsA::nsB::SomeType(2));\n"
+ "x.append(new nsA::nsB::SomeType(3));\n"
+ "QMap<QString, QList<nsA::nsB::SomeType *> > map;\n"
+ "map[\"foo\"] = x;\n"
+ "map[\"bar\"] = x;\n"
+ "map[\"1\"] = x;\n"
+ "map[\"2\"] = x;\n")
+ % Check("map", "<4 items>", "@QMap<@QString, @QList<nsA::nsB::SomeType*>>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, @QList<nsA::nsB::SomeType*>>")
+ % Check("map.0.key", "\"1\"", "@QString")
+ % Check("map.0.value", "<3 items>", "@QList<nsA::nsB::SomeType*>")
+ % Check("map.0.value.0", "[0]", "", "nsA::nsB::SomeType")
+ % Check("map.0.value.0.a", "1", "int")
+ % Check("map.0.value.1", "[1]", "", "nsA::nsB::SomeType")
+ % Check("map.0.value.1.a", "2", "int")
+ % Check("map.0.value.2", "[2]", "", "nsA::nsB::SomeType")
+ % Check("map.0.value.2.a", "3", "int")
+ % Check("map.3", "[3]", "", "@QMapNode<@QString, @QList<nsA::nsB::SomeType*>>")
+ % Check("map.3.key", "\"foo\"", "@QString")
+ % Check("map.3.value", "<3 items>", "@QList<nsA::nsB::SomeType*>")
+ % Check("map.3.value.2", "[2]", "", "nsA::nsB::SomeType")
+ % Check("map.3.value.2.a", "3", "int")
+ % Check("x", "<3 items>", "@QList<nsA::nsB::SomeType*>");
+
+ QTest::newRow("QMultiMapUintFloat")
+ << Data("#include <QMap>\n",
+ "QMultiMap<uint, float> map;\n"
+ "map.insert(11, 11.0);\n"
+ "map.insert(22, 22.0);\n"
+ "map.insert(22, 33.0);\n"
+ "map.insert(22, 34.0);\n"
+ "map.insert(22, 35.0);\n"
+ "map.insert(22, 36.0);\n")
+ % Check("map", "<6 items>", "@QMultiMap<unsigned int, float>")
+ % Check("map.0", "[0]", "11", "float")
+ % Check("map.5", "[5]", "22", "float");
+
+ QTest::newRow("QMultiMapStringFloat")
+ << Data("#include <QMap>\n"
+ "#include <QString>\n",
+ "QMultiMap<QString, float> map;\n"
+ "map.insert(\"22.0\", 22.0);\n")
+ % Check("map", "<1 items>", "@QMultiMap<@QString, float>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, float>")
+ % Check("map.0.key", "\"22.0\"", "@QString")
+ % Check("map.0.value", "22", "float");
+
+ QTest::newRow("QMultiMapIntString")
+ << Data("#include <QMap>\n"
+ "#include <QString>\n",
+ "QMultiMap<int, QString> map;\n"
+ "map.insert(22, \"22.0\");\n")
+ % Check("map", "<1 items>", "@QMultiMap<int, @QString>")
+ % Check("map.0", "[0]", "", "@QMapNode<int, @QString>")
+ % Check("map.0.key", "22", "int")
+ % Check("map.0.value", "\"22.0\"", "@QString");
+
+ QTest::newRow("QMultiMapStringFoo")
+ << Data("#include <QMultiMap>\n" + fooData,
+ "QMultiMap<QString, Foo> map;\n"
+ "map.insert(\"22.0\", Foo(22));\n"
+ "map.insert(\"33.0\", Foo(33));\n"
+ "map.insert(\"22.0\", Foo(22));\n")
+ % Check("map", "<3 items>", "@QMultiMap<@QString, Foo>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, Foo>")
+ % Check("map.0.key", "\"22.0\"", "@QString")
+ % Check("map.0.value", "", "Foo")
+ % Check("map.0.value.a", "22", "int")
+ % Check("map.2", "[2]", "", "@QMapNode<@QString, Foo>");
+
+ QTest::newRow("QMultiMapStringPointer")
+ << Data("#include <QMap>\n"
+ "#include <QObject>\n"
+ "#include <QPointer>\n"
+ "#include <QString>\n",
+ "QObject ob;\n"
+ "QMultiMap<QString, QPointer<QObject> > map;\n"
+ "map.insert(\"Hallo\", QPointer<QObject>(&ob));\n"
+ "map.insert(\"Welt\", QPointer<QObject>(&ob));\n"
+ "map.insert(\".\", QPointer<QObject>(&ob));\n"
+ "map.insert(\".\", QPointer<QObject>(&ob));\n")
+ % Check("map", "<4 items>", "@QMultiMap<@QString, @QPointer<@QObject>>")
+ % Check("map.0", "[0]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.0.key", "\".\"", "@QString")
+ % Check("map.0.value", "", "@QPointer<@QObject>")
+ % Check("map.1", "[1]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.1.key", "\".\"", "@QString")
+ % Check("map.2", "[2]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.2.key", "\"Hallo\"", "@QString")
+ % Check("map.3", "[3]", "", "@QMapNode<@QString, @QPointer<@QObject>>")
+ % Check("map.3.key", "\"Welt\"", "@QString");
+
+
+ QTest::newRow("QObject1")
+ << Data("#include <QObject>\n",
+ "QObject parent;\n"
+ "parent.setObjectName(\"A Parent\");\n"
+ "QObject child(&parent);\n"
+ "child.setObjectName(\"A Child\");\n"
+ "QObject::connect(&child, SIGNAL(destroyed()), &parent, SLOT(deleteLater()));\n"
+ "QObject::disconnect(&child, SIGNAL(destroyed()), &parent, SLOT(deleteLater()));\n"
+ "child.setObjectName(\"A renamed Child\");\n")
+ % Check("child", "\"A renamed Child\"", "@QObject")
+ % Check("parent", "\"A Parent\"", "@QObject");
+
+ QByteArray objectData =
+ "#include <QWidget>\n"
+ " namespace Names {\n"
+ " namespace Bar {\n"
+ " struct Ui { Ui() { w = 0; } QWidget *w; };\n"
+ " class TestObject : public QObject\n"
+ " {\n"
+ " Q_OBJECT\n"
+ " public:\n"
+ " TestObject(QObject *parent = 0)\n"
+ " : QObject(parent)\n"
+ " {\n"
+ " m_ui = new Ui;\n"
+ " #if USE_GUILIB\n"
+ " m_ui->w = new QWidget;\n"
+ " #else\n"
+ " m_ui->w = 0;\n"
+ " #endif\n"
+ " }\n"
+ " Q_PROPERTY(QString myProp1 READ myProp1 WRITE setMyProp1)\n"
+ " QString myProp1() const { return m_myProp1; }\n"
+ " Q_SLOT void setMyProp1(const QString&mt) { m_myProp1 = mt; }\n"
+ " Q_PROPERTY(QString myProp2 READ myProp2 WRITE setMyProp2)\n"
+ " QString myProp2() const { return m_myProp2; }\n"
+ " Q_SLOT void setMyProp2(const QString&mt) { m_myProp2 = mt; }\n"
+ " public:\n"
+ " Ui *m_ui;\n"
+ " QString m_myProp1;\n"
+ " QString m_myProp2;\n"
+ " };\n"
+ " } // namespace Bar\n"
+ " } // namespace Names\n"
+ "\n";
+
+ QTest::newRow("QObject2")
+ << Data(objectData,
+ "Names::Bar::TestObject test;\n"
+ "test.setMyProp1(\"HELLO\");\n"
+ "test.setMyProp2(\"WORLD\");\n"
+ "QString s = test.myProp1();\n"
+ "s += test.myProp2();\n")
+ % Check("s", "\"HELLOWORLD\"", "@QString")
+ % Check("test", "", "Names::Bar::TestObject");
+
+ QTest::newRow("QObject2")
+ << Data("QWidget ob;\n"
+ "ob.setObjectName(\"An Object\");\n"
+ "ob.setProperty(\"USER DEFINED 1\", 44);\n"
+ "ob.setProperty(\"USER DEFINED 2\", QStringList() << \"FOO\" << \"BAR\");\n"
+ ""
+ "QObject ob1;\n"
+ "ob1.setObjectName(\"Another Object\");\n"
+ "QObject::connect(&ob, SIGNAL(destroyed()), &ob1, SLOT(deleteLater()));\n"
+ "QObject::connect(&ob, SIGNAL(destroyed()), &ob1, SLOT(deleteLater()));\n"
+ "//QObject::connect(&app, SIGNAL(lastWindowClosed()), &ob, SLOT(deleteLater()));\n"
+ ""
+ "QList<QObject *> obs;\n"
+ "obs.append(&ob);\n"
+ "obs.append(&ob1);\n"
+ "obs.append(0);\n"
+ "obs.append(&app);\n"
+ "ob1.setObjectName(\"A Subobject\");\n")
+ % GuiProfile()
+ % Check("ob", "An Object", "@QObject");
+
+ QByteArray senderData =
+ " class Sender : public QObject\n"
+ " {\n"
+ " Q_OBJECT\n"
+ " public:\n"
+ " Sender() { setObjectName(\"Sender\"); }\n"
+ " void doEmit() { emit aSignal(); }\n"
+ " signals:\n"
+ " void aSignal();\n"
+ " };\n"
+ "\n"
+ " class Receiver : public QObject\n"
+ " {\n"
+ " Q_OBJECT\n"
+ " public:\n"
+ " Receiver() { setObjectName(\"Receiver\"); }\n"
+ " public slots:\n"
+ " void aSlot() {\n"
+ " QObject *s = sender();\n"
+ " if (s) {\n"
+ " qDebug() << \"SENDER: \" << s;\n"
+ " } else {\n"
+ " qDebug() << \"NO SENDER\";\n"
+ " }\n"
+ " }\n"
+ " };\n";
+
+ QByteArray derivedData =
+ " class DerivedObjectPrivate : public QObjectPrivate\n"
+ " {\n"
+ " public:\n"
+ " DerivedObjectPrivate() {\n"
+ " m_extraX = 43;\n"
+ " m_extraY.append(\"xxx\");\n"
+ " m_extraZ = 1;\n"
+ " }\n"
+ " int m_extraX;\n"
+ " QStringList m_extraY;\n"
+ " uint m_extraZ : 1;\n"
+ " bool m_extraA : 1;\n"
+ " bool m_extraB;\n"
+ " };\n"
+ "\n"
+ " class DerivedObject : public QObject\n"
+ " {\n"
+ " Q_OBJECT\n"
+ "\n"
+ " public:\n"
+ " DerivedObject() : QObject(*new DerivedObjectPrivate, 0) {}\n"
+ "\n"
+ " Q_PROPERTY(int x READ x WRITE setX)\n"
+ " Q_PROPERTY(QStringList y READ y WRITE setY)\n"
+ " Q_PROPERTY(uint z READ z WRITE setZ)\n"
+ "\n"
+ " int x() const;\n"
+ " void setX(int x);\n"
+ " QStringList y() const;\n"
+ " void setY(QStringList y);\n"
+ " uint z() const;\n"
+ " void setZ(uint z);\n"
+ "\n"
+ " private:\n"
+ " Q_DECLARE_PRIVATE(DerivedObject)\n"
+ " };\n"
+ "\n"
+ " int DerivedObject::x() const\n"
+ " {\n"
+ " Q_D(const DerivedObject);\n"
+ " return d->m_extraX;\n"
+ " }\n"
+ "\n"
+ " void DerivedObject::setX(int x)\n"
+ " {\n"
+ " Q_D(DerivedObject);\n"
+ " d->m_extraX = x;\n"
+ " d->m_extraA = !d->m_extraA;\n"
+ " d->m_extraB = !d->m_extraB;\n"
+ " }\n"
+ "\n"
+ " QStringList DerivedObject::y() const\n"
+ " {\n"
+ " Q_D(const DerivedObject);\n"
+ " return d->m_extraY;\n"
+ " }\n"
+ "\n"
+ " void DerivedObject::setY(QStringList y)\n"
+ " {\n"
+ " Q_D(DerivedObject);\n"
+ " d->m_extraY = y;\n"
+ " }\n"
+ "\n"
+ " uint DerivedObject::z() const\n"
+ " {\n"
+ " Q_D(const DerivedObject);\n"
+ " return d->m_extraZ;\n"
+ " }\n"
+ "\n"
+ " void DerivedObject::setZ(uint z)\n"
+ " {\n"
+ " Q_D(DerivedObject);\n"
+ " d->m_extraZ = z;\n"
+ " }\n"
+ "\n"
+ " #endif\n"
+ "\n";
+
+ QTest::newRow("QObjectData")
+ << Data(derivedData,
+ "DerivedObject ob;\n"
+ "ob.setX(26);\n")
+ % Check("ob.properties.x", "26", "@QVariant (int)");
+
+
+ QTest::newRow("QRegExp")
+ << Data("#include <QRegExp>\n",
+ "QRegExp re(QString(\"a(.*)b(.*)c\"));\n"
+ "QString str1 = \"a1121b344c\";\n"
+ "QString str2 = \"Xa1121b344c\";\n"
+ "int pos2 = re.indexIn(str2);\n"
+ "int pos1 = re.indexIn(str1);\n")
+ % Check("re", "\"a(.*)b(.*)c\"", "@QRegExp")
+ % Check("str1", "\"a1121b344c\"", "@QString")
+ % Check("str2", "\"Xa1121b344c\"", "@QString")
+ % Check("pos1", "0", "int")
+ % Check("pos2", "1", "int");
+
+ QTest::newRow("QPoint")
+ << Data("#include <QPoint>\n",
+ "QPoint s0, s;\n"
+ "s = QPoint(100, 200);\n")
+ % Check("s0", "(0, 0)", "@QPoint")
+ % Check("s", "(100, 200)", "@QPoint");
+
+ QTest::newRow("QPointF")
+ << Data("#include <QPointF>\n",
+ "QPointF s0, s;\n"
+ "s = QPointF(100, 200);\n")
+ % Check("s0", "(0, 0)", "@QPointF")
+ % Check("s", "(100, 200)", "@QPointF");
+
+ QTest::newRow("QRect")
+ << Data("#include <QRect>\n",
+ "QRect rect0, rect;\n"
+ "rect = QRect(100, 100, 200, 200);\n")
+ % Check("rect", "0x0+0+0", "@QRect")
+ % Check("rect", "200x200+100+100", "@QRect");
+
+ QTest::newRow("QRectF")
+ << Data("#include <QRectF>\n",
+ "QRectF rect0, rect;\n"
+ "rect = QRectF(100, 100, 200, 200);\n")
+ % Check("rect", "0x0+0+0", "@QRectF")
+ % Check("rect", "200x200+100+100", "@QRectF");
+
+ QTest::newRow("QSize")
+ << Data("#include <QSize>\n",
+ "QSize s0, s;\n"
+ "s = QSize(100, 200);\n")
+ % Check("s0", "(-1, -1)", "@QSize")
+ % Check("s", "(100, 200)", "@QSize");
+
+ QTest::newRow("QSizeF")
+ << Data("#include <QSizeF>\n",
+ "QSizeF s0, s;\n"
+ "s = QSizeF(100, 200);\n")
+ % Check("s0", "(-1, -1)", "@QSizeF")
+ % Check("s", "(100, 200)", "@QSizeF");
+
+ QTest::newRow("QRegion")
+ << Data("#include <QRegion>\n",
+ "QRegion region, region0, region1, region2, region4;\n"
+ "region += QRect(100, 100, 200, 200);\n"
+ "region0 = region;\n"
+ "region += QRect(300, 300, 400, 500);\n"
+ "region1 = region;\n"
+ "region += QRect(500, 500, 600, 600);\n"
+ "region2 = region;\n")
+ % Check("region", "<empty>", "@QRegion")
+ % Check("region", "<1 items>", "@QRegion")
+ % Check("region.extents", "", "@QRect")
+ % Check("region.innerArea", "40000", "int")
+ % Check("region.innerRect", "", "@QRect")
+ % Check("region.numRects", "1", "int")
+ % Check("region.rects", "<0 items>", "@QVector<@QRect>")
+ % Check("region", "<2 items>", "@QRegion")
+ % Check("region.extents", "", "@QRect")
+ % Check("region.innerArea", "200000", "int")
+ % Check("region.innerRect", "", "@QRect")
+ % Check("region.numRects", "2", "int")
+ % Check("region.rects", "<2 items>", "@QVector<@QRect>")
+ % Check("region", "<4 items>", "@QRegion")
+ % Check("region.extents", "", "@QRect")
+ % Check("region.innerArea", "360000", "int")
+ % Check("region.innerRect", "", "@QRect")
+ % Check("region.numRects", "4", "int")
+ % Check("region.rects", "<8 items>", "@QVector<@QRect>")
+ % Check("region", "<4 items>", "@QRegion");
+
+ QTest::newRow("QSettings")
+ << Data("#include <QRegExp>\n",
+ "QCoreApplication app(argc, argv);\n"
+ "QSettings settings(\"/tmp/test.ini\", QSettings::IniFormat);\n"
+ "QVariant value = settings.value(\"item1\", \"\").toString();\n")
+ % Check("settings", "", "@QSettings")
+ % Check("settings.@1", "", "@QObject")
+ % Check("value", "", "@QVariant (QString)");
+
+ QTest::newRow("QSet1")
+ << Data("#include <QRegExp>\n",
+ "QSet<int> s;\n"
+ "s.insert(11);\n"
+ "s.insert(22);\n")
+ % Check("s", "<2 items>", "@QSet<int>")
+ % Check("s.22", "22", "int")
+ % Check("s.11", "11", "int");
+
+ QTest::newRow("QSet2")
+ << Data("#include <QSet>\n"
+ "#include <QString>\n",
+ "QSet<QString> s;\n"
+ "s.insert(\"11.0\");\n"
+ "s.insert(\"22.0\");\n")
+ % Check("s", "<2 items>", "@QSet<@QString>")
+ % Check("s.0", "[0]", "\"11.0\"", "@QString")
+ % Check("s.1", "[1]", "\"22.0\"", "@QString");
+
+ QTest::newRow("QSet3")
+ << Data("#include <QObject>\n"
+ "#include <QPointer>\n"
+ "#include <QSet>\n",
+ "QObject ob;\n"
+ "QSet<QPointer<QObject> > s;\n"
+ "QPointer<QObject> ptr(&ob);\n"
+ "s.insert(ptr);\n"
+ "s.insert(ptr);\n"
+ "s.insert(ptr);\n")
+ % Check("s", "<1 items>", "@QSet<@QPointer<@QObject>>")
+ % Check("s.0", "[0]", "", "@QPointer<@QObject>");
+
+
+ QByteArray sharedData =
+ " class EmployeeData : public QSharedData\n"
+ " {\n"
+ " public:\n"
+ " EmployeeData() : id(-1) { name.clear(); }\n"
+ " EmployeeData(const EmployeeData &other)\n"
+ " : QSharedData(other), id(other.id), name(other.name) { }\n"
+ " ~EmployeeData() { }\n"
+ "\n"
+ " int id;\n"
+ " QString name;\n"
+ " };\n"
+ "\n"
+ " class Employee\n"
+ " {\n"
+ " public:\n"
+ " Employee() { d = new EmployeeData; }\n"
+ " Employee(int id, QString name) {\n"
+ " d = new EmployeeData;\n"
+ " setId(id);\n"
+ " setName(name);\n"
+ " }\n"
+ " Employee(const Employee &other)\n"
+ " : d (other.d)\n"
+ " {\n"
+ " }\n"
+ " void setId(int id) { d->id = id; }\n"
+ " void setName(QString name) { d->name = name; }\n"
+ "\n"
+ " int id() const { return d->id; }\n"
+ " QString name() const { return d->name; }\n"
+ "\n"
+ " private:\n"
+ " QSharedDataPointer<EmployeeData> d;\n"
+ " };\n";
+
+
+ QTest::newRow("QSharedPointer1")
+ << Data("#include <QSharedPointer>\n",
+ "QSharedPointer<int> ptr2 = ptr;\n"
+ "QSharedPointer<int> ptr3 = ptr;\n");
+
+ QTest::newRow("QSharedPointer2")
+ << Data("#include <QSharedPointer>\n",
+ "QSharedPointer<QString> ptr(new QString(\"hallo\"));\n"
+ "QSharedPointer<QString> ptr2 = ptr;\n"
+ "QSharedPointer<QString> ptr3 = ptr;\n");
+
+ QTest::newRow("QSharedPointer3")
+ << Data("#include <QSharedPointer>\n",
+ "QSharedPointer<int> iptr(new int(43));\n"
+ "QWeakPointer<int> ptr(iptr);\n"
+ "QWeakPointer<int> ptr2 = ptr;\n"
+ "QWeakPointer<int> ptr3 = ptr;\n");
+
+ QTest::newRow("QSharedPointer4")
+ << Data("#include <QSharedPointer>\n"
+ "#include <QString>\n",
+ "QSharedPointer<QString> sptr(new QString(\"hallo\"));\n"
+ "QWeakPointer<QString> ptr(sptr);\n"
+ "QWeakPointer<QString> ptr2 = ptr;\n"
+ "QWeakPointer<QString> ptr3 = ptr;\n");
+
+ QTest::newRow("QSharedPointer5")
+ << Data("#include <QSharedPointer>\n" + fooData,
+ "QSharedPointer<Foo> fptr(new Foo(1));\n"
+ "QWeakPointer<Foo> ptr(fptr);\n"
+ "QWeakPointer<Foo> ptr2 = ptr;\n"
+ "QWeakPointer<Foo> ptr3 = ptr;\n");
+
+ QTest::newRow("QXmlAttributes")
+ << Data("#include <QXmlAttributes>\n",
+ "QXmlAttributes atts;\n"
+ "atts.append(\"name1\", \"uri1\", \"localPart1\", \"value1\");\n"
+ "atts.append(\"name2\", \"uri2\", \"localPart2\", \"value2\");\n"
+ "atts.append(\"name3\", \"uri3\", \"localPart3\", \"value3\");\n")
+ % Check("atts", "", "QXmlAttributes")
+ % CheckType("atts.[vptr]", "")
+ % Check("atts.attList", "<3 items>", "@QXmlAttributes::AttributeList")
+ % Check("atts.attList.0", "[0]", "", "QXmlAttributes::Attribute")
+ % Check("atts.attList.0.localname", "\"localPart1\"", "@QString")
+ % Check("atts.attList.0.qname", "\"name1\"", "@QString")
+ % Check("atts.attList.0.uri", "\"uri1\"", "@QString")
+ % Check("atts.attList.0.value", "\"value1\"", "@QString")
+ % Check("atts.attList.1", "[1]", "", "@QXmlAttributes::Attribute")
+ % Check("atts.attList.1.localname", "\"localPart2\"", "@QString")
+ % Check("atts.attList.1.qname", "\"name2\"", "@QString")
+ % Check("atts.attList.1.uri", "\"uri2\"", "@QString")
+ % Check("atts.attList.1.value", "\"value2\"", "@QString")
+ % Check("atts.attList.2", "[2]", "", "@QXmlAttributes::Attribute")
+ % Check("atts.attList.2.localname", "\"localPart3\"", "@QString")
+ % Check("atts.attList.2.qname", "\"name3\"", "@QString")
+ % Check("atts.attList.2.uri", "\"uri3\"", "@QString")
+ % Check("atts.attList.2.value", "\"value3\"", "@QString")
+ % Check("atts.d", "", "@QXmlAttributesPrivate");
+
+ QTest::newRow("StdArray")
+ << Data("#include <memory>\n"
+ "#include <QString>\n",
+ "std::array<int, 4> a = { { 1, 2, 3, 4} };\n"
+ "std::array<QString, 4> b = { { \"1\", \"2\", \"3\", \"4\"} };\n")
+ % Check("a", "<4 items>", "std::array<int, 4u>")
+ % Check("a", "<4 items>", "std::array<QString, 4u>");
+
+ QTest::newRow("StdComplex")
+ << Data("#include <complex>\n",
+ "std::complex<double> c(1, 2);\n")
+ % Check("c", "(1.000000, 2.000000)", "std::complex<double>");
+
+ QTest::newRow("CComplex")
+ << Data("#include <complex.h>\n",
+ "// Doesn't work when compiled as C++.\n"
+ "double complex a = 0;\n"
+ "double _Complex b = 0;\n"
+ "dummyStatement(&a, &b);\n")
+ % ForceC()
+ % Check("a", "0 + 0 * I", "complex double")
+ % Check("b", "0 + 0 * I", "complex double");
+
+ QTest::newRow("StdDequeInt")
+ << Data("#include <deque>\n",
+ "std::deque<int> deque;\n"
+ "deque.push_back(1);\n"
+ "deque.push_back(2);\n")
+ % Check("deque", "<2 items>", Deque("int"))
+ % Check("deque.0", "[0]", "1", "int")
+ % Check("deque.1", "[1]", "2", "int");
+
+ QTest::newRow("StdDequeIntStar")
+ << Data("#include <deque>\n",
+ "std::deque<int *> deque;\n"
+ "deque.push_back(new int(1));\n"
+ "deque.push_back(0);\n"
+ "deque.push_back(new int(2));\n"
+ "deque.push_back(new int(3));\n"
+ "deque.pop_back();\n"
+ "deque.pop_front();\n")
+ % Check("deque", "<2 items>", Deque("int *"))
+ % Check("deque.0", "[0]", "0x0", "int *")
+ % Check("deque.1", "[1]", "2", "int");
+
+ QTest::newRow("StdDequeFoo")
+ << Data("#include <deque>\n" + fooData,
+ "std::deque<Foo> deque;\n"
+ "deque.push_back(1);\n"
+ "deque.push_front(2);\n")
+ % Check("deque", "<2 items>", Deque("Foo"))
+ % Check("deque.0", "[0]", "", "Foo")
+ % Check("deque.0.a", "2", "int")
+ % Check("deque.1", "[1]", "", "Foo")
+ % Check("deque.1.a", "1", "int");
+
+ QTest::newRow("StdDequeFooStar")
+ << Data("#include <deque>\n" + fooData,
+ "std::deque<Foo *> deque;\n"
+ "deque.push_back(new Foo(1));\n"
+ "deque.push_back(new Foo(2));\n")
+ % Check("deque", "<2 items>", Deque("Foo*"))
+ % Check("deque.0", "[0]", "", "Foo")
+ % Check("deque.0.a", "1", "int")
+ % Check("deque.1", "[1]", "", "Foo")
+ % Check("deque.1.a", "2", "int");
+
+ QTest::newRow("StdHashSet")
+ << Data("#include <hash_set>\n"
+ "using namespace __gnu_cxx;\n",
+ "hash_set<int> h;\n"
+ "h.insert(1);\n"
+ "h.insert(194);\n"
+ "h.insert(2);\n"
+ "h.insert(3);\n")
+ % Check("h", "<4 items>", "__gnu__cxx::hash_set<int>")
+ % Check("h.0", "194", "int")
+ % Check("h.1", "1", "int")
+ % Check("h.2", "2", "int")
+ % Check("h.3", "3", "int");
+
+ QTest::newRow("StdListInt")
+ << Data("#include <list>\n",
+ "std::list<int> list;\n"
+ "list.push_back(1);\n"
+ "list.push_back(2);\n")
+ % Check("list", "<2 items>", "std::list<int>")
+ % Check("list.0", "[0]", "1", "int")
+ % Check("list.1", "[1]", "2", "int");
+
+ QTest::newRow("StdListIntStar")
+ << Data("#include <list>\n",
+ "std::list<int *> list;\n"
+ "list.push_back(new int(1));\n"
+ "list.push_back(0);\n"
+ "list.push_back(new int(2));\n")
+ % Check("list", "<3 items>", "std::list<int*>")
+ % Check("list.0", "[0]", "", "int")
+ % Check("list.1", "[1]", "0x0", "int *")
+ % Check("list.2", "[2]", "", "int");
+
+ QTest::newRow("StdListIntBig")
+ << Data("#include <list>\n",
+ "std::list<int> list;\n"
+ "for (int i = 0; i < 10000; ++i)\n"
+ " list.push_back(i);\n")
+ % Check("list", "<more than 1000 items>", "std::list<int>")
+ % Check("list.0", "[0]", "0", "int")
+ % Check("list.999", "[999]", "999", "int");
+
+ QTest::newRow("StdListFoo")
+ << Data("#include <list>\n",
+ "std::list<Foo> list;\n"
+ "list.push_back(15);\n"
+ "list.push_back(16);\n")
+ % Check("list", "<2 items>", "std::list<Foo>")
+ % Check("list.0", "[0]", "", "Foo")
+ % Check("list.0.a", "15", "int")
+ % Check("list.1", "[1]", "", "Foo")
+ % Check("list.1.a", "16", "int");
+
+ QTest::newRow("StdListFooStar")
+ << Data("#include <list>\n",
+ "std::list<Foo *> list;\n"
+ "list.push_back(new Foo(1));\n"
+ "list.push_back(0);\n"
+ "list.push_back(new Foo(2));\n")
+ % Check("list", "<3 items>", "std::list<Foo*>")
+ % Check("list.0", "[0]", "", "Foo")
+ % Check("list.0.a", "1", "int")
+ % Check("list.1", "0x0", "Foo *")
+ % Check("list.2", "[2]", "", "Foo")
+ % Check("list.2.a", "2", "int");
+
+ QTest::newRow("StdListBool")
+ << Data("#include <list>\n",
+ "std::list<bool> list;\n"
+ "list.push_back(true);\n"
+ "list.push_back(false);\n")
+ % Check("list", "<2 items>", "std::list<bool>")
+ % Check("list.0", "[0]", "true", "bool")
+ % Check("list.1", "[1]", "false", "bool");
+
+ QTest::newRow("StdMapStringFoo")
+ << Data("#include <map>\n"
+ "#include <QString>\n",
+ "std::map<QString, Foo> map;\n"
+ "map[\"22.0\"] = Foo(22);\n"
+ "map[\"33.0\"] = Foo(33);\n"
+ "map[\"44.0\"] = Foo(44);\n")
+ % Check("map", "<3 items>", "std::map<@QString, Foo>")
+ % Check("map.0", "[0]", "", "std::pair<@QString const, Foo>")
+ % Check("map.0.first", "\"22.0\"", "@QString")
+ % Check("map.0.second", "", "Foo")
+ % Check("map.0.second.a", "22", "int")
+ % Check("map.1", "[1]", "", "std::pair<@QString const, Foo>")
+ % Check("map.2.first", "\"44.0\"", "@QString")
+ % Check("map.2.second", "", "Foo")
+ % Check("map.2.second.a", "44", "int");
+
+ QTest::newRow("StdMapCharStarFoo")
+ << Data("#include <map>\n" + fooData,
+ "std::map<const char *, Foo> map;\n"
+ "map[\"22.0\"] = Foo(22);\n"
+ "map[\"33.0\"] = Foo(33);\n")
+ % Check("map", "<2 items>", "std::map<char const*, Foo>")
+ % Check("map.0", "[0]", "", "std::pair<char const* const, Foo>")
+ % CheckType("map.0.first", "char *")
+ % Check("map.0.first.*first", "50 '2'", "char")
+ % Check("map.0.second", "", "Foo")
+ % Check("map.0.second.a", "22", "int")
+ % Check("map.1", "[1]", "", "std::pair<char const* const, Foo>")
+ % CheckType("map.1.first", "char *")
+ % Check("map.1.first.*first", "51 '3'", "char")
+ % Check("map.1.second", "", "Foo")
+ % Check("map.1.second.a", "33", "int");
+
+ QTest::newRow("StdMapUIntUInt")
+ << Data("#include <map>\n",
+ "std::map<uint, uint> map;\n"
+ "map[11] = 1;\n"
+ "map[22] = 2;\n")
+ % Check("map", "<2 items>", "std::map<unsigned int, unsigned int>")
+ % Check("map.11", "[11]", "1", "unsigned int")
+ % Check("map.22", "[22]", "2", "unsigned int");
+
+ QTest::newRow("StdMapUIntStringList")
+ << Data("#include <map>\n"
+ "#include <QStringList>\n",
+ "std::map<uint, QStringList> map;\n"
+ "map[11] = QStringList() << \"11\";\n"
+ "map[22] = QStringList() << \"22\";\n")
+ % Check("map", "<2 items>", "std::map<unsigned int, @QStringList>")
+ % Check("map.0", "", "std::pair<unsigned int const, @QStringList>")
+ % Check("map.0.first", "11", "unsigned int")
+ % Check("map.0.second", "<1 items>", "@QStringList")
+ % Check("map.0.second.0", "\"11\"", "@QString")
+ % Check("map.1", "", "std::pair<unsigned int const, @QStringList>")
+ % Check("map.1.first", "22", "unsigned int")
+ % Check("map.1.second", "<1 items>", "@QStringList")
+ % Check("map.1.second.0", "\"22\"", "@QString");
+
+ QTest::newRow("StdMapUIntStringListTypedef")
+ << Data("#include <map>\n",
+ "typedef std::map<uint, QStringList> T;\n"
+ "T map;\n"
+ "map[11] = QStringList() << \"11\";\n"
+ "map[22] = QStringList() << \"22\";\n");
+
+ QTest::newRow("StdMapUIntFloat")
+ << Data("#include <map>\n",
+ "std::map<uint, float> map;\n"
+ "map[11] = 11.0;\n"
+ "map[22] = 22.0;\n")
+ % Check("map", "<2 items>", "std::map<unsigned int, float>")
+ % Check("map.11", "[11]", "11", "float")
+ % Check("map.22", "[22]", "22", "float");
+
+ QTest::newRow("StdMapUIntFloatIterator")
+ << Data("#include <map>\n",
+ "typedef std::map<int, float> Map;\n"
+ "Map map;\n"
+ "map[11] = 11.0;\n"
+ "map[22] = 22.0;\n"
+ "map[33] = 33.0;\n"
+ "map[44] = 44.0;\n"
+ "map[55] = 55.0;\n"
+ "map[66] = 66.0;\n"
+ "Map::iterator it1 = map.begin();\n"
+ "Map::iterator it2 = it1; ++it2;\n"
+ "Map::iterator it3 = it2; ++it3;\n"
+ "Map::iterator it4 = it3; ++it4;\n"
+ "Map::iterator it5 = it4; ++it5;\n"
+ "Map::iterator it6 = it5; ++it6;\n")
+ % Check("map", "<6 items>", "Map")
+ % Check("map.11", "[11]", "11", "float")
+ % Check("it1.first", "11", "int")
+ % Check("it1.second", "11", "float")
+ % Check("it6.first", "66", "int")
+ % Check("it6.second", "66", "float");
+
+ QTest::newRow("StdMapStringFloat")
+ << Data("#include <map>\n",
+ "std::map<QString, float> map;\n"
+ "map[\"11.0\"] = 11.0;\n"
+ "map[\"22.0\"] = 22.0;\n")
+ % Check("map", "<2 items>", "std::map<@QString, float>")
+ % Check("map.0", "[0]", "", "std::pair<@QString const, float>")
+ % Check("map.0.first", "\"11.0\"", "@QString")
+ % Check("map.0.second", "11", "float")
+ % Check("map.1", "[1]", "", "std::pair<@QString const, float>")
+ % Check("map.1.first", "\"22.0\"", "@QString")
+ % Check("map.1.second", "22", "float");
+
+ QTest::newRow("StdMapIntString")
+ << Data("#include <map>\n"
+ "#include <QString>\n",
+ "std::map<int, QString> map;\n"
+ "map[11] = \"11.0\";\n"
+ "map[22] = \"22.0\";\n")
+ % Check("map", "<2 items>", "std::map<int, @QString>")
+ % Check("map.0", "[0]", "", "std::pair<int const, @QString>")
+ % Check("map.0.first", "11", "int")
+ % Check("map.0.second", "\"11.0\"", "@QString")
+ % Check("map.1", "[1]", "", "std::pair<int const, @QString>")
+ % Check("map.1.first", "22", "int")
+ % Check("map.1.second", "\"22.0\"", "@QString");
+
+ QTest::newRow("StdMapStringPointer")
+ << Data("#include <QPointer>\n"
+ "#include <QObject>\n"
+ "#include <QString>\n"
+ "#include <map>\n",
+ "QObject ob;\n"
+ "std::map<QString, QPointer<QObject> > map;\n"
+ "map[\"Hallo\"] = QPointer<QObject>(&ob);\n"
+ "map[\"Welt\"] = QPointer<QObject>(&ob);\n"
+ "map[\".\"] = QPointer<QObject>(&ob);\n")
+ % Check("map", "<3 items>", "std::map<@QString, @QPointer<@QObject>>")
+ % Check("map.0", "[0]", "", "std::pair<@QString const, @QPointer<@QObject>>")
+ % Check("map.0.first", "", "@QString")
+ % Check("map.0.second", "", "@QPointer<@QObject>")
+ % Check("map.2", "[2]", "", "std::pair<@QString const, @QPointer<@QObject>>")
+ % Check("map.2.first", "\"Welt\"", "@QString");
+
+ QTest::newRow("StdUniquePtr")
+ << Data("#include <memory>\n" + fooData,
+ "std::unique_ptr<int> pi(new int(32));\n"
+ "std::unique_ptr<Foo> pf(new Foo);\n")
+ % Cxx11Profile()
+ % Check("pi", Pointer("32"), "std::unique_ptr<int, std::default_delete<int> >")
+ % Check("pf", Pointer(), "std::unique_ptr<Foo, std::default_delete<Foo> >");
+
+ QTest::newRow("StdSharedPtr")
+ << Data("#include <memory>\n" + fooData,
+ "std::shared_ptr<int> pi(new int(32));\n"
+ "std::shared_ptr<Foo> pf(new Foo);\n")
+ % Cxx11Profile()
+ % Check("pi", Pointer("32"), "std::shared_ptr<int, std::default_delete<int> >")
+ % Check("pf", Pointer(), "std::shared_ptr<Foo, std::default_delete<int> >");
+
+ QTest::newRow("StdSetInt")
+ << Data("#include <set>\n",
+ "std::set<int> set;\n"
+ "set.insert(11);\n"
+ "set.insert(22);\n"
+ "set.insert(33);\n")
+ % Check("set", "<3 items>", "std::set<int>");
+
+ QTest::newRow("StdSetIntIterator")
+ << Data("#include <set>\n",
+ "typedef std::set<int> Set;\n"
+ "Set set;\n"
+ "set.insert(11.0);\n"
+ "set.insert(22.0);\n"
+ "set.insert(33.0);\n"
+ "set.insert(44.0);\n"
+ "set.insert(55.0);\n"
+ "set.insert(66.0);\n"
+ "Set::iterator it1 = set.begin();\n"
+ "Set::iterator it2 = it1; ++it2;\n"
+ "Set::iterator it3 = it2; ++it3;\n"
+ "Set::iterator it4 = it3; ++it4;\n"
+ "Set::iterator it5 = it4; ++it5;\n"
+ "Set::iterator it6 = it5; ++it6;\n")
+ % Check("set", "<6 items>", "Set")
+ % Check("it1.value", "11", "int")
+ % Check("it6.value", "66", "int");
+
+ QTest::newRow("StdSetString")
+ << Data("#include <set>\n"
+ "#include <QString>\n",
+ "std::set<QString> set;\n"
+ "set.insert(\"22.0\");\n")
+ % Check("set", "<1 items>", "std::set<Q@String>")
+ % Check("set.0", "[0]", "\"22.0\"", "@QString");
+
+ QTest::newRow("StdSetPointer")
+ << Data("#include <set>\n",
+ "#include <QPointer>\n"
+ "#include <QObject>\n"
+ "QObject ob;\n"
+ "std::set<QPointer<QObject> > hash;\n"
+ "QPointer<QObject> ptr(&ob);\n")
+ % Check("hash", "<0 items>", "std::set<@QPointer<@QObject>, std::less<@QPointer<@QObject>>, std::allocator<@QPointer<@QObject>>>")
+ % Check("ob", "\"\"", "@QObject")
+ % Check("ptr", "", "@QPointer<@QObject>");
+
+ QTest::newRow("StdStack1")
+ << Data("#include <stack>\n",
+ "std::stack<int *> s0, s;\n"
+ "s.push(new int(1));\n"
+ "s.push(0);\n"
+ "s.push(new int(2));\n")
+ % Check("s0", "<0 items>", "std::stack<int*>")
+ % Check("s", "<3 items>", "std::stack<int*>")
+ % Check("s.0", "[0]", "", "int")
+ % Check("s.1", "[1]", "0x0", "int *")
+ % Check("s.2", "[2]", "", "int");
+
+ QTest::newRow("StdStack2")
+ << Data("#include <stack>\n",
+ "std::stack<int> s0, s;\n"
+ "s.push(1);\n"
+ "s.push(2);\n")
+ % Check("s0", "<0 items>", "std::stack<int>")
+ % Check("s", "<2 items>", "std::stack<int>")
+ % Check("s.0", "1", "int")
+ % Check("s.1", "2", "int");
+
+ QTest::newRow("StdStack3")
+ << Data("#include <stack>\n",
+ "std::stack<Foo *> s, s0;\n"
+ "s.push(new Foo(1));\n"
+ "s.push(new Foo(2));\n")
+ % Check("s", "<2 items>", "std::stack<Foo*>")
+ % Check("s.0", "[0]", "", "Foo")
+ % Check("s.0.a", "1", "int")
+ % Check("s.1", "[1]", "", "Foo")
+ % Check("s.1.a", "2", "int");
+
+ QTest::newRow("StdStack4")
+ << Data("#include <stack>\n",
+ "std::stack<Foo> s0, s;\n"
+ "s.push(1);\n"
+ "s.push(2);\n")
+ % Check("s0", "<0 items>", "std::stack<Foo>")
+ % Check("s", "<2 items>", "std::stack<Foo>")
+ % Check("s.0", "[0]", "", "Foo")
+ % Check("s.0.a", "1", "int")
+ % Check("s.1", "[1]", "", "Foo")
+ % Check("s.1.a", "2", "int");
+
+ QTest::newRow("StdString1")
+ << Data("#include <string>\n",
+ "std::string str0, str;\n"
+ "std::wstring wstr0, wstr;\n"
+ "str += \"b\";\n"
+ "wstr += wchar_t('e');\n"
+ "str += \"d\";\n"
+ "wstr += wchar_t('e');\n"
+ "str += \"e\";\n"
+ "str += \"b\";\n"
+ "str += \"d\";\n"
+ "str += \"e\";\n"
+ "wstr += wchar_t('e');\n"
+ "wstr += wchar_t('e');\n"
+ "str += \"e\";\n")
+ % Check("str0", "\"\"", "std::string")
+ % Check("wstr0", "\"\"", "std::wstring")
+ % Check("str", "\"bdebdee\"", "std::string")
+ % Check("wstr", "\"eeee\"", "std::wstring");
+
+ QTest::newRow("StdString2")
+ << Data("#include <string>\n"
+ "#include <vector>\n"
+ "#include <QList>\n",
+ "std::string str = \"foo\";\n"
+ "std::vector<std::string> v;\n"
+ "QList<std::string> l0, l;\n"
+ "v.push_back(str);\n"
+ "v.push_back(str);\n"
+ "l.push_back(str);\n"
+ "l.push_back(str);\n")
+ % Check("l0", "<0 items>", "@QList<std::string>")
+ % Check("l", "<2 items>", "@QList<std::string>")
+ % Check("str", "\"foo\"", "std::string")
+ % Check("v", "<2 items>", "std::vector<std::string>")
+ % Check("v.0", "[0]", "\"foo\"", "std::string");
+
+ QTest::newRow("StdVector1")
+ << Data("#include <vector>\n",
+ "std::vector<int *> v0, v;\n"
+ "v.push_back(new int(1));\n"
+ "v.push_back(0);\n"
+ "v.push_back(new int(2));\n")
+ % Check("v0", "<0 items>", "std::vector<int*>")
+ % Check("v", "<3 items>", "std::vector<int*>")
+ % Check("v.0", "[1]", "1", "int")
+ % Check("v.1", "0x0", "int *")
+ % Check("v.2", "[2]", "2", "int");
+
+ QTest::newRow("StdVector2")
+ << Data("#include <vector>\n",
+ "std::vector<int> v;\n"
+ "v.push_back(1);\n"
+ "v.push_back(2);\n"
+ "v.push_back(3);\n"
+ "v.push_back(4);\n")
+ % Check("v", "<4 items>", "std::vector<int>")
+ % Check("v.0", "[0]", "1", "int")
+ % Check("v.3", "[3]", "4", "int");
+
+ QTest::newRow("StdVector3")
+ << Data("#include <vector>\n",
+ "std::vector<Foo *> v;\n"
+ "v.push_back(new Foo(1));\n"
+ "v.push_back(0);\n"
+ "v.push_back(new Foo(2));\n")
+ % Check("v", "<3 items>", "std::vector<Foo*>")
+ % Check("v.0", "[0]", "", "Foo")
+ % Check("v.0.a", "1", "int")
+ % Check("v.1", "[1]", "0x0", "Foo *")
+ % Check("v.2", "[2]", "", "Foo")
+ % Check("v.2.a", "2", "int");
+
+ QTest::newRow("StdVector4")
+ << Data("#include <vector>\n",
+ "std::vector<Foo> v;\n"
+ "v.push_back(1);\n"
+ "v.push_back(2);\n"
+ "v.push_back(3);\n"
+ "v.push_back(4);\n")
+ % Check("v", "<4 items>", "std::vector<Foo>")
+ % Check("v.0", "[0]", "", "Foo")
+ % Check("v.1.a", "2", "int")
+ % Check("v.3", "[3]", "", "Foo");
+
+ QTest::newRow("StdVectorBool1")
+ << Data("#include <vector>\n",
+ "std::vector<bool> v;\n"
+ "v.push_back(true);\n"
+ "v.push_back(false);\n"
+ "v.push_back(false);\n"
+ "v.push_back(true);\n"
+ "v.push_back(false);\n")
+ % Check("v", "<5 items>", "std::vector<bool>")
+ % Check("v.0", "[0]", "true", "bool")
+ % Check("v.1", "[1]", "false", "bool")
+ % Check("v.2", "[2]", "false", "bool")
+ % Check("v.3", "[3]", "true", "bool")
+ % Check("v.4", "[4]", "false", "bool");
+
+ QTest::newRow("StdVectorBool2")
+ << Data("#include <vector>\n",
+ "std::vector<bool> v1(65, true);\n"
+ "std::vector<bool> v2(65);\n")
+ % Check("v1", "<65 items>", "std::vector<bool>")
+ % Check("v1.0", "[0]", "true", "bool")
+ % Check("v1.64", "[64]", "true", "bool")
+ % Check("v2", "<65 items>", "std::vector<bool>")
+ % Check("v2.0", "[0]", "false", "bool")
+ % Check("v2.64", "[64]", "false", "bool");
+
+ QTest::newRow("StdVector6")
+ << Data("#include <vector>\n"
+ "#include <list>\n",
+ "std::vector<std::list<int> *> vector;\n"
+ "std::list<int> list;\n"
+ "vector.push_back(new std::list<int>(list));\n"
+ "vector.push_back(0);\n"
+ "list.push_back(45);\n"
+ "vector.push_back(new std::list<int>(list));\n"
+ "vector.push_back(0);\n")
+ % Check("list", "<1 items>", "std::list<int>")
+ % Check("list.0", "[0]", "45", "int")
+ % Check("vector", "<4 items>", "std::vector<std::list<int>*>")
+ % Check("vector.0", "[0]", "<0 items>", "std::list<int>")
+ % Check("vector.2", "[2]", "<1 items>", "std::list<int>")
+ % Check("vector.2.0", "45", "int")
+ % Check("vector.3", "[3]", "0x0", "std::list<int> *");
+
+ QTest::newRow("StdStream")
+ << Data("#include <ifstream>\n",
+ "using namespace std;\n"
+ "ifstream is0, is;\n"
+ "#ifdef Q_OS_WIN\n"
+ " is.open(\"C:\\\\Program Files\\\\Windows NT\\\\Accessories\\\\wordpad.exe\");\n"
+ "#else\n"
+ " is.open(\"/etc/passwd\");\n"
+ "#endif\n"
+ " bool ok = is.good();\n")
+ % Check("is", "", "std::ifstream")
+ % Check("ok", "true", "bool");
+
+ QTest::newRow("ItemModel")
+ << Data("#include <QStandardItemModel>\n",
+ "QStandardItemModel m;\n"
+ "QStandardItem *i1, *i2, *i11;\n"
+ "m.appendRow(QList<QStandardItem *>()\n"
+ " << (i1 = new QStandardItem(\"1\")) << (new QStandardItem(\"a\")) << (new QStandardItem(\"a2\")));\n"
+ "QModelIndex mi = i1->index();\n"
+ "m.appendRow(QList<QStandardItem *>()\n"
+ " << (i2 = new QStandardItem(\"2\")) << (new QStandardItem(\"b\")));\n"
+ "i1->appendRow(QList<QStandardItem *>()\n"
+ " << (i11 = new QStandardItem(\"11\")) << (new QStandardItem(\"aa\")));\n")
+ % Check("i1", "", "@QStandardItem")
+ % Check("i11", "", "@QStandardItem")
+ % Check("i2", "", "@QStandardItem")
+ % Check("m", "", "@QStandardItemModel")
+ % Check("mi", "\"1\"", "@QModelIndex");
+
+ QTest::newRow("QStackInt")
+ << Data("#include <QStack>",
+ "QStack<int> s;\n"
+ "s.append(1);\n"
+ "s.append(2);\n")
+ % Check("s", "<2 items>", "@QStack<int>")
+ % Check("s.0", "[0]", "1", "int")
+ % Check("s.1", "[1]", "2", "int");
+
+ QTest::newRow("QStackBig")
+ << Data("#include <QStack>",
+ "QStack<int> s;\n"
+ "for (int i = 0; i != 10000; ++i)\n"
+ " s.append(i);\n")
+ % Check("s", "<10000 items>", "@QStack<int>")
+ % Check("s.0", "[0]", "0", "int")
+ % Check("s.1999", "[1999]", "1999", "int");
+
+ QTest::newRow("QStackFooPointer")
+ << Data("#include <QStack>",
+ "QStack<Foo *> s;\n"
+ "s.append(new Foo(1));\n"
+ "s.append(0);\n"
+ "s.append(new Foo(2));\n")
+ % Check("s", "<3 items>", "@QStack<Foo*>")
+ % Check("s.0", "[0]", "", "Foo")
+ % Check("s.0.a", "1", "int")
+ % Check("s.1", "[1]", "0x0", "Foo *")
+ % Check("s.2", "[2]", "", "Foo")
+ % Check("s.2.a", "2", "int");
+
+ QTest::newRow("QStackFoo")
+ << Data("#include <QStack>" + fooData,
+ "QStack<Foo> s;\n"
+ "s.append(1);\n"
+ "s.append(2);\n"
+ "s.append(3);\n"
+ "s.append(4);\n")
+ % Check("s", "<4 items>", "@QStack<Foo>")
+ % Check("s.0", "[0]", "", "Foo")
+ % Check("s.0.a", "1", "int")
+ % Check("s.3", "[3]", "", "Foo")
+ % Check("s.3.a", "4", "int");
+
+ QTest::newRow("QStackBool")
+ << Data("#include <QStack>",
+ "QStack<bool> s;\n"
+ "s.append(true);\n"
+ "s.append(false);\n")
+ % Check("s", "<2 items>", "@QStack<bool>")
+ % Check("s.0", "true", "bool")
+ % Check("s.1", "false", "bool");
+
+ QTest::newRow("QUrl")
+ << Data("#include <QUrl>",
+ "QUrl url(QString(\"http://qt-project.org\"));\n")
+ % Check("url", "\"http://qt-project.org\"", "@QUrl");
+
+ QTest::newRow("QStringQuotes")
+ << Data("QString str1(\"Hello Qt\");\n"
+ // --> Value: \"Hello Qt\"
+ "QString str2(\"Hello\\nQt\");\n"
+ // --> Value: \\"\"Hello\nQt"" (double quote not expected)
+ "QString str3(\"Hello\\rQt\");\n"
+ // --> Value: ""HelloQt"" (double quote and missing \r not expected)
+ "QString str4(\"Hello\\tQt\");\n")
+ // --> Value: "Hello\9Qt" (expected \t instead of \9)
+ % Check("str1", "\"Hello Qt\"", "@QString")
+ % Check("str2", "\"Hello\nQt\"", "@QString")
+ % Check("str3", "\"Hello\rQt\"", "@QString")
+ % Check("str4", "\"Hello\tQt\"", "@QString");
+
+ QByteArray stringData = "QString str = \"Hello \";\n"
+ "str += '\\t';\n"
+ "str += '\\r';\n"
+ "str += '\\n';\n"
+ "str += QLatin1Char(0);\n"
+ "str += QLatin1Char(1);\n"
+ "str += \" World\";\n"
+ "str.prepend(\"Prefix: \");\n";
+
+ QTest::newRow("QString1")
+ << Data(stringData)
+ % Check("str", "\"Prefix: Hello big, \\t\\r\\n\\000\\001 World\"", "@QString");
+
+ QTest::newRow("QString2")
+ << Data("QChar data[] = { 'H', 'e', 'l', 'l', 'o' };\n"
+ "QString str1 = QString::fromRawData(data, 4);\n"
+ "QString str2 = QString::fromRawData(data + 1, 4);\n")
+ % Check("str1", "\"Hell\"", "@QString")
+ % Check("str2", "\"ello\"", "@QString");
+
+ QTest::newRow("QString3")
+ << Data("#include <QString>\n"
+ "void stringRefTest(const QString &refstring) { stopper(); }\n",
+ "stringRefTest(QString(\"Ref String Test\"));\n")
+ % Check("refstring", "\"Ref String Test\"", "@QString &");
+
+ QTest::newRow("QString4")
+ << Data("#include <QString>\n"
+ "QString str = \"Hello \";\n"
+ "QString string(\"String Test\");\n"
+ "QString *pstring = new QString(\"Pointer String Test\");\n"
+ "dummyStatement(&str, &string, &pstring);\n")
+ % Check("pstring", "\"Pointer String Test\"", "@QString")
+ % Check("str", "\"Hello \"", "@QString")
+ % Check("string", "\"String Test\"", "@QString");
+
+ QTest::newRow("QStringRef1")
+ << Data("#include <QStringRef>\n",
+ "QString str = \"Hello\";\n"
+ "QStringRef ref(&str, 1, 2);")
+ % Check("ref", "\"el\"", "@QStringRef");
+
+ QTest::newRow("QStringList")
+ << Data("#include <QStringList>\n",
+ "QStringList l;\n"
+ "l << \"Hello \";\n"
+ "l << \" big, \";\n"
+ "l.takeFirst();\n"
+ "l << \" World \";\n")
+ % Check("l", "<2 items>", "@QStringList")
+ % Check("l.0", "\" big, \"", "@QString")
+ % Check("l.1", "\" World \"", "@QString");
+
+ QTest::newRow("String")
+ << Data("#include <QString>",
+ "const wchar_t *w = L\"aöa\";\n"
+ "QString u;\n"
+ "if (sizeof(wchar_t) == 4)\n"
+ " u = QString::fromUcs4((uint *)w);\n"
+ "else\n"
+ " u = QString::fromUtf16((ushort *)w);\n")
+ % Check("u", "\"aöa\"", "@QString")
+ % CheckType("w", "", "wchar_t *");
+
+ // All: Select UTF-8 in "Change Format for Type" in L&W context menu");
+ // Windows: Select UTF-16 in "Change Format for Type" in L&W context menu");
+ // Other: Select UCS-6 in "Change Format for Type" in L&W context menu");
+
+
+ // These tests should result in properly displayed umlauts in the
+ // Locals&Watchers view. It is only support on gdb with Python");
+ QTest::newRow("CharPointers")
+ << Data("const char *s = \"aöa\";\n"
+ "const char *t = \"a\\xc3\\xb6\";\n"
+ "const unsigned char uu[] = { 'a', 153 /* ö Latin1 */, 'a' };\n"
+ "const unsigned char *u = uu;\n"
+ "const wchar_t *w = L\"aöa\";\n")
+ % CheckType("u", "unsigned char *")
+ % CheckType("uu", "unsigned char [3]")
+ % CheckType("s", "char *")
+ % CheckType("t", "char *")
+ % CheckType("w", "wchar_t *");
+
+ // All: Select UTF-8 in "Change Format for Type" in L&W context menu");
+ // Windows: Select UTF-16 in "Change Format for Type" in L&W context menu");
+ // Other: Select UCS-6 in "Change Format for Type" in L&W context menu");
+
+
+ QTest::newRow("CharArrays")
+ << Data("const char s[] = \"aöa\";\n"
+ "const char t[] = \"aöax\";\n"
+ "const wchar_t w[] = L\"aöa\";\n")
+ % CheckType("s", "char [5]")
+ % CheckType("t", "char [6]")
+ % CheckType("w", "wchar_t [4]");
+
+
+ QTest::newRow("Text")
+ << Data("#include <QApplication>\n"
+ "#include <QTextCursor>\n"
+ "#include <QTextDocument>\n",
+ "QApplication app(arrc, argv)\n"
+ "QTextDocument doc;\n"
+ "doc.setPlainText(\"Hallo\\nWorld\");\n"
+ "QTextCursor tc;\n"
+ "tc = doc.find(\"all\");\n"
+ "int pos = tc.position();\n"
+ "int anc = tc.anchor();\n")
+ % CheckType("doc", "QTextDocument")
+ % Check("tc", "4", "QTextCursor")
+ % Check("pos", "4", "int")
+ % Check("anc", "1", "int");
+
+ QTest::newRow("QThread")
+ << Data("#include <QThread>\n",
+ "const int N = 14;\n"
+ "Thread thread[N];\n"
+ "for (int i = 0; i != N; ++i) {\n"
+ " thread[i].setId(i);\n"
+ " thread[i].setObjectName(\"This is thread #\" + QString::number(i));\n"
+ " thread[i].start();\n"
+ "}\n")
+ % CheckType("thread", "Thread [14]")
+ % Check("thread.0", "", "Thread")
+ % Check("thread.0.@1.@1", "\"This is thread #0\"", "Thread")
+ % Check("thread.13", "", "Thread")
+ % Check("thread.13.@1.@1", "\"This is thread #13\"", "Thread");
+
+ QByteArray variantData =
+ "Q_DECLARE_METATYPE(QHostAddress)\n"
+ "Q_DECLARE_METATYPE(QList<int>)\n"
+ "Q_DECLARE_METATYPE(QStringList)\n"
+ "#define COMMA ,\n"
+ "Q_DECLARE_METATYPE(QMap<uint COMMA QStringList>)\n";
+
+ QTest::newRow("QVariant1")
+ << Data("#include <QVariant>\n",
+ "QVariant value;\n"
+ "QVariant::Type t = QVariant::String;\n"
+ "value = QVariant(t, (void*)0);\n"
+ "*(QString*)value.data() = QString(\"Some string\");\n"
+ "int i = 1;\n")
+ % Check("t", "QVariant::String (10)", "@QVariant::Type")
+ % Check("value", "\"Some string\"", "@QVariant (QString)");
+
+ QTest::newRow("QVariant2")
+ << Data("#include <QVariant>\n" + variantData,
+ "QVariant var; // Type 0, invalid\n"
+ "QVariant var1(true); // 1, bool\n"
+ "QVariant var2(2); // 2, int\n"
+ "QVariant var3(3u); // 3, uint\n"
+ "QVariant var4(qlonglong(4)); // 4, qlonglong\n"
+ "QVariant var5(qulonglong(5)); // 5, qulonglong\n"
+ "QVariant var6(double(6)); // 6, double\n"
+ "QVariant var7(QChar(7)); // 7, QChar\n"
+ //None, # 8, QVariantMap
+ // None, # 9, QVariantList
+ "QVariant var10(QString(\"Hello 10\")); // 10, QString\n"
+ "QVariant var19(QRect(100, 200, 300, 400)); // 19 QRect\n"
+ "QVariant var20(QRectF(100, 200, 300, 400)); // 20 QRectF\n"
+ )
+ % Check("var", "(invalid)", "@QVariant (invalid)")
+ % Check("var1", "true", "@QVariant (bool)")
+ % Check("var2", "2", "@QVariant (int)")
+ % Check("var3", "3", "@QVariant (uint)")
+ % Check("var4", "4", "@QVariant (qlonglong)")
+ % Check("var5", "5", "@QVariant (qulonglong)")
+ % Check("var6", "6", "@QVariant (double)")
+ % Check("var7", "'?' (7)", "@QVariant (QChar)")
+ % Check("var10", "\"Hello 10\"", "@QVariant (QString)")
+ % Check("var19", "300x400+100+200", "@QVariant (QRect)")
+ % Check("var20", "300x400+100+200", "@QVariant (QRectF)");
+
+ /*
+ "QStringList", # 11
+ "QByteArray", # 12
+ "QBitArray", # 13
+ "QDate", # 14
+ "QTime", # 15
+ "QDateTime", # 16
+ "QUrl", # 17
+ "QLocale", # 18
+ "QRect", # 19
+ "QRectF", # 20
+ "QSize", # 21
+ "QSizeF", # 22
+ "QLine", # 23
+ "QLineF", # 24
+ "QPoint", # 25
+ "QPointF", # 26
+ "QRegExp", # 27
+ */
+
+// QTest::newRow("QVariant3")
+// << Data(
+// "QVariant var;\n"
+// % Check("var (invalid) QVariant (invalid)");
+// % Check("the list is updated properly");
+// "var.setValue(QStringList() << "World");\n"
+// % Check("var <1 items> QVariant (QStringList)");
+// % Check("var.0 "World" QString");
+// "var.setValue(QStringList() << "World" << "Hello");\n"
+// % Check("var <2 items> QVariant (QStringList)");
+// % Check("var.1 "Hello" QString");
+// "var.setValue(QStringList() << "Hello" << "Hello");\n"
+// % Check("var <2 items> QVariant (QStringList)");
+// % Check("var.0 "Hello" QString");
+// % Check("var.1 "Hello" QString");
+// "var.setValue(QStringList() << "World" << "Hello" << "Hello");\n"
+// % Check("var <3 items> QVariant (QStringList)");
+// % Check("var.0 "World" QString");
+
+ QTest::newRow("QVariant4")
+ << Data("#include <QHostAddress>\n"
+ "#include <QVariant>\n",
+ "QVariant var;\n"
+ "QHostAddress ha(\"127.0.0.1\");\n"
+ "var.setValue(ha);\n"
+ "QHostAddress ha1 = var.value<QHostAddress>();\n")
+ % Check("ha", "\"127.0.0.1\"", "@QHostAddress")
+ % Check("ha.a", "0", "quint32")
+ % Check("ha.a6", "", "Q_IPV6ADDR")
+ % Check("ha.ipString", "\"127.0.0.1\"", "@QString")
+ % Check("ha.isParsed", "false", "bool")
+ % Check("ha.protocol", "QAbstractSocket::UnknownNetworkLayerProtocol (-1)",
+ "@QAbstractSocket::NetworkLayerProtocol")
+ % Check("ha.scopeId", "", "@QString")
+ % Check("ha1", "\"127.0.0.1\"", "@QHostAddress")
+ % Check("ha1.a", "0", "quint32")
+ % Check("ha1.a6", "", "Q_IPV6ADDR")
+ % Check("ha1.ipString", "\"127.0.0.1\"", "@QString")
+ % Check("ha1.isParsed", "false", "bool")
+ % Check("ha1.protocol", "QAbstractSocket::UnknownNetworkLayerProtocol (-1)",
+ "@QAbstractSocket::NetworkLayerProtocol")
+ % Check("ha1.scopeId", "", "@QString")
+ % CheckType("var", "", "@QVariant (QHostAddress)")
+ % Check("var.data", "\"127.0.0.1\"", "@QHostAddress");
+
+// QTest::newRow("QVariant5")
+// << Data(
+// // This checks user defined types in QVariants");
+// "typedef QMap<uint, QStringList>\n" MyType;
+// "MyType my;\n"
+// "my[1] = (QStringList() << "Hello");\n"
+// "my[3] = (QStringList() << "World");\n"
+// "QVariant var;\n"
+// "var.setValue(my);\n"
+// // FIXME: Known to break\n"
+// //QString type = var.typeName();\n"
+// "var.setValue(my);\n"
+// % Check("my <2 items> qvariant::MyType");
+// % Check("my.0 QMapNode<unsigned int, QStringList>");
+// % Check("my.0.key 1 unsigned int");
+// % Check("my.0.value <1 items> QStringList");
+// % Check("my.0.value.0 "Hello" QString");
+// % Check("my.1 QMapNode<unsigned int, QStringList>");
+// % Check("my.1.key 3 unsigned int");
+// % Check("my.1.value <1 items> QStringList");
+// % Check("my.1.value.0 "World" QString");
+// % CheckType("var QVariant (QMap<unsigned int , QStringList>)");
+// % Check("var.data <2 items> QMap<unsigned int, QStringList>");
+// % Check("var.data.0 QMapNode<unsigned int, QStringList>");
+// % Check("var.data.0.key 1 unsigned int");
+// % Check("var.data.0.value <1 items> QStringList");
+// % Check("var.0.value.0 "Hello" QString");
+// % Check("var.data.1 QMapNode<unsigned int, QStringList>");
+// % Check("var.data.1.key 3 unsigned int");
+// % Check("var.data.1.value <1 items> QStringList");
+// % Check("var.data.1.value.0 "World" QString");
+// // Continue");
+// var.setValue(my);
+
+// QTest::newRow("QVariant6")
+// << Data(
+// "QList<int> list;\n"
+// "list << 1 << 2 << 3;\n"
+// "QVariant variant = qVariantFromValue(list);\n"
+// % Check("list <3 items> QList<int>");
+// % Check("list.0", "1", "int");
+// % Check("list.1", "2", "int");
+// % Check("list.2", "3", "int");
+// % CheckType("variant QVariant (QList<int>)");
+// % Check("variant.data <3 items> QList<int>");
+// % Check("variant.data.0", "1", "int");
+// % Check("variant.data.1", "2", "int");
+// % Check("variant.data.2", "3", "int");
+// // Continue");
+// list.clear();\n"
+// list = variant.value<QList<int> >();\n"
+// % Check("list <3 items> QList<int>");\n"
+// % Check("list.0", "1", "int");
+// % Check("list.1", "2", "int");
+// % Check("list.2", "3", "int");
+
+// QTest::newRow("QVariantList")
+// << Data(
+// "QVariantList vl;\n"
+// " % Check("vl <0 items> QVariantList");\n"
+// "// Continue");\n"
+// "vl.append(QVariant(1));\n"
+// "vl.append(QVariant(2));\n"
+// "vl.append(QVariant("Some String"));\n"
+// "vl.append(QVariant(21));\n"
+// "vl.append(QVariant(22));\n"
+// "vl.append(QVariant("2Some String"));\n"
+// % Check("vl <6 items> QVariantList");
+// % CheckType("vl.0 QVariant (int)");
+// % CheckType("vl.2 QVariant (QString)");
+
+// QTest::newRow("QVariantMap")
+// << Data(
+// "QVariantMap vm;\n"
+// % Check("vm <0 items> QVariantMap");
+// "// Continue");\n"
+// "vm["a"] = QVariant(1);\n"
+// "vm["b"] = QVariant(2);\n"
+// "vm["c"] = QVariant("Some String");\n"
+// "vm["d"] = QVariant(21);\n"
+// "vm["e"] = QVariant(22);\n"
+// "vm["f"] = QVariant("2Some String");\n"
+// % Check("vm <6 items> QVariantMap");
+// % Check("vm.0 QMapNode<QString, QVariant>");
+// % Check("vm.0.key "a" QString");
+// % Check("vm.0.value 1 QVariant (int)");
+// % Check("vm.5 QMapNode<QString, QVariant>");
+// % Check("vm.5.key "f" QString");
+// % Check("vm.5.value "2Some String" QVariant (QString)");
+
+// QTest::newRow("QVectorIntBig")
+// << Data(
+// // This tests the display of a big vector");
+// QVector<int> vec(10000);
+// for (int i = 0; i != vec.size(); ++i)
+// vec[i] = i * i;
+// % Check("vec <10000 items> QVector<int>");
+// % Check("vec.0", "0", "int");
+// % Check("vec.1999", "3996001", "int");
+// // Continue");
+
+// // step over
+// // check that the display updates in reasonable time
+// vec[1] = 1;
+// vec[2] = 2;
+// vec.append(1);
+// vec.append(1);
+// % Check("vec <10002 items> QVector<int>");
+// % Check("vec.1", "1", "int");
+// % Check("vec.2", "2", "int");
+
+// QTest::newRow("QVectorFoo")
+// << Data(
+// // This tests the display of a vector of pointers to custom structs");\n"
+// "QVector<Foo> vec;\n"
+// % Check("vec <0 items> QVector<Foo>");
+// // Continue");\n"
+// // step over, check display");\n"
+// "vec.append(1);\n"
+// "vec.append(2);\n"
+// % Check("vec <2 items> QVector<Foo>");
+// % Check("vec.0", "Foo");
+// % Check("vec.0.a", "1", "int");
+// % Check("vec.1", "Foo");
+// % Check("vec.1.a", "2", "int");
+
+// typedef QVector<Foo> FooVector;
+
+// QTest::newRow("QVectorFooTypedef")
+// << Data(
+// {
+// "FooVector vec;\n"
+// "vec.append(Foo(2));\n"
+// "vec.append(Foo(3));\n"
+// dummyStatement(&vec);
+// }
+
+// QTest::newRow("QVectorFooStar")
+// << Data(
+// {
+// // This tests the display of a vector of pointers to custom structs");
+// "QVector<Foo *> vec;\n"
+// % Check("vec <0 items> QVector<Foo*>");
+// // Continue");\n"
+// // step over\n"
+// // check that the display is ok");\n"
+// "vec.append(new Foo(1));\n"
+// "vec.append(0);\n"
+// "vec.append(new Foo(2));\n"
+// "vec.append(new Fooooo(3));\n"
+// // switch "Auto derefencing pointers" in Locals context menu\n"
+// // off and on again, and check result looks sane");\n"
+// % Check("vec <4 items> QVector<Foo*>");
+// % Check("vec.0", "Foo");
+// % Check("vec.0.a", "1", "int");
+// % Check("vec.1 0x0 Foo *");
+// % Check("vec.2", "Foo");
+// % Check("vec.2.a", "2", "int");
+// % Check("vec.3", "Fooooo");
+// % Check("vec.3.a", "5", "int");
+
+// QTest::newRow("QVectorBool")
+// << Data(
+// QVector<bool> vec;
+// % Check("vec <0 items> QVector<bool>");
+// // Continue");
+// // step over
+// // check that the display is ok");
+// vec.append(true);
+// vec.append(false);
+// % Check("vec <2 items> QVector<bool>");
+// % Check("vec.0", "true", "bool");
+// % Check("vec.1", "false", "bool");
+
+// QTest::newRow("QVectorListInt")
+// << Data(
+// "QVector<QList<int> > vec;
+// "QVector<QList<int> > *pv = &vec;
+// % Check("pv", "QVector<QList<int>>");
+// % Check("vec <0 items> QVector<QList<int>>");
+// // Continue");
+// "vec.append(QList<int>() << 1);
+// "vec.append(QList<int>() << 2 << 3);
+// % Check("pv", "QVector<QList<int>>");
+// % Check("pv.0 <1 items> QList<int>");
+// % Check("pv.0.0", "1", "int");
+// % Check("pv.1 <2 items> QList<int>");
+// % Check("pv.1.0", "2", "int");
+// % Check("pv.1.1", "3", "int");
+// % Check("vec <2 items> QVector<QList<int>>");
+// % Check("vec.0 <1 items> QList<int>");
+// % Check("vec.0.0", "1", "int");
+// % Check("vec.1 <2 items> QList<int>");
+// % Check("vec.1.0", "2", "int");
+// % Check("vec.1.1", "3", "int");
+
+//namespace noargs {
+
+// class Goo
+// {
+// public:
+// Goo(const QString &str, const int n) : str_(str), n_(n) {}
+// private:
+// QString str_;
+// int n_;
+// };
+
+// typedef QList<Goo> GooList;
+
+// QTest::newRow("NoArgumentName(int i, int, int k)
+// {
+// // This is not supposed to work with the compiled dumpers");
+// "GooList list;
+// "list.append(Goo("Hello", 1));
+// "list.append(Goo("World", 2));
+
+// "QList<Goo> list2;
+// "list2.append(Goo("Hello", 1));
+// "list2.append(Goo("World", 2));
+
+// % Check("i", "1", "int");
+// % Check("k", "3", "int");
+// % Check("list <2 items> noargs::GooList");
+// % Check("list.0", "noargs::Goo");
+// % Check("list.0.n_", "1", "int");
+// % Check("list.0.str_ "Hello" QString");
+// % Check("list.1", "noargs::Goo");
+// % Check("list.1.n_", "2", "int");
+// % Check("list.1.str_ "World" QString");
+// % Check("list2 <2 items> QList<noargs::Goo>");
+// % Check("list2.0", "noargs::Goo");
+// % Check("list2.0.n_", "1", "int");
+// % Check("list2.0.str_ "Hello" QString");
+// % Check("list2.1", "noargs::Goo");
+// % Check("list2.1.n_", "2", "int");
+// % Check("list2.1.str_ "World" QString");
+
+
+//"void foo() {}\n"
+//"void foo(int) {}\n"
+//"void foo(QList<int>) {}\n"
+//"void foo(QList<QVector<int> >) {}\n"
+//"void foo(QList<QVector<int> *>) {}\n"
+//"void foo(QList<QVector<int *> *>) {}\n"
+//"\n"
+//"template <class T>\n"
+//"void foo(QList<QVector<T> *>) {}\n"
+//"\n"
+//"\n"
+//"namespace namespc {\n"
+//"\n"
+//" class MyBase : public QObject\n"
+//" {\n"
+//" public:\n"
+//" MyBase() {}\n"
+//" virtual void doit(int i)\n"
+//" {\n"
+//" n = i;\n"
+//" }\n"
+//" protected:\n"
+//" int n;\n"
+//" };\n"
+//"\n"
+//" namespace nested {\n"
+//"\n"
+//" class MyFoo : public MyBase\n"
+//" {\n"
+//" public:\n"
+//" MyFoo() {}\n"
+//" virtual void doit(int i)\n"
+//" {\n"
+//" // Note there's a local 'n' and one in the base class");\n"
+//" n = i;\n"
+//" }\n"
+//" protected:\n"
+//" int n;\n"
+//" };\n"
+//"\n"
+//" class MyBar : public MyFoo\n"
+//" {\n"
+//" public:\n"
+//" virtual void doit(int i)\n"
+//" {\n"
+//" n = i + 1;\n"
+//" }\n"
+//" };\n"
+//"\n"
+//" namespace {\n"
+//"\n"
+//" class MyAnon : public MyBar\n"
+//" {\n"
+//" public:\n"
+//" virtual void doit(int i)\n"
+//" {\n"
+//" n = i + 3;\n"
+//" }\n"
+//" };\n"
+//"\n"
+//" namespace baz {\n"
+//"\n"
+//" class MyBaz : public MyAnon\n"
+//" {\n"
+//" public:\n"
+//" virtual void doit(int i)\n"
+//" {\n"
+//" n = i + 5;\n"
+//" }\n"
+//" };\n"
+//"\n"
+//" } // namespace baz\n"
+//"\n"
+//" } // namespace anon\n"
+//"\n"
+//" } // namespace nested\n"
+//"\n"
+// QTest::newRow("Namespace()
+// {
+// // This checks whether classes with "special" names are
+// // properly displayed");
+// "using namespace nested;\n"
+// "MyFoo foo;\n"
+// "MyBar bar;\n"
+// "MyAnon anon;\n"
+// "baz::MyBaz baz;\n"
+// % CheckType("anon namespc::nested::(anonymous namespace)::MyAnon");
+// % Check("bar", "namespc::nested::MyBar");
+// % CheckType("baz namespc::nested::(anonymous namespace)::baz::MyBaz");
+// % Check("foo", "namespc::nested::MyFoo");
+// // Continue");
+// // step into the doit() functions
+
+// baz.doit(1);\n"
+// anon.doit(1);\n"
+// foo.doit(1);\n"
+// bar.doit(1);\n"
+// dummyStatement();\n"
+// }
+
+
+// QTest::newRow("GccExtensions")
+// "#ifdef __GNUC__\n"
+// "char v[8] = { 1, 2 };\n"
+// "char w __attribute__ ((vector_size (8))) = { 1, 2 };\n"
+// "int y[2] = { 1, 2 };\n"
+// "int z __attribute__ ((vector_size (8))) = { 1, 2 };\n"
+// "#endif\n"
+// % Check("v.0", "1", "char");
+// % Check("v.1", "2", "char");
+// % Check("w.0", "1", "char");
+// % Check("w.1", "2", "char");
+// % Check("y.0", "1", "int");
+// % Check("y.1", "2", "int");
+// % Check("z.0", "1", "int");
+// % Check("z.1", "2", "int");
+
+
+//class Z : public QObject
+//{
+//public:
+// Z() {
+// f = new Foo();
+// i = 0;
+// i = 1;
+// i = 2;
+// i = 3;
+// }
+// int i;
+// Foo *f;
+//};
+
+//QString fooxx()
+//{
+// return "bababa";
+//}
+
+
+ QTest::newRow("Int")
+ << Data("#include <qglobal.h>\n"
+ "#include <limits.h>\n"
+ "#include <QString>\n",
+ "quint64 u64 = ULLONG_MAX;\n"
+ "qint64 s64 = LLONG_MAX;\n"
+ "quint32 u32 = ULONG_MAX;\n"
+ "qint32 s32 = LONG_MAX;\n"
+ "quint64 u64s = 0;\n"
+ "qint64 s64s = LLONG_MIN;\n"
+ "quint32 u32s = 0;\n"
+ "qint32 s32s = LONG_MIN;\n"
+ "QString dummy; // needed to get namespace\n"
+ "dummyStatement(&u64, &s64, &u32, &s32, &u64s, &s64s, &u32s, &s32s, &dummy);\n")
+ % Check("u64", "18446744073709551615", "@quint64")
+ % Check("s64", "9223372036854775807", "@qint64")
+ % Check("u32", "4294967295", "@quint32")
+ % Check("s32", "2147483647", "@qint32")
+ % Check("u64s", "0", "@quint64")
+ % Check("s64s", "-9223372036854775808", "@qint64")
+ % Check("u32s", "0", "@quint32")
+ % Check("s32s", "-2147483648", "@qint32");
+
+
+// QTest::newRow("Array1")
+// << Data(
+// "double d[3][3];\n"
+// "for (int i = 0; i != 3; ++i)\n"
+// " for (int j = 0; j != 3; ++j)\n"
+// " d[i][j] = i + j;\n"
+// % CheckType("d double [3][3]");
+// % CheckType("d.0 double [3]");
+// % Check("d.0.0", "0", "double");
+// % Check("d.0.2", "2", "double");
+// % CheckType("d.2 double [3]");
+
+// QTest::newRow("Array2")
+// << Data(
+// "char c[20];\n"
+// "c[0] = 'a';\n"
+// "c[1] = 'b';\n"
+// "c[2] = 'c';\n"
+// "c[3] = 'd';\n"
+// % CheckType("c char [20]");
+// % Check("c.0 97 'a' char");
+// % Check("c.3 100 'd' char");
+
+// QTest::newRow("Array3")
+// << Data(
+// "QString s[20];
+// "s[0] = "a";\n"
+// "s[1] = "b";\n"
+// "s[2] = "c";\n"
+// "s[3] = "d";\n"
+// % CheckType("s QString [20]");
+// % Check("s.0 "a" QString");
+// % Check("s.3 "d" QString");
+// % Check("s.4 "" QString");
+// % Check("s.19 "" QString");
+
+// QTest::newRow("Array4")
+// << Data(
+// "QByteArray b[20];\n"
+// "b[0] = "a";\n"
+// "b[1] = "b";\n"
+// "b[2] = "c";\n"
+// "b[3] = "d";\n"
+// % CheckType("b QByteArray [20]");
+// % Check("b.0 "a" QByteArray");
+// % Check("b.3 "d" QByteArray");
+// % Check("b.4 "" QByteArray");
+// % Check("b.19 "" QByteArray");
+
+ QTest::newRow("Array5")
+ << Data(fooData,
+ "Foo foo[10];\n"
+ "for (int i = 0; i < 5; ++i)\n"
+ " foo[i].a = i;\n")
+ % CheckType("foo", "Foo [10]")
+ % Check("foo.0", "[0]", "", "Foo")
+ % Check("foo.9", "[9]", "", "Foo");
+
+
+ QTest::newRow("Bitfields")
+ << Data("struct S\n"
+ "{\n"
+ " S() : x(0), y(0), c(0), b(0), f(0), d(0), i(0) {}\n"
+ " unsigned int x : 1;\n"
+ " unsigned int y : 1;\n"
+ " bool c : 1;\n"
+ " bool b;\n"
+ " float f;\n"
+ " double d;\n"
+ " int i;\n"
+ "} s;\n"
+ "dummyStatement(&s);\n")
+ % Check("s", "", "S")
+ % Check("s.b", "false", "bool")
+ % Check("s.c", "false", "bool")
+ % Check("s.d", "0", "double")
+ % Check("s.f", "0", "float")
+ % Check("s.i", "0", "int")
+ % Check("s.x", "0", "unsigned int")
+ % Check("s.y", "0", "unsigned int");
+
+
+ QTest::newRow("Function")
+ << Data("#include <QByteArray>\n"
+ "struct Function\n"
+ "{\n"
+ " Function(QByteArray var, QByteArray f, double min, double max)\n"
+ " : var(var), f(f), min(min), max(max) {}\n"
+ " QByteArray var;\n"
+ " QByteArray f;\n"
+ " double min;\n"
+ " double max;\n"
+ "};\n",
+ "// In order to use this, switch on the 'qDump__Function' in dumper.py\n"
+ "Function func(\"x\", \"sin(x)\", 0, 1);\n"
+ "func.max = 10;\n"
+ "func.f = \"cos(x)\";\n"
+ "func.max = 4;\n"
+ "func.max = 5;\n"
+ "func.max = 6;\n"
+ "func.max = 7;\n")
+ % Check("func", "", "Function")
+ % Check("func.f", "sin(x)", "@QByteArray")
+ % Check("func.max", "1", "double")
+ % Check("func.min", "0", "double")
+ % Check("func.var", "\"x\"", "@QByteArray")
+ % Check("func", "", "Function")
+ % Check("func.f", "\"cos(x)\"", "@QByteArray")
+ % Check("func.max", "7", "double");
+
+// QTest::newRow("AlphabeticSorting")
+// << Data(
+// "// This checks whether alphabetic sorting of structure\n"
+// "// members work");\n"
+// "struct Color\n"
+// "{\n"
+// " int r,g,b,a;\n"
+// " Color() { r = 1, g = 2, b = 3, a = 4; }\n"
+// "};\n"
+// " Color c;\n"
+// % Check("c", "basic::Color");
+// % Check("c.a", "4", "int");
+// % Check("c.b", "3", "int");
+// % Check("c.g", "2", "int");
+// % Check("c.r", "1", "int");
+
+// // Manual: Toogle "Sort Member Alphabetically" in context menu
+// // Manual: of "Locals and Expressions" view");
+// // Manual: Check that order of displayed members changes");
+
+// QTest::newRow("Typedef")
+// << Data(
+// "namespace ns {\n"
+// " typedef unsigned long long vl;\n"
+// " typedef vl verylong;\n"
+// "}\n"
+
+// "typedef quint32 myType1;\n"
+// "typedef unsigned int myType2;\n"
+// "myType1 t1 = 0;\n"
+// "myType2 t2 = 0;\n"
+// "ns::vl j = 1000;\n"
+// "ns::verylong k = 1000;\n"
+// % Check("j", "1000", "basic::ns::vl");
+// % Check("k", "1000", "basic::ns::verylong");
+// % Check("t1", "0", "basic::myType1");
+// % Check("t2", "0", "basic::myType2");
+
+// QTest::newRow("Struct")
+// << Data(
+// "Foo f(2);\n"
+// "f.doit();\n"
+// "f.doit();\n"
+// "f.doit();\n"
+// % Check("f", "Foo");
+// % Check("f.a", "5", "int");
+// % Check("f.b", "2", "int");
+
+// QTest::newRow("Union")
+// << Data(
+// "union U\n"
+// "{\n"
+// " int a;\n"
+// " int b;\n"
+// "} u;\n"
+// % Check("u", "basic::U");
+// % Check("u.a", "int");
+// % Check("u.b", "int");
+
+// QTest::newRow("TypeFormats")
+// << Data(
+// "// These tests should result in properly displayed umlauts in the\n"
+// "// Locals and Expressions view. It is only support on gdb with Python");\n"
+// "const char *s = "aöa";\n"
+// "const wchar_t *w = L"aöa";\n"
+// "QString u;\n"
+// "// All: Select UTF-8 in "Change Format for Type" in L&W context menu");\n"
+// "// Windows: Select UTF-16 in "Change Format for Type" in L&W context menu");\n"
+// "// Other: Select UCS-6 in "Change Format for Type" in L&W context menu");\n"
+// "if (sizeof(wchar_t) == 4)\n"
+// " u = QString::fromUcs4((uint *)w);\n"
+// "else\n"
+// " u = QString::fromUtf16((ushort *)w);\n"
+// % CheckType("s char *");
+// % Check("u "" QString");
+// % CheckType("w wchar_t *");
+
+
+
+// typedef void *VoidPtr;
+// typedef const void *CVoidPtr;
+
+// struct A
+// {
+// A() : test(7) {}
+// int test;
+// void doSomething(CVoidPtr cp) const;
+// };
+
+// void A::doSomething(CVoidPtr cp) const
+// % Check("cp", "basic::CVoidPtr");
+
+// QTest::newRow("Pointer")
+// << Data(
+// "Foo *f = new Foo();\n"
+// % Check("f", "Foo");
+// % Check("f.a", "0", "int");
+// % Check("f.b", "5", "int");
+
+// QTest::newRow("PointerTypedef")
+// << Data(
+// "A a;\n"
+// "VoidPtr p = &a;\n"
+// "CVoidPtr cp = &a;\n"
+// % Check("a", "basic::A");
+// % Check("cp", "basic::CVoidPtr");
+// % Check("p", "basic::VoidPtr");
+
+// QTest::newRow("StringWithNewline")
+// << Data(
+// "QString hallo = "hallo\nwelt";\n"
+// % Check("hallo "hallo\nwelt" QString");
+// % Check("that string is properly displayed");
+
+// QTest::newRow("Reference1")
+// << Data(
+// "int a = 43;\n"
+// "const int &b = a;\n"
+// "typedef int &Ref;\n"
+// "const int c = 44;\n"
+// "const Ref d = a;\n"
+// % Check("a", "43", "int");
+// % Check("b 43 int &");
+// % Check("c", "44", "int");
+// % Check("d", "43", "basic::Ref");
+
+// QTest::newRow("Reference2")
+// << Data(
+// "QString a = "hello";\n"
+// "const QString &b = fooxx();\n"
+// "typedef QString &Ref;\n"
+// "const QString c = "world";\n"
+// "const Ref d = a;\n"
+// % Check("a "hello" QString");
+// % Check("b "bababa" QString &");
+// % Check("c "world" QString");
+// % Check("d "hello" basic::Ref");
+
+ QTest::newRow("Reference3")
+ << Data("#include <QString>\n",
+ "const QString &b = a;\n"
+ "typedef QString &Ref;\n"
+ "const Ref d = const_cast<Ref>(a);\n")
+ % Check("a", "\"hello\"", "@QString &")
+ % Check("b", "\"hello\"", "@QString &")
+ % Check("d", "\"hello\"", "Ref");
+
+ QTest::newRow("DynamicReference")
+ << Data("DerivedClass d;\n"
+ "BaseClass *b1 = &d;\n"
+ "BaseClass &b2 = d;\n"
+ "dummyStatement(&b1, &b2);\n")
+ % CheckType("b1", "DerivedClass *")
+ % CheckType("b2", "DerivedClass &");
+
+// QTest::newRow("LongEvaluation1")
+// << Data(
+// "QDateTime time = QDateTime::currentDateTime();\n"
+// "const int N = 10000;\n"
+// "QDateTime bigv[N];\n"
+// "for (int i = 0; i < 10000; ++i) {\n"
+// " bigv[i] = time;\n"
+// " time = time.addDays(1);\n"
+// "}\n"
+// % Check("N", "10000", "int");
+// % CheckType("bigv QDateTime [10000]");
+// % Check("bigv.0", "QDateTime");
+// % Check("bigv.9999", "QDateTime");
+// % Check("time", "QDateTime");
+
+// QTest::newRow("LongEvaluation2")
+// << Data(
+// "const int N = 10000;\n"
+// "int bigv[N];\n"
+// "for (int i = 0; i < 10000; ++i)\n"
+// " bigv[i] = i;\n"
+// % Check("N", "10000", "int");
+// % CheckType("bigv int [10000]");
+// % Check("bigv.0", "0", "int");
+// % Check("bigv.9999", "9999", "int");
+
+// QTest::newRow("Fork")
+// << Data(
+// "QProcess proc;\n"
+// "proc.start("/bin/ls");\n"
+// "proc.waitForFinished();\n"
+// "QByteArray ba = proc.readAllStandardError();\n"
+// "ba.append('x');\n"
+// % Check("ba "x" QByteArray");
+// % Check("proc QProcess");
+
+
+// QTest::newRow("FunctionPointer")
+// << Data(
+// "int testFunctionPointerHelper(int x) { return x; }\n"
+// "typedef int (*func_t)(int);\n"
+// "func_t f = testFunctionPointerHelper;\n"
+// "int a = f(43);\n"
+// % Check("f", "basic::func_t");
+
+// QByteArray dataClass = "struct Class
+// "{\n"
+// " Class() : a(34) {}\n"
+// " int testFunctionPointerHelper(int x) { return x; }\n"
+// " int a;\n"
+// "};\n"
+
+// QTest::newRow("MemberFunctionPointer")
+// << Data(
+
+// "Class x;\n"
+// "typedef int (Class::*func_t)(int);\n"
+// "func_t f = &Class::testFunctionPointerHelper;\n"
+// "int a = (x.*f)(43);\n"
+// % Check("f", "basic::func_t");
+
+// QTest::newRow("MemberPointer")
+// << Data(
+// Class x;\n"
+// typedef int (Class::*member_t);\n"
+// member_t m = &Class::a;\n"
+// int a = x.*m;\n"
+// % Check("m", "basic::member_t");\n"
+// // Continue");\n"
+
+// % Check("there's a valid display for m");
+
+// QTest::newRow("PassByReferenceHelper(Foo &f)
+// % CheckType("f Foo &");\n"
+// % Check("f.a", "12", "int");\n"
+// // Continue");\n"
+// ++f.a;\n"
+// % CheckType("f Foo &");\n"
+// % Check("f.a", "13", "int");\n"
+
+// QTest::newRow("PassByReference")
+// << Data(
+// "Foo f(12);\n"
+// "testPassByReferenceHelper(f);\n"
+
+// QTest::newRow("BigInt")
+// << Data(
+// "qint64 a = Q_INT64_C(0xF020304050607080);\n"
+// "quint64 b = Q_UINT64_C(0xF020304050607080);\n"
+// "quint64 c = std::numeric_limits<quint64>::max() - quint64(1);\n"
+// % Check("a", "-1143861252567568256", "qint64");
+// % Check("b", "-1143861252567568256", "quint64");
+// % Check("c", "-2", "quint64");
+
+// QTest::newRow("Hidden")
+// << Data(
+// {
+// int n = 1;\n"
+// n = 2;\n"
+// BREAK_HERE;\n"
+// % Check("n", "2", "int");\n"
+// // Continue");\n"
+// n = 3;\n"
+// BREAK_HERE;\n"
+// % Check("n", "3", "int");\n"
+// // Continue");\n"
+// {\n"
+// QString n = "2";\n"
+// BREAK_HERE;\n"
+// % Check("n "2" QString");\n"
+// % Check("n@1", "3", "int");\n"
+// // Continue");\n"
+// n = "3";\n"
+// BREAK_HERE;\n"
+// % Check("n "3" QString");\n"
+// % Check("n@1", "3", "int");\n"
+// // Continue");\n"
+// {\n"
+// double n = 3.5;\n"
+// BREAK_HERE;\n"
+// % Check("n", "3.5", "double");\n"
+// % Check("n@1 "3" QString");\n"
+// % Check("n@2", "3", "int");\n"
+// // Continue");\n"
+// ++n;\n"
+// BREAK_HERE;\n"
+// % Check("n", "4.5", "double");\n"
+// % Check("n@1 "3" QString");\n"
+// % Check("n@2", "3", "int");\n"
+// // Continue");\n"
+// dummyStatement(&n);\n"
+// }\n"
+// BREAK_HERE;\n"
+// % Check("n "3" QString");\n"
+// % Check("n@1", "3", "int");\n"
+// // Continue");\n"
+// n = "3";\n"
+// n = "4";
+// BREAK_HERE;\n"
+// % Check("n "4" QString");\n"
+// % Check("n@1", "3", "int");\n"
+// // Continue");\n"
+// dummyStatement(&n);\n"
+// }\n"
+// ++n;\n"
+// dummyStatement(&n);\n"
+// }\n"
+//\n"
+// int testReturnInt")
+// << Data(
+// {
+// return 1;
+// }
+
+// bool testReturnBool")
+// << Data(
+// {
+// return true;
+// }
+
+// QString testReturnQString")
+// << Data(
+// {
+// return "string";
+// }
+
+// QTest::newRow("Return")
+// << Data(
+// {
+// bool b = testReturnBool();
+// BREAK_HERE;
+// % Check("b", "true", "bool");
+// // Continue");
+// int i = testReturnInt();
+// BREAK_HERE;
+// % Check("i", "1", "int");
+// // Continue");
+// QString s = testReturnQString();
+// BREAK_HERE;
+// % Check("s "string" QString");
+// // Continue");
+// dummyStatement(&i, &b, &s);
+// }
+
+// #ifdef Q_COMPILER_RVALUE_REFS\n"
+// struct X { X() : a(2), b(3) {} int a, b; };\n"
+//\n"
+// X testRValueReferenceHelper1()\n"
+// {\n"
+// return X();\n"
+// }\n"
+//\n"
+// X testRValueReferenceHelper2(X &&x)\n"
+// {\n"
+// return x;\n"
+// }\n"
+//\n"
+// QTest::newRow("RValueReference()\n"
+// {\n"
+// X &&x1 = testRValueReferenceHelper1();\n"
+// X &&x2 = testRValueReferenceHelper2(std::move(x1));\n"
+// X &&x3 = testRValueReferenceHelper2(testRValueReferenceHelper1());\n"
+//\n"
+// X y1 = testRValueReferenceHelper1();\n"
+// X y2 = testRValueReferenceHelper2(std::move(y1));\n"
+// X y3 = testRValueReferenceHelper2(testRValueReferenceHelper1());\n"
+//\n"
+// BREAK_HERE;\n"
+// // Continue");\n"
+// dummyStatement(&x1, &x2, &x3, &y1, &y2, &y3);\n"
+// }\n"
+
+// QTest::newRow("SSE")
+// << Data(
+// {
+// #ifdef __SSE__\n"
+// float a[4];\n"
+// float b[4];\n"
+// int i;\n"
+// for (i = 0; i < 4; i++) {\n"
+// a[i] = 2 * i;\n"
+// b[i] = 2 * i;\n"
+// }\n"
+// __m128 sseA, sseB;\n"
+// sseA = _mm_loadu_ps(a);\n"
+// sseB = _mm_loadu_ps(b);\n"
+// % Check("sseA", "__m128");
+// % Check("sseB", "__m128");
+// // Continue");
+// dummyStatement(&i, &sseA, &sseB);
+// #endif
+// }
+
+//} // namespace sse
+
+
+//namespace qscript {
+
+// QTest::newRow("QScript")
+// << Data(
+//" QScriptEngine engine;n"
+//" QDateTime date = QDateTime::currentDateTime();n"
+//" QScriptValue s;n"
+//"n"
+//" % Check("engine QScriptEngine");n"
+//" % Check("s", "(invalid)", "QScriptValue");n"
+//" % Check("x1 <not accessible> QString");n"
+//" // Continue");n"
+//" s = QScriptValue(33);n"
+//" int x = s.toInt32();n"
+//"n"
+//" s = QScriptValue(QString("34"));n"
+//" QString x1 = s.toString();n"
+//"n"
+//" s = engine.newVariant(QVariant(43));n"
+//" QVariant v = s.toVariant();n"
+//"n"
+//" s = engine.newVariant(QVariant(43.0));n"
+//" s = engine.newVariant(QVariant(QString("sss")));n"
+//" s = engine.newDate(date);n"
+//" date = s.toDateTime();n"
+//" s.setProperty("a", QScriptValue());n"
+//" QScriptValue d = s.data();n"
+// % Check("d", "(invalid)", "QScriptValue");
+// % Check("v 43 QVariant (int)");
+// % Check("x", "33", "int");
+// % Check("x1 "34" QString");
+
+
+// QTest::newRow("WTFString")
+// << Data(
+// "QWebPage p;
+// % Check("p", "QWebPage");
+
+// QTest::newRow("BoostOptional1")
+// << Data(
+// "boost::optional<int> i0, i;
+// "i = 1;
+// % Check("i0", "<uninitialized>", "boost::optional<int>");
+// % Check("i", "1", "boost::optional<int>");
+
+// QTest::newRow("BoostOptional2")
+// << Data(
+// "boost::optional<QStringList> sl0, sl;\n"
+// "sl = (QStringList() << "xxx" << "yyy");\n"
+// "sl.get().append("zzz");\n"
+// % Check("sl", "<uninitialized>", "boost::optional<QStringList>");
+// % Check("sl <3 items> boost::optional<QStringList>");
+
+// QTest::newRow("BoostSharedPtr")
+// << Data(
+// "boost::shared_ptr<int> s;\n"
+// "boost::shared_ptr<int> i(new int(43));\n"
+// "boost::shared_ptr<int> j = i;\n"
+// "boost::shared_ptr<QStringList> sl(new QStringList(QStringList() << "HUH!"));
+// % Check("s", "(null)", "boost::shared_ptr<int>");
+// % Check("i", "43", "boost::shared_ptr<int>");
+// % Check("j", "43", "boost::shared_ptr<int>");
+// % Check("sl boost::shared_ptr<QStringList>");
+// % Check("sl.data <1 items> QStringList
+
+// QTest::newRow("BoostGregorianDate")
+// << Data(
+// "using namespace boost;\n"
+// "using namespace gregorian;\n"
+// "date d(2005, Nov, 29);\n"
+// "d += months(1);\n"
+// "d += months(1);\n"
+// "// snap-to-end-of-month behavior kicks in:\n"
+// "d += months(1);\n"
+// "// Also end of the month (expected in boost)\n"
+// "d += months(1);\n"
+// "// Not where we started (expected in boost)\n"
+// "d -= months(4);\n"
+// % Check("d Tue Nov 29 2005 boost::gregorian::date");
+// % Check("d Thu Dec 29 2005 boost::gregorian::date");
+// % Check("d Sun Jan 29 2006 boost::gregorian::date");
+// % Check("d Tue Feb 28 2006 boost::gregorian::date");
+// % Check("d Fri Mar 31 2006 boost::gregorian::date");
+// % Check("d Wed Nov 30 2005 boost::gregorian::date");
+
+// QTest::newRow("BoostPosixTimeTimeDuration")
+// << Data(
+// "using namespace boost;\n"
+// "using namespace posix_time;\n"
+// "time_duration d1(1, 0, 0);\n"
+// "time_duration d2(0, 1, 0);\n"
+// "time_duration d3(0, 0, 1);\n"
+// % Check("d1", "01:00:00", "boost::posix_time::time_duration");
+// % Check("d2", "00:01:00", "boost::posix_time::time_duration");
+// % Check("d3", "00:00:01", "boost::posix_time::time_duration");
+
+// QTest::newRow("BoostBimap")
+// << Data(
+// "typedef boost::bimap<int, int> B;\n"
+// "B b;\n"
+// "b.left.insert(B::left_value_type(1, 2));\n"
+// "B::left_const_iterator it = b.left.begin();\n"
+// "int l = it->first;\n"
+// "int r = it->second;\n"
+// % Check("b <0 items> boost::B");
+// % Check("b <1 items> boost::B");
+
+// QTest::newRow("BoostPosixTimePtime")
+// << Data(
+// "using namespace boost;\n"
+// "using namespace gregorian;\n"
+// "using namespace posix_time;\n"
+// "ptime p1(date(2002, 1, 10), time_duration(1, 0, 0));\n"
+// "ptime p2(date(2002, 1, 10), time_duration(0, 0, 0));\n"
+// "ptime p3(date(1970, 1, 1), time_duration(0, 0, 0));\n"
+// % Check("p1 Thu Jan 10 01:00:00 2002 boost::posix_time::ptime");
+// % Check("p2 Thu Jan 10 00:00:00 2002 boost::posix_time::ptime");
+// % Check("p3 Thu Jan 1 00:00:00 1970 boost::posix_time::ptime");
+
+
+
+// // This tests qdump__KRBase in dumpers/qttypes.py which uses
+// // a static typeflag to dispatch to subclasses");
+
+// QTest::newRow("KR")
+// << Data(
+// "namespace kr {\n"
+//\n"
+// " // FIXME: put in namespace kr, adjust qdump__KRBase in dumpers/qttypes.py\n"
+// " struct KRBase\n"
+// " {\n"
+// " enum Type { TYPE_A, TYPE_B } type;\n"
+// " KRBase(Type _type) : type(_type) {}\n"
+// " };\n"
+//\n"
+// " struct KRA : KRBase { int x; int y; KRA():KRBase(TYPE_A), x(1), y(32) {} };\n"
+// " struct KRB : KRBase { KRB():KRBase(TYPE_B) {} };\n"
+
+// "/} // namespace kr\n"
+
+// "KRBase *ptr1 = new KRA;\n"
+// "KRBase *ptr2 = new KRB;\n"
+// "ptr2 = new KRB;\n"
+// % Check("ptr1", "KRBase");
+// % Check("ptr1.type KRBase::TYPE_A (0) KRBase::Type");
+// % Check("ptr2", "KRBase");
+// % Check("ptr2.type KRBase::TYPE_B (1) KRBase::Type");
+
+
+
+// QTest::newRow("Eigen")
+// << Data(
+// "using namespace Eigen;\n"
+
+// "Vector3d test = Vector3d::Zero();\n"
+
+// "Matrix3d myMatrix = Matrix3d::Constant(5);\n"
+// "MatrixXd myDynamicMatrix(30, 10);\n"
+
+// "myDynamicMatrix(0, 0) = 0;\n"
+// "myDynamicMatrix(1, 0) = 1;\n"
+// "myDynamicMatrix(2, 0) = 2;\n"
+
+// "Matrix<double, 12, 15, ColMajor> colMajorMatrix;\n"
+// "Matrix<double, 12, 15, RowMajor> rowMajorMatrix;\n"
+
+// "int k = 0;\n"
+// "for (int i = 0; i != 12; ++i) {\n"
+// " for (int j = 0; j != 15; ++j) {\n"
+// " colMajorMatrix(i, j) = k;\n"
+// " rowMajorMatrix(i, j) = k;\n"
+// " ++k;\n"
+// " }\n"
+// "}\n"
+
+
+
+// QTest::newRow("https://bugreports.qt-project.org/browse/QTCREATORBUG-3611")
+// "typedef unsigned char byte;\n"
+// "byte f = '2';\n"
+// "int *x = (int*)&f;\n"
+// % Check("f 50 '2' bug3611::byte");
+
+
+
+// QTest::newRow("https://bugreports.qt-project.org/browse/QTCREATORBUG-4904")
+// << Data(
+
+// "struct CustomStruct {\n"
+// " int id;\n"
+// " double dvalue;\n"
+// "};",
+// "QMap<int, CustomStruct> map;\n"
+// "CustomStruct cs1;\n"
+// "cs1.id = 1;\n"
+// "cs1.dvalue = 3.14;\n"
+// "CustomStruct cs2 = cs1;\n"
+// "cs2.id = -1;\n"
+// "map.insert(cs1.id, cs1);\n"
+// "map.insert(cs2.id, cs2);\n"
+// "QMap<int, CustomStruct>::iterator it = map.begin();\n"
+// % Check("map <2 items> QMap<int, bug4904::CustomStruct>");
+// % Check("map.0 QMapNode<int, bug4904::CustomStruct>");
+// % Check("map.0.key", "-1", "int");
+// % Check("map.0.value", "bug4904::CustomStruct");
+// % Check("map.0.value.dvalue", "3.1400000000000001", "double");
+// % Check("map.0.value.id", "-1", "int");
+
+
+// QTest::newRow("// https://bugreports.qt-project.org/browse/QTCREATORBUG-5106")
+// << Data(
+// "class A5106\n"
+// "{\n"
+// "public:\n"
+// " A5106(int a, int b) : m_a(a), m_b(b) {}\n"
+// " virtual int test() { return 5; }\n"
+// "private:\n"
+// " int m_a, m_b;\n"
+// "};\n"
+
+// "class B5106 : public A5106\n"
+// "{\n"
+// "public:\n"
+// " B5106(int c, int a, int b) : A5106(a, b), m_c(c) {}\n"
+// " virtual int test() { return 4; BREAK_HERE; }\n"
+// "private:\n"
+// " int m_c;\n"
+// "};\n"
+// ,
+// " B5106 b(1,2,3);\n"
+// " b.test();\n"
+// " b.A5106::test();\n"
+// }
+
+
+// // https://bugreports.qt-project.org/browse/QTCREATORBUG-5184
+
+// // Note: The report there shows type field "QUrl &" instead of QUrl");
+// // It's unclear how this can happen. It should never have been like
+// // that with a stock 7.2 and any version of Creator");
+
+// void helper(const QUrl &url)\n"
+// {\n"
+// QNetworkRequest request(url);\n"
+// QList<QByteArray> raw = request.rawHeaderList();\n"
+// % Check("raw <0 items> QList<QByteArray>");
+// % Check("request", "QNetworkRequest");
+// % Check("url "http://127.0.0.1/" QUrl &");
+// }
+
+// QTest::newRow("5184()
+// {
+// QUrl url(QString("http://127.0.0.1/"));\n"
+// helper(url);\n"
+// }
+
+
+//namespace qc42170 {
+
+// // http://www.qtcentre.org/threads/42170-How-to-watch-data-of-actual-type-in-debugger
+
+// struct Object
+// {
+// Object(int id_) : id(id_) {}
+// virtual ~Object() {}
+// int id;
+// };
+
+// struct Point : Object
+// {
+// Point(double x_, double y_) : Object(1), x(x_), y(y_) {}
+// double x, y;
+// };
+
+// struct Circle : Point
+// {
+// Circle(double x_, double y_, double r_) : Point(x_, y_), r(r_) { id = 2; }
+// double r;
+// };
+
+// void helper(Object *obj)
+// {
+// % Check("obj", "qc42170::Circle");
+// // Continue");
+
+// % Check("that obj is shown as a 'Circle' object");
+// dummyStatement(obj);
+// }
+
+// QTest::newRow("42170")
+// << Data(
+// {
+// Circle *circle = new Circle(1.5, -2.5, 3.0);
+// Object *obj = circle;
+// helper(circle);
+// helper(obj);
+// }
+
+//} // namespace qc42170
+
+
+//namespace bug5799 {
+
+// // https://bugreports.qt-project.org/browse/QTCREATORBUG-5799
+
+// QTest::newRow("5799()
+// "typedef struct { int m1; int m2; } S1;\n"
+// "struct S2 : S1 { };\n"
+// "typedef struct S3 { int m1; int m2; } S3;\n"
+// "struct S4 : S3 { };\n"
+
+// "S2 s2;\n"
+// "s2.m1 = 5;\n"
+// "S4 s4;\n"
+// "s4.m1 = 5;\n"
+// "S1 a1[10];\n"
+// "typedef S1 Array[10];\n"
+// "Array a2;\n"
+// % CheckType("a1 bug5799::S1 [10]");
+// % Check("a2", "bug5799::Array");
+// % Check("s2", "bug5799::S2");
+// % Check("s2.@1", "bug5799::S1");
+// % Check("s2.@1.m1", "5", "int");
+// % Check("s2.@1.m2", "int");
+// % Check("s4", "bug5799::S4");
+// % Check("s4.@1", "bug5799::S3");
+// % Check("s4.@1.m1", "5", "int");
+// % Check("s4.@1.m2", "int");
+
+
+// // http://www.qtcentre.org/threads/41700-How-to-watch-STL-containers-iterators-during-debugging
+
+// QTest::newRow("41700")
+// << Data(
+// {
+// "using namespace std;\n"
+// "typedef map<string, list<string> > map_t;\n"
+// "map_t m;\n"
+// "m["one"].push_back("a");\n"
+// "m["one"].push_back("b");\n"
+// "m["one"].push_back("c");\n"
+// "m["two"].push_back("1");\n"
+// "m["two"].push_back("2");\n"
+// "m["two"].push_back("3");\n"
+// "map_t::const_iterator it = m.begin();
+// % Check("m <2 items> qc41700::map_t");
+// % Check("m.0 std::pair<std::string const, std::list<std::string>>");
+// % Check("m.0.first "one" std::string");
+// % Check("m.0.second <3 items> std::list<std::string>");
+// % Check("m.0.second.0 "a" std::string");
+// % Check("m.0.second.1 "b" std::string");
+// % Check("m.0.second.2 "c" std::string");
+// % Check("m.1 std::pair<std::string const, std::list<std::string>>");
+// % Check("m.1.first "two" std::string");
+// % Check("m.1.second <3 items> std::list<std::string>");
+// % Check("m.1.second.0 "1" std::string");
+// % Check("m.1.second.1 "2" std::string");
+// % Check("m.1.second.2 "3" std::string");
+
+
+// // http://codepaster.europe.nokia.com/?id=42895
+
+// QTest::newRow("42895()
+// "void g(int c, int d)\n"
+// "{\n"
+// "qDebug() << c << d;\n"
+// "stopper()"\n"
+//\n"
+// "void f(int a, int b)\n"
+// "{\n"
+// " g(a, b);\n"
+// "}\n"
+
+// " f(3, 4);\n"
+
+// % Check("c", "3", "int");
+// % Check("d", "4", "int");
+// % Check("there are frames for g and f in the stack view");
+
+
+
+
+// // https://bugreports.qt-project.org/browse/QTCREATORBUG-6465
+
+// QTest::newRow("6465()\n"
+// {\n"
+// typedef char Foo[20];\n"
+// Foo foo = "foo";\n"
+// char bar[20] = "baz";
+
+//namespace bug6857 {
+
+// class MyFile : public QFile
+// {
+// public:
+// MyFile(const QString &fileName)
+// : QFile(fileName) {}
+// };
+
+// QTest::newRow("6857")
+// << Data(
+// MyFile file("/tmp/tt");
+// file.setObjectName("A file");
+// % Check("file bug6857::MyFile");
+// % Check("file.@1 "/tmp/tt" QFile");
+// % Check("file.@1.@1.@1 "A file" QObject");
+
+
+//namespace bug6858 {
+
+// class MyFile : public QFile\n"
+// {\n"
+// public:\n"
+// MyFile(const QString &fileName)\n"
+// : QFile(fileName) {}\n"
+// };\n"
+
+// QTest::newRow("6858")
+// << Data(
+// MyFile file("/tmp/tt");\n"
+// file.setObjectName("Another file");\n"
+// QFile *pfile = &file;\n"
+// % Check("pfile bug6858::MyFile");
+// % Check("pfile.@1 "/tmp/tt" QFile");
+// % Check("pfile.@1.@1.@1 "Another file" QObject");
+
+//namespace bug6863 {
+
+// class MyObject : public QObject\n"
+// {\n"
+// Q_OBJECT\n"
+// public:\n"
+// MyObject() {}\n"
+// };\n"
+//\n"
+// void setProp(QObject *obj)\n"
+// {\n"
+// obj->setProperty("foo", "bar");
+// % Check("obj.[QObject].properties", "<2", "items>");
+// // Continue");
+// dummyStatement(&obj);
+// }
+
+// QTest::newRow("6863")
+// << Data(
+// {
+// QFile file("/tmp/tt");\n"
+// setProp(&file);\n"
+// MyObject obj;\n"
+// setProp(&obj);\n"
+// }\n"
+
+//}
+
+
+
+// QTest::newRow("6933")
+// << Data(
+// "class Base\n"
+// "{\n"
+// "public:\n"
+// " Base() : a(21) {}\n"
+// " virtual ~Base() {}\n"
+// " int a;\n"
+// "};\n"
+
+// "class Derived : public Base\n"
+// "{\n"
+// "public:\n"
+// " Derived() : b(42) {}\n"
+// " int b;\n"
+// "};\n"
+
+// "Derived d;\n"
+// "Base *b = &d;\n"
+// % Check("b.[bug6933::Base].[vptr]
+// % Check("b.b", "42", "int");
+
+
+ QTest::newRow("valist")
+ << Data("#include <stdarg.h>\n"
+ "void test(const char *format, ...)\n"
+ "{\n"
+ " va_list arg;\n"
+ " va_start(arg, format);\n"
+ " int i = va_arg(arg, int);\n"
+ " double f = va_arg(arg, double);\n"
+ " dummyStatement(&i, &f);\n"
+ " va_end(arg);\n"
+ " stopper();\n"
+ "}\n",
+ "test(\"abc\", 1, 2.0);\n")
+ % Check("i", "1", "int")
+ % Check("f", "2", "double");
+
+
+ QTest::newRow("gdb13393")
+ << Data(
+ "struct Base {\n"
+ " Base() : a(1) {}\n"
+ " virtual ~Base() {} // Enforce type to have RTTI\n"
+ " int a;\n"
+ "};\n"
+ "struct Derived : public Base {\n"
+ " Derived() : b(2) {}\n"
+ " int b;\n"
+ "};\n"
+ "struct S\n"
+ "{\n"
+ " Base *ptr;\n"
+ " const Base *ptrConst;\n"
+ " Base &ref;\n"
+ " const Base &refConst;\n"
+ " S(Derived &d)\n"
+ " : ptr(&d), ptrConst(&d), ref(d), refConst(d)\n"
+ " {}\n"
+ " };\n"
+ ,
+ "Derived d;\n"
+ "S s(d);\n"
+ "Base *ptr = &d;\n"
+ "const Base *ptrConst = &d;\n"
+ "Base &ref = d;\n"
+ "const Base &refConst = d;\n"
+ "Base **ptrToPtr = &ptr;\n"
+ "#if USE_BOOST\n"
+ "boost::shared_ptr<Base> sharedPtr(new Derived());\n"
+ "#else\n"
+ "int sharedPtr = 1;\n"
+ "#endif\n"
+ "dummyStatement(&ptrConst, &ref, &refConst, &ptrToPtr, &sharedPtr);\n")
+ % Check("d", "", "Derived")
+ % Check("d.@1", "[Base]", "", "Base")
+ % Check("d.b", "2", "int")
+ % Check("ptr", "", "Derived")
+ % Check("ptr.@1", "[Base]", "", "Base")
+ % Check("ptr.@1.a", "1", "int")
+ % Check("ptrConst", "", "Derived")
+ % Check("ptrConst.@1", "[Base]", "", "Base")
+ % Check("ptrConst.b", "2", "int")
+ % Check("ptrToPtr", "", "Derived")
+ //% CheckType("ptrToPtr.[vptr]", " ")
+ % Check("ptrToPtr.@1.a", "1", "int")
+ % Check("ref", "", "Derived &")
+ //% CheckType("ref.[vptr]", "")
+ % Check("ref.@1.a", "1", "int")
+ % Check("refConst", "", "Derived &")
+ //% CheckType("refConst.[vptr]", "")
+ % Check("refConst.@1.a", "1", "int")
+ % Check("s", "", "S")
+ % Check("s.ptr", "", "Derived")
+ % Check("s.ptrConst", "", "Derived")
+ % Check("s.ref", "", "Derived &")
+ % Check("s.refConst", "", "Derived &")
+ % Check("sharedPtr", "1", "int");
+
+
+ // http://sourceware.org/bugzilla/show_bug.cgi?id=10586. fsf/MI errors out
+ // on -var-list-children on an anonymous union. mac/MI was fixed in 2006");
+ // The proposed fix has been reported to crash gdb steered from eclipse");
+ // http://sourceware.org/ml/gdb-patches/2011-12/msg00420.html
+ QTest::newRow("gdb10586mi")
+ << Data("struct Test {\n"
+ " struct { int a; float b; };\n"
+ " struct { int c; float d; };\n"
+ "} v = {{1, 2}, {3, 4}};\n"
+ "dummyStatement(&v);\n")
+ % Check("v", "", "Test")
+ % Check("v.a", "1", "int");
+
+ QTest::newRow("gdb10586eclipse")
+ << Data("struct { int x; struct { int a; }; struct { int b; }; } v = {1, {2}, {3}};\n"
+ "struct S { int x, y; } n = {10, 20};\n"
+ "dummyStatement(&v, &n);\n")
+ % Check("v", "", "{...}")
+ % Check("n", "", "S")
+ % Check("v.a", "2", "int")
+ % Check("v.b", "3", "int")
+ % Check("v.x", "1", "int")
+ % Check("n.x", "10", "int")
+ % Check("n.y", "20", "int");
}
@@ -2507,4 +3956,3 @@ int main(int argc, char *argv[])
}
#include "tst_dumpers.moc"
-
diff --git a/tests/auto/debugger/tst_gdb.cpp b/tests/auto/debugger/tst_gdb.cpp
index 347832e378..6367c9cba6 100644
--- a/tests/auto/debugger/tst_gdb.cpp
+++ b/tests/auto/debugger/tst_gdb.cpp
@@ -36,7 +36,7 @@ bool checkUninitialized = false;
#define DO_DEBUG 1
//TESTED_COMPONENT=src/plugins/debugger/gdb
-#include "gdb/gdbmi.h"
+#include "debuggerprotocol.h"
#ifdef QT_GUI_LIB
#include <QBitmap>
@@ -97,6 +97,14 @@ QString gdbBinary = "c:\\MinGw\\bin\\gdb.exe";
QString gdbBinary = "gdb";
#endif
+#if QT_VERSION >= 0x050000
+#define MSKIP_SINGLE(x) QSKIP(x)
+#define MSKIP_ALL(x) QSKIP(x);
+#else
+#define MSKIP_SINGLE(x) QSKIP(x, SkipSingle)
+#define MSKIP_ALL(x) QSKIP(x, SkipAll)
+#endif
+
void nothing() {}
template <typename T> QByteArray N(T v) { return QByteArray::number(v); }
@@ -329,11 +337,13 @@ QByteArray str(const void *p)
void tst_Gdb::dumperCompatibility()
{
+#ifdef Q_OS_MACX
// Ensure that no arbitrary padding is introduced by QVectorTypedData.
const size_t qVectorDataSize = 16;
QCOMPARE(sizeof(QVectorData), qVectorDataSize);
QVectorTypedData<int> *v = 0;
QCOMPARE(size_t(&v->array), qVectorDataSize);
+#endif
}
static const QByteArray utfToHex(const QString &string)
@@ -369,7 +379,7 @@ GdbWrapper::GdbWrapper(tst_Gdb *test) : m_test(test)
{
qWarning() << "SETUP START\n\n";
#ifndef Q_CC_GNU
- QSKIP("gdb test not applicable for compiler", SkipAll);
+ MSKIP_ALL("gdb test not applicable for compiler");
#endif
//qDebug() << "\nRUN" << getpid() << gettid();
QStringList args;
@@ -381,7 +391,7 @@ GdbWrapper::GdbWrapper(tst_Gdb *test) : m_test(test)
if (!m_proc.waitForStarted()) {
const QString msg = QString::fromLatin1("Unable to run %1: %2")
.arg(gdbBinary, m_proc.errorString());
- QSKIP(msg.toLatin1().constData(), SkipAll);
+ MSKIP_ALL(msg.toLatin1().constData());
}
connect(&m_proc, SIGNAL(error(QProcess::ProcessError)),
@@ -540,7 +550,7 @@ void tst_Gdb::initTestCase()
if (!file.open(QIODevice::ReadOnly)) {
const QString msg = QString::fromLatin1("Unable to open %1: %2")
.arg(fileName, file.errorString());
- QSKIP(msg.toLatin1().constData(), SkipAll);
+ MSKIP_ALL(msg.toLatin1().constData());
}
QByteArray funcName;
diff --git a/tests/auto/debugger/tst_namedemangler.cpp b/tests/auto/debugger/tst_namedemangler.cpp
index c7eeb303ee..7622b29976 100644
--- a/tests/auto/debugger/tst_namedemangler.cpp
+++ b/tests/auto/debugger/tst_namedemangler.cpp
@@ -34,7 +34,7 @@
#define TEST_CORRECTLY_MANGLED_NAME(mangled, expectedDemangled) \
do { \
- QVERIFY2(demangler.demangle(mangled), qPrintable(demangler.errorString())); \
+ QVERIFY2(demangler.demangle(QLatin1String(mangled)), qPrintable(demangler.errorString())); \
QCOMPARE(demangler.demangledName(), QLatin1String(expectedDemangled)); \
} while (0)
@@ -58,7 +58,8 @@ private:
void NameDemanglerAutoTest::testUnmangledName()
{
- QVERIFY(demangler.demangle("f") && demangler.demangledName() == "f");
+ QVERIFY(demangler.demangle(QLatin1String("f"))
+ && demangler.demangledName() == QLatin1String("f"));
}
void NameDemanglerAutoTest::testCorrectlyMangledNames()
diff --git a/tests/auto/debugger/tst_olddumpers.cpp b/tests/auto/debugger/tst_olddumpers.cpp
new file mode 100644
index 0000000000..ab38245301
--- /dev/null
+++ b/tests/auto/debugger/tst_olddumpers.cpp
@@ -0,0 +1,2510 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#define private public // Give us access to private 'backward' member of QMapNode.
+# include <QMap>
+#undef private
+
+#include "gdb/gdbmi.h"
+#include "dumper.h"
+#include "dumper_p.h"
+
+#include "json.h"
+
+#ifdef USE_PRIVATE
+#include <private/qobject_p.h>
+#else
+#warning "No private headers for this Qt version available"
+#endif
+
+#include <QStandardItemModel>
+#include <QStringListModel>
+
+#include <QtTest>
+//#include <QtTest/qtest_gui.h>
+
+//TESTED_COMPONENT=src/plugins/debugger/gdb
+
+static const char *pointerPrintFormat()
+{
+ return sizeof(quintptr) == sizeof(long) ? "0x%lx" : "0x%llx";
+}
+
+#undef NS
+#ifdef QT_NAMESPACE
+# define STRINGIFY0(s) #s
+# define STRINGIFY1(s) STRINGIFY0(s)
+# define NS STRINGIFY1(QT_NAMESPACE) "::"
+#else
+# define NS ""
+#endif
+
+using namespace Debugger;
+using namespace Debugger::Internal;
+
+static QByteArray operator<<(QByteArray ba, const QByteArray &replacement)
+{
+ int pos = ba.indexOf('%');
+ Q_ASSERT(pos != -1);
+ return ba.replace(pos, 1, replacement);
+}
+
+static QByteArray &operator<<=(QByteArray &ba, const QByteArray &replacement)
+{
+ int pos = ba.indexOf('%');
+ Q_ASSERT(pos != -1);
+ return ba.replace(pos, 1, replacement);
+}
+
+
+template <typename T>
+inline QByteArray N(T t) { return QByteArray::number(t); }
+
+static const char gdbmi1[] =
+ "[frame={level=\"0\",addr=\"0x00000000004061ca\","
+ "func=\"main\",file=\"test1.cpp\","
+ "fullname=\"/home/apoenitz/work/test1/test1.cpp\",line=\"209\"}]";
+
+static const char gdbmi2[] =
+ "[frame={level=\"0\",addr=\"0x00002ac058675840\","
+ "func=\"QApplication\",file=\"/home/apoenitz/dev/qt/src/gui/kernel/qapplication.cpp\","
+ "fullname=\"/home/apoenitz/dev/qt/src/gui/kernel/qapplication.cpp\",line=\"592\"},"
+ "frame={level=\"1\",addr=\"0x00000000004061e0\",func=\"main\",file=\"test1.cpp\","
+ "fullname=\"/home/apoenitz/work/test1/test1.cpp\",line=\"209\"}]";
+
+static const char gdbmi3[] =
+ "[stack={frame={level=\"0\",addr=\"0x00000000004061ca\","
+ "func=\"main\",file=\"test1.cpp\","
+ "fullname=\"/home/apoenitz/work/test1/test1.cpp\",line=\"209\"}}]";
+
+static const char gdbmi4[] =
+ "&\"source /home/apoenitz/dev/ide/main/bin/gdb/qt4macros\\n\""
+ "4^done\n";
+
+static const char gdbmi5[] =
+ "[reason=\"breakpoint-hit\",bkptno=\"1\",thread-id=\"1\","
+ "frame={addr=\"0x0000000000405738\",func=\"main\","
+ "args=[{name=\"argc\",value=\"1\"},{name=\"argv\",value=\"0x7fff1ac78f28\"}],"
+ "file=\"test1.cpp\",fullname=\"/home/apoenitz/work/test1/test1.cpp\","
+ "line=\"209\"}]";
+
+static const char gdbmi8[] =
+ "[data={locals={{name=\"a\"},{name=\"w\"}}}]";
+
+static const char gdbmi9[] =
+ "[data={locals=[name=\"baz\",name=\"urgs\",name=\"purgs\"]}]";
+
+static const char gdbmi10[] =
+ "[name=\"urgs\",numchild=\"1\",type=\"Urgs\"]";
+
+static const char gdbmi11[] =
+ "[{name=\"size\",value=\"1\",type=\"size_t\",readonly=\"true\"},"
+ "{name=\"0\",value=\"one\",type=\"QByteArray\"}]";
+
+static const char gdbmi12[] =
+ "[{iname=\"local.hallo\",value=\"\\\"\\\\\\00382\\t\\377\",type=\"QByteArray\","
+ "numchild=\"0\"}]";
+
+
+static const char jsont1[] =
+ "{\"Size\":100564,\"UID\":0,\"GID\":0,\"Permissions\":33261,"
+ "\"ATime\":1242370878000,\"MTime\":1239154689000}";
+
+struct Int3 {
+ Int3() { i1 = 42; i2 = 43; i3 = 44; }
+ int i1, i2, i3;
+};
+
+struct QString3 {
+ QString3() { s1 = "a"; s2 = "b"; s3 = "c"; }
+ QString s1, s2, s3;
+};
+
+class tst_Dumpers : public QObject
+{
+ Q_OBJECT
+
+public:
+ tst_Dumpers() {}
+
+ void testMi(const char* input)
+ {
+ GdbMi gdbmi;
+ gdbmi.fromString(QByteArray(input));
+ QCOMPARE('\n' + QString::fromLatin1(gdbmi.toString(false)),
+ '\n' + QString(input));
+ }
+
+ void testJson(const char* input)
+ {
+ QCOMPARE('\n' + Utils::JsonStringValue(QLatin1String(input)).value(),
+ '\n' + QString(input));
+ }
+
+private slots:
+ void mi1() { testMi(gdbmi1); }
+ void mi2() { testMi(gdbmi2); }
+ void mi3() { testMi(gdbmi3); }
+ //void mi4() { testMi(gdbmi4); }
+ void mi5() { testMi(gdbmi5); }
+ void mi8() { testMi(gdbmi8); }
+ void mi9() { testMi(gdbmi9); }
+ void mi10() { testMi(gdbmi10); }
+ void mi11() { testMi(gdbmi11); }
+ //void mi12() { testMi(gdbmi12); }
+
+ void json1() { testJson(jsont1); }
+
+ void infoBreak();
+ void niceType();
+ void niceType_data();
+
+ void dumperCompatibility();
+ void dumpQAbstractItemAndModelIndex();
+ void dumpQAbstractItemModel();
+ void dumpQByteArray();
+ void dumpQChar();
+ void dumpQDateTime();
+ void dumpQDir();
+ void dumpQFile();
+ void dumpQFileInfo();
+ void dumpQHash();
+ void dumpQHashNode();
+ void dumpQImage();
+ void dumpQImageData();
+ void dumpQLinkedList();
+ void dumpQList_int();
+ void dumpQList_int_star();
+ void dumpQList_char();
+ void dumpQList_QString();
+ void dumpQList_QString3();
+ void dumpQList_Int3();
+ void dumpQLocale();
+ void dumpQMap();
+ void dumpQMapNode();
+#ifdef USE_PRIVATE
+ void dumpQObject();
+ void dumpQObjectChildList();
+ void dumpQObjectMethodList();
+ void dumpQObjectPropertyList();
+ void dumpQObjectSignal();
+ void dumpQObjectSignalList();
+ void dumpQObjectSlot();
+ void dumpQObjectSlotList();
+#endif
+ void dumpQPixmap();
+ void dumpQSharedPointer();
+ void dumpQString();
+ void dumpQTextCodec();
+ void dumpQVariant_invalid();
+ void dumpQVariant_QString();
+ void dumpQVariant_QStringList();
+#ifndef Q_CC_MSVC
+ void dumpStdVector();
+#endif // !Q_CC_MSVC
+ void dumpQWeakPointer();
+ void initTestCase();
+
+private:
+ void dumpQAbstractItemHelper(QModelIndex &index);
+ void dumpQAbstractItemModelHelper(QAbstractItemModel &m);
+ template <typename K, typename V> void dumpQHashNodeHelper(QHash<K, V> &hash);
+ void dumpQImageHelper(const QImage &img);
+ void dumpQImageDataHelper(QImage &img);
+ template <typename T> void dumpQLinkedListHelper(QLinkedList<T> &l);
+ void dumpQLocaleHelper(QLocale &loc);
+ template <typename K, typename V> void dumpQMapHelper(QMap<K, V> &m);
+ template <typename K, typename V> void dumpQMapNodeHelper(QMap<K, V> &m);
+ void dumpQObjectChildListHelper(QObject &o);
+ void dumpQObjectSignalHelper(QObject &o, int sigNum);
+#if QT_VERSION >= 0x040500
+ template <typename T>
+ void dumpQSharedPointerHelper(QSharedPointer<T> &ptr);
+ template <typename T>
+ void dumpQWeakPointerHelper(QWeakPointer<T> &ptr);
+#endif
+ void dumpQTextCodecHelper(QTextCodec *codec);
+};
+
+void tst_Dumpers::infoBreak()
+{
+ // This tests the regular expression used in GdbEngine::extractDataFromInfoBreak
+ // to discover breakpoints in constructors.
+
+ // Copied from gdbengine.cpp:
+
+ QRegExp re("MULTIPLE.*(0x[0-9a-f]+) in (.*)\\s+at (.*):([\\d]+)([^\\d]|$)");
+ re.setMinimal(true);
+
+ QCOMPARE(re.indexIn(
+ "2 breakpoint keep y <MULTIPLE> 0x0040168e\n"
+ "2.1 y 0x0040168e "
+ "in MainWindow::MainWindow(QWidget*) at mainwindow.cpp:7\n"
+ "2.2 y 0x00401792 "
+ "in MainWindow::MainWindow(QWidget*) at mainwindow.cpp:7\n"), 33);
+ QCOMPARE(re.cap(1), QString("0x0040168e"));
+ QCOMPARE(re.cap(2).trimmed(), QString("MainWindow::MainWindow(QWidget*)"));
+ QCOMPARE(re.cap(3), QString("mainwindow.cpp"));
+ QCOMPARE(re.cap(4), QString("7"));
+
+
+ QCOMPARE(re.indexIn(
+ "Num Type Disp Enb Address What"
+ "4 breakpoint keep y <MULTIPLE> 0x00000000004066ad"
+ "4.1 y 0x00000000004066ad in CTorTester"
+ " at /main/tests/manual/gdbdebugger/simple/app.cpp:124"), 88);
+
+ QCOMPARE(re.cap(1), QString("0x00000000004066ad"));
+ QCOMPARE(re.cap(2).trimmed(), QString("CTorTester"));
+ QCOMPARE(re.cap(3), QString("/main/tests/manual/gdbdebugger/simple/app.cpp"));
+ QCOMPARE(re.cap(4), QString("124"));
+}
+
+//
+// type simplification
+//
+
+static QString chopConst(QString type)
+{
+ while (1) {
+ if (type.startsWith("const"))
+ type = type.mid(5);
+ else if (type.startsWith(' '))
+ type = type.mid(1);
+ else if (type.endsWith("const"))
+ type.chop(5);
+ else if (type.endsWith(' '))
+ type.chop(1);
+ else
+ break;
+ }
+ return type;
+}
+
+QString niceType(QString type)
+{
+ type.replace('*', '@');
+
+ for (int i = 0; i < 10; ++i) {
+ int start = type.indexOf("std::allocator<");
+ if (start == -1)
+ break;
+ // search for matching '>'
+ int pos;
+ int level = 0;
+ for (pos = start + 12; pos < type.size(); ++pos) {
+ int c = type.at(pos).unicode();
+ if (c == '<') {
+ ++level;
+ } else if (c == '>') {
+ --level;
+ if (level == 0)
+ break;
+ }
+ }
+ QString alloc = type.mid(start, pos + 1 - start).trimmed();
+ QString inner = alloc.mid(15, alloc.size() - 16).trimmed();
+ //qDebug() << "MATCH: " << pos << alloc << inner;
+
+ if (inner == QLatin1String("char"))
+ // std::string
+ type.replace(QLatin1String("basic_string<char, std::char_traits<char>, "
+ "std::allocator<char> >"), QLatin1String("string"));
+ else if (inner == QLatin1String("wchar_t"))
+ // std::wstring
+ type.replace(QLatin1String("basic_string<wchar_t, std::char_traits<wchar_t>, "
+ "std::allocator<wchar_t> >"), QLatin1String("wstring"));
+
+ // std::vector, std::deque, std::list
+ QRegExp re1(QString("(vector|list|deque)<%1, %2\\s*>").arg(inner, alloc));
+ if (re1.indexIn(type) != -1)
+ type.replace(re1.cap(0), QString("%1<%2>").arg(re1.cap(1), inner));
+
+
+ // std::stack
+ QRegExp re6(QString("stack<%1, std::deque<%2> >").arg(inner, inner));
+ re6.setMinimal(true);
+ if (re6.indexIn(type) != -1)
+ type.replace(re6.cap(0), QString("stack<%1>").arg(inner));
+
+ // std::set
+ QRegExp re4(QString("set<%1, std::less<%2>, %3\\s*>").arg(inner, inner, alloc));
+ re4.setMinimal(true);
+ if (re4.indexIn(type) != -1)
+ type.replace(re4.cap(0), QString("set<%1>").arg(inner));
+
+
+ // std::map
+ if (inner.startsWith("std::pair<")) {
+ // search for outermost ','
+ int pos;
+ int level = 0;
+ for (pos = 10; pos < inner.size(); ++pos) {
+ int c = inner.at(pos).unicode();
+ if (c == '<')
+ ++level;
+ else if (c == '>')
+ --level;
+ else if (c == ',' && level == 0)
+ break;
+ }
+ QString ckey = inner.mid(10, pos - 10);
+ QString key = chopConst(ckey);
+ QString value = inner.mid(pos + 2, inner.size() - 3 - pos);
+
+ QRegExp re5(QString("map<%1, %2, std::less<%3>, %4\\s*>")
+ .arg(key, value, key, alloc));
+ re5.setMinimal(true);
+ if (re5.indexIn(type) != -1)
+ type.replace(re5.cap(0), QString("map<%1, %2>").arg(key, value));
+ else {
+ QRegExp re7(QString("map<const %1, %2, std::less<const %3>, %4\\s*>")
+ .arg(key, value, key, alloc));
+ re7.setMinimal(true);
+ if (re7.indexIn(type) != -1)
+ type.replace(re7.cap(0), QString("map<const %1, %2>").arg(key, value));
+ }
+ }
+ }
+ type.replace('@', '*');
+ type.replace(QLatin1String(" >"), QString(QLatin1Char('>')));
+ return type;
+}
+
+void tst_Dumpers::niceType()
+{
+ // cf. watchutils.cpp
+ QFETCH(QString, input);
+ QFETCH(QString, simplified);
+ QCOMPARE(::niceType(input), simplified);
+}
+
+void tst_Dumpers::niceType_data()
+{
+ QTest::addColumn<QString>("input");
+ QTest::addColumn<QString>("simplified");
+
+ QTest::newRow("list")
+ << "std::list<int, std::allocator<int> >"
+ << "std::list<int>";
+
+ QTest::newRow("combined")
+ << "std::vector<std::list<int, std::allocator<int> >*, "
+ "std::allocator<std::list<int, std::allocator<int> >*> >"
+ << "std::vector<std::list<int>*>";
+
+ QTest::newRow("stack")
+ << "std::stack<int, std::deque<int, std::allocator<int> > >"
+ << "std::stack<int>";
+
+ QTest::newRow("map")
+ << "std::map<myns::QString, Foo, std::less<myns::QString>, "
+ "std::allocator<std::pair<const myns::QString, Foo> > >"
+ << "std::map<myns::QString, Foo>";
+
+ QTest::newRow("map2")
+ << "std::map<const char*, Foo, std::less<const char*>, "
+ "std::allocator<std::pair<const char* const, Foo> > >"
+ << "std::map<const char*, Foo>";
+}
+
+//
+// Dumpers
+//
+
+static void testDumper(QByteArray expected0, const void *data, QByteArray outertype,
+ bool dumpChildren, QByteArray innertype = "", QByteArray exp = "",
+ int extraInt0 = 0, int extraInt1 = 0, int extraInt2 = 0, int extraInt3 = 0)
+{
+ sprintf(xDumpInBuffer, "%s%c%s%c%s%c%s%c%s%c",
+ outertype.data(), 0, "iname", 0, exp.data(), 0,
+ innertype.data(), 0, "iname", 0);
+ //qDebug() << "FIXME qDumpObjectData440 signature to use const void *";
+ void *res = qDumpObjectData440(2, 42, data, dumpChildren,
+ extraInt0, extraInt1, extraInt2, extraInt3);
+ QString expected(expected0);
+ char buf[100];
+ sprintf(buf, pointerPrintFormat(), (quintptr)data);
+ if ((!expected.startsWith('t') && !expected.startsWith('f'))
+ || expected.startsWith("type"))
+ expected = "tiname='$I',addr='$A'," + expected;
+ expected.replace("$I", "iname");
+ expected.replace("$T", QByteArray(outertype));
+ expected.replace("$A", QByteArray(buf));
+ expected.replace('\'', '"');
+ QString actual____ = QString::fromLatin1(xDumpOutBuffer);
+ actual____.replace('\'', '"');
+ QCOMPARE(res, xDumpOutBuffer);
+ if (actual____ != expected) {
+ QStringList l1 = actual____.split(",");
+ QStringList l2 = expected.split(",");
+ for (int i = 0; i < l1.size() && i < l2.size(); ++i) {
+ if (l1.at(i) == l2.at(i))
+ qWarning() << "== " << l1.at(i);
+ else
+ //qWarning() << "!= " << l1.at(i).right(30) << l2.at(i).right(30);
+ qWarning() << "!= " << l1.at(i) << l2.at(i);
+ }
+ if (l1.size() != l2.size())
+ qWarning() << "!= size: " << l1.size() << l2.size();
+ }
+ QCOMPARE(actual____, expected);
+}
+
+QByteArray str(const void *p)
+{
+ char buf[100];
+ sprintf(buf, pointerPrintFormat(), (quintptr)p);
+ return buf;
+}
+
+static const void *deref(const void *p)
+{
+ return *reinterpret_cast<const char* const*>(p);
+}
+
+void tst_Dumpers::dumperCompatibility()
+{
+ // Ensure that no arbitrary padding is introduced by QVectorTypedData.
+ const size_t qVectorDataSize = 16;
+ QCOMPARE(sizeof(QVectorData), qVectorDataSize);
+ QVectorTypedData<int> *v = 0;
+ QCOMPARE(size_t(&v->array), qVectorDataSize);
+}
+
+static const QByteArray utfToBase64(const QString &string)
+{
+ return QByteArray(reinterpret_cast<const char *>(string.utf16()), 2 * string.size()).toBase64();
+}
+
+static const char *boolToVal(bool b)
+{
+ return b ? "'true'" : "'false'";
+}
+
+static const QByteArray ptrToBa(const void *p, bool symbolicNull = true)
+{
+ return QByteArray().append(p == 0 && symbolicNull ?
+ "<null>" :
+ QByteArray("0x") + QByteArray::number((quintptr) p, 16));
+}
+
+static const QByteArray generateQStringSpec(const QString &str, bool isNull = false)
+{
+ if (isNull)
+ return QByteArray("value='IiIgKG51bGwp',valueencoded='5',"
+ "type='" NS "QString',numchild='0'");
+ return
+ QByteArray("value='%',valueencoded='2',type='" NS "QString',numchild='0'")
+ << utfToBase64(str);
+}
+
+static const QByteArray generateQCharSpec(const QChar& ch)
+{
+ return QByteArray("value='%',valueencoded='2',type='" NS "QChar',numchild='0'")
+ << utfToBase64(QString(QLatin1String("'%1' (%2, 0x%3)")).
+ arg(ch).arg(ch.unicode()).arg(ch.unicode(), 0, 16));
+}
+
+static const QByteArray generateBoolSpec(bool b)
+{
+ return QByteArray("value=%,type='bool',numchild='0'")
+ << boolToVal(b);
+}
+
+static const QByteArray generateLongSpec(long n)
+{
+ return QByteArray("value='%',type='long',numchild='0'")
+ << N(qlonglong(n));
+}
+
+static const QByteArray generateIntSpec(int n)
+{
+ return QByteArray("value='%',type='int',numchild='0'")
+ << N(n);
+}
+
+const QByteArray createExp(const void *ptr,
+ const QByteArray &type, const QByteArray &method)
+{
+ return QByteArray("exp='((" NSX "%" NSY "*)%)->%'")
+ << type << ptrToBa(ptr) << method;
+}
+
+// Helper functions.
+
+template <typename T> static const char *typeToString()
+{
+ return "<unknown type>";
+}
+template <typename T> const QByteArray valToString(const T &)
+{
+ return "<unknown value>";
+}
+template <> const QByteArray valToString(const int &n)
+{
+ return QByteArray().append(N(n));
+}
+template <> const QByteArray valToString(const QString &s)
+{
+ return QByteArray(utfToBase64(s)).append("',valueencoded='2");
+}
+template <> const QByteArray valToString(int * const &p)
+{
+ return ptrToBa(p);
+}
+template <typename T> const QByteArray derefValToString(const T &v)
+{
+ return valToString(v);
+}
+template <> const QByteArray derefValToString(int * const &ptr)
+{
+ return valToString(*ptr);
+}
+const QString stripPtrType(const QString &ptrTypeStr)
+{
+ return ptrTypeStr.mid(0, ptrTypeStr.size() - 2);
+}
+template <> const char *typeToString<int>()
+{
+ return "int";
+}
+template <> const char *typeToString<QString>()
+{
+ return NS"QString";
+}
+template <> const char *typeToString<int *>()
+{
+ return "int *";
+}
+template <typename T> bool isSimpleType()
+{
+ return false;
+}
+template <> bool isSimpleType<int>()
+{
+ return true;
+}
+template <typename T> bool isPointer()
+{
+ return false;
+}
+template <> bool isPointer<int *>()
+{
+ return true;
+}
+
+template <typename T> static const char *typeToNumchild()
+{
+ return "1";
+}
+template <> const char *typeToNumchild<int>()
+{
+ return "0";
+}
+template <> const char *typeToNumchild<QString>()
+{
+ return "0";
+}
+template <typename K, typename V>
+QByteArray getMapType()
+{
+ return QByteArray(typeToString<K>()) + "@" + QByteArray(typeToString<V>());
+}
+template <typename K, typename V>
+void getMapNodeParams(size_t &nodeSize, size_t &valOffset)
+{
+#if QT_VERSION >= 0x040500
+ typedef QMapNode<K, V> NodeType;
+ NodeType *node = 0;
+ nodeSize = sizeof(NodeType);
+ valOffset = size_t(&node->value);
+#else
+ nodeSize = sizeof(K) + sizeof(V) + 2*sizeof(void *);
+ valOffset = sizeof(K);
+#endif
+}
+
+void tst_Dumpers::dumpQAbstractItemHelper(QModelIndex &index)
+{
+ const QAbstractItemModel *model = index.model();
+ const QString &rowStr = N(index.row());
+ const QString &colStr = N(index.column());
+ const QByteArray &internalPtrStrSymbolic = ptrToBa(index.internalPointer());
+ const QByteArray &internalPtrStrValue = ptrToBa(index.internalPointer(), false);
+ const QByteArray &modelPtrStr = ptrToBa(model);
+ QByteArray indexSpecSymbolic = QByteArray().append(rowStr + "," + colStr + ",").
+ append(internalPtrStrSymbolic + "," + modelPtrStr);
+ QByteArray indexSpecValue = QByteArray().append(rowStr + "," + colStr + ",").
+ append(internalPtrStrValue + "," + modelPtrStr);
+ QByteArray expected = QByteArray("tiname='iname',addr='").append(ptrToBa(&index)).
+ append("',type='" NS "QAbstractItem',addr='$").append(indexSpecSymbolic).
+ append("',value='").append(valToString(model->data(index).toString())).
+ append("',numchild='%',children=[");
+ int rowCount = model->rowCount(index);
+ int columnCount = model->columnCount(index);
+ expected <<= N(rowCount * columnCount);
+ for (int row = 0; row < rowCount; ++row) {
+ for (int col = 0; col < columnCount; ++col) {
+ const QModelIndex &childIndex = model->index(row, col, index);
+ expected.append("{name='[").append(valToString(row)).append(",").
+ append(N(col)).append("]',numchild='%',addr='$").
+ append(N(childIndex.row())).append(",").
+ append(N(childIndex.column())).append(",").
+ append(ptrToBa(childIndex.internalPointer())).append(",").
+ append(modelPtrStr).append("',type='" NS "QAbstractItem',value='").
+ append(valToString(model->data(childIndex).toString())).append("'}");
+ expected <<= N(model->rowCount(childIndex)
+ * model->columnCount(childIndex));
+ if (col < columnCount - 1 || row < rowCount - 1)
+ expected.append(",");
+ }
+ }
+ expected.append("]");
+ testDumper(expected, &index, NS"QAbstractItem", true, indexSpecValue);
+}
+
+void tst_Dumpers::dumpQAbstractItemAndModelIndex()
+{
+ class PseudoTreeItemModel : public QAbstractItemModel
+ {
+ public:
+ PseudoTreeItemModel() : QAbstractItemModel(), parent1(0),
+ parent1Child(1), parent2(10), parent2Child1(11), parent2Child2(12)
+ {}
+
+ int columnCount(const QModelIndex &parent = QModelIndex()) const
+ {
+ Q_UNUSED(parent);
+ return 1;
+ }
+
+ QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const
+ {
+ return !index.isValid() || role != Qt::DisplayRole ?
+ QVariant() : *static_cast<int *>(index.internalPointer());
+ }
+
+ QModelIndex index(int row, int column,
+ const QModelIndex & parent = QModelIndex()) const
+ {
+ QModelIndex index;
+ if (column == 0) {
+ if (!parent.isValid()) {
+ if (row == 0)
+ index = createIndex(row, column, &parent1);
+ else if (row == 1)
+ index = createIndex(row, column, &parent2);
+ } else if (parent.internalPointer() == &parent1 && row == 0) {
+ index = createIndex(row, column, &parent1Child);
+ } else if (parent.internalPointer() == &parent2) {
+ index = createIndex(row, column,
+ row == 0 ? &parent2Child1 : &parent2Child2);
+ }
+ }
+ return index;
+ }
+
+ QModelIndex parent(const QModelIndex & index) const
+ {
+ QModelIndex parent;
+ if (index.isValid()) {
+ if (index.internalPointer() == &parent1Child)
+ parent = createIndex(0, 0, &parent1);
+ else if (index.internalPointer() == &parent2Child1 ||
+ index.internalPointer() == &parent2Child2)
+ parent = createIndex(1, 0, &parent2);
+ }
+ return parent;
+ }
+
+ int rowCount(const QModelIndex &parent = QModelIndex()) const
+ {
+ int rowCount;
+ if (!parent.isValid() || parent.internalPointer() == &parent2)
+ rowCount = 2;
+ else if (parent.internalPointer() == &parent1)
+ rowCount = 1;
+ else
+ rowCount = 0;
+ return rowCount;
+ }
+
+ private:
+ mutable int parent1;
+ mutable int parent1Child;
+ mutable int parent2;
+ mutable int parent2Child1;
+ mutable int parent2Child2;
+ };
+
+ PseudoTreeItemModel m2;
+
+ // Case 1: ModelIndex with no children.
+ QStringListModel m(QStringList() << "item1" << "item2" << "item3");
+ QModelIndex index = m.index(2, 0);
+
+ testDumper(QByteArray("type='$T',value='(2, 0)',numchild='5',children=["
+ "{name='row',value='2',type='int',numchild='0'},"
+ "{name='column',value='0',type='int',numchild='0'},"
+ "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
+ "type='$T',numchild='1'},"
+ "{name='internalId',%},"
+ "{name='model',value='%',type='" NS "QAbstractItemModel*',"
+ "numchild='1'}]")
+ << generateQStringSpec(N(index.internalId()))
+ << ptrToBa(&m),
+ &index, NS"QModelIndex", true);
+
+ // Case 2: ModelIndex with one child.
+ QModelIndex index2 = m2.index(0, 0);
+ dumpQAbstractItemHelper(index2);
+
+ qDebug() << "FIXME: invalid indices should not have children";
+ testDumper(QByteArray("type='$T',value='(0, 0)',numchild='5',children=["
+ "{name='row',value='0',type='int',numchild='0'},"
+ "{name='column',value='0',type='int',numchild='0'},"
+ "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
+ "type='$T',numchild='1'},"
+ "{name='internalId',%},"
+ "{name='model',value='%',type='" NS "QAbstractItemModel*',"
+ "numchild='1'}]")
+ << generateQStringSpec(N(index2.internalId()))
+ << ptrToBa(&m2),
+ &index2, NS"QModelIndex", true);
+
+
+ // Case 3: ModelIndex with two children.
+ QModelIndex index3 = m2.index(1, 0);
+ dumpQAbstractItemHelper(index3);
+
+ testDumper(QByteArray("type='$T',value='(1, 0)',numchild='5',children=["
+ "{name='row',value='1',type='int',numchild='0'},"
+ "{name='column',value='0',type='int',numchild='0'},"
+ "{name='parent',value='<invalid>',exp='(('$T'*)$A)->parent()',"
+ "type='$T',numchild='1'},"
+ "{name='internalId',%},"
+ "{name='model',value='%',type='" NS "QAbstractItemModel*',"
+ "numchild='1'}]")
+ << generateQStringSpec(N(index3.internalId()))
+ << ptrToBa(&m2),
+ &index3, NS"QModelIndex", true);
+
+
+ // Case 4: ModelIndex with a parent.
+ index = m2.index(0, 0, index3);
+ testDumper(QByteArray("type='$T',value='(0, 0)',numchild='5',children=["
+ "{name='row',value='0',type='int',numchild='0'},"
+ "{name='column',value='0',type='int',numchild='0'},"
+ "{name='parent',value='(1, 0)',exp='(('$T'*)$A)->parent()',"
+ "type='$T',numchild='1'},"
+ "{name='internalId',%},"
+ "{name='model',value='%',type='" NS "QAbstractItemModel*',"
+ "numchild='1'}]")
+ << generateQStringSpec(N(index.internalId()))
+ << ptrToBa(&m2),
+ &index, NS"QModelIndex", true);
+
+
+ // Case 5: Empty ModelIndex
+ QModelIndex index4;
+ testDumper("type='$T',value='<invalid>',numchild='0'",
+ &index4, NS"QModelIndex", true);
+}
+
+void tst_Dumpers::dumpQAbstractItemModelHelper(QAbstractItemModel &m)
+{
+ QByteArray address = ptrToBa(&m);
+ QByteArray expected = QByteArray("tiname='iname',addr='%',"
+ "type='" NS "QAbstractItemModel',value='(%,%)',numchild='1',children=["
+ "{numchild='1',name='" NS "QObject',addr='%',value='%',"
+ "valueencoded='2',type='" NS "QObject',displayedtype='%'}")
+ << address
+ << N(m.rowCount())
+ << N(m.columnCount())
+ << address
+ << utfToBase64(m.objectName())
+ << m.metaObject()->className();
+
+ for (int row = 0; row < m.rowCount(); ++row) {
+ for (int column = 0; column < m.columnCount(); ++column) {
+ QModelIndex mi = m.index(row, column);
+ expected.append(QByteArray(",{name='[%,%]',value='%',"
+ "valueencoded='2',numchild='%',addr='$%,%,%,%',"
+ "type='" NS "QAbstractItem'}")
+ << N(row)
+ << N(column)
+ << utfToBase64(m.data(mi).toString())
+ << N(row * column)
+ << N(mi.row())
+ << N(mi.column())
+ << ptrToBa(mi.internalPointer())
+ << ptrToBa(mi.model()));
+ }
+ }
+ expected.append("]");
+ testDumper(expected, &m, NS"QAbstractItemModel", true);
+}
+
+void tst_Dumpers::dumpQAbstractItemModel()
+{
+ // Case 1: No rows, one column.
+ QStringList strList;
+ QStringListModel model(strList);
+ dumpQAbstractItemModelHelper(model);
+
+ // Case 2: One row, one column.
+ strList << "String 1";
+ model.setStringList(strList);
+ dumpQAbstractItemModelHelper(model);
+
+ // Case 3: Two rows, one column.
+ strList << "String 2";
+ model.setStringList(strList);
+ dumpQAbstractItemModelHelper(model);
+
+ // Case 4: No rows, two columns.
+ QStandardItemModel model2(0, 2);
+ dumpQAbstractItemModelHelper(model2);
+
+ // Case 5: One row, two columns.
+ QStandardItem item1("Item (0,0)");
+ QStandardItem item2("(Item (0,1)");
+ model2.appendRow(QList<QStandardItem *>() << &item1 << &item2);
+ dumpQAbstractItemModelHelper(model2);
+
+ // Case 6: Two rows, two columns
+ QStandardItem item3("Item (1,0");
+ QStandardItem item4("Item (1,1)");
+ model2.appendRow(QList<QStandardItem *>() << &item3 << &item4);
+ dumpQAbstractItemModelHelper(model);
+}
+
+void tst_Dumpers::dumpQByteArray()
+{
+ // Case 1: Empty object.
+ QByteArray ba;
+ testDumper("value='',valueencoded='1',type='" NS "QByteArray',numchild='0',"
+ "childtype='char',childnumchild='0',children=[]",
+ &ba, NS"QByteArray", true);
+
+ // Case 2: One element.
+ ba.append('a');
+ testDumper("value='YQ==',valueencoded='1',type='" NS "QByteArray',numchild='1',"
+ "childtype='char',childnumchild='0',children=[{value='61 (97 'a')'}]",
+ &ba, NS"QByteArray", true);
+
+ // Case 3: Two elements.
+ ba.append('b');
+ testDumper("value='YWI=',valueencoded='1',type='" NS "QByteArray',numchild='2',"
+ "childtype='char',childnumchild='0',children=["
+ "{value='61 (97 'a')'},{value='62 (98 'b')'}]",
+ &ba, NS"QByteArray", true);
+
+ // Case 4: > 100 elements.
+ ba = QByteArray(101, 'a');
+ QByteArray children;
+ for (int i = 0; i < 101; i++)
+ children.append("{value='61 (97 'a')'},");
+ children.chop(1);
+ testDumper(QByteArray("value='YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"
+ "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"
+ "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ== <size: 101, cut...>',"
+ "valueencoded='1',type='" NS "QByteArray',numchild='101',"
+ "childtype='char',childnumchild='0',children=[%]") << children,
+ &ba, NS"QByteArray", true);
+
+ // Case 5: Regular and special characters and the replacement character.
+ ba = QByteArray("abc\a\n\r\033\'\"?");
+ testDumper("value='YWJjBwoNGyciPw==',valueencoded='1',type='" NS "QByteArray',"
+ "numchild='10',childtype='char',childnumchild='0',children=["
+ "{value='61 (97 'a')'},{value='62 (98 'b')'},"
+ "{value='63 (99 'c')'},{value='07 (7 '?')'},"
+ "{value='0a (10 '?')'},{value='0d (13 '?')'},"
+ "{value='1b (27 '?')'},{value='27 (39 '?')'},"
+ "{value='22 (34 '?')'},{value='3f (63 '?')'}]",
+ &ba, NS"QByteArray", true);
+}
+
+void tst_Dumpers::dumpQChar()
+{
+ // Case 1: Printable ASCII character.
+ QChar c('X');
+ testDumper("value=''X', ucs=88',numchild='0'",
+ &c, NS"QChar", false);
+
+ // Case 2: Printable non-ASCII character.
+ c = QChar(0x600);
+ testDumper("value=''?', ucs=1536',numchild='0'",
+ &c, NS"QChar", false);
+
+ // Case 3: Non-printable ASCII character.
+ c = QChar::fromAscii('\a');
+ testDumper("value=''?', ucs=7',numchild='0'",
+ &c, NS"QChar", false);
+
+ // Case 4: Non-printable non-ASCII character.
+ c = QChar(0x9f);
+ testDumper("value=''?', ucs=159',numchild='0'",
+ &c, NS"QChar", false);
+
+ // Case 5: Printable ASCII Character that looks like the replacement character.
+ c = QChar::fromAscii('?');
+ testDumper("value=''?', ucs=63',numchild='0'",
+ &c, NS"QChar", false);
+}
+
+void tst_Dumpers::dumpQDateTime()
+{
+ // Case 1: Null object.
+ QDateTime d;
+ testDumper("value='(null)',type='$T',numchild='0'",
+ &d, NS"QDateTime", true);
+
+ // Case 2: Non-null object.
+ d = QDateTime::currentDateTime();
+ testDumper(QByteArray("value='%',valueencoded='2',"
+ "type='$T',numchild='1',children=["
+ "{name='toTime_t',%},"
+ "{name='toString',%},"
+ "{name='toString_(ISO)',%},"
+ "{name='toString_(SystemLocale)',%},"
+ "{name='toString_(Locale)',%}]")
+ << utfToBase64(d.toString())
+ << generateLongSpec((d.toTime_t()))
+ << generateQStringSpec(d.toString())
+ << generateQStringSpec(d.toString(Qt::ISODate))
+ << generateQStringSpec(d.toString(Qt::SystemLocaleDate))
+ << generateQStringSpec(d.toString(Qt::LocaleDate)),
+ &d, NS"QDateTime", true);
+
+}
+
+void tst_Dumpers::dumpQDir()
+{
+ // Case 1: Current working directory.
+ QDir dir = QDir::current();
+ testDumper(QByteArray("value='%',valueencoded='2',type='" NS "QDir',numchild='3',"
+ "children=[{name='absolutePath',%},{name='canonicalPath',%}]")
+ << utfToBase64(dir.absolutePath())
+ << generateQStringSpec(dir.absolutePath())
+ << generateQStringSpec(dir.canonicalPath()),
+ &dir, NS"QDir", true);
+
+ // Case 2: Root directory.
+ dir = QDir::root();
+ testDumper(QByteArray("value='%',valueencoded='2',type='" NS "QDir',numchild='3',"
+ "children=[{name='absolutePath',%},{name='canonicalPath',%}]")
+ << utfToBase64(dir.absolutePath())
+ << generateQStringSpec(dir.absolutePath())
+ << generateQStringSpec(dir.canonicalPath()),
+ &dir, NS"QDir", true);
+}
+
+
+void tst_Dumpers::dumpQFile()
+{
+ // Case 1: Empty file name => Does not exist.
+ QFile file1("");
+ testDumper(QByteArray("value='',valueencoded='2',type='$T',numchild='2',"
+ "children=[{name='fileName',value='',valueencoded='2',type='" NS "QString',"
+ "numchild='0'},"
+ "{name='exists',value='false',type='bool',numchild='0'}]"),
+ &file1, NS"QFile", true);
+
+ // Case 2: File that is known to exist.
+ QTemporaryFile file2;
+ file2.open();
+ testDumper(QByteArray("value='%',valueencoded='2',type='$T',numchild='2',"
+ "children=[{name='fileName',value='%',valueencoded='2',type='" NS "QString',"
+ "numchild='0'},"
+ "{name='exists',value='true',type='bool',numchild='0'}]")
+ << utfToBase64(file2.fileName()) << utfToBase64(file2.fileName()),
+ &file2, NS"QFile", true);
+
+ // Case 3: File with a name that most likely does not exist.
+ QFile file3("jfjfdskjdflsdfjfdls");
+ testDumper(QByteArray("value='%',valueencoded='2',type='$T',numchild='2',"
+ "children=[{name='fileName',value='%',valueencoded='2',type='" NS "QString',"
+ "numchild='0'},"
+ "{name='exists',value='false',type='bool',numchild='0'}]")
+ << utfToBase64(file3.fileName()) << utfToBase64(file3.fileName()),
+ &file3, NS"QFile", true);
+}
+
+void tst_Dumpers::dumpQFileInfo()
+{
+ QFileInfo fi(".");
+ QByteArray expected("value='%',valueencoded='2',type='$T',numchild='3',"
+ "children=["
+ "{name='absolutePath',%},"
+ "{name='absoluteFilePath',%},"
+ "{name='canonicalPath',%},"
+ "{name='canonicalFilePath',%},"
+ "{name='completeBaseName',%},"
+ "{name='completeSuffix',%},"
+ "{name='baseName',%},"
+#ifdef QX
+ "{name='isBundle',%},"
+ "{name='bundleName',%},"
+#endif
+ "{name='fileName',%},"
+ "{name='filePath',%},"
+ "{name='group',%},"
+ "{name='owner',%},"
+ "{name='path',%},"
+ "{name='groupid',%},"
+ "{name='ownerid',%},"
+ "{name='permissions',value=' ',type='%',numchild='10',"
+ "children=[{name='ReadOwner',%},{name='WriteOwner',%},"
+ "{name='ExeOwner',%},{name='ReadUser',%},{name='WriteUser',%},"
+ "{name='ExeUser',%},{name='ReadGroup',%},{name='WriteGroup',%},"
+ "{name='ExeGroup',%},{name='ReadOther',%},{name='WriteOther',%},"
+ "{name='ExeOther',%}]},"
+ "{name='caching',%},"
+ "{name='exists',%},"
+ "{name='isAbsolute',%},"
+ "{name='isDir',%},"
+ "{name='isExecutable',%},"
+ "{name='isFile',%},"
+ "{name='isHidden',%},"
+ "{name='isReadable',%},"
+ "{name='isRelative',%},"
+ "{name='isRoot',%},"
+ "{name='isSymLink',%},"
+ "{name='isWritable',%},"
+ "{name='created',value='%',valueencoded='2',%,"
+ "type='" NS "QDateTime',numchild='1'},"
+ "{name='lastModified',value='%',valueencoded='2',%,"
+ "type='" NS "QDateTime',numchild='1'},"
+ "{name='lastRead',value='%',valueencoded='2',%,"
+ "type='" NS "QDateTime',numchild='1'}]");
+ expected <<= utfToBase64(fi.filePath());
+ expected <<= generateQStringSpec(fi.absolutePath());
+ expected <<= generateQStringSpec(fi.absoluteFilePath());
+ expected <<= generateQStringSpec(fi.canonicalPath());
+ expected <<= generateQStringSpec(fi.canonicalFilePath());
+ expected <<= generateQStringSpec(fi.completeBaseName());
+ expected <<= generateQStringSpec(fi.completeSuffix(), true);
+ expected <<= generateQStringSpec(fi.baseName());
+#ifdef Q_OS_MACX
+ expected <<= generateBoolSpec(fi.isBundle());
+ expected <<= generateQStringSpec(fi.bundleName());
+#endif
+ expected <<= generateQStringSpec(fi.fileName());
+ expected <<= generateQStringSpec(fi.filePath());
+ expected <<= generateQStringSpec(fi.group());
+ expected <<= generateQStringSpec(fi.owner());
+ expected <<= generateQStringSpec(fi.path());
+ expected <<= generateLongSpec(fi.groupId());
+ expected <<= generateLongSpec(fi.ownerId());
+ QFile::Permissions perms = fi.permissions();
+ expected <<= QByteArray(NS"QFile::Permissions");
+ expected <<= generateBoolSpec((perms & QFile::ReadOwner) != 0);
+ expected <<= generateBoolSpec((perms & QFile::WriteOwner) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ExeOwner) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ReadUser) != 0);
+ expected <<= generateBoolSpec((perms & QFile::WriteUser) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ExeUser) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ReadGroup) != 0);
+ expected <<= generateBoolSpec((perms & QFile::WriteGroup) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ExeGroup) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ReadOther) != 0);
+ expected <<= generateBoolSpec((perms & QFile::WriteOther) != 0);
+ expected <<= generateBoolSpec((perms & QFile::ExeOther) != 0);
+ expected <<= generateBoolSpec(fi.caching());
+ expected <<= generateBoolSpec(fi.exists());
+ expected <<= generateBoolSpec(fi.isAbsolute());
+ expected <<= generateBoolSpec(fi.isDir());
+ expected <<= generateBoolSpec(fi.isExecutable());
+ expected <<= generateBoolSpec(fi.isFile());
+ expected <<= generateBoolSpec(fi.isHidden());
+ expected <<= generateBoolSpec(fi.isReadable());
+ expected <<= generateBoolSpec(fi.isRelative());
+ expected <<= generateBoolSpec(fi.isRoot());
+ expected <<= generateBoolSpec(fi.isSymLink());
+ expected <<= generateBoolSpec(fi.isWritable());
+ expected <<= utfToBase64(fi.created().toString());
+ expected <<= createExp(&fi, "QFileInfo", "created()");
+ expected <<= utfToBase64(fi.lastModified().toString());
+ expected <<= createExp(&fi, "QFileInfo", "lastModified()");
+ expected <<= utfToBase64(fi.lastRead().toString());
+ expected <<= createExp(&fi, "QFileInfo", "lastRead()");
+
+ testDumper(expected, &fi, NS"QFileInfo", true);
+}
+
+void tst_Dumpers::dumpQHash()
+{
+ QHash<QString, QList<int> > hash;
+ hash.insert("Hallo", QList<int>());
+ hash.insert("Welt", QList<int>() << 1);
+ hash.insert("!", QList<int>() << 1 << 2);
+ hash.insert("!", QList<int>() << 1 << 2);
+}
+
+template <typename K, typename V>
+void tst_Dumpers::dumpQHashNodeHelper(QHash<K, V> &hash)
+{
+ typename QHash<K, V>::iterator it = hash.begin();
+ typedef QHashNode<K, V> HashNode;
+ HashNode *dummy = 0;
+ HashNode *node =
+ reinterpret_cast<HashNode *>(reinterpret_cast<char *>(const_cast<K *>(&it.key())) -
+ size_t(&dummy->key));
+ const K &key = it.key();
+ const V &val = it.value();
+ QByteArray expected("value='");
+ if (isSimpleType<V>())
+ expected.append(valToString(val));
+ expected.append("',numchild='2',children=[{name='key',type='").
+ append(typeToString<K>()).append("',addr='").append(ptrToBa(&key)).
+ append("'},{name='value',type='").append(typeToString<V>()).
+ append("',addr='").append(ptrToBa(&val)).append("'}]");
+ testDumper(expected, node, NS"QHashNode", true,
+ getMapType<K, V>(), "", sizeof(it.key()), sizeof(it.value()));
+}
+
+void tst_Dumpers::dumpQHashNode()
+{
+ // Case 1: simple type -> simple type.
+ QHash<int, int> hash1;
+ hash1[2] = 3;
+ dumpQHashNodeHelper(hash1);
+
+ // Case 2: simple type -> composite type.
+ QHash<int, QString> hash2;
+ hash2[5] = "String 7";
+ dumpQHashNodeHelper(hash2);
+
+ // Case 3: composite type -> simple type
+ QHash<QString, int> hash3;
+ hash3["String 11"] = 13;
+ dumpQHashNodeHelper(hash3);
+
+ // Case 4: composite type -> composite type
+ QHash<QString, QString> hash4;
+ hash4["String 17"] = "String 19";
+ dumpQHashNodeHelper(hash4);
+}
+
+void tst_Dumpers::dumpQImageHelper(const QImage &img)
+{
+ QByteArray expected = "value='(%x%)',type='" NS "QImage',numchild='0'"
+ << N(img.width())
+ << N(img.height());
+ testDumper(expected, &img, NS"QImage", true);
+}
+
+void tst_Dumpers::dumpQImage()
+{
+ // Case 1: Null image.
+ QImage img;
+ dumpQImageHelper(img);
+
+ // Case 2: Normal image.
+ img = QImage(3, 700, QImage::Format_RGB555);
+ dumpQImageHelper(img);
+
+ // Case 3: Invalid image.
+ img = QImage(100, 0, QImage::Format_Invalid);
+ dumpQImageHelper(img);
+}
+
+void tst_Dumpers::dumpQImageDataHelper(QImage &img)
+{
+#if QT_VERSION >= 0x050000
+ QSKIP("QImage::numBytes deprecated");
+#else
+ const QByteArray ba(QByteArray::fromRawData((const char*) img.bits(), img.numBytes()));
+ QByteArray expected = QByteArray("tiname='$I',addr='$A',type='" NS "QImageData',").
+ append("numchild='0',value='<hover here>',valuetooltipencoded='1',").
+ append("valuetooltipsize='").append(N(ba.size())).append("',").
+ append("valuetooltip='").append(ba.toBase64()).append("'");
+ testDumper(expected, &img, NS"QImageData", false);
+#endif
+}
+
+void tst_Dumpers::dumpQImageData()
+{
+ // Case 1: Null image.
+ QImage img;
+ dumpQImageDataHelper(img);
+
+ // Case 2: Normal image.
+ img = QImage(3, 700, QImage::Format_RGB555);
+ dumpQImageDataHelper(img);
+
+ // Case 3: Invalid image.
+ img = QImage(100, 0, QImage::Format_Invalid);
+ dumpQImageDataHelper(img);
+}
+
+template <typename T>
+ void tst_Dumpers::dumpQLinkedListHelper(QLinkedList<T> &l)
+{
+ const int size = qMin(l.size(), 1000);
+ const QString &sizeStr = N(size);
+ const QByteArray elemTypeStr = typeToString<T>();
+ QByteArray expected = QByteArray("value='<").append(sizeStr).
+ append(" items>',valueeditable='false',numchild='").append(sizeStr).
+ append("',childtype='").append(elemTypeStr).append("',childnumchild='").
+ append(typeToNumchild<T>()).append("',children=[");
+ typename QLinkedList<T>::const_iterator iter = l.constBegin();
+ for (int i = 0; i < size; ++i, ++iter) {
+ expected.append("{");
+ const T &curElem = *iter;
+ if (isPointer<T>()) {
+ const QString typeStr = stripPtrType(typeToString<T>());
+ const QByteArray addrStr = valToString(curElem);
+ if (curElem != 0) {
+ expected.append("addr='").append(addrStr).append("',type='").
+ append(typeStr).append("',value='").
+ append(derefValToString(curElem)).append("'");
+ } else {
+ expected.append("addr='").append(ptrToBa(&curElem)).append("',type='").
+ append(typeStr).append("',value='<null>',numchild='0'");
+ }
+ } else {
+ expected.append("addr='").append(ptrToBa(&curElem)).
+ append("',value='").append(valToString(curElem)).append("'");
+ }
+ expected.append("}");
+ if (i < size - 1)
+ expected.append(",");
+ }
+ if (size < l.size())
+ expected.append(",...");
+ expected.append("]");
+ testDumper(expected, &l, NS"QLinkedList", true, elemTypeStr);
+}
+
+void tst_Dumpers::dumpQLinkedList()
+{
+ // Case 1: Simple element type.
+ QLinkedList<int> l;
+
+ // Case 1.1: Empty list.
+ dumpQLinkedListHelper(l);
+
+ // Case 1.2: One element.
+ l.append(2);
+ dumpQLinkedListHelper(l);
+
+ // Case 1.3: Two elements
+ l.append(3);
+ dumpQLinkedListHelper(l);
+
+ // Case 2: Composite element type.
+ QLinkedList<QString> l2;
+
+ // Case 2.1: Empty list.
+ dumpQLinkedListHelper(l2);
+
+ // Case 2.2: One element.
+ l2.append("Teststring 1");
+ dumpQLinkedListHelper(l2);
+
+ // Case 2.3: Two elements.
+ l2.append("Teststring 2");
+ dumpQLinkedListHelper(l2);
+
+ // Case 2.4: > 1000 elements.
+ for (int i = 3; i <= 1002; ++i)
+ l2.append("Test " + N(i));
+
+ // Case 3: Pointer type.
+ QLinkedList<int *> l3;
+ l3.append(new int(5));
+ l3.append(new int(7));
+ l3.append(0);
+ dumpQLinkedListHelper(l3);
+}
+
+# if 0
+ void tst_Debugger::dumpQLinkedList()
+ {
+ // Case 1: Simple element type.
+ QLinkedList<int> l;
+
+ // Case 1.1: Empty list.
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "childtype='int',childnumchild='0',children=[]",
+ &l, NS"QLinkedList", true, "int");
+
+ // Case 1.2: One element.
+ l.append(2);
+ testDumper("value='<1 items>',valueeditable='false',numchild='1',"
+ "childtype='int',childnumchild='0',children=[{addr='%',value='2'}]"
+ << ptrToBa(l.constBegin().operator->()),
+ &l, NS"QLinkedList", true, "int");
+
+ // Case 1.3: Two elements
+ l.append(3);
+ QByteArray it0 = ptrToBa(l.constBegin().operator->());
+ QByteArray it1 = ptrToBa(l.constBegin().operator++().operator->());
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "childtype='int',childnumchild='0',children=[{addr='%',value='2'},"
+ "{addr='%',value='3'}]" << it0 << it1,
+ &l, NS"QLinkedList", true, "int");
+
+ // Case 2: Composite element type.
+ QLinkedList<QString> l2;
+ QLinkedList<QString>::const_iterator iter;
+
+ // Case 2.1: Empty list.
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "childtype='" NS "QString',childnumchild='0',children=[]",
+ &l2, NS"QLinkedList", true, NS"QString");
+
+ // Case 2.2: One element.
+ l2.append("Teststring 1");
+ iter = l2.constBegin();
+ qDebug() << *iter;
+ testDumper("value='<1 items>',valueeditable='false',numchild='1',"
+ "childtype='" NS "QString',childnumchild='0',children=[{addr='%',value='%',}]"
+ << ptrToBa(iter.operator->()) << utfToBase64(*iter),
+ &l2, NS"QLinkedList", true, NS"QString");
+
+ // Case 2.3: Two elements.
+ QByteArray expected = "value='<2 items>',valueeditable='false',numchild='2',"
+ "childtype='int',childnumchild='0',children=[";
+ iter = l2.constBegin();
+ expected.append("{addr='%',%},"
+ << ptrToBa(iter.operator->()) << utfToBase64(*iter));
+ ++iter;
+ expected.append("{addr='%',%}]"
+ << ptrToBa(iter.operator->()) << utfToBase64(*iter));
+ testDumper(expected,
+ &l, NS"QLinkedList", true, NS"QString");
+
+ // Case 2.4: > 1000 elements.
+ for (int i = 3; i <= 1002; ++i)
+ l2.append("Test " + N(i));
+
+ expected = "value='<1002 items>',valueeditable='false',"
+ "numchild='1002',childtype='" NS "QString',childnumchild='0',children=['";
+ iter = l2.constBegin();
+ for (int i = 0; i < 1002; ++i, ++iter)
+ expected.append("{addr='%',value='%'},"
+ << ptrToBa(iter.operator->()) << utfToBase64(*iter));
+ expected.append(",...]");
+ testDumper(expected, &l, NS"QLinkedList", true, NS"QString");
+
+
+ // Case 3: Pointer type.
+ QLinkedList<int *> l3;
+ l3.append(new int(5));
+ l3.append(new int(7));
+ l3.append(0);
+ //dumpQLinkedListHelper(l3);
+ testDumper("", &l, NS"QLinkedList", true, NS"QString");
+ }
+# endif
+
+void tst_Dumpers::dumpQList_int()
+{
+ QList<int> ilist;
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "internal='1',children=[]",
+ &ilist, NS"QList", true, "int");
+ ilist.append(1);
+ ilist.append(2);
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "internal='1',childtype='int',childnumchild='0',children=["
+ "{addr='" + str(&ilist.at(0)) + "',value='1'},"
+ "{addr='" + str(&ilist.at(1)) + "',value='2'}]",
+ &ilist, NS"QList", true, "int");
+}
+
+void tst_Dumpers::dumpQList_int_star()
+{
+ QList<int *> ilist;
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "internal='1',children=[]",
+ &ilist, NS"QList", true, "int*");
+ ilist.append(new int(1));
+ ilist.append(0);
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "internal='1',childtype='int*',childnumchild='1',children=["
+ "{addr='" + str(deref(&ilist.at(0))) +
+ "',type='int',value='1'},"
+ "{value='<null>',numchild='0'}]",
+ &ilist, NS"QList", true, "int*");
+}
+
+void tst_Dumpers::dumpQList_char()
+{
+ QList<char> clist;
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "internal='1',children=[]",
+ &clist, NS"QList", true, "char");
+ clist.append('a');
+ clist.append('b');
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "internal='1',childtype='char',childnumchild='0',children=["
+ "{addr='" + str(&clist.at(0)) + "',value=''a', ascii=97'},"
+ "{addr='" + str(&clist.at(1)) + "',value=''b', ascii=98'}]",
+ &clist, NS"QList", true, "char");
+}
+
+void tst_Dumpers::dumpQList_QString()
+{
+ QList<QString> slist;
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "internal='1',children=[]",
+ &slist, NS"QList", true, NS"QString");
+ slist.append("a");
+ slist.append("b");
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "internal='1',childtype='" NS "QString',childnumchild='0',children=["
+ "{addr='" + str(&slist.at(0)) + "',value='YQA=',valueencoded='2'},"
+ "{addr='" + str(&slist.at(1)) + "',value='YgA=',valueencoded='2'}]",
+ &slist, NS"QList", true, NS"QString");
+}
+
+void tst_Dumpers::dumpQList_Int3()
+{
+ QList<Int3> i3list;
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "internal='0',children=[]",
+ &i3list, NS"QList", true, "Int3");
+ i3list.append(Int3());
+ i3list.append(Int3());
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "internal='0',childtype='Int3',children=["
+ "{addr='" + str(&i3list.at(0)) + "'},"
+ "{addr='" + str(&i3list.at(1)) + "'}]",
+ &i3list, NS"QList", true, "Int3");
+}
+
+void tst_Dumpers::dumpQList_QString3()
+{
+ QList<QString3> s3list;
+ testDumper("value='<0 items>',valueeditable='false',numchild='0',"
+ "internal='0',children=[]",
+ &s3list, NS"QList", true, "QString3");
+ s3list.append(QString3());
+ s3list.append(QString3());
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "internal='0',childtype='QString3',children=["
+ "{addr='" + str(&s3list.at(0)) + "'},"
+ "{addr='" + str(&s3list.at(1)) + "'}]",
+ &s3list, NS"QList", true, "QString3");
+}
+
+void tst_Dumpers::dumpQLocaleHelper(QLocale &loc)
+{
+ QByteArray expected = QByteArray("value='%',type='$T',numchild='8',"
+ "children=[{name='country',%},"
+ "{name='language',%},"
+ "{name='measurementSystem',%},"
+ "{name='numberOptions',%},"
+ "{name='timeFormat_(short)',%},"
+ "{name='timeFormat_(long)',%},"
+ "{name='decimalPoint',%},"
+ "{name='exponential',%},"
+ "{name='percent',%},"
+ "{name='zeroDigit',%},"
+ "{name='groupSeparator',%},"
+ "{name='negativeSign',%}]")
+ << valToString(loc.name())
+ << createExp(&loc, "QLocale", "country()")
+ << createExp(&loc, "QLocale", "language()")
+ << createExp(&loc, "QLocale", "measurementSystem()")
+ << createExp(&loc, "QLocale", "numberOptions()")
+ << generateQStringSpec(loc.timeFormat(QLocale::ShortFormat))
+ << generateQStringSpec(loc.timeFormat())
+ << generateQCharSpec(loc.decimalPoint())
+ << generateQCharSpec(loc.exponential())
+ << generateQCharSpec(loc.percent())
+ << generateQCharSpec(loc.zeroDigit())
+ << generateQCharSpec(loc.groupSeparator())
+ << generateQCharSpec(loc.negativeSign());
+ testDumper(expected, &loc, NS"QLocale", true);
+}
+
+void tst_Dumpers::dumpQLocale()
+{
+ QLocale english(QLocale::English);
+ dumpQLocaleHelper(english);
+
+ QLocale german(QLocale::German);
+ dumpQLocaleHelper(german);
+
+ QLocale chinese(QLocale::Chinese);
+ dumpQLocaleHelper(chinese);
+
+ QLocale swahili(QLocale::Swahili);
+ dumpQLocaleHelper(swahili);
+}
+
+template <typename K, typename V>
+ void tst_Dumpers::dumpQMapHelper(QMap<K, V> &map)
+{
+ QByteArray sizeStr(valToString(map.size()));
+ size_t nodeSize;
+ size_t valOff;
+ getMapNodeParams<K, V>(nodeSize, valOff);
+ int transKeyOffset = static_cast<int>(2*sizeof(void *)) - static_cast<int>(nodeSize);
+ int transValOffset = transKeyOffset + valOff;
+ bool simpleKey = isSimpleType<K>();
+ bool simpleVal = isSimpleType<V>();
+ QByteArray expected = QByteArray("value='<").append(sizeStr).append(" items>',numchild='").
+ append(sizeStr).append("',extra='simplekey: ").append(N(simpleKey)).
+ append(" isSimpleValue: ").append(N(simpleVal)).
+ append(" keyOffset: ").append(N(transKeyOffset)).append(" valueOffset: ").
+ append(N(transValOffset)).append(" mapnodesize: ").
+ append(N(qulonglong(nodeSize))).append("',children=["); // 64bit Linux hack
+ typedef typename QMap<K, V>::iterator mapIter;
+ for (mapIter it = map.begin(); it != map.end(); ++it) {
+ if (it != map.begin())
+ expected.append(",");
+ const QByteArray keyString =
+ QByteArray(valToString(it.key())).replace("valueencoded","keyencoded");
+ expected.append("{key='").append(keyString).append("',value='").
+ append(valToString(it.value())).append("',");
+ if (simpleKey && simpleVal) {
+ expected.append("type='").append(typeToString<V>()).
+ append("',addr='").append(ptrToBa(&it.value())).append("'");
+ } else {
+ QByteArray keyTypeStr = typeToString<K>();
+ QByteArray valTypeStr = typeToString<V>();
+#if QT_VERSION >= 0x040500
+ QMapNode<K, V> *node = 0;
+ size_t backwardOffset = size_t(&node->backward) - valOff;
+ char *addr = reinterpret_cast<char *>(&(*it)) + backwardOffset;
+ expected.append("addr='").append(ptrToBa(addr)).
+ append("',type='" NS "QMapNode<").append(keyTypeStr).append(",").
+ append(valTypeStr).append(" >").append("'");
+#else
+ expected.append("type='" NS "QMapData::Node<").append(keyTypeStr).
+ append(",").append(valTypeStr).append(" >").
+ append("',exp='*('" NS "QMapData::Node<").append(keyTypeStr).
+ append(",").append(valTypeStr).append(" >").
+ append(" >'*)").append(ptrToBa(&(*it))).append("'");
+#endif
+ }
+ expected.append("}");
+ }
+ expected.append("]");
+ mapIter it = map.begin();
+ testDumper(expected, *reinterpret_cast<QMapData **>(&it), NS"QMap",
+ true, getMapType<K,V>(), "", 0, 0, nodeSize, valOff);
+}
+
+void tst_Dumpers::dumpQMap()
+{
+ qDebug() << "QMap<int, int>";
+ // Case 1: Simple type -> simple type.
+ QMap<int, int> map1;
+
+ // Case 1.1: Empty map.
+ dumpQMapHelper(map1);
+
+ // Case 1.2: One element.
+ map1[2] = 3;
+ dumpQMapHelper(map1);
+
+ // Case 1.3: Two elements.
+ map1[3] = 5;
+ dumpQMapHelper(map1);
+
+ // Case 2: Simple type -> composite type.
+ qDebug() << "QMap<int, QString>";
+ QMap<int, QString> map2;
+
+ // Case 2.1: Empty Map.
+ dumpQMapHelper(map2);
+
+ // Case 2.2: One element.
+ map2[5] = "String 7";
+ dumpQMapHelper(map2);
+
+ // Case 2.3: Two elements.
+ map2[7] = "String 11";
+ dumpQMapHelper(map2);
+
+ // Case 3: Composite type -> simple type.
+ qDebug() << "QMap<QString, int>";
+ QMap<QString, int> map3;
+
+ // Case 3.1: Empty map.
+ dumpQMapHelper(map3);
+
+ // Case 3.2: One element.
+ map3["String 13"] = 11;
+ dumpQMapHelper(map3);
+
+ // Case 3.3: Two elements.
+ map3["String 17"] = 13;
+ dumpQMapHelper(map3);
+
+ // Case 4: Composite type -> composite type.
+ QMap<QString, QString> map4;
+
+ // Case 4.1: Empty map.
+ dumpQMapHelper(map4);
+
+ // Case 4.2: One element.
+ map4["String 19"] = "String 23";
+ dumpQMapHelper(map4);
+
+ // Case 4.3: Two elements.
+ map4["String 29"] = "String 31";
+ dumpQMapHelper(map4);
+
+ // Case 4.4: Different value, same key (multimap functionality).
+ map4["String 29"] = "String 37";
+ dumpQMapHelper(map4);
+}
+
+template <typename K, typename V>
+ void tst_Dumpers::dumpQMapNodeHelper(QMap<K, V> &m)
+{
+ typename QMap<K, V>::iterator it = m.begin();
+ const K &key = it.key();
+ const V &val = it.value();
+ //const char * const keyType = typeToString(key);
+ QByteArray expected = QByteArray("value='',numchild='2',"
+ "children=[{name='key',addr='").append(ptrToBa(&key)).
+ append("',type='").append(typeToString<K>()).append("',value='").
+ append(valToString(key)).append("'},{name='value',addr='").
+ append(ptrToBa(&val)).append("',type='").append(typeToString<V>()).
+ append("',value='").append(valToString(val)).
+ append("'}]");
+ size_t nodeSize;
+ size_t valOffset;
+ getMapNodeParams<K, V>(nodeSize, valOffset);
+ testDumper(expected, *reinterpret_cast<QMapData **>(&it), NS"QMapNode",
+ true, getMapType<K,V>(), "", 0, 0, nodeSize, valOffset);
+}
+
+void tst_Dumpers::dumpQMapNode()
+{
+ // Case 1: simple type -> simple type.
+ QMap<int, int> map;
+ map[2] = 3;
+ dumpQMapNodeHelper(map);
+
+ // Case 2: simple type -> composite type.
+ QMap<int, QString> map2;
+ map2[3] = "String 5";
+ dumpQMapNodeHelper(map2);
+
+ // Case 3: composite type -> simple type.
+ QMap<QString, int> map3;
+ map3["String 7"] = 11;
+ dumpQMapNodeHelper(map3);
+
+ // Case 4: composite type -> composite type.
+ QMap<QString, QString> map4;
+ map4["String 13"] = "String 17";
+ dumpQMapNodeHelper(map4);
+}
+
+#ifdef USE_PRIVATE
+void tst_Dumpers::dumpQObject()
+{
+ QObject parent;
+ testDumper("value='',valueencoded='2',type='$T',displayedtype='QObject',"
+ "numchild='4'",
+ &parent, NS"QObject", false);
+ testDumper("value='',valueencoded='2',type='$T',displayedtype='QObject',"
+ "numchild='4',children=["
+ "{name='properties',addr='$A',type='$TPropertyList',"
+ "value='<1 items>',numchild='1'},"
+ "{name='signals',addr='$A',type='$TSignalList',"
+ "value='<2 items>',numchild='2'},"
+ "{name='slots',addr='$A',type='$TSlotList',"
+ "value='<2 items>',numchild='2'},"
+ "{name='parent',value='0x0',type='$T *',numchild='0'},"
+ "{name='className',value='QObject',type='',numchild='0'}]",
+ &parent, NS"QObject", true);
+
+#if 0
+ testDumper("numchild='2',value='<2 items>',type='QObjectSlotList',"
+ "children=[{name='2',value='deleteLater()',"
+ "numchild='0',addr='$A',type='QObjectSlot'},"
+ "{name='3',value='_q_reregisterTimers(void*)',"
+ "numchild='0',addr='$A',type='QObjectSlot'}]",
+ &parent, NS"QObjectSlotList", true);
+#endif
+
+ parent.setObjectName("A Parent");
+ testDumper("value='QQAgAFAAYQByAGUAbgB0AA==',valueencoded='2',type='$T',"
+ "displayedtype='QObject',numchild='4'",
+ &parent, NS"QObject", false);
+ QObject child(&parent);
+ testDumper("value='',valueencoded='2',type='$T',"
+ "displayedtype='QObject',numchild='4'",
+ &child, NS"QObject", false);
+ child.setObjectName("A Child");
+ QByteArray ba ="value='QQAgAEMAaABpAGwAZAA=',valueencoded='2',type='$T',"
+ "displayedtype='QObject',numchild='4',children=["
+ "{name='properties',addr='$A',type='$TPropertyList',"
+ "value='<1 items>',numchild='1'},"
+ "{name='signals',addr='$A',type='$TSignalList',"
+ "value='<2 items>',numchild='2'},"
+ "{name='slots',addr='$A',type='$TSlotList',"
+ "value='<2 items>',numchild='2'},"
+ "{name='parent',addr='" + str(&parent) + "',"
+ "value='QQAgAFAAYQByAGUAbgB0AA==',valueencoded='2',type='$T',"
+ "displayedtype='QObject',numchild='1'},"
+ "{name='className',value='QObject',type='',numchild='0'}]";
+ testDumper(ba, &child, NS"QObject", true);
+ connect(&child, SIGNAL(destroyed()), qApp, SLOT(quit()));
+ testDumper(ba, &child, NS"QObject", true);
+ disconnect(&child, SIGNAL(destroyed()), qApp, SLOT(quit()));
+ testDumper(ba, &child, NS"QObject", true);
+ child.setObjectName("A renamed Child");
+ testDumper("value='QQAgAHIAZQBuAGEAbQBlAGQAIABDAGgAaQBsAGQA',valueencoded='2',"
+ "type='$T',displayedtype='QObject',numchild='4'",
+ &child, NS"QObject", false);
+}
+
+void tst_Dumpers::dumpQObjectChildListHelper(QObject &o)
+{
+ const QObjectList children = o.children();
+ const int size = children.size();
+ const QString sizeStr = N(size);
+ QByteArray expected = QByteArray("numchild='").append(sizeStr).append("',value='<").
+ append(sizeStr).append(" items>',type='" NS "QObjectChildList',children=[");
+ for (int i = 0; i < size; ++i) {
+ const QObject *child = children.at(i);
+ expected.append("{addr='").append(ptrToBa(child)).append("',value='").
+ append(utfToBase64(child->objectName())).
+ append("',valueencoded='2',type='" NS "QObject',displayedtype='").
+ append(child->metaObject()->className()).append("',numchild='1'}");
+ if (i < size - 1)
+ expected.append(",");
+ }
+ expected.append("]");
+ testDumper(expected, &o, NS"QObjectChildList", true);
+}
+
+void tst_Dumpers::dumpQObjectChildList()
+{
+ // Case 1: Object with no children.
+ QObject o;
+ dumpQObjectChildListHelper(o);
+
+ // Case 2: Object with one child.
+ QObject o2(&o);
+ dumpQObjectChildListHelper(o);
+
+ // Case 3: Object with two children.
+ QObject o3(&o);
+ dumpQObjectChildListHelper(o);
+}
+
+void tst_Dumpers::dumpQObjectMethodList()
+{
+ QStringListModel m;
+ testDumper("addr='<synthetic>',type='$T',numchild='24',"
+ "childtype='" NS "QMetaMethod::Method',childnumchild='0',children=["
+ "{name='0 0 destroyed(QObject*)',value='<Signal> (1)'},"
+ "{name='1 1 destroyed()',value='<Signal> (1)'},"
+ "{name='2 2 deleteLater()',value='<Slot> (2)'},"
+ "{name='3 3 _q_reregisterTimers(void*)',value='<Slot> (2)'},"
+ "{name='4 4 dataChanged(QModelIndex,QModelIndex)',value='<Signal> (1)'},"
+ "{name='5 5 headerDataChanged(Qt::Orientation,int,int)',value='<Signal> (1)'},"
+ "{name='6 6 layoutChanged()',value='<Signal> (1)'},"
+ "{name='7 7 layoutAboutToBeChanged()',value='<Signal> (1)'},"
+ "{name='8 8 rowsAboutToBeInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='9 9 rowsInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='10 10 rowsAboutToBeRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='11 11 rowsRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='12 12 columnsAboutToBeInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='13 13 columnsInserted(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='14 14 columnsAboutToBeRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='15 15 columnsRemoved(QModelIndex,int,int)',value='<Signal> (1)'},"
+ "{name='16 16 modelAboutToBeReset()',value='<Signal> (1)'},"
+ "{name='17 17 modelReset()',value='<Signal> (1)'},"
+ "{name='18 18 rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
+ "{name='19 19 rowsMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
+ "{name='20 20 columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
+ "{name='21 21 columnsMoved(QModelIndex,int,int,QModelIndex,int)',value='<Signal> (1)'},"
+ "{name='22 22 submit()',value='<Slot> (2)'},"
+ "{name='23 23 revert()',value='<Slot> (2)'}]",
+ &m, NS"QObjectMethodList", true);
+}
+
+void tst_Dumpers::dumpQObjectPropertyList()
+{
+ // Case 1: Model without a parent.
+ QStringListModel m(QStringList() << "Test1" << "Test2");
+ testDumper("addr='<synthetic>',type='$T',numchild='1',value='<1 items>',"
+ "children=[{name='objectName',type='QString',value='',"
+ "valueencoded='2',numchild='0'}]",
+ &m, NS"QObjectPropertyList", true);
+
+ // Case 2: Model with a parent.
+ QStringListModel m2(&m);
+ testDumper("addr='<synthetic>',type='$T',numchild='1',value='<1 items>',"
+ "children=[{name='objectName',type='QString',value='',"
+ "valueencoded='2',numchild='0'}]",
+ &m2, NS"QObjectPropertyList", true);
+}
+
+static const char *connectionType(uint type)
+{
+ Qt::ConnectionType connType = static_cast<Qt::ConnectionType>(type);
+ const char *output = "unknown";
+ switch (connType) {
+ case Qt::AutoConnection: output = "auto"; break;
+ case Qt::DirectConnection: output = "direct"; break;
+ case Qt::QueuedConnection: output = "queued"; break;
+ case Qt::BlockingQueuedConnection: output = "blockingqueued"; break;
+ case 3: output = "autocompat"; break;
+#if QT_VERSION >= 0x040600
+ case Qt::UniqueConnection: break; // Can't happen.
+#endif
+ default:
+ qWarning() << "Unknown connection type: " << type;
+ break;
+ };
+ return output;
+};
+
+class Cheater : public QObject
+{
+public:
+ static const QObjectPrivate *getPrivate(const QObject &o)
+ {
+ const Cheater &cheater = static_cast<const Cheater&>(o);
+#if QT_VERSION >= 0x040600
+ return dynamic_cast<const QObjectPrivate *>(cheater.d_ptr.data());
+#else
+ return dynamic_cast<const QObjectPrivate *>(cheater.d_ptr);
+#endif
+ }
+};
+
+typedef QVector<QObjectPrivate::ConnectionList> ConnLists;
+
+void tst_Dumpers::dumpQObjectSignalHelper(QObject &o, int sigNum)
+{
+ //qDebug() << o.objectName() << sigNum;
+ QByteArray expected("addr='<synthetic>',numchild='1',type='" NS "QObjectSignal'");
+#if QT_VERSION >= 0x040400 && QT_VERSION <= 0x040700
+ expected.append(",children=[");
+ const QObjectPrivate *p = Cheater::getPrivate(o);
+ Q_ASSERT(p != 0);
+ const ConnLists *connLists = reinterpret_cast<const ConnLists *>(p->connectionLists);
+ QObjectPrivate::ConnectionList connList =
+ connLists != 0 && connLists->size() > sigNum ?
+ connLists->at(sigNum) : QObjectPrivate::ConnectionList();
+ int i = 0;
+ // FIXME: 4.6 only
+ for (QObjectPrivate::Connection *conn = connList.first; conn != 0;
+ ++i, conn = conn->nextConnectionList) {
+ const QString iStr = N(i);
+ expected.append("{name='").append(iStr).append(" receiver',");
+ if (conn->receiver == &o)
+ expected.append("value='<this>',type='").
+ append(o.metaObject()->className()).
+ append("',numchild='0',addr='").append(ptrToBa(&o)).append("'");
+ else if (conn->receiver == 0)
+ expected.append("value='0x0',type='" NS "QObject *',numchild='0'");
+ else
+ expected.append("addr='").append(ptrToBa(conn->receiver)).append("',value='").
+ append(utfToBase64(conn->receiver->objectName())).append("',valueencoded='2',").
+ append("type='" NS "QObject',displayedtype='").
+ append(conn->receiver->metaObject()->className()).append("',numchild='1'");
+ expected.append("},{name='").append(iStr).append(" slot',type='',value='");
+ if (conn->receiver != 0)
+ expected.append(conn->receiver->metaObject()->method(conn->method).signature());
+ else
+ expected.append("<invalid receiver>");
+ expected.append("',numchild='0'},{name='").append(iStr).append(" type',type='',value='<").
+ append(connectionType(conn->connectionType)).append(" connection>',").
+ append("numchild='0'}");
+ if (conn != connList.last)
+ expected.append(",");
+ }
+ expected.append("],numchild='").append(N(i)).append("'");
+#endif
+ testDumper(expected, &o, NS"QObjectSignal", true, "", "", sigNum);
+}
+
+void tst_Dumpers::dumpQObjectSignal()
+{
+ // Case 1: Simple QObject.
+ QObject o;
+ o.setObjectName("Test");
+ testDumper("addr='<synthetic>',numchild='1',type='" NS "QObjectSignal',"
+ "children=[],numchild='0'",
+ &o, NS"QObjectSignal", true, "", "", 0);
+
+ // Case 2: QAbstractItemModel with no connections.
+ QStringListModel m(QStringList() << "Test1" << "Test2");
+ for (int signalIndex = 0; signalIndex < 17; ++signalIndex)
+ dumpQObjectSignalHelper(m, signalIndex);
+
+ // Case 3: QAbstractItemModel with connections to itself and to another
+ // object, using different connection types.
+ qRegisterMetaType<QModelIndex>("QModelIndex");
+ connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
+ &o, SLOT(deleteLater()), Qt::DirectConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(revert()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::BlockingQueuedConnection);
+ connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
+ &m, SLOT(deleteLater()), Qt::AutoConnection);
+#if QT_VERSION >= 0x040600
+ connect(&m, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
+ &m, SLOT(revert()), Qt::UniqueConnection);
+#endif
+ for (int signalIndex = 0; signalIndex < 17; ++signalIndex)
+ dumpQObjectSignalHelper(m, signalIndex);
+}
+
+void tst_Dumpers::dumpQObjectSignalList()
+{
+ // Case 1: Simple QObject.
+ QObject o;
+ o.setObjectName("Test");
+
+ testDumper("type='" NS "QObjectSignalList',value='<2 items>',"
+ "addr='$A',numchild='2',children=["
+ "{name='0',value='destroyed(QObject*)',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'},"
+ "{name='1',value='destroyed()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'}]",
+ &o, NS"QObjectSignalList", true);
+
+ // Case 2: QAbstractItemModel with no connections.
+ QStringListModel m(QStringList() << "Test1" << "Test2");
+ QByteArray expected = "type='" NS "QObjectSignalList',value='<20 items>',"
+ "addr='$A',numchild='20',children=["
+ "{name='0',value='destroyed(QObject*)',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'},"
+ "{name='1',value='destroyed()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'},"
+ "{name='4',value='dataChanged(QModelIndex,QModelIndex)',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'},"
+ "{name='5',value='headerDataChanged(Qt::Orientation,int,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='6',value='layoutChanged()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'},"
+ "{name='7',value='layoutAboutToBeChanged()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSignal'},"
+ "{name='8',value='rowsAboutToBeInserted(QModelIndex,int,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='9',value='rowsInserted(QModelIndex,int,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='10',value='rowsAboutToBeRemoved(QModelIndex,int,int)',"
+ "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='11',value='rowsRemoved(QModelIndex,int,int)',"
+ "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='12',value='columnsAboutToBeInserted(QModelIndex,int,int)',"
+ "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='13',value='columnsInserted(QModelIndex,int,int)',"
+ "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='14',value='columnsAboutToBeRemoved(QModelIndex,int,int)',"
+ "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='15',value='columnsRemoved(QModelIndex,int,int)',"
+ "numchild='%',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='16',value='modelAboutToBeReset()',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='17',value='modelReset()',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='18',value='rowsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='19',value='rowsMoved(QModelIndex,int,int,QModelIndex,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='20',value='columnsAboutToBeMoved(QModelIndex,int,int,QModelIndex,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'},"
+ "{name='21',value='columnsMoved(QModelIndex,int,int,QModelIndex,int)',"
+ "numchild='0',addr='$A',type='" NS "QObjectSignal'}]";
+
+
+ testDumper(expected << "0" << "0" << "0" << "0" << "0" << "0",
+ &m, NS"QObjectSignalList", true);
+
+
+ // Case 3: QAbstractItemModel with connections to itself and to another
+ // object, using different connection types.
+ qRegisterMetaType<QModelIndex>("QModelIndex");
+ connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
+ &o, SLOT(deleteLater()), Qt::DirectConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(revert()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::BlockingQueuedConnection);
+ connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
+ &m, SLOT(deleteLater()), Qt::AutoConnection);
+
+ testDumper(expected << "1" << "1" << "2" << "1" << "0" << "0",
+ &m, NS"QObjectSignalList", true);
+}
+
+QByteArray slotIndexList(const QObject *ob)
+{
+ QByteArray slotIndices;
+ const QMetaObject *mo = ob->metaObject();
+ for (int i = 0; i < mo->methodCount(); ++i) {
+ const QMetaMethod &mm = mo->method(i);
+ if (mm.methodType() == QMetaMethod::Slot) {
+ int slotIndex = mo->indexOfSlot(mm.signature());
+ Q_ASSERT(slotIndex != -1);
+ slotIndices.append(N(slotIndex));
+ slotIndices.append(',');
+ }
+ }
+ slotIndices.chop(1);
+ return slotIndices;
+}
+
+void tst_Dumpers::dumpQObjectSlot()
+{
+ // Case 1: Simple QObject.
+ QObject o;
+ o.setObjectName("Test");
+
+ QByteArray slotIndices = slotIndexList(&o);
+ QCOMPARE(slotIndices, QByteArray("2,3"));
+ QCOMPARE(o.metaObject()->indexOfSlot("deleteLater()"), 2);
+
+ QByteArray expected = QByteArray("addr='$A',numchild='1',type='$T',"
+ //"children=[{name='1 sender'}],numchild='1'");
+ "children=[],numchild='0'");
+ qDebug() << "FIXME!";
+ testDumper(expected, &o, NS"QObjectSlot", true, "", "", 2);
+
+
+ // Case 2: QAbstractItemModel with no connections.
+ QStringListModel m(QStringList() << "Test1" << "Test2");
+ slotIndices = slotIndexList(&o);
+
+ QCOMPARE(slotIndices, QByteArray("2,3"));
+ QCOMPARE(o.metaObject()->indexOfSlot("deleteLater()"), 2);
+
+ expected = QByteArray("addr='$A',numchild='1',type='$T',"
+ //"children=[{name='1 sender'}],numchild='1'");
+ "children=[],numchild='0'");
+ qDebug() << "FIXME!";
+ testDumper(expected, &o, NS"QObjectSlot", true, "", "", 2);
+
+
+ // Case 3: QAbstractItemModel with connections to itself and to another
+ // o, using different connection types.
+ qRegisterMetaType<QModelIndex>("QModelIndex");
+ connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
+ &o, SLOT(deleteLater()), Qt::DirectConnection);
+ connect(&o, SIGNAL(destroyed(QObject*)),
+ &m, SLOT(revert()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::BlockingQueuedConnection);
+ connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
+ &m, SLOT(deleteLater()), Qt::AutoConnection);
+#if QT_VERSION >= 0x040600
+ connect(&m, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
+ &m, SLOT(revert()), Qt::UniqueConnection);
+#endif
+ expected = QByteArray("addr='$A',numchild='1',type='$T',"
+ //"children=[{name='1 sender'}],numchild='1'");
+ "children=[],numchild='0'");
+ qDebug() << "FIXME!";
+ testDumper(expected, &o, NS"QObjectSlot", true, "", "", 2);
+
+}
+
+void tst_Dumpers::dumpQObjectSlotList()
+{
+ // Case 1: Simple QObject.
+ QObject o;
+ o.setObjectName("Test");
+ testDumper("numchild='2',value='<2 items>',type='$T',"
+ "children=[{name='2',value='deleteLater()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='3',value='_q_reregisterTimers(void*)',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'}]",
+ &o, NS"QObjectSlotList", true);
+
+ // Case 2: QAbstractItemModel with no connections.
+ QStringListModel m(QStringList() << "Test1" << "Test2");
+ testDumper("numchild='4',value='<4 items>',type='$T',"
+ "children=[{name='2',value='deleteLater()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='3',value='_q_reregisterTimers(void*)',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='22',value='submit()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='23',value='revert()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'}]",
+ &m, NS"QObjectSlotList", true);
+
+ // Case 3: QAbstractItemModel with connections to itself and to another
+ // object, using different connection types.
+ qRegisterMetaType<QModelIndex>("QModelIndex");
+ connect(&m, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)),
+ &o, SLOT(deleteLater()), Qt::DirectConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(revert()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::QueuedConnection);
+ connect(&m, SIGNAL(columnsInserted(QModelIndex,int,int)),
+ &m, SLOT(submit()), Qt::BlockingQueuedConnection);
+ connect(&m, SIGNAL(columnsRemoved(QModelIndex,int,int)),
+ &m, SLOT(deleteLater()), Qt::AutoConnection);
+ connect(&o, SIGNAL(destroyed(QObject*)), &m, SLOT(submit()));
+ testDumper("numchild='4',value='<4 items>',type='$T',"
+ "children=[{name='2',value='deleteLater()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='3',value='_q_reregisterTimers(void*)',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='22',value='submit()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'},"
+ "{name='23',value='revert()',numchild='0',"
+ "addr='$A',type='" NS "QObjectSlot'}]",
+ &m, NS"QObjectSlotList", true);
+}
+#endif
+
+void tst_Dumpers::dumpQPixmap()
+{
+ // Case 1: Null Pixmap.
+ QPixmap p;
+
+ testDumper("value='(0x0)',type='$T',numchild='0'",
+ &p, NS"QPixmap", true);
+
+
+ // Case 2: Uninitialized non-null pixmap.
+ p = QPixmap(20, 100);
+ testDumper("value='(20x100)',type='$T',numchild='0'",
+ &p, NS"QPixmap", true);
+
+
+ // Case 3: Initialized non-null pixmap.
+ const char * const pixmap[] = {
+ "2 24 3 1", " c None", ". c #DBD3CB", "+ c #FCFBFA",
+ " ", " ", " ", ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+",
+ ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+", ".+", " ", " ", " "
+ };
+ p = QPixmap(pixmap);
+ testDumper("value='(2x24)',type='$T',numchild='0'",
+ &p, NS"QPixmap", true);
+}
+
+#if QT_VERSION >= 0x040500
+template<typename T>
+void tst_Dumpers::dumpQSharedPointerHelper(QSharedPointer<T> &ptr)
+{
+ struct Cheater : public QSharedPointer<T>
+ {
+ static const typename QSharedPointer<T>::Data *getData(const QSharedPointer<T> &p)
+ {
+ return static_cast<const Cheater &>(p).d;
+ }
+ };
+
+ QByteArray expected("value='");
+ QString val1 = ptr.isNull() ? "<null>" : valToString(*ptr.data());
+ QString val2 = isSimpleType<T>() ? val1 : "";
+/*
+ const int *weakAddr;
+ const int *strongAddr;
+ int weakValue;
+ int strongValue;
+ if (!ptr.isNull()) {
+ weakAddr = reinterpret_cast<const int *>(&Cheater::getData(ptr)->weakref);
+ strongAddr = reinterpret_cast<const int *>(&Cheater::getData(ptr)->strongref);
+ weakValue = *weakAddr;
+ strongValue = *strongAddr;
+ } else {
+ weakAddr = strongAddr = 0;
+ weakValue = strongValue = 0;
+ }
+ expected.append(val2).append("',valueeditable='false',numchild='1',children=[").
+ append("{name='data',addr='").append(ptrToBa(ptr.data())).
+ append("',type='").append(typeToString<T>()).append("',value='").append(val1).
+ append("'},{name='weakref',value='").append(N(weakValue)).
+ append("',type='int',addr='").append(ptrToBa(weakAddr)).append("',numchild='0'},").
+ append("{name='strongref',value='").append(N(strongValue)).
+ append("',type='int',addr='").append(ptrToBa(strongAddr)).append("',numchild='0'}]");
+ testDumper(expected, &ptr, NS"QSharedPointer", true, typeToString<T>());
+*/
+}
+#endif
+
+void tst_Dumpers::dumpQSharedPointer()
+{
+#if QT_VERSION >= 0x040500
+ // Case 1: Simple type.
+ // Case 1.1: Null pointer.
+ QSharedPointer<int> simplePtr;
+ dumpQSharedPointerHelper(simplePtr);
+
+ // Case 1.2: Non-null pointer,
+ QSharedPointer<int> simplePtr2(new int(99));
+ dumpQSharedPointerHelper(simplePtr2);
+
+ // Case 1.3: Shared pointer.
+ QSharedPointer<int> simplePtr3 = simplePtr2;
+ dumpQSharedPointerHelper(simplePtr2);
+
+ // Case 1.4: Weak pointer.
+ QWeakPointer<int> simplePtr4(simplePtr2);
+ dumpQSharedPointerHelper(simplePtr2);
+
+ // Case 2: Composite type.
+ // Case 1.1: Null pointer.
+ QSharedPointer<QString> compositePtr;
+ // TODO: This case is not handled in dumper.cpp (segfault!)
+ //dumpQSharedPointerHelper(compoistePtr);
+
+ // Case 1.2: Non-null pointer,
+ QSharedPointer<QString> compositePtr2(new QString("Test"));
+ dumpQSharedPointerHelper(compositePtr2);
+
+ // Case 1.3: Shared pointer.
+ QSharedPointer<QString> compositePtr3 = compositePtr2;
+ dumpQSharedPointerHelper(compositePtr2);
+
+ // Case 1.4: Weak pointer.
+ QWeakPointer<QString> compositePtr4(compositePtr2);
+ dumpQSharedPointerHelper(compositePtr2);
+#endif
+}
+
+void tst_Dumpers::dumpQString()
+{
+ QString s;
+ testDumper("value='IiIgKG51bGwp',valueencoded='5',type='$T',numchild='0'",
+ &s, NS"QString", false);
+ s = "abc";
+ testDumper("value='YQBiAGMA',valueencoded='2',type='$T',numchild='0'",
+ &s, NS"QString", false);
+}
+
+void tst_Dumpers::dumpQVariant_invalid()
+{
+ QVariant v;
+ testDumper("value='(invalid)',type='$T',numchild='0'",
+ &v, NS"QVariant", false);
+}
+
+void tst_Dumpers::dumpQVariant_QString()
+{
+ QVariant v = "abc";
+ testDumper("value='KFFTdHJpbmcpICJhYmMi',valueencoded='5',type='$T',"
+ "numchild='0'",
+ &v, NS"QVariant", true);
+/*
+ FIXME: the QString version should have a child:
+ testDumper("value='KFFTdHJpbmcpICJhYmMi',valueencoded='5',type='$T',"
+ "numchild='1',children=[{name='value',value='IgBhAGIAYwAiAA==',"
+ "valueencoded='4',type='QString',numchild='0'}]",
+ &v, NS"QVariant", true);
+*/
+}
+
+void tst_Dumpers::dumpQVariant_QStringList()
+{
+ QVariant v = QStringList() << "Hi";
+ testDumper("value='(QStringList) ',type='$T',numchild='1',"
+ "children=[{name='value',exp='(*('" NS "QStringList'*)%)',"
+ "type='QStringList',numchild='1'}]"
+ << QByteArray::number(quintptr(&v)),
+ &v, NS"QVariant", true);
+}
+
+#ifndef Q_CC_MSVC
+
+void tst_Dumpers::dumpStdVector()
+{
+ std::vector<std::list<int> *> vector;
+ QByteArray inner = "std::list<int> *";
+ QByteArray innerp = "std::list<int>";
+ testDumper("value='<0 items>',valueeditable='false',numchild='0'",
+ &vector, "std::vector", false, inner, "", sizeof(std::list<int> *));
+ std::list<int> list;
+ vector.push_back(new std::list<int>(list));
+ testDumper("value='<1 items>',valueeditable='false',numchild='1',"
+ "childtype='" + inner + "',childnumchild='1',"
+ "children=[{addr='" + str(deref(&vector[0])) + "',type='" + innerp + "'}]",
+ &vector, "std::vector", true, inner, "", sizeof(std::list<int> *));
+ vector.push_back(0);
+ list.push_back(45);
+ testDumper("value='<2 items>',valueeditable='false',numchild='2',"
+ "childtype='" + inner + "',childnumchild='1',"
+ "children=[{addr='" + str(deref(&vector[0])) + "',type='" + innerp + "'},"
+ "{addr='" + str(&vector[1]) + "',"
+ "type='" + innerp + "',value='<null>',numchild='0'}]",
+ &vector, "std::vector", true, inner, "", sizeof(std::list<int> *));
+ vector.push_back(new std::list<int>(list));
+ vector.push_back(0);
+}
+
+#endif // !Q_CC_MSVC
+
+void tst_Dumpers::dumpQTextCodecHelper(QTextCodec *codec)
+{
+ const QByteArray name = codec->name().toBase64();
+ QByteArray expected = QByteArray("value='%',valueencoded='1',type='$T',"
+ "numchild='2',children=[{name='name',value='%',type='" NS "QByteArray',"
+ "numchild='0',valueencoded='1'},{name='mibEnum',%}]")
+ << name << name << generateIntSpec(codec->mibEnum());
+ testDumper(expected, codec, NS"QTextCodec", true);
+}
+
+void tst_Dumpers::dumpQTextCodec()
+{
+ const QList<QByteArray> &codecNames = QTextCodec::availableCodecs();
+ foreach (const QByteArray &codecName, codecNames)
+ dumpQTextCodecHelper(QTextCodec::codecForName(codecName));
+}
+
+#if QT_VERSION >= 0x040500
+template <typename T1, typename T2>
+ size_t offsetOf(const T1 *klass, const T2 *member)
+{
+ return static_cast<size_t>(reinterpret_cast<const char *>(member) -
+ reinterpret_cast<const char *>(klass));
+}
+
+template <typename T>
+void tst_Dumpers::dumpQWeakPointerHelper(QWeakPointer<T> &ptr)
+{
+ typedef QtSharedPointer::ExternalRefCountData Data;
+ const size_t dataOffset = 0;
+ const Data *d = *reinterpret_cast<const Data **>(
+ reinterpret_cast<const char **>(&ptr) + dataOffset);
+ const int *weakRefPtr = reinterpret_cast<const int *>(&d->weakref);
+ const int *strongRefPtr = reinterpret_cast<const int *>(&d->strongref);
+ T *data = ptr.toStrongRef().data();
+ const QString dataStr = valToString(*data);
+ QByteArray expected("value='");
+ if (isSimpleType<T>())
+ expected.append(dataStr);
+ expected.append("',valueeditable='false',numchild='1',children=[{name='data',addr='").
+ append(ptrToBa(data)).append("',type='").append(typeToString<T>()).
+ append("',value='").append(dataStr).append("'},{name='weakref',value='").
+ append(valToString(*weakRefPtr)).append("',type='int',addr='").
+ append(ptrToBa(weakRefPtr)).append("',numchild='0'},{name='strongref',value='").
+ append(valToString(*strongRefPtr)).append("',type='int',addr='").
+ append(ptrToBa(strongRefPtr)).append("',numchild='0'}]");
+ testDumper(expected, &ptr, NS"QWeakPointer", true, typeToString<T>());
+}
+#endif
+
+void tst_Dumpers::dumpQWeakPointer()
+{
+#if QT_VERSION >= 0x040500
+ // Case 1: Simple type.
+
+ // Case 1.1: Null pointer.
+ QSharedPointer<int> spNull;
+ QWeakPointer<int> wp = spNull.toWeakRef();
+ testDumper("value='<null>',valueeditable='false',numchild='0'",
+ &wp, NS"QWeakPointer", true, "int");
+
+ // Case 1.2: Weak pointer is unique.
+ QSharedPointer<int> sp(new int(99));
+ wp = sp.toWeakRef();
+ dumpQWeakPointerHelper(wp);
+
+ // Case 1.3: There are other weak pointers.
+ QWeakPointer<int> wp2 = sp.toWeakRef();
+ dumpQWeakPointerHelper(wp);
+
+ // Case 1.4: There are other strong shared pointers as well.
+ QSharedPointer<int> sp2(sp);
+ dumpQWeakPointerHelper(wp);
+
+ // Case 2: Composite type.
+ QSharedPointer<QString> spS(new QString("Test"));
+ QWeakPointer<QString> wpS = spS.toWeakRef();
+ dumpQWeakPointerHelper(wpS);
+#endif
+}
+
+#define VERIFY_OFFSETOF(member) \
+do { \
+ QObjectPrivate *qob = 0; \
+ ObjectPrivate *ob = 0; \
+ QVERIFY(size_t(&qob->member) == size_t(&ob->member)); \
+} while (0)
+
+
+void tst_Dumpers::initTestCase()
+{
+ QVERIFY(sizeof(QWeakPointer<int>) == 2*sizeof(void *));
+ QVERIFY(sizeof(QSharedPointer<int>) == 2*sizeof(void *));
+#if QT_VERSION < 0x050000
+ QtSharedPointer::ExternalRefCountData d;
+ d.weakref = d.strongref = 0; // That's what the destructor expects.
+ QVERIFY(sizeof(int) == sizeof(d.weakref));
+ QVERIFY(sizeof(int) == sizeof(d.strongref));
+#endif
+#ifdef USE_PRIVATE
+ const size_t qObjectPrivateSize = sizeof(QObjectPrivate);
+ const size_t objectPrivateSize = sizeof(ObjectPrivate);
+ QVERIFY2(qObjectPrivateSize == objectPrivateSize, QString::fromLatin1("QObjectPrivate=%1 ObjectPrivate=%2").arg(qObjectPrivateSize).arg(objectPrivateSize).toLatin1().constData());
+ VERIFY_OFFSETOF(threadData);
+ VERIFY_OFFSETOF(extraData);
+ VERIFY_OFFSETOF(objectName);
+ VERIFY_OFFSETOF(connectionLists);
+ VERIFY_OFFSETOF(senders);
+ VERIFY_OFFSETOF(currentSender);
+ VERIFY_OFFSETOF(eventFilters);
+ VERIFY_OFFSETOF(currentChildBeingDeleted);
+ VERIFY_OFFSETOF(connectedSignals);
+ //VERIFY_OFFSETOF(deleteWatch);
+#ifdef QT3_SUPPORT
+#if QT_VERSION < 0x040600
+ VERIFY_OFFSETOF(pendingChildInsertedEvents);
+#endif
+#endif
+#if QT_VERSION >= 0x040600
+ VERIFY_OFFSETOF(sharedRefcount);
+#endif
+#endif
+}
+
+
+int main(int argc, char *argv[])
+{
+ QApplication app(argc, argv);
+ tst_Dumpers test;
+ return QTest::qExec(&test, argc, argv);
+}
+
+#include "tst_dumpers.moc"
+
diff --git a/tests/auto/debugger/tst_version.cpp b/tests/auto/debugger/tst_version.cpp
index 5d53aab1ac..afb23d329e 100644
--- a/tests/auto/debugger/tst_version.cpp
+++ b/tests/auto/debugger/tst_version.cpp
@@ -27,7 +27,7 @@
**
****************************************************************************/
-#include "gdb/gdbmi.h"
+#include "debuggerprotocol.h"
#include <QtTest>
diff --git a/tests/auto/debugger/version.pro b/tests/auto/debugger/version.pro
index aeb0b4e542..bc158b8c98 100644
--- a/tests/auto/debugger/version.pro
+++ b/tests/auto/debugger/version.pro
@@ -8,5 +8,5 @@ INCLUDEPATH += $$DEBUGGERDIR $$UTILSDIR
SOURCES += \
tst_version.cpp \
- $$DEBUGGERDIR/gdb/gdbmi.cpp \
+ $$DEBUGGERDIR/debuggerprotocol.cpp \
diff --git a/tests/auto/filesearch/tst_filesearch.cpp b/tests/auto/filesearch/tst_filesearch.cpp
index 0e1157c615..dd5f82f78a 100644
--- a/tests/auto/filesearch/tst_filesearch.cpp
+++ b/tests/auto/filesearch/tst_filesearch.cpp
@@ -51,6 +51,7 @@ private slots:
void multipleResults();
void caseSensitive();
void caseInSensitive();
+ void matchCaseReplacement();
};
namespace {
@@ -99,6 +100,49 @@ void tst_FileSearch::caseInSensitive()
test_helper(expectedResults, QLatin1String("CaseSensitive"), QTextDocument::FindFlags(0));
}
+void tst_FileSearch::matchCaseReplacement()
+{
+ QCOMPARE(Utils::matchCaseReplacement("", "foobar"), QString("foobar")); //empty string
+
+ QCOMPARE(Utils::matchCaseReplacement("testpad", "foobar"), QString("foobar")); //lower case
+ QCOMPARE(Utils::matchCaseReplacement("TESTPAD", "foobar"), QString("FOOBAR")); //upper case
+ QCOMPARE(Utils::matchCaseReplacement("Testpad", "foobar"), QString("Foobar")); //capitalized
+ QCOMPARE(Utils::matchCaseReplacement("tESTPAD", "foobar"), QString("fOOBAR")); //un-capitalized
+ QCOMPARE(Utils::matchCaseReplacement("tEsTpAd", "foobar"), QString("foobar")); //mixed case, use replacement as specified
+ QCOMPARE(Utils::matchCaseReplacement("TeStPaD", "foobar"), QString("foobar")); //mixed case, use replacement as specified
+
+ QCOMPARE(Utils::matchCaseReplacement("testpad", "fooBar"), QString("foobar")); //lower case
+ QCOMPARE(Utils::matchCaseReplacement("TESTPAD", "fooBar"), QString("FOOBAR")); //upper case
+ QCOMPARE(Utils::matchCaseReplacement("Testpad", "fooBar"), QString("Foobar")); //capitalized
+ QCOMPARE(Utils::matchCaseReplacement("tESTPAD", "fooBar"), QString("fOOBAR")); //un-capitalized
+ QCOMPARE(Utils::matchCaseReplacement("tEsTpAd", "fooBar"), QString("fooBar")); //mixed case, use replacement as specified
+ QCOMPARE(Utils::matchCaseReplacement("TeStPaD", "fooBar"), QString("fooBar")); //mixed case, use replacement as specified
+
+ //with common prefix
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXtestpad", "prefixfoobar"), QString("pReFiXfoobar")); //lower case
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXTESTPAD", "prefixfoobar"), QString("pReFiXFOOBAR")); //upper case
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXTestpad", "prefixfoobar"), QString("pReFiXFoobar")); //capitalized
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXtESTPAD", "prefixfoobar"), QString("pReFiXfOOBAR")); //un-capitalized
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXtEsTpAd", "prefixfoobar"), QString("pReFiXfoobar")); //mixed case, use replacement as specified
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXTeStPaD", "prefixfoobar"), QString("pReFiXfoobar")); //mixed case, use replacement as specified
+
+ //with common suffix
+ QCOMPARE(Utils::matchCaseReplacement("testpadSuFfIx", "foobarsuffix"), QString("foobarSuFfIx")); //lower case
+ QCOMPARE(Utils::matchCaseReplacement("TESTPADSuFfIx", "foobarsuffix"), QString("FOOBARSuFfIx")); //upper case
+ QCOMPARE(Utils::matchCaseReplacement("TestpadSuFfIx", "foobarsuffix"), QString("FoobarSuFfIx")); //capitalized
+ QCOMPARE(Utils::matchCaseReplacement("tESTPADSuFfIx", "foobarsuffix"), QString("fOOBARSuFfIx")); //un-capitalized
+ QCOMPARE(Utils::matchCaseReplacement("tEsTpAdSuFfIx", "foobarsuffix"), QString("foobarSuFfIx")); //mixed case, use replacement as specified
+ QCOMPARE(Utils::matchCaseReplacement("TeStPaDSuFfIx", "foobarsuffix"), QString("foobarSuFfIx")); //mixed case, use replacement as specified
+
+ //with common prefix and suffix
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXtestpadSuFfIx", "prefixfoobarsuffix"), QString("pReFiXfoobarSuFfIx")); //lower case
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXTESTPADSuFfIx", "prefixfoobarsuffix"), QString("pReFiXFOOBARSuFfIx")); //upper case
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXTestpadSuFfIx", "prefixfoobarsuffix"), QString("pReFiXFoobarSuFfIx")); //capitalized
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXtESTPADSuFfIx", "prefixfoobarsuffix"), QString("pReFiXfOOBARSuFfIx")); //un-capitalized
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXtEsTpAdSuFfIx", "prefixfoobarsuffix"), QString("pReFiXfoobarSuFfIx")); //mixed case, use replacement as specified
+ QCOMPARE(Utils::matchCaseReplacement("pReFiXTeStPaDSuFfIx", "prefixfoobarsuffix"), QString("pReFiXfoobarSuFfIx")); //mixed case, use replacement as specified
+}
+
QTEST_MAIN(tst_FileSearch)
#include "tst_filesearch.moc"
diff --git a/tests/auto/icheckbuild/icheckbuild.pro b/tests/auto/icheckbuild/icheckbuild.pro
deleted file mode 100644
index e7ea6b4b96..0000000000
--- a/tests/auto/icheckbuild/icheckbuild.pro
+++ /dev/null
@@ -1,20 +0,0 @@
-CONFIG += testcase
-
-include(../../../qtcreator.pri)
-include($$IDE_SOURCE_TREE/src/libs/cplusplus/cplusplus.pri)
-include($$IDE_SOURCE_TREE/src/plugins/cpptools/cpptools.pri)
-
-QT += testlib
-
-DEFINES += ICHECK_BUILD ICHECK_APP_BUILD
-
-INCLUDEPATH += $$IDE_SOURCE_TREE/src/libs/cplusplus
-INCLUDEPATH += $$IDE_SOURCE_TREE/src/plugins
-LIBS += $$IDE_SOURCE_TREE/lib/qtcreator/plugins
-
-HEADERS += ichecklib.h \
- ichecklib_global.h \
- parsemanager.h
-SOURCES += ichecklib.cpp \
- parsemanager.cpp \
- tst_icheckbuild.cpp
diff --git a/tests/auto/icheckbuild/ichecklib.cpp b/tests/auto/icheckbuild/ichecklib.cpp
deleted file mode 100644
index 8e17867938..0000000000
--- a/tests/auto/icheckbuild/ichecklib.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "ichecklib.h"
-#include "parsemanager.h"
-#include <QCoreApplication>
-#include <QString>
-#include <QStringList>
-#include <iostream>
-#include <QDebug>
-#include <QDir>
-#include <QFile>
-#include <QFileInfo>
-#include <QProcess>
-
-QStringList getQTIncludePath()
-{
- QStringList ret;
- QStringList processevironment = QProcess::systemEnvironment();
- foreach(QString item, processevironment){
- if(item.indexOf("QTDIR=") == 0){
- QString qtpath = item.remove("QTDIR=");
- ret << qtpath + "/include";
- ret << qtpath + "/include/ActiveQt";
- ret << qtpath + "/include/phonon";
- ret << qtpath + "/include/phonon_compat";
- ret << qtpath + "/include/Qt";
- ret << qtpath + "/include/Qt3Support";
- ret << qtpath + "/include/QtAssistant";
- ret << qtpath + "/include/QtCore";
- ret << qtpath + "/include/QtDBus";
- ret << qtpath + "/include/QtDeclarative";
- ret << qtpath + "/include/QtDesigner";
- ret << qtpath + "/include/QtGui";
- ret << qtpath + "/include/QtHelp";
- ret << qtpath + "/include/QtMultimedia";
- ret << qtpath + "/include/QtNetwork";
- ret << qtpath + "/include/QtOpenGL";
- ret << qtpath + "/include/QtOpenVG";
- ret << qtpath + "/include/QtScript";
- ret << qtpath + "/include/QtScriptTools";
- ret << qtpath + "/include/QtSql";
- ret << qtpath + "/include/QtSvg";
- ret << qtpath + "/include/QtTest";
- ret << qtpath + "/include/QtUiTools";
- ret << qtpath + "/include/QtWebKit";
- ret << qtpath + "/include/QtXml";
- ret << qtpath + "/include/QtXmlPatterns";
- break;
- }
- }
- return ret;
-}
-
-ICheckLib::ICheckLib()
-: pParseManager(0)
-{
-}
-
-void ICheckLib::ParseHeader(const QStringList& includePath, const QStringList& filelist)
-{
- if(pParseManager)
- delete pParseManager;
- pParseManager = 0;
- pParseManager = new CPlusPlus::ParseManager();
- pParseManager->setIncludePath(includePath);
- pParseManager->parse(filelist);
-}
-
-bool ICheckLib::check(const ICheckLib& ichecklib /*ICheckLib from interface header*/, QString outputfile)
-{
- if(pParseManager){
- CPlusPlus::ParseManager* cpparsemanager = ichecklib.pParseManager;
- return pParseManager->checkAllMetadatas(cpparsemanager, outputfile);
- }
- return false;
-}
-
-QStringList ICheckLib::getErrorMsg()
-{
- QStringList ret;
- if(pParseManager){
- ret.append(pParseManager->getErrorMsg());
- }
- else
- ret << "no file was parsed.";
- return ret;
-}
diff --git a/tests/auto/icheckbuild/parsemanager.cpp b/tests/auto/icheckbuild/parsemanager.cpp
deleted file mode 100644
index 1b5607ab01..0000000000
--- a/tests/auto/icheckbuild/parsemanager.cpp
+++ /dev/null
@@ -1,1528 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-#include "parsemanager.h"
-#include "cplusplus/CppDocument.h"
-#include "Control.h"
-#include "Literals.h"
-#include "Overview.h"
-#include "Scope.h"
-#include "TranslationUnit.h"
-#include "AST.h"
-#include "Symbols.h"
-#include "Bind.h"
-#include <QDebug>
-#include "Name.h"
-#include "cpptools/cppmodelmanager.h"
-#include <QTextStream>
-
-using namespace CppTools;
-using namespace CppTools::Internal;
-
-
-using namespace CPlusPlus;
-
-//<------------------------------------------------------- Compare function for the internal structures
-/**********************************
-Compares function with function
-with return type, function name
-and their arguments and arguments
-types.
-**********************************/
-bool FUNCTIONITEM::isEqualTo(FUNCTIONITEM *cpfct, bool ignoreName/* = true*/)
-{
- if(ignoreName)
- return function->isEqualTo(cpfct->function, true);
- return function->isEqualTo(cpfct->function);
-}
-
-/*****************************************************************
-Compares two property regarding
-of their function definition,
-type definition, function arguments
-and function types.
-
-Q_PROPERTY( ConnectionState state READ state NOTIFY stateChanged);
-******************************************************************/
-bool PROPERTYITEM::isEqualTo(PROPERTYITEM *cpppt)
-{
- if (!ast->type_id || !cpppt->ast->type_id)
- return false;
- if (type != cpppt->type)
- return false;
-
- if (!ast->property_name || !ast->property_name->name || !ast->property_name->name->identifier())
- return false;
- QString thistypename = ast->property_name->name->identifier()->chars();
-
- if (!cpppt->ast->property_name || !cpppt->ast->property_name->name || !cpppt->ast->property_name->name->identifier())
- return false;
- QString cppttypename = cpppt->ast->property_name->name->identifier()->chars();
- if(thistypename != cppttypename)
- return false;
-
- if ((this->readAst == 0) != (cpppt->readAst == 0))
- return false;
- if((this->writeAst == 0) != (cpppt->writeAst == 0))
- return false;
- if((this->resetAst == 0) != (cpppt->resetAst == 0))
- return false;
- if((this->notifyAst == 0) != (cpppt->notifyAst == 0))
- return false;
- //check for read function
- if(this->readAst){
- if(!this->readFct || !cpppt->readFct)
- return false;
- if(!this->readFct->isEqualTo(cpppt->readFct))
- return false;
- }
- //check for write function
- if(this->writeAst){
- if(!this->writeFct || !cpppt->writeFct)
- return false;
- if(!this->writeFct->isEqualTo(cpppt->writeFct))
- return false;
- }
- //check for reset function
- if(this->resetAst){
- if(!this->resetFct || !cpppt->resetFct)
- return false;
- if(!this->resetFct->isEqualTo(cpppt->resetFct))
- return false;
- }
- //check for notify function
- if(this->notifyAst){
- if(!this->notifyFct || !cpppt->notifyFct)
- return false;
- if(!this->notifyFct->isEqualTo(cpppt->notifyFct))
- return false;
- }
- return true;
-}
-
-/*****************************************************************
-Compares two enums regarding
-of their values created by the getEnumValueStringList function.
-*****************************************************************/
-bool QENUMITEM::isEqualTo(QENUMITEM *cpenum)
-{
- if(this->values.count() != cpenum->values.count())
- return false;
- foreach(QString str, this->values){
- if(!cpenum->values.contains(str))
- return false;
- }
- return true;
-}
-
-/*****************************************************************
-Compares two flags regarding
-of their enum definitions and their
-values created by the getEnumValueStringList function.
-*****************************************************************/
-bool QFLAGITEM::isEqualTo(QFLAGITEM *cpflag)
-{
- if(this->enumvalues.count() != cpflag->enumvalues.count())
- return false;
- foreach(QString str, this->enumvalues){
- if(!cpflag->enumvalues.contains(str))
- return false;
- }
- return true;
-}
-
-
-
-ParseManager::ParseManager()
-: pCppPreprocessor(0)
-{
-
-}
-
-ParseManager::~ParseManager()
-{
- if(pCppPreprocessor)
- delete pCppPreprocessor;
- if(::m_resultFile){
- ::m_resultFile->close();
- delete ::m_resultFile;
- ::m_resultFile = 0;
- }
-}
-
-/**************************************
-Function for setting the include
-Paths
-**************************************/
-void ParseManager::setIncludePath(const QStringList &includePath)
-{
- m_includePaths = includePath;
-}
-
-/**************************************
-public Function that starts the parsing
-all of the files in the sourceFiles
-string list.
-**************************************/
-void ParseManager::parse(const QStringList &sourceFiles)
-{
- m_errormsgs.clear();
- if(pCppPreprocessor){
- delete pCppPreprocessor;
- pCppPreprocessor = 0;
- }
-
- if (! sourceFiles.isEmpty()) {
- m_strHeaderFile = sourceFiles[0];
- pCppPreprocessor = new CppTools::Internal::CppPreprocessor(QPointer<CPlusPlus::ParseManager>(this));
- pCppPreprocessor->setIncludePaths(m_includePaths);
- pCppPreprocessor->setFrameworkPaths(m_frameworkPaths);
- parse(pCppPreprocessor, sourceFiles);
- }
-}
-
-/*********************************************
-private function that prepare the filelist
-to parse and starts the parser.
-*********************************************/
-void ParseManager::parse(CppTools::Internal::CppPreprocessor *preproc,
- const QStringList &files)
-{
- if (files.isEmpty())
- return;
-
- //check if file is C++ header file
- QStringList headers;
- foreach (const QString &file, files) {
- const QFileInfo fileInfo(file);
- QString ext = fileInfo.suffix();
- if (ext.toLower() == "h")
- headers.append(file);
- }
-
- foreach (const QString &file, files) {
- preproc->snapshot.remove(file);
- }
- preproc->setTodo(headers);
- QString conf = QLatin1String("<configuration>");
-
- preproc->run(conf);
- for (int i = 0; i < headers.size(); ++i) {
- QString fileName = headers.at(i);
- preproc->run(fileName);
- }
-}
-
-//This function creates a class list for each class and its base classes in
-//the header file that needs to be checked.
-//e.g.
-// Cl1 Cl2
-// __|__ __|__
-// | | | |
-// Cl11 Cl12 Cl21 Cl22
-//
-//==> list[0] = {Cl1, Cl11, Cl12}
-// list[1] = {Cl2, Cl21, Cl22}
-
-QList<CLASSTREE*> ParseManager::CreateClassLists(bool isInterfaceHeader)
-{
- QList<CLASSTREE*>ret;
- QList<CLASSLISTITEM*> classlist;
- QList<CLASSLISTITEM*> allclasslist;
-
- Trace("Following classes scaned for header file: " + m_strHeaderFile);
- //Iteration over all parsed documents
- if(getPreProcessor()){
- for (Snapshot::const_iterator it = getPreProcessor()->snapshot.begin()
- ; it != getPreProcessor()->snapshot.end(); ++it)
- {
- Document::Ptr doc = (*it);
- if(doc){
- QFileInfo fileinf(doc->fileName());
- QFileInfo fileinf1(m_strHeaderFile);
- //Get the Translated unit
- Control* ctrl = doc->control();
- TranslationUnit* trlUnit = ctrl->translationUnit();
- AST* pAst = trlUnit->ast();
- TranslationUnitAST *ptrAst = 0;
- if(pAst && (ptrAst = pAst->asTranslationUnit())){
- //iteration over all translated declaration in this document
- for (DeclarationListAST *pDecllist = ptrAst->declaration_list; pDecllist; pDecllist = pDecllist->next) {
- if(pDecllist->value){
- SimpleDeclarationAST *pSimpleDec = pDecllist->value->asSimpleDeclaration();
- if(pSimpleDec){
- //Iteration over class specifier
- for (SpecifierListAST *pSimpleDecDecllist = pSimpleDec->decl_specifier_list; pSimpleDecDecllist; pSimpleDecDecllist = pSimpleDecDecllist->next) {
- ClassSpecifierAST * pclassspec = pSimpleDecDecllist->value->asClassSpecifier();
- if(pclassspec){
- CLASSLISTITEM* item = new CLASSLISTITEM();
- item->classspec = pclassspec;
- item->trlUnit = trlUnit;
- allclasslist.push_back(item);
- QString classname = item->trlUnit->spell(item->classspec->name->firstToken());
- Trace("- " + classname + " class scaned");
-
- //We found a class that is defined in the header file that needs to be checked
- if(fileinf.fileName().toLower() == fileinf1.fileName().toLower()){
- CLASSTREE* cltree = new CLASSTREE();
- cltree->highestlevelclass = item;
- cltree->classlist.push_back(item);
- ret.push_back(cltree);
- }
- }
- }
- }
- }
- }
- }
- }
- }
- }
- //after we search for the classes we need to search for the baseclasses
- Trace("Following classes found in Header file: " + m_strHeaderFile);
- foreach(CLASSTREE *cltree, ret){
- QString classname = cltree->highestlevelclass->trlUnit->spell(cltree->highestlevelclass->classspec->name->firstToken());
- Trace("- " + classname + " class found");
- QList<CLASSLISTITEM*> baseclasslist;
- getBaseClasses(cltree->highestlevelclass, baseclasslist, allclasslist, 0, isInterfaceHeader);
- cltree->classlist.append(baseclasslist);
- }
- return ret;
-}
-
-/********************************************
-Gets all the baseclass from a class and
-add those base classes into the baseclasslist
-********************************************/
-void ParseManager::getBaseClasses(const CLASSLISTITEM* pclass
- , QList<CLASSLISTITEM*> &baseclasslist
- , const QList<CLASSLISTITEM*> &allclasslist
- , int level
- , bool isInterfaceHeader)
-{
- //iteration over the base_clause_list of the current class
- QString levelmarker = " ";
- for(int i = 0; i < level; i++)
- levelmarker += " ";
- levelmarker += "|- ";
- QList<CLASSLISTITEM*>child;
-
- for(BaseSpecifierListAST *pBaseSpecList = pclass->classspec->base_clause_list; pBaseSpecList; pBaseSpecList = pBaseSpecList->next)
- {
- BaseSpecifierAST *pBaseSpec = pBaseSpecList->value;
- bool found = false;
- foreach(CLASSLISTITEM* pclspec, allclasslist)
- {
- if(pclspec->classspec->symbol->name()
- && pBaseSpec->symbol->name()
- && pclspec->classspec->symbol->name()->isEqualTo(pBaseSpec->symbol->name()))
- {
- child.push_back(pclspec);
- baseclasslist.push_back(pclspec);
- QString classname = pclspec->trlUnit->spell(pclspec->classspec->name->firstToken());
- Trace(levelmarker + classname + " class found");
- found = true;
- break;
- }
- }
- if(!found && pBaseSpec->name){
- QString classname = pclass->trlUnit->spell(pBaseSpec->name->firstToken());
- if(isInterfaceHeader)
- Trace(levelmarker + classname + " class not found! Interface classes should not be inherited from Qt Objects!");
- else
- Trace(levelmarker + classname + " class not found!");
- }
- }
- //call the function recursive because all the basclasses can have other base classes
- foreach(CLASSLISTITEM* pchclass, child){
- getBaseClasses(pchclass, baseclasslist, allclasslist, ++level, isInterfaceHeader);
- }
-}
-
-/**************************************************
-This function finds and creates all Elements wich
-are significant for MetaDatas.
-Those element will be added in the aparameter
-lists.
-**************************************************/
-void ParseManager::getElements(QList<FUNCTIONITEM*> &functionlist
- , QList<PROPERTYITEM*> &propertylist
- , QList<QENUMITEM*> &qenumlist
- , QList<ENUMITEM*> &enumlist
- , QList<QFLAGITEM*> &qflaglist
- , QList<QDECLAREFLAGSITEM*> &qdeclareflaglist
- , const QList<CLASSLISTITEM*> classitems
- , const CLASSLISTITEM* highestlevelclass)
-{
- foreach(CLASSLISTITEM* classitem, classitems){
- QString classname = "";
- if(classitem->classspec->name)
- classname = classitem->trlUnit->spell(classitem->classspec->name->firstToken());
- for (DeclarationListAST *pmemberlist = classitem->classspec->member_specifier_list; pmemberlist; pmemberlist = pmemberlist->next) {
- /**********
- Functions
- **********/
- if (FunctionDefinitionAST *pfctdef = pmemberlist->value->asFunctionDefinition()){
- FUNCTIONITEM* item = new FUNCTIONITEM;
- item->trlUnit = classitem->trlUnit;
- item->function = pfctdef->symbol;
- item->classAst = classitem->classspec;
- item->highestlevelclass = highestlevelclass;
- functionlist.push_back(item);
- if(isMetaObjFunction(item))
- Trace(" - " + getTraceFuntionString(item, classname) + " found");
- }
-
- SimpleDeclarationAST *pdecl = pmemberlist->value->asSimpleDeclaration();
- if(pdecl){
- for(List<Symbol*>* decllist = pdecl->symbols; decllist; decllist = decllist->next)
- {
- Function* pfct = decllist->value->type()->asFunctionType();
- if(pfct){
- FUNCTIONITEM* item = new FUNCTIONITEM();
- item->trlUnit = classitem->trlUnit;
- item->function = pfct;
- item->classAst = classitem->classspec;
- item->highestlevelclass = highestlevelclass;
- functionlist.push_back(item);
- if(isMetaObjFunction(item))
- Trace(" - " + getTraceFuntionString(item, classname) + " found");
- }
- }
- /******
- enum
- ******/
- for(List<SpecifierAST*>* decllist = pdecl->decl_specifier_list; decllist; decllist = decllist->next)
- {
- EnumSpecifierAST * penum = decllist->value->asEnumSpecifier();
- if(penum){
- ENUMITEM* item = new ENUMITEM();
- item->ast = penum;
- item->highestlevelclass = highestlevelclass;
- item->trlUnit = classitem->trlUnit;
- enumlist.push_back(item);
- }
- }
- }
- else{
- /**********
- Q_PROPERTY
- **********/
- if(QtPropertyDeclarationAST *ppdecl = pmemberlist->value->asQtPropertyDeclaration()) {
- propertylist.push_back(PROPERTYITEM::create(ppdecl, highestlevelclass));
- if (ppdecl->property_name && ppdecl->property_name->name && ppdecl->property_name->name->identifier()) {
- Trace(" - Q_PROPERTY: " + QLatin1String(ppdecl->property_name->name->identifier()->chars()) + " found");
- }
- } else{
- /**********
- Q_ENUM
- **********/
- if (QtEnumDeclarationAST *pqenum = pmemberlist->value->asQtEnumDeclaration()) {
- for (NameListAST *plist = pqenum->enumerator_list; plist; plist = plist->next) {
- QENUMITEM* item = new QENUMITEM;
- item->name = plist->value->name->identifier()->chars();
- item->highestlevelclass = highestlevelclass;
- qenumlist.push_back(item);
- Trace(" - Q_ENUM: " + classname + "::" + item->name + " found");
- }
- }
- else{
- /**********
- Q_FLAGS
- **********/
- if (QtFlagsDeclarationAST *pqflags = pmemberlist->value->asQtFlagsDeclaration()){
- for (NameListAST *plist = pqflags->flag_enums_list; plist; plist = plist->next) {
- QFLAGITEM* item = new QFLAGITEM;
- item->name = plist->value->name;
- item->highestlevelclass = highestlevelclass;
- qflaglist.push_back(item);
- Trace(" - Q_FLAGS: " + classname + "::" + item->name->identifier()->chars() + " found");
- }
- }
-#if 0
- /*The code for Q_DECLARE_FLAGS was wrong. It's optional, and only does a typedef.
- That means, if you do the typedef yourself and not use Q_DECLARE_FLAGS, that *is* valid.
- Meaning, if one would want to do a check like the ones in this app, one has to check the defined types in the class scope.*/
- else {
- /****************
- Q_DECLARE_FLAGS
- ****************/
- QtDeclareFlagsDeclarationAST *pqdeclflags = pmemberlist->value->asQDeclareFlagsDeclarationAST();
- if(pqdeclflags){
- QDECLAREFLAGSITEM* item = new QDECLAREFLAGSITEM();
- item->ast = pqdeclflags;
- item->highestlevelclass = highestlevelclass;
- item->trlUnit = classitem->trlUnit;
- qdeclareflaglist.push_back(item);
- }
- }
-#endif
- }
- }
- }
- }
- }
-}
-
-/*********************************************
-Function that starts the comare between the
-parser result and their metadata content.
-*********************************************/
-bool ParseManager::checkAllMetadatas(ParseManager* pInterfaceParserManager, QString resultfile)
-{
- bool ret = true;
-
- //Create output file
- if(resultfile != "" && ::m_resultFile == 0){
- ::m_resultFile = new QFile(resultfile);
- if (!::m_resultFile->open(QFile::WriteOnly | QFile::Truncate)) {
- delete ::m_resultFile;
- ::m_resultFile = 0;
- }
- }
-
- /************************************************
- Get all elements from the interface header file
- ************************************************/
- Trace("### Get all elements from the interface header file ###");
- QList<CLASSTREE*> ilookuplist = pInterfaceParserManager->CreateClassLists(true);
- QList<QList<FUNCTIONITEM*> > ifunctionslookuplist;
- QList<QList<PROPERTYITEM*> > ipropertieslookuplist;
- QList<QList<QENUMITEM*> > iqenumlookuplist;
- QList<QList<ENUMITEM*> > ienumlookuplist;
- QList<QList<QFLAGITEM*> > iqflaglookuplist;
- QList<QList<QDECLAREFLAGSITEM*> > iqdeclareflaglookuplist;
- Trace("Following MetaData found:");
- foreach(CLASSTREE* iclasstree, ilookuplist){
- QList<FUNCTIONITEM*>functionlist;
- QList<PROPERTYITEM*>propertylist;
- QList<QENUMITEM*>qenumlist;
- QList<ENUMITEM*>enumlist;
- QList<QFLAGITEM*> qflaglist;
- QList<QDECLAREFLAGSITEM*> qdeclareflag;
- getElements(functionlist
- , propertylist
- , qenumlist
- , enumlist
- , qflaglist
- , qdeclareflag
- , iclasstree->classlist
- , iclasstree->highestlevelclass);
- if(functionlist.size() > 0)
- ifunctionslookuplist.append(functionlist);
- if(propertylist.size() > 0)
- ipropertieslookuplist.append(propertylist);
- if(qenumlist.size() > 0)
- iqenumlookuplist.append(qenumlist);
- if(enumlist.size() > 0)
- ienumlookuplist.append(enumlist);
- if(qflaglist.size() > 0)
- iqflaglookuplist.append(qflaglist);
- if(qdeclareflag.size() > 0)
- iqdeclareflaglookuplist.append(qdeclareflag);
- }
-
- /************************************************
- Get all elements from the compare header file
- ************************************************/
- Trace("\n");
- Trace("### Get all elements from the compare header file ###");
- QList<CLASSTREE*> lookuplist = CreateClassLists(false);
- QList<QList<FUNCTIONITEM*> > functionslookuplist;
- QList<QList<PROPERTYITEM*> > propertieslookuplist;
- QList<QList<QENUMITEM*> > qenumlookuplist;
- QList<QList<ENUMITEM*> > enumlookuplist;
- QList<QList<QFLAGITEM*> > qflaglookuplist;
- QList<QList<QDECLAREFLAGSITEM*> > qdeclareflaglookuplist;
- Trace("Following MetaData found:");
- foreach(CLASSTREE* classtree, lookuplist){
- QList<FUNCTIONITEM*>functionlist;
- QList<PROPERTYITEM*>propertylist;
- QList<QENUMITEM*>qenumlist;
- QList<ENUMITEM*>enumlist;
- QList<QFLAGITEM*> qflaglist;
- QList<QDECLAREFLAGSITEM*> qdeclareflag;
- getElements(functionlist
- , propertylist
- , qenumlist
- , enumlist
- , qflaglist
- , qdeclareflag
- , classtree->classlist
- , classtree->highestlevelclass);
- if(functionlist.size() > 0)
- functionslookuplist.append(functionlist);
- if(propertylist.size() > 0)
- propertieslookuplist.append(propertylist);
- if(qenumlist.size() > 0)
- qenumlookuplist.append(qenumlist);
- if(enumlist.size() > 0)
- enumlookuplist.append(enumlist);
- if(qflaglist.size() > 0)
- qflaglookuplist.append(qflaglist);
- if(qdeclareflag.size() > 0)
- qdeclareflaglookuplist.append(qdeclareflag);
- }
-
- Trace("\n");
- Trace("### Result: ###");
- /******************************
- Check for function
- ******************************/
- Trace("Compare all interface MetaData functions:");
- QList<FUNCTIONITEM*> missingifcts = checkMetadataFunctions(functionslookuplist, ifunctionslookuplist);
- if(missingifcts.size() > 0){
- foreach(FUNCTIONITEM* ifct, missingifcts){
- m_errormsgs.append(getErrorMessage(ifct));
- }
- ret = false;
- Trace("- Failed!");
- }
- else{
- Trace("- OK");
- }
-
- /******************************
- Check for properies
- ******************************/
- Trace("Compare all interface MetaData properties:");
- QList<PROPERTYITEM*> missingippts = checkMetadataProperties(propertieslookuplist, functionslookuplist, ipropertieslookuplist, ifunctionslookuplist);
- if(missingippts.size() > 0){
- foreach(PROPERTYITEM* ippt, missingippts){
- m_errormsgs.append(getErrorMessage(ippt));
- }
- ret = false;
- Trace("- Failed!");
- }
- else{
- Trace("- OK");
- }
-
- /******************************
- Check for enums
- ******************************/
- Trace("Compare all interface MetaData enums:");
- QList<QENUMITEM*> missingiqenums = checkMetadataEnums(qenumlookuplist, enumlookuplist, iqenumlookuplist, ienumlookuplist);
- if(missingiqenums.size() > 0){
- foreach(QENUMITEM* ienum, missingiqenums){
- m_errormsgs.append(getErrorMessage(ienum));
- }
- ret = false;
- Trace("- Failed!");
- }
- else{
- Trace("- OK");
- }
-
- /******************************
- Check for flags
- ******************************/
- Trace("Compare all interface MetaData flags:");
- QList<QFLAGITEM*> missingiqflags = checkMetadataFlags(qflaglookuplist, qdeclareflaglookuplist, enumlookuplist
- , iqflaglookuplist, iqdeclareflaglookuplist, ienumlookuplist);
- if(missingiqflags.size() > 0){
- foreach(QFLAGITEM* iflags, missingiqflags){
- m_errormsgs.append(getErrorMessage(iflags));
- }
- ret = false;
- Trace("- Failed!");
- }
- else{
- Trace("- OK");
- }
-
- /******************************
- Add summary
- ******************************/
- Trace("\n");
- Trace("### summary ###");
- if(m_errormsgs.size() > 0){
- Trace("- Folowing interface items are missing:");
- foreach(QString msg, m_errormsgs)
- Trace(" - " + msg);
- }
- else
- Trace("Interface is full defined.");
-
- //now delet all Classitems
- foreach(CLASSTREE* l, ilookuplist){
- l->classlist.clear();
- }
- foreach(CLASSTREE* l, lookuplist){
- l->classlist.clear();
- }
- //delete all functionitems
- foreach(QList<FUNCTIONITEM*>l, ifunctionslookuplist){
- l.clear();
- }
- foreach(QList<FUNCTIONITEM*>l, functionslookuplist){
- l.clear();
- }
- //delete all properties
- foreach(QList<PROPERTYITEM*>l, ipropertieslookuplist){
- l.clear();
- }
- foreach(QList<PROPERTYITEM*>l, propertieslookuplist){
- l.clear();
- }
- //delete all qenums
- foreach(QList<QENUMITEM*>l, iqenumlookuplist){
- l.clear();
- }
- foreach(QList<QENUMITEM*>l, iqenumlookuplist){
- l.clear();
- }
- //delete all enums
- foreach(QList<ENUMITEM*>l, ienumlookuplist){
- l.clear();
- }
- foreach(QList<ENUMITEM*>l, enumlookuplist){
- l.clear();
- }
- //delete all qflags
- foreach(QList<QFLAGITEM*>l, iqflaglookuplist){
- l.clear();
- }
- foreach(QList<QFLAGITEM*>l, qflaglookuplist){
- l.clear();
- }
- //delete all qdeclareflags
- foreach(QList<QDECLAREFLAGSITEM*>l, iqdeclareflaglookuplist){
- l.clear();
- }
- foreach(QList<QDECLAREFLAGSITEM*>l, qdeclareflaglookuplist){
- l.clear();
- }
-
- return ret;
-}
-
-//<------------------------------------------------------- Start of MetaData functions
-/***********************************
-Function that checks all functions
-which will occur in the MetaData
-***********************************/
-QList<FUNCTIONITEM*> ParseManager::checkMetadataFunctions(const QList<QList<FUNCTIONITEM*> > &classfctlist, const QList<QList<FUNCTIONITEM*> > &iclassfctlist)
-{
- QList<FUNCTIONITEM*> missingifcts;
- //Compare each function from interface with function from header (incl. baseclass functions)
- QList<FUNCTIONITEM*> ifcts;
- foreach(QList<FUNCTIONITEM*>ifunctionlist, iclassfctlist){
- ifcts.clear();
- //check if one header class contains all function from one interface header class
- if(classfctlist.count() > 0){
- foreach(QList<FUNCTIONITEM*>functionlist, classfctlist){
- QList<FUNCTIONITEM*> tmpl = containsAllMetadataFunction(functionlist, ifunctionlist);
- if(tmpl.size() == 0){
- ifcts.clear();
- break;
- }
- else
- ifcts.append(tmpl);
- }
- }
- else {
- foreach(FUNCTIONITEM *pfct, ifunctionlist)
- pfct->classWichIsNotFound << "<all classes>";
- ifcts.append(ifunctionlist);
- }
- missingifcts.append(ifcts);
- }
- return missingifcts;
-}
-
-/*********************************************
-Helper function to check if a function will
-occure in the MetaData.
-*********************************************/
-bool ParseManager::isMetaObjFunction(FUNCTIONITEM* fct)
-{
- if(fct->function->isInvokable()
- || fct->function->isSignal()
- || fct->function->isSlot())
- return true;
- return false;
-}
-
-/****************************************************
-Check if all function from iclassfctlist are defined
-in the classfctlist as well.
-It will return all the function they are missing.
-****************************************************/
-QList<FUNCTIONITEM*> ParseManager::containsAllMetadataFunction(const QList<FUNCTIONITEM*> &classfctlist, const QList<FUNCTIONITEM*> &iclassfctlist)
-{
- QList<FUNCTIONITEM*> ret;
- foreach(FUNCTIONITEM* ifct, iclassfctlist){
- if(isMetaObjFunction(ifct)){
- bool found = false;
- QStringList missingimplinclasses;
- ClassSpecifierAST* clspec = 0;
- QString classname = "";
- foreach(FUNCTIONITEM* fct, classfctlist){
- if(clspec != fct->highestlevelclass->classspec){
- clspec = fct->highestlevelclass->classspec;
- //get the classname
- unsigned int firsttoken = clspec->name->firstToken();
- classname += fct->trlUnit->spell(firsttoken);
- if(missingimplinclasses.indexOf(classname) < 0)
- missingimplinclasses.push_back(classname);
- }
- if(fct->isEqualTo(ifct, false)){
- found = true;
- missingimplinclasses.clear();
- Trace("- " + getTraceFuntionString(fct, classname) + " implemented");
- break;
- }
- }
- if(!found){
- ifct->classWichIsNotFound.append(missingimplinclasses);
- ret.push_back(ifct);
- QString classname = ifct->trlUnit->spell(ifct->highestlevelclass->classspec->name->firstToken());
- Trace("- " + getTraceFuntionString(ifct, classname) + " not implemented!");
- }
- }
- }
- return ret;
-}
-
-/************************************
-Function that gives back an error
-string for a MetaData function
-mismatch.
-************************************/
-QStringList ParseManager::getErrorMessage(FUNCTIONITEM* fct)
-{
- QStringList ret;
- QString fctstring = "";
- QString fcttype = "";
-
- foreach(QString classname, fct->classWichIsNotFound){
- QString tmp;
- QTextStream out(&tmp);
-
- fcttype = "";
- fctstring = classname;
- fctstring += "::";
-
- unsigned int token = fct->function->sourceLocation() - 1;
- while(fct->trlUnit->tokenAt(token).isNot(T_EOF_SYMBOL)){
- fctstring += fct->trlUnit->tokenAt(token).spell();
- if(*fct->trlUnit->tokenAt(token).spell() == ')')
- break;
- fctstring += " ";
- token++;
- }
-
- Function* pfct = fct->function;
- if(pfct){
- fcttype = "type: ";
- //Check for private, protected and public
- if(pfct->isPublic())
- fcttype = "public ";
- if(pfct->isProtected())
- fcttype = "protected ";
- if(pfct->isPrivate())
- fcttype = "private ";
-
- if(pfct->isVirtual())
- fcttype += "virtual ";
- if(pfct->isPureVirtual())
- fcttype += "pure virtual ";
-
- if(pfct->isSignal())
- fcttype += "Signal ";
- if(pfct->isSlot())
- fcttype += "Slot ";
- if(pfct->isNormal())
- fcttype += "Normal ";
- if(pfct->isInvokable())
- fcttype += "Invokable ";
- }
- out << fcttype << fctstring;
- ret << tmp;
- }
- return ret;
-}
-//--->
-
-//<------------------------------------------------------- Start of Q_PROPERTY checks
-/***********************************
-Function that checks all Property
-which will occur in the MetaData
-***********************************/
-QList<PROPERTYITEM*> ParseManager::checkMetadataProperties(const QList<QList<PROPERTYITEM*> > &classproplist
- , const QList<QList<FUNCTIONITEM*> > &classfctlist
- , const QList<QList<PROPERTYITEM*> > &iclassproplist
- , const QList<QList<FUNCTIONITEM*> > &iclassfctlist)
-{
- QList<PROPERTYITEM*> missingiprops;
- //assign the property functions
- foreach(QList<PROPERTYITEM*>proplist, classproplist){
- foreach(PROPERTYITEM* prop, proplist){
- assignPropertyFunctions(prop, classfctlist);
- }
- }
-
- foreach(QList<PROPERTYITEM*>proplist, iclassproplist){
- foreach(PROPERTYITEM* prop, proplist){
- assignPropertyFunctions(prop, iclassfctlist);
- }
- }
-
- //Compare each qproperty from interface with qproperty from header (incl. baseclass functions)
- QList<PROPERTYITEM*> ippts;
- foreach(QList<PROPERTYITEM*>ipropertylist, iclassproplist){
- ippts.clear();
- //check if one header class contains all function from one interface header class
- if(classproplist.count() > 0){
- foreach(QList<PROPERTYITEM*>propertylist, classproplist){
- QList<PROPERTYITEM*> tmpl = containsAllPropertyFunction(propertylist, ipropertylist);
- if(tmpl.size() == 0)
- ippts.clear();
- else
- ippts.append(tmpl);
- }
- }
- else {
- foreach(PROPERTYITEM *pprop, ipropertylist){
- pprop->classWichIsNotFound << "<all classes>";
- QString name = pprop->ast->property_name->name->identifier()->chars();
- Trace("- Property: <all classes>::" + name + " not found!");
- }
- ippts.append(ipropertylist);
- }
- missingiprops.append(ippts);
- }
- return missingiprops;
-}
-
-static QString findName(ExpressionAST *ast)
-{
- // The "old" icheck code assumed that functions were only a single identifier, so I'll assume the same:
- if (NameAST *nameAST = ast->asName())
- return nameAST->name->identifier()->chars();
- else
- return QString();
-}
-
-/**************************************
-Function that resolves the dependensies
-between Q_PROPERTY
-and thier READ, WRITE, NOTIFY and RESET
-functions.
-***************************************/
-void ParseManager::assignPropertyFunctions(PROPERTYITEM* prop, const QList<QList<FUNCTIONITEM*> > &fctlookuplist)
-{
- //get the name of the needed functions
- QString readfctname;
- QString writefctname;
- QString resetfctname;
- QString notifyfctname;
-
- int needtofind = 0;
- if(prop->readAst){
- readfctname = findName(prop->readAst);
- needtofind++;
- }
- if(prop->writeAst){
- writefctname = findName(prop->writeAst);
- needtofind++;
- }
- if(prop->resetAst){
- resetfctname = findName(prop->resetAst);
- needtofind++;
- }
- if(prop->notifyAst){
- notifyfctname = findName(prop->notifyAst);
- needtofind++;
- }
- //Now iterate over all function to find all functions wich are defined in the Q_PROPERTY macro
- if(needtofind > 0){
- prop->foundalldefinedfct = false;
- foreach(QList<FUNCTIONITEM*> fctlist, fctlookuplist){
- foreach(FUNCTIONITEM* pfct, fctlist){
- QString fctname = pfct->trlUnit->spell(pfct->function->sourceLocation());
- //check the function type against the property type
- FullySpecifiedType retTy = pfct->function->returnType();
-
- if (!fctname.isEmpty() && retTy.isValid()) {
- if(prop->readAst && fctname == readfctname){
- if (prop->type != retTy)
- continue;
- prop->readFct = pfct;
- needtofind--;
- }
- if(prop->writeAst && fctname == writefctname){
- prop->writeFct = pfct;
- needtofind--;
- }
- if(prop->resetAst && fctname == resetfctname){
- prop->resetFct = pfct;
- needtofind--;
- }
- if(prop->notifyAst && fctname == notifyfctname){
- prop->notifyFct = pfct;
- needtofind--;
- }
- if(needtofind <= 0){
- //a flag that indicates if a function was missing
- prop->foundalldefinedfct = true;
- return;
- }
- }
- }
- }
- }
-}
-
-/**************************************
-Function that checks if all functions
-dependencies in Q_PROPERTY have the
-same arguments and retunr value.
-***************************************/
-QList<PROPERTYITEM*> ParseManager::containsAllPropertyFunction(const QList<PROPERTYITEM*> &classproplist, const QList<PROPERTYITEM*> &iclassproplist)
-{
- QList<PROPERTYITEM*> ret;
- foreach(PROPERTYITEM* ipropt, iclassproplist){
- if(ipropt->foundalldefinedfct){
- bool found = false;
- QStringList missingimplinclasses;
- ClassSpecifierAST* clspec = 0;
- QString classname = "";
- foreach(PROPERTYITEM* propt, classproplist){
- if(clspec != propt->highestlevelclass->classspec){
- clspec = propt->highestlevelclass->classspec;
- //get the classname
- unsigned int firsttoken = clspec->name->firstToken();
- classname += propt->trlUnit->spell(firsttoken);
- if(missingimplinclasses.indexOf(classname) < 0)
- missingimplinclasses.push_back(classname);
- }
- if(propt->isEqualTo(ipropt)){
- found = true;
- missingimplinclasses.clear();
- Trace("- Property: " + classname + "::" + propt->ast->property_name->name->identifier()->chars() + " found");
- break;
- }
- }
- if(!found){
- ipropt->classWichIsNotFound.append(missingimplinclasses);
- ret.push_back(ipropt);
- QString classname = ipropt->trlUnit->spell(ipropt->highestlevelclass->classspec->name->firstToken());
- Trace("- Property: " + classname + "::" + ipropt->ast->property_name->name->identifier()->chars() + " not found!");
- }
- }
- else{
- QString classname = ipropt->trlUnit->spell(ipropt->highestlevelclass->classspec->name->firstToken());
- Overview oo;
- QString proptype = oo(ipropt->type);
- Trace("- Property: " + classname + "::" + proptype + " functions are missing!");
- ret.push_back(ipropt);
- }
- }
- return ret;
-}
-
-/************************************
-Function that gives back an error
-string for a Q_PROPERTY mismatch.
-************************************/
-QStringList ParseManager::getErrorMessage(PROPERTYITEM* ppt)
-{
- QStringList ret;
- QString pptstring = "";
-
- if(!ppt->foundalldefinedfct)
- {
- QString tmp;
- QTextStream out(&tmp);
-
- unsigned int firsttoken = ppt->highestlevelclass->classspec->name->firstToken();
- unsigned int lasttoken = ppt->highestlevelclass->classspec->name->lastToken();
- for(unsigned int i = firsttoken; i < lasttoken; i++){
- out << ppt->trlUnit->spell(i);
- }
- out << "::";
- firsttoken = ppt->ast->firstToken();
- lasttoken = ppt->ast->lastToken();
- for(unsigned int i = firsttoken; i <= lasttoken; i++){
- out << ppt->trlUnit->spell(i) << " ";
- }
- out << endl << " -";
- if(ppt->readAst && !ppt->readFct)
- out << "READ ";
- if(ppt->writeAst && !ppt->writeFct)
- out << "WRITE ";
- if(ppt->resetAst && !ppt->resetFct)
- out << "RESET.";
- if(ppt->notifyAst && !ppt->notifyFct)
- out << "NOTIFY ";
- out << "functions missing." << endl;
- ret << tmp;
- }
- for(int i = 0; i < ppt->classWichIsNotFound.size(); i++){
- QString tmp;
- QTextStream out(&tmp);
-
- pptstring = ppt->classWichIsNotFound[i];
- pptstring += "::";
-
- unsigned int firsttoken = ppt->ast->firstToken();
- unsigned int lasttoken = ppt->ast->lastToken();
- for(unsigned int i = firsttoken; i <= lasttoken; i++){
- pptstring += ppt->trlUnit->spell(i);
- pptstring += " ";
- }
-
- out << pptstring;
- ret << tmp;
- }
- return ret;
-}
-//--->
-
-
-//<------------------------------------------------------- Start of Q_ENUMS checks
-/***********************************
-Function that checks all enums
-which will occur in the MetaData
-***********************************/
-QList<QENUMITEM*> ParseManager::checkMetadataEnums(const QList<QList<QENUMITEM*> > &classqenumlist
- , const QList<QList<ENUMITEM*> > &classenumlist
- , const QList<QList<QENUMITEM*> > &iclassqenumlist
- , const QList<QList<ENUMITEM*> > &iclassenumlist)
-{
- QList<QENUMITEM*> missingiqenums;
- //assign the property functions
- foreach(QList<QENUMITEM*>qenumlist, classqenumlist){
- foreach(QENUMITEM* qenum, qenumlist){
- assignEnumValues(qenum, classenumlist);
- }
- }
- foreach(QList<QENUMITEM*>qenumlist, iclassqenumlist){
- foreach(QENUMITEM* qenum, qenumlist){
- assignEnumValues(qenum, iclassenumlist);
- }
- }
-
- //Compare each qenum from interface with qenum from header (incl. baseclass functions)
- QList<QENUMITEM*> iqenums;
- foreach(QList<QENUMITEM*>iqenumlist, iclassqenumlist){
- iqenums.clear();
- //check if one header class contains all function from one interface header class
- if(classqenumlist.count() > 0){
- foreach(QList<QENUMITEM*>qenumlist, classqenumlist){
- QList<QENUMITEM*> tmpl = containsAllEnums(qenumlist, iqenumlist);
- if(tmpl.size() == 0)
- iqenums.clear();
- else
- iqenums.append(tmpl);
-
- }
- }
- else {
- foreach(QENUMITEM *qenum, iqenumlist){
- qenum->classWichIsNotFound << "<all classes>";
- Trace("- Enum: <all classes>::" + qenum->name + " not found!");
- }
- iqenums.append(iqenumlist);
- }
- missingiqenums.append(iqenums);
- }
-
- return missingiqenums;
-}
-
-/*********************************************
-Helper function which creates a string out of
-an enumerator including its values.
-*********************************************/
-QStringList ParseManager::getEnumValueStringList(ENUMITEM *penum, QString mappedenumname/* = ""*/)
-{
- QStringList ret;
- EnumSpecifierAST *penumsec = penum->ast;
- QString enumname = penum->trlUnit->spell(penumsec->name->firstToken());
- int enumvalue = 0;
- //now iterrate over all enumitems and create a string like following:
- //EnumName.EnumItemName.Value
- //ConnectionState.disconnected.0
- for (EnumeratorListAST *plist = penum->ast->enumerator_list; plist; plist = plist->next) {
- QString value = enumname;
- if(mappedenumname.size() > 0)
- value = mappedenumname;
- value += ".";
- value += penum->trlUnit->spell(plist->value->identifier_token);
- value += ".";
- if(plist->value->equal_token > 0 && plist->value->expression){
- QString v = penum->trlUnit->spell(plist->value->expression->firstToken());
- bool ch;
- int newval = enumvalue;
- if(v.indexOf("0x") >= 0)
- newval = v.toInt(&ch, 16);
- else
- newval = v.toInt(&ch, 10);
- if(ch)
- enumvalue = newval;
- }
- value += QString::number(enumvalue);
- enumvalue++;
- // now add this enumitem string in the VALUE list
- ret << value;
- }
- return ret;
-}
-
-/**************************************
-Function that resolves the dependensies
-between Q_ENUMS and enums.
-***************************************/
-void ParseManager::assignEnumValues(QENUMITEM* qenum, const QList<QList<ENUMITEM*> > &enumlookuplist)
-{
- //iterate over all enums and find the one with the same name like enumname
- bool found = false;
- foreach (QList<ENUMITEM*> penumlist, enumlookuplist) {
- foreach(ENUMITEM *penum, penumlist){
- EnumSpecifierAST *penumsec = penum->ast;
- QString enumname1 = penum->trlUnit->spell(penumsec->name->firstToken());
- if(qenum->name == enumname1){
- qenum->values << getEnumValueStringList(penum);
- found = true;
- break;
- }
- }
- if(!found)
- qenum->foundallenums = false;
- }
-}
-
-/***********************************
-Function that checkt if the Q_ENUMS
-are completed defined and if the
-Enum values are the same.
-***********************************/
-QList<QENUMITEM*> ParseManager::containsAllEnums(const QList<QENUMITEM*> &classqenumlist, const QList<QENUMITEM*> &iclassqenumlist)
-{
- Overview oo;
-
- QList<QENUMITEM*> ret;
- foreach(QENUMITEM* iqenum, iclassqenumlist){
- bool found = false;
- QStringList missingimplinclasses;
- ClassSpecifierAST* clspec = 0;
- QString classname = "";
- foreach(QENUMITEM* qenum, classqenumlist){
- if(clspec != qenum->highestlevelclass->classspec){
- clspec = qenum->highestlevelclass->classspec;
- //get the classname
- classname += oo(clspec->symbol);
- if(missingimplinclasses.indexOf(classname) < 0)
- missingimplinclasses.push_back(classname);
- }
- if(qenum->isEqualTo(iqenum)){
- found = true;
- missingimplinclasses.clear();
- Trace("- Enum: " + classname + "::" + qenum->name + " found");
- break;
- }
- }
- if(!found){
- iqenum->classWichIsNotFound.append(missingimplinclasses);
- ret.push_back(iqenum);
- QString classname = oo(iqenum->highestlevelclass->classspec->symbol);
- Trace("- Enum: " + classname + "::" + iqenum->name + " not found!");
- }
- }
- return ret;
-}
-
-/************************************
-Function that gives back an error
-string for a Q_ENUMS mismatch.
-************************************/
-QStringList ParseManager::getErrorMessage(QENUMITEM* qenum)
-{
- Overview oo;
- QStringList ret;
-
- if(!qenum->foundallenums)
- {
- QString tmp;
- QTextStream out(&tmp);
-
- out << oo(qenum->highestlevelclass->classspec->symbol);
- out << "::Q_ENUMS " << qenum->name << " enum missing.";
- ret << tmp;
- }
-
- for (int i = 0; i < qenum->classWichIsNotFound.size(); i++){
- QString tmp;
- QTextStream out(&tmp);
-
- out << qenum->classWichIsNotFound[i] << "::Q_ENUMS "
- << qenum->name;
- ret << tmp;
- }
- return ret;
-}
-//--->
-
-//<------------------------------------------------------- Start of Q_FLAGS checks
-/***********************************
-Function that checks all flags
-which will occur in the MetaData
-***********************************/
-QList<QFLAGITEM*> ParseManager::checkMetadataFlags(const QList<QList<QFLAGITEM*> > &classqflaglist
- , const QList<QList<QDECLAREFLAGSITEM*> > &classqdeclareflaglist
- , const QList<QList<ENUMITEM*> > &classenumlist
- , const QList<QList<QFLAGITEM*> > &iclassqflaglist
- , const QList<QList<QDECLAREFLAGSITEM*> > &iclassqdeclareflaglist
- , const QList<QList<ENUMITEM*> > &iclassenumlist)
-{
- QList<QFLAGITEM*> missingqflags;
- //assign the enums to the flags
- foreach(QList<QFLAGITEM*>qflaglist, classqflaglist){
- foreach(QFLAGITEM* qflag, qflaglist){
- assignFlagValues(qflag, classqdeclareflaglist, classenumlist);
- }
- }
- foreach(QList<QFLAGITEM*>qflaglist, iclassqflaglist){
- foreach(QFLAGITEM* qflag, qflaglist){
- assignFlagValues(qflag, iclassqdeclareflaglist, iclassenumlist);
- }
- }
-
- //Compare each qenum from interface with qenum from header (incl. baseclass functions)
- QList<QFLAGITEM*> iqflags;
- foreach(QList<QFLAGITEM*>iqflaglist, iclassqflaglist){
- iqflags.clear();
- //check if one header class contains all function from one interface header class
- if(classqflaglist.count() >0){
- foreach(QList<QFLAGITEM*>qflaglist, classqflaglist){
- QList<QFLAGITEM*> tmpl = containsAllFlags(qflaglist, iqflaglist);
- if(tmpl.size() == 0)
- iqflags.clear();
- else
- iqflags.append(tmpl);
-
- }
- }
- else {
- foreach(QFLAGITEM *pflag, iqflaglist){
- pflag->classWichIsNotFound << "<all classes>";
- QString name= pflag->name->identifier()->chars();
- Trace("- Flag: <all classes>::" + name + " not found!");
- }
- iqflags.append(iqflaglist);
- }
- missingqflags.append(iqflags);
- }
- return missingqflags;
-}
-
-/**************************************
-Function that resolves the dependensies
-between Q_FLAG, Q_DECLARE_FLAGS
-and enums.
-***************************************/
-void ParseManager::assignFlagValues(QFLAGITEM* qflags, const QList<QList<QDECLAREFLAGSITEM*> > &qdeclareflagslookuplist, const QList<QList<ENUMITEM*> > &enumlookuplist)
-{
- QString enumname;
-
- //try to find if there is a deflare flag macro with the same name as in qflagname
- Scope *classMembers = qflags->highestlevelclass->classspec->symbol;
- Symbol *s = classMembers->find(qflags->name);
- if (s->isTypedef()) {
- FullySpecifiedType ty = s->type();
- if (Enum *e = ty->asEnumType()) {
- enumname = e->name()->identifier()->chars();
- }
- }
-
- //now we have the right enum name now we need to find the enum
- bool found = false;
- foreach(QList<ENUMITEM*> enumitemlist, enumlookuplist){
- foreach(ENUMITEM* enumitem, enumitemlist){
- EnumSpecifierAST *penumspec = enumitem->ast;
- QString enumspecname = enumitem->trlUnit->spell(penumspec->name->firstToken());
- if(enumspecname == enumname){
- qflags->enumvalues << getEnumValueStringList(enumitem, qflags->name->identifier()->chars());
- found = true;
- break;
- }
- }
- if(found)
- break;
- }
- if(!found)
- qflags->foundallenums = false;
-}
-
-/*****************************************
-Function that compares if all enums
-and flags assigned by using the Q_FLAGS
-are complete defined.
-*****************************************/
-QList<QFLAGITEM*> ParseManager::containsAllFlags(const QList<QFLAGITEM*> &classqflaglist, const QList<QFLAGITEM*> &iclassqflaglist)
-{
- QList<QFLAGITEM*> ret;
- foreach(QFLAGITEM* iqflags, iclassqflaglist){
- if(iqflags->foundallenums){
- bool found = false;
- QStringList missingimplinclasses;
- ClassSpecifierAST* clspec = 0;
- QString classname = "";
- foreach(QFLAGITEM* qflags, classqflaglist){
- if(clspec != qflags->highestlevelclass->classspec){
- clspec = qflags->highestlevelclass->classspec;
- //get the classname
- classname += clspec->symbol->name()->identifier()->chars();
- if(missingimplinclasses.indexOf(classname) < 0)
- missingimplinclasses.push_back(classname);
- }
- if(qflags->isEqualTo(iqflags)){
- found = true;
- missingimplinclasses.clear();
- Trace("- Flag: " + classname + "::" + qflags->name->identifier()->chars() + " found");
- break;
- }
- }
- if(!found){
- iqflags->classWichIsNotFound.append(missingimplinclasses);
- ret.push_back(iqflags);
- QString classname = iqflags->highestlevelclass->classspec->symbol->name()->identifier()->chars();
- Trace("- Flag: " + classname + "::" + iqflags->name->identifier()->chars() + " not found!");
- }
- }
- else
- ret.push_back(iqflags);
- }
- return ret;
-}
-
-/************************************
-Function that gives back an error
-string for a Q_FLAGS mismatch.
-************************************/
-QStringList ParseManager::getErrorMessage(QFLAGITEM* pfg)
-{
- Overview oo;
- QStringList ret;
-
- if(!pfg->foundallenums)
- {
- QString tmp;
- QTextStream out(&tmp);
-
- out << oo(pfg->highestlevelclass->classspec->symbol->name());
- out << "::Q_FLAGS "<<pfg->name->identifier()->chars()<< ": enum missing.";
- ret << tmp;
- }
- for(int i = 0; i < pfg->classWichIsNotFound.size(); i++){
- QString tmp;
- QTextStream out(&tmp);
-
- out << pfg->classWichIsNotFound[i] << "::Q_FLAGS " << oo(pfg->name);
- ret << tmp;
- }
- return ret;
-}
-
-inline QString ParseManager::getTraceFuntionString(const FUNCTIONITEM *fctitem, const QString& classname)
-{
- QString ret;
-
- if(fctitem->function->isPublic())
- ret = "public ";
- if(fctitem->function->isProtected())
- ret = "protected ";
- if(fctitem->function->isPrivate())
- ret = "private ";
-
- if(fctitem->function->isVirtual())
- ret += "virtual ";
- if(fctitem->function->isPureVirtual())
- ret += "pure virtual ";
-
- if(fctitem->function->isSignal())
- ret += "Signal ";
- if(fctitem->function->isSlot())
- ret += "Slot ";
- if(fctitem->function->isNormal())
- ret += "Normal ";
- if(fctitem->function->isInvokable())
- ret += "Invokable ";
-
- ret += classname;
- ret += "::";
- ret += fctitem->trlUnit->spell(fctitem->function->sourceLocation());
- return ret;
-}
-
-void ParseManager::Trace(QString value)
-{
- if(::m_resultFile){
- QTextStream out(::m_resultFile);
- if(value == "\n")
- out << endl;
- else
- out << value << endl;
- }
-}
-
-PROPERTYITEM *PROPERTYITEM::create(QtPropertyDeclarationAST *ast, const CLASSLISTITEM *clazz)
-{
- PROPERTYITEM *item = new PROPERTYITEM;
- item->ast = ast;
- item->highestlevelclass = clazz;
- item->trlUnit = clazz->trlUnit;
-
- if (ast->type_id) {
- Bind bind(item->trlUnit);
- item->type = bind(ast->type_id, clazz->classspec->symbol);
- }
-
- for (QtPropertyDeclarationItemListAST *it = ast->property_declaration_items;
- it; it = it->next) {
- if (!it->value->item_name_token)
- continue;
- const char *name = item->trlUnit->spell(it->value->item_name_token);
- if (!qstrcmp(name, "READ"))
- item->readAst = it->value->expression;
- else if (!qstrcmp(name, "WRITE"))
- item->writeAst = it->value->expression;
- else if (!qstrcmp(name, "RESET"))
- item->resetAst = it->value->expression;
- else if (!qstrcmp(name, "NOTIFY"))
- item->notifyAst = it->value->expression;
- }
-
- return item;
-}
-
-//--->
diff --git a/tests/auto/icheckbuild/parsemanager.h b/tests/auto/icheckbuild/parsemanager.h
deleted file mode 100644
index 7dd5b0b0b8..0000000000
--- a/tests/auto/icheckbuild/parsemanager.h
+++ /dev/null
@@ -1,304 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
-** Contact: http://www.qt-project.org/legal
-**
-** This file is part of Qt Creator.
-**
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and Digia. For licensing terms and
-** conditions see http://qt.digia.com/licensing. For further information
-** use the contact form at http://qt.digia.com/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 2.1 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 2.1 requirements
-** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
-**
-** In addition, as a special exception, Digia gives you certain additional
-** rights. These rights are described in the Digia Qt LGPL Exception
-** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
-**
-****************************************************************************/
-
-/*
-** Description:
-**
-** The ParseManager parses and compares to different header files
-** of its metadata. This can be used for checking if an Interface
-** is implemented complete.
-**
-** How to use it:
-**
-** //Parse the interface header
-** ParseManager* iParseManager = new ParseManager();
-** iParseManager->setIncludePath(iIncludepathlist);
-** iParseManager->parse(iFilelist);
-**
-** //Parse the header that needs to be compared against the interface header
-** ParseManager* chParseManager = new ParseManager();
-** chIncludepathlist << getQTIncludePath();
-* chParseManager->setIncludePath(chIncludepathlist);
-** chParseManager->parse(chFilelist);
-**
-** if(!chParseManager->checkAllMetadatas(iParseManager)){
-** cout << "Following interface items are missing:" << endl;
-** QStringList errorlist = chParseManager->getErrorMsg();
-** foreach(QString msg, errorlist){
-** cout << (const char *)msg.toLatin1() << endl;
-** }
-** return -1;
-** }
-** else
-** cout << "Interface is full defined.";
-*/
-
-#ifndef PARSEMANAGER_H
-#define PARSEMANAGER_H
-
-#include "cplusplus/CppDocument.h"
-#include "ASTfwd.h"
-#include "FullySpecifiedType.h"
-
-#include <QObject>
-#include <QList>
-#include <QFuture>
-#include <QStringList>
-#include <QFile>
-
-namespace CppTools{
- namespace Internal{
- class CppPreprocessor;
- }
-}
-
-namespace CPlusPlus {
- class CLASSLISTITEM
- {
- public:
- CPlusPlus::TranslationUnit* trlUnit;
- ClassSpecifierAST* classspec;
- };
- class CLASSTREE
- {
- public:
- CLASSLISTITEM* highestlevelclass;
- QList<CLASSLISTITEM*> classlist;
- };
- class FUNCTIONITEM
- {
- public:
- const CLASSLISTITEM* highestlevelclass;
- CPlusPlus::TranslationUnit* trlUnit;
- ClassSpecifierAST* classAst;
- QStringList classWichIsNotFound;
- CPlusPlus::Function* function;
-
- bool isEqualTo(FUNCTIONITEM* cpfct, bool ignoreName = true);
-
- FUNCTIONITEM()
- {
- highestlevelclass = 0;
- trlUnit = 0;
- classAst = 0;
- function = 0;
- }
- };
- class PROPERTYITEM
- {
- public:
- const CLASSLISTITEM* highestlevelclass;
- QStringList classWichIsNotFound;
- QtPropertyDeclarationAST *ast;
- CPlusPlus::TranslationUnit* trlUnit;
- FullySpecifiedType type;
- ExpressionAST *readAst;
- FUNCTIONITEM *readFct;
- ExpressionAST *writeAst;
- FUNCTIONITEM *writeFct;
- ExpressionAST *resetAst;
- FUNCTIONITEM *resetFct;
- ExpressionAST *notifyAst;
- FUNCTIONITEM *notifyFct;
- bool foundalldefinedfct;
-
- bool isEqualTo(PROPERTYITEM* cpppt);
- PROPERTYITEM()
- {
- highestlevelclass = 0;
- ast = 0;
- trlUnit = 0;
- readAst = 0;
- readFct = 0;
- writeAst = 0;
- writeFct = 0;
- resetAst = 0;
- resetFct = 0;
- notifyAst = 0;
- notifyFct = 0;
- foundalldefinedfct = false;
- }
-
- static PROPERTYITEM *create(QtPropertyDeclarationAST *ast, const CLASSLISTITEM *clazz);
- };
-
- class QENUMITEM
- {
- public:
- const CLASSLISTITEM* highestlevelclass;
- QStringList classWichIsNotFound;
- QString name;
- //an item in this list will be shown like:
- //EnumName.EnumItemName.Value
- //ConnectionState.disconnected.0
- QStringList values;
- bool foundallenums;
-
- bool isEqualTo(QENUMITEM *cpenum);
- QENUMITEM()
- {
- highestlevelclass = 0;
- values.clear();
- foundallenums = true;
- }
- };
-
- class ENUMITEM
- {
- public:
- const CLASSLISTITEM* highestlevelclass;
- CPlusPlus::TranslationUnit* trlUnit;
- QStringList classWichIsNotFound;
- EnumSpecifierAST* ast;
-
- ENUMITEM()
- {
- highestlevelclass = 0;
- trlUnit = 0;
- ast = 0;
- }
- };
-
- class QFLAGITEM
- {
- public:
- const CLASSLISTITEM* highestlevelclass;
- const Name *name;
- QStringList classWichIsNotFound;
- QStringList enumvalues;
- bool foundallenums;
-
- bool isEqualTo(QFLAGITEM *cpflag);
- QFLAGITEM()
- {
- highestlevelclass = 0;
- enumvalues.clear();
- foundallenums = true;
- }
- };
-
- class QDECLAREFLAGSITEM
- {
- public:
- const CLASSLISTITEM* highestlevelclass;
- CPlusPlus::TranslationUnit* trlUnit;
- QStringList classWichIsNotFound;
- QtFlagsDeclarationAST* ast;
-
- QDECLAREFLAGSITEM()
- {
- highestlevelclass = 0;
- trlUnit = 0;
- ast = 0;
- }
- };
-
- static QFile* m_resultFile = 0;
- class ParseManager : public QObject
- {
- Q_OBJECT
- public:
- ParseManager();
- virtual ~ParseManager();
- void setIncludePath(const QStringList &includePath);
- void parse(const QStringList &sourceFiles);
- bool checkAllMetadatas(ParseManager* pInterfaceParserManager, QString resultfile);
- CppTools::Internal::CppPreprocessor *getPreProcessor() { return pCppPreprocessor; }
- QList<CLASSTREE*> CreateClassLists(bool isInterfaceHeader);
- QStringList getErrorMsg() { return m_errormsgs; }
-
- private:
- void parse(CppTools::Internal::CppPreprocessor *preproc, const QStringList &files);
- void Trace(QString value);
- inline QString getTraceFuntionString(const FUNCTIONITEM* fctitem, const QString& classname);
- void getBaseClasses(const CLASSLISTITEM* pclass
- , QList<CLASSLISTITEM*> &baseclasslist
- , const QList<CLASSLISTITEM*> &allclasslist
- , int level
- , bool isInterfaceHeader);
- void getElements(QList<FUNCTIONITEM*> &functionlist
- , QList<PROPERTYITEM*> &propertylist
- , QList<QENUMITEM*> &qenumlist
- , QList<ENUMITEM*> &enumlist
- , QList<QFLAGITEM*> &qflaglist
- , QList<QDECLAREFLAGSITEM*> &qdeclareflaglist
- , const QList<CLASSLISTITEM*> classitems
- , const CLASSLISTITEM* highestlevelclass);
-
- //<--- for Metadata functions checks
- QList<FUNCTIONITEM*> checkMetadataFunctions(const QList<QList<FUNCTIONITEM*> > &classfctlist, const QList<QList<FUNCTIONITEM*> > &iclassfctlist);
- bool isMetaObjFunction(FUNCTIONITEM* fct);
- QList<FUNCTIONITEM*> containsAllMetadataFunction(const QList<FUNCTIONITEM*> &classfctlist, const QList<FUNCTIONITEM*> &iclassfctlist);
- QStringList getErrorMessage(FUNCTIONITEM* fct);
- //--->
-
- //<--- for Q_PROPERTY functions checks
- QList<PROPERTYITEM*> checkMetadataProperties(const QList<QList<PROPERTYITEM*> > &classproplist
- , const QList<QList<FUNCTIONITEM*> > &classfctlist
- , const QList<QList<PROPERTYITEM*> > &iclassproplist
- , const QList<QList<FUNCTIONITEM*> > &iclassfctlist);
- void assignPropertyFunctions(PROPERTYITEM* prop, const QList<QList<FUNCTIONITEM*> > &fctlookuplist);
- QList<PROPERTYITEM*> containsAllPropertyFunction(const QList<PROPERTYITEM*> &classproplist, const QList<PROPERTYITEM*> &iclassproplist);
- QStringList getErrorMessage(PROPERTYITEM* ppt);
- //--->
-
- //<--- for Q_ENUMS checks
- QList<QENUMITEM*> checkMetadataEnums(const QList<QList<QENUMITEM*> > &classqenumlist
- , const QList<QList<ENUMITEM*> > &classenumlist
- , const QList<QList<QENUMITEM*> > &iclassqenumlist
- , const QList<QList<ENUMITEM*> > &iclassenumlist);
- QStringList getEnumValueStringList(ENUMITEM *penum, QString mappedenumname = "");
- void assignEnumValues(QENUMITEM* qenum, const QList<QList<ENUMITEM*> > &enumlookuplist);
- QList<QENUMITEM*> containsAllEnums(const QList<QENUMITEM*> &classqenumlist, const QList<QENUMITEM*> &iclassqenumlist);
- QStringList getErrorMessage(QENUMITEM* qenum);
- //--->
-
- //<--- for QFlags checks --->
- QList<QFLAGITEM*> checkMetadataFlags(const QList<QList<QFLAGITEM*> > &classqflaglist
- , const QList<QList<QDECLAREFLAGSITEM*> > &classqdeclareflaglist
- , const QList<QList<ENUMITEM*> > &classenumlist
- , const QList<QList<QFLAGITEM*> > &iclassqflaglist
- , const QList<QList<QDECLAREFLAGSITEM*> > &iclassqdeclareflaglist
- , const QList<QList<ENUMITEM*> > &iclassenumlist);
- void assignFlagValues(QFLAGITEM* qflags, const QList<QList<QDECLAREFLAGSITEM*> > &qdeclareflagslookuplist, const QList<QList<ENUMITEM*> > &enumlookuplist);
- QList<QFLAGITEM*> containsAllFlags(const QList<QFLAGITEM*> &classqflaglist, const QList<QFLAGITEM*> &iclassqflaglist);
- QStringList getErrorMessage(QFLAGITEM* pfg);
- //--->
-
- private:
- // cache
- QStringList m_includePaths;
- QStringList m_frameworkPaths;
- QByteArray m_definedMacros;
- CppTools::Internal::CppPreprocessor* pCppPreprocessor;
- QString m_strHeaderFile;
- QStringList m_errormsgs;
- };
-}
-#endif // PARSEMANAGER_H
diff --git a/tests/auto/ioutils/tst_ioutils.cpp b/tests/auto/ioutils/tst_ioutils.cpp
index 6cba3949e7..4ccb1efca2 100644
--- a/tests/auto/ioutils/tst_ioutils.cpp
+++ b/tests/auto/ioutils/tst_ioutils.cpp
@@ -75,7 +75,7 @@ void tst_IoUtils::quoteArg()
QFETCH(QString, in);
QFETCH(QString, out);
- QCOMPARE(ProFileEvaluatorInternal::IoUtils::shellQuote(in), out);
+ QCOMPARE(QMakeInternal::IoUtils::shellQuote(in), out);
}
QTEST_MAIN(tst_IoUtils)
diff --git a/tests/auto/profilewriter/tst_profilewriter.cpp b/tests/auto/profilewriter/tst_profilewriter.cpp
index 8c23c09f42..85c6ec6fdd 100644
--- a/tests/auto/profilewriter/tst_profilewriter.cpp
+++ b/tests/auto/profilewriter/tst_profilewriter.cpp
@@ -38,8 +38,10 @@
static void print(const QString &fileName, int lineNo, const QString &msg)
{
- if (lineNo)
+ if (lineNo > 0)
qWarning("%s(%d): %s", qPrintable(fileName), lineNo, qPrintable(msg));
+ else if (lineNo)
+ qWarning("%s: %s", qPrintable(fileName), qPrintable(msg));
else
qWarning("%s", qPrintable(msg));
}
diff --git a/tests/auto/qml/persistenttrie/completion.data b/tests/auto/qml/persistenttrie/completion.data
new file mode 100644
index 0000000000..b94aeb1819
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/completion.data
@@ -0,0 +1,10 @@
+com.bla.Pippo 0.1
+com.bla.Pippo 2.0
+com.bla.Pippo 2.1
+com.bla.Pallino 0.1
+QtQuick 1.0
+
+pa
+com.bla.Pallino 0.1
+
+13
diff --git a/tests/auto/qml/persistenttrie/intersect.data b/tests/auto/qml/persistenttrie/intersect.data
new file mode 100644
index 0000000000..a388f08078
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/intersect.data
@@ -0,0 +1,81 @@
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+com.bla.Pippo 0.1
+com.bla.Pippo 2.0
+com.bla.Pippo 2.1
+com.bla.Pallino 0.1
+QtQuick 1.0
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+com.bla.Pippo 0.1
+com.bla.Pippo 2.0
+com.bla.Pippo 2.1
+com.bla.Pallino 0.1
+QtQuick 1.0
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+a
+artz
+tzj
+tzg
+art
+tzg
diff --git a/tests/auto/qml/persistenttrie/listAll.data b/tests/auto/qml/persistenttrie/listAll.data
new file mode 100644
index 0000000000..79a3477b2e
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/listAll.data
@@ -0,0 +1,26 @@
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+com.bla.Pippo 0.1
+com.bla.Pippo 2.0
+com.bla.Pippo 2.1
+com.bla.Pallino 0.1
+QtQuick 1.0
diff --git a/tests/auto/qml/persistenttrie/merge.data b/tests/auto/qml/persistenttrie/merge.data
new file mode 100644
index 0000000000..a388f08078
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/merge.data
@@ -0,0 +1,81 @@
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+abbc
+a
+acc
+tzk
+ttk
+mm
+
+com.bla.Pippo 0.1
+com.bla.Pippo 2.0
+com.bla.Pippo 2.1
+com.bla.Pallino 0.1
+QtQuick 1.0
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+a
+artz
+tzj
+tzg
+art
+tzg
+
+com.bla.Pippo 0.1
+com.bla.Pippo 2.0
+com.bla.Pippo 2.1
+com.bla.Pallino 0.1
+QtQuick 1.0
+
+abbc
+ab
+mmk
+ab
+abc
+ab
+
+a
+artz
+tzj
+tzg
+art
+tzg
diff --git a/tests/auto/qml/persistenttrie/persistenttrie.pro b/tests/auto/qml/persistenttrie/persistenttrie.pro
new file mode 100644
index 0000000000..03f039fcb7
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/persistenttrie.pro
@@ -0,0 +1,25 @@
+include(../../qttest.pri)
+
+DEFINES+=QTCREATORDIR=\\\"$$IDE_SOURCE_TREE\\\"
+DEFINES+=TESTSRCDIR=\\\"$$PWD\\\"
+
+include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+include($$IDE_SOURCE_TREE/src/libs/languageutils/languageutils.pri)
+include($$IDE_SOURCE_TREE/src/libs/qmljs/qmljs.pri)
+
+TARGET = tst_trie_check
+
+HEADERS += tst_testtrie.h
+
+SOURCES += \
+ tst_testtrie.cpp
+
+TEMPLATE = app
+TARGET = tester
+DEFINES += QMLJS_BUILD_DIR QT_CREATOR
+
+OTHER_FILES += \
+ listAll.data \
+ intersect.data \
+ merge.data \
+ completion.data
diff --git a/tests/auto/qml/persistenttrie/tst_testtrie.cpp b/tests/auto/qml/persistenttrie/tst_testtrie.cpp
new file mode 100644
index 0000000000..601f9e1635
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/tst_testtrie.cpp
@@ -0,0 +1,374 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include "tst_testtrie.h"
+#include <qmljs/persistenttrie.h>
+
+#include <QCoreApplication>
+#include <QDebug>
+#include <QLatin1String>
+#include <QMap>
+#include <QString>
+#include <QStringList>
+#include <QTextStream>
+
+using namespace QmlJS::PersistentTrie;
+
+void tst_TestTrie::initTestCase() {
+}
+
+const bool VERBOSE=false;
+
+tst_TestTrie::tst_TestTrie() { QObject::QObject(); }
+
+void tst_TestTrie::testListAll_data()
+{
+ QTest::addColumn<QStringList>("strs");
+
+ QFile f(QString(TESTSRCDIR)+QString("/listAll.data"));
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
+ return;
+ QTextStream stream(&f);
+ int iline = 0;
+ while (true) {
+ QStringList list;
+ QString line;
+ while (true) {
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ list.append(line);
+ }
+ QTest::newRow(QString::number(iline++).toLatin1()) << list;
+ list.clear();
+ if (stream.atEnd())
+ break;
+ }
+}
+
+void tst_TestTrie::testListAll()
+{
+ QFETCH(QStringList, strs);
+ Trie trie;
+ foreach (const QString &s, strs)
+ trie.insert(s);
+ QStringList ref=strs;
+ ref.sort();
+ ref.removeDuplicates();
+ QStringList content=trie.stringList();
+ content.sort();
+ if (VERBOSE && ref != content) {
+ QDebug dbg = qDebug();
+ dbg << "ERROR inserting [";
+ bool comma = false;
+ foreach (const QString &s, strs) {
+ if (comma)
+ dbg << ",";
+ else
+ comma = true;
+ dbg << s;
+ }
+ dbg << "] one gets " << trie;
+ }
+ QCOMPARE(ref, content);
+ foreach (const QString &s,strs) {
+ if (VERBOSE && ! trie.contains(s)) {
+ qDebug() << "ERROR could not find " << s << "in" << trie;
+ }
+ QVERIFY(trie.contains(s));
+ }
+}
+
+void tst_TestTrie::testMerge_data()
+{
+ QTest::addColumn<QStringList>("str1");
+ QTest::addColumn<QStringList>("str2");
+
+ QFile f(QString(TESTSRCDIR)+QString("/merge.data"));
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
+ return;
+ QTextStream stream(&f);
+ int iline = 0;
+ while (true) {
+ QStringList list1;
+ QString line;
+ while (true) {
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ list1.append(line);
+ }
+ QStringList list2;
+ while (true) {
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ list2.append(line);
+ }
+ QTest::newRow(QString::number(iline++).toLatin1()) << list1 << list2;
+ list1.clear();
+ list2.clear();
+ if (stream.atEnd())
+ break;
+ }
+}
+
+void tst_TestTrie::testMerge()
+{
+ QFETCH(QStringList, str1);
+ QFETCH(QStringList, str2);
+ Trie trie1;
+ foreach (const QString &s, str1)
+ trie1.insert(s);
+ Trie trie2;
+ foreach (const QString &s, str2)
+ trie2.insert(s);
+ QStringList ref=str1;
+ ref.append(str2);
+ ref.sort();
+ ref.removeDuplicates();
+ Trie trie3 = trie1.mergeF(trie2);
+ QStringList content=trie3.stringList();
+ content.sort();
+ if (VERBOSE && ref != content) {
+ QDebug dbg=qDebug();
+ dbg << "ERROR merging [";
+ bool comma = false;
+ foreach (const QString &s, str1) {
+ if (comma)
+ dbg << ",";
+ else
+ comma = true;
+ dbg << s;
+ }
+ dbg << "] => " << trie1 << " and [";
+ comma = false;
+ foreach (const QString &s, str2) {
+ if (comma)
+ dbg << ",";
+ else
+ comma = true;
+ dbg << s;
+ }
+ dbg << "] => " << trie2
+ << " to " << trie3;
+ }
+ QCOMPARE(ref, content);
+}
+
+void tst_TestTrie::testIntersect_data()
+{
+ QTest::addColumn<QStringList>("str1");
+ QTest::addColumn<QStringList>("str2");
+
+ QFile f(QString(TESTSRCDIR)+QString("/intersect.data"));
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
+ return;
+ QTextStream stream(&f);
+ int iline = 0;
+ while (true) {
+ QStringList list1;
+ QString line;
+ while (true) {
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ list1.append(line);
+ }
+ QStringList list2;
+ while (true) {
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ list2.append(line);
+ }
+ QTest::newRow(QString::number(iline++).toLatin1()) << list1 << list2;
+ list1.clear();
+ list2.clear();
+ if (stream.atEnd())
+ break;
+ }
+}
+
+void tst_TestTrie::testIntersect()
+{
+ QFETCH(QStringList, str1);
+ QFETCH(QStringList, str2);
+ Trie trie1;
+ foreach (const QString &s, str1)
+ trie1.insert(s);
+ Trie trie2;
+ foreach (const QString &s, str2)
+ trie2.insert(s);
+ QSet<QString> ref1;
+ foreach (const QString &s, str1)
+ ref1.insert(s);
+ QSet<QString> ref2;
+ foreach (const QString &s, str2)
+ ref2.insert(s);
+ ref1.intersect(ref2);
+ Trie trie3 = trie1.intersectF(trie2);
+ ref2.clear();
+ foreach (const QString &s, trie3.stringList())
+ ref2.insert(s);
+ if (VERBOSE && ref1 != ref2) {
+ QDebug dbg=qDebug();
+ dbg << "ERROR intersecting [";
+ bool comma = false;
+ foreach (const QString &s, str1) {
+ if (comma)
+ dbg << ",";
+ else
+ comma = true;
+ dbg << s;
+ }
+ dbg << "] => " << trie1 << " and [";
+ comma = false;
+ foreach (const QString &s, str2) {
+ if (comma)
+ dbg << ",";
+ else
+ comma = true;
+ dbg << s;
+ }
+ dbg << "] => " << trie2
+ << " to " << trie3;
+ }
+ QCOMPARE(ref1, ref2);
+}
+
+void tst_TestTrie::testCompletion_data()
+{
+ QTest::addColumn<QStringList>("trieContents");
+ QTest::addColumn<QString>("str");
+ QTest::addColumn<QStringList>("completions");
+ QTest::addColumn<int>("flags");
+
+ QFile f(QString(TESTSRCDIR)+QString("/completion.data"));
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
+ return;
+ QTextStream stream(&f);
+ int iline = 0;
+ while (true) {
+ QStringList list1;
+ QString line;
+ while (true) {
+ line = stream.readLine();
+ if (line.isEmpty())
+ break;
+ list1.append(line);
+ }
+ QString str = stream.readLine();
+ QStringList list2;
+ while (true) {
+ line = stream.readLine();
+ if (line.isEmpty())
+ break;
+ list2.append(line);
+ }
+ int flags = stream.readLine().toInt();
+ QTest::newRow(QString::number(iline++).toLatin1()) << list1 << str << list2 << flags;
+ list1.clear();
+ list2.clear();
+ if (stream.atEnd())
+ break;
+ }
+}
+
+void tst_TestTrie::testCompletion() {
+ QFETCH(QStringList, trieContents);
+ QFETCH(QString, str);
+ QFETCH(QStringList, completions);
+ QFETCH(int, flags);
+
+ Trie trie;
+ foreach (const QString &s, trieContents)
+ trie.insert(s);
+ QStringList res = trie.complete(str, QString(), LookupFlags(flags));
+ res = matchStrengthSort(str, res);
+ if (VERBOSE && res != completions) {
+ qDebug() << "unexpected completions for " << str
+ << " in " << trie;
+ qDebug() << "expected :[";
+ foreach (const QString &s, completions) {
+ qDebug() << s;
+ }
+ qDebug() << "] got [";
+ foreach (const QString &s, res) {
+ qDebug() << s;
+ }
+ qDebug() << "]";
+ }
+ QCOMPARE(res, completions);
+}
+
+void interactiveCompletionTester(){
+ Trie trie;
+ qDebug() << "interactive completion tester, insert the strings int the trie (empty line to stop)";
+ QTextStream stream(stdin);
+ QString line;
+ while (true) {
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ trie.insert(line);
+ }
+ qDebug() << "testing Complete on " << trie;
+ while (true) {
+ qDebug() << "insert a string to complete (empty line to stop)";
+ line=stream.readLine();
+ if (line.isEmpty())
+ break;
+ QStringList res=trie.complete(line, QString(),
+ LookupFlags(CaseInsensitive|SkipChars|SkipSpaces));
+ res = matchStrengthSort(line,res);
+ qDebug() << "possible completions:[";
+ foreach (const QString &s, res) {
+ qDebug() << s;
+ }
+ qDebug() << "]";
+ }
+}
+
+#ifdef INTERACTIVE_COMPLETION_TEST
+
+int main(int , const char *[])
+{
+ interactiveCompletionTester();
+
+ return 0;
+}
+
+#else
+
+QTEST_MAIN(tst_TestTrie);
+
+//#include "moc_tst_testtrie.cpp"
+
+#endif
diff --git a/tests/auto/qml/persistenttrie/tst_testtrie.h b/tests/auto/qml/persistenttrie/tst_testtrie.h
new file mode 100644
index 0000000000..2559e4a0c0
--- /dev/null
+++ b/tests/auto/qml/persistenttrie/tst_testtrie.h
@@ -0,0 +1,56 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <QtTest>
+#include <QObject>
+
+QT_FORWARD_DECLARE_CLASS(QStringList)
+
+class tst_TestTrie : public QObject
+{
+ Q_OBJECT
+public:
+ tst_TestTrie();
+
+private slots:
+ void initTestCase();
+ //void cleanupTestCase();
+ //void init();
+ //void cleanup();
+
+ void testListAll_data();
+ void testMerge_data();
+ void testIntersect_data();
+ void testCompletion_data();
+
+ void testListAll();
+ void testMerge();
+ void testIntersect();
+ void testCompletion();
+};
diff --git a/tests/auto/qml/qmldesigner/common/statichelpers.cpp b/tests/auto/qml/qmldesigner/common/statichelpers.cpp
index 7b8ae206c7..5970e697db 100644
--- a/tests/auto/qml/qmldesigner/common/statichelpers.cpp
+++ b/tests/auto/qml/qmldesigner/common/statichelpers.cpp
@@ -69,19 +69,6 @@ static QString bareTemplate("import Qt 4.6\n"
"}");
static QString contentsTemplate(bareTemplate.arg("Text { id: textChild; x:10; y: 10; text: \"%1\"; %2 }"));
-
-void printErrors(const QList<QDeclarativeError> &errors, const QString &fileName)
-{
- if (errors.isEmpty())
- return;
-
- qDebug() << "Error loading file \"" << fileName << "\":";
-
- foreach (const QDeclarativeError &error, errors) {
- qDebug() << error.line() << ":" << error.column() << ": " << error.description();
- }
-}
-
// TODO: this need to e updated for states
static bool compareProperty(const AbstractProperty &property1, const AbstractProperty &property2)
{
diff --git a/tests/auto/qml/qmldesigner/coretests/coretests.pro b/tests/auto/qml/qmldesigner/coretests/coretests.pro
index b82c68f5a6..8924538412 100644
--- a/tests/auto/qml/qmldesigner/coretests/coretests.pro
+++ b/tests/auto/qml/qmldesigner/coretests/coretests.pro
@@ -1,33 +1,43 @@
-include(../../../qttest.pri)
-
-QTCREATOR_SOURCE=$$PWD/../../../../..
-QTCREATOR_BUILD=$$OUT_PWD/../../../../..
+IDE_SOURCE_TREE=$$PWD/../../../../..
+IDE_BUILD_TREE=$$OUT_PWD/../../../../..
# can we check that this is a valid build dir?
-
OUT_PWD_SAVE=$$OUT_PWD
-OUT_PWD=QTCREATOR_BUILD
+OUT_PWD=IDE_BUILD_TREE
include($$IDE_SOURCE_TREE/src/plugins/qmldesigner/config.pri)
+include(../../../qttest.pri)
OUT_PWD=$$OUT_PWD_SAVE
-
LIBS += -L$$IDE_PLUGIN_PATH/QtProject
+LIBS += -L$$IDE_LIBRARY_PATH
unix: QMAKE_LFLAGS += \'-Wl,-rpath,$${IDE_LIBRARY_PATH}\' \'-Wl,-rpath,$${IDE_PLUGIN_PATH}/QtProject\'
QT += script \
- network \
- declarative \
- webkit
+ network
+
+greaterThan(QT_MAJOR_VERSION, 4) {
+ QT += printsupport
+ !isEmpty(QT.webkitwidgets.name): QT += webkitwidgets webkit
+ else: DEFINES += QT_NO_WEBKIT
+} else {
+ contains(QT_CONFIG, webkit): QT += webkit
+}
+
# DEFINES+=QTCREATOR_UTILS_STATIC_LIB QML_BUILD_STATIC_LIB
DEFINES+=QTCREATORDIR=\\\"$$IDE_BUILD_TREE\\\"
-DEFINES+=QT_CREATOR QTCREATOR_TEST
+DEFINES+=QT_CREATOR QTCREATOR_TEST QMLDESIGNER_TEST
INCLUDEPATH += $$IDE_SOURCE_TREE/src/plugins/qmldesigner/designercore/include
INCLUDEPATH += $$IDE_SOURCE_TREE/src/plugins/qmldesigner/designercore
+INCLUDEPATH += $$IDE_SOURCE_TREE//share/qtcreator/qml/qmlpuppet
+INCLUDEPATH += $$IDE_SOURCE_TREE/src/plugins/qmldesigner
-include($$IDE_SOURCE_TREE/src/plugins/qmldesigner/designercore/designercore.pri)
-include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+
+include($$IDE_SOURCE_TREE/src/plugins/qmldesigner/designercore/designercore-lib.pri)
include($$IDE_SOURCE_TREE/src/plugins/qmljstools/qmljstools.pri)
+include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+include($$IDE_SOURCE_TREE/src/libs/qmljs/qmljs.pri)
+include($$IDE_SOURCE_TREE/src/libs/cplusplus/cplusplus.pri)
CONFIG += console
CONFIG -= app_bundle
diff --git a/tests/auto/qml/qmldesigner/coretests/setupPath.bat b/tests/auto/qml/qmldesigner/coretests/setupPath.bat
new file mode 100644
index 0000000000..7355f3c099
--- /dev/null
+++ b/tests/auto/qml/qmldesigner/coretests/setupPath.bat
@@ -0,0 +1 @@
+@set path=%PATH%;%CD%\..\..\..\..\..\lib\qtcreator\plugins\QtProject\
diff --git a/tests/auto/qml/qmldesigner/coretests/tst_testcore.cpp b/tests/auto/qml/qmldesigner/coretests/tst_testcore.cpp
index bab2419b12..10f89ace88 100644
--- a/tests/auto/qml/qmldesigner/coretests/tst_testcore.cpp
+++ b/tests/auto/qml/qmldesigner/coretests/tst_testcore.cpp
@@ -32,6 +32,8 @@
#include <QScopedPointer>
#include <QLatin1String>
#include <QGraphicsObject>
+#include <QTest>
+#include <QVariant>
#include <metainfo.h>
#include <model.h>
@@ -55,17 +57,22 @@
#include <nodelistproperty.h>
#include <nodeabstractproperty.h>
#include <componenttextmodifier.h>
-#include <instances/objectnodeinstance.h>
#include <bytearraymodifier.h>
#include "testrewriterview.h"
+#include <utils/fileutils.h>
#include <qmljs/qmljsinterpreter.h>
#include <QPlainTextEdit>
-#include <private/qdeclarativestate_p.h>
-#include <private/qdeclarativemetatype_p.h>
-#include <QDeclarativeItem>
+
+#if QT_VERSION >= 0x050000
+#define MSKIP_SINGLE(x) QSKIP(x)
+#define MSKIP_ALL(x) QSKIP(x);
+#else
+#define MSKIP_SINGLE(x) QSKIP(x, SkipSingle)
+#define MSKIP_ALL(x) QSKIP(x, SkipAll)
+#endif
//TESTED_COMPONENT=src/plugins/qmldesigner/designercore
@@ -74,6 +81,7 @@ using namespace QmlDesigner;
#include "../common/statichelpers.cpp"
#include <qmljstools/qmljsmodelmanager.h>
+#include <qmljs/qmljsinterpreter.h>
#ifdef Q_OS_MAC
# define SHARE_PATH "/Resources"
@@ -93,10 +101,17 @@ public:
{
loadQmlTypeDescriptions(resourcePath());
}
- void loadFile(QString fileName)
+ void updateSourceFiles(const QStringList &files, bool emitDocumentOnDiskChanged)
{
- refreshSourceFiles(QStringList() << fileName, false).waitForFinished();
+ refreshSourceFiles(files, emitDocumentOnDiskChanged).waitForFinished();
}
+
+ QmlJS::LibraryInfo builtins(const QmlJS::Document::Ptr &) const
+ {
+ return QmlJS::LibraryInfo();
+ }
+
+
};
static void initializeMetaTypeSystem(const QString &resourcePath)
@@ -107,9 +122,36 @@ static void initializeMetaTypeSystem(const QString &resourcePath)
QDir::Files,
QDir::Name);
- const QStringList errors = QmlJS::Interpreter::CppQmlTypesLoader::loadQmlTypes(qmlFiles);
- foreach (const QString &error, errors)
- qWarning() << qPrintable(error);
+ QStringList errorsAndWarnings;
+ QmlJS::CppQmlTypesLoader::loadQmlTypes(qmlFiles, &errorsAndWarnings, &errorsAndWarnings);
+ foreach (const QString &errorAndWarning, errorsAndWarnings)
+ qWarning() << qPrintable(errorAndWarning);
+}
+
+static QmlDesigner::Model* createModel(const QString &typeName, int major = 1, int minor = 1, Model *metaInfoPropxyModel = 0)
+{
+ QApplication::processEvents();
+
+ QmlDesigner::Model *model = QmlDesigner::Model::create(typeName, major, minor, metaInfoPropxyModel);
+
+ QPlainTextEdit *textEdit = new QPlainTextEdit;
+ QObject::connect(model, SIGNAL(destroyed()), textEdit, SLOT(deleteLater()));
+ textEdit->setPlainText(QString("import %1 %3.%4; %2{}").arg(typeName.split(".").first())
+ .arg(typeName.split(".").last())
+ .arg(major)
+ .arg(minor));
+
+ NotIndentingTextEditModifier *modifier = new NotIndentingTextEditModifier(textEdit);
+ modifier->setParent(textEdit);
+
+ QmlDesigner::RewriterView *rewriterView = new QmlDesigner::RewriterView(QmlDesigner::RewriterView::Validate, model);
+ rewriterView->setCheckSemanticErrors(false);
+ rewriterView->setTextModifier(modifier);
+
+ model->attachView(rewriterView);
+
+ return model;
+
}
tst_TestCore::tst_TestCore()
@@ -130,9 +172,9 @@ void tst_TestCore::initTestCase()
// Load plugins
#ifdef Q_OS_MAC
- const QString pluginPath = QTCREATORDIR "/bin/Qt Creator.app/Contents/PlugIns/QmlDesigner";
+ const QString pluginPath = QTCREATORDIR "/bin/Qt Creator.app/Contents/PlugIns/QtCreator/QmlDesigner";
#else
- const QString pluginPath = QTCREATORDIR "/lib/qmldesigner";
+ const QString pluginPath = QTCREATORDIR "/lib/qtcreator/qmldesigner";
#endif
qDebug() << pluginPath;
@@ -147,9 +189,18 @@ void tst_TestCore::cleanupTestCase()
MetaInfo::clearGlobal();
}
+void tst_TestCore::init()
+{
+ QApplication::processEvents();
+}
+void tst_TestCore::cleanup()
+{
+ QApplication::processEvents();
+}
+
void tst_TestCore::testModelCreateCoreModel()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> testView(new TestView(model.data()));
@@ -168,17 +219,17 @@ void tst_TestCore::loadEmptyCoreModel()
textEdit1.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
model1->attachView(testRewriterView1.data());
QPlainTextEdit textEdit2;
- textEdit2.setPlainText("import Qt 4.7; Item{}");
+ textEdit2.setPlainText("import QtQuick 1.1; Item{}");
NotIndentingTextEditModifier modifier2(&textEdit2);
- QScopedPointer<Model> model2(Model::create("Qt/item"));
+ QScopedPointer<Model> model2(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView2(new TestRewriterView());
testRewriterView2->setTextModifier(&modifier2);
@@ -191,10 +242,10 @@ void tst_TestCore::testRewriterView()
{
try {
QPlainTextEdit textEdit;
- textEdit.setPlainText("import Qt 4.7;\n\nItem {\n}\n");
+ textEdit.setPlainText("import QtQuick 1.1;\n\nItem {\n}\n");
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -207,15 +258,15 @@ void tst_TestCore::testRewriterView()
testRewriterView->setTextModifier(&textModifier);
model->attachView(testRewriterView.data());
- ModelNode childNode(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode childNode(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
QVERIFY(childNode.isValid());
childNode.setId("childNode");
- ModelNode childNode2(addNodeListChild(childNode, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode childNode2(addNodeListChild(childNode, "QtQuick.Rectangle", 1, 0, "data"));
childNode2.setId("childNode2");
- ModelNode childNode3(addNodeListChild(childNode2, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode childNode3(addNodeListChild(childNode2, "QtQuick.Rectangle", 1, 0, "data"));
childNode3.setId("childNode3");
- ModelNode childNode4(addNodeListChild(childNode3, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode childNode4(addNodeListChild(childNode3, "QtQuick.Rectangle", 1, 0, "data"));
childNode4.setId("childNode4");
QVERIFY(childNode.isValid());
@@ -241,7 +292,7 @@ void tst_TestCore::testRewriterView()
testRewriterView->modelToTextMerger()->applyChanges();
- childNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ childNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(testRewriterView->modelToTextMerger()->isNodeScheduledForAddition(childNode));
testRewriterView->modelToTextMerger()->applyChanges();
@@ -261,10 +312,10 @@ void tst_TestCore::testRewriterView()
void tst_TestCore::testRewriterErrors()
{
QPlainTextEdit textEdit;
- textEdit.setPlainText("import Qt 4.7;\n\nItem {\n}\n");
+ textEdit.setPlainText("import QtQuick 1.1;\n\nItem {\n}\n");
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -278,16 +329,15 @@ void tst_TestCore::testRewriterErrors()
model->attachView(testRewriterView.data());
QVERIFY(testRewriterView->errors().isEmpty());
- textEdit.setPlainText("import Qt 4.7;\n\nError {\n}\n");
+ textEdit.setPlainText("import QtQuick 1.1;\nRectangle {\ntest: blah\n}\n");
QVERIFY(!testRewriterView->errors().isEmpty());
- textEdit.setPlainText("import Qt 4.7;\n\nItem {\n}\n");
+ textEdit.setPlainText("import QtQuick 1.1;\n\nItem {\n}\n");
QVERIFY(testRewriterView->errors().isEmpty());
}
void tst_TestCore::saveEmptyCoreModel()
{
- QList<QDeclarativeError> errors;
QFile file(":/fx/empty.qml");
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
@@ -295,7 +345,7 @@ void tst_TestCore::saveEmptyCoreModel()
textEdit1.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -307,10 +357,10 @@ void tst_TestCore::saveEmptyCoreModel()
modifier1.save(&buffer);
QPlainTextEdit textEdit2;
- textEdit2.setPlainText("import Qt 4.7; Item{}");
+ textEdit2.setPlainText("import QtQuick 1.1; Item{}");
NotIndentingTextEditModifier modifier2(&textEdit2);
- QScopedPointer<Model> model2(Model::create("Qt/item"));
+ QScopedPointer<Model> model2(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView2(new TestRewriterView());
testRewriterView2->setTextModifier(&modifier2);
@@ -322,7 +372,6 @@ void tst_TestCore::saveEmptyCoreModel()
void tst_TestCore::loadAttributesInCoreModel()
{
- QList<QDeclarativeError> errors;
QFile file(":/fx/attributes.qml");
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
@@ -330,17 +379,17 @@ void tst_TestCore::loadAttributesInCoreModel()
textEdit1.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
model1->attachView(testRewriterView1.data());
QPlainTextEdit textEdit2;
- textEdit2.setPlainText("import Qt 4.7; Item{}");
+ textEdit2.setPlainText("import QtQuick 1.1; Item{}");
NotIndentingTextEditModifier modifier2(&textEdit2);
- QScopedPointer<Model> model2(Model::create("Qt/item"));
+ QScopedPointer<Model> model2(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView2(new TestRewriterView());
testRewriterView2->setTextModifier(&modifier2);
@@ -365,7 +414,7 @@ void tst_TestCore::saveAttributesInCoreModel()
textEdit1.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -381,7 +430,7 @@ void tst_TestCore::saveAttributesInCoreModel()
textEdit2.setPlainText(buffer.data());
NotIndentingTextEditModifier modifier2(&textEdit2);
- QScopedPointer<Model> model2(Model::create("Qt/Item"));
+ QScopedPointer<Model> model2(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView2(new TestRewriterView());
testRewriterView2->setTextModifier(&modifier2);
@@ -396,7 +445,7 @@ void tst_TestCore::testModelCreateRect()
{
try {
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -404,7 +453,7 @@ void tst_TestCore::testModelCreateRect()
model->attachView(view.data());
QVERIFY(view->rootModelNode().isValid());
- ModelNode childNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
QVERIFY(view->rootModelNode().allDirectSubModelNodes().contains(childNode));
QVERIFY(childNode.parentProperty().parentModelNode() == view->rootModelNode());
@@ -423,7 +472,7 @@ void tst_TestCore::testModelCreateRect()
QCOMPARE(childNode.propertyNames().count(), 4);
QCOMPARE(childNode.variantProperty("scale").value(), QVariant());
- } catch (Exception &exception) {
+ } catch (Exception &) {
QFAIL("Exception thrown");
}
@@ -432,7 +481,7 @@ void tst_TestCore::testModelCreateRect()
void tst_TestCore::testRewriterDynamicProperties()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" property int i\n"
@@ -459,7 +508,7 @@ void tst_TestCore::testRewriterDynamicProperties()
textEdit1.setPlainText(qmlString);
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -549,10 +598,10 @@ void tst_TestCore::testRewriterDynamicProperties()
// test model2text
// QPlainTextEdit textEdit2;
-// textEdit2.setPlainText("import Qt 4.7; Item{}");
+// textEdit2.setPlainText("import QtQuick 1.1; Item{}");
// NotIndentingTextEditModifier modifier2(&textEdit2);
//
-// QScopedPointer<Model> model2(Model::create("Qt/Item"));
+// QScopedPointer<Model> model2(Model::create("QtQuick.Item"));
//
// QScopedPointer<TestRewriterView> testRewriterView2(new TestRewriterView());
// testRewriterView2->setTextModifier(&modifier2);
@@ -566,7 +615,7 @@ void tst_TestCore::testRewriterDynamicProperties()
void tst_TestCore::testRewriterGroupedProperties()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Text {\n"
" font {\n"
@@ -579,7 +628,7 @@ void tst_TestCore::testRewriterGroupedProperties()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier modifier1(&textEdit);
- QScopedPointer<Model> model1(Model::create("Qt/Text"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Text"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -603,7 +652,7 @@ void tst_TestCore::testRewriterGroupedProperties()
rootModelNode.removeProperty(QLatin1String("font.pointSize"));
const QLatin1String expected("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Text {\n"
"}\n");
@@ -614,7 +663,7 @@ void tst_TestCore::testRewriterGroupedProperties()
void tst_TestCore::testRewriterPreserveOrder()
{
const QLatin1String qmlString1("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"width: 640\n"
@@ -635,7 +684,7 @@ void tst_TestCore::testRewriterPreserveOrder()
"}\n"
"}\n");
const QLatin1String qmlString2("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"width: 640\n"
@@ -661,7 +710,7 @@ void tst_TestCore::testRewriterPreserveOrder()
textEdit.setPlainText(qmlString2);
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Text"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Text"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&modifier);
@@ -674,7 +723,7 @@ void tst_TestCore::testRewriterPreserveOrder()
RewriterTransaction transaction = testRewriterView->beginRewriterTransaction();
- ModelNode newModelNode = testRewriterView->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode newModelNode = testRewriterView->createModelNode("QtQuick.Rectangle", 1, 0);
newModelNode.setParentProperty(rootModelNode.nodeAbstractProperty("data"));
@@ -696,7 +745,7 @@ void tst_TestCore::testRewriterPreserveOrder()
textEdit.setPlainText(qmlString1);
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Text"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Text"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&modifier);
@@ -709,7 +758,7 @@ void tst_TestCore::testRewriterPreserveOrder()
RewriterTransaction transaction = testRewriterView->beginRewriterTransaction();
- ModelNode newModelNode = testRewriterView->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode newModelNode = testRewriterView->createModelNode("QtQuick.Rectangle", 1, 0);
newModelNode.setParentProperty(rootModelNode.nodeAbstractProperty("data"));
@@ -730,7 +779,7 @@ void tst_TestCore::testRewriterPreserveOrder()
void tst_TestCore::testRewriterActionCompression()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: root\n"
@@ -750,7 +799,7 @@ void tst_TestCore::testRewriterActionCompression()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier modifier1(&textEdit);
- QScopedPointer<Model> model1(Model::create("Qt/Rectangle"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Rectangle"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&modifier1);
@@ -776,7 +825,7 @@ void tst_TestCore::testRewriterActionCompression()
transaction.commit();
const QLatin1String expected("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: root\n"
@@ -804,7 +853,7 @@ void tst_TestCore::testRewriterImports()
textEdit.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
model->setFileUrl(QUrl::fromLocalFile(fileName));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -815,12 +864,12 @@ void tst_TestCore::testRewriterImports()
QVERIFY(model->imports().size() == 3);
- // import Qt 4.7
+ // import QtQuick 1.1
Import import = model->imports().at(0);
QVERIFY(import.isLibraryImport());
- QCOMPARE(import.url(), QString("Qt"));
+ QCOMPARE(import.url(), QString("QtQuick"));
QVERIFY(import.hasVersion());
- QCOMPARE(import.version(), QString("4.7"));
+ QCOMPARE(import.version(), QString("1.0"));
QVERIFY(!import.hasAlias());
// import "subitems"
@@ -843,7 +892,7 @@ void tst_TestCore::testRewriterImports()
void tst_TestCore::testRewriterChangeImports()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {}\n");
@@ -851,7 +900,7 @@ void tst_TestCore::testRewriterChangeImports()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Rectangle"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Rectangle"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView(0, RewriterView::Amend));
testRewriterView->setTextModifier(&modifier);
@@ -870,7 +919,7 @@ void tst_TestCore::testRewriterChangeImports()
model->changeImports(importList, QList<Import>());
const QLatin1String qmlWithImport("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"import QtWebKit 1.0\n"
"\n"
"Rectangle {}\n");
@@ -879,7 +928,7 @@ void tst_TestCore::testRewriterChangeImports()
model->changeImports(QList<Import>(), importList);
QCOMPARE(model->imports().size(), 1);
- QCOMPARE(model->imports().first(), Import::createLibraryImport("Qt", "4.7"));
+ QCOMPARE(model->imports().first(), Import::createLibraryImport("QtQuick", "1.1"));
QCOMPARE(textEdit.toPlainText(), qmlString);
@@ -887,45 +936,45 @@ void tst_TestCore::testRewriterChangeImports()
//
// Add / Remove an import in the model (with alias)
//
- model->changeImports(importList, QList<Import>());
+
+ Import webkitImportAlias = Import::createLibraryImport("QtWebKit", "1.0", "Web");
+
+ model->changeImports(QList<Import>() << webkitImportAlias, QList<Import>() << webkitImport);
const QLatin1String qmlWithAliasImport("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"import QtWebKit 1.0 as Web\n"
"\n"
"Rectangle {}\n");
QCOMPARE(textEdit.toPlainText(), qmlWithAliasImport);
- model->changeImports(QList<Import>(), importList);
-
- QCOMPARE(model->imports().size(), 1);
- QCOMPARE(model->imports().first(), Import::createLibraryImport("Qt", "4.7"));
+ model->changeImports(QList<Import>(), QList<Import>() << webkitImportAlias);
+ QCOMPARE(model->imports().first(), Import::createLibraryImport("QtQuick", "1.1"));
QCOMPARE(textEdit.toPlainText(), qmlString);
-
//
// Add / Remove an import in text
//
textEdit.setPlainText(qmlWithImport);
QCOMPARE(model->imports().size(), 2);
- QCOMPARE(model->imports().first(), Import::createLibraryImport("Qt", "4.7"));
+ QCOMPARE(model->imports().first(), Import::createLibraryImport("QtQuick", "1.1"));
QCOMPARE(model->imports().last(), Import::createLibraryImport("QtWebKit", "1.0"));
textEdit.setPlainText(qmlWithAliasImport);
QCOMPARE(model->imports().size(), 2);
- QCOMPARE(model->imports().first(), Import::createLibraryImport("Qt", "4.7"));
+ QCOMPARE(model->imports().first(), Import::createLibraryImport("QtQuick", "1.1"));
QCOMPARE(model->imports().last(), Import::createLibraryImport("QtWebKit", "1.0", "Web"));
textEdit.setPlainText(qmlString);
QCOMPARE(model->imports().size(), 1);
- QCOMPARE(model->imports().first(), Import::createLibraryImport("Qt", "4.7"));
+ QCOMPARE(model->imports().first(), Import::createLibraryImport("QtQuick", "1.1"));
}
void tst_TestCore::testRewriterForGradientMagic()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: root\n"
@@ -963,7 +1012,7 @@ void tst_TestCore::testRewriterForGradientMagic()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Text"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Text"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&modifier);
@@ -979,7 +1028,7 @@ void tst_TestCore::testRewriterForGradientMagic()
myRect.variantProperty("rotation") = QVariant(45);
QVERIFY(myRect.isValid());
- QScopedPointer<Model> model1(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model1.data());
QScopedPointer<TestView> view1(new TestView(model1.data()));
@@ -987,7 +1036,7 @@ void tst_TestCore::testRewriterForGradientMagic()
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item {}");
+ textEdit1.setPlainText("import QtQuick 1.1; Item {}");
NotIndentingTextEditModifier modifier1(&textEdit1);
testRewriterView1->setTextModifier(&modifier1);
@@ -1013,7 +1062,7 @@ void tst_TestCore::loadSubItems()
textEdit1.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -1022,16 +1071,16 @@ void tst_TestCore::loadSubItems()
void tst_TestCore::createInvalidCoreModel()
{
- QScopedPointer<Model> invalidModel(Model::create("ItemSUX"));
+ QScopedPointer<Model> invalidModel(createModel("ItemSUX"));
//QVERIFY(!invalidModel.data()); //#no direct ype checking in model atm
- QScopedPointer<Model> invalidModel2(Model::create("InvalidNode"));
+ QScopedPointer<Model> invalidModel2(createModel("InvalidNode"));
//QVERIFY(!invalidModel2.data());
}
void tst_TestCore::testModelCreateSubNode()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1043,7 +1092,7 @@ void tst_TestCore::testModelCreateSubNode()
QCOMPARE(view->methodCalls(), expectedCalls);
QVERIFY(view->rootModelNode().isValid());
- ModelNode childNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
QVERIFY(view->rootModelNode().allDirectSubModelNodes().contains(childNode));
QVERIFY(childNode.parentProperty().parentModelNode() == view->rootModelNode());
@@ -1077,7 +1126,7 @@ void tst_TestCore::testModelCreateSubNode()
void tst_TestCore::testTypicalRewriterOperations()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1087,46 +1136,46 @@ void tst_TestCore::testTypicalRewriterOperations()
ModelNode rootModelNode = view->rootModelNode();
QCOMPARE(rootModelNode.allDirectSubModelNodes().count(), 0);
- QVERIFY(rootModelNode.property("test").isValid());
- QVERIFY(!rootModelNode.property("test").isVariantProperty());
- QVERIFY(!rootModelNode.property("test").isBindingProperty());
+ QVERIFY(rootModelNode.property("x").isValid());
+ QVERIFY(!rootModelNode.property("x").isVariantProperty());
+ QVERIFY(!rootModelNode.property("x").isBindingProperty());
- QVERIFY(rootModelNode.variantProperty("test").isValid());
- QVERIFY(!rootModelNode.hasProperty("test"));
+ QVERIFY(rootModelNode.variantProperty("x").isValid());
+ QVERIFY(!rootModelNode.hasProperty("x"));
- rootModelNode.variantProperty("test") = 70;
+ rootModelNode.variantProperty("x") = 70;
- QVERIFY(rootModelNode.hasProperty("test"));
- QVERIFY(rootModelNode.property("test").isVariantProperty());
- QCOMPARE(rootModelNode.variantProperty("test").value(), QVariant(70));
+ QVERIFY(rootModelNode.hasProperty("x"));
+ QVERIFY(rootModelNode.property("x").isVariantProperty());
+ QCOMPARE(rootModelNode.variantProperty("x").value(), QVariant(70));
- rootModelNode.bindingProperty("test") = "parent.x";
- QVERIFY(!rootModelNode.property("test").isVariantProperty());
- QVERIFY(rootModelNode.property("test").isBindingProperty());
+ rootModelNode.bindingProperty("x") = "parent.x";
+ QVERIFY(!rootModelNode.property("x").isVariantProperty());
+ QVERIFY(rootModelNode.property("x").isBindingProperty());
- QCOMPARE(rootModelNode.bindingProperty("test").expression(), QString("parent.x"));
+ QCOMPARE(rootModelNode.bindingProperty("x").expression(), QString("parent.x"));
- ModelNode childNode(addNodeListChild(rootModelNode, "Qt/Rectangle", 4 ,6, "data"));
- rootModelNode.nodeListProperty("test").reparentHere(childNode);
- QCOMPARE(childNode.parentProperty(), rootModelNode.nodeAbstractProperty("test"));
- QVERIFY(rootModelNode.property("test").isNodeAbstractProperty());
- QVERIFY(rootModelNode.property("test").isNodeListProperty());
- QVERIFY(!rootModelNode.property("test").isBindingProperty());
+ ModelNode childNode(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1 ,0, "data"));
+ rootModelNode.nodeListProperty("data").reparentHere(childNode);
+ QCOMPARE(childNode.parentProperty(), rootModelNode.nodeAbstractProperty("data"));
+ QVERIFY(rootModelNode.property("data").isNodeAbstractProperty());
+ QVERIFY(rootModelNode.property("data").isNodeListProperty());
+ QVERIFY(!rootModelNode.property("data").isBindingProperty());
QVERIFY(childNode.parentProperty().isNodeListProperty());
QCOMPARE(childNode, childNode.parentProperty().toNodeListProperty().toModelNodeList().first());
QCOMPARE(rootModelNode, childNode.parentProperty().parentModelNode());
- QCOMPARE(childNode.parentProperty().name(), QString("test"));
+ QCOMPARE(childNode.parentProperty().name(), QString("data"));
- QVERIFY(!rootModelNode.property("test").isVariantProperty());
- rootModelNode.variantProperty("test") = 90;
- QVERIFY(rootModelNode.property("test").isVariantProperty());
- QCOMPARE(rootModelNode.variantProperty("test").value(), QVariant(90));
+ QVERIFY(!rootModelNode.property("x").isVariantProperty());
+ rootModelNode.variantProperty("x") = 90;
+ QVERIFY(rootModelNode.property("x").isVariantProperty());
+ QCOMPARE(rootModelNode.variantProperty("x").value(), QVariant(90));
}
void tst_TestCore::testBasicStates()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"id: root;\n"
"Rectangle {\n"
@@ -1165,7 +1214,7 @@ void tst_TestCore::testBasicStates()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1174,13 +1223,13 @@ void tst_TestCore::testBasicStates()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
model->attachView(testRewriterView.data());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
QVERIFY(rootModelNode.hasProperty("data"));
@@ -1213,6 +1262,7 @@ void tst_TestCore::testBasicStates()
QCOMPARE(state1.propertyChanges().count(), 2);
QCOMPARE(state2.propertyChanges().count(), 2);
+ QVERIFY(state1.propertyChanges().first().modelNode().metaInfo().isSubclassOf("<cpp>.QDeclarative1StateOperation", -1, -1));
QVERIFY(!state1.hasPropertyChanges(rootModelNode));
QVERIFY(state1.propertyChanges(rect1).isValid());
@@ -1275,10 +1325,117 @@ void tst_TestCore::testBasicStates()
// QCOMPARE(rect2Instance.property("x").toInt(), 0);
}
+void tst_TestCore::testBasicStatesQtQuick20()
+{
+ char qmlString[] = "import QtQuick 2.0\n"
+ "Rectangle {\n"
+ "id: root;\n"
+ "Rectangle {\n"
+ "id: rect1;\n"
+ "}\n"
+ "Rectangle {\n"
+ "id: rect2;\n"
+ "}\n"
+ "states: [\n"
+ "State {\n"
+ "name: \"state1\"\n"
+ "PropertyChanges {\n"
+ "target: rect1\n"
+ "}\n"
+ "PropertyChanges {\n"
+ "target: rect2\n"
+ "}\n"
+ "}\n"
+ ","
+ "State {\n"
+ "name: \"state2\"\n"
+ "PropertyChanges {\n"
+ "target: rect1\n"
+ "}\n"
+ "PropertyChanges {\n"
+ "target: rect2;\n"
+ "x: 10;\n"
+ "}\n"
+ "}\n"
+ "]\n"
+ "}\n";
+
+ Exception::setShouldAssert(true);
+
+ QPlainTextEdit textEdit;
+ textEdit.setPlainText(qmlString);
+ NotIndentingTextEditModifier textModifier(&textEdit);
+
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
+ QVERIFY(model.data());
+
+ QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
+ testRewriterView->setTextModifier(&textModifier);
+ model->attachView(testRewriterView.data());
+
+ ModelNode rootModelNode(testRewriterView->rootModelNode());
+ QVERIFY(rootModelNode.isValid());
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
+ QCOMPARE(rootModelNode.majorVersion(), 2);
+ QCOMPARE(rootModelNode.majorQtQuickVersion(), 2);
+
+ qDebug() << rootModelNode.nodeListProperty("states").toModelNodeList().first().metaInfo().majorVersion();
+ qDebug() << rootModelNode.nodeListProperty("states").toModelNodeList().first().metaInfo().typeName();
+
+ MSKIP_ALL("No qml2puppet");
+
+ QScopedPointer<TestView> view(new TestView(model.data()));
+ QVERIFY(view.data());
+ model->attachView(view.data());
+
+ QVERIFY(rootModelNode.hasProperty("data"));
+
+ QVERIFY(rootModelNode.property("data").isNodeListProperty());
+
+ QCOMPARE(rootModelNode.nodeListProperty("data").toModelNodeList().count(), 2);
+
+ ModelNode rect1 = rootModelNode.nodeListProperty("data").toModelNodeList().first();
+ ModelNode rect2 = rootModelNode.nodeListProperty("data").toModelNodeList().last();
+
+ QVERIFY(QmlItemNode(rect1).isValid());
+ QVERIFY(QmlItemNode(rect2).isValid());
+
+ QVERIFY(QmlItemNode(rootModelNode).isValid());
+
+ QCOMPARE(QmlItemNode(rootModelNode).states().allStates().count(), 2);
+ QCOMPARE(QmlItemNode(rootModelNode).states().names().count(), 2);
+ QCOMPARE(QmlItemNode(rootModelNode).states().names().first(), QString("state1"));
+ QCOMPARE(QmlItemNode(rootModelNode).states().names().last(), QString("state2"));
+
+ //
+ // QmlModelState API tests
+ //
+ QmlModelState state1 = QmlItemNode(rootModelNode).states().state("state1");
+ QmlModelState state2 = QmlItemNode(rootModelNode).states().state("state2");
+
+ QVERIFY(state1.isValid());
+ QVERIFY(state2.isValid());
+
+ QCOMPARE(state1.propertyChanges().count(), 2);
+ QCOMPARE(state2.propertyChanges().count(), 2);
+
+ QVERIFY(!state1.hasPropertyChanges(rootModelNode));
+
+ QVERIFY(state1.propertyChanges(rect1).isValid());
+ QVERIFY(state1.propertyChanges(rect2).isValid());
+
+ state1.propertyChanges(rect2).modelNode().hasProperty("x");
+
+ QCOMPARE(QmlItemNode(rect1).allAffectingStates().count(), 2);
+ QCOMPARE(QmlItemNode(rect2).allAffectingStates().count(), 2);
+ QCOMPARE(QmlItemNode(rootModelNode).allAffectingStates().count(), 0);
+ QCOMPARE(QmlItemNode(rect1).allAffectingStatesOperations().count(), 2);
+ QCOMPARE(QmlItemNode(rect2).allAffectingStatesOperations().count(), 2);
+}
+
void tst_TestCore::testModelBasicOperations()
{
- QSKIP("Fix MetaInfo", SkipAll);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Flipable"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1299,8 +1456,8 @@ void tst_TestCore::testModelBasicOperations()
QVERIFY(!rootModelNode.hasProperty("width"));
QVERIFY(!rootModelNode.hasProperty("children"));
- ModelNode childNode1(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "children"));
- ModelNode childNode2(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode childNode1(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "children"));
+ ModelNode childNode2(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
QVERIFY(childNode1.isValid());
QVERIFY(childNode2.isValid());
@@ -1338,7 +1495,7 @@ void tst_TestCore::testModelBasicOperations()
void tst_TestCore::testModelResolveIds()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1348,47 +1505,47 @@ void tst_TestCore::testModelResolveIds()
ModelNode rootNode = view->rootModelNode();
rootNode.setId("rootNode");
- ModelNode childNode1(addNodeListChild(rootNode, "Qt/Rectangle", 4, 7, "children"));
+ ModelNode childNode1(addNodeListChild(rootNode, "QtQuick.Rectangle", 1, 0, "children"));
- ModelNode childNode2(addNodeListChild(childNode1, "Qt/Rectangle", 4, 7, "children"));
+ ModelNode childNode2(addNodeListChild(childNode1, "QtQuick.Flipable", 1, 0, "children"));
childNode2.setId("childNode2");
- childNode2.bindingProperty("test").setExpression("parent.parent");
+ childNode2.bindingProperty("anchors.fill").setExpression("parent.parent");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), rootNode);
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), rootNode);
childNode1.setId("childNode1");
- childNode2.bindingProperty("test").setExpression("childNode1.parent");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), rootNode);
- childNode2.bindingProperty("test").setExpression("rootNode");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), rootNode);
+ childNode2.bindingProperty("anchors.fill").setExpression("childNode1.parent");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), rootNode);
+ childNode2.bindingProperty("anchors.fill").setExpression("rootNode");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), rootNode);
- ModelNode childNode3(addNodeListChild(childNode2, "Qt/Rectangle", 4, 7, "children"));
+ ModelNode childNode3(addNodeListChild(childNode2, "QtQuick.Rectangle", 1, 0, "children"));
childNode3.setId("childNode3");
childNode2.nodeProperty("front").setModelNode(childNode3);
- childNode2.bindingProperty("test").setExpression("childNode3.parent");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), childNode2);
- childNode2.bindingProperty("test").setExpression("childNode3.parent.parent");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), childNode1);
- childNode2.bindingProperty("test").setExpression("childNode3.parent.parent.parent");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), rootNode);
- childNode2.bindingProperty("test").setExpression("childNode3");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), childNode3);
- childNode2.bindingProperty("test").setExpression("front");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), childNode3);
- childNode2.bindingProperty("test").setExpression("back");
- QVERIFY(!childNode2.bindingProperty("test").resolveToModelNode().isValid());
- childNode2.bindingProperty("test").setExpression("childNode3.parent.front");
- QCOMPARE(childNode2.bindingProperty("test").resolveToModelNode(), childNode3);
+ childNode2.bindingProperty("anchors.fill").setExpression("childNode3.parent");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), childNode2);
+ childNode2.bindingProperty("anchors.fill").setExpression("childNode3.parent.parent");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), childNode1);
+ childNode2.bindingProperty("anchors.fill").setExpression("childNode3.parent.parent.parent");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), rootNode);
+ childNode2.bindingProperty("anchors.fill").setExpression("childNode3");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), childNode3);
+ childNode2.bindingProperty("anchors.fill").setExpression("front");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), childNode3);
+ childNode2.bindingProperty("anchors.fill").setExpression("back");
+ QVERIFY(!childNode2.bindingProperty("anchors.fill").resolveToModelNode().isValid());
+ childNode2.bindingProperty("anchors.fill").setExpression("childNode3.parent.front");
+ QCOMPARE(childNode2.bindingProperty("anchors.fill").resolveToModelNode(), childNode3);
childNode2.variantProperty("x") = 10;
QCOMPARE(childNode2.variantProperty("x").value().toInt(), 10);
- childNode2.bindingProperty("test").setExpression("childNode3.parent.x");
- QVERIFY(childNode2.bindingProperty("test").resolveToProperty().isVariantProperty());
- QCOMPARE(childNode2.bindingProperty("test").resolveToProperty().toVariantProperty().value().toInt(), 10);
+ childNode2.bindingProperty("width").setExpression("childNode3.parent.x");
+ QVERIFY(childNode2.bindingProperty("width").resolveToProperty().isVariantProperty());
+ QCOMPARE(childNode2.bindingProperty("width").resolveToProperty().toVariantProperty().value().toInt(), 10);
- childNode2.bindingProperty("test").setExpression("childNode3.parent.test");
- QVERIFY(childNode2.bindingProperty("test").resolveToProperty().isBindingProperty());
- QCOMPARE(childNode2.bindingProperty("test").resolveToProperty().toBindingProperty().expression(), QString("childNode3.parent.test"));
+ childNode2.bindingProperty("width").setExpression("childNode3.parent.width");
+ QVERIFY(childNode2.bindingProperty("width").resolveToProperty().isBindingProperty());
+ QCOMPARE(childNode2.bindingProperty("width").resolveToProperty().toBindingProperty().expression(), QString("childNode3.parent.width"));
}
void tst_TestCore::testModelNodeListProperty()
@@ -1396,7 +1553,7 @@ void tst_TestCore::testModelNodeListProperty()
//
// Test NodeListProperty API
//
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1414,7 +1571,7 @@ void tst_TestCore::testModelNodeListProperty()
QVERIFY(!rootChildren.isNodeListProperty());
QVERIFY(rootChildren.isEmpty());
- ModelNode rectNode = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode rectNode = view->createModelNode("QtQuick.Rectangle", 1, 0);
rootChildren.reparentHere(rectNode);
//
@@ -1425,7 +1582,7 @@ void tst_TestCore::testModelNodeListProperty()
QVERIFY(rootChildren.isNodeListProperty());
QVERIFY(!rootChildren.isEmpty());
- ModelNode mouseAreaNode = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode mouseAreaNode = view->createModelNode("QtQuick.Item", 1, 1);
NodeListProperty rectChildren = rectNode.nodeListProperty("children");
rectChildren.reparentHere(mouseAreaNode);
@@ -1453,7 +1610,7 @@ void tst_TestCore::testModelNodeListProperty()
void tst_TestCore::testBasicOperationsWithView()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1467,10 +1624,6 @@ void tst_TestCore::testBasicOperationsWithView()
QCOMPARE(rootModelNode.allDirectSubModelNodes().count(), 0);
NodeInstance rootInstance = nodeInstanceView->instanceForNode(rootModelNode);
- // no width, height specified implicitly is set to 100x100
- QCOMPARE(rootInstance.size().width(), 100.0);
- QCOMPARE(rootInstance.size().height(), 100.0);
-
QVERIFY(rootInstance.isValid());
QVERIFY(rootModelNode.isValid());
@@ -1484,8 +1637,8 @@ void tst_TestCore::testBasicOperationsWithView()
QCOMPARE(rootInstance.size().width(), 10.0);
QCOMPARE(rootInstance.size().height(), 10.0);
- ModelNode childNode(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
- ModelNode childNode2(addNodeListChild(childNode, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode childNode(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
+ ModelNode childNode2(addNodeListChild(childNode, "QtQuick.Rectangle", 1, 0, "data"));
QVERIFY(childNode2.parentProperty().parentModelNode() == childNode);
QVERIFY(childNode.isValid());
@@ -1519,10 +1672,10 @@ void tst_TestCore::testBasicOperationsWithView()
QVERIFY(!childInstance2.isValid());
}
- childNode = addNodeListChild(rootModelNode, "Qt/Image", 4, 7, "data");
+ childNode = addNodeListChild(rootModelNode, "QtQuick.Image", 1, 0, "data");
QVERIFY(childNode.isValid());
- QCOMPARE(childNode.type(), QString("Qt/Image"));
- childNode2 = addNodeListChild(childNode, "Qt/Rectangle", 4, 7, "data");
+ QCOMPARE(childNode.type(), QString("QtQuick.Image"));
+ childNode2 = addNodeListChild(childNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode2.isValid());
childNode2.setParentProperty(rootModelNode, "data");
QVERIFY(childNode2.isValid());
@@ -1560,7 +1713,7 @@ void tst_TestCore::testBasicOperationsWithView()
void tst_TestCore::testQmlModelView()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QmlModelView *view = new TestView(model.data());
@@ -1578,7 +1731,7 @@ void tst_TestCore::testQmlModelView()
propertyList.append(qMakePair(QString("width"), QVariant(20)));
propertyList.append(qMakePair(QString("height"), QVariant(20)));
- QmlObjectNode node1 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
+ QmlObjectNode node1 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
QVERIFY(node1.isValid());
QVERIFY(!node1.hasNodeParent());
@@ -1594,7 +1747,7 @@ void tst_TestCore::testQmlModelView()
QVERIFY(node1.instanceParent() == view->rootQmlObjectNode());
- QmlObjectNode node2 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
+ QmlObjectNode node2 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
QVERIFY(node2.isValid());
QVERIFY(!node2.hasNodeParent());
@@ -1622,12 +1775,12 @@ void tst_TestCore::testQmlModelView()
QCOMPARE(node1.instanceValue("x").toInt(), 2);
- QmlObjectNode node3 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
- QmlObjectNode node4 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
- QmlObjectNode node5 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
- QmlObjectNode node6 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
- QmlObjectNode node7 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
- QmlObjectNode node8 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
+ QmlObjectNode node3 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
+ QmlObjectNode node4 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
+ QmlObjectNode node5 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
+ QmlObjectNode node6 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
+ QmlObjectNode node7 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
+ QmlObjectNode node8 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
node3.setParentProperty(node2.nodeAbstractProperty("children"));
node4.setParentProperty(node3.nodeAbstractProperty("children"));
@@ -1655,21 +1808,20 @@ void tst_TestCore::testQmlModelView()
QCOMPARE(node2.instanceValue("x").toInt(), 10); // is this right? or should it be a invalid qvariant?
- node1 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
+ node1 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
node1.setId("node1");
QCOMPARE(node2.instanceValue("x").toInt(), 20);
- node3 = view->createQmlObjectNode("Qt/Rectangle", 4, 7, propertyList);
+ node3 = view->createQmlObjectNode("QtQuick.Rectangle", 1, 0, propertyList);
node3.setParentProperty(node2.nodeAbstractProperty("children"));
QCOMPARE(node3.instanceValue("width").toInt(), 20);
node3.setVariantProperty("width", 0);
QCOMPARE(node3.instanceValue("width").toInt(), 0);
QCOMPARE(node3.instanceValue("x").toInt(), 20);
- QVERIFY(!QDeclarativeMetaType::toQObject(node3.instanceValue("anchors.fill")));
+ //QVERIFY(!QDeclarativeMetaType::toQObject(node3.instanceValue("anchors.fill")));
node3.setBindingProperty("anchors.fill", "parent");
- QVERIFY(QDeclarativeMetaType::toQObject(node3.instanceValue("anchors.fill")));
QCOMPARE(node3.instanceValue("x").toInt(), 0);
QCOMPARE(node3.instanceValue("width").toInt(), 20);
@@ -1682,7 +1834,7 @@ void tst_TestCore::testQmlModelView()
void tst_TestCore::testModelRemoveNode()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1695,7 +1847,7 @@ void tst_TestCore::testModelRemoveNode()
QCOMPARE(view->rootModelNode().allDirectSubModelNodes().count(), 0);
- ModelNode childNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
QCOMPARE(view->rootModelNode().allDirectSubModelNodes().count(), 1);
QVERIFY(view->rootModelNode().allDirectSubModelNodes().contains(childNode));
@@ -1707,7 +1859,7 @@ void tst_TestCore::testModelRemoveNode()
QVERIFY(childInstance.parentId() == view->rootModelNode().internalId());
}
- ModelNode subChildNode = addNodeListChild(childNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode subChildNode = addNodeListChild(childNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(subChildNode.isValid());
QCOMPARE(childNode.allDirectSubModelNodes().count(), 1);
QVERIFY(childNode.allDirectSubModelNodes().contains(subChildNode));
@@ -1738,7 +1890,7 @@ void tst_TestCore::testModelRemoveNode()
QVERIFY(view->rootModelNode().isValid());
// delete node not in hierarchy
- childNode = view->createModelNode("Qt/Item", 4, 7);
+ childNode = view->createModelNode("QtQuick.Item", 1, 1);
childNode.destroy();
model->detachView(nodeInstanceView);
@@ -1746,7 +1898,7 @@ void tst_TestCore::testModelRemoveNode()
void tst_TestCore::reparentingNode()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
@@ -1763,7 +1915,7 @@ void tst_TestCore::reparentingNode()
NodeInstanceView *nodeInstanceView = new NodeInstanceView(model.data(), NodeInstanceServerInterface::TestModus);
model->attachView(nodeInstanceView);
- ModelNode childNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QCOMPARE(childNode.parentProperty().parentModelNode(), rootModelNode);
QVERIFY(rootModelNode.allDirectSubModelNodes().contains(childNode));
@@ -1773,7 +1925,7 @@ void tst_TestCore::reparentingNode()
QVERIFY(childInstance.parentId() == view->rootModelNode().internalId());
}
- ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/Item", 4, 7, "data");
+ ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.Item", 1, 1, "data");
QCOMPARE(childNode2.parentProperty().parentModelNode(), rootModelNode);
QVERIFY(rootModelNode.allDirectSubModelNodes().contains(childNode2));
@@ -1808,16 +1960,17 @@ void tst_TestCore::reparentingNode()
QCOMPARE(childNode.parentProperty().parentModelNode(), childNode2);
+ QApplication::processEvents();
model->detachView(nodeInstanceView);
}
void tst_TestCore::reparentingNodeLikeDragAndDrop()
{
QPlainTextEdit textEdit;
- textEdit.setPlainText("import Qt 4.7;\n\nItem {\n}\n");
+ textEdit.setPlainText("import QtQuick 1.1;\n\nItem {\n}\n");
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -1833,7 +1986,7 @@ void tst_TestCore::reparentingNodeLikeDragAndDrop()
view->rootModelNode().setId("rootModelNode");
QCOMPARE(view->rootModelNode().id(), QString("rootModelNode"));
- ModelNode rectNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode rectNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
rectNode.setId("rect_1");
rectNode.variantProperty("x").setValue(20);
rectNode.variantProperty("y").setValue(30);
@@ -1842,7 +1995,7 @@ void tst_TestCore::reparentingNodeLikeDragAndDrop()
RewriterTransaction transaction(view->beginRewriterTransaction());
- ModelNode textNode = addNodeListChild(view->rootModelNode(), "Qt/Text", 4, 7, "data");
+ ModelNode textNode = addNodeListChild(view->rootModelNode(), "QtQuick.Text", 1, 1, "data");
QCOMPARE(textNode.parentProperty().parentModelNode(), view->rootModelNode());
QVERIFY(view->rootModelNode().allDirectSubModelNodes().contains(textNode));
@@ -1925,12 +2078,14 @@ void tst_TestCore::reparentingNodeLikeDragAndDrop()
QCOMPARE(textNode.parentProperty().parentModelNode(), rectNode);
QVERIFY(rectNode.allDirectSubModelNodes().contains(textNode));
+ QApplication::processEvents();
+
model->detachView(nodeInstanceView);
}
void tst_TestCore::testModelReorderSiblings()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1943,11 +2098,11 @@ void tst_TestCore::testModelReorderSiblings()
ModelNode rootModelNode = view->rootModelNode();
QVERIFY(rootModelNode.isValid());
- ModelNode a = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode a = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(a.isValid());
- ModelNode b = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode b = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(b.isValid());
- ModelNode c = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode c = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(c.isValid());
{
@@ -1976,12 +2131,14 @@ void tst_TestCore::testModelReorderSiblings()
QVERIFY(nodeInstanceView->instanceForNode(c).parentId() == rootModelNode.internalId());
}
+ QApplication::processEvents();
+
model->detachView(nodeInstanceView);
}
void tst_TestCore::testModelRootNode()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -1992,10 +2149,10 @@ void tst_TestCore::testModelRootNode()
ModelNode rootModelNode = view->rootModelNode();
QVERIFY(rootModelNode.isValid());
QVERIFY(rootModelNode.isRootNode());
- ModelNode topChildNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode topChildNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(topChildNode.isValid());
QVERIFY(rootModelNode.isRootNode());
- ModelNode childNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
QVERIFY(rootModelNode.isValid());
QVERIFY(rootModelNode.isRootNode());
@@ -2008,19 +2165,20 @@ void tst_TestCore::testModelRootNode()
QString errorMsg = tr("Exception: %1 %2 %3:%4").arg(exception.type(), exception.function(), exception.file()).arg(exception.line());
QFAIL(errorMsg.toLatin1().constData());
}
+ QApplication::processEvents();
}
void tst_TestCore::reparentingNodeInModificationGroup()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- ModelNode childNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode2 = addNodeListChild(view->rootModelNode(), "Qt/Item", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode2 = addNodeListChild(view->rootModelNode(), "QtQuick.Item", 1, 1, "data");
childNode.variantProperty("x").setValue(10);
childNode.variantProperty("y").setValue(10);
@@ -2058,11 +2216,13 @@ void tst_TestCore::reparentingNodeInModificationGroup()
QCOMPARE(childNode2.parentProperty().parentModelNode(), view->rootModelNode());
QVERIFY(childNode2.isValid());
QVERIFY(view->rootModelNode().allDirectSubModelNodes().contains(childNode2));
+
+ QApplication::processEvents();
}
void tst_TestCore::testModelAddAndRemoveProperty()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2098,12 +2258,14 @@ void tst_TestCore::testModelAddAndRemoveProperty()
QVERIFY(node.hasProperty("foo"));
QCOMPARE(node.variantProperty("foo").value().toString(), QString("bar"));
+ QApplication::processEvents();
+
model->detachView(nodeInstanceView);
}
void tst_TestCore::testModelViewNotification()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view1(new TestView(model.data()));
@@ -2125,7 +2287,7 @@ void tst_TestCore::testModelViewNotification()
QCOMPARE(view1->methodCalls(), expectedCalls);
QCOMPARE(view2->methodCalls(), expectedCalls);
- ModelNode childNode = addNodeListChild(view2->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view2->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
expectedCalls << TestView::MethodCall("nodeCreated", QStringList() << "");
expectedCalls << TestView::MethodCall("nodeReparented", QStringList() << "" << "data" << "" << "PropertiesAdded");
QCOMPARE(view1->methodCalls(), expectedCalls);
@@ -2155,7 +2317,7 @@ void tst_TestCore::testModelViewNotification()
QCOMPARE(view1->methodCalls(), expectedCalls);
QCOMPARE(view2->methodCalls(), expectedCalls);
- childNode.bindingProperty("visible").setExpression("false");
+ childNode.bindingProperty("visible").setExpression("false && true");
expectedCalls << TestView::MethodCall("propertiesAboutToBeRemoved", QStringList() << "visible");
expectedCalls << TestView::MethodCall("bindingPropertiesChanged", QStringList() << "visible" << "PropertiesAdded");
QCOMPARE(view1->methodCalls(), expectedCalls);
@@ -2170,12 +2332,14 @@ void tst_TestCore::testModelViewNotification()
model->detachView(view1.data());
expectedCalls << TestView::MethodCall("modelAboutToBeDetached", QStringList() << QString::number(reinterpret_cast<long>(model.data())));
QCOMPARE(view1->methodCalls(), expectedCalls);
+
+ QApplication::processEvents();
}
void tst_TestCore::testRewriterTransaction()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2185,7 +2349,7 @@ void tst_TestCore::testRewriterTransaction()
RewriterTransaction transaction = view->beginRewriterTransaction();
QVERIFY(transaction.isValid());
- ModelNode childNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
childNode.destroy();
@@ -2195,7 +2359,7 @@ void tst_TestCore::testRewriterTransaction()
RewriterTransaction transaction2 = view->beginRewriterTransaction();
QVERIFY(transaction2.isValid());
- ModelNode childNode = addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
childNode.destroy();
@@ -2222,7 +2386,7 @@ void tst_TestCore::testRewriterTransaction()
void tst_TestCore::testRewriterId()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2230,7 +2394,7 @@ void tst_TestCore::testRewriterId()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2245,16 +2409,16 @@ void tst_TestCore::testRewriterId()
model->attachView(testRewriterView.data());
- QCOMPARE(rootModelNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
QVERIFY(rootModelNode.isValid());
- ModelNode newNode(view->createModelNode("Qt/Rectangle", 4, 7));
+ ModelNode newNode(view->createModelNode("QtQuick.Rectangle", 1, 0));
newNode.setId("testId");
rootModelNode.nodeListProperty("data").reparentHere(newNode);
- const QLatin1String expected("import Qt 4.7\n"
+ const QLatin1String expected("import QtQuick 1.1\n"
"Rectangle {\n"
"Rectangle {\n"
" id: testId\n"
@@ -2266,7 +2430,7 @@ void tst_TestCore::testRewriterId()
void tst_TestCore::testRewriterNodeReparentingTransaction1()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2274,7 +2438,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction1()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2283,7 +2447,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction1()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
@@ -2291,12 +2455,12 @@ void tst_TestCore::testRewriterNodeReparentingTransaction1()
QVERIFY(rootModelNode.isValid());
- ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode3 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode4 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode3 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode4 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
- ModelNode reparentNode = addNodeListChild(childNode1, "Qt/Rectangle", 4, 7, "data");
+ ModelNode reparentNode = addNodeListChild(childNode1, "QtQuick.Rectangle", 1, 0, "data");
RewriterTransaction rewriterTransaction = view->beginRewriterTransaction();
@@ -2311,7 +2475,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction1()
void tst_TestCore::testRewriterNodeReparentingTransaction2()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2319,7 +2483,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction2()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2328,7 +2492,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction2()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
@@ -2336,8 +2500,8 @@ void tst_TestCore::testRewriterNodeReparentingTransaction2()
QVERIFY(rootModelNode.isValid());
- ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
childNode2.variantProperty("x") = 200;
childNode2.variantProperty("y") = 50;
@@ -2377,7 +2541,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction2()
void tst_TestCore::testRewriterNodeReparentingTransaction3()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2385,7 +2549,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction3()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2394,7 +2558,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction3()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
@@ -2402,10 +2566,10 @@ void tst_TestCore::testRewriterNodeReparentingTransaction3()
QVERIFY(rootModelNode.isValid());
- ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode3 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode4 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode3 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode4 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
RewriterTransaction rewriterTransaction = view->beginRewriterTransaction();
@@ -2427,7 +2591,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction3()
void tst_TestCore::testRewriterNodeReparentingTransaction4()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2435,7 +2599,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction4()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2444,7 +2608,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction4()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
@@ -2452,11 +2616,11 @@ void tst_TestCore::testRewriterNodeReparentingTransaction4()
QVERIFY(rootModelNode.isValid());
- ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode3 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode4 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
- ModelNode childNode5 = addNodeListChild(childNode2, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode3 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode4 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
+ ModelNode childNode5 = addNodeListChild(childNode2, "QtQuick.Rectangle", 1, 0, "data");
RewriterTransaction rewriterTransaction = view->beginRewriterTransaction();
@@ -2478,7 +2642,7 @@ void tst_TestCore::testRewriterNodeReparentingTransaction4()
void tst_TestCore::testRewriterAddNodeTransaction()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2486,7 +2650,7 @@ void tst_TestCore::testRewriterAddNodeTransaction()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2495,7 +2659,7 @@ void tst_TestCore::testRewriterAddNodeTransaction()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
@@ -2504,11 +2668,11 @@ void tst_TestCore::testRewriterAddNodeTransaction()
QVERIFY(rootModelNode.isValid());
- ModelNode childNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
RewriterTransaction rewriterTransaction = view->beginRewriterTransaction();
- ModelNode newNode = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode newNode = view->createModelNode("QtQuick.Rectangle", 1, 0);
newNode.variantProperty("x") = 100;
newNode.variantProperty("y") = 100;
@@ -2520,7 +2684,7 @@ void tst_TestCore::testRewriterAddNodeTransaction()
void tst_TestCore::testRewriterComponentId()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
" Component {\n"
" id: testComponent\n"
@@ -2533,7 +2697,7 @@ void tst_TestCore::testRewriterComponentId()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2546,17 +2710,17 @@ void tst_TestCore::testRewriterComponentId()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
ModelNode component(rootModelNode.allDirectSubModelNodes().first());
QVERIFY(component.isValid());
- QCOMPARE(component.type(), QString("Qt/Component"));
+ QCOMPARE(component.type(), QString("QtQuick.Component"));
QCOMPARE(component.id(), QString("testComponent"));
}
void tst_TestCore::testRewriterTransactionRewriter()
{
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"}\n";
@@ -2564,7 +2728,7 @@ void tst_TestCore::testRewriterTransactionRewriter()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2573,7 +2737,7 @@ void tst_TestCore::testRewriterTransactionRewriter()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
@@ -2586,7 +2750,7 @@ void tst_TestCore::testRewriterTransactionRewriter()
{
RewriterTransaction transaction = view->beginRewriterTransaction();
- childNode1 = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ childNode1 = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
childNode1.variantProperty("x") = 10;
childNode1.variantProperty("y") = 10;
}
@@ -2598,7 +2762,7 @@ void tst_TestCore::testRewriterTransactionRewriter()
{
RewriterTransaction transaction = view->beginRewriterTransaction();
- childNode2 = addNodeListChild(childNode1, "Qt/Rectangle", 4, 7, "data");
+ childNode2 = addNodeListChild(childNode1, "QtQuick.Rectangle", 1, 0, "data");
childNode2.destroy();
}
@@ -2623,7 +2787,7 @@ void tst_TestCore::testRewriterPropertyDeclarations()
// property variant myArray: [ Rectangle {} ]
// property variant someGradient: Gradient {}
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Item {\n"
" property int intProperty\n"
" property bool boolProperty: true\n"
@@ -2636,7 +2800,7 @@ void tst_TestCore::testRewriterPropertyDeclarations()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2654,7 +2818,7 @@ void tst_TestCore::testRewriterPropertyDeclarations()
//
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QCOMPARE(rootModelNode.properties().size(), 4);
@@ -2687,7 +2851,7 @@ void tst_TestCore::testRewriterPropertyAliases()
// where type is (int | bool | double | real | string | url | color | date | variant)
//
- char qmlString[] = "import Qt 4.7\n"
+ char qmlString[] = "import QtQuick 1.1\n"
"Item {\n"
" property alias theText: t.text\n"
" default alias property yPos: t.y\n"
@@ -2698,7 +2862,7 @@ void tst_TestCore::testRewriterPropertyAliases()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2711,7 +2875,7 @@ void tst_TestCore::testRewriterPropertyAliases()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QList<AbstractProperty> properties = rootModelNode.properties();
QCOMPARE(properties.size(), 0); // TODO: How to represent alias properties? As Bindings?
@@ -2720,7 +2884,7 @@ void tst_TestCore::testRewriterPropertyAliases()
void tst_TestCore::testRewriterPositionAndOffset()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: root\n"
@@ -2758,7 +2922,7 @@ void tst_TestCore::testRewriterPositionAndOffset()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2771,7 +2935,7 @@ void tst_TestCore::testRewriterPositionAndOffset()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
QString string = QString(qmlString).mid(testRewriterView->nodeOffset(rootNode), testRewriterView->nodeLength(rootNode));
const QString qmlExpected0("Rectangle {\n"
@@ -2837,7 +3001,7 @@ void tst_TestCore::testRewriterPositionAndOffset()
void tst_TestCore::testRewriterComponentTextModifier()
{
- const QString qmlString("import Qt 4.7\n"
+ const QString qmlString("import QtQuick 1.1\n"
"Rectangle {\n"
" id: root\n"
" x: 10;\n"
@@ -2860,7 +3024,7 @@ void tst_TestCore::testRewriterComponentTextModifier()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2873,7 +3037,7 @@ void tst_TestCore::testRewriterComponentTextModifier()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
ModelNode componentNode = rootNode.allDirectSubModelNodes().last();
@@ -2884,7 +3048,7 @@ void tst_TestCore::testRewriterComponentTextModifier()
ComponentTextModifier componentTextModifier(&textModifier, componentStartOffset, componentEndOffset, rootStartOffset);
- const QString qmlExpected("import Qt 4.7\n"
+ const QString qmlExpected("import QtQuick 1.1\n"
" "
" "
" "
@@ -2905,19 +3069,20 @@ void tst_TestCore::testRewriterComponentTextModifier()
QCOMPARE(componentTextModifier.text(), qmlExpected);
- QScopedPointer<Model> componentModel(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> componentModel(Model::create("QtQuick.Item", 1, 1));
QScopedPointer<TestRewriterView> testRewriterViewComponent(new TestRewriterView());
testRewriterViewComponent->setTextModifier(&componentTextModifier);
componentModel->attachView(testRewriterViewComponent.data());
ModelNode componentrootNode = testRewriterViewComponent->rootModelNode();
QVERIFY(componentrootNode.isValid());
- QCOMPARE(componentrootNode.type(), QLatin1String("Qt/Component"));
+ //The <Component> node is skipped
+ QCOMPARE(componentrootNode.type(), QLatin1String("QtQuick.Rectangle"));
}
void tst_TestCore::testRewriterPreserveType()
{
- const QString qmlString("import Qt 4.7\n"
+ const QString qmlString("import QtQuick 1.1\n"
"Rectangle {\n"
" id: root\n"
" Text {\n"
@@ -2930,7 +3095,7 @@ void tst_TestCore::testRewriterPreserveType()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2943,7 +3108,7 @@ void tst_TestCore::testRewriterPreserveType()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
ModelNode textNode = rootNode.allDirectSubModelNodes().first();
QCOMPARE(QVariant::Bool, textNode.variantProperty("font.bold").value().type());
@@ -2952,7 +3117,7 @@ void tst_TestCore::testRewriterPreserveType()
textNode.variantProperty("font.bold") = QVariant(true);
textNode.variantProperty("font.pointSize") = QVariant(13.0);
- ModelNode newTextNode = addNodeListChild(rootNode, "Qt/Text", 4, 7, "data");
+ ModelNode newTextNode = addNodeListChild(rootNode, "QtQuick.Text", 1, 1, "data");
newTextNode.variantProperty("font.bold") = QVariant(true);
newTextNode.variantProperty("font.pointSize") = QVariant(13.0);
@@ -2964,7 +3129,7 @@ void tst_TestCore::testRewriterPreserveType()
void tst_TestCore::testRewriterForArrayMagic()
{
try {
- const QLatin1String qmlString("import Qt 4.7\n"
+ const QLatin1String qmlString("import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" states: State {\n"
@@ -2975,7 +3140,7 @@ void tst_TestCore::testRewriterForArrayMagic()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -2988,16 +3153,16 @@ void tst_TestCore::testRewriterForArrayMagic()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
QVERIFY(rootNode.property(QLatin1String("states")).isNodeListProperty());
QmlItemNode rootItem(rootNode);
QVERIFY(rootItem.isValid());
QmlModelState state1(rootItem.states().addState("s2"));
- QCOMPARE(state1.modelNode().type(), QString("Qt/State"));
+ QCOMPARE(state1.modelNode().type(), QString("QtQuick.State"));
- const QLatin1String expected("import Qt 4.7\n"
+ const QLatin1String expected("import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" states: [\n"
@@ -3018,7 +3183,7 @@ void tst_TestCore::testRewriterForArrayMagic()
void tst_TestCore::testRewriterWithSignals()
{
- const QLatin1String qmlString("import Qt 4.7\n"
+ const QLatin1String qmlString("import QtQuick 1.1\n"
"\n"
"TextEdit {\n"
" onTextChanged: { print(\"foo\"); }\n"
@@ -3027,7 +3192,7 @@ void tst_TestCore::testRewriterWithSignals()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3040,7 +3205,7 @@ void tst_TestCore::testRewriterWithSignals()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/TextEdit"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.TextEdit"));
QmlItemNode rootItem(rootNode);
QVERIFY(rootItem.isValid());
@@ -3050,7 +3215,7 @@ void tst_TestCore::testRewriterWithSignals()
void tst_TestCore::testRewriterNodeSliding()
{
- const QLatin1String qmlString("import Qt 4.7\n"
+ const QLatin1String qmlString("import QtQuick 1.1\n"
"Rectangle {\n"
" id: root\n"
" Rectangle {\n"
@@ -3070,7 +3235,7 @@ void tst_TestCore::testRewriterNodeSliding()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3083,7 +3248,7 @@ void tst_TestCore::testRewriterNodeSliding()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
QCOMPARE(rootNode.id(), QLatin1String("root"));
QCOMPARE(rootNode.nodeListProperty(QLatin1String("data")).toModelNodeList().at(0).id(), QLatin1String("rectangle1"));
@@ -3102,7 +3267,7 @@ void tst_TestCore::testRewriterNodeSliding()
void tst_TestCore::testRewriterExceptionHandling()
{
- const QLatin1String qmlString("import Qt 4.7\n"
+ const QLatin1String qmlString("import QtQuick 1.1\n"
"Text {\n"
"}");
@@ -3110,7 +3275,7 @@ void tst_TestCore::testRewriterExceptionHandling()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Text", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Text", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3123,7 +3288,7 @@ void tst_TestCore::testRewriterExceptionHandling()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Text"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Text"));
try
{
@@ -3132,9 +3297,9 @@ void tst_TestCore::testRewriterExceptionHandling()
rootNode.variantProperty("bla") = QVariant("blah");
transaction.commit();
QFAIL("RewritingException should be thrown");
- } catch (RewritingException &e) {
+ } catch (RewritingException &) {
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Text"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Text"));
QVERIFY(!rootNode.hasProperty("bla"));
QVERIFY(!rootNode.hasProperty("text"));
}
@@ -3142,7 +3307,7 @@ void tst_TestCore::testRewriterExceptionHandling()
void tst_TestCore::testRewriterFirstDefinitionInside()
{
- const QString qmlString("import Qt 4.7\n"
+ const QString qmlString("import QtQuick 1.1\n"
"Rectangle {\n"
" id: root\n"
" x: 10;\n"
@@ -3166,7 +3331,7 @@ void tst_TestCore::testRewriterFirstDefinitionInside()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3179,7 +3344,7 @@ void tst_TestCore::testRewriterFirstDefinitionInside()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
ModelNode componentNode = rootNode.allDirectSubModelNodes().last();
@@ -3198,7 +3363,7 @@ void tst_TestCore::testRewriterFirstDefinitionInside()
void tst_TestCore::testCopyModelRewriter1()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: root\n"
@@ -3236,7 +3401,7 @@ void tst_TestCore::testCopyModelRewriter1()
textEdit1.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model1.data());
QScopedPointer<TestView> view1(new TestView(model1.data()));
@@ -3249,13 +3414,13 @@ void tst_TestCore::testCopyModelRewriter1()
ModelNode rootNode1 = view1->rootModelNode();
QVERIFY(rootNode1.isValid());
- QCOMPARE(rootNode1.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode1.type(), QLatin1String("QtQuick.Rectangle"));
QPlainTextEdit textEdit2;
textEdit2.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier2(&textEdit2);
- QScopedPointer<Model> model2(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model2(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model2.data());
QScopedPointer<TestView> view2(new TestView(model2.data()));
@@ -3268,7 +3433,7 @@ void tst_TestCore::testCopyModelRewriter1()
ModelNode rootNode2 = view2->rootModelNode();
QVERIFY(rootNode2.isValid());
- QCOMPARE(rootNode2.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode2.type(), QLatin1String("QtQuick.Rectangle"));
//
@@ -3293,7 +3458,7 @@ void tst_TestCore::testCopyModelRewriter1()
const QLatin1String expected(
"\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: root\n"
@@ -3368,7 +3533,7 @@ void tst_TestCore::testCopyModelRewriter1()
void tst_TestCore::testCopyModelRewriter2()
{
const QLatin1String qmlString1("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"id: root\n"
@@ -3408,7 +3573,7 @@ void tst_TestCore::testCopyModelRewriter2()
const QLatin1String qmlString2("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -3417,7 +3582,7 @@ void tst_TestCore::testCopyModelRewriter2()
textEdit1.setPlainText(qmlString1);
NotIndentingTextEditModifier textModifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model1.data());
QScopedPointer<TestView> view1(new TestView(model1.data()));
@@ -3430,7 +3595,7 @@ void tst_TestCore::testCopyModelRewriter2()
ModelNode rootNode1 = view1->rootModelNode();
QVERIFY(rootNode1.isValid());
- QCOMPARE(rootNode1.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode1.type(), QLatin1String("QtQuick.Rectangle"));
// read in 2
@@ -3439,7 +3604,7 @@ void tst_TestCore::testCopyModelRewriter2()
textEdit2.setPlainText(qmlString2);
NotIndentingTextEditModifier textModifier2(&textEdit2);
- QScopedPointer<Model> model2(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model2(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model2.data());
QScopedPointer<TestView> view2(new TestView(model2.data()));
@@ -3451,7 +3616,7 @@ void tst_TestCore::testCopyModelRewriter2()
ModelNode rootNode2 = view2->rootModelNode();
QVERIFY(rootNode2.isValid());
- QCOMPARE(rootNode2.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode2.type(), QLatin1String("QtQuick.Rectangle"));
//
@@ -3460,7 +3625,7 @@ void tst_TestCore::testCopyModelRewriter2()
merger.replaceModel(rootNode1);
QVERIFY(rootNode2.isValid());
- QCOMPARE(rootNode2.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode2.type(), QLatin1String("QtQuick.Rectangle"));
QCOMPARE(textEdit2.toPlainText(), qmlString1);
}
@@ -3475,9 +3640,9 @@ void tst_TestCore::testSubComponentManager()
textEdit.setPlainText(file.readAll());
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
model->setFileUrl(QUrl::fromLocalFile(fileName));
- QScopedPointer<SubComponentManager> subComponentManager(new SubComponentManager(model->metaInfo(), 0));
+ QScopedPointer<SubComponentManager> subComponentManager(new SubComponentManager(model.data()));
subComponentManager->update(QUrl::fromLocalFile(fileName), model->imports());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -3489,9 +3654,9 @@ void tst_TestCore::testSubComponentManager()
QVERIFY(testRewriterView->rootModelNode().isValid());
- QVERIFY(model->metaInfo("Qt/Rectangle").propertyNames().contains("border.width"));
+ QVERIFY(model->metaInfo("QtQuick.Rectangle").propertyNames().contains("border.width"));
- QVERIFY(model->metaInfo("Qt/Pen").isValid());
+ QVERIFY(model->metaInfo("<cpp>.QDeclarative1Pen").isValid());
NodeMetaInfo myButtonMetaInfo = model->metaInfo("MyButton");
QVERIFY(myButtonMetaInfo.isValid());
QVERIFY(myButtonMetaInfo.propertyNames().contains("border.width"));
@@ -3500,7 +3665,7 @@ void tst_TestCore::testSubComponentManager()
void tst_TestCore::testAnchorsAndRewriting()
{
- const QString qmlString("import Qt 4.7\n"
+ const QString qmlString("import QtQuick 1.1\n"
"Rectangle {\n"
" id: root\n"
" x: 10;\n"
@@ -3523,7 +3688,7 @@ void tst_TestCore::testAnchorsAndRewriting()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3536,7 +3701,7 @@ void tst_TestCore::testAnchorsAndRewriting()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
QmlItemNode rootItemNode = view->rootQmlItemNode();
QVERIFY(rootItemNode.isValid());
@@ -3561,7 +3726,7 @@ void tst_TestCore::testAnchorsAndRewriting()
void tst_TestCore::testAnchorsAndRewritingCenter()
{
- const QString qmlString("import Qt 4.7\n"
+ const QString qmlString("import QtQuick 1.1\n"
"Rectangle {\n"
" id: root\n"
" x: 10;\n"
@@ -3584,7 +3749,7 @@ void tst_TestCore::testAnchorsAndRewritingCenter()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3597,7 +3762,7 @@ void tst_TestCore::testAnchorsAndRewritingCenter()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
QmlItemNode rootItemNode = view->rootQmlItemNode();
QVERIFY(rootItemNode.isValid());
@@ -3611,7 +3776,7 @@ void tst_TestCore::testAnchorsAndRewritingCenter()
void tst_TestCore::loadQml()
{
-char qmlString[] = "import Qt 4.7\n"
+char qmlString[] = "import QtQuick 1.1\n"
"Rectangle {\n"
"id: root;\n"
"width: 200;\n"
@@ -3652,7 +3817,7 @@ char qmlString[] = "import Qt 4.7\n"
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -3661,14 +3826,14 @@ char qmlString[] = "import Qt 4.7\n"
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
testRewriterView->setTextModifier(&textModifier);
model->attachView(testRewriterView.data());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
QCOMPARE(rootModelNode.id(), QString("root"));
QCOMPARE(rootModelNode.variantProperty("width").value().toInt(), 200);
QCOMPARE(rootModelNode.variantProperty("height").value().toInt(), 200);
@@ -3678,7 +3843,7 @@ char qmlString[] = "import Qt 4.7\n"
QCOMPARE(rootModelNode.nodeListProperty("data").toModelNodeList().count(), 3);
ModelNode textNode1 = rootModelNode.nodeListProperty("data").toModelNodeList().first();
QVERIFY(textNode1.isValid());
- QCOMPARE(textNode1.type(), QString("Qt/Text"));
+ QCOMPARE(textNode1.type(), QString("QtQuick.Text"));
QCOMPARE(textNode1.id(), QString("text1"));
QCOMPARE(textNode1.variantProperty("text").value().toString(), QString("Hello World"));
QVERIFY(textNode1.hasProperty("anchors.centerIn"));
@@ -3694,13 +3859,13 @@ char qmlString[] = "import Qt 4.7\n"
ModelNode rectNode = rootModelNode.nodeListProperty("data").toModelNodeList().at(1);
QVERIFY(rectNode.isValid());
- QCOMPARE(rectNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rectNode.type(), QString("QtQuick.Rectangle"));
QCOMPARE(rectNode.id(), QString("rectangle"));
QVERIFY(rectNode.hasProperty("gradient"));
QVERIFY(rectNode.property("gradient").isNodeProperty());
ModelNode gradientNode = rectNode.nodeProperty("gradient").modelNode();
QVERIFY(gradientNode.isValid());
- QCOMPARE(gradientNode.type(), QString("Qt/Gradient"));
+ QCOMPARE(gradientNode.type(), QString("QtQuick.Gradient"));
QVERIFY(gradientNode.hasProperty("stops"));
QVERIFY(gradientNode.property("stops").isNodeListProperty());
QCOMPARE(gradientNode.nodeListProperty("stops").toModelNodeList().count(), 2);
@@ -3711,15 +3876,15 @@ char qmlString[] = "import Qt 4.7\n"
QVERIFY(stop1.isValid());
QVERIFY(stop2.isValid());
- QCOMPARE(stop1.type(), QString("Qt/GradientStop"));
- QCOMPARE(stop2.type(), QString("Qt/GradientStop"));
+ QCOMPARE(stop1.type(), QString("QtQuick.GradientStop"));
+ QCOMPARE(stop2.type(), QString("QtQuick.GradientStop"));
QCOMPARE(stop1.variantProperty("position").value().toInt(), 0);
QCOMPARE(stop2.variantProperty("position").value().toInt(), 1);
ModelNode textNode2 = rootModelNode.nodeListProperty("data").toModelNodeList().last();
QVERIFY(textNode2.isValid());
- QCOMPARE(textNode2.type(), QString("Qt/Text"));
+ QCOMPARE(textNode2.type(), QString("QtQuick.Text"));
QCOMPARE(textNode2.id(), QString("text2"));
QCOMPARE(textNode2.variantProperty("width").value().toInt(), 80);
QCOMPARE(textNode2.variantProperty("height").value().toInt(), 20);
@@ -3730,105 +3895,83 @@ char qmlString[] = "import Qt 4.7\n"
void tst_TestCore::testMetaInfo()
{
- QSKIP("Fix metainfo", SkipAll);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
+ model->changeImports(QList<Import>() << Import::createLibraryImport("QtWebKit", "1.0"), QList<Import>());
// test whether default type is registered
- QVERIFY(model->metaInfo("Qt/Item", 4, 7).isValid());
+ QVERIFY(model->metaInfo("QtQuick.Item", -1, -1).isValid());
// test whether types from plugins are registered
- QVERIFY(model->hasNodeMetaInfo("QtWebKit/WebView", 1, 0));
+ QVERIFY(model->hasNodeMetaInfo("QtWebKit.WebView", -1, -1));
// test whether non-qml type is registered
- QVERIFY(model->hasNodeMetaInfo("QGraphicsObject", 4, 7)); // Qt 4.7 namespace
- QVERIFY(model->hasNodeMetaInfo("QGraphicsObject", 1, 0)); // webkit 1.0 namespace
+ QVERIFY(model->hasNodeMetaInfo("<cpp>.QGraphicsObject", -1, -1)); // Qt 4.7 namespace
}
void tst_TestCore::testMetaInfoSimpleType()
{
- QSKIP("Fix metainfo", SkipAll);
- //
- // Test type registered with qmlRegisterType:
- //
- // qmlRegisterType<QDeclarativeItem>("Qt",4,7,"Item")
- //
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
- QVERIFY(model->hasNodeMetaInfo("Qt/Item", 4, 7));
- QVERIFY(model->hasNodeMetaInfo("Qt/Item", 4, 7));
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.Item", 1, 1));
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.Item", 1, 1));
- NodeMetaInfo itemMetaInfo = model->metaInfo("Qt/Item", 4, 7);
- NodeMetaInfo itemMetaInfo2 = model->metaInfo("Qt/Item", 4, 7);
+ NodeMetaInfo itemMetaInfo = model->metaInfo("QtQuick.Item", 1, 1);
+ NodeMetaInfo itemMetaInfo2 = model->metaInfo("QtQuick.Item", 1, 1);
QVERIFY(itemMetaInfo.isValid());
- QCOMPARE(itemMetaInfo.typeName(), QLatin1String("Qt/Item"));
- QCOMPARE(itemMetaInfo.majorVersion(), 4);
- QCOMPARE(itemMetaInfo.minorVersion(), 7);
+ QCOMPARE(itemMetaInfo.typeName(), QLatin1String("QtQuick.Item"));
+ QCOMPARE(itemMetaInfo.majorVersion(), 1);
+ QCOMPARE(itemMetaInfo.minorVersion(), 1);
// super classes
NodeMetaInfo graphicsObjectInfo = itemMetaInfo.directSuperClass();
QVERIFY(graphicsObjectInfo.isValid());
- QCOMPARE(graphicsObjectInfo.typeName(), QLatin1String("QGraphicsObject"));
+ QCOMPARE(graphicsObjectInfo.typeName(), QLatin1String("QtQuick.QGraphicsObject"));
QCOMPARE(graphicsObjectInfo.majorVersion(), -1);
QCOMPARE(graphicsObjectInfo.minorVersion(), -1);
- QCOMPARE(itemMetaInfo.superClasses().size(), 2); // QGraphicsObject, Qt/QtObject
- QVERIFY(itemMetaInfo.isSubclassOf("QGraphicsObject", 4, 7));
- QVERIFY(itemMetaInfo.isSubclassOf("Qt/QtObject", 4, 7));
+ QCOMPARE(itemMetaInfo.superClasses().size(), 3); // Item, QGraphicsObject, QtQuick.QtObject
+ QVERIFY(itemMetaInfo.isSubclassOf("QtQuick.QGraphicsObject", -1, -1));
+ QVERIFY(itemMetaInfo.isSubclassOf("<cpp>.QObject", -1, -1));
// availableInVersion
- QVERIFY(itemMetaInfo.availableInVersion(4, 7));
- QVERIFY(itemMetaInfo.availableInVersion(4, 8));
- QVERIFY(itemMetaInfo.availableInVersion(5, 0));
+ QVERIFY(itemMetaInfo.availableInVersion(1, 1));
+ QVERIFY(itemMetaInfo.availableInVersion(1, 0));
QVERIFY(itemMetaInfo.availableInVersion(-1, -1));
- QVERIFY(!itemMetaInfo.availableInVersion(4, 6));
- QVERIFY(!itemMetaInfo.availableInVersion(3, 7));
}
void tst_TestCore::testMetaInfoUncreatableType()
{
- QSKIP("Fix metainfo", SkipAll);
- // Test type registered with qmlRegisterUncreatableType or qmlRegisterTypeNotAvailable:
- //
- // qmlRegisterUncreatableType<QDeclarativeAbstractAnimation>("Qt",4,7,"Animation",QDeclarativeAbstractAnimation::tr("Animation is an abstract class"));
- //
-
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
- QVERIFY(model->hasNodeMetaInfo("Qt/Animation"));
- NodeMetaInfo animationTypeInfo = model->metaInfo("Qt/Animation", 4, 7);
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.Animation"));
+ NodeMetaInfo animationTypeInfo = model->metaInfo("QtQuick.Animation", 1, 1);
QVERIFY(animationTypeInfo.isValid());
QVERIFY(animationTypeInfo.isValid());
- QCOMPARE(animationTypeInfo.typeName(), QLatin1String("Qt/Animation"));
- QCOMPARE(animationTypeInfo.majorVersion(), 4);
- QCOMPARE(animationTypeInfo.minorVersion(), 7);
+ QCOMPARE(animationTypeInfo.typeName(), QLatin1String("QtQuick.Animation"));
+ QCOMPARE(animationTypeInfo.majorVersion(), 1);
+ QCOMPARE(animationTypeInfo.minorVersion(), 1);
NodeMetaInfo qObjectTypeInfo = animationTypeInfo.directSuperClass();
QVERIFY(qObjectTypeInfo.isValid());
- QCOMPARE(qObjectTypeInfo.typeName(), QLatin1String("Qt/QtObject"));
- QCOMPARE(qObjectTypeInfo.majorVersion(), 4);
- QCOMPARE(qObjectTypeInfo.minorVersion(), 7);
- QCOMPARE(animationTypeInfo.superClasses().size(), 1);
+ QCOMPARE(qObjectTypeInfo.typeName(), QLatin1String("QtQuick.QtObject"));
+ QCOMPARE(qObjectTypeInfo.majorVersion(), 1);
+ QCOMPARE(qObjectTypeInfo.minorVersion(), 0);
+ QCOMPARE(animationTypeInfo.superClasses().size(), 2);
}
void tst_TestCore::testMetaInfoExtendedType()
{
- QSKIP("Fix metainfo", SkipAll);
- // Test type registered with qmlRegisterExtendedType
- //
- // qmlRegisterExtendedType<QGraphicsWidget,QDeclarativeGraphicsWidget>("Qt",4,7,"QGraphicsWidget");
- //
-
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
- QVERIFY(model->hasNodeMetaInfo("Qt/QGraphicsWidget"));
- NodeMetaInfo graphicsWidgetTypeInfo = model->metaInfo("Qt/QGraphicsWidget", 4, 7);
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.QGraphicsWidget"));
+ NodeMetaInfo graphicsWidgetTypeInfo = model->metaInfo("QtQuick.QGraphicsWidget", 1, 1);
QVERIFY(graphicsWidgetTypeInfo.isValid());
QVERIFY(graphicsWidgetTypeInfo.hasProperty("layout")); // from QGraphicsWidgetDeclarativeUI
QVERIFY(graphicsWidgetTypeInfo.hasProperty("font")); // from QGraphicsWidget
@@ -3836,10 +3979,10 @@ void tst_TestCore::testMetaInfoExtendedType()
NodeMetaInfo graphicsObjectTypeInfo = graphicsWidgetTypeInfo.directSuperClass();
QVERIFY(graphicsObjectTypeInfo.isValid());
- QCOMPARE(graphicsObjectTypeInfo.typeName(), QLatin1String("QGraphicsObject"));
+ QCOMPARE(graphicsObjectTypeInfo.typeName(), QLatin1String("<cpp>.QGraphicsObject"));
QCOMPARE(graphicsObjectTypeInfo.majorVersion(), -1);
QCOMPARE(graphicsObjectTypeInfo.minorVersion(), -1);
- QCOMPARE(graphicsWidgetTypeInfo.superClasses().size(), 2);
+ QCOMPARE(graphicsWidgetTypeInfo.superClasses().size(), 3);
}
void tst_TestCore::testMetaInfoInterface()
@@ -3847,22 +3990,16 @@ void tst_TestCore::testMetaInfoInterface()
// Test type registered with qmlRegisterInterface
//
- QSKIP("TODO: Test not implemented yet", SkipAll);
+ MSKIP_ALL("TODO: Test not implemented yet");
}
void tst_TestCore::testMetaInfoCustomType()
{
- QSKIP("Fix metainfo", SkipAll);
-
- // Test type registered with qmlRegisterCustomType:
- //
- // qmlRegisterCustomType<QDeclarativePropertyChanges>("Qt", 4, 7, "PropertyChanges", new QDeclarativePropertyChangesParser);
-
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
- QVERIFY(model->hasNodeMetaInfo("Qt/PropertyChanges"));
- NodeMetaInfo propertyChangesInfo = model->metaInfo("Qt/PropertyChanges", 4, 7);
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.PropertyChanges"));
+ NodeMetaInfo propertyChangesInfo = model->metaInfo("QtQuick.PropertyChanges", 1, 1);
QVERIFY(propertyChangesInfo.isValid());
QVERIFY(propertyChangesInfo.hasProperty("target")); // from QDeclarativePropertyChanges
QVERIFY(propertyChangesInfo.hasProperty("restoreEntryValues")); // from QDeclarativePropertyChanges
@@ -3870,27 +4007,27 @@ void tst_TestCore::testMetaInfoCustomType()
NodeMetaInfo stateOperationInfo = propertyChangesInfo.directSuperClass();
QVERIFY(stateOperationInfo.isValid());
- QCOMPARE(stateOperationInfo.typeName(), QLatin1String("QDeclarativeStateOperation"));
+ QCOMPARE(stateOperationInfo.typeName(), QLatin1String("QtQuick.QDeclarative1StateOperation"));
QCOMPARE(stateOperationInfo.majorVersion(), -1);
QCOMPARE(stateOperationInfo.minorVersion(), -1);
- QCOMPARE(propertyChangesInfo.superClasses().size(), 2);
+ QCOMPARE(propertyChangesInfo.superClasses().size(), 3);
// DeclarativePropertyChanges just has 3 properties
QCOMPARE(propertyChangesInfo.propertyNames().size() - stateOperationInfo.propertyNames().size(), 3);
+
+ QApplication::processEvents();
}
void tst_TestCore::testMetaInfoEnums()
{
- QSKIP("Fix metainfo", SkipAll);
-
- QScopedPointer<Model> model(Model::create("Qt/Text"));
+ QScopedPointer<Model> model(createModel("QtQuick.Text"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- QCOMPARE(view->rootModelNode().metaInfo().typeName(), QString("Qt/Text"));
+ QCOMPARE(view->rootModelNode().metaInfo().typeName(), QString("QtQuick.Text"));
QVERIFY(view->rootModelNode().metaInfo().hasProperty("transformOrigin"));
@@ -3903,42 +4040,107 @@ void tst_TestCore::testMetaInfoEnums()
QCOMPARE(view->rootModelNode().metaInfo().propertyTypeName("horizontalAlignment"), QLatin1String("HAlignment"));
QVERIFY(view->rootModelNode().metaInfo().propertyKeysForEnum("horizontalAlignment").contains(QLatin1String("AlignLeft")));
QVERIFY(view->rootModelNode().metaInfo().propertyKeysForEnum("horizontalAlignment").contains(QLatin1String("AlignRight")));
+
+ QApplication::processEvents();
}
-void tst_TestCore::testMetaInfoProperties()
+void tst_TestCore::testMetaInfoQtQuick1Vs2()
{
- QSKIP("Fix metainfo", SkipAll);
+ char qmlString[] = "import QtQuick 2.0\n"
+ "Rectangle {\n"
+ "id: root;\n"
+ "width: 200;\n"
+ "height: 200;\n"
+ "color: \"white\";\n"
+ "Text {\n"
+ "id: text1\n"
+ "text: \"Hello World\"\n"
+ "anchors.centerIn: parent\n"
+ "Item {\n"
+ "id: item\n"
+ "}\n"
+ "}\n"
+ "Rectangle {\n"
+ "id: rectangle;\n"
+ "gradient: Gradient {\n"
+ "GradientStop {\n"
+ "position: 0\n"
+ "color: \"white\"\n"
+ "}\n"
+ "GradientStop {\n"
+ "position: 1\n"
+ "color: \"black\"\n"
+ "}\n"
+ "}\n"
+ "}\n"
+ "Text {\n"
+ "text: \"text\"\n"
+ "x: 66\n"
+ "y: 43\n"
+ "width: 80\n"
+ "height: 20\n"
+ "id: text2\n"
+ "}\n"
+ "}\n";
+
+ QPlainTextEdit textEdit;
+ textEdit.setPlainText(qmlString);
+ NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Text"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
- NodeMetaInfo textNodeMetaInfo = model->metaInfo("Qt/TextEdit", 4, 7);
+ QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
+ testRewriterView->setTextModifier(&textModifier);
+
+ model->attachView(testRewriterView.data());
+
+ ModelNode rootModelNode = testRewriterView->rootModelNode();
+ QVERIFY(rootModelNode.isValid());
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
+
+ QVERIFY(!model->metaInfo("Rectangle", 1, 0).isValid());
+ QVERIFY(model->metaInfo("Rectangle", -1, -1).isValid());
+ QVERIFY(model->metaInfo("Rectangle", 2, 0).isValid());
+
+ QVERIFY(!model->metaInfo("QtQuick.Rectangle", 1, 0).isValid());
+ QVERIFY(model->metaInfo("QtQuick.Rectangle", -1, -1).isValid());
+ QVERIFY(model->metaInfo("QtQuick.Rectangle", 2, 0).isValid());
+}
+
+void tst_TestCore::testMetaInfoProperties()
+{
+ QScopedPointer<Model> model(createModel("QtQuick.Text"));
+ QVERIFY(model.data());
+
+ NodeMetaInfo textNodeMetaInfo = model->metaInfo("QtQuick.TextEdit", 1, 1);
QVERIFY(textNodeMetaInfo.hasProperty("text")); // QDeclarativeTextEdit
QVERIFY(textNodeMetaInfo.hasProperty("parent")); // QDeclarativeItem
QVERIFY(textNodeMetaInfo.hasProperty("x")); // QGraphicsObject
- QVERIFY(textNodeMetaInfo.hasProperty("objectName")); // Qt/QObject
+ QVERIFY(textNodeMetaInfo.hasProperty("objectName")); // QtQuick.QObject
QVERIFY(!textNodeMetaInfo.hasProperty("bla"));
QVERIFY(textNodeMetaInfo.propertyIsWritable("text"));
QVERIFY(textNodeMetaInfo.propertyIsWritable("x"));
+
+ QApplication::processEvents();
}
void tst_TestCore::testMetaInfoDotProperties()
{
- QSKIP("Fix metainfo", SkipAll);
-
- QScopedPointer<Model> model(Model::create("Qt/Text"));
+ QScopedPointer<Model> model(createModel("QtQuick.Text"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- QVERIFY(model->hasNodeMetaInfo("Qt/Text"));
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.Text"));
- QVERIFY(model->hasNodeMetaInfo("Qt/Pen"));
+ QVERIFY(model->metaInfo("QtQuick.Rectangle").hasProperty("border"));
+ QCOMPARE(model->metaInfo("QtQuick.Rectangle").propertyTypeName("border"), QString("<cpp>.QDeclarative1Pen"));
- QCOMPARE(view->rootModelNode().metaInfo().typeName(), QString("Qt/Text"));
+ QCOMPARE(view->rootModelNode().metaInfo().typeName(), QString("QtQuick.Text"));
QVERIFY(view->rootModelNode().metaInfo().hasProperty("font"));
QVERIFY(view->rootModelNode().metaInfo().hasProperty("font.bold"));
@@ -3946,32 +4148,30 @@ void tst_TestCore::testMetaInfoDotProperties()
QVERIFY(view->rootModelNode().metaInfo().propertyNames().contains("font.pointSize"));
QVERIFY(view->rootModelNode().metaInfo().hasProperty("font.pointSize"));
- ModelNode rectNode(addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data"));
-
+ ModelNode rectNode(addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data"));
- QVERIFY(rectNode.metaInfo().propertyNames().contains("pos.x"));
- QVERIFY(!rectNode.metaInfo().propertyNames().contains("pos.x"));
+ QVERIFY(rectNode.metaInfo().propertyNames().contains("pos"));
QVERIFY(rectNode.metaInfo().propertyNames().contains("pos.y"));
- QVERIFY(!rectNode.metaInfo().propertyNames().contains("pos.y"));
- QVERIFY(!rectNode.metaInfo().propertyNames().contains("anchors.topMargin"));
+ QVERIFY(rectNode.metaInfo().propertyNames().contains("pos.x"));
+ QVERIFY(rectNode.metaInfo().propertyNames().contains("anchors.topMargin"));
QVERIFY(rectNode.metaInfo().propertyNames().contains("border.width"));
QVERIFY(rectNode.metaInfo().hasProperty("border"));
QVERIFY(rectNode.metaInfo().hasProperty("border.width"));
+
+ QApplication::processEvents();
}
void tst_TestCore::testMetaInfoListProperties()
{
- QSKIP("Fix metainfo", SkipAll);
-
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- QVERIFY(model->hasNodeMetaInfo("Qt/Item"));
- QCOMPARE(view->rootModelNode().metaInfo().typeName(), QString("Qt/Item"));
+ QVERIFY(model->hasNodeMetaInfo("QtQuick.Item"));
+ QCOMPARE(view->rootModelNode().metaInfo().typeName(), QString("QtQuick.Item"));
QVERIFY(view->rootModelNode().metaInfo().hasProperty("states"));
QVERIFY(view->rootModelNode().metaInfo().propertyIsListProperty("states"));
@@ -3990,15 +4190,65 @@ void tst_TestCore::testMetaInfoListProperties()
QVERIFY(!view->rootModelNode().metaInfo().propertyIsListProperty("effect"));
QVERIFY(view->rootModelNode().metaInfo().hasProperty("parent"));
QVERIFY(!view->rootModelNode().metaInfo().propertyIsListProperty("parent"));
+
+ QApplication::processEvents();
+}
+
+void tst_TestCore::testQtQuick20Basic()
+{
+ QPlainTextEdit textEdit;
+ textEdit.setPlainText("\nimport QtQuick 2.0\n\nItem {\n}\n");
+ NotIndentingTextEditModifier modifier(&textEdit);
+
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
+ QVERIFY(model.data());
+
+ TestRewriterView *testRewriterView = new TestRewriterView(model.data());
+ testRewriterView->setTextModifier(&modifier);
+ model->attachView(testRewriterView);
+
+ QVERIFY(testRewriterView->errors().isEmpty());
+ ModelNode rootModelNode(testRewriterView->rootModelNode());
+ QVERIFY(rootModelNode.isValid());
+ QCOMPARE(rootModelNode.metaInfo().majorVersion(), 2);
+ QCOMPARE(rootModelNode.metaInfo().minorVersion(), 0);
+ QCOMPARE(rootModelNode.majorQtQuickVersion(), 2);
+ QCOMPARE(rootModelNode.majorVersion(), 2);
+}
+
+void tst_TestCore::testQtQuick20BasicRectangle()
+{
+ QPlainTextEdit textEdit;
+ textEdit.setPlainText("\nimport QtQuick 2.0\nRectangle {\n}\n");
+ NotIndentingTextEditModifier modifier(&textEdit);
+
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
+ QVERIFY(model.data());
+
+ TestRewriterView *testRewriterView = new TestRewriterView(model.data());
+ testRewriterView->setTextModifier(&modifier);
+ model->attachView(testRewriterView);
+
+ QTest::qSleep(1000);
+ QApplication::processEvents();
+
+ QVERIFY(testRewriterView->errors().isEmpty());
+ ModelNode rootModelNode(testRewriterView->rootModelNode());
+ QVERIFY(rootModelNode.isValid());
+ QCOMPARE(rootModelNode.type(), QString("QtQuick.Rectangle"));
+ QCOMPARE(rootModelNode.metaInfo().majorVersion(), 2);
+ QCOMPARE(rootModelNode.metaInfo().minorVersion(), 0);
+ QCOMPARE(rootModelNode.majorQtQuickVersion(), 2);
+ QCOMPARE(rootModelNode.majorVersion(), 2);
}
void tst_TestCore::testStatesRewriter()
{
QPlainTextEdit textEdit;
- textEdit.setPlainText("import Qt 4.7; Item {}\n");
+ textEdit.setPlainText("import QtQuick 1.1; Item {}\n");
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
@@ -4042,10 +4292,10 @@ void tst_TestCore::testStatesRewriter()
void tst_TestCore::testGradientsRewriter()
{
QPlainTextEdit textEdit;
- textEdit.setPlainText("\nimport Qt 4.7\n\nItem {\n}\n");
+ textEdit.setPlainText("\nimport QtQuick 1.1\n\nItem {\n}\n");
NotIndentingTextEditModifier modifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
@@ -4061,9 +4311,9 @@ void tst_TestCore::testGradientsRewriter()
QVERIFY(rootModelNode.isValid());
- ModelNode rectNode(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode rectNode(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
- const QLatin1String expected1("\nimport Qt 4.7\n"
+ const QLatin1String expected1("\nimport QtQuick 1.1\n"
"\n"
"Item {\n"
"Rectangle {\n"
@@ -4071,11 +4321,11 @@ void tst_TestCore::testGradientsRewriter()
"}\n");
QCOMPARE(textEdit.toPlainText(), expected1);
- ModelNode gradientNode(addNodeChild(rectNode, "Qt/Gradient", 4, 7, "gradient"));
+ ModelNode gradientNode(addNodeChild(rectNode, "QtQuick.Gradient", 1, 0, "gradient"));
QVERIFY(rectNode.hasNodeProperty("gradient"));
- const QLatin1String expected2("\nimport Qt 4.7\n"
+ const QLatin1String expected2("\nimport QtQuick 1.1\n"
"\n"
"Item {\n"
"Rectangle {\n"
@@ -4092,11 +4342,11 @@ void tst_TestCore::testGradientsRewriter()
propertyList.append(qMakePair(QString("position"), QVariant::fromValue(0)));
propertyList.append(qMakePair(QString("color"), QVariant::fromValue(QColor(Qt::red))));
- ModelNode gradientStop1(gradientNode.view()->createModelNode("Qt/GradientStop", 4, 7, propertyList));
+ ModelNode gradientStop1(gradientNode.view()->createModelNode("QtQuick.GradientStop", 1, 0, propertyList));
QVERIFY(gradientStop1.isValid());
stops.reparentHere(gradientStop1);
- const QLatin1String expected3("\nimport Qt 4.7\n"
+ const QLatin1String expected3("\nimport QtQuick 1.1\n"
"\n"
"Item {\n"
"Rectangle {\n"
@@ -4115,11 +4365,11 @@ void tst_TestCore::testGradientsRewriter()
propertyList.append(qMakePair(QString("position"), QVariant::fromValue(0.5)));
propertyList.append(qMakePair(QString("color"), QVariant::fromValue(QColor(Qt::blue))));
- ModelNode gradientStop2(gradientNode.view()->createModelNode("Qt/GradientStop", 4, 7, propertyList));
+ ModelNode gradientStop2(gradientNode.view()->createModelNode("QtQuick.GradientStop", 1, 0, propertyList));
QVERIFY(gradientStop2.isValid());
stops.reparentHere(gradientStop2);
- const QLatin1String expected4("\nimport Qt 4.7\n"
+ const QLatin1String expected4("\nimport QtQuick 1.1\n"
"\n"
"Item {\n"
"Rectangle {\n"
@@ -4143,11 +4393,11 @@ void tst_TestCore::testGradientsRewriter()
propertyList.append(qMakePair(QString("position"), QVariant::fromValue(0.8)));
propertyList.append(qMakePair(QString("color"), QVariant::fromValue(QColor(Qt::yellow))));
- ModelNode gradientStop3(gradientNode.view()->createModelNode("Qt/GradientStop", 4, 7, propertyList));
+ ModelNode gradientStop3(gradientNode.view()->createModelNode("QtQuick.GradientStop", 1, 0, propertyList));
QVERIFY(gradientStop3.isValid());
stops.reparentHere(gradientStop3);
- const QLatin1String expected5("\nimport Qt 4.7\n"
+ const QLatin1String expected5("\nimport QtQuick 1.1\n"
"\n"
"Item {\n"
"Rectangle {\n"
@@ -4174,7 +4424,7 @@ void tst_TestCore::testGradientsRewriter()
gradientNode.removeProperty("stops");
- const QLatin1String expected6("\nimport Qt 4.7\n"
+ const QLatin1String expected6("\nimport QtQuick 1.1\n"
"\n"
"Item {\n"
"Rectangle {\n"
@@ -4191,7 +4441,7 @@ void tst_TestCore::testGradientsRewriter()
propertyList.append(qMakePair(QString("position"), QVariant::fromValue(0)));
propertyList.append(qMakePair(QString("color"), QVariant::fromValue(QColor(Qt::blue))));
- gradientStop1 = gradientNode.view()->createModelNode("Qt/GradientStop", 4, 7, propertyList);
+ gradientStop1 = gradientNode.view()->createModelNode("QtQuick.GradientStop", 1, 0, propertyList);
QVERIFY(gradientStop1.isValid());
stops.reparentHere(gradientStop1);
@@ -4199,7 +4449,7 @@ void tst_TestCore::testGradientsRewriter()
void tst_TestCore::testQmlModelStates()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
@@ -4232,7 +4482,7 @@ void tst_TestCore::testQmlModelStates()
void tst_TestCore::testInstancesStates()
{
//
-// import Qt 4.7
+// import QtQuick 1.1
//
// Rectangle {
// Text {
@@ -4260,7 +4510,7 @@ void tst_TestCore::testInstancesStates()
// }
//
-// QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+// QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
// QVERIFY(model.data());
// QScopedPointer<TestView> view(new TestView(model.data()));
// QVERIFY(view.data());
@@ -4271,28 +4521,28 @@ void tst_TestCore::testInstancesStates()
// //
// ModelNode rootNode = view->rootModelNode();
-// ModelNode textNode = view->createModelNode("Qt/Text", 4, 7);
+// ModelNode textNode = view->createModelNode("QtQuick.Text", 1, 1);
// textNode.setId("targetObject");
// textNode.variantProperty("text").setValue("base state");
// rootNode.nodeListProperty("data").reparentHere(textNode);
-// ModelNode propertyChanges1Node = view->createModelNode("Qt/PropertyChanges", 4, 7);
+// ModelNode propertyChanges1Node = view->createModelNode("QtQuick.PropertyChanges", 1, 1);
// propertyChanges1Node.bindingProperty("target").setExpression("targetObject");
// propertyChanges1Node.variantProperty("x").setValue(10);
// propertyChanges1Node.variantProperty("text").setValue("state1");
-// ModelNode state1Node = view->createModelNode("Qt/State", 4, 7);
+// ModelNode state1Node = view->createModelNode("QtQuick.State", 1, 1);
// state1Node.variantProperty("name").setValue("state1");
// state1Node.nodeListProperty("changes").reparentHere(propertyChanges1Node);
// rootNode.nodeListProperty("states").reparentHere(state1Node);
-// ModelNode propertyChanges2Node = view->createModelNode("Qt/PropertyChanges", 4, 7);
+// ModelNode propertyChanges2Node = view->createModelNode("QtQuick.PropertyChanges", 1, 1);
// propertyChanges2Node.bindingProperty("target").setExpression("targetObject");
// propertyChanges2Node.variantProperty("text").setValue("state2");
-// ModelNode state2Node = view->createModelNode("Qt/State", 4, 7);
+// ModelNode state2Node = view->createModelNode("QtQuick.State", 1, 1);
// state2Node.variantProperty("name").setValue("state2");
// state2Node.nodeListProperty("changes").reparentHere(propertyChanges2Node);
@@ -4389,7 +4639,7 @@ void tst_TestCore::testInstancesStates()
// //
// // move property changes of current state out of state
-// ModelNode state3Node = view->createModelNode("Qt/State", 4, 7);
+// ModelNode state3Node = view->createModelNode("QtQuick.State", 1, 1);
// QDeclarativeListReference changes(state1, "changes");
// QCOMPARE(changes.count(), 1);
// state3Node.nodeListProperty("changes").reparentHere(propertyChanges1Node);
@@ -4412,7 +4662,7 @@ void tst_TestCore::testInstancesStates()
// textNode.variantProperty("text").setValue("base state");
// // expressions
-// ModelNode textNode2 = view->createModelNode("Qt/Text", 4, 7);
+// ModelNode textNode2 = view->createModelNode("QtQuick.Text", 1, 1);
// textNode2.setId("targetObject2");
// textNode2.variantProperty("text").setValue("textNode2");
@@ -4472,7 +4722,7 @@ void tst_TestCore::testInstancesStates()
void tst_TestCore::testStates()
{
//
-// import Qt 4.7
+// import QtQuick 1.1
//
// Rectangle {
// Text {
@@ -4491,7 +4741,7 @@ void tst_TestCore::testStates()
// }
//
-// QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+// QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
// QVERIFY(model.data());
// QScopedPointer<TestView> view(new TestView(model.data()));
// QVERIFY(view.data());
@@ -4500,7 +4750,7 @@ void tst_TestCore::testStates()
// // build up model
// ModelNode rootNode = view->rootModelNode();
-// ModelNode textNode = view->createModelNode("Qt/Text", 4, 7);
+// ModelNode textNode = view->createModelNode("QtQuick.Text", 1, 1);
// textNode.setId("targetObject");
// textNode.variantProperty("text").setValue("base state");
@@ -4516,7 +4766,7 @@ void tst_TestCore::testStates()
// QVERIFY(textItem.isValid());
// QmlModelState state1(rootItem.states().addState("state 1")); //add state "state 1"
-// QCOMPARE(state1.modelNode().type(), QString("Qt/State"));
+// QCOMPARE(state1.modelNode().type(), QString("QtQuick.State"));
// QVERIFY(view->currentState().isBaseState());
@@ -4549,7 +4799,7 @@ void tst_TestCore::testStates()
// QCOMPARE(changes.modelNode().variantProperty("text").value(), QVariant("state 1"));
// QCOMPARE(changes.modelNode().bindingProperty("target").expression(), QString("targetObject"));
// QCOMPARE(changes.target(), textNode);
-// QCOMPARE(changes.modelNode().type(), QString("Qt/PropertyChanges"));
+// QCOMPARE(changes.modelNode().type(), QString("QtQuick.PropertyChanges"));
// QCOMPARE(changes.modelNode().parentProperty().name(), QString("changes"));
// QCOMPARE(changes.modelNode().parentProperty().parentModelNode(), state1.modelNode());
@@ -4568,7 +4818,7 @@ void tst_TestCore::testStates()
void tst_TestCore::testStatesBaseState()
{
//
-// import Qt 4.7
+// import QtQuick 1.1
//
// Rectangle {
// Text {
@@ -4587,7 +4837,7 @@ void tst_TestCore::testStatesBaseState()
// }
//
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
@@ -4596,7 +4846,7 @@ void tst_TestCore::testStatesBaseState()
// build up model
ModelNode rootNode = view->rootModelNode();
- ModelNode textNode = view->createModelNode("Qt/Text", 4, 7);
+ ModelNode textNode = view->createModelNode("QtQuick.Text", 1, 1);
textNode.setId("targetObject");
textNode.variantProperty("text").setValue("base state");
@@ -4612,17 +4862,19 @@ void tst_TestCore::testStatesBaseState()
QVERIFY(textItem.isValid());
QmlModelState state1(rootItem.states().addState("state 1")); //add state "state 1"
- QCOMPARE(state1.modelNode().type(), QString("Qt/State"));
+ QCOMPARE(state1.modelNode().type(), QString("QtQuick.State"));
QVERIFY(view->currentState().isBaseState());
view->setCurrentState(state1); //set currentState "state 1"
QCOMPARE(view->currentState(), state1);
+ QApplication::processEvents();
textItem.setVariantProperty("text", QVariant("state 1")); //set text in state !
QVERIFY(textItem.propertyAffectedByCurrentState("text"));
+ QApplication::processEvents();
QCOMPARE(textItem.instanceValue("text"), QVariant("state 1"));
- ModelNode newNode = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode newNode = view->createModelNode("QtQuick.Rectangle", 1, 0);
QVERIFY(!QmlObjectNode(newNode).currentState().isBaseState());
view->setCurrentState(view->baseState()); //set currentState base state
@@ -4644,13 +4896,13 @@ void tst_TestCore::testStatesBaseState()
void tst_TestCore::testInstancesIdResolution()
{
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- // import Qt 4.7
+ // import QtQuick 1.1
//
// Rectangle {
// id: root
@@ -4668,7 +4920,7 @@ void tst_TestCore::testInstancesIdResolution()
rootNode.variantProperty("width").setValue(100);
rootNode.variantProperty("height").setValue(100);
- ModelNode item1Node = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode item1Node = view->createModelNode("QtQuick.Rectangle", 1, 0);
item1Node.setId("item1");
item1Node.bindingProperty("width").setExpression("root.width");
item1Node.bindingProperty("height").setExpression("item2.height");
@@ -4688,7 +4940,7 @@ void tst_TestCore::testInstancesIdResolution()
// height: root.height
// }
- ModelNode item2Node = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode item2Node = view->createModelNode("QtQuick.Rectangle", 1, 0);
item2Node.setId("item2");
item2Node.bindingProperty("width").setExpression("root.width / 2");
item2Node.bindingProperty("height").setExpression("root.height");
@@ -4713,7 +4965,7 @@ void tst_TestCore::testInstancesIdResolution()
// height: 80
// }
- ModelNode item3Node = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode item3Node = view->createModelNode("QtQuick.Rectangle", 1, 0);
item3Node.setId("item3");
item3Node.variantProperty("height").setValue(80);
rootNode.nodeListProperty("data").reparentHere(item3Node);
@@ -4731,16 +4983,16 @@ void tst_TestCore::testInstancesNotInScene()
// test whether deleting an instance which is not in the scene crashes
//
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- ModelNode node1 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node1 = view->createModelNode("QtQuick.Item", 1, 1);
node1.setId("node1");
- ModelNode node2 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node2 = view->createModelNode("QtQuick.Item", 1, 1);
node2.setId("node2");
node1.nodeListProperty("children").reparentHere(node2);
@@ -4752,21 +5004,21 @@ void tst_TestCore::testInstancesBindingsInStatesStress()
{
//This is a stress test to provoke a crash
for (int j=0;j<20;j++) {
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- ModelNode node1 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node1 = view->createModelNode("QtQuick.Item", 1, 1);
node1.setId("node1");
view->rootModelNode().nodeListProperty("children").reparentHere(node1);
- ModelNode node2 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node2 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node2.setId("node2");
- ModelNode node3 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node3 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node3.setId("node3");
node1.nodeListProperty("children").reparentHere(node2);
@@ -4857,21 +5109,21 @@ void tst_TestCore::testInstancesPropertyChangeTargets()
//this tests checks if a change of the target of a CropertyChange
//node is handled correctly
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- ModelNode node1 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node1 = view->createModelNode("QtQuick.Item", 1, 1);
node1.setId("node1");
view->rootModelNode().nodeListProperty("children").reparentHere(node1);
- ModelNode node2 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node2 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node2.setId("node2");
- ModelNode node3 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node3 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node3.setId("node3");
node1.nodeListProperty("children").reparentHere(node2);
@@ -4963,21 +5215,21 @@ void tst_TestCore::testInstancesPropertyChangeTargets()
void tst_TestCore::testInstancesDeletePropertyChanges()
{
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
model->attachView(view.data());
- ModelNode node1 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node1 = view->createModelNode("QtQuick.Item", 1, 1);
node1.setId("node1");
view->rootModelNode().nodeListProperty("children").reparentHere(node1);
- ModelNode node2 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node2 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node2.setId("node2");
- ModelNode node3 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node3 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node3.setId("node3");
node1.nodeListProperty("children").reparentHere(node2);
@@ -5052,7 +5304,7 @@ void tst_TestCore::testInstancesDeletePropertyChanges()
void tst_TestCore::testInstancesChildrenLowLevel()
{
-// QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+// QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
// QVERIFY(model.data());
// QScopedPointer<NodeInstanceView> view(new NodeInstanceView);
@@ -5064,11 +5316,11 @@ void tst_TestCore::testInstancesChildrenLowLevel()
// rootModelNode.setId("rootModelNode");
-// ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Text", 4, 7, "data");
+// ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Text", 1, 1, "data");
// QVERIFY(childNode1.isValid());
// childNode1.setId("childNode1");
-// ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/TextEdit", 4, 7, "data");
+// ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.TextEdit", 1, 1, "data");
// QVERIFY(childNode2.isValid());
// childNode2.setId("childNode2");
@@ -5142,7 +5394,7 @@ void tst_TestCore::testInstancesChildrenLowLevel()
void tst_TestCore::testInstancesResourcesLowLevel()
{
-// QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+// QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
// QVERIFY(model.data());
// QScopedPointer<NodeInstanceView> view(new NodeInstanceView);
@@ -5154,15 +5406,15 @@ void tst_TestCore::testInstancesResourcesLowLevel()
// rootModelNode.setId("rootModelNode");
-// ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Text", 4, 7, "data");
+// ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Text", 1, 1, "data");
// QVERIFY(childNode1.isValid());
// childNode1.setId("childNode1");
-// ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/TextEdit", 4, 7, "data");
+// ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.TextEdit", 1, 1, "data");
// QVERIFY(childNode2.isValid());
// childNode2.setId("childNode2");
-// ModelNode listModel = addNodeListChild(rootModelNode, "Qt/ListModel", 4, 7, "data");
+// ModelNode listModel = addNodeListChild(rootModelNode, "QtQuick.ListModel", 1, 1, "data");
// QVERIFY(listModel.isValid());
// listModel.setId("listModel");
@@ -5241,7 +5493,7 @@ void tst_TestCore::testInstancesResourcesLowLevel()
// QCOMPARE(listReferenceData.at(1), child1Item);
// QCOMPARE(listReferenceData.at(2), child2Item);
-// ModelNode listModel2 = addNodeListChild(rootModelNode, "Qt/ListModel", 4, 7, "data");
+// ModelNode listModel2 = addNodeListChild(rootModelNode, "QtQuick.ListModel", 1, 1, "data");
// QVERIFY(listModel2.isValid());
// listModel2.setId("listModel2");
@@ -5289,7 +5541,7 @@ void tst_TestCore::testInstancesResourcesLowLevel()
void tst_TestCore::testInstancesFlickableLowLevel()
{
-// QScopedPointer<Model> model(Model::create("Qt/Flickable", 4, 7));
+// QScopedPointer<Model> model(createModel("QtQuick.Flickable", 1, 1));
// QVERIFY(model.data());
// QScopedPointer<NodeInstanceView> view(new NodeInstanceView);
@@ -5301,15 +5553,15 @@ void tst_TestCore::testInstancesFlickableLowLevel()
// rootModelNode.setId("rootModelNode");
-// ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Text", 4, 7, "flickableData");
+// ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Text", 1, 1, "flickableData");
// QVERIFY(childNode1.isValid());
// childNode1.setId("childNode1");
-// ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/TextEdit", 4, 7, "flickableData");
+// ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.TextEdit", 1, 1, "flickableData");
// QVERIFY(childNode2.isValid());
// childNode2.setId("childNode2");
-// ModelNode listModel = addNodeListChild(rootModelNode, "Qt/ListModel", 4, 7, "flickableData");
+// ModelNode listModel = addNodeListChild(rootModelNode, "QtQuick.ListModel", 1, 1, "flickableData");
// QVERIFY(listModel.isValid());
// listModel.setId("listModel");
@@ -5377,7 +5629,7 @@ void tst_TestCore::testInstancesFlickableLowLevel()
void tst_TestCore::testInstancesReorderChildrenLowLevel()
{
-// QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+// QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
// QVERIFY(model.data());
// QScopedPointer<NodeInstanceView> view(new NodeInstanceView);
@@ -5389,23 +5641,23 @@ void tst_TestCore::testInstancesReorderChildrenLowLevel()
// rootModelNode.setId("rootModelNode");
-// ModelNode childNode1 = addNodeListChild(rootModelNode, "Qt/Text", 4, 7, "data");
+// ModelNode childNode1 = addNodeListChild(rootModelNode, "QtQuick.Text", 1, 1, "data");
// QVERIFY(childNode1.isValid());
// childNode1.setId("childNode1");
-// ModelNode childNode2 = addNodeListChild(rootModelNode, "Qt/TextEdit", 4, 7, "data");
+// ModelNode childNode2 = addNodeListChild(rootModelNode, "QtQuick.TextEdit", 1, 1, "data");
// QVERIFY(childNode2.isValid());
// childNode2.setId("childNode2");
-// ModelNode listModel = addNodeListChild(rootModelNode, "Qt/ListModel", 4, 7, "data");
+// ModelNode listModel = addNodeListChild(rootModelNode, "QtQuick.ListModel", 1, 1, "data");
// QVERIFY(listModel.isValid());
// listModel.setId("listModel");
-// ModelNode childNode3 = addNodeListChild(rootModelNode, "Qt/TextEdit", 4, 7, "data");
+// ModelNode childNode3 = addNodeListChild(rootModelNode, "QtQuick.TextEdit", 1, 1, "data");
// QVERIFY(childNode3.isValid());
// childNode3.setId("childNode3");
-// ModelNode childNode4 = addNodeListChild(rootModelNode, "Qt/TextEdit", 4, 7, "data");
+// ModelNode childNode4 = addNodeListChild(rootModelNode, "QtQuick.TextEdit", 1, 1, "data");
// QVERIFY(childNode4.isValid());
// childNode4.setId("childNode4");
@@ -5476,7 +5728,7 @@ void tst_TestCore::testInstancesReorderChildrenLowLevel()
void tst_TestCore::testQmlModelStatesInvalidForRemovedNodes()
{
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -5493,11 +5745,11 @@ void tst_TestCore::testQmlModelStatesInvalidForRemovedNodes()
QVERIFY(state1.isValid());
QCOMPARE(state1.name(), QString("state1"));
- ModelNode childNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(childNode.isValid());
childNode.setId("childNode");
- ModelNode subChildNode = addNodeListChild(childNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode subChildNode = addNodeListChild(childNode, "QtQuick.Rectangle", 1, 0, "data");
QVERIFY(subChildNode.isValid());
subChildNode.setId("subChildNode");
@@ -5517,7 +5769,7 @@ void tst_TestCore::testInstancesAttachToExistingModel()
// Test attaching nodeinstanceview to an existing model
//
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -5525,7 +5777,7 @@ void tst_TestCore::testInstancesAttachToExistingModel()
model->attachView(view.data());
ModelNode rootNode = view->rootModelNode();
- ModelNode rectangleNode = addNodeListChild(rootNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode rectangleNode = addNodeListChild(rootNode, "QtQuick.Rectangle", 1, 0, "data");
rectangleNode.variantProperty("width").setValue(100);
@@ -5534,7 +5786,7 @@ void tst_TestCore::testInstancesAttachToExistingModel()
// Attach NodeInstanceView
- QScopedPointer<NodeInstanceView> instanceView(new NodeInstanceView);
+ QScopedPointer<NodeInstanceView> instanceView(new NodeInstanceView(0, NodeInstanceServerInterface::TestModus));
QVERIFY(instanceView.data());
model->attachView(instanceView.data());
@@ -5549,7 +5801,7 @@ void tst_TestCore::testInstancesAttachToExistingModel()
void tst_TestCore::testQmlModelAddMultipleStates()
{
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -5580,7 +5832,7 @@ void tst_TestCore::testQmlModelAddMultipleStates()
void tst_TestCore::testQmlModelRemoveStates()
{
- QScopedPointer<Model> model(Model::create("Qt/Rectangle", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle", 1, 1));
QScopedPointer<TestView> view(new TestView(model.data()));
QVERIFY(view.data());
@@ -5610,10 +5862,10 @@ void tst_TestCore::testQmlModelRemoveStates()
void tst_TestCore::testQmlModelStateWithName()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Rectangle { id: theRect; width: 100; states: [ State { name: \"a\"; PropertyChanges { target: theRect; width: 200; } } ] }\n");
+ textEdit1.setPlainText("import QtQuick 1.1; Rectangle { id: theRect; width: 100; states: [ State { name: \"a\"; PropertyChanges { target: theRect; width: 200; } } ] }\n");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
TestRewriterView *testRewriterView1 = new TestRewriterView(model1.data());
testRewriterView1->setTextModifier(&modifier1);
@@ -5635,7 +5887,7 @@ void tst_TestCore::testQmlModelStateWithName()
view->setCurrentState(rootNode.states().allStates().at(0));
rootNode.setVariantProperty("width", 112);
- const QLatin1String expected1("import Qt 4.7; Rectangle { id: theRect; width: 100; states: [ State { name: \"a\"; PropertyChanges { target: theRect; width: 112 } } ] }\n");
+ const QLatin1String expected1("import QtQuick 1.1; Rectangle { id: theRect; width: 100; states: [ State { name: \"a\"; PropertyChanges { target: theRect; width: 112 } } ] }\n");
QCOMPARE(textEdit1.toPlainText(), expected1);
QVERIFY(!rootNode.isInBaseState());
@@ -5655,10 +5907,10 @@ void tst_TestCore::testQmlModelStateWithName()
void tst_TestCore::testRewriterAutomaticSemicolonAfterChangedProperty()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Rectangle {\n width: 640\n height: 480\n}\n");
+ textEdit1.setPlainText("import QtQuick 1.1; Rectangle {\n width: 640\n height: 480\n}\n");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
TestRewriterView *testRewriterView1 = new TestRewriterView(model1.data());
testRewriterView1->setTextModifier(&modifier1);
@@ -5675,7 +5927,7 @@ void tst_TestCore::testRewriterAutomaticSemicolonAfterChangedProperty()
void tst_TestCore::defaultPropertyValues()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -5685,12 +5937,12 @@ void tst_TestCore::defaultPropertyValues()
QCOMPARE(view->rootModelNode().variantProperty("x").value().toDouble(), 0.0);
QCOMPARE(view->rootModelNode().variantProperty("width").value().toDouble(), 0.0);
- ModelNode rectNode(addNodeListChild(view->rootModelNode(), "Qt/Rectangle", 4, 7, "data"));
+ ModelNode rectNode(addNodeListChild(view->rootModelNode(), "QtQuick.Rectangle", 1, 0, "data"));
QCOMPARE(rectNode.variantProperty("y").value().toDouble(), 0.0);
QCOMPARE(rectNode.variantProperty("width").value().toDouble(), 0.0);
- ModelNode imageNode(addNodeListChild(view->rootModelNode(), "Qt/Image", 4, 7, "data"));
+ ModelNode imageNode(addNodeListChild(view->rootModelNode(), "QtQuick.Image", 1, 0, "data"));
QCOMPARE(imageNode.variantProperty("y").value().toDouble(), 0.0);
QCOMPARE(imageNode.variantProperty("width").value().toDouble(), 0.0);
@@ -5699,10 +5951,10 @@ void tst_TestCore::defaultPropertyValues()
void tst_TestCore::testModelPropertyValueTypes()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Rectangle { width: 100; radius: 1.5; color: \"red\"; }");
+ textEdit1.setPlainText("import QtQuick 1.1; Rectangle { width: 100; radius: 1.5; color: \"red\"; }");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model1(Model::create("Qt/Item"));
+ QScopedPointer<Model> model1(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -5720,7 +5972,7 @@ void tst_TestCore::testModelPropertyValueTypes()
void tst_TestCore::testModelNodeInHierarchy()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -5728,9 +5980,9 @@ void tst_TestCore::testModelNodeInHierarchy()
model->attachView(view.data());
QVERIFY(view->rootModelNode().isInHierarchy());
- ModelNode node1 = addNodeListChild(view->rootModelNode(), "Qt/Item", 4, 7, "data");
+ ModelNode node1 = addNodeListChild(view->rootModelNode(), "QtQuick.Item", 1, 1, "data");
QVERIFY(node1.isInHierarchy());
- ModelNode node2 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node2 = view->createModelNode("QtQuick.Item", 1, 1);
QVERIFY(!node2.isInHierarchy());
node2.nodeListProperty("data").reparentHere(node1);
QVERIFY(!node2.isInHierarchy());
@@ -5741,11 +5993,11 @@ void tst_TestCore::testModelNodeInHierarchy()
void tst_TestCore::testModelNodeIsAncestorOf()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
//
- // import Qt 4.7
+ // import QtQuick 1.1
// Item {
// Item {
// id: item2
@@ -5763,11 +6015,11 @@ void tst_TestCore::testModelNodeIsAncestorOf()
model->attachView(view.data());
view->rootModelNode().setId("item1");
- ModelNode item2 = addNodeListChild(view->rootModelNode(), "Qt/Item", 4, 7, "data");
+ ModelNode item2 = addNodeListChild(view->rootModelNode(), "QtQuick.Item", 1, 1, "data");
item2.setId("item2");
- ModelNode item3 = addNodeListChild(view->rootModelNode(), "Qt/Item", 4, 7, "data");
+ ModelNode item3 = addNodeListChild(view->rootModelNode(), "QtQuick.Item", 1, 1, "data");
item3.setId("item3");
- ModelNode item4 = addNodeListChild(item3, "Qt/Item", 4, 7, "data");
+ ModelNode item4 = addNodeListChild(item3, "QtQuick.Item", 1, 1, "data");
item4.setId("item4");
QVERIFY(view->rootModelNode().isAncestorOf(item2));
@@ -5780,8 +6032,7 @@ void tst_TestCore::testModelNodeIsAncestorOf()
void tst_TestCore::testModelDefaultProperties()
{
- QSKIP("Fix metainfo", SkipAll);
- QScopedPointer<Model> model(Model::create("Qt/Rectangle"));
+ QScopedPointer<Model> model(createModel("QtQuick.Rectangle"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -5797,10 +6048,10 @@ void tst_TestCore::testModelDefaultProperties()
void tst_TestCore::loadAnchors()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item { width: 100; height: 100; Rectangle { anchors.left: parent.left; anchors.horizontalCenter: parent.horizontalCenter; anchors.rightMargin: 20; }}");
+ textEdit1.setPlainText("import QtQuick 1.1; Item { width: 100; height: 100; Rectangle { anchors.left: parent.left; anchors.horizontalCenter: parent.horizontalCenter; anchors.rightMargin: 20; }}");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -5836,10 +6087,10 @@ void tst_TestCore::loadAnchors()
void tst_TestCore::changeAnchors()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item { width: 100; height: 100; Rectangle { anchors.left: parent.left; anchors.horizontalCenter: parent.horizontalCenter; anchors.rightMargin: 20; }}");
+ textEdit1.setPlainText("import QtQuick 1.1; Item { width: 100; height: 100; Rectangle { anchors.left: parent.left; anchors.horizontalCenter: parent.horizontalCenter; anchors.rightMargin: 20; }}");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -5897,10 +6148,10 @@ void tst_TestCore::changeAnchors()
void tst_TestCore::anchorToSibling()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item { Rectangle {} Rectangle { id: secondChild } }");
+ textEdit1.setPlainText("import QtQuick 1.1; Item { Rectangle {} Rectangle { id: secondChild } }");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -5941,10 +6192,10 @@ void tst_TestCore::anchorToSibling()
void tst_TestCore::removeFillAnchorByDetaching()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item { width: 100; height: 100; Rectangle { id: child; anchors.fill: parent } }");
+ textEdit1.setPlainText("import QtQuick 1.1; Item { width: 100; height: 100; Rectangle { id: child; anchors.fill: parent } }");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -6021,10 +6272,10 @@ void tst_TestCore::removeFillAnchorByDetaching()
void tst_TestCore::removeFillAnchorByChanging()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item { width: 100; height: 100; Rectangle { id: child; anchors.fill: parent } }");
+ textEdit1.setPlainText("import QtQuick 1.1; Item { width: 100; height: 100; Rectangle { id: child; anchors.fill: parent } }");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -6101,7 +6352,7 @@ void tst_TestCore::removeFillAnchorByChanging()
void tst_TestCore::testModelBindings()
{
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(createModel("QtQuick.Item", 1, 1));
QVERIFY(model.data());
NodeInstanceView *nodeInstanceView = new NodeInstanceView(model.data(), NodeInstanceServerInterface::TestModus);
@@ -6111,9 +6362,9 @@ void tst_TestCore::testModelBindings()
QCOMPARE(rootModelNode.allDirectSubModelNodes().count(), 0);
NodeInstance rootInstance = nodeInstanceView->instanceForNode(rootModelNode);
- // default width/height is forced to 100
- QCOMPARE(rootInstance.size().width(), 100.0);
- QCOMPARE(rootInstance.size().height(), 100.0);
+ // default width/height is 0
+ QCOMPARE(rootInstance.size().width(), 0.0);
+ QCOMPARE(rootInstance.size().height(), 0.0);
rootModelNode.variantProperty("width") = 200;
rootModelNode.variantProperty("height") = 100;
@@ -6121,7 +6372,7 @@ void tst_TestCore::testModelBindings()
QCOMPARE(rootInstance.size().width(), 200.0);
QCOMPARE(rootInstance.size().height(), 100.0);
- ModelNode childNode = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode childNode = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
childNode.variantProperty("width") = 100;
childNode.variantProperty("height") = 100;
@@ -6159,7 +6410,8 @@ void tst_TestCore::testModelBindings()
void tst_TestCore::testModelDynamicProperties()
{
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ MSKIP_ALL("Fix rewriter dynamic properties writing");
+ QScopedPointer<Model> model(createModel("QtQuick.Item", 1, 1));
QVERIFY(model.data());
TestView *testView = new TestView(model.data());
@@ -6169,15 +6421,15 @@ void tst_TestCore::testModelDynamicProperties()
ModelNode rootModelNode = rootQmlItemNode.modelNode();
rootModelNode.variantProperty("x") = 10;
- rootModelNode.variantProperty("myDouble") = qMakePair(QString("real"), QVariant(10));
- rootModelNode.variantProperty("myColor").setDynamicTypeNameAndValue("color", Qt::red);
+ rootModelNode.variantProperty("myColor").setDynamicTypeNameAndValue("color", QVariant(QColor(Qt::red)));
+ rootModelNode.variantProperty("myDouble").setDynamicTypeNameAndValue("real", 10);
QVERIFY(!rootModelNode.property("x").isDynamic());
QVERIFY(rootModelNode.property("myColor").isDynamic());
QVERIFY(rootModelNode.property("myDouble").isDynamic());
QCOMPARE(rootModelNode.property("myColor").dynamicTypeName(), QString("color"));
- QCOMPARE(rootModelNode.variantProperty("myColor").value(), QVariant(Qt::red));
+ QCOMPARE(rootModelNode.variantProperty("myColor").value(), QVariant(QColor(Qt::red)));
//QCOMPARE(rootQmlItemNode.instanceValue("myColor"), QVariant(Qt::red)); //not working yet
QCOMPARE(rootModelNode.property("myDouble").dynamicTypeName(), QString("real"));
QCOMPARE(rootModelNode.variantProperty("myDouble").value(), QVariant(10));
@@ -6203,7 +6455,7 @@ void tst_TestCore::testModelDynamicProperties()
void tst_TestCore::testModelSliding()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6212,10 +6464,10 @@ void tst_TestCore::testModelSliding()
ModelNode rootModelNode(view->rootModelNode());
- ModelNode rect00(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
- ModelNode rect01(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
- ModelNode rect02(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
- ModelNode rect03(addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data"));
+ ModelNode rect00(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
+ ModelNode rect01(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
+ ModelNode rect02(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
+ ModelNode rect03(addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data"));
QVERIFY(rect00.isValid());
QVERIFY(rect01.isValid());
@@ -6271,13 +6523,13 @@ void tst_TestCore::testModelSliding()
void tst_TestCore::testRewriterChangeId()
{
- const char* qmlString = "import Qt 4.7\nRectangle { }";
+ const char* qmlString = "import QtQuick 1.1\nRectangle { }";
QPlainTextEdit textEdit;
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6296,25 +6548,25 @@ void tst_TestCore::testRewriterChangeId()
QCOMPARE(rootModelNode.id(), QString("rectId"));
- QString expected = "import Qt 4.7\n"
+ QString expected = "import QtQuick 1.1\n"
"Rectangle { id: rectId }";
QCOMPARE(textEdit.toPlainText(), expected);
// change id for node outside of hierarchy
- ModelNode node = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node = view->createModelNode("QtQuick.Item", 1, 1);
node.setId("myId");
}
void tst_TestCore::testRewriterRemoveId()
{
- const char* qmlString = "import Qt 4.7\nRectangle { id: rect }";
+ const char* qmlString = "import QtQuick 1.1\nRectangle { id: rect }";
QPlainTextEdit textEdit;
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6332,7 +6584,7 @@ void tst_TestCore::testRewriterRemoveId()
//
// remove id in text
//
- const char* qmlString2 = "import Qt 4.7\nRectangle { }";
+ const char* qmlString2 = "import QtQuick 1.1\nRectangle { }";
textEdit.setPlainText(qmlString2);
QCOMPARE(rootModelNode.id(), QString());
@@ -6340,13 +6592,13 @@ void tst_TestCore::testRewriterRemoveId()
void tst_TestCore::testRewriterChangeValueProperty()
{
- const char* qmlString = "import Qt 4.7\nRectangle { x: 10; y: 10 }";
+ const char* qmlString = "import QtQuick 1.1\nRectangle { x: 10; y: 10 }";
QPlainTextEdit textEdit;
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6369,14 +6621,14 @@ void tst_TestCore::testRewriterChangeValueProperty()
// change property for node outside of hierarchy
PropertyListType properties;
properties.append(QPair<QString,QVariant>("x", 10));
- ModelNode node = view->createModelNode("Qt/Item", 4, 7, properties);
+ ModelNode node = view->createModelNode("QtQuick.Item", 1, 1, properties);
node.variantProperty("x").setValue(20);
}
void tst_TestCore::testRewriterRemoveValueProperty()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"Rectangle {\n"
" x: 10\n"
" y: 10;\n"
@@ -6386,7 +6638,7 @@ void tst_TestCore::testRewriterRemoveValueProperty()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6407,7 +6659,7 @@ void tst_TestCore::testRewriterRemoveValueProperty()
rootModelNode.removeProperty("x");
const QLatin1String expected("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"Rectangle {\n"
" y: 10;\n"
"}\n");
@@ -6416,19 +6668,19 @@ void tst_TestCore::testRewriterRemoveValueProperty()
// remove property for node outside of hierarchy
PropertyListType properties;
properties.append(QPair<QString,QVariant>("x", 10));
- ModelNode node = view->createModelNode("Qt/Item", 4, 7, properties);
+ ModelNode node = view->createModelNode("QtQuick.Item", 1, 1, properties);
node.removeProperty("x");
}
void tst_TestCore::testRewriterSignalProperty()
{
- const char* qmlString = "import Qt 4.7\nRectangle { onColorChanged: {} }";
+ const char* qmlString = "import QtQuick 1.1\nRectangle { onColorChanged: {} }";
QPlainTextEdit textEdit;
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6448,13 +6700,13 @@ void tst_TestCore::testRewriterSignalProperty()
void tst_TestCore::testRewriterObjectTypeProperty()
{
- const char* qmlString = "import Qt 4.7\nRectangle { x: 10; y: 10 }";
+ const char* qmlString = "import QtQuick 1.1\nRectangle { x: 10; y: 10 }";
QPlainTextEdit textEdit;
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6468,11 +6720,11 @@ void tst_TestCore::testRewriterObjectTypeProperty()
ModelNode rootModelNode(view->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QLatin1String("QtQuick.Rectangle"));
- view->changeRootNodeType(QLatin1String("Qt/Text"), 4, 7);
+ view->changeRootNodeType(QLatin1String("QtQuick.Text"), 1, 1);
- QCOMPARE(rootModelNode.type(), QLatin1String("Qt/Text"));
+ QCOMPARE(rootModelNode.type(), QLatin1String("QtQuick.Text"));
}
void tst_TestCore::testRewriterPropertyChanges()
@@ -6482,7 +6734,7 @@ void tst_TestCore::testRewriterPropertyChanges()
// Use a slightly more complicated example so that target properties are not resolved in default scope
const char* qmlString
- = "import Qt 4.7\n"
+ = "import QtQuick 1.1\n"
"Rectangle {\n"
" Text {\n"
" id: targetObj\n"
@@ -6502,7 +6754,7 @@ void tst_TestCore::testRewriterPropertyChanges()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6515,7 +6767,7 @@ void tst_TestCore::testRewriterPropertyChanges()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
QVERIFY(rootNode.propertyNames().contains(QLatin1String("data")));
QVERIFY(rootNode.propertyNames().contains(QLatin1String("states")));
QCOMPARE(rootNode.propertyNames().count(), 2);
@@ -6526,7 +6778,7 @@ void tst_TestCore::testRewriterPropertyChanges()
ModelNode stateNode = statesProperty.toModelNodeList().first();
QVERIFY(stateNode.isValid());
- QCOMPARE(stateNode.type(), QString("Qt/State"));
+ QCOMPARE(stateNode.type(), QString("QtQuick.State"));
QCOMPARE(stateNode.propertyNames(), QStringList("changes"));
NodeListProperty stateChangesProperty = stateNode.property("changes").toNodeListProperty();
@@ -6549,17 +6801,17 @@ void tst_TestCore::testRewriterPropertyChanges()
void tst_TestCore::testRewriterListModel()
{
- QSKIP("See BAUHAUS-157", SkipAll);
+ MSKIP_ALL("See BAUHAUS-157");
try {
// ListModel uses a custom parser
- const char* qmlString = "import Qt 4.7; ListModel {\n ListElement {\n age: 12\n} \n}";
+ const char* qmlString = "import QtQuick 1.1; ListModel {\n ListElement {\n age: 12\n} \n}";
QPlainTextEdit textEdit;
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -6588,7 +6840,7 @@ void tst_TestCore::testRewriterListModel()
void tst_TestCore::testRewriterAddProperty()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -6596,7 +6848,7 @@ void tst_TestCore::testRewriterAddProperty()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6609,7 +6861,7 @@ void tst_TestCore::testRewriterAddProperty()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
rootNode.variantProperty(QLatin1String("x")).setValue(123);
@@ -6618,7 +6870,7 @@ void tst_TestCore::testRewriterAddProperty()
QCOMPARE(rootNode.variantProperty(QLatin1String("x")).value(), QVariant(123));
const QLatin1String expected("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"x: 123\n"
@@ -6629,7 +6881,7 @@ void tst_TestCore::testRewriterAddProperty()
void tst_TestCore::testRewriterAddPropertyInNestedObject()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Rectangle {\n"
@@ -6640,7 +6892,7 @@ void tst_TestCore::testRewriterAddPropertyInNestedObject()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6653,18 +6905,18 @@ void tst_TestCore::testRewriterAddPropertyInNestedObject()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
ModelNode childNode = rootNode.nodeListProperty(QLatin1String("data")).toModelNodeList().at(0);
QVERIFY(childNode.isValid());
- QCOMPARE(childNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(childNode.type(), QLatin1String("QtQuick.Rectangle"));
QCOMPARE(childNode.id(), QLatin1String("rectangle1"));
childNode.variantProperty(QLatin1String("x")).setValue(10);
childNode.variantProperty(QLatin1String("y")).setValue(10);
const QLatin1String expected("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Rectangle {\n"
@@ -6678,7 +6930,7 @@ void tst_TestCore::testRewriterAddPropertyInNestedObject()
void tst_TestCore::testRewriterAddObjectDefinition()
{
- const QLatin1String qmlString("import Qt 4.7\n"
+ const QLatin1String qmlString("import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -6686,7 +6938,7 @@ void tst_TestCore::testRewriterAddObjectDefinition()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6699,20 +6951,20 @@ void tst_TestCore::testRewriterAddObjectDefinition()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
- ModelNode childNode = view->createModelNode("Qt/MouseArea", 4, 7);
+ ModelNode childNode = view->createModelNode("QtQuick.MouseArea", 1, 1);
rootNode.nodeAbstractProperty(QLatin1String("data")).reparentHere(childNode);
QCOMPARE(rootNode.nodeProperty(QLatin1String("data")).toNodeListProperty().toModelNodeList().size(), 1);
childNode = rootNode.nodeProperty(QLatin1String("data")).toNodeListProperty().toModelNodeList().at(0);
- QCOMPARE(childNode.type(), QString(QLatin1String("Qt/MouseArea")));
+ QCOMPARE(childNode.type(), QString(QLatin1String("QtQuick.MouseArea")));
}
void tst_TestCore::testRewriterAddStatesArray()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -6720,7 +6972,7 @@ void tst_TestCore::testRewriterAddStatesArray()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6732,13 +6984,13 @@ void tst_TestCore::testRewriterAddStatesArray()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
- ModelNode stateNode = view->createModelNode("Qt/State", 4, 7);
+ ModelNode stateNode = view->createModelNode("QtQuick.State", 1, 0);
rootNode.nodeListProperty(QLatin1String("states")).reparentHere(stateNode);
const QString expected1 = QLatin1String("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"states: [\n"
@@ -6748,11 +7000,11 @@ void tst_TestCore::testRewriterAddStatesArray()
"}");
QCOMPARE(textEdit.toPlainText(), expected1);
- ModelNode stateNode2 = view->createModelNode("Qt/State", 4, 7);
+ ModelNode stateNode2 = view->createModelNode("QtQuick.State", 1, 0);
rootNode.nodeListProperty(QLatin1String("states")).reparentHere(stateNode2);
const QString expected2 = QLatin1String("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"states: [\n"
@@ -6768,7 +7020,7 @@ void tst_TestCore::testRewriterAddStatesArray()
void tst_TestCore::testRewriterRemoveStates()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" states: [\n"
@@ -6782,7 +7034,7 @@ void tst_TestCore::testRewriterRemoveStates()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6794,7 +7046,7 @@ void tst_TestCore::testRewriterRemoveStates()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
NodeListProperty statesProperty = rootNode.nodeListProperty(QLatin1String("states"));
QVERIFY(statesProperty.isValid());
@@ -6804,7 +7056,7 @@ void tst_TestCore::testRewriterRemoveStates()
state.destroy();
const QLatin1String expected1("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" states: [\n"
@@ -6818,7 +7070,7 @@ void tst_TestCore::testRewriterRemoveStates()
state.destroy();
const QLatin1String expected2("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -6828,7 +7080,7 @@ void tst_TestCore::testRewriterRemoveStates()
void tst_TestCore::testRewriterRemoveObjectDefinition()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" MouseArea {\n"
@@ -6840,7 +7092,7 @@ void tst_TestCore::testRewriterRemoveObjectDefinition()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6853,24 +7105,24 @@ void tst_TestCore::testRewriterRemoveObjectDefinition()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
QCOMPARE(rootNode.nodeProperty(QLatin1String("data")).toNodeListProperty().toModelNodeList().size(), 2);
ModelNode childNode = rootNode.nodeProperty(QLatin1String("data")).toNodeListProperty().toModelNodeList().at(1);
- QCOMPARE(childNode.type(), QString(QLatin1String("Qt/MouseArea")));
+ QCOMPARE(childNode.type(), QString(QLatin1String("QtQuick.MouseArea")));
childNode.destroy();
QCOMPARE(rootNode.nodeProperty(QLatin1String("data")).toNodeListProperty().toModelNodeList().size(), 1);
childNode = rootNode.nodeProperty(QLatin1String("data")).toNodeListProperty().toModelNodeList().at(0);
- QCOMPARE(childNode.type(), QString(QLatin1String("Qt/MouseArea")));
+ QCOMPARE(childNode.type(), QString(QLatin1String("QtQuick.MouseArea")));
childNode.destroy();
QVERIFY(!rootNode.hasProperty(QLatin1String("data")));
const QString expected = QLatin1String("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" // some comment here\n"
@@ -6878,9 +7130,9 @@ void tst_TestCore::testRewriterRemoveObjectDefinition()
QCOMPARE(textEdit.toPlainText(), expected);
// don't crash when deleting nodes not in any hierarchy
- ModelNode node1 = view->createModelNode("Qt/Rectangle", 4, 7);
- ModelNode node2 = addNodeListChild(node1, "Qt/Item", 4, 7, "data");
- ModelNode node3 = addNodeListChild(node2, "Qt/Item", 4, 7, "data");
+ ModelNode node1 = view->createModelNode("QtQuick.Rectangle", 1, 0);
+ ModelNode node2 = addNodeListChild(node1, "QtQuick.Item", 1, 1, "data");
+ ModelNode node3 = addNodeListChild(node2, "QtQuick.Item", 1, 1, "data");
node3.destroy();
node1.destroy();
@@ -6889,7 +7141,7 @@ void tst_TestCore::testRewriterRemoveObjectDefinition()
void tst_TestCore::testRewriterRemoveScriptBinding()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" x: 10; // some comment\n"
@@ -6899,7 +7151,7 @@ void tst_TestCore::testRewriterRemoveScriptBinding()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6912,7 +7164,7 @@ void tst_TestCore::testRewriterRemoveScriptBinding()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
QCOMPARE(rootNode.properties().size(), 2);
QVERIFY(rootNode.hasProperty(QLatin1String("x")));
@@ -6929,7 +7181,7 @@ void tst_TestCore::testRewriterRemoveScriptBinding()
QCOMPARE(rootNode.properties().size(), 0);
const QString expected = QLatin1String("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" // some comment\n"
@@ -6940,7 +7192,7 @@ void tst_TestCore::testRewriterRemoveScriptBinding()
void tst_TestCore::testRewriterNodeReparenting()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -6952,7 +7204,7 @@ void tst_TestCore::testRewriterNodeReparenting()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -6965,15 +7217,15 @@ void tst_TestCore::testRewriterNodeReparenting()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
ModelNode itemNode = rootNode.nodeListProperty("data").toModelNodeList().at(0);
QVERIFY(itemNode.isValid());
- QCOMPARE(itemNode.type(), QLatin1String("Qt/Item"));
+ QCOMPARE(itemNode.type(), QLatin1String("QtQuick.Item"));
ModelNode mouseArea = itemNode.nodeListProperty("data").toModelNodeList().at(0);
QVERIFY(mouseArea.isValid());
- QCOMPARE(mouseArea.type(), QLatin1String("Qt/MouseArea"));
+ QCOMPARE(mouseArea.type(), QLatin1String("QtQuick.MouseArea"));
rootNode.nodeListProperty("data").reparentHere(mouseArea);
@@ -6981,7 +7233,7 @@ void tst_TestCore::testRewriterNodeReparenting()
QCOMPARE(rootNode.nodeListProperty("data").toModelNodeList().size(), 2);
QString expected = "\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -6993,9 +7245,9 @@ void tst_TestCore::testRewriterNodeReparenting()
QCOMPARE(textEdit.toPlainText(), expected);
// reparenting outside of the hierarchy
- ModelNode node1 = view->createModelNode("Qt/Rectangle", 4, 7);
- ModelNode node2 = view->createModelNode("Qt/Item", 4, 7);
- ModelNode node3 = view->createModelNode("Qt/Item", 4, 7);
+ ModelNode node1 = view->createModelNode("QtQuick.Rectangle", 1, 0);
+ ModelNode node2 = view->createModelNode("QtQuick.Item", 1, 1);
+ ModelNode node3 = view->createModelNode("QtQuick.Item", 1, 1);
node2.nodeListProperty("data").reparentHere(node3);
node1.nodeListProperty("data").reparentHere(node2);
@@ -7003,7 +7255,7 @@ void tst_TestCore::testRewriterNodeReparenting()
rootNode.nodeListProperty("data").reparentHere(node1);
expected = "\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -7023,11 +7275,11 @@ void tst_TestCore::testRewriterNodeReparenting()
QCOMPARE(textEdit.toPlainText(), expected);
// reparent out of the hierarchy
- ModelNode node4 = view->createModelNode("Qt/Rectangle", 4, 7);
+ ModelNode node4 = view->createModelNode("QtQuick.Rectangle", 1, 0);
node4.nodeListProperty("data").reparentHere(node1);
expected = "\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -7043,7 +7295,7 @@ void tst_TestCore::testRewriterNodeReparenting()
void tst_TestCore::testRewriterNodeReparentingWithTransaction()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: rootItem\n"
@@ -7060,7 +7312,7 @@ void tst_TestCore::testRewriterNodeReparentingWithTransaction()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -7073,17 +7325,17 @@ void tst_TestCore::testRewriterNodeReparentingWithTransaction()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QLatin1String("QtQuick.Rectangle"));
QCOMPARE(rootNode.id(), QLatin1String("rootItem"));
ModelNode item1Node = rootNode.nodeListProperty("data").toModelNodeList().at(0);
QVERIFY(item1Node.isValid());
- QCOMPARE(item1Node.type(), QLatin1String("Qt/Item"));
+ QCOMPARE(item1Node.type(), QLatin1String("QtQuick.Item"));
QCOMPARE(item1Node.id(), QLatin1String("firstItem"));
ModelNode item2Node = rootNode.nodeListProperty("data").toModelNodeList().at(1);
QVERIFY(item2Node.isValid());
- QCOMPARE(item2Node.type(), QLatin1String("Qt/Item"));
+ QCOMPARE(item2Node.type(), QLatin1String("QtQuick.Item"));
QCOMPARE(item2Node.id(), QLatin1String("secondItem"));
RewriterTransaction transaction = testRewriterView->beginRewriterTransaction();
@@ -7094,7 +7346,7 @@ void tst_TestCore::testRewriterNodeReparentingWithTransaction()
transaction.commit();
const QLatin1String expected("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" id: rootItem\n"
@@ -7113,7 +7365,7 @@ void tst_TestCore::testRewriterNodeReparentingWithTransaction()
void tst_TestCore::testRewriterMovingInOut()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -7121,7 +7373,7 @@ void tst_TestCore::testRewriterMovingInOut()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -7134,13 +7386,13 @@ void tst_TestCore::testRewriterMovingInOut()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
- ModelNode newNode = view->createModelNode("Qt/MouseArea", 4, 7);
+ ModelNode newNode = view->createModelNode("QtQuick.MouseArea", 1, 1);
rootNode.nodeListProperty(QLatin1String("data")).reparentHere(newNode);
const QLatin1String expected1("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"MouseArea {\n"
@@ -7159,17 +7411,19 @@ void tst_TestCore::testRewriterMovingInOut()
newNode.destroy();
const QLatin1String expected2("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
QCOMPARE(textEdit.toPlainText(), expected2);
+
+ QApplication::processEvents();
}
void tst_TestCore::testRewriterMovingInOutWithTransaction()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
@@ -7177,7 +7431,7 @@ void tst_TestCore::testRewriterMovingInOutWithTransaction()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -7190,11 +7444,11 @@ void tst_TestCore::testRewriterMovingInOutWithTransaction()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
RewriterTransaction transaction = view->beginRewriterTransaction();
- ModelNode newNode = view->createModelNode("Qt/MouseArea", 4, 7);
+ ModelNode newNode = view->createModelNode("QtQuick.MouseArea", 1, 1);
rootNode.nodeListProperty(QLatin1String("data")).reparentHere(newNode);
#define move(node, x, y) {\
@@ -7210,17 +7464,18 @@ void tst_TestCore::testRewriterMovingInOutWithTransaction()
transaction.commit();
const QLatin1String expected2("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
"}");
QCOMPARE(textEdit.toPlainText(), expected2);
+ QApplication::processEvents();
}
void tst_TestCore::testRewriterComplexMovingInOut()
{
const QLatin1String qmlString("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -7230,7 +7485,7 @@ void tst_TestCore::testRewriterComplexMovingInOut()
textEdit.setPlainText(qmlString);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -7243,14 +7498,14 @@ void tst_TestCore::testRewriterComplexMovingInOut()
ModelNode rootNode = view->rootModelNode();
QVERIFY(rootNode.isValid());
- QCOMPARE(rootNode.type(), QString("Qt/Rectangle"));
+ QCOMPARE(rootNode.type(), QString("QtQuick.Rectangle"));
ModelNode itemNode = rootNode.nodeListProperty(QLatin1String("data")).toModelNodeList().at(0);
- ModelNode newNode = view->createModelNode("Qt/MouseArea", 4, 7);
+ ModelNode newNode = view->createModelNode("QtQuick.MouseArea", 1, 1);
rootNode.nodeListProperty(QLatin1String("data")).reparentHere(newNode);
const QLatin1String expected1("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -7270,7 +7525,7 @@ void tst_TestCore::testRewriterComplexMovingInOut()
move(newNode, 3, 3);
const QLatin1String expected2("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -7286,7 +7541,7 @@ void tst_TestCore::testRewriterComplexMovingInOut()
itemNode.nodeListProperty(QLatin1String("data")).reparentHere(newNode);
const QLatin1String expected3("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
@@ -7306,22 +7561,23 @@ void tst_TestCore::testRewriterComplexMovingInOut()
newNode.destroy();
const QLatin1String expected4("\n"
- "import Qt 4.7\n"
+ "import QtQuick 1.1\n"
"\n"
"Rectangle {\n"
" Item {\n"
" }\n"
"}");
QCOMPARE(textEdit.toPlainText(), expected4);
+ QApplication::processEvents();
}
void tst_TestCore::removeCenteredInAnchorByDetaching()
{
QPlainTextEdit textEdit1;
- textEdit1.setPlainText("import Qt 4.7; Item { Rectangle { id: child; anchors.centerIn: parent } }");
+ textEdit1.setPlainText("import QtQuick 1.1; Item { Rectangle { id: child; anchors.centerIn: parent } }");
NotIndentingTextEditModifier modifier1(&textEdit1);
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item"));
QScopedPointer<TestRewriterView> testRewriterView1(new TestRewriterView());
testRewriterView1->setTextModifier(&modifier1);
@@ -7372,7 +7628,7 @@ void tst_TestCore::removeCenteredInAnchorByDetaching()
void tst_TestCore::changePropertyBinding()
{
- QScopedPointer<Model> model(Model::create("Qt/Item"));
+ QScopedPointer<Model> model(createModel("QtQuick.Item"));
QVERIFY(model.data());
QScopedPointer<TestView> view(new TestView(model.data()));
@@ -7381,7 +7637,7 @@ void tst_TestCore::changePropertyBinding()
ModelNode rootModelNode(view->rootModelNode());
rootModelNode.variantProperty("width") = 20;
- ModelNode firstChild = addNodeListChild(rootModelNode, "Qt/Rectangle", 4, 7, "data");
+ ModelNode firstChild = addNodeListChild(rootModelNode, "QtQuick.Rectangle", 1, 0, "data");
firstChild.bindingProperty("width").setExpression(QString("parent.width"));
firstChild.variantProperty("height")= 10;
QVERIFY(firstChild.isValid());
@@ -7421,7 +7677,7 @@ void tst_TestCore::loadTestFiles()
textEdit.setPlainText(QString(file.readAll()));
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -7432,7 +7688,7 @@ void tst_TestCore::loadTestFiles()
QVERIFY(model.data());
ModelNode rootModelNode(testRewriterView->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QLatin1String("Qt/Item"));
+ QCOMPARE(rootModelNode.type(), QLatin1String("QtQuick.Item"));
QVERIFY(rootModelNode.allDirectSubModelNodes().isEmpty());
}
@@ -7444,7 +7700,7 @@ void tst_TestCore::loadTestFiles()
textEdit.setPlainText(QString(file.readAll()));
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -7455,14 +7711,14 @@ void tst_TestCore::loadTestFiles()
QVERIFY(model.data());
ModelNode rootModelNode(testRewriterView->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QLatin1String("QtQuick.Rectangle"));
QCOMPARE(rootModelNode.allDirectSubModelNodes().count(), 1);
QCOMPARE(rootModelNode.variantProperty("width").value().toInt(), 200);
QCOMPARE(rootModelNode.variantProperty("height").value().toInt(), 200);
ModelNode textNode(rootModelNode.allDirectSubModelNodes().first());
QVERIFY(textNode.isValid());
- QCOMPARE(textNode.type(), QLatin1String("Qt/Text"));
+ QCOMPARE(textNode.type(), QLatin1String("QtQuick.Text"));
QCOMPARE(textNode.variantProperty("x").value().toInt(), 66);
QCOMPARE(textNode.variantProperty("y").value().toInt(), 93);
}
@@ -7474,7 +7730,7 @@ void tst_TestCore::loadTestFiles()
textEdit.setPlainText(QString(file.readAll()));
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -7485,7 +7741,7 @@ void tst_TestCore::loadTestFiles()
QVERIFY(model.data());
ModelNode rootModelNode(testRewriterView->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QLatin1String("QtQuick.Rectangle"));
QCOMPARE(rootModelNode.allDirectSubModelNodes().count(), 4);
QCOMPARE(rootModelNode.variantProperty("width").value().toInt(), 200);
QCOMPARE(rootModelNode.variantProperty("height").value().toInt(), 200);
@@ -7496,14 +7752,14 @@ void tst_TestCore::loadTestFiles()
ModelNode textNode(rootModelNode.nodeListProperty("data").toModelNodeList().first());
QVERIFY(textNode.isValid());
QCOMPARE(textNode.id(), QLatin1String("text"));
- QCOMPARE(textNode.type(), QLatin1String("Qt/Text"));
+ QCOMPARE(textNode.type(), QLatin1String("QtQuick.Text"));
QCOMPARE(textNode.variantProperty("x").value().toInt(), 66);
QCOMPARE(textNode.variantProperty("y").value().toInt(), 93);
ModelNode imageNode(rootModelNode.nodeListProperty("data").toModelNodeList().last());
QVERIFY(imageNode.isValid());
QCOMPARE(imageNode.id(), QLatin1String("image1"));
- QCOMPARE(imageNode.type(), QLatin1String("Qt/Image"));
+ QCOMPARE(imageNode.type(), QLatin1String("QtQuick.Image"));
QCOMPARE(imageNode.variantProperty("x").value().toInt(), 41);
QCOMPARE(imageNode.variantProperty("y").value().toInt(), 46);
QCOMPARE(imageNode.variantProperty("source").value().toUrl(), QUrl("images/qtcreator.png"));
@@ -7514,7 +7770,7 @@ void tst_TestCore::loadTestFiles()
QCOMPARE(rootModelNode.nodeListProperty("states").toModelNodeList().count(), 2);
}
- QSKIP("Fails because the text editor model doesn't know about components", SkipAll);
+ MSKIP_ALL("Fails because the text editor model doesn't know about components");
{ //usingbutton.qml
QFile file(":/fx/usingbutton.qml");
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
@@ -7523,7 +7779,7 @@ void tst_TestCore::loadTestFiles()
textEdit.setPlainText(QString(file.readAll()));
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -7535,12 +7791,12 @@ void tst_TestCore::loadTestFiles()
QVERIFY(model.data());
ModelNode rootModelNode(testRewriterView->rootModelNode());
QVERIFY(rootModelNode.isValid());
- QCOMPARE(rootModelNode.type(), QLatin1String("Qt/Rectangle"));
+ QCOMPARE(rootModelNode.type(), QLatin1String("QtQuick.Rectangle"));
QVERIFY(!rootModelNode.allDirectSubModelNodes().isEmpty());
}
}
-static QString rectWithGradient = "import Qt 4.7\n"
+static QString rectWithGradient = "import QtQuick 1.1\n"
"Rectangle {\n"
" gradient: Gradient {\n"
" id: pGradient\n"
@@ -7560,7 +7816,7 @@ void tst_TestCore::loadGradient()
textEdit.setPlainText(rectWithGradient);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -7579,7 +7835,7 @@ void tst_TestCore::loadGradient()
QVERIFY(gradientProperty.isNodeProperty());
ModelNode gradientPropertyModelNode = gradientProperty.toNodeProperty().modelNode();
QVERIFY(gradientPropertyModelNode.isValid());
- QCOMPARE(gradientPropertyModelNode.type(), QString("Qt/Gradient"));
+ QCOMPARE(gradientPropertyModelNode.type(), QString("QtQuick.Gradient"));
QCOMPARE(gradientPropertyModelNode.allDirectSubModelNodes().size(), 2);
AbstractProperty stopsProperty = gradientPropertyModelNode.property("stops");
@@ -7592,7 +7848,7 @@ void tst_TestCore::loadGradient()
ModelNode pOne = stops.first();
ModelNode pTwo = stops.last();
- QCOMPARE(pOne.type(), QString("Qt/GradientStop"));
+ QCOMPARE(pOne.type(), QString("QtQuick.GradientStop"));
QCOMPARE(pOne.id(), QString("pOne"));
QCOMPARE(pOne.allDirectSubModelNodes().size(), 0);
QCOMPARE(pOne.propertyNames().size(), 2);
@@ -7601,7 +7857,7 @@ void tst_TestCore::loadGradient()
QCOMPARE(pOne.variantProperty("color").value().type(), QVariant::Color);
QCOMPARE(pOne.variantProperty("color").value().value<QColor>(), QColor("lightsteelblue"));
- QCOMPARE(pTwo.type(), QString("Qt/GradientStop"));
+ QCOMPARE(pTwo.type(), QString("QtQuick.GradientStop"));
QCOMPARE(pTwo.id(), QString("pTwo"));
QCOMPARE(pTwo.allDirectSubModelNodes().size(), 0);
QCOMPARE(pTwo.propertyNames().size(), 2);
@@ -7614,8 +7870,8 @@ void tst_TestCore::loadGradient()
{
ModelNode gradientNode = rootModelNode.allDirectSubModelNodes().last();
QVERIFY(gradientNode.isValid());
- QVERIFY(!gradientNode.metaInfo().isSubclassOf("Qt/Item", -1, -1));
- QCOMPARE(gradientNode.type(), QString("Qt/Gradient"));
+ QVERIFY(!gradientNode.metaInfo().isSubclassOf("QtQuick.Item", -1, -1));
+ QCOMPARE(gradientNode.type(), QString("QtQuick.Gradient"));
QCOMPARE(gradientNode.id(), QString("secondGradient"));
QCOMPARE(gradientNode.allDirectSubModelNodes().size(), 2);
@@ -7629,7 +7885,7 @@ void tst_TestCore::loadGradient()
ModelNode nOne = stops.first();
ModelNode nTwo = stops.last();
- QCOMPARE(nOne.type(), QString("Qt/GradientStop"));
+ QCOMPARE(nOne.type(), QString("QtQuick.GradientStop"));
QCOMPARE(nOne.id(), QString("nOne"));
QCOMPARE(nOne.allDirectSubModelNodes().size(), 0);
QCOMPARE(nOne.propertyNames().size(), 2);
@@ -7638,7 +7894,7 @@ void tst_TestCore::loadGradient()
QCOMPARE(nOne.variantProperty("color").value().type(), QVariant::Color);
QCOMPARE(nOne.variantProperty("color").value().value<QColor>(), QColor("blue"));
- QCOMPARE(nTwo.type(), QString("Qt/GradientStop"));
+ QCOMPARE(nTwo.type(), QString("QtQuick.GradientStop"));
QCOMPARE(nTwo.id(), QString("nTwo"));
QCOMPARE(nTwo.allDirectSubModelNodes().size(), 0);
QCOMPARE(nTwo.propertyNames().size(), 2);
@@ -7656,7 +7912,7 @@ void tst_TestCore::changeGradientId()
textEdit.setPlainText(rectWithGradient);
NotIndentingTextEditModifier textModifier(&textEdit);
- QScopedPointer<Model> model(Model::create("Qt/Item", 4, 7));
+ QScopedPointer<Model> model(Model::create("QtQuick.Item", 1, 1));
QVERIFY(model.data());
QScopedPointer<TestRewriterView> testRewriterView(new TestRewriterView());
@@ -7689,7 +7945,7 @@ void tst_TestCore::changeGradientId()
firstStop.destroy();
QVERIFY(!firstStop.isValid());
- ModelNode gradientStop = addNodeListChild(gradientNode, "Qt/GradientStop", 4, 7, "stops");
+ ModelNode gradientStop = addNodeListChild(gradientNode, "QtQuick.GradientStop", 1, 0, "stops");
gradientStop.variantProperty("position") = 0.5;
gradientStop.variantProperty("color") = QColor("yellow");
diff --git a/tests/auto/qml/qmldesigner/coretests/tst_testcore.h b/tests/auto/qml/qmldesigner/coretests/tst_testcore.h
index f8489ed54b..a8293a33ae 100644
--- a/tests/auto/qml/qmldesigner/coretests/tst_testcore.h
+++ b/tests/auto/qml/qmldesigner/coretests/tst_testcore.h
@@ -44,6 +44,10 @@ public:
private slots:
void initTestCase();
void cleanupTestCase();
+ void init();
+ void cleanup();
+
+
//
// unit tests MetaInfo, NodeMetaInfo, PropertyMetaInfo
@@ -57,7 +61,10 @@ private slots:
void testMetaInfoEnums();
void testMetaInfoProperties();
void testMetaInfoDotProperties();
+ void testMetaInfoQtQuick1Vs2();
void testMetaInfoListProperties();
+ void testQtQuick20Basic();
+ void testQtQuick20BasicRectangle();
//
// unit tests Model, ModelNode, NodeProperty, AbstractView
@@ -161,6 +168,7 @@ private slots:
// integration tests
//
void testBasicStates();
+ void testBasicStatesQtQuick20();
void testStates();
void testStatesBaseState();
void testStatesRewriter();
diff --git a/tests/auto/qml/qmldesigner/testview.cpp b/tests/auto/qml/qmldesigner/testview.cpp
index b4383ecb4c..b1d0aca75a 100644
--- a/tests/auto/qml/qmldesigner/testview.cpp
+++ b/tests/auto/qml/qmldesigner/testview.cpp
@@ -30,6 +30,7 @@
#include "testview.h"
#include <QDebug>
+#include <QUrl>
#include <qtestcase.h>
#include <abstractproperty.h>
#include <bindingproperty.h>
@@ -151,10 +152,10 @@ void TestView::nodeOrderChanged(const QmlDesigner::NodeListProperty &listPropert
m_methodCalls += MethodCall("nodeOrderChanged", QStringList() << listProperty.name() << movedNode.id() << QString::number(oldIndex));
}
-void TestView::stateChanged(const QmlDesigner::QmlModelState &newQmlModelState, const QmlDesigner::QmlModelState &oldQmlModelState)
+void TestView::actualStateChanged(const QmlDesigner::ModelNode &node)
{
- QmlDesigner::QmlModelView::stateChanged(newQmlModelState, oldQmlModelState);
- m_methodCalls += MethodCall("stateChanged", QStringList() << newQmlModelState.name() << oldQmlModelState.name());
+ QmlDesigner::QmlModelView::actualStateChanged(node);
+ m_methodCalls += MethodCall("actualStateChanged", QStringList() << node.id());
}
QList<TestView::MethodCall> &TestView::methodCalls()
diff --git a/tests/auto/qml/qmldesigner/testview.h b/tests/auto/qml/qmldesigner/testview.h
index 13033402a1..a377d38d92 100644
--- a/tests/auto/qml/qmldesigner/testview.h
+++ b/tests/auto/qml/qmldesigner/testview.h
@@ -72,8 +72,7 @@ public:
void nodeOrderChanged(const QmlDesigner::NodeListProperty &listProperty, const QmlDesigner::ModelNode &movedNode, int oldIndex);
- void stateChanged(const QmlDesigner::QmlModelState &newQmlModelState, const QmlDesigner::QmlModelState &oldQmlModelState);
-
+ void actualStateChanged(const QmlDesigner::ModelNode &node);
QList<MethodCall> &methodCalls();
QString lastFunction() const;
diff --git a/tests/auto/qml/qmleditor/qmlcodeformatter/tst_qmlcodeformatter.cpp b/tests/auto/qml/qmleditor/qmlcodeformatter/tst_qmlcodeformatter.cpp
index 338015b9c1..d5358c3f61 100644
--- a/tests/auto/qml/qmleditor/qmlcodeformatter/tst_qmlcodeformatter.cpp
+++ b/tests/auto/qml/qmleditor/qmlcodeformatter/tst_qmlcodeformatter.cpp
@@ -75,7 +75,8 @@ private Q_SLOTS:
void ifStatementWithBraces3();
void ifStatementMixed();
void ifStatementAndComments();
- void ifStatementLongCondition();
+ void ifStatementLongCondition1();
+ void ifStatementLongCondition2();
void moreIfThenElse();
void strayElse();
void oneLineIf();
@@ -941,7 +942,7 @@ void tst_QMLCodeFormatter::ifStatementAndComments()
checkIndent(data);
}
-void tst_QMLCodeFormatter::ifStatementLongCondition()
+void tst_QMLCodeFormatter::ifStatementLongCondition1()
{
QList<Line> data;
data << Line("Rectangle {")
@@ -958,6 +959,23 @@ void tst_QMLCodeFormatter::ifStatementLongCondition()
checkIndent(data);
}
+void tst_QMLCodeFormatter::ifStatementLongCondition2()
+{
+ QList<Line> data;
+ data << Line("function test() {")
+ << Line(" if (foo(function() {")
+ << Line(" if (xx) {")
+ << Line(" yy = yy - 1")
+ << Line(" } else {")
+ << Line(" yy = yy + 1")
+ << Line(" }")
+ << Line(" })) {")
+ << Line(" zz = !zz")
+ << Line(" }")
+ << Line("}");
+ checkIndent(data);
+}
+
void tst_QMLCodeFormatter::strayElse()
{
QList<Line> data;
@@ -1572,7 +1590,7 @@ void tst_QMLCodeFormatter::bug3()
checkIndent(data);
}
-QTEST_APPLESS_MAIN(tst_QMLCodeFormatter)
+QTEST_MAIN(tst_QMLCodeFormatter)
#include "tst_qmlcodeformatter.moc"
diff --git a/tests/auto/qml/qmljssimplereader/qmljssimplereader.pro b/tests/auto/qml/qmljssimplereader/qmljssimplereader.pro
new file mode 100644
index 0000000000..20722acddf
--- /dev/null
+++ b/tests/auto/qml/qmljssimplereader/qmljssimplereader.pro
@@ -0,0 +1,12 @@
+include(../../qttest.pri)
+
+DEFINES+=QTCREATORDIR=\\\"$$IDE_SOURCE_TREE\\\"
+DEFINES+=TESTSRCDIR=\\\"$$PWD\\\"
+
+include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+include($$IDE_SOURCE_TREE/src/libs/qmljs/qmljs.pri)
+
+TARGET = tst_qmljssimplereader
+
+SOURCES += \
+ tst_qmljssimplereader.cpp
diff --git a/tests/auto/qml/qmljssimplereader/tst_qmljssimplereader.cpp b/tests/auto/qml/qmljssimplereader/tst_qmljssimplereader.cpp
new file mode 100644
index 0000000000..80972ca410
--- /dev/null
+++ b/tests/auto/qml/qmljssimplereader/tst_qmljssimplereader.cpp
@@ -0,0 +1,257 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+#include <qmljs/qmljssimplereader.h>
+
+#include <QtTest>
+#include <algorithm>
+
+using namespace QmlJS;
+
+class tst_SimpleReader : public QObject
+{
+ Q_OBJECT
+public:
+ tst_SimpleReader();
+
+private slots:
+ void testWellFormed();
+ void testIllFormed01();
+ void testIllFormed02();
+ void testArrays();
+ void testBug01();
+};
+
+tst_SimpleReader::tst_SimpleReader()
+{
+}
+
+void tst_SimpleReader::testWellFormed()
+{
+ char source[] = "RootNode {\n"
+ " ChildNode {\n"
+ " property01: 10\n"
+ " }\n"
+ " ChildNode {\n"
+ " propertyString: \"str\"\n"
+ " InnerChild {\n"
+ " test: \"test\"\n"
+ " }\n"
+ " }\n"
+ " propertyBlah: false\n"
+ "}\n";
+
+ QmlJS::SimpleReaderNode::WeakPtr weak01;
+ QmlJS::SimpleReaderNode::WeakPtr weak02;
+ {
+ QmlJS::SimpleReader reader;
+ QmlJS::SimpleReaderNode::Ptr rootNode = reader.readFromSource(source);
+ QVERIFY(reader.errors().isEmpty());
+ QVERIFY(rootNode);
+ QVERIFY(rootNode->isValid());
+ QCOMPARE(rootNode->name(), QLatin1String("RootNode"));
+
+ QCOMPARE(rootNode->children().count(), 2);
+ QCOMPARE(rootNode->properties().count(), 1);
+
+ QVERIFY(rootNode->properties().contains("propertyBlah"));
+ QCOMPARE(rootNode->property("property01").toBool(), false);
+
+ QVERIFY(rootNode->children().first()->isValid());
+ QVERIFY(!rootNode->children().first()->isRoot());
+
+ QVERIFY(rootNode->children().first()->properties().contains("property01"));
+ QCOMPARE(rootNode->children().first()->property("property01").toInt(), 10);
+
+ QmlJS::SimpleReaderNode::Ptr secondChild = rootNode->children().at(1);
+
+ QVERIFY(secondChild);
+ QVERIFY(secondChild->isValid());
+ QVERIFY(!secondChild->isRoot());
+ QCOMPARE(secondChild->name(), QLatin1String("ChildNode"));
+
+ QVERIFY(secondChild->properties().contains("propertyString"));
+ QCOMPARE(secondChild->property("propertyString").toString(), QLatin1String("str"));
+
+ QCOMPARE(secondChild->children().count(), 1);
+
+ QmlJS::SimpleReaderNode::Ptr innerChild = secondChild->children().first();
+
+ QVERIFY(innerChild);
+ QVERIFY(innerChild->isValid());
+ QVERIFY(!innerChild->isRoot());
+ QCOMPARE(innerChild->name(), QLatin1String("InnerChild"));
+
+ QVERIFY(innerChild->properties().contains("test"));
+ QCOMPARE(innerChild->property("test").toString(), QLatin1String("test"));
+
+ weak01 = rootNode;
+ weak02 = secondChild;
+ }
+
+ QVERIFY(!weak01);
+ QVERIFY(!weak02);
+}
+
+void tst_SimpleReader::testIllFormed01()
+{
+ char source[] = "RootNode {\n"
+ " ChildNode {\n"
+ " property01: 10\n"
+ " }\n"
+ " ChildNode {\n"
+ " propertyString: \"str\"\n"
+ " InnerChild \n" //missing {
+ " test: \"test\"\n"
+ " }\n"
+ " }\n"
+ " propertyBlah: false\n"
+ "}\n";
+ QmlJS::SimpleReader reader;
+ QmlJS::SimpleReaderNode::Ptr rootNode = reader.readFromSource(source);
+
+ QVERIFY(!rootNode);
+ QVERIFY(!reader.errors().empty());
+}
+
+void tst_SimpleReader::testIllFormed02()
+{
+ char source[] = "RootNode {\n"
+ " ChildNode {\n"
+ " property01: 10\n"
+ " property01: 20\n"
+ " }\n"
+ " ChildNode {\n"
+ " propertyString: \"str\"\n"
+ " InnerChild {\n"
+ " test: \"test\"\n"
+ " test: \"test2\"\n"
+ " }\n"
+ " }\n"
+ "}\n";
+
+ QmlJS::SimpleReader reader;
+ QmlJS::SimpleReaderNode::Ptr rootNode = reader.readFromSource(source);
+
+ QVERIFY(rootNode);
+ QVERIFY(rootNode->isValid());
+ QVERIFY(rootNode->isRoot());
+
+ QVERIFY(!reader.errors().empty());
+ QCOMPARE(reader.errors().count(), 2);
+
+ QmlJS::SimpleReaderNode::Ptr firstChild = rootNode->children().at(0);
+
+ QVERIFY(firstChild);
+ QVERIFY(firstChild->isValid());
+ QVERIFY(!firstChild->isRoot());
+
+ QCOMPARE(firstChild->properties().count(), 1);
+ QVERIFY(firstChild->properties().contains("property01"));
+ QCOMPARE(firstChild->property("property01").toString(), QLatin1String("20"));
+}
+
+void tst_SimpleReader::testArrays()
+{
+ char source[] = "RootNode {\n"
+ " propertyArray: [\"string01\", \"string02\" ]\n"
+ " ChildNode {\n"
+ " propertyArray: [\"string01\", \"string02\" ]\n"
+ " propertyArrayMixed: [\"string03\", [\"string01\", \"string02\"] ]\n"
+ " }\n"
+ "}\n";
+
+ QList<QVariant> variantList;
+ variantList << QVariant(QLatin1String("string01")) << QVariant(QLatin1String("string02"));
+ const QVariant variant = variantList;
+
+ QmlJS::SimpleReader reader;
+ QmlJS::SimpleReaderNode::Ptr rootNode = reader.readFromSource(source);
+
+ QVERIFY(rootNode);
+ QVERIFY(rootNode->isValid());
+ QVERIFY(rootNode->isRoot());
+
+ QCOMPARE(rootNode->property("propertyArray"), variant);
+
+
+ QmlJS::SimpleReaderNode::Ptr firstChild = rootNode->children().at(0);
+
+ QVERIFY(firstChild);
+ QVERIFY(firstChild->isValid());
+ QVERIFY(!firstChild->isRoot());
+ QCOMPARE(firstChild->property("propertyArray"), variant);
+
+ QList<QVariant> variantList2;
+ variantList2 << QVariant(QLatin1String("string03")) << variant;
+ const QVariant variant2 = variantList2;
+
+ QCOMPARE(firstChild->property("propertyArrayMixed"), variant2);
+}
+
+void tst_SimpleReader::testBug01()
+{
+ char source[] = "\n"
+ "AutoTypes {\n"
+ " imports: [ \"import HelperWidgets 1.0\", \"import QtQuick 1.0\", \"import Bauhaus 1.0\" ]\n"
+ " Type {\n"
+ " typeNames: [\"int\"]\n"
+ " sourceFile: \"IntEditorTemplate.qml\"\n"
+ " }\n"
+ " Type {\n"
+ " typeNames: [\"real\", \"double\", \"qreal\"]\n"
+ " sourceFile: \"RealEditorTemplate.qml\"\n"
+ " }\n"
+ " Type {\n"
+ " typeNames: [\"string\", \"QString\", \"QUrl\", \"url\"]\n"
+ " sourceFile: \"StringEditorTemplate.qml\"\n"
+ " }\n"
+ " Type {\n"
+ " typeNames: [\"bool\", \"boolean\"]\n"
+ " sourceFile: \"BooleanEditorTemplate.qml\"\n"
+ " }\n"
+ " Type {\n"
+ " typeNames: [\"color\", \"QColor\"]\n"
+ " sourceFile: \"ColorEditorTemplate.qml\"\n"
+ " }\n"
+ "}\n";
+
+ QmlJS::SimpleReader reader;
+ QmlJS::SimpleReaderNode::Ptr rootNode = reader.readFromSource(source);
+
+ QVERIFY(rootNode);
+ QVERIFY(rootNode->isValid());
+ QVERIFY(rootNode->isRoot());
+
+ QCOMPARE(rootNode->propertyNames().count(), 1);
+}
+
+QTEST_MAIN(tst_SimpleReader);
+
+#include "tst_qmljssimplereader.moc"
diff --git a/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.pro b/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.pro
index ec195534d9..639e7b7a04 100644
--- a/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.pro
+++ b/tests/auto/qml/qmlprojectmanager/fileformat/fileformat.pro
@@ -6,6 +6,7 @@ QT += script \
PLUGIN_DIR=../../../../../src/plugins/qmlprojectmanager
include($$PLUGIN_DIR/fileformat/fileformat.pri)
+include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
INCLUDEPATH += $$PLUGIN_DIR/fileformat
diff --git a/tests/auto/qttest.pri b/tests/auto/qttest.pri
index cc4ce6888c..83a24b73e1 100644
--- a/tests/auto/qttest.pri
+++ b/tests/auto/qttest.pri
@@ -6,6 +6,7 @@ QT += testlib
CONFIG += qt warn_on console depend_includepath testcase
CONFIG -= app_bundle
+DEFINES -= QT_NO_CAST_FROM_ASCII
# prefix test binary with tst_
!contains(TARGET, ^tst_.*):TARGET = $$join(TARGET,,"tst_")
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Frameworks b/tests/cppmodelmanager/testdata/frameworks/My.framework/Frameworks
new file mode 120000
index 0000000000..dc3d02e21f
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Frameworks
@@ -0,0 +1 @@
+Versions/A/Frameworks \ No newline at end of file
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Headers b/tests/cppmodelmanager/testdata/frameworks/My.framework/Headers
new file mode 120000
index 0000000000..d5ab97c5c7
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Headers
@@ -0,0 +1 @@
+Versions/A/Headers \ No newline at end of file
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Headers b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Headers
new file mode 120000
index 0000000000..a177d2a6b9
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Headers
@@ -0,0 +1 @@
+Versions/Current/Headers \ No newline at end of file
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/IncorrectVersion.h b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/IncorrectVersion.h
new file mode 100644
index 0000000000..8034d179c6
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/IncorrectVersion.h
@@ -0,0 +1,4 @@
+#ifndef IncorrectVersion_h
+#define IncorrectVersion_h
+
+#endif // IncorrectVersion_h
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/Nested.h b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/Nested.h
new file mode 100644
index 0000000000..fc0234ab64
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/A/Headers/Nested.h
@@ -0,0 +1,6 @@
+#ifndef Nested_h
+#define Nested_h
+
+#include "IncorrectVersion.h"
+
+#endif // Nested_h
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/CorrectVersion.h b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/CorrectVersion.h
new file mode 100644
index 0000000000..c4df20a40a
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/CorrectVersion.h
@@ -0,0 +1,4 @@
+#ifndef CorrectVersion_h
+#define CorrectVersion_h
+
+#endif // CorrectVersion_h
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/Nested.h b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/Nested.h
new file mode 100644
index 0000000000..79067d54e1
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/B/Headers/Nested.h
@@ -0,0 +1,6 @@
+#ifndef Nested_h
+#define Nested_h
+
+#include "CorrectVersion.h"
+
+#endif // Nested_h
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/Current b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/Current
new file mode 120000
index 0000000000..7371f47a6f
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Frameworks/Nested.framework/Versions/Current
@@ -0,0 +1 @@
+B \ No newline at end of file
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Headers/MyHeader.h b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Headers/MyHeader.h
new file mode 100644
index 0000000000..8ca3e6e88c
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/A/Headers/MyHeader.h
@@ -0,0 +1,6 @@
+#ifndef MyHeader_h
+#define MyHeader_h
+
+#include <Nested/Nested.h>
+
+#endif // MyHeader_h
diff --git a/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/Current b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/Current
new file mode 120000
index 0000000000..8c7e5a667f
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/frameworks/My.framework/Versions/Current
@@ -0,0 +1 @@
+A \ No newline at end of file
diff --git a/tests/cppmodelmanager/testdata/include/header.h b/tests/cppmodelmanager/testdata/include/header.h
new file mode 100644
index 0000000000..689ec03871
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/include/header.h
@@ -0,0 +1,4 @@
+#ifndef HEADER_H
+#define HEADER_H
+
+#endif // HEADER_H
diff --git a/tests/cppmodelmanager/testdata/sources/test_modelmanager_framework_headers.cpp b/tests/cppmodelmanager/testdata/sources/test_modelmanager_framework_headers.cpp
new file mode 100644
index 0000000000..27a6b5e518
--- /dev/null
+++ b/tests/cppmodelmanager/testdata/sources/test_modelmanager_framework_headers.cpp
@@ -0,0 +1,19 @@
+#include <My/MyHeader.h>
+
+#ifndef MyHeader_h
+bool failure_MyHeader_not_included;
+#endif
+
+#ifndef Nested_h
+bool failure_Nested_header_not_included;
+#endif
+
+#ifdef IncorrectVersion_h
+bool failure_Incorrect_version_of_nested_header_included;
+#endif
+
+#ifdef CorrectVersion_h
+bool success_is_the_only_option;
+#endif
+
+
diff --git a/tests/manual/appwizards/main.cpp b/tests/manual/appwizards/main.cpp
index 00afe96a42..0e9d40f6d6 100644
--- a/tests/manual/appwizards/main.cpp
+++ b/tests/manual/appwizards/main.cpp
@@ -71,26 +71,6 @@ int main(int argc, char *argv[])
}
{
- const QString rootPath = QLatin1String("../appwizards/qmlimportscenario_02/");
- QtQuickApp sAppImport02;
- sAppImport02.setProjectPath(projectPath);
- sAppImport02.setProjectName(QLatin1String("qml_imported_scenario_02"));
- sAppImport02.setMainQml(QtQuickApp::ModeImport, rootPath + QLatin1String("subfolder1/myqmlapp.qml"));
- QStringList moduleNames;
- moduleNames.append(QLatin1String("no.trolltech.QmlModule01"));
- moduleNames.append(QLatin1String("com.nokia.QmlModule02"));
- QStringList importPaths;
- importPaths.append(rootPath + QLatin1String("subfolder2/"));
- importPaths.append(rootPath + QLatin1String("subfolder3/"));
- if (!sAppImport02.setExternalModules(moduleNames, importPaths)) {
- qDebug() << sAppImport02.error();
- return 2;
- }
- if (!sAppImport02.generateFiles(&errorMessage))
- return 1;
- }
-
- {
Html5App sAppNew;
sAppNew.setProjectPath(projectPath);
sAppNew.setProjectName(QLatin1String("new_html5_app"));
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/apple.svg b/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/apple.svg
deleted file mode 100644
index 31288ecce4..0000000000
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/apple.svg
+++ /dev/null
@@ -1,16 +0,0 @@
-<svg height="100%" version="1.1" viewBox="0 0 50 50" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg">
- <defs>
- </defs>
- <metadata>
- <rdf:RDF>
- <cc:Work rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
- <dc:title/>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <path d="m22.7,3.84c-1.06,3.24-1.17,7.42-0.191,12.7" fill="none" stroke="#830" stroke-width="2.5"/>
- <path d="m36.8,12.9c6.24,3.02,11.1,9.74,10.3,16.9-0.548,5.22-3.35,10.1-7.3,13.5-3.99,2.83-7.36-0.79-11.9-0.037-4.75,0.587-8.68,3.8-13.3,1.88-8.57-3.18-12.1-6.91-12.2-16.4,0.0813-6.01,2.05-12,7.75-14.6,2.95-1.03,8.83-0.118,12,0.363,4.83-3.24,9.26-3.55,14.6-1.61z" fill="#3A0"/>
- <path d="m14,16.1c0.683,1.19-1.08,1.56-2.56,3.1-1.48,1.53-2.28,4.13-3.78,3.92-1.5-0.21-0.485-4.18,1.47-5.74,1.95-1.56,4.19-2.47,4.87-1.28z" fill="#FFF" opacity="0.5"/>
-</svg> \ No newline at end of file
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/qmldir b/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/qmldir
deleted file mode 100644
index 3a36c14330..0000000000
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder2/no/trolltech/QmlModule01/qmldir
+++ /dev/null
@@ -1 +0,0 @@
-QmlComponent01 1.0 QmlComponent01.qml \ No newline at end of file
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/qmldir b/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/qmldir
deleted file mode 100644
index 33f694a57e..0000000000
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/qmldir
+++ /dev/null
@@ -1 +0,0 @@
-QmlComponent02 1.0 QmlComponent02.qml \ No newline at end of file
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/tomato.svg b/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/tomato.svg
deleted file mode 100644
index c0df58c20b..0000000000
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder3/com/nokia/QmlModule02/tomato.svg
+++ /dev/null
@@ -1,16 +0,0 @@
-<svg height="100%" id="svg2" version="1.1" viewBox="0 0 50 50" width="100%" xmlns="http://www.w3.org/2000/svg" xmlns:cc="http://creativecommons.org/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg">
- <defs id="defs14">
- </defs>
- <metadata id="metadata4">
- <rdf:RDF>
- <cc:Work rdf:about="">
- <dc:format>image/svg+xml</dc:format>
- <dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
- <dc:title/>
- </cc:Work>
- </rdf:RDF>
- </metadata>
- <path d="M24.7,5.65c-2.7,2.23-3.2,5.65-2.2,10.8" fill="none" stroke="#080" stroke-width="2.5"/>
- <path d="m41.6,16.9c6.71,7.89,3.30,18.5-2.42,23.6-5.73,5.11-16.2,6.50-26.6,1.84-10.4-4.7-13.1-21.3-3.65-27,9.45-5.68,26-6.29,32.6,1.6z" fill="#F00"/>
- <path d="m15.6,15.3c0.683,1.19-1.88,1.16-4.97,4.10-2.95,2.8-2.64,6.7-4.14,6.5-1.50-0.2,0.72-7,2.67-8.5,1.95-1.56,5.80-3.27,6.48-2.08z" fill="#FFF" opacity="0.5"/>
-</svg> \ No newline at end of file
diff --git a/tests/manual/cplusplus-frontend/cplusplus-frontend.cpp b/tests/manual/cplusplus-frontend/cplusplus-frontend.cpp
index 531f493d3f..e964b78370 100644
--- a/tests/manual/cplusplus-frontend/cplusplus-frontend.cpp
+++ b/tests/manual/cplusplus-frontend/cplusplus-frontend.cpp
@@ -72,11 +72,11 @@ int main(int argc, char *argv[])
bool optionVerbose = false;
// Process options & arguments
- if (args.contains("-v")) {
+ if (args.contains(QLatin1String("-v"))) {
optionVerbose = true;
- args.removeOne("-v");
+ args.removeOne(QLatin1String("-v"));
}
- const bool helpRequested = args.contains("-h") || args.contains("-help");
+ const bool helpRequested = args.contains(QLatin1String("-h")) || args.contains(QLatin1String("-help"));
if (args.isEmpty() || helpRequested) {
printUsage();
return helpRequested ? EXIT_SUCCESS : EXIT_FAILURE;
diff --git a/tests/manual/debugger/simple/deep/deep/simple_test_app.h b/tests/manual/debugger/simple/deep/deep/simple_test_app.h
index 504dd15e47..820fe560c7 100644
--- a/tests/manual/debugger/simple/deep/deep/simple_test_app.h
+++ b/tests/manual/debugger/simple/deep/deep/simple_test_app.h
@@ -149,7 +149,7 @@ namespace breakpoints {
// <=== Break here.
Twice<int> cc = Twice<int>(1);
Twice<float> dd = Twice<float>(1.0);
- dummyStatement(&a, &b, &c, &d, &e, &f, &z, bb, aa, cc, dd);
+ dummyStatement(&a, &b, &c, &d, &e, &f, &z, &bb, &aa, &cc, &dd);
}
} // namespace breakpoints
diff --git a/tests/manual/debugger/simple/simple_test_app.cpp b/tests/manual/debugger/simple/simple_test_app.cpp
index 04c47d4b07..8a8c18a394 100644
--- a/tests/manual/debugger/simple/simple_test_app.cpp
+++ b/tests/manual/debugger/simple/simple_test_app.cpp
@@ -767,13 +767,23 @@ namespace qdir {
void testQDir()
{
+#ifdef Q_OS_WIN
+ QDir dir("C:\\Program Files");
+ dir.absolutePath(); // Keep in to facilitate stepping
+ BREAK_HERE;
+ // Check dir "C:/Program Files" QDir.
+ // Check dir.absolutePath "C:/Program Files" QString.
+ // Check dir.canonicalPath "C:/Program Files" QString.
+ // Continue.
+#else
QDir dir("/tmp");
- dir.absolutePath();
+ dir.absolutePath(); // Keep in to facilitate stepping
BREAK_HERE;
// Check dir "/tmp" QDir.
// Check dir.absolutePath "/tmp" QString.
// Check dir.canonicalPath "/tmp" QString.
// Continue.
+#endif
dummyStatement(&dir);
}
@@ -784,6 +794,18 @@ namespace qfileinfo {
void testQFileInfo()
{
+#ifdef Q_OS_WIN
+ QFile file("C:\\Program Files\\t");
+ file.setObjectName("A QFile instance");
+ QFileInfo fi("C:\\Program Files\\tt");
+ QString s = fi.absoluteFilePath();
+ BREAK_HERE;
+ // Check fi "C:/Program Files/tt" QFileInfo.
+ // Check file "C:\Program Files\t" QFile.
+ // Check s "C:/Program Files/tt" QString.
+ // Continue.
+ dummyStatement(&file, &s);
+#else
QFile file("/tmp/t");
file.setObjectName("A QFile instance");
QFileInfo fi("/tmp/tt");
@@ -794,6 +816,7 @@ namespace qfileinfo {
// Check s "/tmp/tt" QString.
// Continue.
dummyStatement(&file, &s);
+#endif
}
} // namespace qfileinfo
@@ -3451,7 +3474,11 @@ namespace stdstream {
BREAK_HERE;
// CheckType is std::ifstream.
// Continue.
+#ifdef Q_OS_WIN
+ is.open("C:\\Program Files\\Windows NT\\Accessories\\wordpad.exe");
+#else
is.open("/etc/passwd");
+#endif
BREAK_HERE;
// Continue.
bool ok = is.good();
@@ -3676,11 +3703,22 @@ namespace qstring {
dummyStatement(&str, &string, pstring);
}
+ void testQStringRef()
+ {
+ QString str = "Hello";
+ QStringRef ref(&str, 1, 2);
+ BREAK_HERE;
+ // Check ref "el" QStringRef.
+ // Continue.
+ dummyStatement(&str, &ref);
+ }
+
void testQString()
{
testQString1();
testQString2();
testQString3();
+ testQStringRef();
testQStringQuotes();
}
@@ -3823,6 +3861,24 @@ namespace text {
} // namespace text
+namespace qprocess {
+
+ void testQProcess()
+ {
+ return;
+ const int N = 14;
+ QProcess proc[N];
+ for (int i = 0; i != N; ++i) {
+ proc[i].start("sleep 10");
+ proc[i].waitForStarted();
+ }
+ BREAK_HERE;
+ dummyStatement(&proc);
+ }
+
+} // namespace qprocess
+
+
namespace qthread {
class Thread : public QThread
@@ -4191,11 +4247,13 @@ namespace qvector {
{
// This tests the display of a big vector.
QVector<int> vec(10000);
+ for (int i = 0; i != vec.size(); ++i)
+ vec[i] = i * i;
BREAK_HERE;
// Expand vec.
// Check vec <10000 items> QVector<int>.
// Check vec.0 0 int.
- // Check vec.1999 0 int.
+ // Check vec.1999 3996001 int.
// Continue.
// step over
@@ -4486,6 +4544,31 @@ namespace namespc {
} // namespace namespc
+namespace gccextensions {
+
+ void testGccExtensions()
+ {
+#ifdef __GNUC__
+ char v[8] = { 1, 2 };
+ char w __attribute__ ((vector_size (8))) = { 1, 2 };
+ int y[2] = { 1, 2 };
+ int z __attribute__ ((vector_size (8))) = { 1, 2 };
+ BREAK_HERE;
+ // Expand v.
+ // Check v.0 1 char.
+ // Check v.1 2 char.
+ // Check w.0 1 char.
+ // Check w.1 2 char.
+ // Check y.0 1 int.
+ // Check y.1 2 int.
+ // Check z.0 1 int.
+ // Check z.1 2 int.
+ // Continue.
+ dummyStatement(&v, &w, &y, &z);
+#endif
+ }
+
+} // namespace gccextension
class Z : public QObject
{
@@ -4519,6 +4602,32 @@ namespace basic {
// This tests display of basic types.
+ void testInt()
+ {
+ quint64 u64 = ULLONG_MAX;
+ qint64 s64 = LLONG_MAX;
+ quint32 u32 = ULONG_MAX;
+ qint32 s32 = LONG_MAX;
+ quint64 u64s = 0;
+ qint64 s64s = LLONG_MIN;
+ quint32 u32s = 0;
+ qint32 s32s = LONG_MIN;
+
+ BREAK_HERE;
+ // Check u64 18446744073709551615 quint64.
+ // Check s64 9223372036854775807 qint64.
+ // Check u32 4294967295 quint32.
+ // Check s32 2147483647 qint32.
+ // Check u64s 0 quint64.
+ // Check s64s -9223372036854775808 qint64.
+ // Check u32s 0 quint32.
+ // Check s32s -2147483648 qint32.
+ // Continue.
+
+ dummyStatement(&u64, &s64, &u32, &s32, &u64s, &s64s, &u32s, &s32s);
+ }
+
+
void testArray1()
{
double d[3][3];
@@ -5248,11 +5357,47 @@ namespace basic {
dummyStatement(&i, &b, &s);
}
+ #ifdef Q_COMPILER_RVALUE_REFS
+ struct X { X() : a(2), b(3) {} int a, b; };
+
+ X testRValueReferenceHelper1()
+ {
+ return X();
+ }
+
+ X testRValueReferenceHelper2(X &&x)
+ {
+ return x;
+ }
+
+ void testRValueReference()
+ {
+ X &&x1 = testRValueReferenceHelper1();
+ X &&x2 = testRValueReferenceHelper2(std::move(x1));
+ X &&x3 = testRValueReferenceHelper2(testRValueReferenceHelper1());
+
+ X y1 = testRValueReferenceHelper1();
+ X y2 = testRValueReferenceHelper2(std::move(y1));
+ X y3 = testRValueReferenceHelper2(testRValueReferenceHelper1());
+
+ BREAK_HERE;
+ // Continue.
+ dummyStatement(&x1, &x2, &x3, &y1, &y2, &y3);
+ }
+
+ #else
+
+ void testRValueReference() {}
+
+ #endif
+
void testBasic()
{
+ testInt();
testReference1();
testReference2();
testReference3("hello");
+ testRValueReference();
testDynamicReference();
testReturn();
testArray1();
@@ -5567,15 +5712,15 @@ namespace boost {
using namespace posix_time;
time_duration d1(1, 0, 0);
BREAK_HERE;
- // Check d1 01:00:00 boost::posix_time::time_duration.
+ // Check d1 01:00:00 boost::posix_time::time_duration.
// Continue.
time_duration d2(0, 1, 0);
BREAK_HERE;
- // Check d2 00:01:00 boost::posix_time::time_duration.
+ // Check d2 00:01:00 boost::posix_time::time_duration.
// Continue.
time_duration d3(0, 0, 1);
BREAK_HERE;
- // Check d3 00:00:01 boost::posix_time::time_duration.
+ // Check d3 00:00:01 boost::posix_time::time_duration.
// Continue.
dummyStatement(&d1, &d2, &d3);
}
@@ -5605,15 +5750,15 @@ namespace boost {
using namespace posix_time;
ptime p1(date(2002, 1, 10), time_duration(1, 0, 0));
BREAK_HERE;
- // Check p1 Thu Jan 10 01:00:00 2002 boost::posix_time::ptime.
+ // Check p1 Thu Jan 10 01:00:00 2002 boost::posix_time::ptime.
// Continue.
ptime p2(date(2002, 1, 10), time_duration(0, 0, 0));
BREAK_HERE;
- // Check p2 Thu Jan 10 00:00:00 2002 boost::posix_time::ptime.
+ // Check p2 Thu Jan 10 00:00:00 2002 boost::posix_time::ptime.
// Continue.
ptime p3(date(1970, 1, 1), time_duration(0, 0, 0));
BREAK_HERE;
- // Check p3 Thu Jan 1 00:00:00 1970 boost::posix_time::ptime.
+ // Check p3 Thu Jan 1 00:00:00 1970 boost::posix_time::ptime.
// Continue.
dummyStatement(&p1, &p2, &p3);
}
@@ -5832,14 +5977,14 @@ namespace bug3611 {
byte f = '2';
int *x = (int*)&f;
BREAK_HERE;
- // Check f 50 bug3611::byte.
+ // Check f 50 '2' bug3611::byte.
// Continue.
// Step.
f += 1;
f += 1;
f += 1;
BREAK_HERE;
- // Check f 53 bug3611::byte.
+ // Check f 53 '5' bug3611::byte.
// Continue.
dummyStatement(&f, &x);
}
@@ -6566,6 +6711,7 @@ int main(int argc, char *argv[])
// Check for normal dumpers.
basic::testBasic();
+ gccextensions::testGccExtensions();
qhostaddress::testQHostAddress();
varargs::testVaList();
@@ -6620,6 +6766,7 @@ int main(int argc, char *argv[])
qstringlist::testQStringList();
qstring::testQString();
qthread::testQThread();
+ qprocess::testQProcess();
qurl::testQUrl();
qvariant::testQVariant();
qvector::testQVector();
diff --git a/tests/manual/debugger/simple/simple_test_app.pro b/tests/manual/debugger/simple/simple_test_app.pro
index e7f85a4589..12a6cc4ec7 100644
--- a/tests/manual/debugger/simple/simple_test_app.pro
+++ b/tests/manual/debugger/simple/simple_test_app.pro
@@ -12,6 +12,9 @@ QT += xml
contains(QT_CONFIG, webkit) {
QT += webkit
+ greaterThan(QT_MAJOR_VERSION, 4) {
+ QT += webkitwidgets
+ }
}
greaterThan(QT_MAJOR_VERSION, 4) {
@@ -34,6 +37,11 @@ maemo5 {
INSTALLS += target
}
+#*g++* {
+# DEFINES += USE_CXX11
+# QMAKE_CXXFLAGS += -std=c++0x
+#}
+
exists($$QMAKE_INCDIR_QT/QtCore/private/qobject_p.h):DEFINES += USE_PRIVATE
exists(/usr/include/boost/optional.hpp): DEFINES += USE_BOOST
exists(/usr/include/eigen2/Eigen/Core): DEFINES += USE_EIGEN
diff --git a/tests/manual/preprocessor/main.cpp b/tests/manual/preprocessor/main.cpp
index c44e7c45eb..6bbbc9a6eb 100644
--- a/tests/manual/preprocessor/main.cpp
+++ b/tests/manual/preprocessor/main.cpp
@@ -97,14 +97,16 @@ public:
#endif
}
- virtual void passedMacroDefinitionCheck(unsigned, const Macro &)
+ virtual void passedMacroDefinitionCheck(unsigned, unsigned, const Macro &)
{ }
virtual void failedMacroDefinitionCheck(unsigned, const ByteArrayRef &)
{ }
- virtual void startExpandingMacro(unsigned, const Macro &,
- const ByteArrayRef &,
+ virtual void notifyMacroReference(unsigned, unsigned, const Macro &)
+ { }
+
+ virtual void startExpandingMacro(unsigned, unsigned, const Macro &,
const QVector<MacroArgumentReference> &)
{ }
@@ -116,6 +118,9 @@ public:
virtual void stopSkippingBlocks(unsigned)
{ }
+
+ virtual void sourceNeeded(unsigned, QString &, IncludeType)
+ { }
};
int make_depend(QCoreApplication *app);
diff --git a/tests/manual/preprocessor/preprocessor.pro b/tests/manual/preprocessor/preprocessor.pro
index 99d588dea4..9cb836d598 100644
--- a/tests/manual/preprocessor/preprocessor.pro
+++ b/tests/manual/preprocessor/preprocessor.pro
@@ -2,8 +2,10 @@ QT = core
macx:CONFIG -= app_bundle
TARGET = pp
-include(../../../qtcreator.pri)
+include(../../auto/qttest.pri)
+
include($$IDE_SOURCE_TREE/src/libs/cplusplus/cplusplus.pri)
+include($$IDE_SOURCE_TREE/src/libs/languageutils/languageutils.pri)
include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
include($$IDE_SOURCE_TREE/src/libs/3rdparty/botan/botan.pri)
diff --git a/tests/manual/proparser/main.cpp b/tests/manual/proparser/main.cpp
index 95c7f5585d..36ee676106 100644
--- a/tests/manual/proparser/main.cpp
+++ b/tests/manual/proparser/main.cpp
@@ -46,8 +46,10 @@ static void print(const QString &fileName, int lineNo, int type, const QString &
{
QString pfx = ((type & QMakeHandler::CategoryMask) == QMakeHandler::WarningMessage)
? QString::fromLatin1("WARNING: ") : QString();
- if (lineNo)
+ if (lineNo > 0)
qWarning("%s%s:%d: %s", qPrintable(pfx), qPrintable(fileName), lineNo, qPrintable(msg));
+ else if (lineNo)
+ qWarning("%s%s: %s", qPrintable(pfx), qPrintable(fileName), qPrintable(msg));
else
qWarning("%s%s", qPrintable(pfx), qPrintable(msg));
}
@@ -67,7 +69,7 @@ public:
static EvalHandler evalHandler;
static int evaluate(const QString &fileName, const QString &in_pwd, const QString &out_pwd,
- bool cumulative, QMakeGlobals *option, QMakeParser *parser, int level)
+ bool cumulative, ProFileGlobals *option, QMakeParser *parser, int level)
{
static QSet<QString> visited;
if (visited.contains(fileName))
@@ -140,30 +142,59 @@ int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
- QStringList args = app.arguments();
- args.removeFirst();
- int level = -1; // verbose
- if (args.count() && args.first() == QLatin1String("-v"))
- level = 0, args.removeFirst();
- if (args.count() < 2)
- qFatal("need at least two arguments: [-v] <cumulative?> <filenme> [<out_pwd> [<qmake options>]]");
-
- QMakeGlobals option;
+ ProFileGlobals option;
QString qmake = QString::fromLocal8Bit(qgetenv("TESTREADER_QMAKE"));
if (qmake.isEmpty())
qmake = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QLatin1String("/qmake");
option.qmake_abslocation = QDir::cleanPath(qmake);
option.initProperties();
- if (args.count() >= 4)
- option.setCommandLineArguments(args.mid(3));
- QMakeParser parser(0, &evalHandler);
- bool cumulative = args[0] == QLatin1String("true");
- QFileInfo infi(args[1]);
- QString file = infi.absoluteFilePath();
- QString in_pwd = infi.absolutePath();
- QString out_pwd = (args.count() > 2) ? QFileInfo(args[2]).absoluteFilePath() : in_pwd;
+ QStringList args = app.arguments();
+ args.removeFirst();
+ int level = -1; // verbose
+ bool cumulative = false;
+ QString file;
+ QString in_pwd;
+ QString out_pwd;
+ QMakeCmdLineParserState state(QDir::currentPath());
+ for (int pos = 0; ; ) {
+ QMakeGlobals::ArgumentReturn cmdRet = option.addCommandLineArguments(state, args, &pos);
+ if (cmdRet == QMakeGlobals::ArgumentsOk)
+ break;
+ if (cmdRet == QMakeGlobals::ArgumentMalformed) {
+ qCritical("argument %s needs a parameter", qPrintable(args.at(pos - 1)));
+ return 3;
+ }
+ Q_ASSERT(cmdRet == QMakeGlobals::ArgumentUnknown);
+ QString arg = args.at(pos++);
+ if (arg == QLatin1String("-v")) {
+ level = 0;
+ } else if (arg == QLatin1String("-d")) {
+ option.debugLevel++;
+ } else if (arg == QLatin1String("-c")) {
+ cumulative = true;
+ } else if (arg.startsWith(QLatin1Char('-'))) {
+ qCritical("unrecognized option %s", qPrintable(arg));
+ return 3;
+ } else if (file.isEmpty()) {
+ QFileInfo infi(arg);
+ file = QDir::cleanPath(infi.absoluteFilePath());
+ in_pwd = QDir::cleanPath(infi.absolutePath());
+ } else if (out_pwd.isEmpty()) {
+ out_pwd = QDir::cleanPath(QFileInfo(arg).absoluteFilePath());
+ } else {
+ qCritical("excess argument '%s'", qPrintable(arg));
+ return 3;
+ }
+ }
+ if (file.isEmpty()) {
+ qCritical("usage: testreader [-v] [-d [-d]] [-c] <filenme> [<out_pwd>] [<variable assignments>]");
+ return 3;
+ }
+ if (out_pwd.isEmpty())
+ out_pwd = in_pwd;
option.setDirectories(in_pwd, out_pwd);
+ QMakeParser parser(0, &evalHandler);
return evaluate(file, in_pwd, out_pwd, cumulative, &option, &parser, level);
}
diff --git a/tests/manual/qml/testfiles/subcomponent.qml b/tests/manual/qml/testfiles/subcomponent.qml
index 3b2d27d274..89a9d77512 100644
--- a/tests/manual/qml/testfiles/subcomponent.qml
+++ b/tests/manual/qml/testfiles/subcomponent.qml
@@ -30,8 +30,8 @@
import Qt 4.7
Rectangle {
- x: 640
- y: 480
+ width: 640
+ height: 480
Component {
id: redSquare
Rectangle {
diff --git a/tests/manual/qml/testfiles_quick2/components/MyButton.qml b/tests/manual/qml/testfiles_quick2/components/MyButton.qml
new file mode 100644
index 0000000000..0aa1b1b09e
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/components/MyButton.qml
@@ -0,0 +1,36 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 64
+ height: 48
+ color: "Red"
+}
diff --git a/tests/manual/qml/testfiles_quick2/empty.qml b/tests/manual/qml/testfiles_quick2/empty.qml
new file mode 100644
index 0000000000..35e165eb5d
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/empty.qml
@@ -0,0 +1,35 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 640
+ height: 480
+}
diff --git a/tests/manual/qml/testfiles_quick2/flipable.qml b/tests/manual/qml/testfiles_quick2/flipable.qml
new file mode 100644
index 0000000000..e841a33736
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/flipable.qml
@@ -0,0 +1,42 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Flipable {
+ width: 640
+ height: 480
+ front: Text {
+ text: "front"
+ }
+ back: Text {
+ text: "back"
+ }
+
+}
diff --git a/tests/manual/qml/testfiles_quick2/helloworld.qml b/tests/manual/qml/testfiles_quick2/helloworld.qml
new file mode 100644
index 0000000000..c1ab8bb3b1
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/helloworld.qml
@@ -0,0 +1,40 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 200
+ height: 200
+ Text {
+ x: 66
+ y: 93
+ text: "Hello World"
+ }
+}
diff --git a/tests/manual/qml/testfiles_quick2/helloworld_inverted.qml b/tests/manual/qml/testfiles_quick2/helloworld_inverted.qml
new file mode 100644
index 0000000000..90c741da41
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/helloworld_inverted.qml
@@ -0,0 +1,42 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 200
+ height: 200
+ color: "black"
+ Text {
+ x: 66
+ y: 93
+ text: "Hello World"
+ color: "white"
+ }
+}
diff --git a/tests/manual/qml/testfiles_quick2/images.qml b/tests/manual/qml/testfiles_quick2/images.qml
new file mode 100644
index 0000000000..8a45b2b173
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/images.qml
@@ -0,0 +1,56 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 640
+ height: 480
+
+ Image {
+ id: image1
+ x: 20
+ y: 18
+ source: "images/qtcreator.png"
+ }
+
+ Image {
+ id: image2
+ x: 327
+ y: 18
+ source: "images/qtcreator.jpg"
+ }
+
+ Image {
+ id: image3
+ x: 20
+ y: 288
+ source: "images/qtcreator.ico"
+ }
+}
diff --git a/tests/manual/qml/testfiles_quick2/images/qtcreator.ico b/tests/manual/qml/testfiles_quick2/images/qtcreator.ico
new file mode 100644
index 0000000000..6bca2585a6
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/images/qtcreator.ico
Binary files differ
diff --git a/tests/manual/qml/testfiles_quick2/images/qtcreator.jpg b/tests/manual/qml/testfiles_quick2/images/qtcreator.jpg
new file mode 100644
index 0000000000..d856c51b43
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/images/qtcreator.jpg
Binary files differ
diff --git a/tests/manual/qml/testfiles_quick2/images/qtcreator.png b/tests/manual/qml/testfiles_quick2/images/qtcreator.png
new file mode 100644
index 0000000000..1cf9f91170
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/images/qtcreator.png
Binary files differ
diff --git a/tests/manual/qml/testfiles_quick2/listmodel.qml b/tests/manual/qml/testfiles_quick2/listmodel.qml
new file mode 100644
index 0000000000..667b671dd5
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/listmodel.qml
@@ -0,0 +1,39 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+ListModel {
+ id: myModel
+ ListElement {
+ content: "foo"
+ text: "bar"
+ }
+
+}
diff --git a/tests/manual/qml/testfiles_quick2/listview.qml b/tests/manual/qml/testfiles_quick2/listview.qml
new file mode 100644
index 0000000000..f3cbeb2a84
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/listview.qml
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Item {
+ width: 200
+ height: 100
+
+ ListView {
+ anchors.fill: parent;
+ model: ListModel {
+ ListElement {
+ name: "BMW"
+ speed: 200
+ }
+ ListElement {
+ name: "Mercedes"
+ speed: 180
+ }
+ ListElement {
+ name: "Audi"
+ speed: 190
+ }
+ ListElement {
+ name: "VW"
+ speed: 180
+ }
+ }
+
+
+ delegate: Item {
+ height: 40
+ Row {
+ spacing: 10
+ Text {
+ text: name;
+ font.bold: true
+ }
+
+ Text { text: "speed: " + speed }
+ }
+
+
+ }
+ }
+}
diff --git a/tests/manual/qml/testfiles_quick2/positioners.qml b/tests/manual/qml/testfiles_quick2/positioners.qml
new file mode 100644
index 0000000000..c7abfd4ac8
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/positioners.qml
@@ -0,0 +1,209 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 232
+ height: 232
+
+ Column {
+ id: column
+ x: 39
+ y: 20
+ spacing: 2
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#c2d11b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#d11b1b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#1e3fd3"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#3bd527"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8726b7"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8b8b8b"
+ }
+ }
+
+ Row {
+ id: row
+ x: 78
+ y: 20
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#c2d11b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#d11b1b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#1e3fd3"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#3bd527"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8726b7"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8b8b8b"
+ }
+ spacing: 2
+ }
+
+ Flow {
+ id: flow
+ x: 78
+ y: 53
+ width: 84
+ height: 31
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#c2d11b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#d11b1b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#1e3fd3"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#3bd527"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8726b7"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8b8b8b"
+ }
+ spacing: 2
+ }
+
+ Grid {
+ id: grid
+ x: 78
+ y: 108
+ columns: 3
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#c2d11b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#d11b1b"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#1e3fd3"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#3bd527"
+ }
+
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8726b7"
+ }
+
+ spacing: 2
+ Rectangle {
+ width: 20
+ height: 20
+ color: "#8b8b8b"
+ }
+ }
+
+}
diff --git a/tests/manual/qml/testfiles_quick2/states.qml b/tests/manual/qml/testfiles_quick2/states.qml
new file mode 100644
index 0000000000..3b39eedb5a
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/states.qml
@@ -0,0 +1,73 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ id: rect
+ width: 200
+ height: 200
+ Text {
+ id: text
+ x: 66
+ y: 93
+ text: "Base State"
+ }
+ states: [
+ State {
+ name: "State1"
+ PropertyChanges {
+ target: rect
+ color: "blue"
+ }
+ PropertyChanges {
+ target: text
+ text: "State1"
+ }
+ },
+ State {
+ name: "State2"
+ PropertyChanges {
+ target: rect
+ color: "gray"
+ }
+ PropertyChanges {
+ target: text
+ text: "State2"
+ }
+ }
+ ]
+
+ Image {
+ id: image1
+ x: 41
+ y: 46
+ source: "images/qtcreator.png"
+ }
+}
diff --git a/tests/manual/appwizards/qmlimportscenario_02/subfolder1/myqmlapp.qml b/tests/manual/qml/testfiles_quick2/subcomponent.qml
index f454b2a6df..5586feb44a 100644
--- a/tests/manual/appwizards/qmlimportscenario_02/subfolder1/myqmlapp.qml
+++ b/tests/manual/qml/testfiles_quick2/subcomponent.qml
@@ -27,19 +27,20 @@
**
****************************************************************************/
-import QtQuick 1.0
+import QtQuick 2.0
Rectangle {
- width: 360
- height: 360
- Text {
- text: "Hello World"
- anchors.centerIn: parent
- }
- MouseArea {
- anchors.fill: parent
- onClicked: {
- Qt.quit();
+ width: 640
+ height: 480
+ Component {
+ id: redSquare
+ Rectangle {
+ color: "red"
+ width: 100
+ height: 100
}
}
+
+ Loader { sourceComponent: redSquare;}
+ Loader { sourceComponent: redSquare; x: 20 }
}
diff --git a/tests/manual/appwizards/qmlimportscenario_02/myqmlapp.qmlproject b/tests/manual/qml/testfiles_quick2/testfiles_quick2.qmlproject
index 1040b01e31..337caca3fe 100644
--- a/tests/manual/appwizards/qmlimportscenario_02/myqmlapp.qmlproject
+++ b/tests/manual/qml/testfiles_quick2/testfiles_quick2.qmlproject
@@ -1,8 +1,9 @@
-import QmlProject 1.0
+import QmlProject 1.1
Project {
+ // Scan current directory for .qml, .js, and image files
QmlFiles {
- directory: "subfolder1"
+ directory: "."
}
JavaScriptFiles {
directory: "."
@@ -10,8 +11,4 @@ Project {
ImageFiles {
directory: "."
}
- importPaths: [
- "subfolder2",
- "subfolder3"
- ]
}
diff --git a/tests/manual/qml/testfiles_quick2/usingbutton.qml b/tests/manual/qml/testfiles_quick2/usingbutton.qml
new file mode 100644
index 0000000000..76dfbe7f5b
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/usingbutton.qml
@@ -0,0 +1,40 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+import "components" as X
+
+Rectangle {
+ width: 640
+ height: 480
+
+ X.MyButton {
+ }
+
+}
diff --git a/tests/manual/qml/testfiles_quick2/views.qml b/tests/manual/qml/testfiles_quick2/views.qml
new file mode 100644
index 0000000000..164b86e75a
--- /dev/null
+++ b/tests/manual/qml/testfiles_quick2/views.qml
@@ -0,0 +1,198 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of Qt Creator.
+**
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+****************************************************************************/
+
+import QtQuick 2.0
+
+Rectangle {
+ width: 640
+ height: 480
+
+ GridView {
+ id: grid_view1
+ x: 35
+ y: 28
+ width: 140
+ height: 140
+ cellHeight: 70
+ delegate: Item {
+ x: 5
+ height: 50
+ Column {
+ Rectangle {
+ width: 40
+ height: 40
+ color: colorCode
+ anchors.horizontalCenter: parent.horizontalCenter
+ }
+
+ Text {
+ x: 5
+ text: name
+ anchors.horizontalCenter: parent.horizontalCenter
+ font.bold: true
+ }
+ spacing: 5
+ }
+ }
+ model: ListModel {
+ ListElement {
+ name: "Grey"
+ colorCode: "grey"
+ }
+
+ ListElement {
+ name: "Red"
+ colorCode: "red"
+ }
+
+ ListElement {
+ name: "Blue"
+ colorCode: "blue"
+ }
+
+ ListElement {
+ name: "Green"
+ colorCode: "green"
+ }
+ }
+ cellWidth: 70
+ }
+
+ ListView {
+ id: list_view1
+ x: 248
+ y: 28
+ width: 110
+ height: 160
+ delegate: Item {
+ x: 5
+ height: 40
+ Row {
+ id: row1
+ Rectangle {
+ width: 40
+ height: 40
+ color: colorCode
+ }
+
+ Text {
+ text: name
+ anchors.verticalCenter: parent.verticalCenter
+ font.bold: true
+ }
+ spacing: 10
+ }
+ }
+ model: ListModel {
+ ListElement {
+ name: "Grey"
+ colorCode: "grey"
+ }
+
+ ListElement {
+ name: "Red"
+ colorCode: "red"
+ }
+
+ ListElement {
+ name: "Blue"
+ colorCode: "blue"
+ }
+
+ ListElement {
+ name: "Green"
+ colorCode: "green"
+ }
+ }
+ }
+
+ PathView {
+ id: path_view1
+ x: 35
+ y: 239
+ width: 250
+ height: 130
+ delegate: Component {
+ Column {
+ Rectangle {
+ width: 40
+ height: 40
+ color: colorCode
+ anchors.horizontalCenter: parent.horizontalCenter
+ }
+
+ Text {
+ x: 5
+ text: name
+ anchors.horizontalCenter: parent.horizontalCenter
+ font.bold: true
+ }
+ spacing: 5
+ }
+ }
+ model: ListModel {
+ ListElement {
+ name: "Grey"
+ colorCode: "grey"
+ }
+
+ ListElement {
+ name: "Red"
+ colorCode: "red"
+ }
+
+ ListElement {
+ name: "Blue"
+ colorCode: "blue"
+ }
+
+ ListElement {
+ name: "Green"
+ colorCode: "green"
+ }
+ }
+ path: Path {
+ PathQuad {
+ x: 120
+ y: 25
+ controlY: 75
+ controlX: 260
+ }
+
+ PathQuad {
+ x: 120
+ y: 100
+ controlY: 75
+ controlX: -20
+ }
+ startY: 100
+ startX: 120
+ }
+ }
+}
diff --git a/tests/manual/ssh/remoteprocess/argumentscollector.cpp b/tests/manual/ssh/remoteprocess/argumentscollector.cpp
index a12fb4c872..3830243535 100644
--- a/tests/manual/ssh/remoteprocess/argumentscollector.cpp
+++ b/tests/manual/ssh/remoteprocess/argumentscollector.cpp
@@ -45,6 +45,7 @@ ArgumentsCollector::ArgumentsCollector(const QStringList &args)
QSsh::SshConnectionParameters ArgumentsCollector::collect(bool &success) const
{
SshConnectionParameters parameters;
+ parameters.options &= ~SshIgnoreDefaultProxy;
try {
bool authTypeGiven = false;
bool portGiven = false;
@@ -76,13 +77,13 @@ QSsh::SshConnectionParameters ArgumentsCollector::collect(bool &success) const
authTypeGiven = true;
continue;
}
- if (!checkForNoProxy(pos, parameters.proxyType, proxySettingGiven))
+ if (!checkForNoProxy(pos, parameters.options, proxySettingGiven))
throw ArgumentErrorException(QLatin1String("unknown option ") + m_arguments.at(pos));
}
Q_ASSERT(pos <= m_arguments.count());
if (pos == m_arguments.count() - 1) {
- if (!checkForNoProxy(pos, parameters.proxyType, proxySettingGiven))
+ if (!checkForNoProxy(pos, parameters.options, proxySettingGiven))
throw ArgumentErrorException(QLatin1String("unknown option ") + m_arguments.at(pos));
}
@@ -156,13 +157,13 @@ bool ArgumentsCollector::checkAndSetIntArg(int &pos, int &val,
return false;
}
-bool ArgumentsCollector::checkForNoProxy(int &pos,
- SshConnectionParameters::ProxyType &type, bool &alreadyGiven) const
+bool ArgumentsCollector::checkForNoProxy(int &pos, SshConnectionOptions &options,
+ bool &alreadyGiven) const
{
if (m_arguments.at(pos) == QLatin1String("-no-proxy")) {
if (alreadyGiven)
throw ArgumentErrorException(QLatin1String("proxy setting given twice."));
- type = SshConnectionParameters::NoProxy;
+ options |= SshIgnoreDefaultProxy;
alreadyGiven = true;
return true;
}
diff --git a/tests/manual/ssh/remoteprocess/argumentscollector.h b/tests/manual/ssh/remoteprocess/argumentscollector.h
index 9e6573f79c..6f3963061c 100644
--- a/tests/manual/ssh/remoteprocess/argumentscollector.h
+++ b/tests/manual/ssh/remoteprocess/argumentscollector.h
@@ -50,9 +50,7 @@ private:
bool checkAndSetStringArg(int &pos, QString &arg, const char *opt) const;
bool checkAndSetIntArg(int &pos, int &val, bool &alreadyGiven,
const char *opt) const;
- bool checkForNoProxy(int &pos,
- QSsh::SshConnectionParameters::ProxyType &type,
- bool &alreadyGiven) const;
+ bool checkForNoProxy(int &pos, QSsh::SshConnectionOptions &options, bool &alreadyGiven) const;
const QStringList m_arguments;
};
diff --git a/tests/manual/ssh/remoteprocess/remoteprocesstest.h b/tests/manual/ssh/remoteprocess/remoteprocesstest.h
index 2b8122f7e1..70b7be2bf7 100644
--- a/tests/manual/ssh/remoteprocess/remoteprocesstest.h
+++ b/tests/manual/ssh/remoteprocess/remoteprocesstest.h
@@ -70,10 +70,10 @@ private:
const QSsh::SshConnectionParameters m_sshParams;
QTimer * const m_timeoutTimer;
QTextStream *m_textStream;
- QSsh::SshConnection *m_sshConnection;
- QSsh::SshRemoteProcessRunner * const m_remoteRunner;
QSsh::SshRemoteProcess::Ptr m_catProcess;
QSsh::SshRemoteProcess::Ptr m_echoProcess;
+ QSsh::SshConnection *m_sshConnection;
+ QSsh::SshRemoteProcessRunner * const m_remoteRunner;
QByteArray m_remoteStdout;
QByteArray m_remoteStderr;
QByteArray m_remoteData;
diff --git a/tests/manual/ssh/sftp/argumentscollector.cpp b/tests/manual/ssh/sftp/argumentscollector.cpp
index 95c8960a02..5869e3a862 100644
--- a/tests/manual/ssh/sftp/argumentscollector.cpp
+++ b/tests/manual/ssh/sftp/argumentscollector.cpp
@@ -43,6 +43,7 @@ ArgumentsCollector::ArgumentsCollector(const QStringList &args)
Parameters ArgumentsCollector::collect(bool &success) const
{
Parameters parameters;
+ parameters.sshParams.options &= ~SshIgnoreDefaultProxy;
try {
bool authTypeGiven = false;
bool portGiven = false;
@@ -77,13 +78,13 @@ Parameters ArgumentsCollector::collect(bool &success) const
authTypeGiven = true;
continue;
}
- if (!checkForNoProxy(pos, parameters.sshParams.proxyType, proxySettingGiven))
+ if (!checkForNoProxy(pos, parameters.sshParams.options, proxySettingGiven))
throw ArgumentErrorException(QLatin1String("unknown option ") + m_arguments.at(pos));
}
Q_ASSERT(pos <= m_arguments.count());
if (pos == m_arguments.count() - 1) {
- if (!checkForNoProxy(pos, parameters.sshParams.proxyType, proxySettingGiven))
+ if (!checkForNoProxy(pos, parameters.sshParams.options, proxySettingGiven))
throw ArgumentErrorException(QLatin1String("unknown option ") + m_arguments.at(pos));
}
@@ -154,13 +155,13 @@ bool ArgumentsCollector::checkAndSetIntArg(int &pos, int &val,
return false;
}
-bool ArgumentsCollector::checkForNoProxy(int &pos,
- SshConnectionParameters::ProxyType &type, bool &alreadyGiven) const
+bool ArgumentsCollector::checkForNoProxy(int &pos, SshConnectionOptions &options,
+ bool &alreadyGiven) const
{
if (m_arguments.at(pos) == QLatin1String("-no-proxy")) {
if (alreadyGiven)
throw ArgumentErrorException(QLatin1String("proxy setting given twice."));
- type = SshConnectionParameters::NoProxy;
+ options |= SshIgnoreDefaultProxy;
alreadyGiven = true;
return true;
}
diff --git a/tests/manual/ssh/sftp/argumentscollector.h b/tests/manual/ssh/sftp/argumentscollector.h
index 4f10a9a85c..b82e7266fe 100644
--- a/tests/manual/ssh/sftp/argumentscollector.h
+++ b/tests/manual/ssh/sftp/argumentscollector.h
@@ -50,7 +50,7 @@ private:
bool checkAndSetStringArg(int &pos, QString &arg, const char *opt) const;
bool checkAndSetIntArg(int &pos, int &val, bool &alreadyGiven,
const char *opt) const;
- bool checkForNoProxy(int &pos, QSsh::SshConnectionParameters::ProxyType &type,
+ bool checkForNoProxy(int &pos, QSsh::SshConnectionOptions &options,
bool &alreadyGiven) const;
const QStringList m_arguments;
diff --git a/tests/manual/ssh/ssh.pro b/tests/manual/ssh/ssh.pro
index 6284229802..fdfd768132 100644
--- a/tests/manual/ssh/ssh.pro
+++ b/tests/manual/ssh/ssh.pro
@@ -5,4 +5,4 @@
#-------------------------------------------------
TEMPLATE = subdirs
-SUBDIRS = errorhandling sftp remoteprocess shell sftpfsmodel
+SUBDIRS = errorhandling sftp remoteprocess shell sftpfsmodel tunnel
diff --git a/tests/manual/ssh/tunnel/argumentscollector.cpp b/tests/manual/ssh/tunnel/argumentscollector.cpp
new file mode 100644
index 0000000000..28276dfd6b
--- /dev/null
+++ b/tests/manual/ssh/tunnel/argumentscollector.cpp
@@ -0,0 +1,175 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+#include "argumentscollector.h"
+
+#include <QDir>
+#include <QProcessEnvironment>
+
+#include <iostream>
+
+using namespace QSsh;
+
+using namespace std;
+
+ArgumentsCollector::ArgumentsCollector(const QStringList &args)
+ : m_arguments(args)
+{
+}
+
+QSsh::SshConnectionParameters ArgumentsCollector::collect(bool &success) const
+{
+ SshConnectionParameters parameters;
+ parameters.options &= ~SshIgnoreDefaultProxy;
+ parameters.host = QLatin1String("localhost");
+
+ try {
+ bool authTypeGiven = false;
+ bool portGiven = false;
+ bool timeoutGiven = false;
+ bool proxySettingGiven = false;
+ int pos;
+ int port;
+
+ for (pos = 1; pos < m_arguments.count() - 1; ++pos) {
+ if (checkAndSetStringArg(pos, parameters.userName, "-u"))
+ continue;
+ if (checkAndSetIntArg(pos, port, portGiven, "-p")
+ || checkAndSetIntArg(pos, parameters.timeout, timeoutGiven, "-t"))
+ continue;
+ if (checkAndSetStringArg(pos, parameters.password, "-pwd")) {
+ if (!parameters.privateKeyFile.isEmpty())
+ throw ArgumentErrorException(QLatin1String("-pwd and -k are mutually exclusive."));
+ parameters.authenticationType
+ = SshConnectionParameters::AuthenticationByPassword;
+ authTypeGiven = true;
+ continue;
+ }
+ if (checkAndSetStringArg(pos, parameters.privateKeyFile, "-k")) {
+ if (!parameters.password.isEmpty())
+ throw ArgumentErrorException(QLatin1String("-pwd and -k are mutually exclusive."));
+ parameters.authenticationType
+ = SshConnectionParameters::AuthenticationByKey;
+ authTypeGiven = true;
+ continue;
+ }
+ if (!checkForNoProxy(pos, parameters.options, proxySettingGiven))
+ throw ArgumentErrorException(QLatin1String("unknown option ") + m_arguments.at(pos));
+ }
+
+ Q_ASSERT(pos <= m_arguments.count());
+ if (pos == m_arguments.count() - 1) {
+ if (!checkForNoProxy(pos, parameters.options, proxySettingGiven))
+ throw ArgumentErrorException(QLatin1String("unknown option ") + m_arguments.at(pos));
+ }
+
+ if (!authTypeGiven) {
+ parameters.authenticationType = SshConnectionParameters::AuthenticationByKey;
+ parameters.privateKeyFile = QDir::homePath() + QLatin1String("/.ssh/id_rsa");
+ }
+
+ if (parameters.userName.isEmpty()) {
+ parameters.userName
+ = QProcessEnvironment::systemEnvironment().value(QLatin1String("USER"));
+ }
+ if (parameters.userName.isEmpty())
+ throw ArgumentErrorException(QLatin1String("No user name given."));
+
+ if (parameters.host.isEmpty())
+ throw ArgumentErrorException(QLatin1String("No host given."));
+
+ parameters.port = portGiven ? port : 22;
+ if (!timeoutGiven)
+ parameters.timeout = 30;
+ success = true;
+ } catch (ArgumentErrorException &ex) {
+ cerr << "Error: " << qPrintable(ex.error) << endl;
+ printUsage();
+ success = false;
+ }
+ return parameters;
+}
+
+void ArgumentsCollector::printUsage() const
+{
+ cerr << "Usage: " << qPrintable(m_arguments.first())
+ << "[ -u <user> ] "
+ << "[ -pwd <password> | -k <private key file> ] [ -p <port> ] "
+ << "[ -t <timeout> ] [ -no-proxy ]" << endl;
+}
+
+bool ArgumentsCollector::checkAndSetStringArg(int &pos, QString &arg, const char *opt) const
+{
+ if (m_arguments.at(pos) == QLatin1String(opt)) {
+ if (!arg.isEmpty()) {
+ throw ArgumentErrorException(QLatin1String("option ") + opt
+ + QLatin1String(" was given twice."));
+ }
+ arg = m_arguments.at(++pos);
+ if (arg.isEmpty() && QLatin1String(opt) != QLatin1String("-pwd"))
+ throw ArgumentErrorException(QLatin1String("empty argument not allowed here."));
+ return true;
+ }
+ return false;
+}
+
+bool ArgumentsCollector::checkAndSetIntArg(int &pos, int &val,
+ bool &alreadyGiven, const char *opt) const
+{
+ if (m_arguments.at(pos) == QLatin1String(opt)) {
+ if (alreadyGiven) {
+ throw ArgumentErrorException(QLatin1String("option ") + opt
+ + QLatin1String(" was given twice."));
+ }
+ bool isNumber;
+ val = m_arguments.at(++pos).toInt(&isNumber);
+ if (!isNumber) {
+ throw ArgumentErrorException(QLatin1String("option ") + opt
+ + QLatin1String(" needs integer argument"));
+ }
+ alreadyGiven = true;
+ return true;
+ }
+ return false;
+}
+
+bool ArgumentsCollector::checkForNoProxy(int &pos, SshConnectionOptions &options,
+ bool &alreadyGiven) const
+{
+ if (m_arguments.at(pos) == QLatin1String("-no-proxy")) {
+ if (alreadyGiven)
+ throw ArgumentErrorException(QLatin1String("proxy setting given twice."));
+ options |= SshIgnoreDefaultProxy;
+ alreadyGiven = true;
+ return true;
+ }
+ return false;
+}
diff --git a/tests/manual/ssh/tunnel/argumentscollector.h b/tests/manual/ssh/tunnel/argumentscollector.h
new file mode 100644
index 0000000000..25f4d306ef
--- /dev/null
+++ b/tests/manual/ssh/tunnel/argumentscollector.h
@@ -0,0 +1,61 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+
+#ifndef ARGUMENTSCOLLECTOR_H
+#define ARGUMENTSCOLLECTOR_H
+
+#include <ssh/sshconnection.h>
+
+#include <QStringList>
+
+class ArgumentsCollector
+{
+public:
+ ArgumentsCollector(const QStringList &args);
+ QSsh::SshConnectionParameters collect(bool &success) const;
+private:
+ struct ArgumentErrorException
+ {
+ ArgumentErrorException(const QString &error) : error(error) {}
+ const QString error;
+ };
+
+ void printUsage() const;
+ bool checkAndSetStringArg(int &pos, QString &arg, const char *opt) const;
+ bool checkAndSetIntArg(int &pos, int &val, bool &alreadyGiven,
+ const char *opt) const;
+ bool checkForNoProxy(int &pos, QSsh::SshConnectionOptions &options, bool &alreadyGiven) const;
+
+ const QStringList m_arguments;
+};
+
+#endif // ARGUMENTSCOLLECTOR_H
diff --git a/tests/manual/ssh/tunnel/main.cpp b/tests/manual/ssh/tunnel/main.cpp
new file mode 100644
index 0000000000..b25beb46ff
--- /dev/null
+++ b/tests/manual/ssh/tunnel/main.cpp
@@ -0,0 +1,55 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+#include "../remoteprocess/argumentscollector.h"
+#include "tunnel.h"
+
+#include <ssh/sshconnection.h>
+
+#include <QCoreApplication>
+#include <QObject>
+#include <QStringList>
+
+#include <cstdlib>
+#include <iostream>
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication app(argc, argv);
+ bool parseSuccess;
+ const QSsh::SshConnectionParameters &parameters
+ = ArgumentsCollector(app.arguments()).collect(parseSuccess);
+ if (!parseSuccess)
+ return EXIT_FAILURE;
+ Tunnel tunnel(parameters);
+ tunnel.run();
+ return app.exec();
+}
diff --git a/tests/manual/ssh/tunnel/tunnel.cpp b/tests/manual/ssh/tunnel/tunnel.cpp
new file mode 100644
index 0000000000..342102a881
--- /dev/null
+++ b/tests/manual/ssh/tunnel/tunnel.cpp
@@ -0,0 +1,165 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+**
+** GNU Lesser General Public License Usage
+**
+** This file may be used under the terms of the GNU Lesser General Public
+** License version 2.1 as published by the Free Software Foundation and
+** appearing in the file LICENSE.LGPL included in the packaging of this file.
+** Please review the following information to ensure the GNU Lesser General
+** Public License version 2.1 requirements will be met:
+** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Nokia gives you certain additional
+** rights. These rights are described in the Nokia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** Other Usage
+**
+** Alternatively, this file may be used in accordance with the terms and
+** conditions contained in a signed written agreement between you and Nokia.
+**
+** If you have questions regarding the use of this file, please contact
+** Nokia at qt-info@nokia.com.
+**
+**************************************************************************/
+#include "tunnel.h"
+
+#include <ssh/sshconnection.h>
+#include <ssh/sshdirecttcpiptunnel.h>
+
+#include <QCoreApplication>
+#include <QTcpServer>
+#include <QTcpSocket>
+#include <QTimer>
+
+#include <cstdlib>
+#include <iostream>
+
+const QByteArray ServerDataPrefix("Received the following data: ");
+const QByteArray TestData("Urgsblubb?");
+
+using namespace QSsh;
+
+Tunnel::Tunnel(const QSsh::SshConnectionParameters &parameters, QObject *parent)
+ : QObject(parent),
+ m_connection(new SshConnection(parameters, this)),
+ m_tunnelServer(new QTcpServer(this)),
+ m_expectingChannelClose(false)
+{
+ connect(m_connection, SIGNAL(connected()), SLOT(handleConnected()));
+ connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(handleConnectionError()));
+}
+
+Tunnel::~Tunnel()
+{
+}
+
+void Tunnel::run()
+{
+ std::cout << "Connecting to SSH server..." << std::endl;
+ m_connection->connectToHost();
+}
+
+void Tunnel::handleConnectionError()
+{
+ std::cerr << "SSH connection error: " << qPrintable(m_connection->errorString()) << std::endl;
+ qApp->exit(EXIT_FAILURE);
+}
+
+void Tunnel::handleConnected()
+{
+ std::cout << "Opening server side..." << std::endl;
+ if (!m_tunnelServer->listen(QHostAddress::LocalHost)) {
+ std::cerr << "Error opening port: "
+ << m_tunnelServer->errorString().toLocal8Bit().constData() << std::endl;
+ qApp->exit(EXIT_FAILURE);
+ return;
+ }
+ m_forwardedPort = m_tunnelServer->serverPort();
+ connect(m_tunnelServer, SIGNAL(newConnection()), SLOT(handleNewConnection()));
+
+ m_tunnel = m_connection->createTunnel(m_forwardedPort);
+ connect(m_tunnel.data(), SIGNAL(initialized()), SLOT(handleInitialized()));
+ connect(m_tunnel.data(), SIGNAL(error(QString)), SLOT(handleTunnelError(QString)));
+ connect(m_tunnel.data(), SIGNAL(readyRead()), SLOT(handleServerData()));
+ connect(m_tunnel.data(), SIGNAL(tunnelClosed()), SLOT(handleTunnelClosed()));
+
+ std::cout << "Initializing tunnel..." << std::endl;
+ m_tunnel->initialize();
+}
+
+void Tunnel::handleInitialized()
+{
+ std::cout << "Writing data into the tunnel..." << std::endl;
+ m_tunnel->write(TestData);
+ QTimer * const timeoutTimer = new QTimer(this);
+ connect(timeoutTimer, SIGNAL(timeout()), SLOT(handleTimeout()));
+ timeoutTimer->start(10000);
+}
+
+void Tunnel::handleServerData()
+{
+ m_dataReceivedFromServer += m_tunnel->readAll();
+ if (m_dataReceivedFromServer == ServerDataPrefix + TestData) {
+ std::cout << "Data exchange successful. Closing server socket..." << std::endl;
+ m_expectingChannelClose = true;
+ m_tunnelSocket->close();
+ }
+}
+
+void Tunnel::handleTunnelError(const QString &reason)
+{
+ std::cerr << "Tunnel error: " << reason.toLocal8Bit().constData() << std::endl;
+ qApp->exit(EXIT_FAILURE);
+}
+
+void Tunnel::handleTunnelClosed()
+{
+ if (m_expectingChannelClose) {
+ std::cout << "Successfully detected channel close." << std::endl;
+ std::cout << "Test finished successfully." << std::endl;
+ qApp->quit();
+ } else {
+ std::cerr << "Error: Remote host closed channel." << std::endl;
+ qApp->exit(EXIT_FAILURE);
+ }
+}
+
+void Tunnel::handleNewConnection()
+{
+ m_tunnelSocket = m_tunnelServer->nextPendingConnection();
+ m_tunnelServer->close();
+ connect(m_tunnelSocket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(handleSocketError()));
+ connect(m_tunnelSocket, SIGNAL(readyRead()), SLOT(handleClientData()));
+ handleClientData();
+}
+
+void Tunnel::handleSocketError()
+{
+ std::cerr << "Socket error: " << m_tunnelSocket->errorString().toLocal8Bit().constData()
+ << std::endl;
+ qApp->exit(EXIT_FAILURE);
+}
+
+void Tunnel::handleClientData()
+{
+ m_dataReceivedFromClient += m_tunnelSocket->readAll();
+ if (m_dataReceivedFromClient == TestData) {
+ std::cout << "Client data successfully received by server, now sending data to client..."
+ << std::endl;
+ m_tunnelSocket->write(ServerDataPrefix + m_dataReceivedFromClient);
+ }
+}
+
+void Tunnel::handleTimeout()
+{
+ std::cerr << "Error: Timeout waiting for test completion." << std::endl;
+ qApp->exit(EXIT_FAILURE);
+}
diff --git a/src/plugins/debugger/qtmessagelogwindow.h b/tests/manual/ssh/tunnel/tunnel.h
index d6a6fab9b7..b53cd7311a 100644
--- a/src/plugins/debugger/qtmessagelogwindow.h
+++ b/tests/manual/ssh/tunnel/tunnel.h
@@ -26,56 +26,53 @@
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
+#ifndef TUNNEL_H
+#define TUNNEL_H
-#ifndef QTMESSAGELOGWINDOW_H
-#define QTMESSAGELOGWINDOW_H
-
-#include <QWidget>
+#include <QObject>
+#include <QSharedPointer>
QT_BEGIN_NAMESPACE
-class QAbstractItemModel;
-class QAction;
+class QTcpServer;
+class QTcpSocket;
QT_END_NAMESPACE
-namespace Utils {
-class StatusLabel;
-class SavedAction;
+namespace QSsh {
+class SshConnection;
+class SshConnectionParameters;
+class SshDirectTcpIpTunnel;
}
-namespace Debugger {
-namespace Internal {
-
-class QtMessageLogView;
-class QtMessageLogItemDelegate;
-class QtMessageLogProxyModel;
-class QtMessageLogWindow : public QWidget
+class Tunnel : public QObject
{
Q_OBJECT
-
public:
- QtMessageLogWindow(QWidget *parent = 0);
- ~QtMessageLogWindow();
+ Tunnel(const QSsh::SshConnectionParameters &parameters, QObject *parent = 0);
+ ~Tunnel();
- void setModel(QAbstractItemModel *model);
- void readSettings();
- void showStatus(const QString &context, int timeout);
+ void run();
-public slots:
- void writeSettings() const;
+private slots:
+ void handleConnected();
+ void handleConnectionError();
+ void handleServerData();
+ void handleInitialized();
+ void handleTunnelError(const QString &reason);
+ void handleTunnelClosed();
+ void handleNewConnection();
+ void handleSocketError();
+ void handleClientData();
+ void handleTimeout();
private:
- Utils::StatusLabel *m_statusLabel;
- Utils::SavedAction *m_showLogAction;
- Utils::SavedAction *m_showWarningAction;
- Utils::SavedAction *m_showErrorAction;
- QAction *m_clearAction;
- QtMessageLogView *m_treeView;
- QtMessageLogItemDelegate *m_itemDelegate;
- QtMessageLogProxyModel *m_proxyModel;
+ QSsh::SshConnection * const m_connection;
+ QSharedPointer<QSsh::SshDirectTcpIpTunnel> m_tunnel;
+ QTcpServer * const m_tunnelServer;
+ QTcpSocket *m_tunnelSocket;
+ quint16 m_forwardedPort;
+ QByteArray m_dataReceivedFromServer;
+ QByteArray m_dataReceivedFromClient;
+ bool m_expectingChannelClose;
};
-} // namespace Internal
-} // namespace Debugger
-
-#endif // QTMESSAGELOGWINDOW_H
-
+#endif // TUNNEL_H
diff --git a/tests/manual/ssh/tunnel/tunnel.pro b/tests/manual/ssh/tunnel/tunnel.pro
new file mode 100644
index 0000000000..f2f960b98a
--- /dev/null
+++ b/tests/manual/ssh/tunnel/tunnel.pro
@@ -0,0 +1,5 @@
+include(../ssh.pri)
+
+TARGET=tunnel
+SOURCES=main.cpp tunnel.cpp argumentscollector.cpp
+HEADERS=tunnel.h argumentscollector.h
diff --git a/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.pro b/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.pro
index 1c0a7f4e6c..0e500831e2 100644
--- a/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.pro
+++ b/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.pro
@@ -24,5 +24,5 @@ SOURCES += \
$${UTILSDIR}/portlist.cpp \
$${UTILSDIR}/tcpportsgatherer.cpp
-win32:LIBS += -liphlpapi -lWs2_32
+win32:LIBS += -liphlpapi -lws2_32
SOURCES += main.cpp
diff --git a/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.qbp b/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.qbp
index 4a491ff5eb..c84e9fdd3d 100644
--- a/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.qbp
+++ b/tests/manual/utils/tcpportsgatherer/tcpportsgatherer.qbp
@@ -16,7 +16,7 @@ Application {
Properties {
condition: qbs.targetOS == "windows"
- cpp.dynamicLibraries: [ "iphlpapi.lib", "Ws2_32.lib" ]
+ cpp.dynamicLibraries: [ "iphlpapi.lib", "ws2_32.lib" ]
}
Depends { name: "cpp" }
diff --git a/tests/system/objects.map b/tests/system/objects.map
index 2e50fd33c8..327d4eeff8 100644
--- a/tests/system/objects.map
+++ b/tests/system/objects.map
@@ -28,6 +28,7 @@
:CMake Wizard.Next_QPushButton {name='__qt__passive_wizardbutton1' text~='(Next.*|Continue)' type='QPushButton' visible='1' window=':CMake Wizard_CMakeProjectManager::Internal::CMakeOpenProjectWizard'}
:CMake Wizard.Run CMake_QPushButton {text='Run CMake' type='QPushButton' unnamed='1' visible='1' window=':CMake Wizard_CMakeProjectManager::Internal::CMakeOpenProjectWizard'}
:CMake Wizard_CMakeProjectManager::Internal::CMakeOpenProjectWizard {type='CMakeProjectManager::Internal::CMakeOpenProjectWizard' unnamed='1' visible='1' windowTitle='CMake Wizard'}
+:CompilerPath.Utils_BaseValidatingLineEdit {container=':qt_tabwidget_stackedwidget_QWidget' name='LineEdit' type='Utils::BaseValidatingLineEdit' visible='1'}
:Core__Internal__GeneralSettings.User Interface_QGroupBox {container=':qt_tabwidget_stackedwidget.Core__Internal__GeneralSettings_QWidget' name='interfaceBox' title='User Interface' type='QGroupBox' visible='1'}
:CppTools__Internal__CompletionSettingsPage.Behavior_QGroupBox {container=':qt_tabwidget_stackedwidget.CppTools__Internal__CompletionSettingsPage_QWidget' name='groupBox' title='Behavior' type='QGroupBox' visible='1'}
:CreateProject_QStyleItem {clip='false' container=':Qt Creator_QDeclarativeView' enabled='true' text='Create Project' type='LinkedText' unnamed='1' visible='true'}
@@ -50,7 +51,7 @@
:Generator:_QComboBox {buddy=':CMake Wizard.Generator:_QLabel' type='QComboBox' unnamed='1' visible='1'}
:Hits_QCLuceneResultWidget {aboveWidget=':Hits_QLabel' type='QCLuceneResultWidget' unnamed='1' visible='1' window=':Qt Creator_Core::Internal::MainWindow'}
:Hits_QLabel {text~='\\\\d+ - \\\\d+ of \\\\d+ Hits' type='QLabel' unnamed='1' visible='1' window=':Qt Creator_Core::Internal::MainWindow'}
-:Kits_QTreeView {container=':qt_tabwidget_stackedwidget_QWidget' type='QTreeView' unnamed='1' visible='1'}
+:Kits_Or_Compilers_QTreeView {container=':qt_tabwidget_stackedwidget_QWidget' type='QTreeView' unnamed='1' visible='1'}
:Kits_QtVersion_QComboBox {container=':qt_tabwidget_stackedwidget_QWidget' occurrence='4' type='QComboBox' unnamed='1' visible='1'}
:New.frame_QFrame {name='frame' type='QFrame' visible='1' window=':New_Core::Internal::NewDialog'}
:New.templateCategoryView_QTreeView {name='templateCategoryView' type='QTreeView' visible='1' window=':New_Core::Internal::NewDialog'}
@@ -113,6 +114,7 @@
:Qt Gui Application.Source file:_QLabel {name='sourceLabel' text='Source file:' type='QLabel' visible='1' window=':Qt Gui Application_Qt4ProjectManager::Internal::GuiAppWizardDialog'}
:Qt Gui Application_Qt4ProjectManager::Internal::GuiAppWizardDialog {type='Qt4ProjectManager::Internal::GuiAppWizardDialog' unnamed='1' visible='1' windowTitle='Qt Gui Application'}
:QtSupport__Internal__QtVersionManager.QLabel {container=':qt_tabwidget_stackedwidget.QtSupport__Internal__QtVersionManager_QtSupport::Internal::QtOptionsPageWidget' type='QLabel' unnamed='1' visible='1'}
+:QtSupport__Internal__QtVersionManager.errorLabel.QLabel {container=':qt_tabwidget_stackedwidget.QtSupport__Internal__QtVersionManager_QtSupport::Internal::QtOptionsPageWidget' name='errorLabel' type='QLabel' visible='1'}
:QtSupport__Internal__QtVersionManager.qmake_QLabel {container=':qt_tabwidget_stackedwidget.QtSupport__Internal__QtVersionManager_QtSupport::Internal::QtOptionsPageWidget' name='qmakePath' type='QLabel' visible='1'}
:QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget {container=':qt_tabwidget_stackedwidget.QtSupport__Internal__QtVersionManager_QtSupport::Internal::QtOptionsPageWidget' name='qtdirList' type='QTreeWidget' visible='1'}
:Restart required.OK_QPushButton {text='OK' type='QPushButton' unnamed='1' visible='1' window=':Restart required_QMessageBox'}
diff --git a/tests/system/shared/debugger.py b/tests/system/shared/debugger.py
index 9c5b14bab0..db78d54db7 100644
--- a/tests/system/shared/debugger.py
+++ b/tests/system/shared/debugger.py
@@ -40,18 +40,6 @@ def takeDebuggerLog():
# on the given file,line pairs inside the given list of dicts
# the lines are treated as regular expression
def setBreakpointsForCurrentProject(filesAndLines):
- # internal helper for setBreakpointsForCurrentProject
- # double clicks the treeElement inside the given navTree
- # TODO: merge with doubleClickFile() from tst_qml_editor & move to utils(?)
- def __doubleClickFile__(navTree, treeElement):
- waitForObjectItem(navTree, treeElement)
- fileNamePattern = re.compile(".*\.(?P<file>(.*\\\..*)?)$")
- fileName = fileNamePattern.search(treeElement).group("file").replace("\\.", ".")
- doubleClickItem(navTree, treeElement, 5, 5, 0, Qt.LeftButton)
- mainWindow = waitForObject(":Qt Creator_Core::Internal::MainWindow")
- waitFor('fileName in str(mainWindow.windowTitle)', 5000)
- return fileName
-
switchViewTo(ViewConstants.DEBUG)
removeOldBreakpoints()
if not filesAndLines or not isinstance(filesAndLines, (list,tuple)):
@@ -61,12 +49,13 @@ def setBreakpointsForCurrentProject(filesAndLines):
"window=':Qt Creator_Core::Internal::MainWindow'}")
for current in filesAndLines:
for curFile,curLine in current.iteritems():
- fName = __doubleClickFile__(navTree, curFile)
+ if not openDocument(curFile):
+ return False
editor = getEditorForFileSuffix(curFile)
if not placeCursorToLine(editor, curLine, True):
return False
invokeMenuItem("Debug", "Toggle Breakpoint")
- test.log('Set breakpoint in %s' % fName, curLine)
+ test.log('Set breakpoint in %s' % curFile, curLine)
try:
breakPointTreeView = waitForObject(":Breakpoints_Debugger::Internal::BreakTreeView")
waitFor("breakPointTreeView.model().rowCount() == len(filesAndLines)", 2000)
diff --git a/tests/system/shared/editor_utils.py b/tests/system/shared/editor_utils.py
index c438804429..558eef273d 100644
--- a/tests/system/shared/editor_utils.py
+++ b/tests/system/shared/editor_utils.py
@@ -287,14 +287,22 @@ def invokeFindUsage(editor, line, typeOperation, n=1):
invokeContextMenuItem(editor, "Find Usages")
return True
+def addBranchWildcardToRoot(rootNode):
+ pos = rootNode.find(".")
+ return rootNode[:pos] + " (*)" + rootNode[pos:]
+
def openDocument(treeElement):
try:
selectFromCombo(":Qt Creator_Core::Internal::NavComboBox", "Open Documents")
navigator = waitForObject(":Qt Creator_Utils::NavigationTreeView")
- fileName = waitForObjectItem(navigator, treeElement).text
+ try:
+ item = waitForObjectItem(navigator, treeElement, 3000)
+ except:
+ treeElement = addBranchWildcardToRoot(treeElement)
+ item = waitForObjectItem(navigator, treeElement)
doubleClickItem(navigator, treeElement, 5, 5, 0, Qt.LeftButton)
mainWindow = waitForObject(":Qt Creator_Core::Internal::MainWindow")
- waitFor("fileName in str(mainWindow.windowTitle)")
+ waitFor("item.text in str(mainWindow.windowTitle)")
return True
except:
return False
diff --git a/tests/system/shared/project_explorer.py b/tests/system/shared/project_explorer.py
index aacc57bbfa..1f2a1470ac 100644
--- a/tests/system/shared/project_explorer.py
+++ b/tests/system/shared/project_explorer.py
@@ -155,7 +155,7 @@ def getQtInformationForQmlProject():
waitForObjectItem(":Options_QListView", "Build & Run")
clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
clickTab(waitForObject(":Options.qt_tabwidget_tabbar_QTabBar"), "Kits")
- targetsTreeView = waitForObject(":Kits_QTreeView")
+ targetsTreeView = waitForObject(":Kits_Or_Compilers_QTreeView")
if not __selectTreeItemOnBuildAndRun__(targetsTreeView, "%s(\s\(default\))?" % kit, True):
test.fatal("Found no matching kit - this shouldn't happen.")
clickButton(waitForObject(":Options.Cancel_QPushButton"))
diff --git a/tests/system/shared/utils.py b/tests/system/shared/utils.py
index 3430b50d5f..4e015fd437 100644
--- a/tests/system/shared/utils.py
+++ b/tests/system/shared/utils.py
@@ -291,7 +291,7 @@ def getConfiguredKits():
return treeWidget.currentItem().text(0)
# end of internal function for iterateQtVersions
def __setQtVersionForKit__(kit, kitName, kitsQtVersionName):
- treeView = waitForObject(":Kits_QTreeView")
+ treeView = waitForObject(":Kits_Or_Compilers_QTreeView")
clickItem(treeView, kit, 5, 5, 0, Qt.LeftButton)
qtVersionStr = str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
kitsQtVersionName[kitName] = qtVersionStr
@@ -343,7 +343,7 @@ def regexVerify(text, expectedTexts):
def checkDebuggingLibrary(kitIDs):
def __getQtVersionForKit__(kit, kitName):
- treeView = waitForObject(":Kits_QTreeView")
+ treeView = waitForObject(":Kits_Or_Compilers_QTreeView")
clickItem(treeView, kit, 5, 5, 0, Qt.LeftButton)
return str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
# end of internal function for iterate kits
@@ -490,7 +490,7 @@ def iterateKits(keepOptionsOpen=False, alreadyOnOptionsDialog=False,
waitForObjectItem(":Options_QListView", "Build & Run")
clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
clickTab(waitForObject(":Options.qt_tabwidget_tabbar_QTabBar"), "Kits")
- treeView = waitForObject(":Kits_QTreeView")
+ treeView = waitForObject(":Kits_Or_Compilers_QTreeView")
model = treeView.model()
test.compare(model.rowCount(), 2, "Verifying expected target section count")
autoDetected = model.index(0, 0)
diff --git a/tests/system/suite_CCOM/tst_CCOM02/test.py b/tests/system/suite_CCOM/tst_CCOM02/test.py
index a687649f8c..02b3e93df3 100755
--- a/tests/system/suite_CCOM/tst_CCOM02/test.py
+++ b/tests/system/suite_CCOM/tst_CCOM02/test.py
@@ -15,7 +15,7 @@ def main():
# open example project
openQmakeProject(examplePath)
# create syntax error
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation.QML.qml.property-animation\\.qml", 5, 5, 0, Qt.LeftButton)
+ openDocument("propertyanimation.QML.qml.property-animation\\.qml")
if not appendToLine(waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget"), "Image {", "SyntaxError"):
invokeMenuItem("File", "Exit")
return
diff --git a/tests/system/suite_CSUP/tst_CSUP01/test.py b/tests/system/suite_CSUP/tst_CSUP01/test.py
index 10b4f3ffa6..b3ca9bdece 100644
--- a/tests/system/suite_CSUP/tst_CSUP01/test.py
+++ b/tests/system/suite_CSUP/tst_CSUP01/test.py
@@ -8,10 +8,11 @@ def main():
# Step 1: Open test .pro project.
createNewQtQuickApplication(tempDir(), "SampleApp")
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)")
- test.verify(waitForObjectItem(":Qt Creator_Utils::NavigationTreeView", "SampleApp"),
- "Step 1: Verifying if: Project is opened.")
# Step 2: Open .cpp file in Edit mode.
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "SampleApp.Sources.main\\.cpp", 5, 5, 0, Qt.LeftButton)
+ if not openDocument("SampleApp.Sources.main\\.cpp"):
+ test.fatal("Could not open main.cpp")
+ invokeMenuItem("File", "Exit")
+ return
test.verify(checkIfObjectExists(":Qt Creator_CppEditor::Internal::CPPEditorWidget"),
"Step 2: Verifying if: .cpp file is opened in Edit mode.")
# Step 3: Insert text "re" to new line in Editor mode and press Ctrl+Space.
diff --git a/tests/system/suite_CSUP/tst_CSUP02/test.py b/tests/system/suite_CSUP/tst_CSUP02/test.py
index 9e5a5b9c7a..c235574b0e 100644
--- a/tests/system/suite_CSUP/tst_CSUP02/test.py
+++ b/tests/system/suite_CSUP/tst_CSUP02/test.py
@@ -8,10 +8,11 @@ def main():
# Step 1: Open test .pro project.
createNewQtQuickApplication(tempDir(), "SampleApp")
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)")
- test.verify(waitForObjectItem(":Qt Creator_Utils::NavigationTreeView", "SampleApp"),
- "Step 1: Verifying if: Project is opened.")
# Step 2: Open .cpp file in Edit mode.
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "SampleApp.Sources.main\\.cpp", 5, 5, 0, Qt.LeftButton)
+ if not openDocument("SampleApp.Sources.main\\.cpp"):
+ test.fatal("Could not open main.cpp")
+ invokeMenuItem("File", "Exit")
+ return
test.verify(checkIfObjectExists(":Qt Creator_CppEditor::Internal::CPPEditorWidget"),
"Step 2: Verifying if: .cpp file is opened in Edit mode.")
# Steps 3&4: Insert text "class" to new line in Editor mode and press Ctrl+Space.
@@ -26,7 +27,6 @@ def main():
else:
type(editorWidget, "<Ctrl+Space>")
type(waitForObject(":popupFrame_Proposal_QListView"), "<Down>")
- type(waitForObject(":popupFrame_Proposal_QListView"), "<Down>")
listView = waitForObject(":popupFrame_Proposal_QListView")
test.compare("class derived from QObject", str(listView.model().data(listView.currentIndex())),
"Verifying selecting the correct entry.")
diff --git a/tests/system/suite_CSUP/tst_CSUP04/test.py b/tests/system/suite_CSUP/tst_CSUP04/test.py
index 28d4ac145b..e60c2ba362 100644
--- a/tests/system/suite_CSUP/tst_CSUP04/test.py
+++ b/tests/system/suite_CSUP/tst_CSUP04/test.py
@@ -18,11 +18,11 @@ def main():
installLazySignalHandler("{type='Core::FutureProgress' unnamed='1'}", "finished()", "__handleFutureProgress__")
# wait for parsing to complete
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)")
- # open test .pro project.
- test.verify(waitForObjectItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation"),
- "Verifying if: Project is opened.")
# open .cpp file in editor
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation.Sources.main\\.cpp", 5, 5, 0, Qt.LeftButton)
+ if not openDocument("propertyanimation.Sources.main\\.cpp"):
+ test.fatal("Could not open main.cpp")
+ invokeMenuItem("File", "Exit")
+ return
test.verify(checkIfObjectExists(":Qt Creator_CppEditor::Internal::CPPEditorWidget"),
"Verifying if: .cpp file is opened in Edit mode.")
# place cursor on line "QmlApplicationViewer viewer;"
@@ -39,7 +39,7 @@ def main():
test.verify(result, "Verifying if: The list of all usages of the selected text is displayed in Search Results. "
"File with used text is opened.")
# move cursor to the other word and test Find Usages function by pressing Ctrl+Shift+U.
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation.Sources.main\\.cpp", 5, 5, 0, Qt.LeftButton)
+ openDocument("propertyanimation.Sources.main\\.cpp")
if not placeCursorToLine(editorWidget, "viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);"):
return
for i in range(4):
diff --git a/tests/system/suite_CSUP/tst_CSUP05/test.py b/tests/system/suite_CSUP/tst_CSUP05/test.py
index f3d065ed0e..9db59aec2e 100644
--- a/tests/system/suite_CSUP/tst_CSUP05/test.py
+++ b/tests/system/suite_CSUP/tst_CSUP05/test.py
@@ -16,10 +16,11 @@ def main():
openQmakeProject(examplePath)
# wait for parsing to complete
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)")
- test.verify(waitForObjectItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation"),
- "Verifying if: Project is opened.")
# open .cpp file in editor
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation.Sources.main\\.cpp", 5, 5, 0, Qt.LeftButton)
+ if not openDocument("propertyanimation.Sources.main\\.cpp"):
+ test.fatal("Could not open main.cpp")
+ invokeMenuItem("File", "Exit")
+ return
test.verify(checkIfObjectExists(":Qt Creator_CppEditor::Internal::CPPEditorWidget"),
"Verifying if: .cpp file is opened in Edit mode.")
# select some word for example "viewer" and press Ctrl+F.
diff --git a/tests/system/suite_QMLS/shared/qmls.py b/tests/system/suite_QMLS/shared/qmls.py
index 37bcdcb622..1792c98ff4 100644
--- a/tests/system/suite_QMLS/shared/qmls.py
+++ b/tests/system/suite_QMLS/shared/qmls.py
@@ -6,8 +6,11 @@ def startQtCreatorWithNewAppAtQMLEditor(projectDir, projectName, line = None):
# create qt quick application
createNewQtQuickApplication(projectDir, projectName)
# open qml file
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", projectName + ".QML.qml/" +
- projectName + ".main\\.qml", 5, 5, 0, Qt.LeftButton)
+ qmlFile = projectName + ".QML.qml/" + projectName + ".main\\.qml"
+ if not openDocument(qmlFile):
+ test.fatal("Could not open %s" % qmlFile)
+ invokeMenuItem("File", "Exit")
+ return None
# get editor
editorArea = waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget")
# place to line if needed
diff --git a/tests/system/suite_QMLS/tst_QMLS03/test.py b/tests/system/suite_QMLS/tst_QMLS03/test.py
index 4340260f65..abb3ab3a5a 100644
--- a/tests/system/suite_QMLS/tst_QMLS03/test.py
+++ b/tests/system/suite_QMLS/tst_QMLS03/test.py
@@ -50,7 +50,7 @@ def main():
# open example project
openQmakeProject(examplePath)
# open qml file
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "propertyanimation.QML.qml.color-animation\\.qml", 5, 5, 0, Qt.LeftButton)
+ openDocument("propertyanimation.QML.qml.color-animation\\.qml")
# get editor
editorArea = waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget")
# 1. check usages using context menu
diff --git a/tests/system/suite_SCOM/tst_SCOM02/test.py b/tests/system/suite_SCOM/tst_SCOM02/test.py
index 67e8fca6ab..517217dabd 100644
--- a/tests/system/suite_SCOM/tst_SCOM02/test.py
+++ b/tests/system/suite_SCOM/tst_SCOM02/test.py
@@ -7,7 +7,7 @@ def main():
# create qt quick application
createNewQtQuickApplication(tempDir(), "SampleApp")
# create syntax error in qml file
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "SampleApp.QML.qml/SampleApp.main\\.qml", 5, 5, 0, Qt.LeftButton)
+ openDocument("SampleApp.QML.qml/SampleApp.main\\.qml")
if not appendToLine(waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget"), "Text {", "SyntaxError"):
invokeMenuItem("File", "Exit")
return
diff --git a/tests/system/suite_SCOM/tst_SCOM04/test.py b/tests/system/suite_SCOM/tst_SCOM04/test.py
index 254fea1060..be20b1fd36 100644
--- a/tests/system/suite_SCOM/tst_SCOM04/test.py
+++ b/tests/system/suite_SCOM/tst_SCOM04/test.py
@@ -10,7 +10,7 @@ def main():
# create qt quick application
checkedTargets, projectName = createNewQtQuickApplication(tempDir(), "SampleApp")
# create syntax error in cpp file
- doubleClickItem(":Qt Creator_Utils::NavigationTreeView", "SampleApp.Sources.main\\.cpp", 5, 5, 0, Qt.LeftButton)
+ openDocument("SampleApp.Sources.main\\.cpp")
if not appendToLine(waitForObject(":Qt Creator_CppEditor::Internal::CPPEditorWidget"), "viewer.showExpanded();", "SyntaxError"):
invokeMenuItem("File", "Exit")
return
diff --git a/tests/system/suite_WELP/tst_WELP02/test.py b/tests/system/suite_WELP/tst_WELP02/test.py
index edf29c9dc1..1dfa303b4d 100644
--- a/tests/system/suite_WELP/tst_WELP02/test.py
+++ b/tests/system/suite_WELP/tst_WELP02/test.py
@@ -29,7 +29,7 @@ def main():
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}",
"sourceFilesRefreshed(QStringList)")
test.verify(checkIfObjectExists("{column='0' container=':Qt Creator_Utils::NavigationTreeView'"
- " text='SampleApp' type='QModelIndex'}"),
+ " text~='SampleApp( \(.*\))?' type='QModelIndex'}"),
"Verifying: The project is opened in 'Edit' mode after configuring.")
# go to "Welcome page" -> "Develop" topic again.
switchViewTo(ViewConstants.WELCOME)
@@ -43,7 +43,7 @@ def main():
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}",
"sourceFilesRefreshed(QStringList)")
test.verify(checkIfObjectExists("{column='0' container=':Qt Creator_Utils::NavigationTreeView'"
- " text='propertyanimation' type='QModelIndex'}"),
+ " text~='propertyanimation( \(.*\))?' type='QModelIndex'}"),
"Verifying: The project is opened in 'Edit' mode after configuring.")
# go to "Welcome page" -> "Develop" again and check if there is an information about
# recent projects in "Recent Projects".
diff --git a/tests/system/suite_debugger/tst_simple_debug/test.py b/tests/system/suite_debugger/tst_simple_debug/test.py
index 6f8231a844..bc581174db 100644
--- a/tests/system/suite_debugger/tst_simple_debug/test.py
+++ b/tests/system/suite_debugger/tst_simple_debug/test.py
@@ -34,7 +34,7 @@ def main():
test.log("Setting breakpoints")
result = setBreakpointsForCurrentProject(filesAndLines)
if result:
- expectedBreakpointsOrder = [{"main.cpp":9}, {"main.qml":13}]
+ expectedBreakpointsOrder = [{"main.cpp":10}, {"main.qml":13}]
# Only use 4.7.4 to work around QTBUG-25187
availableConfigs = iterateBuildConfigs(len(checkedTargets), "Debug")
if not availableConfigs:
diff --git a/tests/system/suite_editors/shared/testdata/main.c++ b/tests/system/suite_editors/shared/testdata/main.c++
new file mode 100644
index 0000000000..b48f94ec82
--- /dev/null
+++ b/tests/system/suite_editors/shared/testdata/main.c++
@@ -0,0 +1,11 @@
+#include "mainwindow.h"
+#include <QApplication>
+
+int main(int argc, char *argv[])
+{
+ QApplication a(argc, argv);
+ MainWindow w;
+ w.show();
+
+ return a.exec();
+}
diff --git a/tests/system/suite_editors/tst_qml_indent/test.py b/tests/system/suite_editors/tst_qml_indent/test.py
index e38f766906..ea20cd59da 100644
--- a/tests/system/suite_editors/tst_qml_indent/test.py
+++ b/tests/system/suite_editors/tst_qml_indent/test.py
@@ -15,12 +15,9 @@ def main():
invokeMenuItem("File", "Exit")
def prepareQmlFile():
- # make sure the QML file is opened
- navTree = waitForObject("{type='Utils::NavigationTreeView' unnamed='1' visible='1' "
- "window=':Qt Creator_Core::Internal::MainWindow'}")
- model = navTree.model()
- waitForObjectItem(navTree, "untitled.QML.qml/untitled.main\\.qml")
- doubleClickItem(navTree, "untitled.QML.qml/untitled.main\\.qml", 5, 5, 0, Qt.LeftButton)
+ if not openDocument("untitled.QML.qml/untitled.main\\.qml"):
+ test.fatal("Could not open main.qml")
+ return False
editor = waitForObject(":Qt Creator_QmlJSEditor::QmlJSTextEditorWidget")
for i in range(3):
content = "%s" % editor.plainText
diff --git a/tests/system/suite_general/suite.conf b/tests/system/suite_general/suite.conf
index 0eebd931d6..19ee1d31df 100644
--- a/tests/system/suite_general/suite.conf
+++ b/tests/system/suite_general/suite.conf
@@ -7,6 +7,6 @@ HOOK_SUB_PROCESSES=false
IMPLICITAUTSTART=0
LANGUAGE=Python
OBJECTMAP=../objects.map
-TEST_CASES=tst_build_speedcrunch tst_cmake_speedcrunch tst_create_proj_wizard tst_installed_languages tst_openqt_creator
+TEST_CASES=tst_build_speedcrunch tst_cmake_speedcrunch tst_create_proj_wizard tst_default_settings tst_installed_languages tst_openqt_creator
VERSION=2
WRAPPERS=Qt
diff --git a/tests/system/suite_general/tst_default_settings/test.py b/tests/system/suite_general/tst_default_settings/test.py
new file mode 100644
index 0000000000..c7523eba2c
--- /dev/null
+++ b/tests/system/suite_general/tst_default_settings/test.py
@@ -0,0 +1,236 @@
+source("../../shared/qtcreator.py")
+
+import re
+import tempfile
+import __builtin__
+
+currentSelectedTreeItem = None
+warningOrError = re.compile('<p><b>((Error|Warning).*?)</p>')
+
+def main():
+ emptySettings = tempDir()
+ __createMinimumIni__(emptySettings)
+ SettingsPath = ' -settingspath "%s"' % emptySettings
+ startApplication("qtcreator" + SettingsPath)
+ invokeMenuItem("Tools", "Options...")
+ __checkBuildAndRun__()
+ clickButton(waitForObject(":Options.Cancel_QPushButton"))
+ invokeMenuItem("File", "Exit")
+ __checkCreatedSettings__(emptySettings)
+
+def __createMinimumIni__(emptyParent):
+ qtProjDir = os.path.join(emptyParent, "QtProject")
+ os.mkdir(qtProjDir)
+ iniFile = open(os.path.join(qtProjDir, "QtCreator.ini"), "w")
+ iniFile.write("[%General]\n")
+ iniFile.write("OverrideLanguage=C\n")
+ iniFile.close()
+
+def __checkBuildAndRun__():
+ waitForObjectItem(":Options_QListView", "Build & Run")
+ clickItem(":Options_QListView", "Build & Run", 14, 15, 0, Qt.LeftButton)
+ # check compilers
+ expectedCompilers = __getExpectedCompilers__()
+ foundCompilers = []
+ foundCompilerNames = []
+ clickTab(waitForObject(":Options.qt_tabwidget_tabbar_QTabBar"), "Compilers")
+ compilerTV = waitForObject(":Kits_Or_Compilers_QTreeView")
+ __iterateTree__(compilerTV, __compFunc__, foundCompilers, foundCompilerNames)
+ test.verify(__compareCompilers__(foundCompilers, expectedCompilers),
+ "Verifying found and expected compilers are equal.")
+ # check Qt versions
+ qmakePath = which("qmake")
+ foundQt = []
+ clickTab(waitForObject(":Options.qt_tabwidget_tabbar_QTabBar"), "Qt Versions")
+ qtTW = waitForObject(":QtSupport__Internal__QtVersionManager.qtdirList_QTreeWidget")
+ __iterateTree__(qtTW, __qtFunc__, foundQt, qmakePath)
+ if foundQt:
+ foundQt = foundQt[0]
+ # check kits
+ clickTab(waitForObject(":Options.qt_tabwidget_tabbar_QTabBar"), "Kits")
+ kitsTV = waitForObject(":Kits_Or_Compilers_QTreeView")
+ __iterateTree__(kitsTV, __kitFunc__, foundQt, foundCompilerNames)
+
+def __iterateTree__(treeObj, additionalFunc, *additionalParameters):
+ global currentSelectedTreeItem
+ model = treeObj.model()
+ # 1st row: Auto-detected, 2nd row: Manual
+ for sect in dumpIndices(model):
+ sObj = "%s container=%s}" % (objectMap.realName(sect)[:-1], objectMap.realName(treeObj))
+ items = dumpIndices(model, sect)
+ doneItems = []
+ for it in items:
+ indexName = str(it.data().toString())
+ itObj = "%s container=%s}" % (objectMap.realName(it)[:-1], sObj)
+ alreadyDone = doneItems.count(itObj)
+ doneItems.append(itObj)
+ if alreadyDone:
+ itObj = "%s occurrence='%d'}" % (itObj[:-1], alreadyDone + 1)
+ currentSelectedTreeItem = waitForObject(itObj, 3000)
+ mouseClick(currentSelectedTreeItem, 5, 5, 0, Qt.LeftButton)
+ additionalFunc(indexName, *additionalParameters)
+ currentSelectedTreeItem = None
+
+def __compFunc__(it, foundComp, foundCompNames):
+ try:
+ waitFor("object.exists(':CompilerPath.Utils_BaseValidatingLineEdit')", 1000)
+ pathLineEdit = findObject(":CompilerPath.Utils_BaseValidatingLineEdit")
+ foundComp.append(str(pathLineEdit.text))
+ except:
+ label = findObject("{buddy={container=':qt_tabwidget_stackedwidget_QWidget' "
+ "text='Initialization:' type='QLabel' unnamed='1' visible='1'} "
+ "type='QLabel' unnamed='1' visible='1'}")
+ foundComp.append({it:str(label.text)})
+ foundCompNames.append(it)
+
+def __qtFunc__(it, foundQt, qmakePath):
+ foundQt.append(it)
+ qtPath = str(waitForObject(":QtSupport__Internal__QtVersionManager.qmake_QLabel").text)
+ if platform.system() in ('Microsoft', 'Windows'):
+ qtPath = qtPath.lower()
+ qmakePath = qmakePath.lower()
+ test.compare(qtPath, qmakePath, "Verifying found and expected Qt version are equal.")
+ try:
+ errorLabel = findObject(":QtSupport__Internal__QtVersionManager.errorLabel.QLabel")
+ test.warning("Detected error or warning: '%s'" % errorLabel.text)
+ except:
+ pass
+
+def __kitFunc__(it, foundQt, foundCompNames):
+ global currentSelectedTreeItem, warningOrError
+ qtVersionStr = str(waitForObject(":Kits_QtVersion_QComboBox").currentText)
+ test.compare(it, "Desktop (default)", "Verifying whether default Desktop kit has been created.")
+ if foundQt:
+ test.compare(qtVersionStr, foundQt, "Verifying if Qt versions match.")
+ compilerCombo = waitForObject("{occurrence='3' type='QComboBox' unnamed='1' visible='1' "
+ "window=':Qt Creator_Core::Internal::MainWindow'}")
+ test.verify(str(compilerCombo.currentText) in foundCompNames,
+ "Verifying if one of the found compilers had been set.")
+ if currentSelectedTreeItem:
+ foundWarningOrError = warningOrError.search(str(currentSelectedTreeItem.toolTip))
+ if foundWarningOrError:
+ details = str(foundWarningOrError.group(1)).replace("<br>", "\n")
+ details = details.replace("<b>", "").replace("</b>", "")
+ test.warning("Detected error and/or warning: %s" % details)
+
+def __getExpectedCompilers__():
+ expected = []
+ if platform.system() in ('Microsoft', 'Windows'):
+ expected.extend(__getWinCompilers__())
+ compilers = ["g++"]
+ if platform.system() in ('Linux', 'Darwin'):
+ compilers.extend(["g++-4.0", "g++-4.2", "clang++"])
+ for compiler in compilers:
+ compilerPath = which(compiler)
+ if compilerPath:
+ if compiler == 'clang++':
+ if subprocess.call(['clang++', '-dumpmachine']) != 0:
+ test.warning("clang found in PATH, but version is not supported.")
+ continue
+ expected.append(compilerPath)
+ return expected
+
+def __getWinCompilers__():
+ result = []
+ winEnvVars = __getWinEnvVars__()
+ for record in testData.dataset("win_compiler_paths.tsv"):
+ envvar = winEnvVars.get(testData.field(record, "envvar"), "")
+ compiler = os.path.abspath(os.path.join(envvar, testData.field(record, "path"),
+ testData.field(record, "file")))
+ if os.path.exists(compiler):
+ parameters = testData.field(record, "displayedParameters").split(",")
+ usedParameters = testData.field(record, "usedParameters").split(",")
+ if testData.field(record, "isSDK") == "true":
+ for para, used in zip(parameters, usedParameters):
+ result.append(
+ {"%s \(.*?\) \(%s\)" % (testData.field(record, 'displayName'),
+ para)
+ :"%s %s" % (compiler, used)})
+ else:
+ for para, used in zip(parameters, usedParameters):
+ result.append({"%s (%s)" % (testData.field(record, 'displayName'), para)
+ :"%s %s" % (compiler, used)})
+ return result
+
+# using os.getenv() or getOutputFromCmdline() do not work - they would return C:\Program Files (x86)
+# for %ProgramFiles% as well as for %ProgramFiles(x86)% when using Python 32bit on 64bit machines
+def __getWinEnvVars__():
+ result = {}
+ tmpF, tmpFPath = tempfile.mkstemp()
+ envvars = subprocess.call('set', stdout=tmpF, shell=True)
+ os.close(tmpF)
+ tmpF = open(tmpFPath, "r")
+ for line in tmpF:
+ tmp = line.split("=")
+ result[tmp[0]] = tmp[1]
+ tmpF.close()
+ os.remove(tmpFPath)
+ return result
+
+
+def __compareCompilers__(foundCompilers, expectedCompilers):
+ equal = True
+ flags = 0
+ isWin = platform.system() in ('Microsoft', 'Windows')
+ if isWin:
+ flags = re.IGNORECASE
+ for currentFound in foundCompilers:
+ if isinstance(currentFound, dict):
+ foundExp = False
+ for currentExp in expectedCompilers:
+ if isinstance(currentExp, (str, unicode)):
+ continue
+ key = currentExp.keys()[0]
+ # the regex .*? is used for the different possible version strings of the WinSDK
+ # if it's present a regex will be validated otherwise simple string comparison
+ if (((".*?" in key and re.match(key, currentFound.keys()[0], flags))
+ or currentFound.keys() == currentExp.keys())):
+ if ((isWin and os.path.abspath(currentFound.values()[0].lower())
+ == os.path.abspath(currentExp.values()[0].lower()))
+ or currentFound.values() == currentExp.values()):
+ foundExp = True
+ break
+ equal = foundExp
+ else:
+ if isWin:
+ equal = currentFound.lower() in __lowerStrs__(expectedCompilers)
+ else:
+ equal = currentFound in expectedCompilers
+ if not equal:
+ test.fail("Found '%s' but was not expected." % str(currentFound),
+ str(expectedCompilers))
+ break
+ return equal
+
+def __lowerStrs__(iterable):
+ for it in iterable:
+ if isinstance(it, (str, unicode)):
+ yield it.lower()
+ else:
+ yield it
+
+def __checkCreatedSettings__(settingsFolder):
+ qtProj = os.path.join(settingsFolder, "QtProject")
+ folders = []
+ files = [{os.path.join(qtProj, "QtCreator.db"):0},
+ {os.path.join(qtProj, "QtCreator.ini"):30}]
+ folders.append(os.path.join(qtProj, "qtcreator"))
+ files.extend([{os.path.join(folders[0], "devices.xml"):0},
+ {os.path.join(folders[0], "helpcollection.qhc"):0},
+ {os.path.join(folders[0], "profiles.xml"):0},
+ {os.path.join(folders[0], "qtversion.xml"):0},
+ {os.path.join(folders[0], "toolchains.xml"):0}])
+ folders.extend([os.path.join(folders[0], "generic-highlighter"),
+ os.path.join(folders[0], "json"),
+ os.path.join(folders[0], "macros")])
+ for f in folders:
+ test.verify(os.path.isdir(f),
+ "Verifying whether folder '%s' has been created." % os.path.basename(f))
+ for f in files:
+ fName = f.keys()[0]
+ fMinSize = f.values()[0]
+ text = "created non-empty"
+ if fMinSize > 0:
+ text = "modified"
+ test.verify(os.path.isfile(fName) and os.path.getsize(fName) > fMinSize,
+ "Verifying whether file '%s' has been %s." % (os.path.basename(fName), text))
diff --git a/tests/system/suite_general/tst_default_settings/testdata/win_compiler_paths.tsv b/tests/system/suite_general/tst_default_settings/testdata/win_compiler_paths.tsv
new file mode 100644
index 0000000000..0438a4698b
--- /dev/null
+++ b/tests/system/suite_general/tst_default_settings/testdata/win_compiler_paths.tsv
@@ -0,0 +1,19 @@
+"envvar" "path" "file" "displayName" "displayedParameters" "usedParameters" "isSDK"
+"ProgramFiles" "Microsoft SDKs\Windows\v7.0\Bin" "SetEnv.cmd" "Microsoft Windows SDK for Windows 7" "x86,amd64,x86_amd64,ia64,x86_ia64" "/x86,/x64,/x64,/ia64,/ia64" "true"
+"ProgramFiles(x86)" "Microsoft SDKs\Windows\v7.0\Bin" "SetEnv.cmd" "Microsoft Windows SDK for Windows 7" "x86,amd64,x86_amd64,ia64,x86_ia64" "/x86,/x64,/x64,/ia64,/ia64" "true"
+"ProgramFiles" "Microsoft SDKs\Windows\v7.1\Bin" "SetEnv.cmd" "Microsoft Windows SDK for Windows 7" "x86,amd64,x86_amd64,ia64,x86_ia64" "/x86,/x64,/x64,/ia64,/ia64" "true"
+"ProgramFiles(x86)" "Microsoft SDKs\Windows\v7.1\Bin" "SetEnv.cmd" "Microsoft Windows SDK for Windows 7" "x86,amd64,x86_amd64,ia64,x86_ia64" "/x86,/x64,/x64,/ia64,/ia64" "true"
+"VS80COMNTOOLS" "..\..\VC\Bin" "vcvars32.bat" "Microsoft Visual C++ Compiler 8.0" "x86" "" "false"
+"VS80COMNTOOLS" "..\..\VC\Bin\amd64" "vcvarsamd64.bat" "Microsoft Visual C++ Compiler 8.0" "amd64" "amd64" "false"
+"VS80COMNTOOLS" "..\..\VC\Bin" "vcvarsx86_amd64.bat" "Microsoft Visual C++ Compiler 8.0" "x86_amd64" "x86_amd64" "false"
+"VS80COMNTOOLS" "..\..\VC\Bin" "vcvars64.bat" "Microsoft Visual C++ Compiler 8.0" "ia64" "ia64" "false"
+"VS80COMNTOOLS" "..\..\VC\Bin" "vcvarsx86_ia64.bat" "Microsoft Visual C++ Compiler 8.0" "x86_ia64" "x86_ia64" "false"
+"VS90COMNTOOLS" "..\..\VC\Bin" "vcvars32.bat" "Microsoft Visual C++ Compiler 9.0" "x86" "" "false"
+"VS90COMNTOOLS" "..\..\VC\Bin\amd64" "vcvarsamd64.bat" "Microsoft Visual C++ Compiler 9.0" "amd64" "amd64" "false"
+"VS90COMNTOOLS" "..\..\VC\Bin" "vcvarsx86_amd64.bat" "Microsoft Visual C++ Compiler 9.0" "x86_amd64" "x86_amd64" "false"
+"VS90COMNTOOLS" "..\..\VC\Bin" "vcvars64.bat" "Microsoft Visual C++ Compiler 9.0" "ia64" "ia64" "false"
+"VS90COMNTOOLS" "..\..\VC\Bin" "vcvarsx86_ia64.bat" "Microsoft Visual C++ Compiler 9.0" "x86_ia64" "x86_ia64" "false"
+"VS100COMNTOOLS" "..\..\VC\Bin" "vcvars32.bat" "Microsoft Visual C++ Compiler 10.0" "x86" "" "false"
+"VS100COMNTOOLS" "..\..\VC" "vcvarsall.bat" "Microsoft Visual C++ Compiler 10.0" "x86,amd64,x86_amd64,ia64,x86_ia64" "x86,amd64,x86_amd64,ia64,x86_ia64" "false"
+"VS110COMNTOOLS" "..\..\VC\Bin" "vcvars32.bat" "Microsoft Visual C++ Compiler 11.0" "x86" "" "false"
+"VS110COMNTOOLS" "..\..\VC" "vcvarsall.bat" "Microsoft Visual C++ Compiler 11.0" "x86,amd64,x86_amd64,ia64,x86_ia64" "x86,amd64,x86_amd64,ia64,x86_ia64" "false"
diff --git a/tests/system/suite_general/tst_openqt_creator/test.py b/tests/system/suite_general/tst_openqt_creator/test.py
index 8d34cbc100..6708d2c0a7 100644
--- a/tests/system/suite_general/tst_openqt_creator/test.py
+++ b/tests/system/suite_general/tst_openqt_creator/test.py
@@ -15,9 +15,9 @@ def main():
# Wait for parsing to complete
waitForSignal("{type='CppTools::Internal::CppModelManager' unnamed='1'}", "sourceFilesRefreshed(QStringList)", 300000)
- naviTreeView = "{column='0' container=':Qt Creator_Utils::NavigationTreeView' text='%s' type='QModelIndex'}"
- compareProjectTree(naviTreeView % "speedcrunch", "projecttree_speedcrunch.tsv")
- compareProjectTree(naviTreeView % "qtcreator", "projecttree_creator.tsv")
+ naviTreeView = "{column='0' container=':Qt Creator_Utils::NavigationTreeView' text~='%s' type='QModelIndex'}"
+ compareProjectTree(naviTreeView % "speedcrunch( \(\S+\))?", "projecttree_speedcrunch.tsv")
+ compareProjectTree(naviTreeView % "qtcreator( \(\S+\))?", "projecttree_creator.tsv")
# Now check some basic lookups in the search box
selectFromLocator(": Qlist::QList", "QList::QList")
diff --git a/tests/tools/cplusplus-ast2png/cplusplus-ast2png.cpp b/tests/tools/cplusplus-ast2png/cplusplus-ast2png.cpp
index 3298ea4a59..308090ed09 100644
--- a/tests/tools/cplusplus-ast2png/cplusplus-ast2png.cpp
+++ b/tests/tools/cplusplus-ast2png/cplusplus-ast2png.cpp
@@ -57,6 +57,7 @@
#include <cstdlib>
#include <fstream>
#include <iostream>
+#include <string>
#ifdef __GNUC__
# include <cxxabi.h>
#endif
@@ -115,7 +116,7 @@ protected:
void alignTerminals() {
out<<"{ rank=same;" << std::endl;
foreach (const QByteArray &terminalShape, _terminalShapes) {
- out << " " << std::string(terminalShape) << ";" << std::endl;
+ out << " " << std::string(terminalShape.constData(), terminalShape.size()).c_str() << ";" << std::endl;
}
out<<"}"<<std::endl;
}
@@ -203,9 +204,9 @@ public:
SymbolDump(TranslationUnit *unit)
: translationUnit(unit)
{
- o.setShowArgumentNames(true);
- o.setShowFunctionSignatures(true);
- o.setShowReturnTypes(true);
+ o.showArgumentNames = true;
+ o.showFunctionSignatures = true;
+ o.showReturnTypes = true;
}
void operator()(Symbol *s) {
@@ -383,7 +384,7 @@ QString example()
#else
QString::fromLatin1("$ echo \"int foo() {}\" | ./%1 && xdg-open %2.ast.png")
#endif
- .arg(QFileInfo(qApp->arguments().at(0)).fileName(), PATH_STDIN_FILE);
+ .arg(QFileInfo(qApp->arguments().at(0)).fileName(), QLatin1String(PATH_STDIN_FILE));
}
void printUsage()
@@ -391,7 +392,7 @@ void printUsage()
std::cout << "Usage: " << qPrintable(QFileInfo(qApp->arguments().at(0)).fileName())
<< " [-v] <file1> <file2> ...\n\n";
- std::cout << qPrintable(QString::fromLatin1(
+ std::cout << QString::fromLatin1(
"Visualize AST and symbol hierarchy of given C++ files by generating png image files\n"
"in the same directory as the input files. Print paths to generated image files.\n"
"\n"
@@ -404,7 +405,7 @@ void printUsage()
"Prerequisites:\n"
" 1) Make sure to have 'dot' from graphviz locatable by PATH.\n"
" 2) Make sure to have an up to date dumpers file by using 'cplusplus-update-frontend'.\n"
- ).arg(PATH_STDIN_FILE, example()));
+ ).arg(QLatin1String(PATH_STDIN_FILE), example()).toLocal8Bit().constData();
}
int main(int argc, char *argv[])
@@ -417,7 +418,7 @@ int main(int argc, char *argv[])
// Data from stdin?
if (!tty_for_stdin()) {
- QFile file("_stdincontents.cpp");
+ QFile file((QLatin1String(PATH_STDIN_FILE)));
if (! file.open(QFile::WriteOnly)) {
std::cerr << "Error: Cannot open file for writing\"" << qPrintable(file.fileName())
<< "\"" << std::endl;
@@ -429,11 +430,12 @@ int main(int argc, char *argv[])
}
// Process options & arguments
- if (args.contains("-v")) {
+ if (args.contains(QLatin1String("-v"))) {
optionVerbose = true;
- args.removeOne("-v");
+ args.removeOne(QLatin1String("-v"));
}
- const bool helpRequested = args.contains("-h") || args.contains("-help");
+ const bool helpRequested = args.contains(QLatin1String("-h"))
+ || args.contains(QLatin1String("-help"));
if (args.isEmpty() || helpRequested) {
printUsage();
return helpRequested ? EXIT_SUCCESS : EXIT_FAILURE;
diff --git a/tests/tools/cplusplus-ast2png/cplusplus-ast2png.pro b/tests/tools/cplusplus-ast2png/cplusplus-ast2png.pro
index 8a0fd726ad..c02c4dba9f 100644
--- a/tests/tools/cplusplus-ast2png/cplusplus-ast2png.pro
+++ b/tests/tools/cplusplus-ast2png/cplusplus-ast2png.pro
@@ -9,4 +9,5 @@ include(../../../qtcreator.pri)
include(../../../src/libs/cplusplus/cplusplus-lib.pri)
include(../../../src/tools/cplusplus-tools-utils/cplusplus-tools-utils.pri)
+DEFINES *= QT_NO_CAST_FROM_ASCII
SOURCES += cplusplus-ast2png.cpp
diff --git a/tests/tools/cplusplus-ast2png/dumpers.inc b/tests/tools/cplusplus-ast2png/dumpers.inc
index 0d1d8e4620..1d3d20238b 100644
--- a/tests/tools/cplusplus-ast2png/dumpers.inc
+++ b/tests/tools/cplusplus-ast2png/dumpers.inc
@@ -22,7 +22,7 @@
// W A R N I N G
// -------------
//
-// This file is automatically generated.
+// This file is automatically generated by "cplusplus-update-frontend".
// Changes will be lost.
//
@@ -359,6 +359,8 @@ virtual bool visit(ClassSpecifierAST *ast)
for (SpecifierListAST *iter = ast->attribute_list; iter; iter = iter->next)
nonterminal(iter->value);
nonterminal(ast->name);
+ if (ast->final_token)
+ terminal(ast->final_token, ast);
if (ast->colon_token)
terminal(ast->colon_token, ast);
for (BaseSpecifierListAST *iter = ast->base_clause_list; iter; iter = iter->next)
@@ -477,6 +479,8 @@ virtual bool visit(FunctionDeclaratorAST *ast)
terminal(ast->rparen_token, ast);
for (SpecifierListAST *iter = ast->cv_qualifier_list; iter; iter = iter->next)
nonterminal(iter->value);
+ if (ast->ref_qualifier_token)
+ terminal(ast->ref_qualifier_token, ast);
nonterminal(ast->exception_specification);
nonterminal(ast->trailing_return_type);
nonterminal(ast->as_cpp_initializer);
@@ -544,7 +548,13 @@ virtual bool visit(EnumSpecifierAST *ast)
{
if (ast->enum_token)
terminal(ast->enum_token, ast);
+ if (ast->key_token)
+ terminal(ast->key_token, ast);
nonterminal(ast->name);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
if (ast->lbrace_token)
terminal(ast->lbrace_token, ast);
for (EnumeratorListAST *iter = ast->enumerator_list; iter; iter = iter->next)
@@ -649,6 +659,24 @@ virtual bool visit(ForeachStatementAST *ast)
return false;
}
+virtual bool visit(RangeBasedForStatementAST *ast)
+{
+ if (ast->for_token)
+ terminal(ast->for_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
+ nonterminal(iter->value);
+ nonterminal(ast->declarator);
+ if (ast->colon_token)
+ terminal(ast->colon_token, ast);
+ nonterminal(ast->expression);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ nonterminal(ast->statement);
+ return false;
+}
+
virtual bool visit(ForStatementAST *ast)
{
if (ast->for_token)
@@ -727,12 +755,7 @@ virtual bool visit(LinkageSpecificationAST *ast)
virtual bool visit(MemInitializerAST *ast)
{
nonterminal(ast->name);
- if (ast->lparen_token)
- terminal(ast->lparen_token, ast);
- for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
- nonterminal(iter->value);
- if (ast->rparen_token)
- terminal(ast->rparen_token, ast);
+ nonterminal(ast->expression);
return false;
}
@@ -831,7 +854,21 @@ virtual bool visit(NamespaceAliasDefinitionAST *ast)
return false;
}
-virtual bool visit(NewPlacementAST *ast)
+virtual bool visit(AliasDeclarationAST *ast)
+{
+ if (ast->using_token)
+ terminal(ast->using_token, ast);
+ if (ast->identifier_token)
+ terminal(ast->identifier_token, ast);
+ if (ast->equal_token)
+ terminal(ast->equal_token, ast);
+ nonterminal(ast->typeId);
+ if (ast->semicolon_token)
+ terminal(ast->semicolon_token, ast);
+ return false;
+}
+
+virtual bool visit(ExpressionListParenAST *ast)
{
if (ast->lparen_token)
terminal(ast->lparen_token, ast);
@@ -869,16 +906,6 @@ virtual bool visit(NewExpressionAST *ast)
return false;
}
-virtual bool visit(NewInitializerAST *ast)
-{
- if (ast->lparen_token)
- terminal(ast->lparen_token, ast);
- nonterminal(ast->expression);
- if (ast->rparen_token)
- terminal(ast->rparen_token, ast);
- return false;
-}
-
virtual bool visit(NewTypeIdAST *ast)
{
for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
@@ -980,12 +1007,7 @@ virtual bool visit(TypenameCallExpressionAST *ast)
if (ast->typename_token)
terminal(ast->typename_token, ast);
nonterminal(ast->name);
- if (ast->lparen_token)
- terminal(ast->lparen_token, ast);
- for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
- nonterminal(iter->value);
- if (ast->rparen_token)
- terminal(ast->rparen_token, ast);
+ nonterminal(ast->expression);
return false;
}
@@ -993,12 +1015,7 @@ virtual bool visit(TypeConstructorCallAST *ast)
{
for (SpecifierListAST *iter = ast->type_specifier_list; iter; iter = iter->next)
nonterminal(iter->value);
- if (ast->lparen_token)
- terminal(ast->lparen_token, ast);
- for (ExpressionListAST *iter = ast->expression_list; iter; iter = iter->next)
- nonterminal(iter->value);
- if (ast->rparen_token)
- terminal(ast->rparen_token, ast);
+ nonterminal(ast->expression);
return false;
}
@@ -1012,6 +1029,8 @@ virtual bool visit(PointerToMemberAST *ast)
terminal(ast->star_token, ast);
for (SpecifierListAST *iter = ast->cv_qualifier_list; iter; iter = iter->next)
nonterminal(iter->value);
+ if (ast->ref_qualifier_token)
+ terminal(ast->ref_qualifier_token, ast);
return false;
}
@@ -1084,6 +1103,18 @@ virtual bool visit(SizeofExpressionAST *ast)
return false;
}
+virtual bool visit(AlignofExpressionAST *ast)
+{
+ if (ast->alignof_token)
+ terminal(ast->alignof_token, ast);
+ if (ast->lparen_token)
+ terminal(ast->lparen_token, ast);
+ nonterminal(ast->typeId);
+ if (ast->rparen_token)
+ terminal(ast->rparen_token, ast);
+ return false;
+}
+
virtual bool visit(PointerLiteralAST *ast)
{
if (ast->literal_token)
@@ -1614,6 +1645,9 @@ virtual bool visit(LambdaCaptureAST *ast)
virtual bool visit(CaptureAST *ast)
{
+ if (ast->amper_token)
+ terminal(ast->amper_token, ast);
+ nonterminal(ast->identifier);
return false;
}
diff --git a/tests/tools/qml-ast2dot/main.cpp b/tests/tools/qml-ast2dot/main.cpp
index b79fb35ace..870ad50846 100644
--- a/tests/tools/qml-ast2dot/main.cpp
+++ b/tests/tools/qml-ast2dot/main.cpp
@@ -43,6 +43,7 @@
#include <cstdlib>
#include <fstream>
#include <iostream>
+#include <string>
#ifdef __GNUC__
# include <cxxabi.h>
#endif
@@ -83,7 +84,7 @@ protected:
void alignTerminals() {
out<<"{ rank=same;" << endl;
foreach (const QByteArray &terminalShape, _terminalShapes) {
- out << " " << string(terminalShape) << ";" << endl;
+ out << " " << string(terminalShape.constData(), terminalShape.size()).c_str() << ";" << endl;
}
out<<"}"<<endl;
}
diff --git a/tests/valgrind/callgrind/callgrindparsertests.cpp b/tests/valgrind/callgrind/callgrindparsertests.cpp
index 3157491b1f..da909fc3b1 100644
--- a/tests/valgrind/callgrind/callgrindparsertests.cpp
+++ b/tests/valgrind/callgrind/callgrindparsertests.cpp
@@ -121,8 +121,8 @@ void CallgrindParserTests::testHeaderData()
{
QScopedPointer<const ParseData> data(parseDataFile(dataFile("simpleFunction.out")));
- QCOMPARE(data->command(), QString("ls"));
- QCOMPARE(data->creator(), QString("callgrind-3.6.0.SVN-Debian"));
+ QCOMPARE(data->command(), QLatin1String("ls"));
+ QCOMPARE(data->creator(), QLatin1String("callgrind-3.6.0.SVN-Debian"));
QCOMPARE(data->pid(), quint64(2992));
QCOMPARE(data->version(), 1);
QCOMPARE(data->part(), 1u);
@@ -144,9 +144,9 @@ void CallgrindParserTests::testSimpleFunction()
{
const Function *func = data->functions().at(0);
- QCOMPARE(func->file(), QString("/my/file.cpp"));
- QCOMPARE(func->object(), QString("/my/object"));
- QCOMPARE(func->name(), QString("myFunction"));
+ QCOMPARE(func->file(), QLatin1String("/my/file.cpp"));
+ QCOMPARE(func->object(), QLatin1String("/my/object"));
+ QCOMPARE(func->name(), QLatin1String("myFunction"));
QVERIFY(func->outgoingCalls().isEmpty());
QCOMPARE(func->called(), quint64(0));
@@ -157,7 +157,7 @@ void CallgrindParserTests::testSimpleFunction()
testSimpleCostItem(func->costItems().at(2), 3, 3);
testSimpleCostItem(func->costItems().at(3), 1, 1);
testSimpleCostItem(func->costItems().at(4), 5, 4);
- testDifferringFileCostItem(func->costItems().at(5), QString("/my/file3.h"), 1, 5);
+ testDifferringFileCostItem(func->costItems().at(5), QLatin1String("/my/file3.h"), 1, 5);
testSimpleCostItem(func->costItems().at(6), 7, 5);
QCOMPARE(func->selfCost(0), quint64(20));
QCOMPARE(func->inclusiveCost(0), quint64(20));
@@ -165,9 +165,9 @@ void CallgrindParserTests::testSimpleFunction()
{
const Function *func = data->functions().at(1);
- QCOMPARE(func->file(), QString("/my/file.cpp"));
- QCOMPARE(func->object(), QString("/my/object"));
- QCOMPARE(func->name(), QString("myFunction2"));
+ QCOMPARE(func->file(), QLatin1String("/my/file.cpp"));
+ QCOMPARE(func->object(), QLatin1String("/my/object"));
+ QCOMPARE(func->name(), QLatin1String("myFunction2"));
QVERIFY(func->incomingCalls().isEmpty());
QCOMPARE(func->called(), quint64(0));
@@ -179,9 +179,9 @@ void CallgrindParserTests::testSimpleFunction()
{
const Function *func = data->functions().at(2);
- QCOMPARE(func->file(), QString("/my/file2.cpp"));
- QCOMPARE(func->object(), QString("/my/object"));
- QCOMPARE(func->name(), QString("myFunction4"));
+ QCOMPARE(func->file(), QLatin1String("/my/file2.cpp"));
+ QCOMPARE(func->object(), QLatin1String("/my/object"));
+ QCOMPARE(func->name(), QLatin1String("myFunction4"));
QVERIFY(func->incomingCalls().isEmpty());
QCOMPARE(func->called(), quint64(0));
@@ -193,9 +193,9 @@ void CallgrindParserTests::testSimpleFunction()
{
const Function *func = data->functions().at(3);
- QCOMPARE(func->file(), QString("/my/file.cpp"));
- QCOMPARE(func->object(), QString("/my/object2"));
- QCOMPARE(func->name(), QString("myFunction3"));
+ QCOMPARE(func->file(), QLatin1String("/my/file.cpp"));
+ QCOMPARE(func->object(), QLatin1String("/my/object2"));
+ QCOMPARE(func->name(), QLatin1String("myFunction3"));
QVERIFY(func->incomingCalls().isEmpty());
QCOMPARE(func->called(), quint64(0));
@@ -213,9 +213,9 @@ void CallgrindParserTests::testCallee()
// basic function data testing
const Function *main = data->functions().at(0);
- QCOMPARE(main->file(), QString("file1.c"));
- QCOMPARE(main->object(), QString(""));
- QCOMPARE(main->name(), QString("main"));
+ QCOMPARE(main->file(), QLatin1String("file1.c"));
+ QCOMPARE(main->object(), QLatin1String(""));
+ QCOMPARE(main->name(), QLatin1String("main"));
QVERIFY(main->incomingCalls().isEmpty());
QCOMPARE(main->called(), quint64(0));
@@ -227,9 +227,9 @@ void CallgrindParserTests::testCallee()
QCOMPARE(main->inclusiveCost(0), quint64(1230));
const Function *func1 = data->functions().at(1);
- QCOMPARE(func1->file(), QString("file1.c"));
- QCOMPARE(func1->object(), QString(""));
- QCOMPARE(func1->name(), QString("func1"));
+ QCOMPARE(func1->file(), QLatin1String("file1.c"));
+ QCOMPARE(func1->object(), QLatin1String(""));
+ QCOMPARE(func1->name(), QLatin1String("func1"));
QCOMPARE(func1->incomingCalls().size(), 1);
QCOMPARE(func1->called(), quint64(1));
@@ -240,9 +240,9 @@ void CallgrindParserTests::testCallee()
QCOMPARE(func1->inclusiveCost(0), quint64(400));
const Function *func2 = data->functions().at(2);
- QCOMPARE(func2->file(), QString("file2.c"));
- QCOMPARE(func2->object(), QString(""));
- QCOMPARE(func2->name(), QString("func2"));
+ QCOMPARE(func2->file(), QLatin1String("file2.c"));
+ QCOMPARE(func2->object(), QLatin1String(""));
+ QCOMPARE(func2->name(), QLatin1String("func2"));
QCOMPARE(func2->incomingCalls().size(), 2);
QCOMPARE(func2->called(), quint64(8));
@@ -286,18 +286,18 @@ void CallgrindParserTests::testInlinedCalls()
QCOMPARE(data->functions().size(), 3);
const Function *main = data->functions().first();
- QCOMPARE(main->name(), QString("main"));
- QCOMPARE(main->file(), QString("file1.c"));
+ QCOMPARE(main->name(), QLatin1String("main"));
+ QCOMPARE(main->file(), QLatin1String("file1.c"));
QCOMPARE(main->selfCost(0), quint64(4));
QCOMPARE(main->inclusiveCost(0), quint64(804));
const Function *inlined = data->functions().at(1);
- QCOMPARE(inlined->name(), QString("Something::Inlined()"));
- QCOMPARE(inlined->file(), QString("file.h"));
+ QCOMPARE(inlined->name(), QLatin1String("Something::Inlined()"));
+ QCOMPARE(inlined->file(), QLatin1String("file.h"));
const Function *func1 = data->functions().last();
- QCOMPARE(func1->name(), QString("func1"));
- QCOMPARE(func1->file(), QString("file3.h"));
+ QCOMPARE(func1->name(), QLatin1String("func1"));
+ QCOMPARE(func1->file(), QLatin1String("file3.h"));
QCOMPARE(main->outgoingCalls().size(), 2);
QCOMPARE(main->costItems().at(2)->call()->callee(), inlined);
@@ -395,9 +395,9 @@ void CallgrindParserTests::testCycle()
QCOMPARE(b->selfCost(0), quint64(20));
QCOMPARE(data->functions(true).size(), 3);
- QCOMPARE(findFunction(QString("main"), data->functions(true)), main);
- QCOMPARE(findFunction(QString("A()"), data->functions(true)), a);
- const FunctionCycle *cycle = dynamic_cast<const FunctionCycle*>(findFunction(QString("cycle 1"), data->functions(true)));
+ QCOMPARE(findFunction(QLatin1String("main"), data->functions(true)), main);
+ QCOMPARE(findFunction(QLatin1String("A()"), data->functions(true)), a);
+ const FunctionCycle *cycle = dynamic_cast<const FunctionCycle*>(findFunction(QLatin1String("cycle 1"), data->functions(true)));
QVERIFY(cycle);
QCOMPARE(cycle->called(), quint64(2));
QCOMPARE(cycle->inclusiveCost(0), quint64(40));
@@ -409,34 +409,34 @@ void CallgrindParserTests::testRecursiveCycle()
QScopedPointer<const ParseData> data(parseDataFile(dataFile("recursiveCycle.out")));
QCOMPARE(data->functions().size(), 5);
- const Function *main = findFunction(QString("main"), data->functions());
+ const Function *main = findFunction(QLatin1String("main"), data->functions());
QVERIFY(main);
QCOMPARE(main->inclusiveCost(0), quint64(70701765 + 3 + 4));
QCOMPARE(data->totalCost(0), main->inclusiveCost(0));
QCOMPARE(main->selfCost(0), quint64(3 + 4));
- const Function *a1 = findFunction(QString("A(int)"), data->functions());
+ const Function *a1 = findFunction(QLatin1String("A(int)"), data->functions());
QVERIFY(a1);
QCOMPARE(a1->inclusiveCost(0), quint64(700017 + 70001746 + 2));
QCOMPARE(a1->selfCost(0), quint64(700017 + 2));
- const Function *a2 = findFunction(QString("A(int)'2"), data->functions());
+ const Function *a2 = findFunction(QLatin1String("A(int)'2"), data->functions());
QVERIFY(a2);
QCOMPARE(a2->inclusiveCost(0), quint64(35000846 + 1715042679 + 100));
QCOMPARE(a2->selfCost(0), quint64(35000846 + 100));
- const Function *b1 = findFunction(QString("B(int)"), data->functions());
+ const Function *b1 = findFunction(QLatin1String("B(int)"), data->functions());
QVERIFY(b1);
QCOMPARE(b1->inclusiveCost(0), quint64(700014 + 69301730 + 2));
QCOMPARE(b1->selfCost(0), quint64(700014 + 2));
- const Function *b2 = findFunction(QString("B(int)'2"), data->functions());
+ const Function *b2 = findFunction(QLatin1String("B(int)'2"), data->functions());
QVERIFY(b2);
QCOMPARE(b2->inclusiveCost(0), quint64(34300686 + 1680741895 + 98));
QCOMPARE(b2->selfCost(0), quint64(34300686 + 98));
{ // cycle detection
QCOMPARE(data->functions(true).size(), 4);
- QCOMPARE(findFunction(QString("main"), data->functions(true)), main);
- QCOMPARE(findFunction(QString("A(int)"), data->functions(true)), a1);
- QCOMPARE(findFunction(QString("B(int)"), data->functions(true)), b1);
- const FunctionCycle *cycle = dynamic_cast<const FunctionCycle*>(findFunction(QString("cycle 1"), data->functions(true)));
+ QCOMPARE(findFunction(QLatin1String("main"), data->functions(true)), main);
+ QCOMPARE(findFunction(QLatin1String("A(int)"), data->functions(true)), a1);
+ QCOMPARE(findFunction(QLatin1String("B(int)"), data->functions(true)), b1);
+ const FunctionCycle *cycle = dynamic_cast<const FunctionCycle*>(findFunction(QLatin1String("cycle 1"), data->functions(true)));
QVERIFY(cycle);
QCOMPARE(cycle->called(), quint64(1));
const quint64 restCost = data->totalCost(0) - main->selfCost(0) - a1->selfCost(0) - b1->selfCost(0);
@@ -451,17 +451,17 @@ void CallgrindParserTests::testRecursion()
QCOMPARE(data->functions().size(), 3);
QCOMPARE(data->totalCost(0), quint64(35700972));
- const Function *main = findFunction(QString("main"), data->functions());
+ const Function *main = findFunction(QLatin1String("main"), data->functions());
QVERIFY(main);
QCOMPARE(main->inclusiveCost(0), quint64(4 + 35700965 + 3));
QCOMPARE(main->selfCost(0), quint64(4 + 3));
- const Function *a1 = findFunction(QString("A(int)"), data->functions());
+ const Function *a1 = findFunction(QLatin1String("A(int)"), data->functions());
QVERIFY(a1);
QCOMPARE(a1->inclusiveCost(0), quint64(700010 + 35000946 + 2));
QCOMPARE(a1->selfCost(0), quint64(700010 + 2));
- const Function *a2 = findFunction(QString("A(int)'2"), data->functions());
+ const Function *a2 = findFunction(QLatin1String("A(int)'2"), data->functions());
QVERIFY(a2);
// inclusive cost must be the same as call-cost from a1
QCOMPARE(a2->inclusiveCost(0), quint64(35000946));
diff --git a/tests/valgrind/callgrind/callgrindparsertests.pro b/tests/valgrind/callgrind/callgrindparsertests.pro
index 39b25046c4..99ccfb9bd0 100644
--- a/tests/valgrind/callgrind/callgrindparsertests.pro
+++ b/tests/valgrind/callgrind/callgrindparsertests.pro
@@ -1,6 +1,7 @@
include(../../auto/qttest.pri)
include($$IDE_SOURCE_TREE/src/plugins/valgrind/valgrind_test.pri)
include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+include($$IDE_SOURCE_TREE/src/libs/ssh/ssh.pri)
TARGET = callgrindparsertests
DEFINES += "PARSERTESTS_DATA_DIR=\\\"$$PWD/data\\\""
diff --git a/tests/valgrind/memcheck/modeldemo.pro b/tests/valgrind/memcheck/modeldemo.pro
index e002f36542..eb843efdf7 100644
--- a/tests/valgrind/memcheck/modeldemo.pro
+++ b/tests/valgrind/memcheck/modeldemo.pro
@@ -2,6 +2,7 @@ include(../../../qtcreator.pri)
include(../../auto/qttestrpath.pri)
include($$IDE_SOURCE_TREE/src/libs/3rdparty/botan/botan.pri)
include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
+include($$IDE_SOURCE_TREE/src/libs/ssh/ssh.pri)
include($$IDE_SOURCE_TREE/src/plugins/valgrind/valgrind_test.pri)
TEMPLATE = app
diff --git a/tests/valgrind/memcheck/parsertests.cpp b/tests/valgrind/memcheck/parsertests.cpp
index eeb884587c..cf72a3f97f 100644
--- a/tests/valgrind/memcheck/parsertests.cpp
+++ b/tests/valgrind/memcheck/parsertests.cpp
@@ -115,7 +115,7 @@ void ParserTests::initTest(const QLatin1String &testfile, const QStringList &oth
m_process->start(
fakeValgrindExecutable(),
QStringList()
- << QString("--xml-socket=127.0.0.1:%1").arg(m_server->serverPort())
+ << QString::fromLatin1("--xml-socket=127.0.0.1:%1").arg(m_server->serverPort())
<< QLatin1String("-i")
<< dataFile(testfile)
<< otherArgs
@@ -457,7 +457,7 @@ void ParserTests::testRealValgrind()
ThreadedParser parser;
Valgrind::Memcheck::MemcheckRunner runner;
- runner.setValgrindExecutable(QString("valgrind"));
+ runner.setValgrindExecutable(QLatin1String("valgrind"));
runner.setDebuggeeExecutable(executable);
runner.setParser(&parser);
RunnerDumper dumper(&runner, &parser);
@@ -472,13 +472,14 @@ void ParserTests::testValgrindStartError_data()
QTest::addColumn<QString>("debuggee");
QTest::addColumn<QString>("debuggeeArgs");
- QTest::newRow("invalid_client") << QString("valgrind") << QStringList()
- << QString("please-dont-let-this-app-exist") << QString();
+ QTest::newRow("invalid_client") << QString::fromLatin1("valgrind") << QStringList()
+ << QString::fromLatin1("please-dont-let-this-app-exist") << QString();
- QTest::newRow("invalid_valgrind") << QString("valgrind-that-does-not-exist") << QStringList()
+ QTest::newRow("invalid_valgrind") << QString::fromLatin1("valgrind-that-does-not-exist") << QStringList()
<< fakeValgrindExecutable() << QString();
- QTest::newRow("invalid_valgrind_args") << QString("valgrind") << (QStringList() << "--foobar-fail")
+ QTest::newRow("invalid_valgrind_args") << QString::fromLatin1("valgrind")
+ << (QStringList() << QString::fromLatin1("--foobar-fail"))
<< fakeValgrindExecutable() << QString();
}
diff --git a/tests/valgrind/memcheck/parsertests.pro b/tests/valgrind/memcheck/parsertests.pro
index 3170210d38..e58578dabe 100644
--- a/tests/valgrind/memcheck/parsertests.pro
+++ b/tests/valgrind/memcheck/parsertests.pro
@@ -1,5 +1,6 @@
include(../../auto/qttest.pri)
include($$IDE_SOURCE_TREE/src/libs/3rdparty/botan/botan.pri)
+include($$IDE_SOURCE_TREE/src/libs/ssh/ssh.pri)
include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
include($$IDE_SOURCE_TREE/src/plugins/valgrind/valgrind_test.pri)
diff --git a/tests/valgrind/memcheck/testrunner.cpp b/tests/valgrind/memcheck/testrunner.cpp
index dc74f6c0a6..d445d3bdfe 100644
--- a/tests/valgrind/memcheck/testrunner.cpp
+++ b/tests/valgrind/memcheck/testrunner.cpp
@@ -151,11 +151,11 @@ void TestRunner::testLeak1()
QCOMPARE(stack.frames().count(), 2);
{
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("operator new(unsigned long)"));
+ QCOMPARE(frame.functionName(), QLatin1String("operator new(unsigned long)"));
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 5);
QCOMPARE(frame.object(), binary);
@@ -181,15 +181,15 @@ void TestRunner::testLeak2()
QCOMPARE(stack.frames().count(), 3);
{
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("malloc"));
+ QCOMPARE(frame.functionName(), QLatin1String("malloc"));
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("strdup"));
+ QCOMPARE(frame.functionName(), QLatin1String("strdup"));
}
{
const Frame frame = stack.frames().at(2);
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 7);
QCOMPARE(frame.object(), binary);
@@ -215,15 +215,15 @@ void TestRunner::testLeak3()
QCOMPARE(stack.frames().count(), 3);
{
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("malloc"));
+ QCOMPARE(frame.functionName(), QLatin1String("malloc"));
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("strdup"));
+ QCOMPARE(frame.functionName(), QLatin1String("strdup"));
}
{
const Frame frame = stack.frames().at(2);
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 7);
QCOMPARE(frame.object(), binary);
@@ -254,11 +254,11 @@ void TestRunner::testLeak4()
QCOMPARE(stack.frames().count(), 3);
{
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("operator new(unsigned long)"));
+ QCOMPARE(frame.functionName(), QLatin1String("operator new(unsigned long)"));
}
{
const Frame frame = stack.frames().at(2);
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 14);
QCOMPARE(frame.object(), binary);
@@ -267,7 +267,7 @@ void TestRunner::testLeak4()
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("Foo::Foo()"));
+ QCOMPARE(frame.functionName(), QLatin1String("Foo::Foo()"));
QCOMPARE(frame.line(), 6);
QCOMPARE(frame.object(), binary);
@@ -276,7 +276,7 @@ void TestRunner::testLeak4()
}
{
const Frame frame = stack.frames().at(2);
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 14);
QCOMPARE(frame.object(), binary);
@@ -296,11 +296,11 @@ void TestRunner::testLeak4()
QCOMPARE(stack.frames().count(), 2);
{
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("operator new(unsigned long)"));
+ QCOMPARE(frame.functionName(), QLatin1String("operator new(unsigned long)"));
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 14);
QCOMPARE(frame.object(), binary);
@@ -329,7 +329,7 @@ void TestRunner::uninit1()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 4);
QCOMPARE(frame.object(), binary);
@@ -343,7 +343,7 @@ void TestRunner::uninit1()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 2);
QCOMPARE(frame.object(), binary);
@@ -374,7 +374,7 @@ void TestRunner::uninit2()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 4);
QCOMPARE(frame.object(), binary);
@@ -388,7 +388,7 @@ void TestRunner::uninit2()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 2);
QCOMPARE(frame.object(), binary);
@@ -407,7 +407,7 @@ void TestRunner::uninit2()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 4);
QCOMPARE(frame.object(), binary);
@@ -438,7 +438,7 @@ void TestRunner::uninit3()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 4);
QCOMPARE(frame.object(), binary);
@@ -452,7 +452,7 @@ void TestRunner::uninit3()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 2);
QCOMPARE(frame.object(), binary);
@@ -471,7 +471,7 @@ void TestRunner::uninit3()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 4);
QCOMPARE(frame.object(), binary);
@@ -501,15 +501,15 @@ void TestRunner::syscall()
{
///TODO: is this platform specific?
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("_Exit"));
+ QCOMPARE(frame.functionName(), QLatin1String("_Exit"));
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("exit"));
+ QCOMPARE(frame.functionName(), QLatin1String("exit"));
}
{
const Frame frame = stack.frames().at(2);
- QCOMPARE(frame.functionName(), QString("(below main)"));
+ QCOMPARE(frame.functionName(), QLatin1String("(below main)"));
}
}
//BEGIN second stack
@@ -519,7 +519,7 @@ void TestRunner::syscall()
QCOMPARE(stack.frames().count(), 1);
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 2);
QCOMPARE(frame.object(), binary);
@@ -548,11 +548,11 @@ void TestRunner::free1()
{
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("operator delete(void*)"));
+ QCOMPARE(frame.functionName(), QLatin1String("operator delete(void*)"));
}
{
const Frame frame = stack.frames().last();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 7);
QCOMPARE(frame.object(), binary);
@@ -569,11 +569,11 @@ void TestRunner::free1()
{
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("operator delete(void*)"));
+ QCOMPARE(frame.functionName(), QLatin1String("operator delete(void*)"));
}
{
const Frame frame = stack.frames().last();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 6);
QCOMPARE(frame.object(), binary);
@@ -603,11 +603,11 @@ void TestRunner::free2()
{
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("free"));
+ QCOMPARE(frame.functionName(), QLatin1String("free"));
}
{
const Frame frame = stack.frames().last();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 6);
QCOMPARE(frame.object(), binary);
@@ -624,11 +624,11 @@ void TestRunner::free2()
{
const Frame frame = stack.frames().first();
- QCOMPARE(frame.functionName(), QString("operator new(unsigned long)"));
+ QCOMPARE(frame.functionName(), QLatin1String("operator new(unsigned long)"));
}
{
const Frame frame = stack.frames().last();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 5);
QCOMPARE(frame.object(), binary);
@@ -661,7 +661,7 @@ void TestRunner::invalidjump()
}
{
const Frame frame = stack.frames().at(1);
- QCOMPARE(frame.functionName(), QString("(below main)"));
+ QCOMPARE(frame.functionName(), QLatin1String("(below main)"));
}
}
@@ -684,11 +684,11 @@ void TestRunner::overlap()
QCOMPARE(stack.frames().count(), 2);
{
const Frame frame = stack.frames().at(0);
- QCOMPARE(frame.functionName(), QString("memcpy"));
+ QCOMPARE(frame.functionName(), QLatin1String("memcpy"));
}
{
const Frame frame = stack.frames().last();
- QCOMPARE(frame.functionName(), QString("main"));
+ QCOMPARE(frame.functionName(), QLatin1String("main"));
QCOMPARE(frame.line(), 6);
QCOMPARE(frame.object(), binary);
diff --git a/tests/valgrind/memcheck/testrunner.pro b/tests/valgrind/memcheck/testrunner.pro
index 53035bbac7..fea9eebd00 100644
--- a/tests/valgrind/memcheck/testrunner.pro
+++ b/tests/valgrind/memcheck/testrunner.pro
@@ -1,6 +1,7 @@
include(../../auto/qttest.pri)
include($$IDE_SOURCE_TREE/src/libs/utils/utils.pri)
include($$IDE_SOURCE_TREE/src/libs/3rdparty/botan/botan.pri)
+include($$IDE_SOURCE_TREE/src/libs/ssh/ssh.pri)
include($$IDE_SOURCE_TREE/src/plugins/valgrind/valgrind_test.pri)
TARGET = testrunner